From 0690841c6b5d33bfcbf91be3b02f13e63c990ed1 Mon Sep 17 00:00:00 2001 From: Martin McWhorter Date: Mon, 10 Feb 2014 17:40:59 +0000 Subject: [PATCH 001/324] Update angular.d.ts The listener may take a single event argument. --- angularjs/angular.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index a8c1d991d..10dec18ae 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -227,6 +227,7 @@ declare module ng { $new(isolate?: boolean): IScope; $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; + $on(name: string, listener: (event: IAngularEvent, eventArg: any) => any): Function; $watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function; $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; From 045537ef49c478296abc3becf0ea5d27be326823 Mon Sep 17 00:00:00 2001 From: Martin McWhorter Date: Tue, 25 Feb 2014 17:32:17 +0000 Subject: [PATCH 002/324] Update angular-ui-router.d.ts --- angular-ui/angular-ui-router.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/angular-ui/angular-ui-router.d.ts b/angular-ui/angular-ui-router.d.ts index da3d92e5e..285149a0d 100644 --- a/angular-ui/angular-ui-router.d.ts +++ b/angular-ui/angular-ui-router.d.ts @@ -84,6 +84,7 @@ declare module ng.ui { get(state: string): IState; get(): IState[]; current: IState; + $current: IState; params: IStateParamsService; } From 17e72ca4827f7d9f3e92b3322f0021771301b8cb Mon Sep 17 00:00:00 2001 From: Martin McWhorter Date: Tue, 25 Feb 2014 17:37:58 +0000 Subject: [PATCH 003/324] Revert "Update angular.d.ts" This reverts commit 0690841c6b5d33bfcbf91be3b02f13e63c990ed1. --- angularjs/angular.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 10dec18ae..a8c1d991d 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -227,7 +227,6 @@ declare module ng { $new(isolate?: boolean): IScope; $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; - $on(name: string, listener: (event: IAngularEvent, eventArg: any) => any): Function; $watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function; $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; From 41073b2393a4a4ee03fdfcfccd8f2e1204617341 Mon Sep 17 00:00:00 2001 From: StefanSchoof Date: Tue, 22 Apr 2014 21:14:51 +0200 Subject: [PATCH 004/324] Update to changes in angular-translate uses now is named use new cloakClassName, useFallbackLanguage and determinePreferredLanguage functions --- angular-translate/angular-translate.d.ts | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts index 106d0ae25..d621007c8 100644 --- a/angular-translate/angular-translate.d.ts +++ b/angular-translate/angular-translate.d.ts @@ -29,8 +29,11 @@ declare module ng.translate { refresh(lankKey: string): ng.IPromise; storage(): IStorage; storageKey(): string; - uses(): string; - uses(key: string): ng.IPromise; + use(): string; + use(key: string): ng.IPromise; + cloakClassName(): string; + cloakClassName(name: string): ITranslateProvider; + useFallbackLanguage(): void; } interface ITranslateProvider extends ng.IServiceProvider { @@ -48,8 +51,8 @@ declare module ng.translate { fallbackLanguage(): string; fallbackLanguage(language: string): ITranslateProvider; fallbackLanguage(languages: string[]): ITranslateProvider; - uses(): string; - uses(key: string): ITranslateProvider; + use(): string; + use(key: string): ITranslateProvider; useUrlLoader(url: string): ITranslateProvider; useStaticFilesLoader(options: ISTaticFilesLoaderOptions): ITranslateProvider; useLoader(loaderFactory: string, options: any): ITranslateProvider; @@ -60,5 +63,8 @@ declare module ng.translate { storagePrefix(prefix: string): ITranslateProvider; useMissingTranslationHandlerLog(): ITranslateProvider; useMissingTranslationHandler(factory: string): ITranslateProvider; + determinePreferredLanguage(): ITranslateProvider; + cloakClassName(): string; + cloakClassName(name: string): ITranslateProvider; } } From a55232a29af91fcc636aaaf0aaef13d9b5ee0d97 Mon Sep 17 00:00:00 2001 From: StefanSchoof Date: Tue, 29 Apr 2014 07:54:11 +0200 Subject: [PATCH 005/324] Fix Test --- angular-translate/angular-translate-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angular-translate/angular-translate-tests.ts b/angular-translate/angular-translate-tests.ts index bea7faa09..559555418 100644 --- a/angular-translate/angular-translate-tests.ts +++ b/angular-translate/angular-translate-tests.ts @@ -24,6 +24,6 @@ interface Scope extends ng.IScope { app.controller('Ctrl', ($scope: Scope, $translate: ng.translate.ITranslateService) => { $scope['changeLanguage'] = function (key: any) { - $translate.uses(key); + $translate.use(key); }; }); From 57a3b6e1b8c3ba05db9dcb2f1110d39ef8c94b0e Mon Sep 17 00:00:00 2001 From: Santi Albo Date: Tue, 3 Jun 2014 13:22:50 +0100 Subject: [PATCH 006/324] Add basic type definitions for express 4.x --- body-parser/body-parser.d.ts | 12 + compression/compression-tests.ts | 10 + compression/compression.d.ts | 20 + cookie-parser/cookie-parser-tests.ts | 7 + cookie-parser/cookie-parser.d.ts | 12 + errorhandler/errorhandler-tests.ts | 7 + errorhandler/errorhandler.d.ts | 12 + express/express-3.1.0-tests.ts | 1498 ++++++++++++++++++ express/express-3.1.0-tests.ts.tscparams | 1 + express/express-3.1.0.d.ts | 1832 ++++++++++++++++++++++ express/express-tests.ts | 1493 +----------------- express/express.d.ts | 903 +---------- method-override/method-override-tests.ts | 15 + method-override/method-override.d.ts | 24 + 14 files changed, 3514 insertions(+), 2332 deletions(-) create mode 100644 body-parser/body-parser.d.ts create mode 100644 compression/compression-tests.ts create mode 100644 compression/compression.d.ts create mode 100644 cookie-parser/cookie-parser-tests.ts create mode 100644 cookie-parser/cookie-parser.d.ts create mode 100644 errorhandler/errorhandler-tests.ts create mode 100644 errorhandler/errorhandler.d.ts create mode 100644 express/express-3.1.0-tests.ts create mode 100644 express/express-3.1.0-tests.ts.tscparams create mode 100644 express/express-3.1.0.d.ts create mode 100644 method-override/method-override-tests.ts create mode 100644 method-override/method-override.d.ts diff --git a/body-parser/body-parser.d.ts b/body-parser/body-parser.d.ts new file mode 100644 index 000000000..f16b2eefb --- /dev/null +++ b/body-parser/body-parser.d.ts @@ -0,0 +1,12 @@ +// Type definitions for body-parser +// Project: http://expressjs.com +// Definitions by: Santi Albo +// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "body-parser" { + import express = require('express'); + function e(options?: any): express.RequestHandler; + export = e; +} \ No newline at end of file diff --git a/compression/compression-tests.ts b/compression/compression-tests.ts new file mode 100644 index 000000000..ecfcab432 --- /dev/null +++ b/compression/compression-tests.ts @@ -0,0 +1,10 @@ +/// + +import express = require('express'); +import compress = require('compression'); + +var app = express(); +app.use(compress()); +app.use(compress({ + threshold: 512 +})); diff --git a/compression/compression.d.ts b/compression/compression.d.ts new file mode 100644 index 000000000..9ef3a8cb7 --- /dev/null +++ b/compression/compression.d.ts @@ -0,0 +1,20 @@ +// Type definitions for compression +// Project: https://github.com/expressjs/compression +// Definitions by: Santi Albo +// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "compression" { + import express = require('express'); + + module e { + interface CompressionOptions { + threshold?: number; + filter?: Function; + } + } + + function e(options?: e.CompressionOptions): express.RequestHandler; + export = e; +} \ No newline at end of file diff --git a/cookie-parser/cookie-parser-tests.ts b/cookie-parser/cookie-parser-tests.ts new file mode 100644 index 000000000..94e8a9fdb --- /dev/null +++ b/cookie-parser/cookie-parser-tests.ts @@ -0,0 +1,7 @@ +/// + +import express = require('express'); +import cookieParser = require('cookie-parser'); + +var app = express(); +app.use(cookieParser('optional secret string')); diff --git a/cookie-parser/cookie-parser.d.ts b/cookie-parser/cookie-parser.d.ts new file mode 100644 index 000000000..f43553b7c --- /dev/null +++ b/cookie-parser/cookie-parser.d.ts @@ -0,0 +1,12 @@ +// Type definitions for cookie-parser +// Project: https://github.com/expressjs/cookie-parser +// Definitions by: Santi Albo +// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "cookie-parser" { + import express = require('express'); + function e(secret?: string, options?: any): express.RequestHandler; + export = e; +} \ No newline at end of file diff --git a/errorhandler/errorhandler-tests.ts b/errorhandler/errorhandler-tests.ts new file mode 100644 index 000000000..02f788790 --- /dev/null +++ b/errorhandler/errorhandler-tests.ts @@ -0,0 +1,7 @@ +/// + +import express = require('express'); +import errorhandler = require('errorhandler'); +var app = express(); + +app.use(errorhandler()); diff --git a/errorhandler/errorhandler.d.ts b/errorhandler/errorhandler.d.ts new file mode 100644 index 000000000..e6c3011a5 --- /dev/null +++ b/errorhandler/errorhandler.d.ts @@ -0,0 +1,12 @@ +// Type definitions for errorhandler +// Project: https://github.com/expressjs/errorhandler +// Definitions by: Santi Albo +// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "errorhandler" { + import express = require('express'); + function e(): express.ErrorRequestHandler; + export = e; +} \ No newline at end of file diff --git a/express/express-3.1.0-tests.ts b/express/express-3.1.0-tests.ts new file mode 100644 index 000000000..904f64511 --- /dev/null +++ b/express/express-3.1.0-tests.ts @@ -0,0 +1,1498 @@ +/// + +import express = require('express'); +var app = express(); + +////////////////////////// + +var hash: any; + +// config + +app.set('view engine', 'ejs'); +app.set('views', __dirname + '/views'); + +// middleware + +app.use(express.bodyParser()); +app.use(express.cookieParser('shhhh, very secret')); +app.use(express.session()); + +// Session-persisted message middleware + +app.use((req: express.Request, res: express.Response, next) => { + var err = req.session.error + , msg = req.session.success; + delete req.session.error; + delete req.session.success; + res.locals.message = ''; + if (err) res.locals.message = '

' + err + '

'; + if (msg) res.locals.message = '

' + msg + '

'; + next(); +}); + +// dummy database + +var users = { + tj: { name: 'tj' } +}; + +// when you create a user, generate a salt +// and hash the password ('foobar' is the pass here) + +hash('foobar', (err, salt, hash) => { + if (err) throw err; + // store the salt & hash in the "db" + users.tj.salt = salt; + users.tj.hash = hash; +}); + + +// Authenticate using our plain-object database of doom! + +function authenticate(name, pass, fn) { + if (!module.parent) console.log('authenticating %s:%s', name, pass); + var user = users[name]; + // query the db for the given username + if (!user) return fn(new Error('cannot find user')); + // apply the same algorithm to the POSTed password, applying + // the hash against the pass / salt, if there is a match we + // found the user + hash(pass, user.salt, (err, hash) => { + if (err) return fn(err); + if (hash == user.hash) return fn(null, user); + fn(new Error('invalid password')); + }); +} + +function restrict(req: express.Request, res: express.Response, next?: Function) { + if (req.session.user) { + next(); + } else { + req.session.error = 'Access denied!'; + res.redirect('/login'); + } +} + +app.get('/', (req: express.Request, res: express.Response) => { + res.redirect('login'); +}); + +app.get('/restricted', restrict, (req: express.Request, res: express.Response) => { + res.send('Wahoo! restricted area, click to logout'); +}); + +app.get('/logout', (req: express.Request, res: express.Response) => { + // destroy the user's session to log them out + // will be re-created next request + req.session.destroy(() => { + res.redirect('/'); + }); +}); + +app.get('/login', (req: express.Request, res: express.Response) => { + res.render('login'); +}); + +app.post('/login', (req: express.Request, res: express.Response) => { + authenticate(req.body.username, req.body.password, (err, user) => { + if (user) { + // Regenerate session when signing in + // to prevent fixation + req.session.regenerate(() => { + // Store the user's primary key + // in the session store to be retrieved, + // or in this case the entire user object + req.session.user = user; + req.session.success = 'Authenticated as ' + user.name + + ' click to logout. ' + + ' You may now access /restricted.'; + res.redirect('back'); + }); + } else { + req.session.error = 'Authentication failed, please check your ' + + ' username and password.' + + ' (use "tj" and "foobar")'; + res.redirect('login'); + } + }); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +////////////// + +app.set('views', __dirname); +app.set('view engine', 'jade'); + +var pets = []; + +var n = 1000; +while (n--) { + pets.push({ name: 'Tobi', age: 2, species: 'ferret' }); + pets.push({ name: 'Loki', age: 1, species: 'ferret' }); + pets.push({ name: 'Jane', age: 6, species: 'ferret' }); +} + +app.use(express.logger('dev')); + +app.get('/', (req: express.Request, res: express.Response) => { + res.render('pets', { pets: pets }); +}); + +app.listen(3000); +console.log('Express listening on port 3000'); + +///////////// + +app.get('/', (req: express.Request, res: express.Response) => { + res.format({ + html: () => { + res.send('
    ' + users.map(user => { + return '
  • ' + user.name + '
  • '; + }).join('') + '
'); + }, + + text: () => { + res.send(users.map(user => { + return ' - ' + user.name + '\n'; + }).join('')); + }, + + json: () => { + res.json(users); + } + }); +}); + +// or you could write a tiny middleware like +// this to abstract make things a bit more declarative: + +function format(mod) { + var obj = require(mod); + return (req: express.Request, res: express.Response) => { + res.format(obj); + }; +} + +app.get('/users', format('./users')); + +if (!module.parent) { + app.listen(3000); + console.log('listening on port 3000'); +} + +///////////////////////// + +// add favicon() before logger() so +// GET /favicon.ico requests are not +// logged, because this middleware +// reponds to /favicon.ico and does not +// call next() +app.use(express.favicon()); + +// custom log format +if ('test' != process.env.NODE_ENV) + app.use(express.logger(':method :url')); + +// parses request cookies, populating +// req.cookies and req.signedCookies +// when the secret is passed, used +// for signing the cookies. +app.use(express.cookieParser('my secret here')); + +// parses json, x-www-form-urlencoded, and multipart/form-data +app.use(express.bodyParser()); + +app.get('/', (req: express.Request, res: express.Response) => { + if (req.cookies.remember) { + res.send('Remembered :). Click to forget!.'); + } else { + res.send('

Check to ' + + '.

'); + } +}); + +app.get('/forget', (req: express.Request, res: express.Response) => { + res.clearCookie('remember'); + res.redirect('back'); +}); + +app.post('/', (req: express.Request, res: express.Response) => { + var minute = 60000; + if (req.body.remember) res.cookie('remember', 1, { maxAge: minute }); + res.redirect('back'); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +/////////////////// + +// ignore GET /favicon.ico +app.use(express.favicon()); + +// pass a secret to cookieParser() for signed cookies +app.use(express.cookieParser('manny is cool')); + +// add req.session cookie support +app.use(express.cookieSession()); + +// do something with the session +app.use(count); + +// custom middleware +function count(req: express.Request, res: express.Response) { + req.session.count = req.session.count || 0; + var n = req.session.count++; + res.send('viewed ' + n + ' times\n'); +} + +if (!module.parent) { + app.listen(3000); + console.log('Express server listening on port 3000'); +} + +/////////////// + +var api = app; + +app.use(express.static(__dirname + '/public')); + +// api middleware + +api.use(express.logger('dev')); +api.use(express.bodyParser()); + +/** + * CORS support. + */ + +api.all('*', (req: express.Request, res: express.Response, next) => { + if (!req.get('Origin')) return next(); + // use "*" here to accept any origin + res.set('Access-Control-Allow-Origin', 'http://localhost:3000'); + res.set('Access-Control-Allow-Methods', 'GET, POST'); + res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type'); + // res.set('Access-Control-Allow-Max-Age', 3600); + if ('OPTIONS' == req.method) return res.send(200); + next(); +}); + +/** + * POST a user. + */ + +api.post('/user', (req: express.Request, res: express.Response) => { + console.log(req.body); + res.send(201); +}); + +app.listen(3000); +api.listen(3001); + +console.log('app listening on 3000'); +console.log('api listening on 3001'); + +//////////////////// + +app.get('/', (req: express.Request, res: express.Response) => { + res.send(''); +}); + +// /files/* is accessed via req.params[0] +// but here we name it :file +app.get('/files/:file(*)', (req: express.Request, res: express.Response) => { + var file = req.params.file + , path = __dirname + '/files/' + file; + + res.download(path); +}); + +// error handling middleware. Because it's +// below our routes, you will be able to +// "intercept" errors, otherwise Connect +// will respond with 500 "Internal Server Error". +app.use((err, req, res: express.Response, next) => { + // special-case 404s, + // remember you could + // render a 404 template here + if (404 == err.status) { + res.statusCode = 404; + res.send('Cant find that file, sorry!'); + } else { + next(err); + } +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +/////////////////// + +// Register ejs as .html. If we did +// not call this, we would need to +// name our views foo.ejs instead +// of foo.html. The __express method +// is simply a function that engines +// use to hook into the Express view +// system by default, so if we want +// to change "foo.ejs" to "foo.html" +// we simply pass _any_ function, in this +// case `ejs.__express`. + +app.engine('.html', require('ejs').__express); + +// Optional since express defaults to CWD/views + +app.set('views', __dirname + '/views'); + +// Without this you would need to +// supply the extension to res.render() +// ex: res.render('users.html'). +app.set('view engine', 'html'); + +app.get('/', (req: express.Request, res: express.Response) => { + res.render('users', { + users: users, + title: "EJS example", + header: "Some users" + }); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express app started on port 3000'); +} + +//////////////////// + +var test: any; + +if (!test) app.use(express.logger('dev')); +app.use(app.router); + +// the error handler is strategically +// placed *below* the app.router; if it +// were above it would not receive errors +// from app.get() etc +app.use(error); + +// error handling middleware have an arity of 4 +// instead of the typical (req: express.Request, res: express.Response, next), +// otherwise they behave exactly like regular +// middleware, you may have several of them, +// in different orders etc. + +function error(err, req, res: express.Response, next) { + // log it + if (!test) console.error(err.stack); + + // respond with 500 "Internal Server Error". + res.send(500); +} + +app.get('/', () => { + // Caught and passed down to the errorHandler middleware + throw new Error('something broke!'); +}); + +app.get('/next', (req: express.Request, res: express.Response, next) => { + // We can also pass exceptions to next() + process.nextTick(() => { + next(new Error('oh no!')); + }); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +///////////////////// + +var silent: any; + +// general config +app.set('views', __dirname + '/views'); +app.set('view engine', 'jade'); + +// our custom "verbose errors" setting +// which we can use in the templates +// via settings['verbose errors'] +app.enable('verbose errors'); + +// disable them in production +// use $ NODE_ENV=production node examples/error-pages +if ('production' == app.settings.env) { + app.disable('verbose errors'); +} + +app.use(express.favicon()); + +silent || app.use(express.logger('dev')); + +// "app.router" positions our routes +// above the middleware defined below, +// this means that Express will attempt +// to match & call routes _before_ continuing +// on, at which point we assume it's a 404 because +// no route has handled the request. + +app.use(app.router); + +// Since this is the last non-error-handling +// middleware use()d, we assume 404, as nothing else +// responded. + +// $ curl http://localhost:3000/notfound +// $ curl http://localhost:3000/notfound -H "Accept: application/json" +// $ curl http://localhost:3000/notfound -H "Accept: text/plain" + +app.use((req: express.Request, res: express.Response) => { + res.status(404); + + // respond with html page + if (req.accepts('html')) { + res.render('404', { url: req.url }); + return; + } + + // respond with json + if (req.accepts('json')) { + res.send({ error: 'Not found' }); + return; + } + + // default to plain-text. send() + res.type('txt').send('Not found'); +}); + +// error-handling middleware, take the same form +// as regular middleware, however they require an +// arity of 4, aka the signature (err, req, res: express.Response, next). +// when connect has an error, it will invoke ONLY error-handling +// middleware. + +// If we were to next() here any remaining non-error-handling +// middleware would then be executed, or if we next(err) to +// continue passing the error, only error-handling middleware +// would remain being executed, however here +// we simply respond with an error page. + +app.use((err, req, res: express.Response) => { + // we may use properties of the error object + // here and next(err) appropriately, or if + // we possibly recovered from the error, simply next(). + res.status(err.status || 500); + res.render('500', { error: err }); +}); + +// Routes + +app.get('/', (req: express.Request, res: express.Response) => { + res.render('index.jade'); +}); + +app.get('/404', (req: express.Request, res: express.Response, next) => { + // trigger a 404 since no other middleware + // will match /404 after this one, and we're not + // responding here + next(); +}); + +app.get('/403', (req: express.Request, res: express.Response, next) => { + // trigger a 403 error + var err = new Error('not allowed!'); + err.status = 403; + next(err); +}); + +app.get('/500', (req: express.Request, res: express.Response, next) => { + // trigger a generic (500) error + next(new Error('keyboard cat!')); +}); + +if (!module.parent) { + app.listen(3000); + //silent ||  console.log('Express started on port 3000'); +} + +/////////////// + +var fs: any; +var md: any; + +app.set('view engine', 'jade'); +app.set('views', __dirname + '/views'); + +function User(name) { + this.private = 'heyyyy'; + this.secret = 'something'; + this.name = name; + this.id = 123; +} + +// You'll probably want to do +// something like this so you +// dont expose "secret" data. + +User.prototype.toJSON = function () { + return { + id: this.id, + name: this.name + }; +}; + +app.use(express.logger('dev')); + +// earlier on expose an object +// that we can tack properties on. +// all res.locals props are exposed +// to the templates, so "expose" will +// be present. + +app.use((req: express.Request, res: express.Response, next) => { + res.locals.expose = {}; + // you could alias this as req or res.expose + // to make it shorter and less annoying + next(); +}); + +// pretend we loaded a user + +app.use((req: express.Request, res: express.Response, next) => { + req.user = new User('Tobi'); + next(); +}); + +app.get('/', (req: express.Request, res: express.Response) => { + res.redirect('/user'); +}); + +app.get('/user', (req: express.Request, res: express.Response) => { + // we only want to expose the user + // to the client for this route: + res.locals.expose.user = req.user; + res.render('page'); +}); + +app.listen(3000); +console.log('app listening on port 3000'); + +/////////////////////// + +app.get('/', (req: express.Request, res: express.Response) => { + res.send('Hello World'); +}); + +app.listen(3000); +console.log('Express started on port 3000'); + +//////////////////// + +// register .md as an engine in express view system + +app.engine('md', (path, options, fn) => { + fs.readFile(path, 'utf8', (err, str) => { + if (err) return fn(err); + try { + var html = md(str); + html = html.replace(/\{([^}]+)\}/g, (_, name) => { + return options[name] || ''; + }); + fn(null, html); + } catch (err) { + fn(err); + } + }); +}); + +app.set('views', __dirname + '/views'); + +// make it the default so we dont need .md +app.set('view engine', 'md'); + +app.get('/', (req: express.Request, res: express.Response) => { + res.render('index', { title: 'Markdown Example' }); +}); + +app.get('/fail', (req: express.Request, res: express.Response) => { + res.render('missing', { title: 'Markdown Example' }); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +/////////////////////// + +var mformat: any; + +// bodyParser in connect 2.x uses node-formidable to parse +// the multipart form data. +app.use(express.bodyParser()); + +app.get('/', (req: express.Request, res: express.Response) => { + res.send('
' + + '

Title:

' + + '

Image:

' + + '

' + + '
'); +}); + +app.post('/', (req: express.Request, res: express.Response) => { + // the uploaded file can be found as `req.files.image` and the + // title field as `req.body.title` + res.send(mformat('\nuploaded %s (%d Kb) to %s as %s' + , req.files.image.name + , req.files.image.size / 1024 | 0 + , req.files.image.path + , req.body.title)); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +////////////////// + + +// first: +// $ npm install redis online +// $ redis-server + +/** + * Module dependencies. + */ + +var online: any; +var db: any; + +// online + +online = online(db); + +// activity tracking, in this case using +// the UA string, you would use req.user.id etc + +app.use((req: express.Request, res: express.Response, next) => { + // fire-and-forget + online.add(req.headers['user-agent']); + next(); +}); + +/** + * List helper. + */ + +function list(ids) { + return '
    ' + ids.map(id => { + return '
  • ' + id + '
  • '; + }).join('') + '
'; +} + +/** + * GET users online. + */ + +app.get('/', (req: express.Request, res: express.Response, next) => { + online.last(5, (err, ids) => { + if (err) return next(err); + res.send('

Users online: ' + ids.length + '

' + list(ids)); + }); +}); + +app.listen(3000); +console.log('listening on port 3000'); + +/////////////////// + +// Convert :to and :from to integers + +app.param(['to', 'from'], (req: express.Request, res: express.Response, next, num, name) => { + req.params[name] = num = parseInt(num, 10); + if (isNaN(num)) { + next(new Error('failed to parseInt ' + num)); + } else { + next(); + } +}); + +// Load user by id + +app.param('user', (req: express.Request, res: express.Response, next, id) => { + if (req.user = users[id]) { + next(); + } else { + next(new Error('failed to find user')); + } +}); + +/** + * GET index. + */ + +app.get('/', (req: express.Request, res: express.Response) => { + res.send('Visit /user/0 or /users/0-2'); +}); + +/** + * GET :user. + */ + +app.get('/user/:user', (req: express.Request, res: express.Response) => { + res.send('user ' + req.user.name); +}); + +/** + * GET users :from - :to. + */ + +app.get('/users/:from-:to', (req: express.Request, res: express.Response) => { + var from = req.params.from + , to = req.params.to + , names = users.map(user => { return user.name; }); + res.send('users ' + names.slice(from, to).join(', ')); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +////////////////// + +// Ad-hoc example resource method + +app.resource = function (path, obj) { + this.get(path, obj.index); + this.get(path + '/:a..:b.:format?', (req: express.Request, res: express.Response) => { + var a = parseInt(req.params.a, 10) + , b = parseInt(req.params.b, 10) + , format = req.params.format; + obj.range(req, res, a, b, format); + }); + this.get(path + '/:id', obj.show); + this.del(path + '/:id', obj.destroy); +}; + +// Fake controller. + +var FUser = { + index: (req: express.Request, res: express.Response) => { + res.send(users); + }, + show: (req: express.Request, res: express.Response) => { + res.send(users[req.params.id] || { error: 'Cannot find user' }); + }, + destroy: (req: express.Request, res: express.Response) => { + var id = req.params.id; + var destroyed = id in users; + delete users[id]; + res.send(destroyed ? 'destroyed' : 'Cannot find user'); + }, + range: (req: express.Request, res: express.Response, a, b, format) => { + var range = users.slice(a, b + 1); + switch (format) { + case 'json': + res.send(range); + break; + case 'html': + default: + var html = '
    ' + range.map(user => { + return '
  • ' + user.name + '
  • '; + }).join('\n') + '
'; + res.send(html); + break; + } + } +}; + +// curl http://localhost:3000/users -- responds with all users +// curl http://localhost:3000/users/1 -- responds with user 1 +// curl http://localhost:3000/users/4 -- responds with error +// curl http://localhost:3000/users/1..3 -- responds with several users +// curl -X DELETE http://localhost:3000/users/1 -- deletes the user + +app.resource('/users', FUser); + +app.get('/', (req: express.Request, res: express.Response) => { + res.send([ + '

Examples:

    ' + , '
  • GET /users
  • ' + , '
  • GET /users/1
  • ' + , '
  • GET /users/3
  • ' + , '
  • GET /users/1..3
  • ' + , '
  • GET /users/1..3.json
  • ' + , '
  • DELETE /users/4
  • ' + , '
' + ].join('\n')); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +///////////////////// + + +var verbose: any; + +app.map = (a, route) => { + route = route || ''; + for (var key in a) { + switch (typeof a[key]) { + // { '/path': { ... }} + case 'object': + app.map(a[key], route + key); + break; + // get: function(){ ... } + case 'function': + if (verbose) console.log('%s %s', key, route); + app[key](route, a[key]); + break; + } + } +}; + +var users2 = { + list: (req: express.Request, res: express.Response) => { + res.send('user list'); + }, + + get: (req: express.Request, res: express.Response) => { + res.send('user ' + req.params.uid); + }, + + del: (req: express.Request, res: express.Response) => { + res.send('delete users'); + } +}; + +var pets2 = { + list: (req: express.Request, res: express.Response) => { + res.send('user ' + req.params.uid + '\'s pets'); + }, + + del: (req: express.Request, res: express.Response) => { + res.send('delete ' + req.params.uid + '\'s pet ' + req.params.pid); + } +}; + +app.map({ + '/users': { + get: users2.list, + del: users2.del, + '/:uid': { + get: users.get , + '/pets': { + get: pets2.list, + '/:pid': { + del: pets2.del + } + } + } + } +}); + +app.listen(3000); + +/////////////////////////// + +// Example requests: +// curl http://localhost:3000/user/0 +// curl http://localhost:3000/user/0/edit +// curl http://localhost:3000/user/1 +// curl http://localhost:3000/user/1/edit (unauthorized since this is not you) +// curl -X DELETE http://localhost:3000/user/0 (unauthorized since you are not an admin) + +function loadUser(req: express.Request, res: express.Response, next) { + // You would fetch your user from the db + var user = users[req.params.id]; + if (user) { + req.user = user; + next(); + } else { + next(new Error('Failed to load user ' + req.params.id)); + } +} + +function andRestrictToSelf(req: express.Request, res: express.Response, next) { + // If our authenticated user is the user we are viewing + // then everything is fine :) + if (req.authenticatedUser.id == req.user.id) { + next(); + } else { + // You may want to implement specific exceptions + // such as UnauthorizedError or similar so that you + // can handle these can be special-cased in an error handler + // (view ./examples/pages for this) + next(new Error('Unauthorized')); + } +} + +function andRestrictTo(role) { + return (req: express.Request, res: express.Response, next) => { + if (req.authenticatedUser.role == role) { + next(); + } else { + next(new Error('Unauthorized')); + } + }; +} + +// Middleware for faux authentication +// you would of course implement something real, +// but this illustrates how an authenticated user +// may interact with middleware + +app.use((req: express.Request, res: express.Response, next) => { + req.authenticatedUser = users[0]; + next(); +}); + +app.get('/', (req: express.Request, res: express.Response) => { + res.redirect('/user/0'); +}); + +app.get('/user/:id', loadUser, (req: express.Request, res: express.Response) => { + res.send('Viewing user ' + req.user.name); +}); + +app.get('/user/:id/edit', loadUser, andRestrictToSelf, (req: express.Request, res: express.Response) => { + res.send('Editing user ' + req.user.name); +}); + +app.del('/user/:id', loadUser, andRestrictTo('admin'), (req: express.Request, res: express.Response) => { + res.send('Deleted user ' + req.user.name); +}); + +app.listen(3000); +console.log('Express app started on port 3000'); + +///////////////////////// + +app.set('view engine', 'jade'); +app.set('views', __dirname); + +// populate search + +db.sadd('ferret', 'tobi'); +db.sadd('ferret', 'loki'); +db.sadd('ferret', 'jane'); +db.sadd('cat', 'manny'); +db.sadd('cat', 'luna'); + +/** + * GET the search page. + */ + +app.get('/', (req: express.Request, res: express.Response) => { + res.render('search'); +}); + +/** + * GET search for :query. + */ + +app.get('/search/:query?', (req: express.Request, res: express.Response) => { + var query = req.params.query; + db.smembers(query, (err, vals) => { + if (err) return res.send(500); + res.send(vals); + }); +}); + +/** + * GET client javascript. Here we use sendfile() + * because serving __dirname with the static() middleware + * would also mean serving our server "index.js" and the "search.jade" + * template. + */ + +app.get('/client.js', (req: express.Request, res: express.Response) => { + res.sendfile(__dirname + '/client.js'); +}); + +app.listen(3000); +console.log('app listening on port 3000'); + +/////////////////// + +app.use(express.logger('dev')); + +// Required by session() middleware +// pass the secret for signed cookies +// (required by session()) +app.use(express.cookieParser('keyboard cat')); + +// Populates req.session +app.use(express.session()); + +app.get('/', (req: express.Request, res: express.Response) => { + var body = ''; + if (req.session.views) { + ++req.session.views; + } else { + req.session.views = 1; + body += '

First time visiting? view this page in several browsers :)

'; + } + res.send(body + '

viewed ' + req.session.views + ' times.

'); +}); + +app.listen(3000); +console.log('Express app started on port 3000'); + +//////////////////////// + +// log requests +app.use(express.logger('dev')); + +// express on its own has no notion +// of a "file". The express.static() +// middleware checks for a file matching +// the `req.path` within the directory +// that you pass it. In this case "GET /js/app.js" +// will look for "./public/js/app.js". + +app.use(express.static(__dirname + '/public')); + +// if you wanted to "prefix" you may use +// the mounting feature of Connect, for example +// "GET /static/js/app.js" instead of "GET /js/app.js". +// The mount-path "/static" is simply removed before +// passing control to the express.static() middleware, +// thus it serves the file correctly by ignoring "/static" +app.use('/static', express.static(__dirname + '/public')); + +// if for some reason you want to serve files from +// several directories, you can use express.static() +// multiple times! Here we're passing "./public/css", +// this will allow "GET /style.css" instead of "GET /css/style.css": +app.use(express.static(__dirname + '/public/css')); + +// this examples does not have any routes, however +// you may `app.use(app.router)` before or after these +// static() middleware. If placed before them your routes +// will be matched BEFORE file serving takes place. If placed +// after as shown here then file serving is performed BEFORE +// any routes are hit: +app.use(app.router); + +app.listen(3000); +console.log('listening on port 3000'); +console.log('try:'); +console.log(' GET /hello.txt'); +console.log(' GET /js/app.js'); +console.log(' GET /css/style.css'); + +////////////////// + +/* +edit /etc/vhosts: + +127.0.0.1 foo.example.com +127.0.0.1 bar.example.com +127.0.0.1 example.com +*/ + +// Main app + +var main = express(); + +main.use(express.logger('dev')); + +main.get('/', (req: express.Request, res: express.Response) => { + res.send('Hello from main app!'); +}); + +main.get('/:sub', (req: express.Request, res: express.Response) => { + res.send('requsted ' + req.params.sub); +}); + +// Redirect app + +var redirect = express(); + +redirect.all('*', (req: express.Request, res: express.Response) => { + console.log(req.subdomains); + res.redirect('http://example.com:3000/' + req.subdomains[0]); +}); + +app.use(express.vhost('*.example.com', redirect)); +app.use(express.vhost('example.com', main)); + +app.listen(3000); +console.log('Express app started on port 3000'); + +//////////////////// + +// create an error with .status. we +// can then use the property in our +// custom error handler (Connect repects this prop as well) + +function merror(status, msg) { + var err = new Error(msg); + err.status = status; + return err; +} + +// if we wanted to supply more than JSON, we could +// use something similar to the content-negotiation +// example. + +// here we validate the API key, +// by mounting this middleware to /api +// meaning only paths prefixed with "/api" +// will cause this middleware to be invoked + +app.use('/api', (req, res: express.Response, next) => { + var key = req.query['api-key']; + + // key isnt present + if (!key) return next(merror(400, 'api key required')); + + // key is invalid + if (!~apiKeys.indexOf(key)) return next(merror(401, 'invalid api key')); + + // all good, store req.key for route access + req.key = key; + next(); +}); + +// position our routes above the error handling middleware, +// and below our API middleware, since we want the API validation +// to take place BEFORE our routes +app.use(app.router); + +// middleware with an arity of 4 are considered +// error handling middleware. When you next(err) +// it will be passed through the defined middleware +// in order, but ONLY those with an arity of 4, ignoring +// regular middleware. +app.use((err, req, res: express.Response) => { + // whatever you want here, feel free to populate + // properties on `err` to treat it differently in here. + res.send(err.status || 500, { error: err.message }); +}); + +// our custom JSON 404 middleware. Since it's placed last +// it will be the last middleware called, if all others +// invoke next() and do not respond. +app.use((req: express.Request, res: express.Response) => { + res.send(404, { error: "Lame, can't find that" }); +}); + +// map of valid api keys, typically mapped to +// account info with some sort of database like redis. +// api keys do _not_ serve as authentication, merely to +// track API usage or help prevent malicious behavior etc. + +var apiKeys = ['foo', 'bar', 'baz']; + +// these two objects will serve as our faux database + +var repos = [ + { name: 'express', url: 'http://github.com/visionmedia/express' } + , { name: 'stylus', url: 'http://github.com/learnboost/stylus' } + , { name: 'cluster', url: 'http://github.com/learnboost/cluster' } +]; + +var userRepos = { + tobi: [repos[0], repos[1]] + , loki: [repos[1]] + , jane: [repos[2]] +}; + +// we now can assume the api key is valid, +// and simply expose the data + +app.get('/api/users', (req: express.Request, res: express.Response) => { + res.send(users); +}); + +app.get('/api/repos', (req: express.Request, res: express.Response) => { + res.send(repos); +}); + +app.get('/api/user/:name/repos', (req: express.Request, res: express.Response, next) => { + var name = req.params.name + , user = userRepos[name]; + + if (user) res.send(user); + else next(); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express server listening on port 3000'); +} + +////// + +var router = new express.Router(); + +router.get('/', function (req, resp, next?) { + resp.send('response from router'); + resp.end(); + if (next) { + next(); + } +}); + +function test_general() { + + app.use((err, req, res: express.Response) => { + console.error(err.stack); + res.send(500, 'Something broke!'); + }); + app.use(express.bodyParser()); + app.use(express.methodOverride()); + app.use(app.router); + app.use(() => {}); + app.use(express.bodyParser()); + app.use(express.methodOverride()); + app.use(app.router); + + app.get('/', (req: express.Request, res: express.Response) => { + res.send('hello world'); + }); + + app.listen(3000); + + app.set('title', 'My Site'); + app.get('title'); + + app.enable('trust proxy'); + app.get('trust proxy'); + + app.disable('trust proxy'); + app.get('trust proxy'); + + app.enabled('trust proxy'); + + app.configure(() => { + app.set('title', 'My Application'); + }); + + app.configure('development', () => { + app.set('db uri', 'localhost/dev'); + }); + + app.configure('stage', 'production', () => {}); + + app.configure('1', '2', '3', () => {}); + + app.use((req: express.Request, res: express.Response) => { + res.send('Hello World'); + }); + + app.engine('jade', require('jade').__express); + + var User; + app.param('user', (req: express.Request, res: express.Response, next, id) => { + User.find(id, (err, user) =>{ + if (err) { + next(err); + } else if (user) { + req.user = user; + next(); + } else { + next(new Error('failed to load user')); + } + }); + }); + + app.get(/^\/commits\/(\d+)(?:\.\.(\d+))?$/, (req: express.Request, res: express.Response) => { + var from = req.params[0]; + var to = req.params[1] || 'HEAD'; + res.send('commit range ' + from + '..' + to); + }); + + app.locals.title = 'My App'; + app.locals.strftime = require('strftime'); + + var requireAuthentication; + var loadUser = () => {}; + app.all('*', requireAuthentication, loadUser); + app.all('*', loadUser); + app.all('*', loadUser, loadUser, loadUser); + + app.locals.title = 'My App'; + app.locals.strftime = require('strftime'); + app.locals({ + title: 'My App', + phone: '1-250-858-9990', + email: 'me@myapp.com' + }); + app.render('email', () => {}); + + app.render('email', { name: 'Tobi' }, () => {}); +} + +function test_request() { + var req: express.Request; + req.params.name; + req.params[0]; + req.query.q; + req.body.user.name; + app.use(express.bodyParser({ keepExtensions: true, uploadDir: '/my/files' })); + req.param('name'); + req.route; + req.cookies.name; + req.signedCookies; + req.get('Content-Type'); + req.accepts('html'); + req.accepts(['html', 'json']); + req.is('html'); + req.ip; + req.path; + req.host; + req.fresh; + req.stale; + req.xhr; + req.protocol; + req.subdomains; + req.originalUrl; + req.acceptedLanguages; + req.acceptedCharsets; + var charset; + req.acceptsCharset(charset); + var lang; + req.acceptsLanguage(lang); + req.session = null; +} + +function test_response() { + var res: express.Response; + res.status(404).sendfile('path/to/404.png'); + res.set('Content-Type', 'text/plain'); + res.set({ + 'Content-Type': 'text/plain', + 'Content-Length': '123', + 'ETag': '12345' + }); + res.get('Content-Type'); + res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true }); + res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }); + res.cookie('cart', { items: [1, 2, 3] }); + res.cookie('cart', { items: [1, 2, 3] }, { maxAge: 900000 });; + res.cookie('name', 'tobi', { signed: true }); + res.cookie('name', 'tobi', { path: '/admin' }); + res.clearCookie('name', { path: '/admin' }); + res.redirect('/foo/bar'); + res.redirect('http://example.com'); + res.redirect(301, 'http://example.com'); + res.charset = 'value'; + res.send('some html'); + res.send(new Buffer('whoop')); + res.send({ some: 'json' }); + res.send('some html'); + res.send(404, 'Sorry, we cannot find that!'); + res.send(500, { error: 'something blew up' }); + res.send(200); + res.set('Content-Type', 'text/html'); + res.send(new Buffer('some html')); + res.send('some html'); + res.send({ user: 'tobi' }); + res.send([1, 2, 3]); + res.json(null); + res.json({ user: 'tobi' }); + res.json(500, { error: 'message' }); + res.jsonp(null); + res.jsonp({ user: 'tobi' }); + res.jsonp(500, { error: 'message' }); + res.jsonp({ user: 'tobi' }); + res.type('application/json'); + + res.format({ + 'text/plain': () => { + res.send('hey'); + }, + 'text/html': () => { + res.send('hey'); + }, + 'application/json': () => { + res.send({ message: 'hey' }); + } + }); + + res.attachment(); + res.attachment('path/to/logo.png'); + app.get('/user/:uid/photos/:file', (req: express.Request, res: express.Response) => { + var uid = req.params.uid + , file = req.params.file; + + req.user.mayViewFilesFrom(uid, yes => { + if (yes) { + res.sendfile('/uploads/' + uid + '/' + file); + } else { + res.send(403, 'Sorry! you cant see that.'); + } + }); + }); + + res.download('/report-12345.pdf'); + res.download('/report-12345.pdf', 'report.pdf'); + res.download('/report-12345.pdf', 'report.pdf', err => { + if (err) { } else { } + }); + + res.links({ + next: 'http://api.example.com/users?page=2', + last: 'http://api.example.com/users?page=5' + }); + + app.use((req: express.Request, res: express.Response, next) => { + res.locals.user = req.user; + res.locals.authenticated = !req.user.anonymous; + next(); + }); + res.render('index', () => {}); + res.render('user', { name: 'Tobi' }, () => {}); + +} + +function test_middleware() { + app.use(express.basicAuth('username', 'password')); + app.use(express.basicAuth((user, pass) => { + return 'tj' == user && 'wahoo' == pass; + })); + app.use(express.bodyParser()); + app.use(express.json()); + app.use(express.urlencoded()); + app.use(express.multipart()); + app.use(express.logger()); + app.use(express.compress()); + app.use(express.methodOverride()); + app.use(express.bodyParser()); + app.use(express.cookieParser()); + app.use(express.cookieParser('some secret')); + app.use(express.cookieSession()); + app.use(express.directory('public')); + app.use(express.static('public')); + app.use(router.middleware); +} + +//////////////////// + +// make sure server can be shut down +var testShutdownServer = app.listen(0); +console.log('listening on port ' + testShutdownServer.address().port); +testShutdownServer.close(); diff --git a/express/express-3.1.0-tests.ts.tscparams b/express/express-3.1.0-tests.ts.tscparams new file mode 100644 index 000000000..e16c76dff --- /dev/null +++ b/express/express-3.1.0-tests.ts.tscparams @@ -0,0 +1 @@ +"" diff --git a/express/express-3.1.0.d.ts b/express/express-3.1.0.d.ts new file mode 100644 index 000000000..d5865f418 --- /dev/null +++ b/express/express-3.1.0.d.ts @@ -0,0 +1,1832 @@ +// Type definitions for Express 3.1 +// Project: http://expressjs.com +// Definitions by: Boris Yankov +// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped + +/* =================== USAGE =================== + + import express = require('express'); + var app = express(); + + =============================================== */ + +/// + + +declare module Express { + + // These open interfaces may be extended in an application-specific manner via declaration merging. + // See for example passport.d.ts (https://github.com/borisyankov/DefinitelyTyped/blob/master/passport/passport.d.ts) + export interface Request { } + export interface Response { } + export interface Application { } +} + + +declare module "express" { + import http = require('http'); + + // Merged declaration, e is both a callable function and a namespace + function e(): e.Express; + + module e { + interface IRoute { + path: string; + + method: string; + + callbacks: Function[]; + + regexp: any; + + /** + * Check if this route matches `path`, if so + * populate `.params`. + */ + match(path: string): boolean; + } + + class Route implements IRoute { + path: string; + + method: string; + + callbacks: Function[]; + + regexp: any; + match(path: string): boolean; + + /** + * Initialize `Route` with the given HTTP `method`, `path`, + * and an array of `callbacks` and `options`. + * + * Options: + * + * - `sensitive` enable case-sensitive routes + * - `strict` enable strict matching for trailing slashes + * + * @param method + * @param path + * @param callbacks + * @param options + */ + new (method: string, path: string, callbacks: Function[], options: any): Route; + } + + interface IRouter { + /** + * Map the given param placeholder `name`(s) to the given callback(s). + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the samesignature as middleware, the only differencing + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * next(err); + * } else if (user) { + * req.user = user; + * next(); + * } else { + * next(new Error('failed to load user')); + * } + * }); + * }); + * + * @param name + * @param fn + */ + param(name: string, fn: Function): T; + + param(name: string[], fn: Function): T; + + /** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + * + * @param path + * @param fn + */ + all(path: string, fn?: (req: Request, res: Response, next: Function) => any): T; + + all(path: string, ...callbacks: Function[]): void; + + get(name: string, ...handlers: RequestFunction[]): T; + + get(name: RegExp, ...handlers: RequestFunction[]): T; + + post(name: string, ...handlers: RequestFunction[]): T; + + post(name: RegExp, ...handlers: RequestFunction[]): T; + + put(name: string, ...handlers: RequestFunction[]): T; + + put(name: RegExp, ...handlers: RequestFunction[]): T; + + del(name: string, ...handlers: RequestFunction[]): T; + + del(name: RegExp, ...handlers: RequestFunction[]): T; + + patch(name: string, ...handlers: RequestFunction[]): T; + + patch(name: RegExp, ...handlers: RequestFunction[]): T; + } + + export class Router implements IRouter { + new (options?: any): Router; + + middleware (): any; + + param(name: string, fn: Function): Router; + + param(name: any[], fn: Function): Router; + + all(path: string, fn?: (req: Request, res: Response, next: Function) => any): Router; + + all(path: string, ...callbacks: Function[]): void; + + get(name: string, ...handlers: RequestFunction[]): Router; + + get(name: RegExp, ...handlers: RequestFunction[]): Router; + + post(name: string, ...handlers: RequestFunction[]): Router; + + post(name: RegExp, ...handlers: RequestFunction[]): Router; + + put(name: string, ...handlers: RequestFunction[]): Router; + + put(name: RegExp, ...handlers: RequestFunction[]): Router; + + del(name: string, ...handlers: RequestFunction[]): Router; + + del(name: RegExp, ...handlers: RequestFunction[]): Router; + + patch(name: string, ...handlers: RequestFunction[]): Router; + + patch(name: RegExp, ...handlers: RequestFunction[]): Router; + } + + interface Handler { + (req: Request, res: Response, next?: Function): void; + } + + interface CookieOptions { + maxAge?: number; + signed?: boolean; + expires?: Date; + httpOnly?: boolean; + path?: string; + domain?: string; + secure?: boolean; + } + + interface Errback { (err: Error): void; } + + interface Session { + /** + * Update reset `.cookie.maxAge` to prevent + * the cookie from expiring when the + * session is still active. + * + * @return {Session} for chaining + * @api public + */ + touch(): Session; + + /** + * Reset `.maxAge` to `.originalMaxAge`. + */ + resetMaxAge(): Session; + + /** + * Save the session data with optional callback `fn(err)`. + */ + save(fn: Function): Session; + + /** + * Re-loads the session data _without_ altering + * the maxAge properties. Invokes the callback `fn(err)`, + * after which time if no exception has occurred the + * `req.session` property will be a new `Session` object, + * although representing the same session. + */ + reload(fn: Function): Session; + + /** + * Destroy `this` session. + */ + destroy(fn: Function): Session; + + /** + * Regenerate this request's session. + */ + regenerate(fn: Function): Session; + + user: any; + + error: string; + + success: string; + + views: any; + + count: number; + } + + interface Request extends http.ServerRequest, Express.Request { + + session: Session; + + /** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + * + * @param name + */ + get (name: string): string; + + header(name: string): string; + + headers: { [key: string]: string; }; + + /** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json", a comma-delimted list such as "json, html, text/plain", + * or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html, json'); + * // => "json" + */ + accepts(type: string): string; + + accepts(type: string[]): string; + + /** + * Check if the given `charset` is acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param charset + */ + acceptsCharset(charset: string): boolean; + + /** + * Check if the given `lang` is acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param lang + */ + acceptsLanguage(lang: string): boolean; + + /** + * Parse Range header field, + * capping to the given `size`. + * + * Unspecified ranges such as "0-" require + * knowledge of your resource length. In + * the case of a byte range this is of course + * the total number of bytes. If the Range + * header field is not given `null` is returned, + * `-1` when unsatisfiable, `-2` when syntactically invalid. + * + * NOTE: remember that ranges are inclusive, so + * for example "Range: users=0-3" should respond + * with 4 users when available, not 3. + * + * @param size + */ + range(size: number): any[]; + + /** + * Return an array of Accepted media types + * ordered from highest quality to lowest. + */ + accepted: MediaType[]; + + /** + * Return an array of Accepted languages + * ordered from highest quality to lowest. + * + * Examples: + * + * Accept-Language: en;q=.5, en-us + * ['en-us', 'en'] + */ + acceptedLanguages: any[]; + + /** + * Return an array of Accepted charsets + * ordered from highest quality to lowest. + * + * Examples: + * + * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8 + * ['unicode-1-1', 'iso-8859-5'] + */ + acceptedCharsets: any[]; + + /** + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `connect.bodyParser()` middleware. + * + * @param name + * @param defaultValue + */ + param(name: string, defaultValue?: any): string; + + /** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param type + */ + is(type: string): boolean; + + /** + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting is enabled the "X-Forwarded-Proto" header + * field will be trusted. If you're running behind + * a reverse proxy that supplies https for you this + * may be enabled. + */ + protocol: string; + + /** + * Short-hand for: + * + * req.protocol == 'https' + */ + secure: boolean; + + /** + * Return the remote address, or when + * "trust proxy" is `true` return + * the upstream addr. + */ + ip: string; + + /** + * When "trust proxy" is `true`, parse + * the "X-Forwarded-For" ip address list. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream. + */ + ips: string[]; + + /** + * Return basic auth credentials. + * + * Examples: + * + * // http://tobi:hello@example.com + * req.auth + * // => { username: 'tobi', password: 'hello' } + */ + auth: any; + + /** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + */ + subdomains: string[]; + + /** + * Short-hand for `url.parse(req.url).pathname`. + */ + path: string; + + /** + * Parse the "Host" header field hostname. + */ + host: string; + + /** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + */ + fresh: boolean; + + /** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + */ + stale: boolean; + + /** + * Check if the request was an _XMLHttpRequest_. + */ + xhr: boolean; + + //body: { username: string; password: string; remember: boolean; title: string; }; + body: any; + + //cookies: { string; remember: boolean; }; + cookies: any; + + /** + * Used to generate an anti-CSRF token. + * Placed by the CSRF protection middleware. + */ + csrfToken(): string; + + method: string; + + params: any; + + user: any; + + authenticatedUser: any; + + files: any; + + /** + * Clear cookie `name`. + * + * @param name + * @param options + */ + clearCookie(name: string, options?: any): Response; + + query: any; + + route: any; + + signedCookies: any; + + originalUrl: string; + + url: string; + } + + interface MediaType { + value: string; + quality: number; + type: string; + subtype: string; + } + + interface Send { + (status: number, body?: any): Response; + (body: any): Response; + } + + interface Response extends http.ServerResponse, Express.Response { + /** + * Set status `code`. + * + * @param code + */ + status(code: number): Response; + + /** + * Set Link header field with the given `links`. + * + * Examples: + * + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); + * + * @param links + */ + links(links: any): Response; + + /** + * Send a response. + * + * Examples: + * + * res.send(new Buffer('wahoo')); + * res.send({ some: 'json' }); + * res.send('

some html

'); + * res.send(404, 'Sorry, cant find that'); + * res.send(404); + */ + send: Send; + + /** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * res.json(500, 'oh noes!'); + * res.json(404, 'I dont have that'); + */ + json: Send; + + /** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * res.jsonp(500, 'oh noes!'); + * res.jsonp(404, 'I dont have that'); + */ + jsonp: Send; + + /** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `fn(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 + * - `root` root directory for relative filenames + * + * Examples: + * + * The following example illustrates how `res.sendfile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendfile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendfile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + */ + sendfile(path: string): void; + + sendfile(path: string, options: any): void; + + sendfile(path: string, fn: Errback): void; + + sendfile(path: string, options: any, fn: Errback): void; + + /** + * Transfer the file at the given `path` as an attachment. + * + * Optionally providing an alternate attachment `filename`, + * and optional callback `fn(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * ocurred. Be sure to check `res.headerSent` if you plan to respond. + * + * This method uses `res.sendfile()`. + */ + download(path: string): void; + + download(path: string, filename: string): void; + + download(path: string, fn: Errback): void; + + download(path: string, filename: string, fn: Errback): void; + + /** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param type + */ + contentType(type: string): Response; + + /** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param type + */ + type(type: string): Response; + + /** + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. + * + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". + * + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. + * + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, + * + * 'text/html': function(){ + * res.send('

hey

'); + * }, + * + * 'appliation/json': function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * In addition to canonicalized MIME types you may + * also use extnames mapped to these types: + * + * res.format({ + * text: function(){ + * res.send('hey'); + * }, + * + * html: function(){ + * res.send('

hey

'); + * }, + * + * json: function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * By default Express passes an `Error` + * with a `.status` of 406 to `next(err)` + * if a match is not made. If you provide + * a `.default` callback it will be invoked + * instead. + * + * @param obj + */ + format(obj: any): Response; + + /** + * Set _Content-Disposition_ header to _attachment_ with optional `filename`. + * + * @param filename + */ + attachment(filename?: string): Response; + + /** + * Set header `field` to `val`, or pass + * an object of header fields. + * + * Examples: + * + * res.set('Foo', ['bar', 'baz']); + * res.set('Accept', 'application/json'); + * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + * + * Aliased as `res.header()`. + */ + set (field: any): Response; + + set (field: string, value?: string): Response; + + header(field: any): Response; + + header(field: string, value?: string): Response; + + /** + * Get value for header `field`. + * + * @param field + */ + get (field: string): string; + + /** + * Clear cookie `name`. + * + * @param name + * @param options + */ + clearCookie(name: string, options?: any): Response; + + /** + * Set cookie `name` to `val`, with the given `options`. + * + * Options: + * + * - `maxAge` max-age in milliseconds, converted to `expires` + * - `signed` sign the cookie + * - `path` defaults to "/" + * + * Examples: + * + * // "Remember Me" for 15 minutes + * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + * + * // save as above + * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) + */ + cookie(name: string, val: string, options: CookieOptions): Response; + + cookie(name: string, val: any, options: CookieOptions): Response; + + cookie(name: string, val: any): Response; + + /** + * Set the location header to `url`. + * + * The given `url` can also be the name of a mapped url, for + * example by default express supports "back" which redirects + * to the _Referrer_ or _Referer_ headers or "/". + * + * Examples: + * + * res.location('/foo/bar').; + * res.location('http://example.com'); + * res.location('../login'); // /blog/post/1 -> /blog/login + * + * Mounting: + * + * When an application is mounted and `res.location()` + * is given a path that does _not_ lead with "/" it becomes + * relative to the mount-point. For example if the application + * is mounted at "/blog", the following would become "/blog/login". + * + * res.location('login'); + * + * While the leading slash would result in a location of "/login": + * + * res.location('/login'); + * + * @param url + */ + location(url: string): Response; + + /** + * Redirect to the given `url` with optional response `status` + * defaulting to 302. + * + * The resulting `url` is determined by `res.location()`, so + * it will play nicely with mounted apps, relative paths, + * `"back"` etc. + * + * Examples: + * + * res.redirect('/foo/bar'); + * res.redirect('http://example.com'); + * res.redirect(301, 'http://example.com'); + * res.redirect('http://example.com', 301); + * res.redirect('../login'); // /blog/post/1 -> /blog/login + */ + redirect(url: string): void; + + redirect(status: number, url: string): void; + + redirect(url: string, status: number): void; + + /** + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. + * + * Options: + * + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered + */ + + render(view: string, options?: Object, callback?: (err: Error, html: string) => void ): void; + + render(view: string, callback?: (err: Error, html: string) => void ): void; + + locals: any; + + charset: string; + } + + interface RequestFunction { + (req: Request, res: Response, next: Function): any; + } + + interface Application extends IRouter, Express.Application { + /** + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + */ + init(): void; + + /** + * Initialize application configuration. + */ + defaultConfiguration(): void; + + /** + * Proxy `connect#use()` to apply settings to + * mounted applications. + **/ + use(route: string, callback?: Function): Application; + + use(route: string, server: Application): Application; + + use(callback: Function): Application; + + use(server: Application): Application; + + /** + * Register the given template engine callback `fn` + * as `ext`. + * + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.jade" file Express will invoke the following internally: + * + * app.engine('jade', require('jade').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you dont need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/visionmedia/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + */ + engine(ext: string, fn: Function): Application; + + param(name: string, fn: Function): Application; + + param(name: string[], fn: Function): Application; + + /** + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.get('foo'); + * // => "bar" + * + * Mounted servers inherit their parent server's settings. + * + * @param setting + * @param val + */ + set (setting: string, val: string): Application; + + get(name: string): string; + + get(name: string, ...handlers: RequestFunction[]): Application; + + get(name: RegExp, ...handlers: RequestFunction[]): Application; + + /** + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". + */ + path(): string; + + /** + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + */ + enabled(setting: string): boolean; + + /** + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + * + * @param setting + */ + disabled(setting: string): boolean; + + /** + * Enable `setting`. + * + * @param setting + */ + enable(setting: string): Application; + + /** + * Disable `setting`. + * + * @param setting + */ + disable(setting: string): Application; + + /** + * Configure callback for zero or more envs, + * when no `env` is specified that callback will + * be invoked for all environments. Any combination + * can be used multiple times, in any order desired. + * + * Examples: + * + * app.configure(function(){ + * // executed for all envs + * }); + * + * app.configure('stage', function(){ + * // executed staging env + * }); + * + * app.configure('stage', 'production', function(){ + * // executed for stage and production + * }); + * + * Note: + * + * These callbacks are invoked immediately, and + * are effectively sugar for the following: + * + * var env = process.env.NODE_ENV || 'development'; + * + * switch (env) { + * case 'development': + * ... + * break; + * case 'stage': + * ... + * break; + * case 'production': + * ... + * break; + * } + * + * @param env + * @param fn + */ + configure(env: string, fn: Function): Application; + + configure(env0: string, env1: string, fn: Function): Application; + + configure(env0: string, env1: string, env2: string, fn: Function): Application; + + configure(env0: string, env1: string, env2: string, env3: string, fn: Function): Application; + + configure(env0: string, env1: string, env2: string, env3: string, env4: string, fn: Function): Application; + + configure(fn: Function): Application; + + + /** + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. + * + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + * + * @param name + * @param options or fn + * @param fn + */ + render(name: string, options?: Object, callback?: (err: Error, html: string) => void): void; + + render(name: string, callback: (err: Error, html: string) => void): void; + + + /** + * Listen for connections. + * + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + */ + listen(port: number, hostname: string, backlog: number, callback?: Function): http.Server; + + listen(port: number, hostname: string, callback?: Function): http.Server; + + listen(port: number, callback?: Function): http.Server; + + listen(path: string, callback?: Function): http.Server; + + listen(handle: any, listeningListener?: Function): http.Server; + + route: IRoute; + + router: string; + + settings: any; + + resource: any; + + map: any; + + locals: any; + + /** + * The app.routes object houses all of the routes defined mapped by the + * associated HTTP verb. This object may be used for introspection + * capabilities, for example Express uses this internally not only for + * routing but to provide default OPTIONS behaviour unless app.options() + * is used. Your application or framework may also remove routes by + * simply by removing them from this object. + */ + routes: any; + } + + interface Express extends Application { + /** + * Framework version. + */ + version: string; + + /** + * Expose mime. + */ + mime: string; + + (): Application; + + /** + * Create an express application. + */ + createApplication(): Application; + + createServer(): Application; + + application: any; + + request: Request; + + response: Response; + } + + /** + * Body parser: + * + * Parse request bodies, supports _application/json_, + * _application/x-www-form-urlencoded_, and _multipart/form-data_. + * + * This is equivalent to: + * + * app.use(connect.json()); + * app.use(connect.urlencoded()); + * app.use(connect.multipart()); + * + * Examples: + * + * connect() + * .use(connect.bodyParser()) + * .use(function(req, res) { + * res.end('viewing user ' + req.body.user.name); + * }); + * + * $ curl -d 'user[name]=tj' http://local/ + * $ curl -d '{"user":{"name":"tj"}}' -H "Content-Type: application/json" http://local/ + * + * View [json](json.html), [urlencoded](urlencoded.html), and [multipart](multipart.html) for more info. + * + * @param options + */ + function bodyParser(options?: any): Handler; + + /** + * Error handler: + * + * Development error handler, providing stack traces + * and error message responses for requests accepting text, html, + * or json. + * + * Text: + * + * By default, and when _text/plain_ is accepted a simple stack trace + * or error message will be returned. + * + * JSON: + * + * When _application/json_ is accepted, connect will respond with + * an object in the form of `{ "error": error }`. + * + * HTML: + * + * When accepted connect will output a nice html stack trace. + */ + function errorHandler(opts?: any): Handler; + + /** + * Method Override: + * + * Provides faux HTTP method support. + * + * Pass an optional `key` to use when checking for + * a method override, othewise defaults to _\_method_. + * The original method is available via `req.originalMethod`. + * + * @param key + */ + function methodOverride(key?: string): Handler; + + /** + * Cookie parser: + * + * Parse _Cookie_ header and populate `req.cookies` + * with an object keyed by the cookie names. Optionally + * you may enabled signed cookie support by passing + * a `secret` string, which assigns `req.secret` so + * it may be used by other middleware. + * + * Examples: + * + * connect() + * .use(connect.cookieParser('optional secret string')) + * .use(function(req, res, next){ + * res.end(JSON.stringify(req.cookies)); + * }) + * + * @param secret + */ + function cookieParser(secret?: string): Handler; + + /** + * Session: + * + * Setup session store with the given `options`. + * + * Session data is _not_ saved in the cookie itself, however + * cookies are used, so we must use the [cookieParser()](cookieParser.html) + * middleware _before_ `session()`. + * + * Examples: + * + * connect() + * .use(connect.cookieParser()) + * .use(connect.session({ secret: 'keyboard cat', key: 'sid', cookie: { secure: true }})) + * + * Options: + * + * - `key` cookie name defaulting to `connect.sid` + * - `store` session store instance + * - `secret` session cookie is signed with this secret to prevent tampering + * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` + * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") + * + * Cookie option: + * + * By default `cookie.maxAge` is `null`, meaning no "expires" parameter is set + * so the cookie becomes a browser-session cookie. When the user closes the + * browser the cookie (and session) will be removed. + * + * ## req.session + * + * To store or access session data, simply use the request property `req.session`, + * which is (generally) serialized as JSON by the store, so nested objects + * are typically fine. For example below is a user-specific view counter: + * + * connect() + * .use(connect.favicon()) + * .use(connect.cookieParser()) + * .use(connect.session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }})) + * .use(function(req, res, next){ + * var sess = req.session; + * if (sess.views) { + * res.setHeader('Content-Type', 'text/html'); + * res.write('

views: ' + sess.views + '

'); + * res.write('

expires in: ' + (sess.cookie.maxAge / 1000) + 's

'); + * res.end(); + * sess.views++; + * } else { + * sess.views = 1; + * res.end('welcome to the session demo. refresh!'); + * } + * } + * )).listen(3000); + * + * ## Session#regenerate() + * + * To regenerate the session simply invoke the method, once complete + * a new SID and `Session` instance will be initialized at `req.session`. + * + * req.session.regenerate(function(err){ + * // will have a new session here + * }); + * + * ## Session#destroy() + * + * Destroys the session, removing `req.session`, will be re-generated next request. + * + * req.session.destroy(function(err){ + * // cannot access session here + * }); + * + * ## Session#reload() + * + * Reloads the session data. + * + * req.session.reload(function(err){ + * // session updated + * }); + * + * ## Session#save() + * + * Save the session. + * + * req.session.save(function(err){ + * // session saved + * }); + * + * ## Session#touch() + * + * Updates the `.maxAge` property. Typically this is + * not necessary to call, as the session middleware does this for you. + * + * ## Session#cookie + * + * Each session has a unique cookie object accompany it. This allows + * you to alter the session cookie per visitor. For example we can + * set `req.session.cookie.expires` to `false` to enable the cookie + * to remain for only the duration of the user-agent. + * + * ## Session#maxAge + * + * Alternatively `req.session.cookie.maxAge` will return the time + * remaining in milliseconds, which we may also re-assign a new value + * to adjust the `.expires` property appropriately. The following + * are essentially equivalent + * + * var hour = 3600000; + * req.session.cookie.expires = new Date(Date.now() + hour); + * req.session.cookie.maxAge = hour; + * + * For example when `maxAge` is set to `60000` (one minute), and 30 seconds + * has elapsed it will return `30000` until the current request has completed, + * at which time `req.session.touch()` is called to reset `req.session.maxAge` + * to its original value. + * + * req.session.cookie.maxAge; + * // => 30000 + * + * Session Store Implementation: + * + * Every session store _must_ implement the following methods + * + * - `.get(sid, callback)` + * - `.set(sid, session, callback)` + * - `.destroy(sid, callback)` + * + * Recommended methods include, but are not limited to: + * + * - `.length(callback)` + * - `.clear(callback)` + * + * For an example implementation view the [connect-redis](http://github.com/visionmedia/connect-redis) repo. + * + * @param options + */ + function session(options?: any): Handler; + + /** + * Hash the given `sess` object omitting changes + * to `.cookie`. + * + * @param sess + */ + function hash(sess: string): string; + + /** + * Static: + * + * Static file server with the given `root` path. + * + * Examples: + * + * var oneDay = 86400000; + * + * connect() + * .use(connect.static(__dirname + '/public')) + * + * connect() + * .use(connect.static(__dirname + '/public', { maxAge: oneDay })) + * + * Options: + * + * - `maxAge` Browser cache maxAge in milliseconds. defaults to 0 + * - `hidden` Allow transfer of hidden files. defaults to false + * - `redirect` Redirect to trailing "/" when the pathname is a dir. defaults to true + * + * @param root + * @param options + */ + function static(root: string, options?: any): Handler; + + /** + * Basic Auth: + * + * Enfore basic authentication by providing a `callback(user, pass)`, + * which must return `true` in order to gain access. Alternatively an async + * method is provided as well, invoking `callback(user, pass, callback)`. Populates + * `req.user`. The final alternative is simply passing username / password + * strings. + * + * Simple username and password + * + * connect(connect.basicAuth('username', 'password')); + * + * Callback verification + * + * connect() + * .use(connect.basicAuth(function(user, pass){ + * return 'tj' == user & 'wahoo' == pass; + * })) + * + * Async callback verification, accepting `fn(err, user)`. + * + * connect() + * .use(connect.basicAuth(function(user, pass, fn){ + * User.authenticate({ user: user, pass: pass }, fn); + * })) + * + * @param callback or username + * @param realm + */ + export function basicAuth(callback: (user: string, pass: string, fn : Function) => void, realm?: string): Handler; + + export function basicAuth(callback: (user: string, pass: string) => boolean, realm?: string): Handler; + + export function basicAuth(user: string, pass: string, realm?: string): Handler; + + /** + * Compress: + * + * Compress response data with gzip/deflate. + * + * Filter: + * + * A `filter` callback function may be passed to + * replace the default logic of: + * + * exports.filter = function(req, res){ + * return /json|text|javascript/.test(res.getHeader('Content-Type')); + * }; + * + * Options: + * + * All remaining options are passed to the gzip/deflate + * creation functions. Consult node's docs for additional details. + * + * - `chunkSize` (default: 16*1024) + * - `windowBits` + * - `level`: 0-9 where 0 is no compression, and 9 is slow but best compression + * - `memLevel`: 1-9 low is slower but uses less memory, high is fast but uses more + * - `strategy`: compression strategy + * + * @param options + */ + function compress(options?: any): Handler; + + /** + * Cookie Session: + * + * Cookie session middleware. + * + * var app = connect(); + * app.use(connect.cookieParser()); + * app.use(connect.cookieSession({ secret: 'tobo!', cookie: { maxAge: 60 * 60 * 1000 }})); + * + * Options: + * + * - `key` cookie name defaulting to `connect.sess` + * - `secret` prevents cookie tampering + * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` + * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") + * + * Clearing sessions: + * + * To clear the session simply set its value to `null`, + * `cookieSession()` will then respond with a 1970 Set-Cookie. + * + * req.session = null; + * + * @param options + */ + function cookieSession(options?: any): Handler; + + /** + * Anti CSRF: + * + * CSRF protection middleware. + * + * This middleware adds a `req.csrfToken()` function to make a token + * which should be added to requests which mutate + * state, within a hidden form field, query-string etc. This + * token is validated against the visitor's session. + * + * The default `value` function checks `req.body` generated + * by the `bodyParser()` middleware, `req.query` generated + * by `query()`, and the "X-CSRF-Token" header field. + * + * This middleware requires session support, thus should be added + * somewhere _below_ `session()` and `cookieParser()`. + * + * Options: + * + * - `value` a function accepting the request, returning the token + * + * @param options + */ + export function csrf(options?: {value?: Function}): Handler; + + /** + * Directory: + * + * Serve directory listings with the given `root` path. + * + * Options: + * + * - `hidden` display hidden (dot) files. Defaults to false. + * - `icons` display icons. Defaults to false. + * - `filter` Apply this filter function to files. Defaults to false. + * + * @param root + * @param options + */ + function directory(root: string, options?: any): Handler; + + /** + * Favicon: + * + * By default serves the connect favicon, or the favicon + * located by the given `path`. + * + * Options: + * + * - `maxAge` cache-control max-age directive, defaulting to 1 day + * + * Examples: + * + * Serve default favicon: + * + * connect() + * .use(connect.favicon()) + * + * Serve favicon before logging for brevity: + * + * connect() + * .use(connect.favicon()) + * .use(connect.logger('dev')) + * + * Serve custom favicon: + * + * connect() + * .use(connect.favicon('public/favicon.ico)) + * + * @param path + * @param options + */ + export function favicon(path?: string, options?: any): Handler; + + /** + * JSON: + * + * Parse JSON request bodies, providing the + * parsed object as `req.body`. + * + * Options: + * + * - `strict` when `false` anything `JSON.parse()` accepts will be parsed + * - `reviver` used as the second "reviver" argument for JSON.parse + * - `limit` byte limit disabled by default + * + * @param options + */ + function json(options?: any): Handler; + + /** + * Limit: + * + * Limit request bodies to the given size in `bytes`. + * + * A string representation of the bytesize may also be passed, + * for example "5mb", "200kb", "1gb", etc. + * + * connect() + * .use(connect.limit('5.5mb')) + * .use(handleImageUpload) + */ + function limit(bytes: number): Handler; + + function limit(bytes: string): Handler; + + /** + * Logger: + * + * Log requests with the given `options` or a `format` string. + * + * Options: + * + * - `format` Format string, see below for tokens + * - `stream` Output stream, defaults to _stdout_ + * - `buffer` Buffer duration, defaults to 1000ms when _true_ + * - `immediate` Write log line on request instead of response (for response times) + * + * Tokens: + * + * - `:req[header]` ex: `:req[Accept]` + * - `:res[header]` ex: `:res[Content-Length]` + * - `:http-version` + * - `:response-time` + * - `:remote-addr` + * - `:date` + * - `:method` + * - `:url` + * - `:referrer` + * - `:user-agent` + * - `:status` + * + * Formats: + * + * Pre-defined formats that ship with connect: + * + * - `default` ':remote-addr - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"' + * - `short` ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms' + * - `tiny` ':method :url :status :res[content-length] - :response-time ms' + * - `dev` concise output colored by response status for development use + * + * Examples: + * + * connect.logger() // default + * connect.logger('short') + * connect.logger('tiny') + * connect.logger({ immediate: true, format: 'dev' }) + * connect.logger(':method :url - :referrer') + * connect.logger(':req[content-type] -> :res[content-type]') + * connect.logger(function(tokens, req, res){ return 'some format string' }) + * + * Defining Tokens: + * + * To define a token, simply invoke `connect.logger.token()` with the + * name and a callback function. The value returned is then available + * as ":type" in this case. + * + * connect.logger.token('type', function(req, res){ return req.headers['content-type']; }) + * + * Defining Formats: + * + * All default formats are defined this way, however it's public API as well: + * + * connect.logger.format('name', 'string or function') + */ + function logger(options: string): Handler; + + function logger(options: Function): Handler; + + function logger(options?: any): Handler; + + /** + * Compile `fmt` into a function. + * + * @param fmt + */ + function compile(fmt: string): Handler; + + /** + * Define a token function with the given `name`, + * and callback `fn(req, res)`. + * + * @param name + * @param fn + */ + function token(name: string, fn: Function): any; + + /** + * Define a `fmt` with the given `name`. + */ + function format(name: string, str: string): any; + + function format(name: string, str: Function): any; + + /** + * Query: + * + * Automatically parse the query-string when available, + * populating the `req.query` object. + * + * Examples: + * + * connect() + * .use(connect.query()) + * .use(function(req, res){ + * res.end(JSON.stringify(req.query)); + * }); + * + * The `options` passed are provided to qs.parse function. + */ + function query(options: any): Handler; + + /** + * Reponse time: + * + * Adds the `X-Response-Time` header displaying the response + * duration in milliseconds. + */ + function responseTime(): Handler; + + /** + * Static cache: + * + * Enables a memory cache layer on top of + * the `static()` middleware, serving popular + * static files. + * + * By default a maximum of 128 objects are + * held in cache, with a max of 256k each, + * totalling ~32mb. + * + * A Least-Recently-Used (LRU) cache algo + * is implemented through the `Cache` object, + * simply rotating cache objects as they are + * hit. This means that increasingly popular + * objects maintain their positions while + * others get shoved out of the stack and + * garbage collected. + * + * Benchmarks: + * + * static(): 2700 rps + * node-static: 5300 rps + * static() + staticCache(): 7500 rps + * + * Options: + * + * - `maxObjects` max cache objects [128] + * - `maxLength` max cache object length 256kb + */ + function staticCache(options: any): Handler; + + /** + * Timeout: + * + * Times out the request in `ms`, defaulting to `5000`. The + * method `req.clearTimeout()` is added to revert this behaviour + * programmatically within your application's middleware, routes, etc. + * + * The timeout error is passed to `next()` so that you may customize + * the response behaviour. This error has the `.timeout` property as + * well as `.status == 408`. + */ + function timeout(ms: number): Handler; + + /** + * Vhost: + * + * Setup vhost for the given `hostname` and `server`. + * + * connect() + * .use(connect.vhost('foo.com', fooApp)) + * .use(connect.vhost('bar.com', barApp)) + * .use(connect.vhost('*.com', mainApp)) + * + * The `server` may be a Connect server or + * a regular Node `http.Server`. + * + * @param hostname + * @param server + */ + function vhost(hostname: string, server: any): Handler; + + function urlencoded(): any; + + function multipart(): any; + + } + + export = e; +} + diff --git a/express/express-tests.ts b/express/express-tests.ts index 57d1d638c..cda1e3e2e 100644 --- a/express/express-tests.ts +++ b/express/express-tests.ts @@ -3,1496 +3,19 @@ import express = require('express'); var app = express(); -////////////////////////// +app.engine('jade', require('jade').__express); +app.engine('html', require('ejs').renderFile); -var hash: any; - -// config - -app.set('view engine', 'ejs'); -app.set('views', __dirname + '/views'); - -// middleware - -app.use(express.bodyParser()); -app.use(express.cookieParser('shhhh, very secret')); -app.use(express.session()); - -// Session-persisted message middleware - -app.use((req: express.Request, res: express.Response, next) => { - var err = req.session.error - , msg = req.session.success; - delete req.session.error; - delete req.session.success; - res.locals.message = ''; - if (err) res.locals.message = '

' + err + '

'; - if (msg) res.locals.message = '

' + msg + '

'; - next(); -}); - -// dummy database - -var users = { - tj: { name: 'tj' } -}; - -// when you create a user, generate a salt -// and hash the password ('foobar' is the pass here) - -hash('foobar', (err, salt, hash) => { - if (err) throw err; - // store the salt & hash in the "db" - users.tj.salt = salt; - users.tj.hash = hash; -}); - - -// Authenticate using our plain-object database of doom! - -function authenticate(name, pass, fn) { - if (!module.parent) console.log('authenticating %s:%s', name, pass); - var user = users[name]; - // query the db for the given username - if (!user) return fn(new Error('cannot find user')); - // apply the same algorithm to the POSTed password, applying - // the hash against the pass / salt, if there is a match we - // found the user - hash(pass, user.salt, (err, hash) => { - if (err) return fn(err); - if (hash == user.hash) return fn(null, user); - fn(new Error('invalid password')); - }); -} - -function restrict(req: express.Request, res: express.Response, next?: Function) { - if (req.session.user) { - next(); - } else { - req.session.error = 'Access denied!'; - res.redirect('/login'); - } -} - -app.get('/', (req: express.Request, res: express.Response) => { - res.redirect('login'); -}); - -app.get('/restricted', restrict, (req: express.Request, res: express.Response) => { - res.send('Wahoo! restricted area, click to logout'); -}); - -app.get('/logout', (req: express.Request, res: express.Response) => { - // destroy the user's session to log them out - // will be re-created next request - req.session.destroy(() => { - res.redirect('/'); - }); -}); - -app.get('/login', (req: express.Request, res: express.Response) => { - res.render('login'); -}); - -app.post('/login', (req: express.Request, res: express.Response) => { - authenticate(req.body.username, req.body.password, (err, user) => { - if (user) { - // Regenerate session when signing in - // to prevent fixation - req.session.regenerate(() => { - // Store the user's primary key - // in the session store to be retrieved, - // or in this case the entire user object - req.session.user = user; - req.session.success = 'Authenticated as ' + user.name - + ' click to logout. ' - + ' You may now access /restricted.'; - res.redirect('back'); - }); - } else { - req.session.error = 'Authentication failed, please check your ' - + ' username and password.' - + ' (use "tj" and "foobar")'; - res.redirect('login'); - } - }); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -////////////// - -app.set('views', __dirname); -app.set('view engine', 'jade'); - -var pets = []; - -var n = 1000; -while (n--) { - pets.push({ name: 'Tobi', age: 2, species: 'ferret' }); - pets.push({ name: 'Loki', age: 1, species: 'ferret' }); - pets.push({ name: 'Jane', age: 6, species: 'ferret' }); -} - -app.use(express.logger('dev')); - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('pets', { pets: pets }); -}); - -app.listen(3000); -console.log('Express listening on port 3000'); - -///////////// - -app.get('/', (req: express.Request, res: express.Response) => { - res.format({ - html: () => { - res.send('
    ' + users.map(user => { - return '
  • ' + user.name + '
  • '; - }).join('') + '
'); - }, - - text: () => { - res.send(users.map(user => { - return ' - ' + user.name + '\n'; - }).join('')); - }, - - json: () => { - res.json(users); - } - }); -}); - -// or you could write a tiny middleware like -// this to abstract make things a bit more declarative: - -function format(mod) { - var obj = require(mod); - return (req: express.Request, res: express.Response) => { - res.format(obj); - }; -} - -app.get('/users', format('./users')); - -if (!module.parent) { - app.listen(3000); - console.log('listening on port 3000'); -} - -///////////////////////// - -// add favicon() before logger() so -// GET /favicon.ico requests are not -// logged, because this middleware -// reponds to /favicon.ico and does not -// call next() -app.use(express.favicon()); - -// custom log format -if ('test' != process.env.NODE_ENV) - app.use(express.logger(':method :url')); - -// parses request cookies, populating -// req.cookies and req.signedCookies -// when the secret is passed, used -// for signing the cookies. -app.use(express.cookieParser('my secret here')); - -// parses json, x-www-form-urlencoded, and multipart/form-data -app.use(express.bodyParser()); - -app.get('/', (req: express.Request, res: express.Response) => { - if (req.cookies.remember) { - res.send('Remembered :). Click to forget!.'); - } else { - res.send('

Check to ' - + '.

'); - } -}); - -app.get('/forget', (req: express.Request, res: express.Response) => { - res.clearCookie('remember'); - res.redirect('back'); -}); - -app.post('/', (req: express.Request, res: express.Response) => { - var minute = 60000; - if (req.body.remember) res.cookie('remember', 1, { maxAge: minute }); - res.redirect('back'); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -/////////////////// - -// ignore GET /favicon.ico -app.use(express.favicon()); - -// pass a secret to cookieParser() for signed cookies -app.use(express.cookieParser('manny is cool')); - -// add req.session cookie support -app.use(express.cookieSession()); - -// do something with the session -app.use(count); - -// custom middleware -function count(req: express.Request, res: express.Response) { - req.session.count = req.session.count || 0; - var n = req.session.count++; - res.send('viewed ' + n + ' times\n'); -} - -if (!module.parent) { - app.listen(3000); - console.log('Express server listening on port 3000'); -} - -/////////////// - -var api = app; - -app.use(express.static(__dirname + '/public')); - -// api middleware - -api.use(express.logger('dev')); -api.use(express.bodyParser()); - -/** - * CORS support. - */ - -api.all('*', (req: express.Request, res: express.Response, next) => { - if (!req.get('Origin')) return next(); - // use "*" here to accept any origin - res.set('Access-Control-Allow-Origin', 'http://localhost:3000'); - res.set('Access-Control-Allow-Methods', 'GET, POST'); - res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type'); - // res.set('Access-Control-Allow-Max-Age', 3600); - if ('OPTIONS' == req.method) return res.send(200); - next(); -}); - -/** - * POST a user. - */ - -api.post('/user', (req: express.Request, res: express.Response) => { - console.log(req.body); - res.send(201); -}); - -app.listen(3000); -api.listen(3001); - -console.log('app listening on 3000'); -console.log('api listening on 3001'); - -//////////////////// - -app.get('/', (req: express.Request, res: express.Response) => { - res.send(''); -}); - -// /files/* is accessed via req.params[0] -// but here we name it :file -app.get('/files/:file(*)', (req: express.Request, res: express.Response) => { - var file = req.params.file - , path = __dirname + '/files/' + file; - - res.download(path); -}); - -// error handling middleware. Because it's -// below our routes, you will be able to -// "intercept" errors, otherwise Connect -// will respond with 500 "Internal Server Error". -app.use((err, req, res: express.Response, next) => { - // special-case 404s, - // remember you could - // render a 404 template here - if (404 == err.status) { - res.statusCode = 404; - res.send('Cant find that file, sorry!'); - } else { - next(err); - } -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -/////////////////// - -// Register ejs as .html. If we did -// not call this, we would need to -// name our views foo.ejs instead -// of foo.html. The __express method -// is simply a function that engines -// use to hook into the Express view -// system by default, so if we want -// to change "foo.ejs" to "foo.html" -// we simply pass _any_ function, in this -// case `ejs.__express`. - -app.engine('.html', require('ejs').__express); - -// Optional since express defaults to CWD/views - -app.set('views', __dirname + '/views'); - -// Without this you would need to -// supply the extension to res.render() -// ex: res.render('users.html'). -app.set('view engine', 'html'); - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('users', { - users: users, - title: "EJS example", - header: "Some users" - }); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express app started on port 3000'); -} - -//////////////////// - -var test: any; - -if (!test) app.use(express.logger('dev')); -app.use(app.router); - -// the error handler is strategically -// placed *below* the app.router; if it -// were above it would not receive errors -// from app.get() etc -app.use(error); - -// error handling middleware have an arity of 4 -// instead of the typical (req: express.Request, res: express.Response, next), -// otherwise they behave exactly like regular -// middleware, you may have several of them, -// in different orders etc. - -function error(err, req, res: express.Response, next) { - // log it - if (!test) console.error(err.stack); - - // respond with 500 "Internal Server Error". - res.send(500); -} - -app.get('/', () => { - // Caught and passed down to the errorHandler middleware - throw new Error('something broke!'); -}); - -app.get('/next', (req: express.Request, res: express.Response, next) => { - // We can also pass exceptions to next() - process.nextTick(() => { - next(new Error('oh no!')); - }); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -///////////////////// - -var silent: any; - -// general config -app.set('views', __dirname + '/views'); -app.set('view engine', 'jade'); - -// our custom "verbose errors" setting -// which we can use in the templates -// via settings['verbose errors'] -app.enable('verbose errors'); - -// disable them in production -// use $ NODE_ENV=production node examples/error-pages -if ('production' == app.settings.env) { - app.disable('verbose errors'); -} - -app.use(express.favicon()); - -silent || app.use(express.logger('dev')); - -// "app.router" positions our routes -// above the middleware defined below, -// this means that Express will attempt -// to match & call routes _before_ continuing -// on, at which point we assume it's a 404 because -// no route has handled the request. - -app.use(app.router); - -// Since this is the last non-error-handling -// middleware use()d, we assume 404, as nothing else -// responded. - -// $ curl http://localhost:3000/notfound -// $ curl http://localhost:3000/notfound -H "Accept: application/json" -// $ curl http://localhost:3000/notfound -H "Accept: text/plain" - -app.use((req: express.Request, res: express.Response) => { - res.status(404); - - // respond with html page - if (req.accepts('html')) { - res.render('404', { url: req.url }); - return; - } - - // respond with json - if (req.accepts('json')) { - res.send({ error: 'Not found' }); - return; - } - - // default to plain-text. send() - res.type('txt').send('Not found'); -}); - -// error-handling middleware, take the same form -// as regular middleware, however they require an -// arity of 4, aka the signature (err, req, res: express.Response, next). -// when connect has an error, it will invoke ONLY error-handling -// middleware. - -// If we were to next() here any remaining non-error-handling -// middleware would then be executed, or if we next(err) to -// continue passing the error, only error-handling middleware -// would remain being executed, however here -// we simply respond with an error page. - -app.use((err, req, res: express.Response) => { - // we may use properties of the error object - // here and next(err) appropriately, or if - // we possibly recovered from the error, simply next(). - res.status(err.status || 500); - res.render('500', { error: err }); -}); - -// Routes - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('index.jade'); -}); - -app.get('/404', (req: express.Request, res: express.Response, next) => { - // trigger a 404 since no other middleware - // will match /404 after this one, and we're not - // responding here - next(); -}); - -app.get('/403', (req: express.Request, res: express.Response, next) => { - // trigger a 403 error - var err = new Error('not allowed!'); - err.status = 403; - next(err); -}); - -app.get('/500', (req: express.Request, res: express.Response, next) => { - // trigger a generic (500) error - next(new Error('keyboard cat!')); -}); - -if (!module.parent) { - app.listen(3000); - //silent ||  console.log('Express started on port 3000'); -} - -/////////////// - -var fs: any; -var md: any; - -app.set('view engine', 'jade'); -app.set('views', __dirname + '/views'); - -function User(name) { - this.private = 'heyyyy'; - this.secret = 'something'; - this.name = name; - this.id = 123; -} - -// You'll probably want to do -// something like this so you -// dont expose "secret" data. - -User.prototype.toJSON = function () { - return { - id: this.id, - name: this.name - }; -}; - -app.use(express.logger('dev')); - -// earlier on expose an object -// that we can tack properties on. -// all res.locals props are exposed -// to the templates, so "expose" will -// be present. - -app.use((req: express.Request, res: express.Response, next) => { - res.locals.expose = {}; - // you could alias this as req or res.expose - // to make it shorter and less annoying - next(); -}); - -// pretend we loaded a user - -app.use((req: express.Request, res: express.Response, next) => { - req.user = new User('Tobi'); - next(); -}); - -app.get('/', (req: express.Request, res: express.Response) => { - res.redirect('/user'); -}); - -app.get('/user', (req: express.Request, res: express.Response) => { - // we only want to expose the user - // to the client for this route: - res.locals.expose.user = req.user; - res.render('page'); -}); - -app.listen(3000); -console.log('app listening on port 3000'); - -/////////////////////// - -app.get('/', (req: express.Request, res: express.Response) => { - res.send('Hello World'); -}); - -app.listen(3000); -console.log('Express started on port 3000'); - -//////////////////// - -// register .md as an engine in express view system - -app.engine('md', (path, options, fn) => { - fs.readFile(path, 'utf8', (err, str) => { - if (err) return fn(err); - try { - var html = md(str); - html = html.replace(/\{([^}]+)\}/g, (_, name) => { - return options[name] || ''; - }); - fn(null, html); - } catch (err) { - fn(err); - } - }); -}); - -app.set('views', __dirname + '/views'); - -// make it the default so we dont need .md -app.set('view engine', 'md'); - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('index', { title: 'Markdown Example' }); -}); - -app.get('/fail', (req: express.Request, res: express.Response) => { - res.render('missing', { title: 'Markdown Example' }); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -/////////////////////// - -var mformat: any; - -// bodyParser in connect 2.x uses node-formidable to parse -// the multipart form data. -app.use(express.bodyParser()); - -app.get('/', (req: express.Request, res: express.Response) => { - res.send('
' - + '

Title:

' - + '

Image:

' - + '

' - + '
'); -}); - -app.post('/', (req: express.Request, res: express.Response) => { - // the uploaded file can be found as `req.files.image` and the - // title field as `req.body.title` - res.send(mformat('\nuploaded %s (%d Kb) to %s as %s' - , req.files.image.name - , req.files.image.size / 1024 | 0 - , req.files.image.path - , req.body.title)); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -////////////////// - - -// first: -// $ npm install redis online -// $ redis-server - -/** - * Module dependencies. - */ - -var online: any; -var db: any; - -// online - -online = online(db); - -// activity tracking, in this case using -// the UA string, you would use req.user.id etc - -app.use((req: express.Request, res: express.Response, next) => { - // fire-and-forget - online.add(req.headers['user-agent']); - next(); -}); - -/** - * List helper. - */ - -function list(ids) { - return '
    ' + ids.map(id => { - return '
  • ' + id + '
  • '; - }).join('') + '
'; -} - -/** - * GET users online. - */ - -app.get('/', (req: express.Request, res: express.Response, next) => { - online.last(5, (err, ids) => { - if (err) return next(err); - res.send('

Users online: ' + ids.length + '

' + list(ids)); - }); -}); - -app.listen(3000); -console.log('listening on port 3000'); - -/////////////////// - -// Convert :to and :from to integers - -app.param(['to', 'from'], (req: express.Request, res: express.Response, next, num, name) => { - req.params[name] = num = parseInt(num, 10); - if (isNaN(num)) { - next(new Error('failed to parseInt ' + num)); - } else { - next(); - } -}); - -// Load user by id - -app.param('user', (req: express.Request, res: express.Response, next, id) => { - if (req.user = users[id]) { - next(); - } else { - next(new Error('failed to find user')); - } -}); - -/** - * GET index. - */ - -app.get('/', (req: express.Request, res: express.Response) => { - res.send('Visit /user/0 or /users/0-2'); -}); - -/** - * GET :user. - */ - -app.get('/user/:user', (req: express.Request, res: express.Response) => { - res.send('user ' + req.user.name); -}); - -/** - * GET users :from - :to. - */ - -app.get('/users/:from-:to', (req: express.Request, res: express.Response) => { - var from = req.params.from - , to = req.params.to - , names = users.map(user => { return user.name; }); - res.send('users ' + names.slice(from, to).join(', ')); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -////////////////// - -// Ad-hoc example resource method - -app.resource = function (path, obj) { - this.get(path, obj.index); - this.get(path + '/:a..:b.:format?', (req: express.Request, res: express.Response) => { - var a = parseInt(req.params.a, 10) - , b = parseInt(req.params.b, 10) - , format = req.params.format; - obj.range(req, res, a, b, format); - }); - this.get(path + '/:id', obj.show); - this.del(path + '/:id', obj.destroy); -}; - -// Fake controller. - -var FUser = { - index: (req: express.Request, res: express.Response) => { - res.send(users); - }, - show: (req: express.Request, res: express.Response) => { - res.send(users[req.params.id] || { error: 'Cannot find user' }); - }, - destroy: (req: express.Request, res: express.Response) => { - var id = req.params.id; - var destroyed = id in users; - delete users[id]; - res.send(destroyed ? 'destroyed' : 'Cannot find user'); - }, - range: (req: express.Request, res: express.Response, a, b, format) => { - var range = users.slice(a, b + 1); - switch (format) { - case 'json': - res.send(range); - break; - case 'html': - default: - var html = '
    ' + range.map(user => { - return '
  • ' + user.name + '
  • '; - }).join('\n') + '
'; - res.send(html); - break; - } - } -}; - -// curl http://localhost:3000/users -- responds with all users -// curl http://localhost:3000/users/1 -- responds with user 1 -// curl http://localhost:3000/users/4 -- responds with error -// curl http://localhost:3000/users/1..3 -- responds with several users -// curl -X DELETE http://localhost:3000/users/1 -- deletes the user - -app.resource('/users', FUser); - -app.get('/', (req: express.Request, res: express.Response) => { - res.send([ - '

Examples:

    ' - , '
  • GET /users
  • ' - , '
  • GET /users/1
  • ' - , '
  • GET /users/3
  • ' - , '
  • GET /users/1..3
  • ' - , '
  • GET /users/1..3.json
  • ' - , '
  • DELETE /users/4
  • ' - , '
' - ].join('\n')); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -///////////////////// - - -var verbose: any; - -app.map = (a, route) => { - route = route || ''; - for (var key in a) { - switch (typeof a[key]) { - // { '/path': { ... }} - case 'object': - app.map(a[key], route + key); - break; - // get: function(){ ... } - case 'function': - if (verbose) console.log('%s %s', key, route); - app[key](route, a[key]); - break; - } - } -}; - -var users2 = { - list: (req: express.Request, res: express.Response) => { - res.send('user list'); - }, - - get: (req: express.Request, res: express.Response) => { - res.send('user ' + req.params.uid); - }, - - del: (req: express.Request, res: express.Response) => { - res.send('delete users'); - } -}; - -var pets2 = { - list: (req: express.Request, res: express.Response) => { - res.send('user ' + req.params.uid + '\'s pets'); - }, - - del: (req: express.Request, res: express.Response) => { - res.send('delete ' + req.params.uid + '\'s pet ' + req.params.pid); - } -}; - -app.map({ - '/users': { - get: users2.list, - del: users2.del, - '/:uid': { - get: users.get , - '/pets': { - get: pets2.list, - '/:pid': { - del: pets2.del - } - } - } - } -}); - -app.listen(3000); - -/////////////////////////// - -// Example requests: -// curl http://localhost:3000/user/0 -// curl http://localhost:3000/user/0/edit -// curl http://localhost:3000/user/1 -// curl http://localhost:3000/user/1/edit (unauthorized since this is not you) -// curl -X DELETE http://localhost:3000/user/0 (unauthorized since you are not an admin) - -function loadUser(req: express.Request, res: express.Response, next) { - // You would fetch your user from the db - var user = users[req.params.id]; - if (user) { - req.user = user; - next(); - } else { - next(new Error('Failed to load user ' + req.params.id)); - } -} - -function andRestrictToSelf(req: express.Request, res: express.Response, next) { - // If our authenticated user is the user we are viewing - // then everything is fine :) - if (req.authenticatedUser.id == req.user.id) { - next(); - } else { - // You may want to implement specific exceptions - // such as UnauthorizedError or similar so that you - // can handle these can be special-cased in an error handler - // (view ./examples/pages for this) - next(new Error('Unauthorized')); - } -} - -function andRestrictTo(role) { - return (req: express.Request, res: express.Response, next) => { - if (req.authenticatedUser.role == role) { - next(); - } else { - next(new Error('Unauthorized')); - } - }; -} - -// Middleware for faux authentication -// you would of course implement something real, -// but this illustrates how an authenticated user -// may interact with middleware - -app.use((req: express.Request, res: express.Response, next) => { - req.authenticatedUser = users[0]; - next(); -}); - -app.get('/', (req: express.Request, res: express.Response) => { - res.redirect('/user/0'); -}); - -app.get('/user/:id', loadUser, (req: express.Request, res: express.Response) => { - res.send('Viewing user ' + req.user.name); -}); - -app.get('/user/:id/edit', loadUser, andRestrictToSelf, (req: express.Request, res: express.Response) => { - res.send('Editing user ' + req.user.name); -}); - -app.del('/user/:id', loadUser, andRestrictTo('admin'), (req: express.Request, res: express.Response) => { - res.send('Deleted user ' + req.user.name); -}); - -app.listen(3000); -console.log('Express app started on port 3000'); - -///////////////////////// - -app.set('view engine', 'jade'); -app.set('views', __dirname); - -// populate search - -db.sadd('ferret', 'tobi'); -db.sadd('ferret', 'loki'); -db.sadd('ferret', 'jane'); -db.sadd('cat', 'manny'); -db.sadd('cat', 'luna'); - -/** - * GET the search page. - */ - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('search'); -}); - -/** - * GET search for :query. - */ - -app.get('/search/:query?', (req: express.Request, res: express.Response) => { - var query = req.params.query; - db.smembers(query, (err, vals) => { - if (err) return res.send(500); - res.send(vals); - }); -}); - -/** - * GET client javascript. Here we use sendfile() - * because serving __dirname with the static() middleware - * would also mean serving our server "index.js" and the "search.jade" - * template. - */ - -app.get('/client.js', (req: express.Request, res: express.Response) => { - res.sendfile(__dirname + '/client.js'); -}); - -app.listen(3000); -console.log('app listening on port 3000'); - -/////////////////// - -app.use(express.logger('dev')); - -// Required by session() middleware -// pass the secret for signed cookies -// (required by session()) -app.use(express.cookieParser('keyboard cat')); - -// Populates req.session -app.use(express.session()); - -app.get('/', (req: express.Request, res: express.Response) => { - var body = ''; - if (req.session.views) { - ++req.session.views; - } else { - req.session.views = 1; - body += '

First time visiting? view this page in several browsers :)

'; - } - res.send(body + '

viewed ' + req.session.views + ' times.

'); -}); - -app.listen(3000); -console.log('Express app started on port 3000'); - -//////////////////////// - -// log requests -app.use(express.logger('dev')); - -// express on its own has no notion -// of a "file". The express.static() -// middleware checks for a file matching -// the `req.path` within the directory -// that you pass it. In this case "GET /js/app.js" -// will look for "./public/js/app.js". - -app.use(express.static(__dirname + '/public')); - -// if you wanted to "prefix" you may use -// the mounting feature of Connect, for example -// "GET /static/js/app.js" instead of "GET /js/app.js". -// The mount-path "/static" is simply removed before -// passing control to the express.static() middleware, -// thus it serves the file correctly by ignoring "/static" app.use('/static', express.static(__dirname + '/public')); -// if for some reason you want to serve files from -// several directories, you can use express.static() -// multiple times! Here we're passing "./public/css", -// this will allow "GET /style.css" instead of "GET /css/style.css": -app.use(express.static(__dirname + '/public/css')); - -// this examples does not have any routes, however -// you may `app.use(app.router)` before or after these -// static() middleware. If placed before them your routes -// will be matched BEFORE file serving takes place. If placed -// after as shown here then file serving is performed BEFORE -// any routes are hit: -app.use(app.router); - -app.listen(3000); -console.log('listening on port 3000'); -console.log('try:'); -console.log(' GET /hello.txt'); -console.log(' GET /js/app.js'); -console.log(' GET /css/style.css'); - -////////////////// - -/* -edit /etc/vhosts: - -127.0.0.1 foo.example.com -127.0.0.1 bar.example.com -127.0.0.1 example.com -*/ - -// Main app - -var main = express(); - -main.use(express.logger('dev')); - -main.get('/', (req: express.Request, res: express.Response) => { - res.send('Hello from main app!'); -}); - -main.get('/:sub', (req: express.Request, res: express.Response) => { - res.send('requsted ' + req.params.sub); -}); - -// Redirect app - -var redirect = express(); - -redirect.all('*', (req: express.Request, res: express.Response) => { - console.log(req.subdomains); - res.redirect('http://example.com:3000/' + req.subdomains[0]); -}); - -app.use(express.vhost('*.example.com', redirect)); -app.use(express.vhost('example.com', main)); - -app.listen(3000); -console.log('Express app started on port 3000'); - -//////////////////// - -// create an error with .status. we -// can then use the property in our -// custom error handler (Connect repects this prop as well) - -function merror(status, msg) { - var err = new Error(msg); - err.status = status; - return err; -} - -// if we wanted to supply more than JSON, we could -// use something similar to the content-negotiation -// example. - -// here we validate the API key, -// by mounting this middleware to /api -// meaning only paths prefixed with "/api" -// will cause this middleware to be invoked - -app.use('/api', (req, res: express.Response, next) => { - var key = req.query['api-key']; - - // key isnt present - if (!key) return next(merror(400, 'api key required')); - - // key is invalid - if (!~apiKeys.indexOf(key)) return next(merror(401, 'invalid api key')); - - // all good, store req.key for route access - req.key = key; +// simple logger +app.use(function(req, res, next){ + console.log('%s %s', req.method, req.url); next(); }); -// position our routes above the error handling middleware, -// and below our API middleware, since we want the API validation -// to take place BEFORE our routes -app.use(app.router); - -// middleware with an arity of 4 are considered -// error handling middleware. When you next(err) -// it will be passed through the defined middleware -// in order, but ONLY those with an arity of 4, ignoring -// regular middleware. -app.use((err, req, res: express.Response) => { - // whatever you want here, feel free to populate - // properties on `err` to treat it differently in here. - res.send(err.status || 500, { error: err.message }); +app.get('/', function(req, res){ + res.send('hello world'); }); -// our custom JSON 404 middleware. Since it's placed last -// it will be the last middleware called, if all others -// invoke next() and do not respond. -app.use((req: express.Request, res: express.Response) => { - res.send(404, { error: "Lame, can't find that" }); -}); - -// map of valid api keys, typically mapped to -// account info with some sort of database like redis. -// api keys do _not_ serve as authentication, merely to -// track API usage or help prevent malicious behavior etc. - -var apiKeys = ['foo', 'bar', 'baz']; - -// these two objects will serve as our faux database - -var repos = [ - { name: 'express', url: 'http://github.com/visionmedia/express' } - , { name: 'stylus', url: 'http://github.com/learnboost/stylus' } - , { name: 'cluster', url: 'http://github.com/learnboost/cluster' } -]; - -var userRepos = { - tobi: [repos[0], repos[1]] - , loki: [repos[1]] - , jane: [repos[2]] -}; - -// we now can assume the api key is valid, -// and simply expose the data - -app.get('/api/users', (req: express.Request, res: express.Response) => { - res.send(users); -}); - -app.get('/api/repos', (req: express.Request, res: express.Response) => { - res.send(repos); -}); - -app.get('/api/user/:name/repos', (req: express.Request, res: express.Response, next) => { - var name = req.params.name - , user = userRepos[name]; - - if (user) res.send(user); - else next(); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express server listening on port 3000'); -} - -////// - -var router = new express.Router(); - -router.get('/', function (req, resp, next?) { - resp.send('response from router'); - resp.end(); - if (next) { - next(); - } -}); - -function test_general() { - - app.use((err, req, res: express.Response) => { - console.error(err.stack); - res.send(500, 'Something broke!'); - }); - app.use(express.bodyParser()); - app.use(express.methodOverride()); - app.use(app.router); - app.use(() => {}); - app.use(express.bodyParser()); - app.use(express.methodOverride()); - app.use(app.router); - - app.get('/', (req: express.Request, res: express.Response) => { - res.send('hello world'); - }); - - app.listen(3000); - - app.set('title', 'My Site'); - app.get('title'); - - app.enable('trust proxy'); - app.get('trust proxy'); - - app.disable('trust proxy'); - app.get('trust proxy'); - - app.enabled('trust proxy'); - - app.configure(() => { - app.set('title', 'My Application'); - }); - - app.configure('development', () => { - app.set('db uri', 'localhost/dev'); - }); - - app.configure('stage', 'production', () => {}); - - app.configure('1', '2', '3', () => {}); - - app.use((req: express.Request, res: express.Response) => { - res.send('Hello World'); - }); - - app.engine('jade', require('jade').__express); - - var User; - app.param('user', (req: express.Request, res: express.Response, next, id) => { - User.find(id, (err, user) =>{ - if (err) { - next(err); - } else if (user) { - req.user = user; - next(); - } else { - next(new Error('failed to load user')); - } - }); - }); - - app.get(/^\/commits\/(\d+)(?:\.\.(\d+))?$/, (req: express.Request, res: express.Response) => { - var from = req.params[0]; - var to = req.params[1] || 'HEAD'; - res.send('commit range ' + from + '..' + to); - }); - - app.locals.title = 'My App'; - app.locals.strftime = require('strftime'); - - var requireAuthentication; - var loadUser = () => {}; - app.all('*', requireAuthentication, loadUser); - app.all('*', loadUser); - app.all('*', loadUser, loadUser, loadUser); - - app.locals.title = 'My App'; - app.locals.strftime = require('strftime'); - app.locals({ - title: 'My App', - phone: '1-250-858-9990', - email: 'me@myapp.com' - }); - app.render('email', () => {}); - - app.render('email', { name: 'Tobi' }, () => {}); -} - -function test_request() { - var req: express.Request; - req.params.name; - req.params[0]; - req.query.q; - req.body.user.name; - app.use(express.bodyParser({ keepExtensions: true, uploadDir: '/my/files' })); - req.param('name'); - req.route; - req.cookies.name; - req.signedCookies; - req.get('Content-Type'); - req.accepts('html'); - req.accepts(['html', 'json']); - req.is('html'); - req.ip; - req.path; - req.host; - req.fresh; - req.stale; - req.xhr; - req.protocol; - req.subdomains; - req.originalUrl; - req.acceptedLanguages; - req.acceptedCharsets; - var charset; - req.acceptsCharset(charset); - var lang; - req.acceptsLanguage(lang); - req.session = null; -} - -function test_response() { - var res: express.Response; - res.status(404).sendfile('path/to/404.png'); - res.set('Content-Type', 'text/plain'); - res.set({ - 'Content-Type': 'text/plain', - 'Content-Length': '123', - 'ETag': '12345' - }); - res.get('Content-Type'); - res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true }); - res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); - res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }); - res.cookie('cart', { items: [1, 2, 3] }); - res.cookie('cart', { items: [1, 2, 3] }, { maxAge: 900000 });; - res.cookie('name', 'tobi', { signed: true }); - res.cookie('name', 'tobi', { path: '/admin' }); - res.clearCookie('name', { path: '/admin' }); - res.redirect('/foo/bar'); - res.redirect('http://example.com'); - res.redirect(301, 'http://example.com'); - res.charset = 'value'; - res.send('some html'); - res.send(new Buffer('whoop')); - res.send({ some: 'json' }); - res.send('some html'); - res.send(404, 'Sorry, we cannot find that!'); - res.send(500, { error: 'something blew up' }); - res.send(200); - res.set('Content-Type', 'text/html'); - res.send(new Buffer('some html')); - res.send('some html'); - res.send({ user: 'tobi' }); - res.send([1, 2, 3]); - res.json(null); - res.json({ user: 'tobi' }); - res.json(500, { error: 'message' }); - res.jsonp(null); - res.jsonp({ user: 'tobi' }); - res.jsonp(500, { error: 'message' }); - res.jsonp({ user: 'tobi' }); - res.type('application/json'); - - res.format({ - 'text/plain': () => { - res.send('hey'); - }, - 'text/html': () => { - res.send('hey'); - }, - 'application/json': () => { - res.send({ message: 'hey' }); - } - }); - - res.attachment(); - res.attachment('path/to/logo.png'); - app.get('/user/:uid/photos/:file', (req: express.Request, res: express.Response) => { - var uid = req.params.uid - , file = req.params.file; - - req.user.mayViewFilesFrom(uid, yes => { - if (yes) { - res.sendfile('/uploads/' + uid + '/' + file); - } else { - res.send(403, 'Sorry! you cant see that.'); - } - }); - }); - - res.download('/report-12345.pdf'); - res.download('/report-12345.pdf', 'report.pdf'); - res.download('/report-12345.pdf', 'report.pdf', err => { - if (err) { } else { } - }); - - res.links({ - next: 'http://api.example.com/users?page=2', - last: 'http://api.example.com/users?page=5' - }); - - app.use((req: express.Request, res: express.Response, next) => { - res.locals.user = req.user; - res.locals.authenticated = !req.user.anonymous; - next(); - }); - res.render('index', () => {}); - res.render('user', { name: 'Tobi' }, () => {}); - -} - -function test_middleware() { - app.use(express.basicAuth('username', 'password')); - app.use(express.basicAuth((user, pass) => { - return 'tj' == user && 'wahoo' == pass; - })); - app.use(express.bodyParser()); - app.use(express.json()); - app.use(express.urlencoded()); - app.use(express.multipart()); - app.use(express.logger()); - app.use(express.compress()); - app.use(express.methodOverride()); - app.use(express.bodyParser()); - app.use(express.cookieParser()); - app.use(express.cookieParser('some secret')); - app.use(express.cookieSession()); - app.use(express.directory('public')); - app.use(express.static('public')); - app.use(router.middleware); -} - -//////////////////// - -// make sure server can be shut down -var testShutdownServer = app.listen(0); -console.log('listening on port ' + testShutdownServer.address().port); -testShutdownServer.close(); +app.listen(3000); diff --git a/express/express.d.ts b/express/express.d.ts index eafc4c596..052173c83 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -1,22 +1,14 @@ -// Type definitions for Express 3.1 +// Type definitions for Express 4.x // Project: http://expressjs.com // Definitions by: Boris Yankov // DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped -/* =================== USAGE =================== - - import express = require('express'); - var app = express(); - - =============================================== */ - /// - declare module Express { // These open interfaces may be extended in an application-specific manner via declaration merging. - // See for example passport.d.ts (https://github.com/borisyankov/DefinitelyTyped/blob/master/passport/passport.d.ts) + // See for example method-override.d.ts (https://github.com/borisyankov/DefinitelyTyped/blob/master/method-override/method-override.d.ts) export interface Request { } export interface Response { } export interface Application { } @@ -26,51 +18,24 @@ declare module Express { declare module "express" { import http = require('http'); - // Merged declaration, e is both a callable function and a namespace function e(): e.Express; module e { interface IRoute { path: string; - - method: string; - - callbacks: Function[]; - - regexp: any; - - /** - * Check if this route matches `path`, if so - * populate `.params`. - */ - match(path: string): boolean; + stack: any; + all(...handler: RequestHandler[]): IRoute; + get(...handler: RequestHandler[]): IRoute; + post(...handler: RequestHandler[]): IRoute; + put(...handler: RequestHandler[]): IRoute; + delete(...handler: RequestHandler[]): IRoute; + patch(...handler: RequestHandler[]): IRoute; + options(...handler: RequestHandler[]): IRoute; } - class Route implements IRoute { - path: string; - - method: string; - - callbacks: Function[]; - - regexp: any; - match(path: string): boolean; - - /** - * Initialize `Route` with the given HTTP `method`, `path`, - * and an array of `callbacks` and `options`. - * - * Options: - * - * - `sensitive` enable case-sensitive routes - * - `strict` enable strict matching for trailing slashes - * - * @param method - * @param path - * @param callbacks - * @param options - */ - new (method: string, path: string, callbacks: Function[], options: any): Route; + interface IRouterMatcher { + (name: string, ...handlers: RequestHandler[]): T; + (name: RegExp, ...handlers: RequestHandler[]): T; } interface IRouter { @@ -103,9 +68,9 @@ declare module "express" { * @param name * @param fn */ - param(name: string, fn: Function): T; - - param(name: string[], fn: Function): T; + param(name: string, handler: RequestParamHandler): T; + param(name: string, matcher: RegExp): T; + param(name: string, mapper: (param: any) => any): T; /** * Special-cased "all" method, applying the given route `path`, @@ -114,68 +79,27 @@ declare module "express" { * @param path * @param fn */ - all(path: string, fn?: (req: Request, res: Response, next: Function) => any): T; + all: IRouterMatcher; + get: IRouterMatcher; + post: IRouterMatcher; + put: IRouterMatcher; + delete: IRouterMatcher; + patch: IRouterMatcher; + options: IRouterMatcher; - all(path: string, ...callbacks: Function[]): void; + route(path: string): IRoute; - get(name: string, ...handlers: RequestFunction[]): T; - - get(name: RegExp, ...handlers: RequestFunction[]): T; - - post(name: string, ...handlers: RequestFunction[]): T; - - post(name: RegExp, ...handlers: RequestFunction[]): T; - - put(name: string, ...handlers: RequestFunction[]): T; - - put(name: RegExp, ...handlers: RequestFunction[]): T; - - del(name: string, ...handlers: RequestFunction[]): T; - - del(name: RegExp, ...handlers: RequestFunction[]): T; - - patch(name: string, ...handlers: RequestFunction[]): T; - - patch(name: RegExp, ...handlers: RequestFunction[]): T; + use(server: Application): Application; + use(handler: RequestHandler): Application; + use(handler: ErrorRequestHandler): Application; + use(path: string, server: Application): Application; + use(path: string, handler: RequestHandler): Application; + use(path: string, handler: ErrorRequestHandler): Application; } - export class Router implements IRouter { - new (options?: any): Router; + export function Router(options?: any): Router; - middleware (): any; - - param(name: string, fn: Function): Router; - - param(name: any[], fn: Function): Router; - - all(path: string, fn?: (req: Request, res: Response, next: Function) => any): Router; - - all(path: string, ...callbacks: Function[]): void; - - get(name: string, ...handlers: RequestFunction[]): Router; - - get(name: RegExp, ...handlers: RequestFunction[]): Router; - - post(name: string, ...handlers: RequestFunction[]): Router; - - post(name: RegExp, ...handlers: RequestFunction[]): Router; - - put(name: string, ...handlers: RequestFunction[]): Router; - - put(name: RegExp, ...handlers: RequestFunction[]): Router; - - del(name: string, ...handlers: RequestFunction[]): Router; - - del(name: RegExp, ...handlers: RequestFunction[]): Router; - - patch(name: string, ...handlers: RequestFunction[]): Router; - - patch(name: RegExp, ...handlers: RequestFunction[]): Router; - } - - interface Handler { - (req: Request, res: Response, next?: Function): void; - } + export interface Router extends IRouter {} interface CookieOptions { maxAge?: number; @@ -189,61 +113,8 @@ declare module "express" { interface Errback { (err: Error): void; } - interface Session { - /** - * Update reset `.cookie.maxAge` to prevent - * the cookie from expiring when the - * session is still active. - * - * @return {Session} for chaining - * @api public - */ - touch(): Session; - - /** - * Reset `.maxAge` to `.originalMaxAge`. - */ - resetMaxAge(): Session; - - /** - * Save the session data with optional callback `fn(err)`. - */ - save(fn: Function): Session; - - /** - * Re-loads the session data _without_ altering - * the maxAge properties. Invokes the callback `fn(err)`, - * after which time if no exception has occurred the - * `req.session` property will be a new `Session` object, - * although representing the same session. - */ - reload(fn: Function): Session; - - /** - * Destroy `this` session. - */ - destroy(fn: Function): Session; - - /** - * Regenerate this request's session. - */ - regenerate(fn: Function): Session; - - user: any; - - error: string; - - success: string; - - views: any; - - count: number; - } - interface Request extends http.ServerRequest, Express.Request { - session: Session; - /** * Return request header. * @@ -450,17 +321,6 @@ declare module "express" { */ ips: string[]; - /** - * Return basic auth credentials. - * - * Examples: - * - * // http://tobi:hello@example.com - * req.auth - * // => { username: 'tobi', password: 'hello' } - */ - auth: any; - /** * Return subdomains as an array. * @@ -509,12 +369,6 @@ declare module "express" { //cookies: { string; remember: boolean; }; cookies: any; - /** - * Used to generate an anti-CSRF token. - * Placed by the CSRF protection middleware. - */ - csrfToken(): string; - method: string; params: any; @@ -650,11 +504,8 @@ declare module "express" { * }); */ sendfile(path: string): void; - sendfile(path: string, options: any): void; - sendfile(path: string, fn: Errback): void; - sendfile(path: string, options: any, fn: Errback): void; /** @@ -668,11 +519,8 @@ declare module "express" { * This method uses `res.sendfile()`. */ download(path: string): void; - download(path: string, filename: string): void; - download(path: string, fn: Errback): void; - download(path: string, filename: string, fn: Errback): void; /** @@ -782,12 +630,10 @@ declare module "express" { * * Aliased as `res.header()`. */ - set (field: any): Response; - - set (field: string, value?: string): Response; + set(field: any): Response; + set(field: string, value?: string): Response; header(field: any): Response; - header(field: string, value?: string): Response; /** @@ -823,9 +669,7 @@ declare module "express" { * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) */ cookie(name: string, val: string, options: CookieOptions): Response; - cookie(name: string, val: any, options: CookieOptions): Response; - cookie(name: string, val: any): Response; /** @@ -875,9 +719,7 @@ declare module "express" { * res.redirect('../login'); // /blog/post/1 -> /blog/login */ redirect(url: string): void; - redirect(status: number, url: string): void; - redirect(url: string, status: number): void; /** @@ -890,9 +732,7 @@ declare module "express" { * - `cache` boolean hinting to the engine it should cache * - `filename` filename of the view being rendered */ - render(view: string, options?: Object, callback?: (err: Error, html: string) => void ): void; - render(view: string, callback?: (err: Error, html: string) => void ): void; locals: any; @@ -900,10 +740,18 @@ declare module "express" { charset: string; } - interface RequestFunction { + interface ErrorRequestHandler { + (err: any, req: Request, res: Response, next: Function): any; + } + + interface RequestHandler { (req: Request, res: Response, next: Function): any; } + interface RequestParamHandler { + (req: Request, res: Response, next: Function, param: any): any; + } + interface Application extends IRouter, Express.Application { /** * Initialize the server. @@ -919,18 +767,6 @@ declare module "express" { */ defaultConfiguration(): void; - /** - * Proxy `connect#use()` to apply settings to - * mounted applications. - **/ - use(route: string, callback?: Function): Application; - - use(route: string, server: Application): Application; - - use(callback: Function): Application; - - use(server: Application): Application; - /** * Register the given template engine callback `fn` * as `ext`. @@ -961,10 +797,6 @@ declare module "express" { */ engine(ext: string, fn: Function): Application; - param(name: string, fn: Function): Application; - - param(name: string[], fn: Function): Application; - /** * Assign `setting` to `val`, or return `setting`'s value. * @@ -977,13 +809,12 @@ declare module "express" { * @param setting * @param val */ - set (setting: string, val: string): Application; - - get(name: string): string; - - get(name: string, ...handlers: RequestFunction[]): Application; - - get(name: RegExp, ...handlers: RequestFunction[]): Application; + set(setting: string, val: string): Application; + get: { + (name: string): string; // Getter + (name: string, ...handlers: RequestHandler[]): Application; + (name: RegExp, ...handlers: RequestHandler[]): Application; + } /** * Return the app's absolute pathname @@ -1079,18 +910,12 @@ declare module "express" { * @param env * @param fn */ - configure(env: string, fn: Function): Application; - - configure(env0: string, env1: string, fn: Function): Application; - - configure(env0: string, env1: string, env2: string, fn: Function): Application; - - configure(env0: string, env1: string, env2: string, env3: string, fn: Function): Application; - - configure(env0: string, env1: string, env2: string, env3: string, env4: string, fn: Function): Application; - configure(fn: Function): Application; - + configure(env0: string, fn: Function): Application; + configure(env0: string, env1: string, fn: Function): Application; + configure(env0: string, env1: string, env2: string, fn: Function): Application; + configure(env0: string, env1: string, env2: string, env3: string, fn: Function): Application; + configure(env0: string, env1: string, env2: string, env3: string, env4: string, fn: Function): Application; /** * Render the given view `name` name with `options` @@ -1108,7 +933,6 @@ declare module "express" { * @param fn */ render(name: string, options?: Object, callback?: (err: Error, html: string) => void): void; - render(name: string, callback: (err: Error, html: string) => void): void; @@ -1130,16 +954,12 @@ declare module "express" { * https.createServer({ ... }, app).listen(443); */ listen(port: number, hostname: string, backlog: number, callback?: Function): http.Server; - listen(port: number, hostname: string, callback?: Function): http.Server; - listen(port: number, callback?: Function): http.Server; - listen(path: string, callback?: Function): http.Server; - listen(handle: any, listeningListener?: Function): http.Server; - route: IRoute; + route(path: string): IRoute; router: string; @@ -1189,237 +1009,6 @@ declare module "express" { response: Response; } - /** - * Body parser: - * - * Parse request bodies, supports _application/json_, - * _application/x-www-form-urlencoded_, and _multipart/form-data_. - * - * This is equivalent to: - * - * app.use(connect.json()); - * app.use(connect.urlencoded()); - * app.use(connect.multipart()); - * - * Examples: - * - * connect() - * .use(connect.bodyParser()) - * .use(function(req, res) { - * res.end('viewing user ' + req.body.user.name); - * }); - * - * $ curl -d 'user[name]=tj' http://local/ - * $ curl -d '{"user":{"name":"tj"}}' -H "Content-Type: application/json" http://local/ - * - * View [json](json.html), [urlencoded](urlencoded.html), and [multipart](multipart.html) for more info. - * - * @param options - */ - function bodyParser(options?: any): Handler; - - /** - * Error handler: - * - * Development error handler, providing stack traces - * and error message responses for requests accepting text, html, - * or json. - * - * Text: - * - * By default, and when _text/plain_ is accepted a simple stack trace - * or error message will be returned. - * - * JSON: - * - * When _application/json_ is accepted, connect will respond with - * an object in the form of `{ "error": error }`. - * - * HTML: - * - * When accepted connect will output a nice html stack trace. - */ - function errorHandler(opts?: any): Handler; - - /** - * Method Override: - * - * Provides faux HTTP method support. - * - * Pass an optional `key` to use when checking for - * a method override, othewise defaults to _\_method_. - * The original method is available via `req.originalMethod`. - * - * @param key - */ - function methodOverride(key?: string): Handler; - - /** - * Cookie parser: - * - * Parse _Cookie_ header and populate `req.cookies` - * with an object keyed by the cookie names. Optionally - * you may enabled signed cookie support by passing - * a `secret` string, which assigns `req.secret` so - * it may be used by other middleware. - * - * Examples: - * - * connect() - * .use(connect.cookieParser('optional secret string')) - * .use(function(req, res, next){ - * res.end(JSON.stringify(req.cookies)); - * }) - * - * @param secret - */ - function cookieParser(secret?: string): Handler; - - /** - * Session: - * - * Setup session store with the given `options`. - * - * Session data is _not_ saved in the cookie itself, however - * cookies are used, so we must use the [cookieParser()](cookieParser.html) - * middleware _before_ `session()`. - * - * Examples: - * - * connect() - * .use(connect.cookieParser()) - * .use(connect.session({ secret: 'keyboard cat', key: 'sid', cookie: { secure: true }})) - * - * Options: - * - * - `key` cookie name defaulting to `connect.sid` - * - `store` session store instance - * - `secret` session cookie is signed with this secret to prevent tampering - * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` - * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") - * - * Cookie option: - * - * By default `cookie.maxAge` is `null`, meaning no "expires" parameter is set - * so the cookie becomes a browser-session cookie. When the user closes the - * browser the cookie (and session) will be removed. - * - * ## req.session - * - * To store or access session data, simply use the request property `req.session`, - * which is (generally) serialized as JSON by the store, so nested objects - * are typically fine. For example below is a user-specific view counter: - * - * connect() - * .use(connect.favicon()) - * .use(connect.cookieParser()) - * .use(connect.session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }})) - * .use(function(req, res, next){ - * var sess = req.session; - * if (sess.views) { - * res.setHeader('Content-Type', 'text/html'); - * res.write('

views: ' + sess.views + '

'); - * res.write('

expires in: ' + (sess.cookie.maxAge / 1000) + 's

'); - * res.end(); - * sess.views++; - * } else { - * sess.views = 1; - * res.end('welcome to the session demo. refresh!'); - * } - * } - * )).listen(3000); - * - * ## Session#regenerate() - * - * To regenerate the session simply invoke the method, once complete - * a new SID and `Session` instance will be initialized at `req.session`. - * - * req.session.regenerate(function(err){ - * // will have a new session here - * }); - * - * ## Session#destroy() - * - * Destroys the session, removing `req.session`, will be re-generated next request. - * - * req.session.destroy(function(err){ - * // cannot access session here - * }); - * - * ## Session#reload() - * - * Reloads the session data. - * - * req.session.reload(function(err){ - * // session updated - * }); - * - * ## Session#save() - * - * Save the session. - * - * req.session.save(function(err){ - * // session saved - * }); - * - * ## Session#touch() - * - * Updates the `.maxAge` property. Typically this is - * not necessary to call, as the session middleware does this for you. - * - * ## Session#cookie - * - * Each session has a unique cookie object accompany it. This allows - * you to alter the session cookie per visitor. For example we can - * set `req.session.cookie.expires` to `false` to enable the cookie - * to remain for only the duration of the user-agent. - * - * ## Session#maxAge - * - * Alternatively `req.session.cookie.maxAge` will return the time - * remaining in milliseconds, which we may also re-assign a new value - * to adjust the `.expires` property appropriately. The following - * are essentially equivalent - * - * var hour = 3600000; - * req.session.cookie.expires = new Date(Date.now() + hour); - * req.session.cookie.maxAge = hour; - * - * For example when `maxAge` is set to `60000` (one minute), and 30 seconds - * has elapsed it will return `30000` until the current request has completed, - * at which time `req.session.touch()` is called to reset `req.session.maxAge` - * to its original value. - * - * req.session.cookie.maxAge; - * // => 30000 - * - * Session Store Implementation: - * - * Every session store _must_ implement the following methods - * - * - `.get(sid, callback)` - * - `.set(sid, session, callback)` - * - `.destroy(sid, callback)` - * - * Recommended methods include, but are not limited to: - * - * - `.length(callback)` - * - `.clear(callback)` - * - * For an example implementation view the [connect-redis](http://github.com/visionmedia/connect-redis) repo. - * - * @param options - */ - function session(options?: any): Handler; - - /** - * Hash the given `sess` object omitting changes - * to `.cookie`. - * - * @param sess - */ - function hash(sess: string): string; - /** * Static: * @@ -1444,387 +1033,7 @@ declare module "express" { * @param root * @param options */ - function static(root: string, options?: any): Handler; - - /** - * Basic Auth: - * - * Enfore basic authentication by providing a `callback(user, pass)`, - * which must return `true` in order to gain access. Alternatively an async - * method is provided as well, invoking `callback(user, pass, callback)`. Populates - * `req.user`. The final alternative is simply passing username / password - * strings. - * - * Simple username and password - * - * connect(connect.basicAuth('username', 'password')); - * - * Callback verification - * - * connect() - * .use(connect.basicAuth(function(user, pass){ - * return 'tj' == user & 'wahoo' == pass; - * })) - * - * Async callback verification, accepting `fn(err, user)`. - * - * connect() - * .use(connect.basicAuth(function(user, pass, fn){ - * User.authenticate({ user: user, pass: pass }, fn); - * })) - * - * @param callback or username - * @param realm - */ - export function basicAuth(callback: (user: string, pass: string, fn : Function) => void, realm?: string): Handler; - - export function basicAuth(callback: (user: string, pass: string) => boolean, realm?: string): Handler; - - export function basicAuth(user: string, pass: string, realm?: string): Handler; - - /** - * Compress: - * - * Compress response data with gzip/deflate. - * - * Filter: - * - * A `filter` callback function may be passed to - * replace the default logic of: - * - * exports.filter = function(req, res){ - * return /json|text|javascript/.test(res.getHeader('Content-Type')); - * }; - * - * Options: - * - * All remaining options are passed to the gzip/deflate - * creation functions. Consult node's docs for additional details. - * - * - `chunkSize` (default: 16*1024) - * - `windowBits` - * - `level`: 0-9 where 0 is no compression, and 9 is slow but best compression - * - `memLevel`: 1-9 low is slower but uses less memory, high is fast but uses more - * - `strategy`: compression strategy - * - * @param options - */ - function compress(options?: any): Handler; - - /** - * Cookie Session: - * - * Cookie session middleware. - * - * var app = connect(); - * app.use(connect.cookieParser()); - * app.use(connect.cookieSession({ secret: 'tobo!', cookie: { maxAge: 60 * 60 * 1000 }})); - * - * Options: - * - * - `key` cookie name defaulting to `connect.sess` - * - `secret` prevents cookie tampering - * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` - * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") - * - * Clearing sessions: - * - * To clear the session simply set its value to `null`, - * `cookieSession()` will then respond with a 1970 Set-Cookie. - * - * req.session = null; - * - * @param options - */ - function cookieSession(options?: any): Handler; - - /** - * Anti CSRF: - * - * CSRF protection middleware. - * - * This middleware adds a `req.csrfToken()` function to make a token - * which should be added to requests which mutate - * state, within a hidden form field, query-string etc. This - * token is validated against the visitor's session. - * - * The default `value` function checks `req.body` generated - * by the `bodyParser()` middleware, `req.query` generated - * by `query()`, and the "X-CSRF-Token" header field. - * - * This middleware requires session support, thus should be added - * somewhere _below_ `session()` and `cookieParser()`. - * - * Options: - * - * - `value` a function accepting the request, returning the token - * - * @param options - */ - export function csrf(options?: {value?: Function}): Handler; - - /** - * Directory: - * - * Serve directory listings with the given `root` path. - * - * Options: - * - * - `hidden` display hidden (dot) files. Defaults to false. - * - `icons` display icons. Defaults to false. - * - `filter` Apply this filter function to files. Defaults to false. - * - * @param root - * @param options - */ - function directory(root: string, options?: any): Handler; - - /** - * Favicon: - * - * By default serves the connect favicon, or the favicon - * located by the given `path`. - * - * Options: - * - * - `maxAge` cache-control max-age directive, defaulting to 1 day - * - * Examples: - * - * Serve default favicon: - * - * connect() - * .use(connect.favicon()) - * - * Serve favicon before logging for brevity: - * - * connect() - * .use(connect.favicon()) - * .use(connect.logger('dev')) - * - * Serve custom favicon: - * - * connect() - * .use(connect.favicon('public/favicon.ico)) - * - * @param path - * @param options - */ - export function favicon(path?: string, options?: any): Handler; - - /** - * JSON: - * - * Parse JSON request bodies, providing the - * parsed object as `req.body`. - * - * Options: - * - * - `strict` when `false` anything `JSON.parse()` accepts will be parsed - * - `reviver` used as the second "reviver" argument for JSON.parse - * - `limit` byte limit disabled by default - * - * @param options - */ - function json(options?: any): Handler; - - /** - * Limit: - * - * Limit request bodies to the given size in `bytes`. - * - * A string representation of the bytesize may also be passed, - * for example "5mb", "200kb", "1gb", etc. - * - * connect() - * .use(connect.limit('5.5mb')) - * .use(handleImageUpload) - */ - function limit(bytes: number): Handler; - - function limit(bytes: string): Handler; - - /** - * Logger: - * - * Log requests with the given `options` or a `format` string. - * - * Options: - * - * - `format` Format string, see below for tokens - * - `stream` Output stream, defaults to _stdout_ - * - `buffer` Buffer duration, defaults to 1000ms when _true_ - * - `immediate` Write log line on request instead of response (for response times) - * - * Tokens: - * - * - `:req[header]` ex: `:req[Accept]` - * - `:res[header]` ex: `:res[Content-Length]` - * - `:http-version` - * - `:response-time` - * - `:remote-addr` - * - `:date` - * - `:method` - * - `:url` - * - `:referrer` - * - `:user-agent` - * - `:status` - * - * Formats: - * - * Pre-defined formats that ship with connect: - * - * - `default` ':remote-addr - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"' - * - `short` ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms' - * - `tiny` ':method :url :status :res[content-length] - :response-time ms' - * - `dev` concise output colored by response status for development use - * - * Examples: - * - * connect.logger() // default - * connect.logger('short') - * connect.logger('tiny') - * connect.logger({ immediate: true, format: 'dev' }) - * connect.logger(':method :url - :referrer') - * connect.logger(':req[content-type] -> :res[content-type]') - * connect.logger(function(tokens, req, res){ return 'some format string' }) - * - * Defining Tokens: - * - * To define a token, simply invoke `connect.logger.token()` with the - * name and a callback function. The value returned is then available - * as ":type" in this case. - * - * connect.logger.token('type', function(req, res){ return req.headers['content-type']; }) - * - * Defining Formats: - * - * All default formats are defined this way, however it's public API as well: - * - * connect.logger.format('name', 'string or function') - */ - function logger(options: string): Handler; - - function logger(options: Function): Handler; - - function logger(options?: any): Handler; - - /** - * Compile `fmt` into a function. - * - * @param fmt - */ - function compile(fmt: string): Handler; - - /** - * Define a token function with the given `name`, - * and callback `fn(req, res)`. - * - * @param name - * @param fn - */ - function token(name: string, fn: Function): any; - - /** - * Define a `fmt` with the given `name`. - */ - function format(name: string, str: string): any; - - function format(name: string, str: Function): any; - - /** - * Query: - * - * Automatically parse the query-string when available, - * populating the `req.query` object. - * - * Examples: - * - * connect() - * .use(connect.query()) - * .use(function(req, res){ - * res.end(JSON.stringify(req.query)); - * }); - * - * The `options` passed are provided to qs.parse function. - */ - function query(options: any): Handler; - - /** - * Reponse time: - * - * Adds the `X-Response-Time` header displaying the response - * duration in milliseconds. - */ - function responseTime(): Handler; - - /** - * Static cache: - * - * Enables a memory cache layer on top of - * the `static()` middleware, serving popular - * static files. - * - * By default a maximum of 128 objects are - * held in cache, with a max of 256k each, - * totalling ~32mb. - * - * A Least-Recently-Used (LRU) cache algo - * is implemented through the `Cache` object, - * simply rotating cache objects as they are - * hit. This means that increasingly popular - * objects maintain their positions while - * others get shoved out of the stack and - * garbage collected. - * - * Benchmarks: - * - * static(): 2700 rps - * node-static: 5300 rps - * static() + staticCache(): 7500 rps - * - * Options: - * - * - `maxObjects` max cache objects [128] - * - `maxLength` max cache object length 256kb - */ - function staticCache(options: any): Handler; - - /** - * Timeout: - * - * Times out the request in `ms`, defaulting to `5000`. The - * method `req.clearTimeout()` is added to revert this behaviour - * programmatically within your application's middleware, routes, etc. - * - * The timeout error is passed to `next()` so that you may customize - * the response behaviour. This error has the `.timeout` property as - * well as `.status == 408`. - */ - function timeout(ms: number): Handler; - - /** - * Vhost: - * - * Setup vhost for the given `hostname` and `server`. - * - * connect() - * .use(connect.vhost('foo.com', fooApp)) - * .use(connect.vhost('bar.com', barApp)) - * .use(connect.vhost('*.com', mainApp)) - * - * The `server` may be a Connect server or - * a regular Node `http.Server`. - * - * @param hostname - * @param server - */ - function vhost(hostname: string, server: any): Handler; - - function urlencoded(): any; - - function multipart(): any; - + function static(root: string, options?: any): RequestHandler; } export = e; diff --git a/method-override/method-override-tests.ts b/method-override/method-override-tests.ts new file mode 100644 index 000000000..84b4e966e --- /dev/null +++ b/method-override/method-override-tests.ts @@ -0,0 +1,15 @@ +/// + +import express = require('express'); +import methodOverride = require('method-override'); +var app = express(); + +app.use(methodOverride('X-HTTP-Method-Override')); +app.use(methodOverride((req: express.Request, res: express.Response) => { + if (req.body && typeof req.body === 'object' && '_method' in req.body) { + // look in urlencoded POST bodies and delete it + var method = req.body._method + delete req.body._method + return method + } +})); diff --git a/method-override/method-override.d.ts b/method-override/method-override.d.ts new file mode 100644 index 000000000..51b62f521 --- /dev/null +++ b/method-override/method-override.d.ts @@ -0,0 +1,24 @@ +// Type definitions for method-override +// Project: https://github.com/expressjs/method-override +// Definitions by: Santi Albo +// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Express { + export interface Request { + originalMethod?: string; + } +} + +declare module "method-override" { + import express = require('express'); + module e { + interface MethodOverrideOptions { + methods: string[]; + } + } + function e(getter: string, options?: any): express.RequestHandler; + function e(getter: (req: express.Request, res: express.Response) => string, options?: any): express.RequestHandler; + export = e; +} \ No newline at end of file From 333341f11141c70aec220cf03e81e0a5b9bb4f20 Mon Sep 17 00:00:00 2001 From: Sean Xu Date: Thu, 12 Jun 2014 13:14:44 -0700 Subject: [PATCH 007/324] Created legacy WinJS 1.0 definitions file. --- winjs/legacy/winjs-1.0.d.ts | 6690 +++++++++++++++++++++++++++++++++++ 1 file changed, 6690 insertions(+) create mode 100644 winjs/legacy/winjs-1.0.d.ts diff --git a/winjs/legacy/winjs-1.0.d.ts b/winjs/legacy/winjs-1.0.d.ts new file mode 100644 index 000000000..901e86e4b --- /dev/null +++ b/winjs/legacy/winjs-1.0.d.ts @@ -0,0 +1,6690 @@ +// Type definitions for WinJS +// Project: http://msdn.microsoft.com/en-us/library/windows/apps/br229773.aspx +// Definitions by: TypeScript samples , Adam Hewitt , Craig Treasure +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +/** + * Defines an Element object. +**/ +interface Element { + winControl: any; // TODO: This should be control? +} + +/** + * Utility class for easy access to operations on application folders +**/ +interface IOHelper { + /** + * Determines whether the specified file exists in the folder. + * @param filename The name of the file. + * @returns A promise that completes with a value of either true (if the file exists) or false. + **/ + exists(filename: string): WinJS.Promise; + + /** + * Reads the specified file. If the file doesn't exist, the specified default value is returned. + * @param fileName The file to read from. + * @param def The default value to be returned if the file failed to open. + * @returns A promise that completes with a value that is either the contents of the file, or the specified default value. + **/ + readText(fileName: string, def?: string): WinJS.Promise; + + /** + * Deletes a file from the folder. + * @param fileName The file to be deleted. + * @returns A promise that is fulfilled when the file has been deleted. + **/ + remove(fileName: string): WinJS.Promise; + + /** + * Writes the specified text to the specified file. + * @param fileName The name of the file. + * @param text The content to be written to the file. + * @returns A promise that completes with a value that is the number of characters written. + **/ + writeText(fileName: string, text: string): WinJS.Promise; +} + +/** + * Provides application-level functionality, for example activation, storage, and application events. +**/ +declare module WinJS.Application { + //#region Objects + + /** + * The local storage of the application. + **/ + var local: IOHelper; + + /** + * The roaming storage of the application. + **/ + var roaming: IOHelper; + + /** + * The temp storage of the application. + **/ + var temp: IOHelper; + + /** + * An object used for storing app information that can be used to restore the app's state after it has been suspended and then resumed. Data that can usefully be contained in this object includes the current navigation page or any information the user has added to the input controls on the page. You should not add information about customization (for example colors) or user-defined lists of content. + **/ + var sessionState: any; + + //#endregion Objects + + //#region Functions + + /** + * Adds an event listener for application-level events: activated, checkpoint, error, loaded, ready, settings, and unload. + * @param type The type (name) of the event. You can use any of the following:"activated", "checkpoint", "error", "loaded", "ready", "settings", and" unload". + * @param listener The listener to invoke when the event is raised. + * @param capture true to initiate capture, otherwise false. + **/ + function addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Queues a checkpoint event. + **/ + function checkpoint(): void; + + /** + * Queues an event to be processed by the WinJS.Application event queue. + * @param eventRecord The event object is expected to have a type property that is used as the event name when dispatching on the WinJS.Application event queue. The entire object is provided to event listeners in the detail property of the event. + **/ + function queueEvent(eventRecord: any): void; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture Specifies whether or not to initiate capture. + **/ + function removeEventListener(type: string, listener: Function, useCapture?: any): void; + + /** + * Starts dispatching application events (the activated, checkpoint, error, loaded, ready, settings, and unload events). + **/ + function start(): void; + + /** + * Stops application event processing and resets WinJS.Application to its initial state. All WinJS.Application event listeners (for the activated, checkpoint, error, loaded, ready, settings, and unload events) are removed. + **/ + function stop(): void; + + //#endregion Functions + + //#region Events + + /** + * Occurs when WinRT activation has occurred. The name of this event is "activated" (and also "mainwindowactivated"). This event occurs after the loaded event and before the ready event. + * @param eventInfo An object that contains information about the event. For more information about event arguments, see the WinRT event argument classes: WebUICachedFileUpdaterActivatedEventArgs, WebUICameraSettingsActivatedEventArgs, WebUIContactPickerActivatedEventArgs, WebUIDeviceActivatedEventArgs, WebUIFileActivatedEventArgs, WebUIFileOpenPickerActivatedEventArgs, WebUIFileSavePickerActivatedEventArgs, WebUILaunchActivatedEventArgs, WebUIPrintTaskSettingsActivatedEventArgs, WebUIProtocolActivatedEventArgs, WebUISearchActivatedEventArgs, WebUIShareTargetActivatedEventArgs. + **/ + function onactivated(eventInfo: CustomEvent): void; + + /** + * Occurs when receiving PLM notification or when the checkpoint function is called. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following subproperties: type, setPromise. + **/ + function oncheckpoint(eventInfo: CustomEvent): void; + + /** + * Occurs when an unhandled error has been raised. + * @param eventInfo An object that contains information about the event. + **/ + function onerror(eventInfo: CustomEvent): void; + + /** + * Occurs after the DOMContentLoaded event, which fires after the page has been parsed but before all the resources are loaded. This event occurs before the activated event and the ready event. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following subproperties: type, setPromise. + **/ + function onloaded(eventInfo: CustomEvent): void; + + /** + * Occurs when the application is ready. This event occurs after the loaded event and the activated event. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following sub-properties: type, setPromise. + **/ + function onready(eventInfo: CustomEvent): void; + + /** + * Occurs when the settings charm is invoked. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: type, applicationcommands. + **/ + function onsettings(eventInfo: CustomEvent): void; + + /** + * Occurs when the application is about to be unloaded. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following sub-properties: type, setPromise. + **/ + function onunload(eventInfo: CustomEvent): void; + + //#endregion Events + +} +/** + * Provides functionality for data and template binding. +**/ +declare module WinJS.Binding { + //#region Properties + + /** + * Determines whether or not binding should automatically set the ID of an element. This property should be set to true in apps that use WinJS (WinJS) binding. + **/ + var optimizeBindingReferences: boolean; + + //#endregion Properties + + //#region Objects + + /** + * Allows you to add bindable properties dynamically. + **/ + var dynamicObservableMixin: { + //#region Methods + + /** + * Adds a property with change notification to this object, including a ECMAScript5 property definition. + * @param name The name of the property to add. + * @param value This object is returned. + **/ + addProperty(name: string, value: any): void; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns This object is returned. + **/ + bind(name: string, action: any): Function; + + /** + * Gets a property value by name. + * @param name The name of the property to get. + * @returns The value of the property as an observable object. + **/ + getProperty(name: string): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: string, oldValue: string): Promise; + + /** + * Removes a property value. + * @param name The name of the property to remove. + * @returns This object is returned. + **/ + removeProperty(name: string): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns This object is returned. + **/ + setProperty(name: string, value: any): any; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns A promise that completes when the notifications for this property change have been processed. If multiple notifications are coalesced, the promise may be canceled or the value of the promise may be updated. The fulfilled value of the promise is the new value of the property for which the notifications have been completed. + **/ + updateProperty(name: string, value: any): Promise; + + //#endregion Methods + + }; + + /** + * Do not instantiate. A list returned by the createFiltered method. + **/ + class FilteredListProjection extends ListProjection { + //#region Methods + + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value that was replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + //#endregion Methods + + //#region Properties + + /** + * The length of the list. Returns an integer value one higher than the highest element defined in an list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Do not instantiate. A list of groups. + **/ + class GroupsListProjection extends ListBase { + //#region Methods + + /** + * Gets a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Gets a key/data pair for the specified key. + * @param key The key of the value to retrieve. + * @returns An object with two properties: key and data. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + //#endregion Methods + + //#region Properties + + /** + * The length of the list. Returns an integer value one higher than the highest element defined in an list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Do not instantiate. Sorts the underlying list by group key and within a group respects the position of the item in the underlying list. Returned by createGrouped. + **/ + class GroupedSortedListProjection extends SortedListProjection { + //#region Properties + + /** + * Gets a List, which is a projection of the groups that were identified in this list. + **/ + groups: GroupsListProjection; + + //#endregion Properties + + } + + /** + * Represents a list of objects that can be accessed by index or by a string key. Provides methods to search, sort, filter, and manipulate the data. + **/ + class List extends ListBaseWithMutators { + //#region Constructors + + /** + * Creates a List object. + * @constructor + * @param list The array containing the elements to initalize the list. + * @param options You can set two Boolean options: binding and proxy. If options.binding is true, the list contains the result of calling as on the element values. If options.proxy is true, the list specified as the first parameter is used as the storage for the List. This option should be used with care, because uncoordinated edits to the data storage may result in errors. + **/ + constructor(list?: T[], options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Gets a key/data pair for the specified list index. + * @param index The index of value to retrieve. + * @returns An object with .key and .data properties. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Gets a key/data pair for the list item key specified. + * @param key The key of the value to retrieve. + * @returns An object with .key and .data properties. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Gets the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Moves the value at index to the specified position. + * @param index The original index of the value. + * @param newIndex The index of the value after the move. + **/ + move(index: number, newIndex: number): void; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Returns a list with the elements reversed. This method reverses the elements of a list object in place. It does not create a new list object during execution. + **/ + reverse(): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value that was replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + /** + * Returns a list with the elements sorted. This method sorts the elements of a list object in place. It does not create a new list object during execution. + * @param sortFunction The function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + **/ + sort(sortFunction: (left: T, right: T) => number): void; + + /** + * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the list from which to start removing elements. + * @param howMany The number of elements to remove. + * @param item The elements to insert into the list in place of the deleted elements. + * @returns The deleted elements. + **/ + splice(start: number, howMany?: number, ...item: T[]): T[]; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the length of the list, which is an integer value one higher than the highest element defined in the list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Represents a base class for lists. + **/ + class ListBase { + //#region Events + + /** + * An item in the list has changed its value. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, newItem, newValue, oldItem, oldValue. + **/ + onitemchanged(eventInfo: CustomEvent): void; + + /** + * A new item has been inserted into the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + oniteminserted(eventInfo: CustomEvent): void; + + /** + * An item has been changed locations in the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemmoved(eventInfo: CustomEvent): void; + + /** + * An item has been mutated. This event occurs as a result of calling the notifyMutated method. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemmutated(eventInfo: CustomEvent): void; + + /** + * An item has been removed from the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemremoved(eventInfo: CustomEvent): void; + + /** + * The list has been refreshed. Any references to items in the list may be incorrect. + * @param eventInfo An object that contains information about the event. The detail property of this object is null. + **/ + onreload(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture If true, initiates capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns A reference to this observableMixin object. + **/ + bind(name: string, action: Function): any; + + /** + * Returns a new list consisting of a combination of two arrays. + * @param item Additional items to add to the end of the list. + * @returns An array containing the concatenation of the list and any other supplied items. + **/ + concat(...item: T[]): T[]; + + /** + * Creates a live filtered projection over this list. As the list changes, the filtered projection reacts to those changes and may also change. + * @param predicate A function that accepts a single argument. The createFiltered function calls the callback with each element in the list. If the function returns true, that element will be included in the filtered list. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @returns A filtered projection over the list. + **/ + createFiltered(predicate: (x: T) => boolean): FilteredListProjection; + + /** + * Creates a live grouped projection over this list. As the list changes, the grouped projection reacts to those changes and may also change. The grouped projection sorts all the elements of the list to be in group-contiguous order. The grouped projection also contains a .groups property, which is a List representing the groups that were found in the list. + * @param groupKey A function that accepts a single argument. The function is called with each element in the list, the function should return a string representing the group containing the element. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @param groupData A function that accepts a single argument. The function is called once, on one element per group. It should return the value that should be set as the data of the .groups list element for this group. The data value usually serves as summary or header information for the group. + * @param groupSorter A function that accepts two arguments. The function is called with pairs of group keys found in the list. It must return one of the following numeric values: negative if the first argument is less than the second (sorted before), zero if the two arguments are equivalent, positive if the first argument is greater than the second (sorted after). + * @returns A grouped projection over the list. + **/ + createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter: (left: string, right: string) => number): GroupedSortedListProjection; + + /** + * Creates a live sorted projection over this list. As the list changes, the sorted projection reacts to those changes and may also change. + * @param sorter A function that accepts two arguments. The function is called with elements in the list. It must return one of the following numeric values: negative if the first argument is less than the second, zero if the two arguments are equivalent, positive if the first argument is greater than the second. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @returns A sorted projection over the list. + **/ + createSorted(sorter: (left: T, right: T) => number): SortedListProjection; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Checks whether the specified callback function returns true for all elements in a list. + * @param callback A function that accepts up to three arguments. This function is called for each element in the list until it returns false or the end of the list is reached. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns true if the callback returns true for all elements in the list. + **/ + every(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Returns the elements of a list that meet the condition specified in a callback function. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns An array containing the elements that meet the condition specified in the callback function. + **/ + filter(callback: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; + + /** + * Calls the specified callback function for each element in a list. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. The arguments are as follows: value, index, array. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + **/ + forEach(callback: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + + /** + * Gets the value at the specified index. + * @param index The index of the value to get. + * @returns The value at the specified index. + **/ + getAt(index: number): T; + + /** + * Gets the index of the first occurrence of the specified value in a list. + * @param searchElement The value to locate in the list. + * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + * @returns The index of the first occurrence of a value in a list or -1 if not found. + **/ + indexOf(searchElement: T, fromIndex?: number): number; + + /** + * Returns a string consisting of all the elements of a list separated by the specified separator string. + * @param separator A string used to separate the elements of a list. If this parameter is omitted, the list elements are separated with a comma. + * @returns The elements of a list separated by the specified separator string. + **/ + join(separator: string): string; + + /** + * Gets the index of the last occurrence of the specified value in a list. + * @param searchElement The value to locate in the list. + * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the list. + * @returns The index of the last occurrence of a value in a list, or -1 if not found. + **/ + lastIndexOf(searchElement: T, fromIndex: number): number; + + /** + * Calls the specified callback function on each element of a list, and returns an array that contains the results. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. + * @param thisArg n object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns An array containing the result of calling the callback function on each element in the list. + **/ + map(callback: (value: T, index: number, array: T[]) => G, thisArg?: any): G[]; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: any, oldValue: any): Promise; + + /** + * Forces the list to send a reload notification to any listeners. + **/ + notifyReload(): void; + + /** + * Accumulates a single result by calling the specified callback function for all elements in a list. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callback A function that accepts up to four arguments. These arguments are: previousValue, currentValue, currentIndex, array. The function is called for each element in the list. + * @param initiallValue If initialValue is specified, it is used as the value with which to start the accumulation. The first call to the function provides this value as an argument instead of a list value. + * @returns The return value from the last call to the callback function. + **/ + reduce(callback: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => T, initiallValue?: T): T; + + /** + * Accumulates a single result by calling the specified callback function for all elements in a list, starting with the last member of the list. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callback A function that accepts up to four arguments. These arguments are: previousValue, currentValue, currentIndex, array. The function is called for each element in the list. + * @param initialValue If initialValue is specified, it is used as the value with which to start the accumulation. The first call to the callback function provides this value as an argument instead of a list value. + * @returns The return value from the last call to callback function. + **/ + reduceRight(callback: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => T, initialValue?: T): T; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true if capture is to be initiated, otherwise false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Extracts a section of a list and returns a new list. + * @param begin The index that specifies the beginning of the section. + * @param end The index that specifies the end of the section. + * @returns Returns a section of list. + **/ + slice(begin: number, end: number): T[]; + + /** + * Checks whether the specified callback function returns true for any element of a list. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list until it returns true, or until the end of the list. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns true if callback returns true for any element in the list. + **/ + some(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + //#endregion Methods + + //#region Properties + + /** + * Gets the IListDataSource for the list. The only purpose of this property is to adapt a List to the data model that is used by ListView and FlipView. + **/ + dataSource: WinJS.UI.IListDataSource; + + /** + * Indicates that the object is compatibile with declarative processing. + **/ + static supportedForProcessing: boolean; + + //#endregion Properties + } + + /** + * Represents a base class for normal list modifying operations. + **/ + class ListBaseWithMutators extends ListBase { + //#region Methods + + /** + * Removes the last element from a list and returns it. + * @returns The last element from the list. + **/ + pop(): T; + + /** + * Appends new element(s) to a list, and returns the new length of the list. + * @param value The element to insert at the end of the list. + * @returns The new length of the list. + **/ + push(value: T): number; + + /** + * Removes the first element from a list and returns it. + * @returns The first element from the list. + **/ + shift(): T; + + /** + * Appends new element(s) to a list, and returns the new length of the list. + * @param value The element to insert at the start of the list. + * @returns The new length of the list. + **/ + unshift(value: T): number; + + //#endregion Methods + } + + /** + * Represents a base class for list projections. + **/ + class ListProjection extends ListBaseWithMutators { + //#region Methods + + /** + * Disconnects a WinJS.Binding.List projection from its underlying WinJS.Binding.List. It's only important to call this method when the WinJS.Binding.List projection and the WinJS.Binding.List have different lifetimes. (Call this method on the WinJS.Binding.List projection, not the underlying WinJS.Binding.List.) + **/ + dispose(): void; + + /** + * Gets a key/data pair for the specified key. + * @param key The key of the value to retrieve. + * @returns An object with two properties: key and data. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Moves the value at index to position newIndex. + * @param index The original index of the value. + * @param newIndex The index of the value after the move. + **/ + move(index: number, newIndex: number): void; + + /** + * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the list from which to start removing elements. + * @param howMany The number of elements to remove. + * @param item The elements to insert into the list in place of the deleted elements. + * @returns The deleted elements. + **/ + splice(start: number, howMany?: number, ...item: T[]): T[]; + + //#endregion Methods + } + + /** + * Provides a standard implementation of the bindable contract, as well as a basic storage mechanism that participates in change notification and an asynchronous notification implementation. + **/ + var mixin: { + //#region Methods + + /** + * Adds a property to the object. The property includes change notification and an ECMAScript 5 property definition . + * @param name The name of the property to add. + * @param value The value of the property. + * @returns This object is returned. + **/ + addProperty(name: string, value: any): any; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns This object is returned. + **/ + bind(name: string, action: any): Function; + + /** + * Gets a property value by name. + * @param name The name of the property to get. + * @returns The value of the property as an observable object. + **/ + getProperty(name: string): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: string, oldValue: string): Promise; + + /** + * Removes a property value. + * @param name The name of the property to remove. + * @returns This object is returned. + **/ + removeProperty(name: string): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns This object is returned. + **/ + setProperty(name: string, value: any): any; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns A promise that completes when the notifications for this property change have been processed. If multiple notifications are coalesced, the promise may be canceled or the value of the promise may be updated. The fulfilled value of the promise is the new value of the property for which the notifications have been completed. + **/ + updateProperty(name: string, value: any): Promise; + + //#endregion Methods + + }; + + /** + * Provides functions that can make an object observable. + **/ + var observableMixin: { + //#region Methods + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns A reference to this observableMixin object. + **/ + bind(name: string, action: Function): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: any, oldValue: any): Promise; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + //#endregion Methods + + }; + + /** + * Do not instantiate. Returned by the createSorted method. + **/ + class SortedListProjection extends ListProjection { + //#region Methods + + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value to be replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the length of the list. Returns an integer value one higher than the highest element defined in a list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Provides a reusable declarative binding element. + **/ + class Template { + //#region Constructors + + /** + * Creates a template that provides a reusable declarative binding element. + * @constructor + * @param element The DOM element to convert to a template. + * @param options If this parameter is supplied, the template is loaded from the URI and the content of the element parameter is ignored. You can add the following options: href. + **/ + constructor(element: HTMLElement, options?: string); + + //#endregion Constructors + + //#region Methods + + render: { + /** + * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. + **/ + (dataContext: any, container?: HTMLElement): Promise; + + /** + * Renders a template based on the specified URI (static method). + * @param href The URI from which to load the template. + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. + **/ + value(href: string, dataContext: any, container?: HTMLElement): Promise; + }; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that is used as the template. + **/ + element: HTMLElement; + + //#endregion Properties + + } + + //#endregion Objects + + //#region Functions + + /** + * Returns an observable object. This may be an observable proxy for the specified object, an existing proxy, or the specified object itself if it directly supports observation. + * @param data The object to observe. + * @returns The observable object. + **/ + function as(data: U): U; + + /** + * Binds to one or more properties on the observable object or or on child values of that object. + * @param observable The object to bind to. + * @param bindingDescriptor An object literal containing the binding declarations. Binding declarations take the form: { propertyName: (function | bindingDeclaration), ... }. + * @returns An object that contains at least a "cancel" field, which is a function that removes all bindings associated with this bind request. + **/ + function bind(observable: any, bindingDescriptor: any): any; + + /** + * Creates a default binding initializer for binding between a source property and a destination property with the specified converter function that is executed on the value of the source property. + * @param convert The conversion function that takes the source property and produces a value that is set to the destination property. This function must be accessible from the global namespace. + * @returns The binding initializer. + **/ + function converter(convert: Function): Function; + + /** + * Creates a one-way binding between the source object and the destination object. Warning Do not attempt to bind data to the ID of an HTML element. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. + * @returns An object with a cancel method that is used to coalesce bindings. + **/ + function defaultBind(source: any, sourceProperties: any, dest: any, destProperties: any): any; + + /** + * Creates a new constructor function that supports observability with the specified set of properties. + * @param data The object to use as the pattern for defining the set of properties. + * @returns A constructor function with 1 optional argument that is the initial state of the properties. + **/ + function define(data: any): Function; + + /** + * Wraps the specified object so that all its properties are instrumented for binding. This is meant to be used in conjunction with the binding mixin. + * @param shape The specification for the bindable object. + * @returns An object with a set of properties all of which are wired for binding. + **/ + function expandProperties(shape: any): any; + + /** + * Marks a custom initializer function as being compatible with declarative data binding. + * @param customInitializer The custom initializer to be marked as compatible with declarative data binding. + * @returns The input customInitializer. + **/ + function initializer(customInitializer: Function): Function; + + /** + * Sets the destination property to the value of the source property. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. + * @returns An object with a cancel method that is used to coalesce bindings. + **/ + function oneTime(source: any, sourceProperties: any, dest: any, destProperties: any): any; + + /** + * Binds the values of an object to the values of a DOM element that has the data-win-bind attribute. If multiple DOM elements are to be bound, you must set the attribute on all of them. See the example below for details. + * @param rootElement Optional. The element at which to start traversing to find elements to bind to. If this parameter is omitted, the entire document is searched. + * @param dataContext The object that contains the values to which the DOM element should be bound. + * @param skipRoot If true, specifies that only the children of rootElement should be bound, otherwise rootElement should be bound as well. + * @param bindingCache The cached binding data. + * @param defaultInitializer The binding initializer to use in the case that one is not specified in a binding expression. If not provided, the behavior is the same as Binding.defaultBind. + * @returns A Promise that completes when every item that contains the data-win-bind attribute has been processed and the update has started. + **/ + function processAll(rootElement?: Element, dataContext?: any, skipRoot?: boolean, bindingCache?: any, defaultInitializer?: Function): Promise; + + /** + * Creates a one-way binding between the source object and an attribute on the destination element. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. This must be a single name. + * @returns An object with a cancel() method that is used to coalesce bindings. + **/ + function setAttribute(source: any, sourceProperties: any[], dest: Element, destProperties: any[]): any; + + /** + * Sets an attribute on the destination element to the value of the source property. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. This must be a single name. + **/ + function setAttributeOneTime(source: any, sourceProperties: any[], dest: Element, destProperties: any[]): void; + + /** + * Returns the original (non-observable) object is returned if the specified object is an observable proxy, + * @param data The object for which to retrieve the original value. + * @returns If the specified object is an observable proxy, the original object is returned, otherwise the same object is returned. + **/ + function unwrap(data: any): any; + + //#endregion Functions + + //#region Interfaces + + interface IKeyDataPair { + key: string; + data: T; + } + + //#endregion Interfaces + +} +/** + * Provides helper functions for defining Classes. +**/ +declare module WinJS.Class { + //#region Functions + + /** + * Defines a class using the given constructor and the specified instance members. + * @param constructor A constructor function that is used to instantiate this type. + * @param instanceMembers The set of instance fields, properties, and methods made available on the type. + * @param staticMembers The set of static fields, properties, and methods made available on the type. + * @returns The newly-defined type. + **/ + function define(constructor: Function, instanceMembers?: any, staticMembers?: any): any; + + /** + * Creates a sub-class based on the specified baseClass parameter, using prototype inheritance. + * @param baseClass The type to inherit from. + * @param constructor A constructor function that is used to instantiate this type. + * @param instanceMembers The set of instance fields, properties, and methods to be made available on the type. + * @param staticMembers The set of static fields, properties, and methods to be made available on the type. + * @returns The newly-defined type. + **/ + function derive(baseClass: any, constructor: Function, instanceMembers?: any, staticMembers?: any): any; + + /** + * Defines a class using the given constructor and the union of the set of instance members specified by all the mixin objects. The mixin parameter list is of variable length. For more information, see Adding functionality with WinJS mixins. + * @param constructor A constructor function that will be used to instantiate this class. + * @param mixin An object declaring the set of instance members. The mixin parameter list is of variable length. + * @returns The newly defined class. + **/ + function mix(constructor: Function, ...mixin: any[]): any; + + //#endregion Functions + +} +/** + * The WinJS namespace provides special Windows Library for JavaScript functionality, including Promise and xhr. +**/ +declare module WinJS { + //#region Properties + + /** + * Can be set to show the results of a validation process. + **/ + var validation: boolean; + + //#endregion Properties + + //#region Objects + + /** + * An error object. + **/ + class ErrorFromName { + //#region Constructors + + /** + * Creates an Error object with the specified name and message properties. + * @constructor + * @param name The name of this error. The name is meant to be consumed programmatically and should not be localized. + * @param message The message for this error. The message is meant to be consumed by humans and should be localized. + **/ + constructor(name: string, message?: string); + + //#endregion Constructors + + } + + /** + * Provides a mechanism to schedule work to be done on a value that has not yet been computed. It is an abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. + **/ + class Promise { + //#region Constructors + + /** + * A promise provides a mechanism to schedule work to be done on a value that has not yet been computed. It is a convenient abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. + * @constructor + * @param init The function that is called during construction of the Promise that contains the implementation of the operation that the Promise will represent. This can be synchronous or asynchronous, depending on the nature of the operation. Note that placing code within this function does not automatically run it asynchronously; that must be done explicitly with other asynchronous APIs such as setImmediate, setTimeout, requestAnimationFrame, and the Windows Runtime asynchronous APIs. The init function is given three arguments: completeDispatch, errorDispatch, progressDispatch. This parameter is optional. + * @param onCancel The function to call if a consumer of this promise wants to cancel its undone work. Promises are not required to support cancellation. + **/ + constructor(init?: (completeDispatch: any, errorDispatch: any, progressDispatch: any) => void, onCancel?: Function); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when there is an error in processing a promise. + * @param eventInfo An object that contains information about the event. + **/ + onerror(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener for the promise. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event is raised. + * @param capture true to initiate capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Returns a promise that is fulfilled when one of the input promises has been fulfilled. + * @param value An array that contains Promise objects or objects whose property values include Promise objects. + * @returns A promise that on fulfillment yields the value of the input (complete or error). + **/ + static any(value: Promise[]): Promise; + + /** + * Returns a promise. If the object is already a Promise it is returned; otherwise the object is wrapped in a Promise. You can use this function when you need to treat a non-Promise object like a Promise, for example when you are calling a function that expects a promise, but already have the value needed rather than needing to get it asynchronously. + * @param value The value to be treated as a Promise. + * @returns The promise. + **/ + static as(value: U): Promise; + + /** + * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). + **/ + cancel(): void; + + /** + * Raises an event of the specified type and properties. + * @param type The type (name) of the event. + * @param details The set of additional properties to be attached to the event object. + * @returns true if preventDefault was called on the event; otherwise, false. + **/ + dispatchEvent(type: string, details: any): boolean; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + **/ + done(onComplete?: (value: T) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): void; + + /** + * Determines whether a value fulfills the promise contract. + * @param value A value that may be a promise. + * @returns true if the object conforms to the promise contract (has a then function), otherwise false. + **/ + static is(value: any): boolean; + + /** + * Creates a Promise that is fulfilled when all the values are fulfilled. + * @param values An object whose members contain values, some of which may be promises. + * @returns A Promise whose value is an object with the same field names as those of the object in the values parameter, where each field value is the fulfilled value of a promise. + **/ + static join(values: any): Promise; + + /** + * Removes an event listener from the control. + * @param eventType The type (name) of the event. + * @param listener The listener to remove. + * @param capture Specifies whether or not to initiate capture. + **/ + removeEventListener(eventType: string, listener: Function, capture?: boolean): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => Promise, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => Promise, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + + /** + * Performs an operation on all the input promises and returns a promise that has the shape of the input and contains the result of the operation that has been performed on each input. + * @param values A set of values (which could be either an array or an object) of which some or all are promises.. + * @param complete The function to be called if the promise is fulfilled with a value. This function takes a single argument, which is the fulfilled value of the promise. + * @param error The function to be called if the promise is fulfilled with an error. This function takes a single argument, which is the error value of the promise. + * @param progress The function to be called if the promise reports progress. This function takes a single argument, which is the data about the progress of the promise. Promises are not required to support progress. + * @returns A Promise that is the result of calling join on the values parameter. + **/ + static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): Promise; + + /** + * This method has two forms: WinJS.Promise.timeout(timeout) and WinJS.Promise.timeout(timeout, promise). WinJS.Promise.timeout(timeout) creates a promise that is completed asynchronously after the specified timeout, essentially wrapping a call to setTimeout within a promise. WinJS.Promise.timeout(timeout, promise) sets a timeout period for completion of the specified promise, automatically canceling the promise if it is not completed within the timeout period. + * @param timeout The timeout period in milliseconds. If this value is zero or not specified, msSetImmediate is called, otherwise setTimeout is called. + * @param promise Optional. A promise that will be canceled if it doesn't complete within the timeout period. + * @returns If the promise parameter is omitted, returns a promise that will be fulfilled after the timeout period. If the promise paramater is provided, the same promise is returned. + **/ + static timeout(timeout: number, promise?: Promise): Promise; + + /** + * Wraps a non-promise value in a promise. This method is like wrapError, which allows you to produce a Promise in error conditions, in that it allows you to return a Promise in success conditions. + * @param value Some non-promise value to be wrapped in a promise. + * @returns A promise that is successfully fulfilled with the specified value. + **/ + static wrap(value: U): Promise; + + /** + * Wraps a non-promise error value in a promise. You can use this function if you need to pass an error to a function that requires a promise. + * @param error A non-promise error value to be wrapped in a promise. + * @returns A promise that is in an error state with the specified value. + **/ + static wrapError(error: U): Promise; + + //#endregion Methods + + } + + //#endregion Objects + + //#region Functions + + /** + * This method has been deprecated. Strict processing is always on; you don't have to call this method to turn it on. + **/ + function strictProcessing(): void; + + /** + * Wraps calls to XMLHttpRequest in a promise. + * @param options The options that are applied to the XMLHttpRequest object, as follows: type, url, user, password, responseType, headers, data, customRequestInitializer. + * @returns A promise that returns the XMLHttpRequest object when it completes. + **/ + function xhr(options: IXHROptions): Promise; + + //#endregion Functions + + //#region Interfaces + + interface IXHROptions { + type?: string; + url: string; + user?: string; + password?: string; + headers?: any; + data: any; + responseType?: string; + } + + //#endregion Interfaces +} +/** + * Provides helper functions for defining namespaces. For more information, see Organizing your code with WinJS.Namespace. +**/ +declare module WinJS.Namespace { + //#region Functions + + /** + * Defines a new namespace with the specified name. For more information, see Organizing your code with WinJS.Namespace. + * @param name The name of the namespace. This could be a dot-separated name for nested namespaces. + * @param members The members of the new namespace. + * @returns The newly-defined namespace. + **/ + function define(name?: string, members?: any): any; + + /** + * Defines a new namespace with the specified name under the specified parent namespace. For more information, see Organizing your code with WinJS.Namespace. + * @param parentNamespace The parent namespace. + * @param name The name of the new namespace. + * @param members The members of the new namespace. + * @returns The newly-defined namespace. + **/ + function defineWithParent(parentNamespace?: any, name?: string, members?: any): any; + + //#endregion Functions + +} +/** + * Provides functionality for dealing with basic navigation, including the navigation stack. +**/ +declare module WinJS.Navigation { + //#region Properties + + /** + * Determines whether it is possible to navigate backwards. + **/ + var canGoBack: boolean; + + /** + * Determines if it is possible to navigate forwards. + **/ + var canGoForward: boolean; + + /** + * Gets or sets the navigation history. + **/ + var history: any; + + /** + * Gets or sets the current location. + **/ + var location: string; + + /** + * Gets or sets a user-defined object that represents the state associated with the current location. + **/ + var state: any; + + //#endregion Properties + + //#region Functions + + /** + * Adds an event listener to the control. + * @param eventType The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param capture If true, specifies that capture should be initiated, otherwise false. + **/ + function addEventListener(eventType: string, listener: Function, capture?: boolean): void; + + /** + * Navigates backwards. + * @param distance The number of entries to go back into the history. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful. + **/ + function back(distance?: number): Promise; + + /** + * Navigates forwards. + * @param distance The number of entries to go forward. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful. + **/ + function forward(distance?: number): Promise; + + /** + * Navigates to a location. + * @param location The location to navigate to. Generally the location is a string containing the URL, but it may be anything. + * @param initialState A user-defined object that represents the navigation state that may be accessed through state. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful (true if successful, otherwise false). + **/ + function navigate(location: any, initialState?: any): Promise; + + /** + * Removes an event listener from the control. + * @param eventType The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture Specifies whether or not to initiate capture. + **/ + function removeEventListener(eventType: string, listener: Function, useCapture?: boolean): void; + + //#endregion Functions + + //#region Events + + /** + * Occurs before navigation. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onbeforenavigate(eventInfo: CustomEvent): void; + + /** + * Occurs after navigation has taken place. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onnavigated(eventInfo: CustomEvent): void; + + /** + * Occurs when navigation is taking place. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onnavigating(eventInfo: CustomEvent): void; + + //#endregion Events + +} +/** + * Provides functions for accessing resources and localizing content. +**/ +declare module WinJS.Resources { + //#region Functions + + /** + * Registers an event handler for the specified event. Use this method to register for events that are related to resources, such as when the app's language, scale, or contrast changes. + * @param type The name of the event to handle. + * @param listener The listener (event handler function) to associate with the event. + * @param useCapture Set to true to register the listener for the capturing phase; otherwise, set to false to register the listener for the bubbling phase. + **/ + function addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The name of the event to raise. + * @param details The set of additional properties to attach to the event object. + **/ + function dispatchEvent(type: string, details: any): void; + + /** + * Retrieves the resource string that has the specified resource identifier. + * @param resourceId The resource ID of the string to retrieve. + * @returns An object that can contain these properties: value, empty, lang. + **/ + function getString(resourceId: string): { value: string; empty?: boolean; lang?: string; }; + + /** + * Processes data-win-res attributes on elements and replaces attributes and properties with resource strings. + * @param rootElement The element to process. The element and its child elements will be processed. If an element isn't specified, the entire document is processed. + **/ + function processAll(rootElement?: HTMLElement): void; + + /** + * Removes an event listener that the addEventListener method registered. + * @param type The name of the event that the event listener is registered for. + * @param listener The listener (event handler function) to remove. + * @param useCapture Set to true to remove the capturing phase listener; set to false to remove the bubbling phase listener. + **/ + function removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Functions + + //#region Events + + /** + * Occurs when the user changes the system's language or contrast, or the scale of the display, or when the user changes any of the items in the current context's qualifier values list. For more info about the current context's qualifier values list, see the Remarks section. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.qualifier, detail.changed. + **/ + function oncontextchanged(eventInfo: CustomEvent): void; + + //#endregion Events + +} +/** + * Provides access to the Windows animations. These functions provide developers with the ability to use animations in their custom controls that are consistent with animations used by Windows controls. +**/ +declare module WinJS.UI.Animation { + //#region Functions + + /** + * Creates an object that performs an animation that adds an item or items to a list. + * @param added Element or elements to add to the list. + * @param affected Element or elements affected by the added items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createAddToListAnimation(added: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that adds an item or items to a list of search results. + * @param added Element or elements to add to the list. + * @param affected Element or elements affected by the added items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createAddToSearchListAnimation(added: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that collapses a list. + * @param hidden Element or elements hidden as a result of the collapse. + * @param affected Element or elements affected by the hidden items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createCollapseAnimation(hidden: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that removes an item or items from a list. + * @param deleted Element or elements to delete from the list. + * @param remaining Element or elements affected by the removal of the deleted items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createDeleteFromListAnimation(deleted: any, remaining: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that removes an item or items from a list of search results. + * @param deleted Element or elements to delete from the list. + * @param remaining Element or elements affected by the removal of the deleted items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createDeleteFromSearchListAnimation(deleted: any, remaining: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that expands a list. + * @param revealed Element or elements revealed by the expansion. + * @param affected Element or elements affected by the newly revealed items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createExpandAnimation(revealed: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs a peek animation. + * @param element Element or elements involved in the peek. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createPeekAnimation(element: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that moves an item or items. + * @param element Element or elements involved in the reposition. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise object that completes when the animation is finished. + **/ + function createRepositionAnimation(element: any): IAnimationMethodResponse; + + /** + * Performs an animation that fades an item or items in, fading out existing items that occupy the same space. + * @param incoming Element or elements being faded in. + * @param outgoing Element or elements being replaced. + * @returns An object that completes when the animation has finished. + **/ + function crossFade(incoming: any, outgoing: any): Promise; + + /** + * Performs an animation when a dragged object is moved such that dropping it in that position would move other items. The potentially affected items are animated out of the way to show where the object would be dropped. + * @param target Element or elements that the dragged object would cause to be moved if it were dropped. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function dragBetweenEnter(target: any, offset: any): Promise; + + /** + * Performs an animation when a dragged object is moved away from items that it had previously involved in a dragBetweenEnter animation. The affected objects are animated back to their original positions. + * @param target Element or elements that the dragged object would no longer cause to be displaced, due to its moving away. This should be the same element or element collection passed as the target parameter in the dragBetweenEnter animation. + * @returns An object that completes when the animation is finished. + **/ + function dragBetweenLeave(target: any): Promise; + + /** + * Performs an animation when the user finishes dragging an object. + * @param dragSource Element or elements that were dragged. + * @param offset Initial offset from the drop point. The dropped object begins at the offset and animates to its final position at the drop point. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param affected Element or elements whose position the dropped object affects. Typically, this is all other items in a reorderable list. This should be the same element or element collection passed as the affected parameter in the dragSourceStart animation. + * @returns An object that completes when the animation is finished. + **/ + function dragSourceEnd(dragSource: any, offset: any, affected?: any): Promise; + + /** + * Performs an animation when the user begins to drag an object. + * @param dragSource Element or elements being dragged. + * @param affected Element or elements whose position is affected by the movement of the dragged object. Typically, this is all other items in a reorderable list. + * @returns An object that completes when the animation is finished. + **/ + function dragSourceStart(dragSource: any, affected?: any): Promise; + + /** + * Performs an animation that displays one or more elements on a page. + * @param incoming Element or elements that compose the incoming content. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function enterContent(incoming: any, offset: any, options?: any): Promise; + + /** + * Performs an animation that shows a new page of content, either when transitioning between pages in a running app or when displaying the first content in a newly launched app. + * @param element Element or an array of elements that represent the content. If element refers to an array of elements, the elements enter in array order. + * @param offset An initial offset where the element or elements begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function enterPage(element: any, offset: any): Promise; + + /** + * Performs an animation that hides one or more elements on a page. + * @param outgoing Element or elements that compose the outgoing content. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function exitContent(outgoing: any, offset: any): Promise; + + /** + * Performs an animation that dismisses the current page when transitioning between pages in an app. + * @param outgoing Element or elements that compose the outgoing page. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function exitPage(outgoing: any, offset: any): Promise; + + /** + * Performs an animation that fades an item or set of items into view. + * @param shown Element or elements being faded in. + * @returns An object that completes when the animation has finished. Use this object when subsequent actions need this animation to finish before they take place. + **/ + function fadeIn(shown: any): Promise; + + /** + * Performs an animation that fades an item or set of items out of view. + * @param hidden Element or elements being faded out. + * @returns An object that completes when the animation is finished. + **/ + function fadeOut(hidden: any): Promise; + + /** + * Performs an animation that hides edge-based user interface (UI). + * @param element Element or elements that are being hidden. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function hideEdgeUI(element: any, offset: any, options?: any): Promise; + + /** + * Performs an animation that hides a panel. + * @param element Element or elements that are being hidden. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function hidePanel(element: any, offset: any): Promise; + + /** + * Performs an animation that removes pop-up user interface (UI). + * @param element Element or elements that are being hidden. + * @returns An object that completes when the animation is finished. + **/ + function hidePopup(element: any): Promise; + + /** + * Performs an animation when a pointer is pressed on an object. + * @param element Element or elements on which the pointer is pressed. + * @returns An object that completes when the animation is finished. + **/ + function pointerDown(element: any): Promise; + + /** + * Performs an animation when a pointer is released. + * @param element Element or elements that the pointer was pressed on. + * @returns An object that completes when the animation is finished. + **/ + function pointerUp(element: any): Promise; + + /** + * Performs an animation that slides a narrow, edge-based user interface (UI) into view. + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function showEdgeUI(element: any, offset: any, options?: any): Promise; + + /** + * Performs an animation that slides a large panel user interface (UI) into view. + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function showPanel(element: any, offset: any): Promise; + + /** + * Performs an animation that displays a pop-up user interface (UI). + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function showPopup(element: any, offset: any): Promise; + + /** + * Performs a deselection animation in response to a swipe interaction. + * @param deselected Element or elements that become unselected. + * @param selection Element or elements that represent the selection, typically a check mark. + * @returns An object that completes when the animation is finished. + **/ + function swipeDeselect(deselected: any, selection: any): Promise; + + /** + * Performs an animation that reveals an item or items in response to a swipe interaction. + * @param target Element or elements being revealed. + * @param offset An initial offset where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function swipeReveal(target: any, offset: any): Promise; + + /** + * Performs a selection animation in response to a swipe interaction. + * @param selected Element or elements being selected. + * @param selection Element or elements that show that something is selected, typically a check mark. + * @returns An object that completes when the animation is finished. + **/ + function swipeSelect(selected: any, selection: any): Promise; + + /** + * Performs an animation that updates a badge. + * @param incoming Element or elements that comprise the new badge. + * @param offset Initial offsets where incoming animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function updateBadge(incoming: any, offset: any): Promise; + + //#endregion Functions + + //#region Interfaces + + interface IAnimationMethodResponse { + execute(): Promise; + } + + //#endregion Interfaces + +} +/** + * Provides controls and objects that manipulate data. +**/ +declare module WinJS.UI { + //#region Enumerations + + /** + * Specifies an icon that appears in an AppBarCommand object. + **/ + enum AppBarIcon { + previous, + next, + play, + pause, + edit, + save, + clear, + delete, + remove, + add, + cancel, + accept, + more, + redo, + undo, + home, + up, + forward, + right, + back, + left, + favorite, + camera, + settings, + video, + sync, + download, + mail, + find, + help, + upload, + emoji, + twopage, + leavechat, + mailforward, + clock, + send, + crop, + rotatecamera, + people, + closepane, + openpane, + world, + flag, + previewlink, + globe, + trim, + attachcamera, + zoomin, + bookmarks, + document, + protecteddocument, + page, + bullets, + comment, + mail2, + contactinfo, + hangup, + viewall, + mappin, + phone, + videochat, + switch, + contact, + rename, + pin, + musicinfo, + go, + keyboard, + dockleft, + dockright, + dockbottom, + remote, + refresh, + rotate, + shuffle, + list, + shop, + selectall, + orientation, + import, + importall, + browsephotos, + webcam, + pictures, + savelocal, + caption, + stop, + showresults, + volume, + repair, + message, + page2, + calendarday, + calendarweek, + calendar, + characters, + mailreplyall, + read, + link, + accounts, + showbcc, + hidebcc, + cut, + attach, + paste, + filter, + copy, + emoji2, + important, + mailreply, + slideshow, + sort, + manage, + allapps, + disconnectdrive, + mapdrive, + newwindow, + openwith, + contactpresence, + priority, + uploadskydrive, + gototoday, + font, + fontcolor, + contact2, + folder, + audio, + placeholder, + view, + setlockscreen, + settile, + cc, + stopslideshow, + permissions, + highlight, + disableupdates, + unfavorite, + unpin, + openlocal, + mute, + italic, + underline, + bold, + movetofolder, + likedislike, + dislike, + like, + alignright, + aligncenter, + alignleft, + zoom, + zoomout, + openfile, + otheruser, + admin, + street, + map, + clearselection, + fontdecrease, + fontincrease, + fontsize, + cellphone, + reshare, + tag, + repeatone, + repeatall, + outlinestar, + solidstar, + calculator, + directions, + target, + library, + phonebook, + memo, + microphone, + postupdate, + backtowindow, + fullscreen, + newfolder, + calendarreply, + unsyncfolder, + reporthacked, + syncfolder, + blockcontact, + switchapps, + addfriend, + touchpointer, + gotostart, + zerobars, + onebar, + twobars, + threebars, + fourbars, + scan, + preview + } + + /** + * Indicates whether the IListDataAdapter was able to provide a count. + **/ + enum CountResult { + /** + * Indicates no count is available. + **/ + unknown + } + + /** + * Indicates that the IListDataAdapter was unable to provide a count. + **/ + enum CountError { + /** + * An attempt to count items timed out. + **/ + noResponse + } + + /** + * Describes the status of an IListDataSource. + **/ + enum DataSourceStatus { + /** + * The IListDataSource is ready. + **/ + ready, + /** + * The IListDataSource is still loading. + **/ + waiting, + /** + * The IListDataSource failed to load. + **/ + failure + } + + /** + * Specifies the type of error that occurred during an edit operation on a IListDataSource or an IListDataAdapter. + **/ + enum EditError { + /** + * The edit operation timed out. + **/ + noResponse, + /** + * The data source cannot be written to. + **/ + notPermitted, + /** + * The item has changed. + **/ + noLongerMeaningful + } + + /** + * Specifies the type of error encountered when retrieving items from an IListDataAdapter. + **/ + enum FetchError { + /** + * The fetch operation timed out. + **/ + noResponse, + /** + * The specified item could not be located. + **/ + doesNotExist + } + + /** + * Specifies the position of group headers relative to their items in a ListView. + **/ + enum HeaderPosition { + /** + * Group headers appear to the left of items. + **/ + left, + /** + * Group headers appear above items. + **/ + top + } + + /** + * Specifies that type of animation for which a contentanimating event was raised. + **/ + enum ListViewAnimationType { + /** + * The animation plays when the ListView is first displayed. + **/ + entrance, + /** + * The animation plays when the ListView is changing its content. + **/ + contentTransition + } + + /** + * Specifies the selection mode of a ListView. + **/ + enum SelectionMode { + /** + * Items cannot be selected. + **/ + none, + /** + * A single item may be selected. + **/ + single, + /** + * Multiple items may be selected. Clicking additional items adds them to the selection. + **/ + multi + } + + /** + * Specifies whether elements are selected when the user performs a swipe interaction. + **/ + enum SwipeBehavior { + /** + * The swipe interaction selects the elements touched by the swipe. + **/ + select, + /** + * The swipe interaction does not change which elements are selected. + **/ + none + } + + /** + * Specifies how items in a ListView respond to the tap interaction. + **/ + enum TapBehavior { + /** + * The item is selected and invoked. + **/ + directSelect, + /** + * The item is selected if was not already selected, and its deselected if it was already selected. + **/ + toggleSelect, + /** + * The item is invoked but not selected. + **/ + invokeOnly, + /** + * Nothing happens. + **/ + none + } + + //#endregion Enumerations + + //#region Interfaces + + /** + * Contains items that were requested from an IListDataAdapter and provides some information about those items. + **/ + interface IFetchResult { + //#region Properties + + /** + * Gets or sets the index of the requested item in the IListDataAdapter object's data source. + **/ + absoluteIndex: number; + + /** + * Gets or sets a value that indicates whether this IFetchResult contains the last items at the end of the IListDataAdapter object's data source. + **/ + atEnd: boolean; + + /** + * Gets or sets a value that indicates whether this IFetchResult contains the first items at the beginning of the IListDataAdapter object's data source. + **/ + atStart: boolean; + + /** + * Gets or sets the items returned by the fetch operation. + **/ + items: T[]; + + /** + * Gets or sets the location of the requested item within the items array. + **/ + offset: number; + + /** + * Gets or sets the number of items in the IListDataAdapter object's underlying data source. + **/ + totalCount: number; + + //#endregion Properties + + } + + /** + * Represents an item in a list. + **/ + interface IItem { + //#region Properties + + /** + * Gets or sets the item's data. + **/ + data: T; + + /** + * Gets the group key for the item. This property is only available for items that belong to a grouped data source. + **/ + groupKey: string; + + /** + * Gets the temporary ID of the item. + **/ + handle: string; + + /** + * Gets the item's index in the IListDataSource. + **/ + index: number; + + /** + * Gets or sets the key the identifies the item. + **/ + key: string; + + //#endregion Properties + + } + + /** + * Provides a mechanism for retrieving IItem objects asynchronously. + **/ + interface IItemPromise { + //#region Events + + /** + * Occurs when there is an error in processing. + * @param eventInfo An object that contains information about the event. + **/ + onerror(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). + **/ + cancel(): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + **/ + done(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): void; + + /** + * Stops change notification tracking for the IItem that fulfills this IItemPromise. + **/ + release(): void; + + /** + * Begins change notification tracking for the IItem that fulfills this IItemPromise. + **/ + retain(): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function becomes the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the complete or error function. + **/ + then(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): IItemPromise; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the temporary ID of the IItem that fulfills this promise. + **/ + handle: string; + + /** + * Gets or sets the index of the IItem contained by this IItemPromise. + **/ + index: number; + + //#endregion Properties + + } + + /** + * Represents a layout for the ListView. + **/ + interface ILayout { + //#region Methods + + /** + * Calculates the index of the first visible item. + * @param beginScrollPosition The first visible pixel in the ListView. For horizontal layouts, this is the x-coordinate of the pixel. For vertical layouts, this is the y-coordinate. + * @param wholeItem true if the item must be completely visible; otherwise, false if its ok for the item to be partially visible. Promise. + * @returns A Promise for the index of the first visible item at the specified point. + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): Promise; + + /** + * Calculates the index of the last visible item. + * @param endScrollPosition The last visible pixel in the ListView. For horizontal layouts, this is the x-coordinate of the pixel. For vertical layouts, this is the y-coordinate. + * @param wholeItem true if the item must be completely visible; otherwise, false if its ok for the item to be partially visible. Promise. + * @returns A Promise for the index of the last visible item at the specified point. + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): Promise; + + /** + * Ends the layout process. + * @returns A object that has these properties: animationPromise, newEndIndex. + **/ + endLayout(): any; + + /** + * Calculates the dimensions of an item. + * @param itemIndex The index of the item. + * @returns A Promise that returns an object with these properties: left, top, contentWidth, contentHeight, totalWidth, totalHeight. + **/ + getItemPosition(itemIndex: number): Promise; + + /** + * Gets the index of the next item relatively to the supplied index and keypress. + * @param itemIndex The data source index of the current item. + * @param element The element for the current item. + * @param keyPressed The key that was pressed. This function must check for the arrow keys (leftArrow, upArrow, rightArrow, downArrow), pageDown, and pageUp and determine which item the user navigated to. + * @returns A Promise that contains the index of the next item (This item becomes the current item). + **/ + getKeyboardNavigatedItem(itemIndex: number, element: HTMLElement, keyPressed: WinJS.Utilities.Key): Promise; + + /** + * Gets the scrollbar range. + * @returns A Promise that returns an object that has these properties: beginScrollPosition, endScrollPosition. + **/ + getScrollBarRange(): Promise; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate to test. + * @param y The y-coordinate to test. + **/ + hitTest(x: number, y: number): void; + + /** + * Notifies of items being added. + * @param elements The elements that represent the items that were added. + **/ + itemsAdded(elements: HTMLElement[]): void; + + /** + * Notifies of items being moved. + **/ + itemsMoved(): void; + + /** + * Notifies of items being removed. + * @param elements The elements that represent the items that were removed. + **/ + itemsRemoved(elements: HTMLElement[]): void; + + /** + * Lays out the specified header at the specified index. + * @param groupIndex The index of the group in the group data source. + * @param element The element to render for the group header. + **/ + layoutHeader(groupIndex: number, element: HTMLElement): void; + + /** + * Lays out the specified item at the speficied index. + * @param itemIndex The index of the item in the data source. + * @param element The element to render for the item. + **/ + layoutItem(itemIndex: number, element: HTMLElement): void; + + /** + * Prepares the header element. + * @param element The element that represents a header in the data source. + **/ + prepareHeader(element: HTMLElement): void; + + /** + * Prepares the item element. + * @param element An element that represents an item in the data source. + **/ + prepareItem(element: HTMLElement): void; + + /** + * Releases the item. + * @param element The element being released. + **/ + releaseItem(element: HTMLElement): void; + + /** + * Resets the layout. + **/ + reset(): void; + + /** + * Sets the ILayoutSite object. + * @param site The layout site for the layout. You can use this object to query the hosting ListView for info you might need to lay out items. + **/ + setSite(site: ILayoutSite): void; + + /** + * Starts the layout. + * @param beginScrollPosition The starting pixel of the area to which the items are rendered. + * @param endScrollPosition The last pixel of the area to which the items are rendered. + * @param count The upper bound of the number of items to render. + * @returns A Promise that returns an object that has these properties: beginIndex, endIndex. + **/ + startLayout(beginScrollPosition: number, endScrollPosition: number, count: number): Promise; + + //#endregion Methods + + //#region Properties + + /** + * A flag indicating whether the direction of this layout implementation is horizontal. + **/ + horizontal: boolean; + + //#endregion Properties + + } + + /** + * Represents a rendering site for an ILayout. + **/ + interface ILayoutSite { + //#region Properties + + /** + * Gets or sets whether animations are disabled. + **/ + animationsDisabled: boolean; + + /** + * Gets the item surface element. + **/ + itemSurface: HTMLElement; + + /** + * Gets or sets whether this layout is in RTL mode. + **/ + rtl: boolean; + + /** + * Gets or sets the scrollbar position. + **/ + scrollbarPos: number; + + /** + * Gets the surface element. + **/ + surface: HTMLElement; + + /** + * Gets the viewport element. + **/ + viewport: HTMLElement; + + /** + * Gets the viewport size. + **/ + viewportSize: any; + + //#endregion Properties + + } + + /** + * Retrieves items from a IListDataSource, enumerates the contents of a IListDataSource, and can optionally register for change notifications. + **/ + interface IListBinding { + //#region Methods + + /** + * Retrieves the current item. + * @returns An IItemPromise that contains the current item. If the cursor has moved past the start or end of the list, the promise completes with a value of null. If the current item has been moved or deleted, the promise returns an error. + **/ + current(): IItemPromise>; + + /** + * Gets the first item from the IListDataSource and makes it the current item. + * @returns An IItemPromise that contains the requested IItem. If the list is empty, the promise completes with a value of null. + **/ + first(): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified description and makes it the current item. + * @param description A domain-specific description, to be interpreted by the IListDataAdapter, that identifies the item to retrieve. + * @returns An IItemPromise that contains the requested IItem object. If the item wasn't found, the promise completes with a value of null. + **/ + fromDescription(description: string): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified index and makes it the current item. + * @param index A value greater than or equal to 0 that is the index of the item to retrieve. + * @returns An IItemPromise that contains the requested IItem. If the item wasn't found, the promise completes with a value of null. + **/ + fromIndex(index: number): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified key and makes it the current item. + * @param key The key that identifies the item to retrieve. This value must be a non-empty string. + * @param hints Domain-specific information that provides additional information to the IListDataAdapter to improve retrieval time. + * @returns An IItemPromise that contains the requested IItem. If they item couldn't be found, the promise completes with a value of null. + **/ + fromKey(key: string, hints?: any): IItemPromise>; + + /** + * Makes the specified IItem or IItemPromise the current item. + * @param item The IItem or IItemPromise that will become the current item. + * @returns An IItemPromise that contains the specified item, if it exists. If the specified item is not in the list, the promise completes with a value of null. + **/ + jumpToItem(item: IItem): IItemPromise>; + + /** + * Retrieves the last item in the IListDataSource and makes it the current item. + * @returns An IItemPromise that contains the requested IItem. f the list is empty, the promise completes with a value of null. + **/ + last(): IItemPromise>; + + /** + * Retrieves the item after the current item and makes it the current item. + * @returns An IItemPromise that contains the item after the current item. If the cursor moves past the end of the list, the promise completes with a value of null. + **/ + next(): IItemPromise>; + + /** + * Retrieves the item before the current item and makes it the current item. + * @returns An IItemPromise that contains the item before the current item. If the cursor moves past the start of the list, the promise completes with a value of null. + **/ + previous(): IItemPromise>; + + /** + * Releases resources, stops notifications, and cancels outstanding promises for all tracked items returned by this IListBinding. + **/ + release(): void; + + /** + * Creates a request to stop change notifications for the specified item. The change notifications stop when the number of releaseItem calls matches the number of IIItemPromise.retain calls. + * @param item The IItem or IItemPromise that should stop receiving notifications. + **/ + releaseItem(item: IItem): void; + + //#endregion Methods + + } + + /** + * Accesses data for an IListDataSource. + **/ + interface IListDataAdapter { + //#region Methods + + /** + * Overwrites the data of the specified item. + * @param key The key of the item to overwrite. + * @param newData The new data for the item. + * @param indexHint The index of the item, if known. + * @returns A Promise that returns null or undefined when the operation completes. + **/ + change(key: string, newData: T, indexHint: number): Promise; + + /** + * Gets the number of items in the IListDataAdapter object's data source. + * @returns A Promise that contains the number of items the IListDataAdapter contains, or an approximate value if the actual number is unknown. + **/ + getCount(): Promise; + + /** + * Inserts the specified data after the specified item. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @param previousKey The key of an item in the IListDataAdapter object's data source. The new data will be inserted after this item. + * @param previousIndexHint The index of the item to insert the new data after, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAfter(key: string, data: T, previousKey: string, previousIndexHint: number): Promise>; + + /** + * Adds the specified key and data to the end of the IListDataAdapter object's data source. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtEnd(key: string, data: T): Promise>; + + /** + * Adds the specified key and data to the beginning of the IListDataAdapter object's data source. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtStart(key: string, data: T): Promise>; + + /** + * Inserts the specified data before the specified item. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @param nextKey The key of an item in the IListDataAdapter object's data source. The new data will be inserted before this item. + * @param nextIndexHint The index of the item to insert the new data before, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertBefore(key: string, data: T, nextKey: string, nextIndexHint: number): Promise>; + + /** + * Retrieves the item that matches the specified description and also retrieves the specified number of items before and after the matched item. + * @param description A description of the item to locate. + * @param countBefore The number of items before the matched item to retrieve. + * @param countAfter The number of items after the matched item to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromDescription(description: string, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the specified number of items from the end of the IListDataAdapter object's data source. + * @param count The number of items to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromEnd(count: number): Promise>; + + /** + * Retrieves the item at the specified index and also retrieves the specified number of items before and after the selected item. + * @param index The index of the item to retrieve. + * @param countBefore The number of items to retrieve from before the selected item. + * @param countAfter The number of items to retrieve from after the selected item. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromIndex(index: number, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the item that has the specified key and also retrieves the specified number of items before and after the selected item. + * @param key The key of the item to retrieve. + * @param countBefore The number of items to retrieve from before the selected item. + * @param countAfter The number of items to retrieve from after the selected item. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromKey(key: string, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the specified number of items from the beginning of the IListDataAdapter object's data source. + * @param count The number of items to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromStart(count: number): Promise>; + + /** + * Returns a string representation of the specified item that can be used for comparisons. + * @param item The item for which to generate a signature. + * @returns The signature representation of the specified item. + **/ + itemSignature(item: IItem): string; + + /** + * Moves the specified item to just after another item. + * @param key A key of the item to move. + * @param previousKey The key of another item. The item to move will be moved to just after this item. + * @param indexHint The index of the item to move, if known. + * @param previousIndexHint The index to move the item after, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveAfter(key: string, previousKey: any, indexHint: string, previousIndexHint: number): Promise>; + + /** + * Moves the specified item to just before another item. + * @param key A key of the item to move. + * @param nextKey The key of another item. The item to move will be moved to just before this item. + * @param indexHint The index of the item to move, if known. + * @param nextIndexHint The index to move the item before, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveBefore(key: string, nextKey: any, indexHint: string, nextIndexHint: number): Promise>; + + /** + * Moves the specified item to the end of the IListDataAdapter object's data source. + * @param key The key for the item to move. + * @param indexHint The index of the item to move, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveToEnd(key: string, indexHint: number): Promise>; + + /** + * Moves the specified item to the beginning of the IListDataAdapter object's data source. + * @param key The key for the item to move. + * @param indexHint The index of the item to move, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveToStart(key: string, indexHint: number): Promise>; + + /** + * Removes the specified item from the IListDataAdapter object's data source. + * @param key The key of the item to remove. + * @param data The new data for the item. + * @param indexHint The index of the item. + * @returns A Promise that returns null or undefined when the operation completes. + **/ + remove(key: string, data: T, indexHint: number): Promise; + + /** + * Registers a notification handler. The IListDataAdapter uses the handler to notify listening objects when its data changes. + * @param notificationHandler The notification handler that the IListDataAdapter will use to provide change notifications. . + **/ + setNotificationHandler(notificationHandler: IListDataNotificationHandler): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether to use an object's identity to determine if an item has changed. + **/ + compareByIdentity: boolean; + + //#endregion Properties + + } + + /** + * Notifies clients when an IListDataAdapter object's data changes. + **/ + interface IListDataNotificationHandler { + //#region Methods + + /** + * Indicates the start of a notification batch. Objects that are listening for notifications should defer making updates until endNotifications is called. + **/ + beginNotifications(): void; + + /** + * Raises a notification that an item in the IListDataAdapter object's data source has changed. + * @param item The item that changed. + **/ + changed(item: IItem): void; + + /** + * Indicates the end of a notification batch. When the beginNotifications method is called, objects listening for notifications should defer making updates until endNotifications is called. + **/ + endNotifications(): void; + + /** + * Raises a notification that an item has been added to the IListDataAdapter object's data source. + * @param newItem The new item added to the IListDataAdapter object's data source. + * @param previousKey The key of the item that now precedes the new item, or null if the item was inserted at the start of the list. If nextKey is provided, this parameter may be null. + * @param nextKey The key of the item that now follows the new item, or null if the item was inserted at the end of the list. If previousKey is provided, this parameter may be null. + * @param index The index of the new item. + **/ + inserted(newItem: IItem, previousKey: string, nextKey: string, index?: number): void; + + /** + * Indicates that all previous data obtained from the IListDataAdapter is invalid and should be refreshed. + * @returns A Promise that completes when the data has been completely refreshed and all change notifications have been sent. + **/ + invalidateAll(): Promise; + + /** + * Raises a notification that an item was moved within the IListDataAdapter object's data source. + * @param item The item that was moved. + * @param previousKey The key of the item that now precedes the new item, or null if the item was moved to the beginning of the list. If nextKey is provided, this parameter may be null. + * @param nextKey The key of the item that now follows the new item, or null if the item was moved to the end of the list. If previousKey is provided, this parameter may be null. + * @param oldIndex The item's original index. + * @param newIndex The item's new index. + **/ + moved(item: IItem, previousKey: string, nextKey: string, oldIndex?: number, newIndex?: number): void; + + /** + * Reloads data from the IListDataAdapter. + **/ + reload(): void; + + /** + * Raises a notification that an item was removed from the IListDataAdapter object's data source. + * @param key The key of the item that was removed. + * @param index The index of the item that was removed. + **/ + removed(key: string, index?: number): void; + + //#endregion Methods + + } + + /** + * Provides access to a data source and enables you to bind, change, add, remove, and move items in that data source. + **/ + interface IListDataSource { + //#region Events + + /** + * Occurs when the status of the IListDataSource changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: status. + **/ + statuschanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Notifies the IListDataSource that a sequence of edits is about to begin. The IListDataSource will defer notifications until endEdits is called. + **/ + beginEdits(): void; + + /** + * Overwrites the data of the specified item. + * @param key The key for the item to replace. + * @param newData The new data for the item. + * @returns A Promise that contains the IItem that was updated or an EditError if an error was encountered. + **/ + change(key: string, newData: T): Promise>; + + /** + * Creates an IListBinding that can retrieve items from the IListDataSource, enumerate the contents of the IListDataSource object's data, and optionally register for change notifications. + * @param notificationHandler Enables the IListBinding to register for change notifications for individual items obtained from the IListDataSource. If you omit this parameter, change notifications won't be available. + * @returns The new IListBinding. + **/ + createListBinding(notificationHandler?: IListNotificationHandler): IListBinding; + + /** + * Notifies the IListDataSource that the batch of edits that began with the last beginEdits call has completed. The IListDataSource will submit notifications for any changes that occurred between the beginEdits and endEdits calls as a batch and resume normal change notifications. + **/ + endEdits(): void; + + /** + * Retrieves the number of items in the data source. + * @returns A Promise that provides a Number that is the number of items in the data source. + **/ + getCount(): Promise; + + /** + * Inserts a new item after another item. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @param previousKey The key for an item in the data source. The new item will be added after this item. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAfter(key: string, data: T, previousKey: string): Promise>; + + /** + * Adds an item to the end of the data source. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtEnd(key: string, data: T): Promise>; + + /** + * Adds an item to the beginning of the data source. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtStart(key: string, data: T): Promise>; + + /** + * Inserts an item before another item. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @param nextKey The key of an item in the data source. The new item will be inserted before this item. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertBefore(key: string, data: T, nextKey: string): Promise>; + + /** + * Indicates that all previous data obtained from the IListDataAdapter is invalid and should be refreshed. + * @returns A Promise that completes when the data has been completely refreshed and all notifications have been sent. + **/ + invalidateAll(): Promise; + + /** + * Retrieves the item that has the specified description. + * @param description Domain-specific information, to be interpreted by the IListDataAdapter, that describes the item to retrieve. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item wasn't found, the promise completes with a value of null. + **/ + itemFromDescription(description: any): Promise>; + + /** + * Retrieves the item at the specified index. + * @param index A value that is greater than or equal to zero that is the index of the item to retrieve. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item wasn't found, the promise completes with a value of null. + **/ + itemFromIndex(index: number): Promise>; + + /** + * Retrieves the item with the specified key. + * @param key The key of the item to retrieve. It must be a non-empty string. + * @param description Domain-specific information that IListDataAdapter can use to improve the retrieval time. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item was not found, the promise completes with a null value. + **/ + itemFromKey(key: string, description?: any): Promise>; + + /** + * Moves an item to just after another item. + * @param key The key that identifies the item to move. + * @param previousKey The key of another item in the data source. The item specified by the key parameter will be moved after this item. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveAfter(key: string, previousKey: string): Promise>; + + /** + * Moves an item before another item. + * @param key The key that identifies the item to move. + * @param nextKey The key of another item in the data source. The item specified by the key parameter will be moved before this item. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveBefore(key: string, nextKey: string): Promise>; + + /** + * Moves an item to the end of the data source. + * @param key The key that identifies the item to move. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveToEnd(key: string): Promise>; + + /** + * Moves the specified item to the beginning of the data source. + * @param key The key that identifies the item to move. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveToStart(key: string): Promise>; + + /** + * Removes the specified item from the data source. + * @param key The key that identifies the item to remove. + * @returns A Promise that contains nothing if the operation was successful or an EditError if an error was encountered. + **/ + remove(key: string): Promise>; + + //#endregion Methods + + } + + /** + * Used by an IListBinding to provide change notifications when items in a IListDataSource change. + **/ + interface IListNotificationHandler { + //#region Methods + + /** + * Indicates the start of a notification batch. Objects that are listening for notifications should defer making updates until endNotifications is called. + **/ + beginNotifications(): void; + + /** + * Indicates that an item changed. + * @param newItem The updated item. + * @param oldItem The original item. + **/ + changed(newItem: IItem, oldItem: IItem): void; + + /** + * Indicates that the number of items in the IListDataSource has changed. + * @param newCount The updated count. + * @param oldCount The original count. + **/ + countChanged(newCount: number, oldCount: number): void; + + /** + * Indicates the end of a notification batch. When the beginNotifications method is called, objects listening for notifications should defer making updates until endNotifications is called. + **/ + endNotifications(): void; + + /** + * Indicates that the index of an item changed. + * @param handle The temporary ID of the item. + * @param newIndex The new index. + * @param oldIndex The original index. + **/ + indexChanged(handle: string, newIndex: number, oldIndex: number): void; + + /** + * Indicates that an item was added to the IListDataSource. + * @param itemPromise A promise for the new IItem. + * @param previousHandle The temporary ID of the item that precedes the new item. + * @param nextHandle The temporary ID of the item that follows the new item. + **/ + inserted(itemPromise: IItemPromise, previousHandle: string, nextHandle: string): void; + + /** + * Indicates that an IItemPromise was fulfilled and that the item is now available. + * @param item The fulfilled item. + **/ + itemAvailable(item: IItem): void; + + /** + * Indicates that an item was moved. + * @param item A promise for the IItem that was moved. + * @param previousHandle The temporary ID of the item that now precedes the moved item. + * @param nextHandle The temporary ID of the item that now follows the moved item. + **/ + moved(item: IItemPromise, previousHandle: string, nextHandle: string): void; + + /** + * Indicates that an item was removed. + * @param handle The temporary ID of the item that was removed. + * @param mirage true if the item never actually existed; false if the item was actually present in the IListDataSource. + **/ + removed(handle: string, mirage: boolean): void; + + //#endregion Methods + + } + + /** + * Used by ListView's currentItem API + **/ + interface IListViewItem { + /** + * Gets or sets index of the ListView item. + **/ + index?: number; + + /** + * Gets or sets key of the ListView item. + **/ + key?: string; + + /** + * Gets or sets whether the ListView item is focused. + **/ + hasFocus?: boolean; + + /** + * Gets or sets whether the ListView item is focused and is showing its focus visual. + **/ + showFocus?: boolean; + } + + /** + * Represents a selection of ListView items. + **/ + interface ISelection { + //#region Methods + + /** + * Adds one or more items to the selection. + * @param items The indexes or keys of the items to add. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + add(items: any): Promise; + + /** + * Clears the selection. + * @returns A Promise that is fulfilled when the clear operation completes. + **/ + clear(): Promise; + + /** + * Returns the number of items in the selection. + * @returns The number of items in the selection. + **/ + count(): number; + + /** + * Returns a list of the indexes for the items in the selection. + * @returns The list of indexes for the items in the selection as an array of Number objects. + **/ + getIndices(): number[]; + + /** + * Returns an array that contains the items in the selection. + * @returns A Promise that contains an array of the requested IItem objects. + **/ + getItems(): Promise[]>; + + /** + * Gets an array of the index ranges for the selected items. + * @returns An array that contains an ISelectionRange object for each index range in the selection. + **/ + getRanges(): ISelectionRange[]; + + /** + * Returns a value that indicates whether the selection contains every item in the data source. + * @returns true if the selection contains every item in the data source; otherwise, false. + **/ + isEverything(): boolean; + + /** + * Removes the specified items from the selection. + * @param items The indexes or keys of the items to remove. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + remove(items: any): Promise; + + /** + * Adds all the items in the ListView to the selection. + **/ + selectAll(): void; + + /** + * Clears the current selection and replaces it with the specified items. + * @param items The indexes or keys of the items that make up the selection. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + set(items: any): Promise; + + //#endregion Methods + + } + + /** + * Represents a range of indexes or keys in an ISelection. + **/ + interface ISelectionRange { + //#region Properties + + /** + * Gets or sets the index of the first item in the range. + **/ + firstIndex: number; + + /** + * Gets or sets the key of the first item in the range. + **/ + firstKey: any; + + /** + * Gets or sets the index of the last item in the range. + **/ + lastIndex: number; + + /** + * Gets or sets of the key of the last item in the range. + **/ + lastKey: any; + + //#endregion Properties + + } + + /** + * Supports semantic zoom functionality by exposing a control as either the zoomed in or the zoomed out view of the SemanticZoom control. + **/ + interface IZoomableView { + //#region Methods + + /** + * Initiates semantic zoom on the custom control. + **/ + beginZoom(): void; + + /** + * Initializes the semantic zoom state for the custom control. + * @param isZoomedOut True if this is the zoomed out view; otherwise false. + * @param isCurrentView True if this is the current view; otherwise false. + * @param triggerZoom The function that manages semantic zoom behavior. Triggers a zoom in or zoom out if the control is the visible control. + * @param prefetchedPages The number of pages of content to pre-fetch for zooming. This value is dependent on the size of the semantic zoom container. More content can be displayed based on the zoom factor and the size of the container. + **/ + configureForZoom(isZoomedOut: boolean, isCurrentView: boolean, triggerZoom: Function, prefetchedPages: number): void; + + /** + * Terminates semantic zoom on the zoomed in or zoomed out child of the custom control. + * @param isCurrentView True if the control is the visible control; otherwise false. + **/ + endZoom(isCurrentView: boolean): void; + + /** + * Retrieves the current item of the zoomed in or zoomed out child of the custom control. + * @returns An object that represents the selected item. This return value must be a Promise for the following: item, position. + **/ + getCurrentItem(): Promise<{ item: T; position: Utilities.IPosition }>; + + /** + * Retrieves the panning axis of the zoomed-in or zoomed-out child of the custom control. + * @returns Identifies the panning axis of the child control. Implementation specific. + **/ + getPanAxis(): string; + + /** + * Positions the specified item within the viewport of the child control when panning or zooming begins. + * @param item The object to position within the viewport of the child control. item can be a number, a string, or an object with any number of properties. + * @param position An object that contains the position data of the item relative to the child control. position must be an object with four number properties: left, top, width, and height. These values specify a rectangle that is typically the bounding box of the current item, though the details are up to the control. The units of the position must be in pixels. And the coordinates must be relative to the top-left of the control viewport (which should occupy the same area as the semantic zoom viewport), except when in RTL mode. In RTL mode, return coordinates relative to the top-right off the control viewport. The rectangle is transformed from the coordinate system of one control to that of the other. + **/ + positionItem(item: T, position: Utilities.IPosition): void; + + /** + * Selects the item closest to the specified screen coordinates. + * @param x The x-coordinate in DIPs relative to the upper-left corner of the SemanticZoom viewport. + * @param y The y-coordinate in DIPs relative to the upper-left corner of the SemanticZoom viewport.. + **/ + setCurrentItem(x: number, y: number): void; + + //#endregion Methods + + } + + //#endregion Interfaces + + //#region Objects + + /** + * Represents an application toolbar for displaying commands. + **/ + class AppBar { + //#region Constructors + + /** + * Creates a new AppBar object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new AppBar. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs immediately after the AppBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Occurs after the AppBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Occurs before the AppBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Occurs before a hidden AppBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Returns the AppBarCommand object identified by id. + * @param id The element idenitifier (ID) of the command to be returned. + * @returns The command identified by id. If multiple commands have the same ID, returns an array of all the commands matching the ID. + **/ + getCommandById(id: string): AppBarCommand; + + /** + * Hides the AppBar. + **/ + hide(): void; + + /** + * Hides the specified commands of the AppBar. + * @param commands The commands to hide. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. + **/ + hideCommands(commands: any[], immediate?: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the AppBar if it is not disabled. + **/ + show(): void; + + /** + * Shows the specified commands of the AppBar. + * @param commands The commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. + **/ + showCommands(commands: any[], immediate?: boolean): void; + + /** + * Shows the specified commands of the AppBar while hiding all other commands. + * @param commands The commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. + **/ + showOnlyCommands(commands: any[], immediate?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Sets the AppBarCommand objects that appear in the app bar. + **/ + commands: AppBarCommand[]; + + /** + * Gets or sets a value that indicates whether the AppBar is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the AppBar. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the AppBar is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the layout of the app bar contents. + **/ + layout: string; + + /** + * Gets or sets a value that specifies whether the AppBar appears at the top or bottom of the main view. + **/ + placement: string; + + /** + * Gets or sets a value that indicates whether the AppBar is sticky (won't light dismiss). If not sticky, the app bar dismisses normally when the user touches outside of the appbar. + **/ + sticky: boolean; + + //#endregion Properties + + } + + /** + * Represents a command to be displayed in an app bar. + **/ + class AppBarCommand { + //#region Constructors + + /** + * Creates a new AppBarCommand object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new AppBarCommand. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that indicates whether the AppBarCommand is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the AppBarCommand. + **/ + element: HTMLElement; + + /** + * Adds an extra CSS class during construction. + **/ + extraClass: string; + + /** + * Gets or sets the Flyout object displayed by this command. The specified flyout is shown when the AppBarCommand's button is invoked. + **/ + flyout: Flyout; + + /** + * Gets or sets a value that indicates whether the AppBarCommand is hiding or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the icon of the AppBarCommand. + **/ + icon: string; + + /** + * Gets the element identifier (ID) of the command. + **/ + id: string; + + /** + * Gets or sets the label of the command. + **/ + label: string; + + /** + * Gets or sets the function to be invoked when the command is clicked. + **/ + onclick: Function; + + /** + * Gets the section of the app bar that the command is in. + **/ + section: string; + + /** + * Gets or sets the selected state of a toggle button. + **/ + selected: boolean; + + /** + * Gets or sets the tooltip of the command. + **/ + tooltip: string; + + /** + * Gets the type of the command. + **/ + type: string; + + //#endregion Properties + + } + + /** + * Allows users to pick a date value. + **/ + class DatePicker { + //#region Constructors + + /** + * Initializes a new instance of the DatePicker control. + * @constructor + * @param element The DOM element associated with the DatePicker control. + * @param options The set of options to be applied initially to the DatePicker control. The options are the following: calendar, current, datePattern, disabled, maxYear, minYear, monthPattern, yearPattern. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when any of the controls are changed by the user. + * @param eventInfo An object that contains information about the event. + **/ + onchange(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener. + * @param type The type (name) of the event. + * @param listener The function that handles the event. + * @param capture If true, specifies that capture should be initiated, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + raiseEvent(type: string, eventProperties: any): boolean; + + /** + * Removes a listener for the specified event. + * @param type The name of the event for which to remove a listener. + * @param listener The listener. + * @param useCapture Optional. The same value that was passed to addEventListener for this listener. It may be omitted if it was omitted when calling addEventListener. + **/ + removeEventListener(type: string, listener: Function, useCapture?: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the calendar to use. + **/ + calendar: string; + + /** + * Gets or sets the current date of the DatePicker. You can use either a date string or a Date object to set this property. + **/ + current: Date; + + /** + * Gets or sets the display pattern for the date. The default date pattern is day.integer(2). You can change the date pattern by changing the number of integers displayed. + **/ + datePattern: string; + + /** + * Specifies whether the DatePicker is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element for the DatePicker. + **/ + element: HTMLElement; + + /** + * Gets or sets the maximum Gregorian year available for picking. + **/ + maxYear: number; + + /** + * Gets or sets the minimum Gregorian year available for picking. + **/ + minYear: number; + + /** + * Gets or sets the display pattern for the month. The default month pattern is month.abbreviated. You can change the month pattern to the following values: month.full. The full name of the month. month.abbreviated(n). You can use abbreviated with or without specifying the number of letters in the abbreviation. If you do specify the number of letters, the actual length of the month name that appears may vary. month.solo.full. A representation of the month that is suitable for stand-alone display. You can also use month.solo.abbreviated(n). month.integer(n). You can use integer with or without specifying the number of integers. + **/ + monthPattern: string; + + /** + * Gets or sets the display pattern for the year. The default year pattern is year.full. You can change the year pattern to the following values: year.abbreviated(n). You can use abbreviated with or without specifying the number of letters in the abbreviation. + **/ + yearPattern: string; + + //#endregion Properties + + } + + /** + * Adds event-related methods to the control. + **/ + class DOMEventMixin { + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture true to initiate capture; otherwise, false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type, adding the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true to initiate capture; otherwise, false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Adds the set of declaratively specified options (properties and events) to the specified control. If the name of the options property begins with "on", the property value is a function and the control supports addEventListener. This method calls the addEventListener method on the control. + * @param control The control on which the properties and events are to be applied. + * @param options The set of options that are specified declaratively. + **/ + setOptions(control: any, options: any): void; + + //#endregion Methods + + } + + /** + * Displays a collection, such as a set of photos, one item at a time. + **/ + class FlipView { + //#region Constructors + + /** + * Creates a new FlipView. + * @constructor + * @param element The DOM element that hosts the control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the pageselected event, add a property named "onpageselected" and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the datasource count changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: source. + **/ + ondatasourcecountchanged(eventInfo: Event): void; + + /** + * Raised when the FlipView flips to a page and its renderer function completes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source. + **/ + onpagecompleted(eventInfo: CustomEvent): void; + + /** + * Raised when the FlipView flips to a page. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source. + **/ + onpageselected(eventInfo: CustomEvent): void; + + /** + * Occurs when an item becomes invisible or visible. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source, detail.visible. + **/ + onpagevisibilitychanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. For a list of events, see the FlipView object page. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Returns the number of items in the FlipView control's itemDataSource. + * @returns A Promise that contains the number of items in the list or WinJS.UI.CountResult.unknown if the count is unavailable. + **/ + count(): Promise; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Forces the FlipView to update its layout. Use this function when making the FlipView visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Navigates to the next page. + * @returns true if the FlipView begins navigating to the next page; false if the FlipView is already at the last item or is in the middle of another navigation animation. + **/ + next(): boolean; + + /** + * Navigates to the previous item. + * @returns true if the FlipView begins navigating to the previous page; nfalse if the FlipView is already at the first page or is in the middle of another navigation animation. + **/ + previous(): boolean; + + /** + * Unregisters an event handler for the specified event. + * @param eventName The name of the event. + * @param eventHandler The event handler function to remove. + * @param useCapture Set to true to unregister the event handler for the capturing phase; otherwise, set to false to unregister the event handler for the bubbling phase. + **/ + removeEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Sets custom animations for the FlipView to use when navigating between pages. + * @param animations An object that contains up to three fields, one for each navigation action: next, previous, and jump. Each of those fields must be a function with this signature: function (outgoingPage, incomingPage) Each function must return a WinJS.Promise that completes once the animations are finished. If a field is null or undefined, the FlipView reverts to its default animation for that action. + **/ + setCustomAnimations(animations: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the index of the currently displayed page. + **/ + currentPage: number; + + /** + * Gets the HTML element that hosts this FlipView. + **/ + element: HTMLElement; + + /** + * Gets or sets the data source that provides the FlipView with items to display. The FlipView displays one item at a time, on its own page. + **/ + itemDataSource: IListDataSource; + + /** + * Gets or sets the spacing between each item, in pixels. + **/ + itemSpacing: number; + + /** + * Gets or sets a Template or function that defines the HTML for each item's page. + **/ + itemTemplate: any; + + /** + * Gets or sets the orientation of the FlipView, horizontal or vertical. + **/ + orientation: string; + + //#endregion Properties + + } + + /** + * Displays lightweight UI that is either information, or requires user interaction. Unlike a dialog, a Flyout can be light dismissed by clicking or tapping off of it. + **/ + class Flyout { + //#region Constructors + + /** + * Creates a new Flyout object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new Flyout. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised immediately after a flyout is fully hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Raised immediately after a flyout is fully shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Raised just before hiding a flyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Raised just before showing a flyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Hides the Flyout, if visible, regardless of other states. + **/ + hide(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the Flyout, if hidden, regardless of other states. + * @param anchor Required. The DOM element to anchor the Flyout. + * @param placement The placement of the Flyout to the anchor: the string literal "top", "bottom", "left", or "right". + * @param alignment For "top" or "bottom" placement, the alignment of the Flyout to the anchor's edge: the string literal "center", "left", or "right". + **/ + show(anchor: HTMLElement, placement: string, alignment: string): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the default alignment to be used for this Flyout. + **/ + alignment: string; + + /** + * Gets or sets the default anchor to be used for this Flyout. + **/ + anchor: HTMLElement; + + /** + * Gets the DOM element that hosts the Flyout. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the Flyout is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the default placement to be used for this Flyout. + **/ + placement: string; + + //#endregion Properties + + } + + /** + * Represents a grid layout for the ListView in which items are arranged in a horizontal grid. + **/ + class GridLayout { + //#region Constructors + + /** + * Creates a new GridLayout object. + * @constructor + * @param options The set of properties and values to apply to the new GridLayout. + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Calculates the index of the first visible item. + * @param beginScrollPosition + * @param wholeItem + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): void; + + /** + * Calculates the index of the last visible item. + * @param endScrollPosition + * @param wholeItem + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): void; + + /** + * Ends the layout process. + **/ + endLayout(): void; + + /** + * Calculates the dimensions of an item. + * @param itemIndex + **/ + getItemPosition(itemIndex: number): void; + + /** + * Gets the index of the next item relatively to the supplied index and keypress. + * @param itemIndex + * @param element + * @param keyPressed + **/ + getKeyboardNavigatedItem(itemIndex: number, element: any, keyPressed: any): void; + + /** + * Gets the scrollbar range. + * @param beginScrollPosition + * @param endScrollPosition + **/ + getScrollbarRange(beginScrollPosition: number, endScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate, or the horizontal position on the screen. + * @param y The y-coordinate, or the vertical position on the screen. + **/ + hitTest(x: number, y: number): void; + + /** + * Initializes this layout. + **/ + init(): void; + + /** + * Notifies of items being added. + * @param elements + **/ + itemsAdded(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param firstPixel The first pixel the range of items falls between. + * @param lastPixel The last pixel the range of items falls between. + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * Notifies of items being moved. + **/ + itemsMoved(): void; + + /** + * Notifies of items being removed. + * @param elements + **/ + itemsRemoved(elements: any): void; + + /** + * Lays out the specified header at the specified index. + * @param groupIndex + * @param element A DOM element. + **/ + layoutHeader(groupIndex: number, element: any): void; + + /** + * Lays out the specified item at the speficied index. + * @param itemIndex + * @param element A DOM element. + **/ + layoutItem(itemIndex: number, element: any): void; + + /** + * Prepares the header element. + * @param element + **/ + prepareHeader(element: HTMLElement): void; + + /** + * Prepares the item element. + * @param itemIndex + * @param element A DOM element. + **/ + prepareItem(itemIndex: number, element: any): void; + + /** + * Releases the item. + * @param item + * @param newItem + **/ + releaseItem(item: any, newItem: any): void; + + /** + * Resets the layout. + **/ + reset(): void; + + /** + * Sets the ILayoutSite object. + * @param layoutSite + **/ + setSite(layoutSite: any): void; + + /** + * Starts the layout. + * @param beginScrollPosition + * @param endScrollPositionScrollPosition + **/ + startLayout(beginScrollPosition: number, endScrollPositionScrollPosition: number): void; + + /** + * Updates the backdrop count. + * @param count + **/ + updateBackdrop(count: number): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the backdrop css color. + **/ + backdropColor: string; + + /** + * Gets or sets whether backdrops are disabled. + **/ + disableBackdrop: boolean; + + /** + * Gets or sets the position of group headers. + **/ + groupHeaderPosition: WinJS.UI.HeaderPosition; + + /** + * Gets or sets the groupInfo function. + **/ + groupInfo: Function; + + /** + * Gets or sets whether the orientation of this layout is horizontal. + **/ + horizontal: boolean; + + /** + * Gets or sets the itemInfo function. + **/ + itemInfo: Function; + + /** + * Gets or sets the maximum number of rows to display. + **/ + maxRows: number; + + //#endregion Properties + + } + + /** + * Enables you to include an HTML page dynamically. As part of the constructor, you must include an option indicating the URI of the page. + **/ + class HtmlControl { + //#region Constructors + + /** + * Initializes a new instance of HtmlControl to define a new page control. + * @constructor + * @param element The element that hosts the HtmlControl. + * @param options The options for configuring the page. The uri option is required in order to specify the source document for the content of the page. Other options are the ones used by the WinJS.Pages.render method. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + } + + /** + * This object supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + class Layout { + } + + /** + * Represents a layout for the ListView in which items are arranged in a vertical list. + **/ + class ListLayout { + //#region Constructors + + /** + * Creates a new ListLayout. + * @constructor + * @param options An object that contains one or more property/value pairs to apply to the new ListLayout. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Calculates the index of the first visible item. + * @param beginScrollPosition + * @param wholeItem + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): void; + + /** + * Calculates the index of the last visible item. + * @param endScrollPosition + * @param wholeItem + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): void; + + /** + * Ends the layout process. + **/ + endLayout(): void; + + /** + * Calculates the dimensions of an item. + * @param itemIndex + **/ + getItemPosition(itemIndex: number): void; + + /** + * Gets the index of the next item relatively to the supplied index and keypress. + * @param itemIndex + * @param element + * @param keyPressed + **/ + getKeyboardNavigatedItem(itemIndex: number, element: HTMLElement, keyPressed: any): void; + + /** + * Gets the scrollbar range. + * @param beginScrollPosition + * @param endScrollPosition + **/ + getScrollbarRange(beginScrollPosition: number, endScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate, or the horizontal position on the screen. + * @param y The y-coordinate, or the vertical position on the screen. + **/ + hitTest(x: number, y: number): void; + + /** + * Initializes this layout. + **/ + init(): void; + + /** + * Notifies of items being added. + * @param elements + **/ + itemsAdded(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param firstPixel + * @param lastPixel + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * Notifies of items being moved. + **/ + itemsMoved(): void; + + /** + * Notifies of items being removed. + * @param elements + **/ + itemsRemoved(elements: any): void; + + /** + * Lays out the specified header at the specified index. + * @param groupIndex + * @param element A DOM element. + **/ + layoutHeader(groupIndex: number, element: any): void; + + /** + * Lays out the specified item at the speficied index. + * @param itemIndex + * @param element A DOM element. + **/ + layoutItem(itemIndex: number, element: any): void; + + /** + * Prepares the header element. + * @param element + **/ + prepareHeader(element: HTMLElement): void; + + /** + * Prepares the item element. + * @param itemIndex + * @param element A DOM element. + **/ + prepareItem(itemIndex: number, element: any): void; + + /** + * Releases the item. + * @param item + * @param newItem + **/ + releaseItem(item: any, newItem: any): void; + + /** + * Resets the layout. + **/ + reset(): void; + + /** + * Sets the ILayoutSite object. + * @param layoutSite + **/ + setSite(layoutSite: ILayoutSite): void; + + /** + * Starts the layout. + * @param beginScrollPosition + * @param endScrollPositionScrollPosition + **/ + startLayout(beginScrollPosition: number, endScrollPositionScrollPosition: number): void; + + /** + * Updates the backdrop count. + * @param count + **/ + updateBackdrop(count: number): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the backdrop css color. + **/ + backdropColor: string; + + /** + * Gets or sets whether backdrops are disabled. + **/ + disableBackdrop: boolean; + + /** + * Gets or sets the position of group headers. + **/ + groupHeaderPosition: WinJS.UI.HeaderPosition; + + /** + * Gets or sets the groupInfo function. + **/ + groupInfo: Function; + + /** + * Gets or sets whether the orientation of this layout is horizontal. + **/ + horizontal: boolean; + + /** + * Gets or sets the itemInfo function. + **/ + itemInfo: Function; + + //#endregion Properties + + } + + /** + * Displays data items in a customizable list or grid. + **/ + class ListView { + //#region Constructors + + /** + * Creates a new ListView. + * @constructor + * @param element The DOM element that hosts the ListView control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the selectionchanged event, add a property named "onselectionchanged" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the ListView is about to play an entrance or contentTransition animation. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.type, detail.setPromise. + **/ + oncontentanimating(eventInfo: CustomEvent): void; + + /** + * Occurs when the user taps or clicks an item. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.itemIndex. + **/ + oniteminvoked(eventInfo: CustomEvent): void; + + /** + * Raised when the focused item changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.oldFocus, detail.oldNewFocus. + **/ + onkeyboardnavigating(eventInfo: CustomEvent): void; + + /** + * Occurs when the ListView control's loadingState changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.scrolling. + **/ + onloadingstatechanged(eventInfo: CustomEvent): void; + + /** + * Occurs after the current selection changes. + * @param eventInfo An object that contains information about the event. The detail property of this object is null. To obtain the selected items, use the ListView.selection property. + **/ + onselectionchanged(eventInfo: CustomEvent): void; + + /** + * Occurs just before the current selection changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.newSelection, detail.preventTapBehavior. + **/ + onselectionchanging(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. See the ListView object page for a list of events. Note that you drop the "on" when specifying the event name for the addEventListener method. For example, instead of specifying "onselectionchange", you specify "selectionchange". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Returns the DOM element that represents the item at the specified index. + * @param itemIndex The index of the item. + * @returns The DOM element that represents the item at the specified index. + **/ + elementFromIndex(itemIndex: number): HTMLElement; + + /** + * Makes the item at the specified index visible. If necessary, the ListView will scroll to the item. + * @param itemIndex The index of the item to scroll into view. + **/ + ensureVisible(itemIndex: number): void; + + /** + * Forces the ListView to update its layout. Use this function when making the ListView visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Returns the index of the item that the specified DOM element displays. + * @param element The DOM element that displays the item. + * @returns The index of the item displayed by element. + **/ + indexOfElement(element: HTMLElement): number; + + /** + * Loads the next set of pages if the ListView control's loadingBehavior is set to "incremental" (otherwise, it does nothing). The number of pages to be loaded is determined by the pagesToLoad property. + **/ + loadMorePages(): void; + + /** + * Repositions all the visible items in the ListView to adjust for items whose sizes have changed. Most apps won’t ever need to call this method. For more info, see the Remarks section. + **/ + recalculateItemPosition(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + /** + * Triggers the ListView disposal service manually. + **/ + static triggerDispose(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that indicates whether the next set of pages is automatically loaded when the user scrolls beyond the number of pages specified by the pagesToLoadThreshold property. + **/ + automaticallyLoadPages: boolean; + + /** + * Gets or sets an IListViewItem that indicates which item should have keyboard focus and the focus state of that item. + **/ + currentItem: IListViewItem; + + /** + * Gets the HTML element that hosts this ListView. + **/ + element: HTMLElement; + + /** + * Gets or sets the data source that contains the groups for the items in the itemDataSource. + **/ + groupDataSource: IListDataSource; + + /** + * Gets or sets the Template or function that creates the DOM elements for each group header in the groupDataSource. Each group header can contain multiple elements, but it must have a single root element. + **/ + groupHeaderTemplate: any; + + /** + * Gets or sets the first visible item. + **/ + indexOfFirstVisible: number; + + /** + * Gets the index of the last visible item in the ListView. + **/ + indexOfLastVisible: number; + + /** + * Gets or sets the data source that provides the ListView with items. + **/ + itemDataSource: IListDataSource; + + /** + * Gets or sets the WinJS.Binding.Template or templating function that creates the DOM elements for each item in the itemDataSource. Each item can contain multiple elements, but it must have a single root element. + **/ + itemTemplate: any; + + /** + * Gets or sets an object that controls the layout of the ListView. + **/ + layout: ILayout; + + /** + * Gets or sets a value that specifies how the ListView fetches items and adds and removes them to the DOM. Don't change the value of this property after the ListView has begun loading data. + **/ + loadingBehavior: string; + + /** + * Gets a value that indicates whether the ListView is still loading or whether loading is complete. + **/ + loadingState: string; + + /** + * Gets or sets the number of pages to load when the loadingBehavior property is set to "incremental" and the user scrolls beyond the threshold specified by the pagesToLoadThreshold property. + **/ + pagesToLoad: number; + + /** + * Gets or sets the threshold (in pages) for initiating an incremental load. When the last visible item is within the specified number of pages from the end of the loaded portion of the list, and if automaticallyLoadPages is true and loadingBehavior is set to "incremental", the ListView initiates an incremental load. + **/ + pagesToLoadThreshold: number; + + /** + * Gets or sets the function that is called when the ListView discards or recycles the element representation of a group header. + **/ + resetGroupHeader: (header: any, element: HTMLElement) => void; + + /** + * Gets or sets the function that is called when an item is removed, an item is changed, or an item falls outside of the realized range of the ListView. + **/ + resetItem: (item: T, element: HTMLElement) => void; + + /** + * Gets or sets the distance, in pixels, of the start of the viewable area within the viewport. + **/ + scrollPosition: number; + + /** + * Gets an ISelection that contains the range of currently selected items. + **/ + selection: ISelection; + + /** + * Gets or sets the selection mode of the ListView. + **/ + selectionMode: SelectionMode; + + /** + * Gets or sets how the ListView reacts to the swipe gesture. The swipe gesture can select the swiped items or can have no effect on the current selection. + **/ + swipeBehavior: WinJS.UI.SwipeBehavior; + + /** + * Gets or sets how the ListView reacts when the user taps or clicks an item. + **/ + tapBehavior: TapBehavior; + + /** + * Gets a ZoomableView that supports semantic zoom functionality. This API supports the SemanticZoom infrastructure and is not intended to be used directly from your code. + **/ + zoomableView: IZoomableView>; + + //#endregion Properties + + } + + /** + * Represents a menu flyout for displaying commands. + **/ + class Menu { + //#region Constructors + + /** + * Creates a new Menu object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new Menu. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs immediately after the Menu is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Occurs after the Menu is shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Occurs before the Menu is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Occurs before a hidden Menu is shown. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Returns the MenuCommand object identified by id. + * @param id The element identifier (ID) of the command to be returned. + * @returns The command identified by id. + **/ + getCommandById(id: string): MenuCommand; + + /** + * Hides the Menu. + **/ + hide(): void; + + /** + * Hides the specified commands of the Menu. + * @param commands The commands to hide. The array elements may be MenuCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. + **/ + hideCommands(commands: any[], immediate: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the Menu, if hidden, regardless of other states. + * @param anchor Required. The DOM element to anchor the Menu. + * @param placement The placement of the Menu to the anchor: top, bottom, left, or right. + * @param alignment For top or bottom placement, the alignment of the Menu to the anchor's edge: center, left, or right. + **/ + show(anchor: HTMLElement, placement: string, alignment: string): void; + + /** + * Shows the specified commands of the Menu. + * @param commands The commands to show. The array elements may be Menu objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. + **/ + showCommands(commands: any[], immediate: boolean): void; + + /** + * Shows the specified commands of the Menu while hiding all other commands. + * @param commands The commands to show. The array elements may be MenuCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. + **/ + showOnlyCommands(commands: any[], immediate: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the default alignment to be used for this Menu. + **/ + alignment: string; + + /** + * Gets or sets the default anchor to be used for this Menu. + **/ + anchor: HTMLElement; + + /** + * Sets the MenuCommand objects that appear in the menu. + **/ + commands: MenuCommand[]; + + /** + * Gets the DOM element that hosts the Menu. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the Menu is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the default placement to be used for this Menu. + **/ + placement: string; + + //#endregion Properties + + } + + /** + * Represents a command to be displayed in a Menu object. + **/ + class MenuCommand { + //#region Constructors + + /** + * Creates a new MenuCommand object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new MenuCommand. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that indicates whether the MenuCommand is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the MenuCommand. + **/ + element: HTMLElement; + + /** + * Adds an extra CSS class during construction. + **/ + extraClass: string; + + /** + * Gets or sets the Flyout object displayed by this command. The specified flyout is shown when the MenuCommand's button is invoked. + **/ + flyout: Flyout; + + /** + * Gets a value that indicates whether the MenuCommand is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets the element identifier (ID) of the command. + **/ + id: string; + + /** + * Gets or sets the label of the command. + **/ + label: string; + + /** + * Gets or sets the function to be invoked when the command is clicked. + **/ + onclick: Function; + + /** + * Gets or sets the selected state of a toggle button. + **/ + selected: boolean; + + /** + * Gets the type of the command. + **/ + type: string; + + //#endregion Properties + + } + + /** + * Lets the user rate something by clicking an icon that represents a rating. The Rating control can display three types of ratings: an average rating, a tentative rating, and the user's rating. + **/ + class Rating { + //#region Constructors + + /** + * Creates a new Rating. + * @constructor + * @param element The DOM element hosts the new Rating. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the cancel event, add a property named "oncancel" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the user finishes interacting with the rating control without committing a tentative rating. + * @param eventInfo An object that contains information about the event. + **/ + oncancel(eventInfo: Event): void; + + /** + * Raised when the user commits a change to the userRating. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tentativeRating. + **/ + onchange(eventInfo: CustomEvent): void; + + /** + * Raised when the user is choosing a new tentative Rating. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tentativeRating. + **/ + onpreviewchange(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the average rating. + **/ + averageRating: number; + + /** + * Gets or sets whether the control is disabled. When the control is disabled, the user can't specify a new user rating or modify an existing rating. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the Rating. + **/ + element: HTMLElement; + + /** + * Gets or sets whether control lets the user clear the rating. + **/ + enableClear: boolean; + + /** + * Gets or sets the maximum possible rating value. + **/ + maxRating: number; + + /** + * Gets or sets a set of descriptions to show for rating values in the tooltip. + **/ + tooltipStrings: string[]; + + /** + * Gets or sets the user's rating. + **/ + userRating: number; + + //#endregion Properties + + } + + /** + * Enables the user to zoom between two different views supplied by two child controls. One child control supplies the zoomed-out view and the other provides the zoomed-in view. + **/ + class SemanticZoom { + //#region Constructors + + /** + * Creates a new SemanticZoom. + * @constructor + * @param element The DOM element that hosts the SemanticZoom. + * @param options An object that contains one or more property/value pairs to apply to the new control. This object can contain these properties: initiallyZoomedOut Boolean, zoomFactor 0.2–0.85. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the control zooms in or out. + * @param eventInfo An object that contains information about the event. The detail property of this object is true when the control is zoomed out. Otherwise, it's false. + **/ + onzoomchanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Forces the SemanticZoom to update its layout. Use this function when making the SemanticZoom visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Unregisters an event handler for the specified event. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the SemanticZoom control. + **/ + element: HTMLElement; + + /** + * Gets or a sets a value that specifies whether to display the SemanticZoom zoom out button. + **/ + enableButton: boolean; + + /** + * Gets or sets a value that indicates whether SemanticZoom is locked and zooming between views is disabled. + **/ + locked: boolean; + + /** + * Gets or sets a value that indicates whether the control is zoomed out. + **/ + zoomedOut: boolean; + + /** + * Gets or sets a value that specifies how much the scaling the cross-fade animation performs when the SemanticZoom transitions between views. + **/ + zoomFactor: number; + + //#endregion Properties + + } + + /** + * Provides users with fast, in-context access to settings that affect the current Windows Store app. + **/ + class SettingsFlyout { + //#region Constructors + + /** + * Creates a new SettingsFlyout object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new SettingsFlyout. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised immediately after the SettingsFlyout is completely hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Raised immediately after a SettingsFlyout is fully shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Raised just before hiding a SettingsFlyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Raised just before showing a SettingsFlyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Hides the SettingsFlyout, if visible, regardless of other states. + **/ + hide(): void; + + /** + * Loads a fragment of the SettingsFlyout. Your app calls this when the user invokes a settings command and the WinJS.Application.onsettings event occurs. + * @param e An object that contains information about the event, received from the WinJS.Application.onsettings event. The detail property of this object contains the applicationcommands sub-property that you set to an array of settings commands. You then populate the SettingsFlyout with these commands by a call to populateSettings. + **/ + static populateSettings(e: CustomEvent): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the SettingsPane UI, if hidden. + **/ + show(): void; + + /** + * Shows the SettingsPane UI, if hidden, regardless of other state. + **/ + static show(): void; + + /** + * Show the Settings flyout using the Settings element identifier (ID) and the path of the page that contains the Settings element. + * @param id The ID of the Settings element. + * @param path The path of the page that contains the Settings element. + **/ + static showSettings(id: string, path: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element the SettingsFlyout is attached to. + **/ + element: HTMLElement; + + /** + * Gets whether the SettingsFlyout is hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the settings command Id for the SettingsFlyout control. + **/ + settingsCommandId: string; + + /** + * This property may be unavailable or altered in future versions. Use the CSS width property of the element that has the win-settingsflyout class instead. + **/ + width: string; + + //#endregion Properties + + } + + /** + * A type of IListDataSource that provides read-access to an object that implements the IStorageQueryResultBase interface. A StorageDataSource enables you to query and bind to items in the data source. + **/ + class StorageDataSource { + //#region Constructors + + /** + * Creates a new StorageDataSource object. + * @constructor + * @param query The IStorageQueryResultBase that the StorageDataSource obtains its items from. Instead of IStorageQueryResultBase, you can also pass one of these string values: Music, Pictures, Videos, Documents. + * @param options The set of properties and values to apply to the new StorageDataSource. Properties on this object may include: mode , requestedThumbnailSize , thumbnailOptions , synchronous . + **/ + constructor(query: any, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Draws the thumbnail for the specified item to the specified img element. + * @param item The item to retrieve the thumbnail for. + * @param image The img element that will display the thumbnail. + * @returns A Promise that completes when the full-quality thumbnail is visible. + **/ + loadThumbnail(item: IItem, image: HTMLImageElement): Promise; + + //#endregion Methods + + } + + /** + * Prevents a DOM sub-tree from receiving tab navigations and focus. + **/ + class TabContainer { + //#region Constructors + + /** + * Creates a new TabContainer. + * @constructor + * @param element The DOM element that hosts the TabContainer control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Properties + + /** + * Gets or sets the child DOM element that receives tab focus. + **/ + childFocus: HTMLElement; + + /** + * Gets or sets the tab index of this container. + **/ + tabIndex: number; + + //#endregion Properties + + } + + /** + * Allows users to select time values. + **/ + class TimePicker { + //#region Constructors + + /** + * Initializes a new instance of a TimePicker control. + * @constructor + * @param element The DOM element associated with the TimePicker control. + * @param options The set of options to be applied initially to the TimePicker control. The options are the following: clock. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when any of the controls are changed by the user. + * @param eventInfo An object that contains information about the event. + **/ + onchange(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener. + * @param type The type (name) of the event. + * @param listener The function that handles the event. + * @param capture If true, specifies that capture should be initiated, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + raiseEvent(type: string, eventProperties: any): boolean; + + /** + * Removes a listener for the specified event. + * @param type The name of the event for which to remove a listener. + * @param listener The listener. + * @param useCapture Optional. The same value that was passed to addEventListener for this listener. It may be omitted if it was omitted when calling addEventListener. + **/ + removeEventListener(type: string, listener: Function, useCapture?: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the type of clock to display (12HourClock or 24HourClock). It defaults to the user setting. + **/ + clock: string; + + /** + * Gets or sets the current time of the TimePicker. Note that the date value is always July 15, 2011. + **/ + current: Date; + + /** + * Specifies whether the TimePicker is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element for the TimePicker. + **/ + element: HTMLElement; + + /** + * Gets or sets the display pattern for the hour. The default hour pattern is hour.integer(2). You can change the hour pattern by changing the number of integers displayed. + **/ + hourPattern: string; + + /** + * Gets or sets the minute increment. For example, 15 specifies that the TimePicker minute control should display only the choices 00, 15, 30, 45. + **/ + minuteIncrement: number; + + /** + * Gets or sets the display pattern for the minute. The default minute pattern is minute.integer(2). You can change the minute pattern by changing the number of integers displayed. + **/ + minutePattern: string; + + /** + * Gets or sets the display pattern for the period. The default period pattern is period.abbreviated(2). You can change the period pattern by changing the number of integers displayed. + **/ + periodPattern: string; + + //#endregion Properties + + } + + /** + * A control that lets the user switch an option between two states: on (checked is set to true) and off (checked is set to false). + **/ + class ToggleSwitch { + //#region Constructors + + /** + * Creates a new ToggleSwitch. + * @constructor + * @param element The DOM that hosts the control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the change event, add a property named "onchange" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the ToggleSwitch control is flipped to on (checked == true) or off (checked == false). + * @param eventInfo An object that contains information about the event. + **/ + onchange(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Handles the specified event. + * @param event The event. + **/ + handleEvent(event: any): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + raiseEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether the control is on or off. + **/ + checked: boolean; + + /** + * Gets or sets a value that specifies whether the control is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the ToggleSwitch. + **/ + element: HTMLElement; + + /** + * Gets or sets the text that displays when the ToggleSwitch is off (checked is set to false). + **/ + labelOff: string; + + /** + * Gets or sets the text that displays when the ToggleSwitch is on (checked is set to true). + **/ + labelOn: string; + + /** + * Gets or sets the main text for the ToggleSwitch control. This text is always displayed, regardless of whether the control is switched on or off. + **/ + title: string; + + //#endregion Properties + + } + + /** + * Displays a tooltip that can contain images and formatting. + **/ + class Tooltip { + //#region Constructors + + /** + * Creates a new Tooltip. + * @constructor + * @param element The DOM element associated that hosts the Tooltip. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the opened event, add a property named "onopened" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised just before the Tooltip is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeclose(eventInfo: CustomEvent): void; + + /** + * Raised just before the Tooltip appears. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeopen(eventInfo: CustomEvent): void; + + /** + * Raised when the Tooltip is no longer displayed. + * @param eventInfo An object that contains information about the event. + **/ + onclosed(eventInfo: CustomEvent): void; + + /** + * Raised when the Tooltip is shown. + * @param eventInfo An object that contains information about the event. + **/ + onopened(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Hides the Tooltip. + **/ + close(): void; + + /** + * Shows the Tooltip. + * @param type A value that specifies when to show the Tooltip. The default value is "mousedown". + **/ + open(type?: string): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the HTML element that is the content of the Tooltip. + **/ + contentElement: HTMLElement; + + /** + * Gets the DOM element that hosts the Tooltip control. + **/ + element: HTMLElement; + + /** + * Gets or appends additional CSS classes to apply to the element that hosts the Tooltip. + **/ + extraClass: string; + + /** + * Gets or sets a value that specifies whether the Tooltip is an infotip, a tooltip that contains a lot of info and should be displayed for longer than a typical Tooltip. + **/ + infotip: boolean; + + /** + * Gets or sets the HTML content of the Tooltip. + **/ + innerHTML: string; + + /** + * Gets or sets the position for the Tooltip relative to its target element: top, bottom, left or right. + **/ + placement: string; + + //#endregion Properties + + } + + /** + * Scales a single child element to fill the available space without resizing it. This control reacts to changes in the size of the container as well as changes in size of the child element. For example, a media query may result in a change in aspect ratio. + **/ + class ViewBox { + //#region Constructors + + /** + * Initializes a new instance of the ViewBox control. + * @constructor + * @param element The DOM element that functions as the scaling box. This element fills 100% of the width and height allotted to it. + * @param options The set of options to be applied initially to the ViewBox control. There are currently no options on this control, and any options included in this parameter are ignored. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Adds an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Forces the ViewBox to update its layout. Use this function when making the ViewBox visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that functions as the scaling box. + **/ + element: HTMLElement; + + //#endregion Properties + + } + + /** + * Serves as the base class for a custom IListDataSource. + **/ + class VirtualizedDataSource { + //#region Constructors + + /** + * Initializes the VirtualizedDataSource base class of a custom data source. + * @constructor + * @param listDataAdapter The object that supplies data to the VirtualizedDataSource. + * @param options An object that can contain properties that specify additional options for the VirtualizedDataSource. It supports these properties: cacheSize. + **/ + constructor(listDataAdapter: IListDataAdapter, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the status of the VirtualizedDataSource changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: status. + **/ + statuschanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. See the VirtualizedDataSource object page for a list of events. Note that you drop the "on" when specifying the event name for the addEventListener method. For example, instead of specifying "onstatuschanged", you specify "statuschanged". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. See the VirtualizedDataSource object page for a list of events. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + } + + //#endregion Objects + + //#region Functions + + /** + * Returns a new IListDataSource that adds group information to the items of another IListDataSource. + * @param listDataSource The data source for the individual items to group. + * @param groupKey A callback function that accepts a single argument: an item in the IListDataSource. The function is called for each item in the list and must return the group key for that item as a string. + * @param groupData A callback function that accepts a single argument: an item in the IListDataSource. The function is called on one IListDataSource item for each group and must return an object that represents the header of that group. + * @param options An object that can contain properties that specify additional options: groupCountEstimate, batchSize. + * @returns An IListDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. + **/ + function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListDataSource; + + /** + * Used to disables all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be disabled, as the determination is made based on several factors. + **/ + function disableAnimations(): void; + + /** + * Used to enable all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be enabled, as the determination is made based on several factors. + **/ + function enableAnimations(): void; + + /** + * Marks a event handler function as being compatible with declarative processing. + * @param handler The handler to be marked as compatible with declarative processing. + * @returns The handler, marked as compatible with declarative processing. + **/ + function eventHandler(handler: any): any; + + /** + * Asynchronously executes a collection of CSS animations on a collection of elements. This is the underlying animation mechanism used by the Animations Library. Apps are encouraged to use the Animations Library to conform with the standard look and feel of the rest of the system, rather than calling this function directly. + * @param element Element or elements to be animated. This parameter can be expressed in several ways: As the special value "undefined", which means that the animation has no target, As a single object, As a JavaScript array (possibly empty), in which each element of the array can be a single element or a JavaScript array of elements., As a NodeList (for example, the result of querySelectorAll), As an HTMLCollection. + * @param animation The animation description or an array of animation descriptions to apply to element. An animation description is a JavaScript object with specific properties, listed below. There are two types of animation descriptions: one for keyframe-based animations and one for explicit animations. These types are distinguished by whether the keyframe property has a defined value. The following properties are required for both types of animation descriptions: property (string), delay (number), duration (number), timing (string). If an animation has a keyframe property with a defined, non-null value, then the animation is a keyframe-based animation. A keyframe-based animation description requires the following property in addition to those mentioned above: keyframe (string). If an animation does not have a keyframe property, or if the value of the property is null or undefined, then the animation is an explicit animation. An explicit animation description requires the following properties in addition to the common properties mentioned above: from, to. The values given in the from and to properties must be valid for the CSS property specified by the property property. For example, if the CSS property is "opacity", then the from and to properties must be numbers between 0 and 1 (inclusive). + * @returns Returns a Promise object that completes when the CSS animation is complete. + **/ + function executeAnimation(element: HTMLElement, animation: any): Promise; + + /** + * Asynchronously executes a collection of CSS transitions on a collection of elements. This is the underlying animation mechanism used by the Animations Library. Apps are encouraged to use the Animations Library to conform with the standard look and feel of the rest of the system, rather than calling this function directly. + * @param element Element or elements on which to perform the transition. This parameter can be expressed in several ways: As the special value "undefined", which means that the transition has no target, As a single object, As a JavaScript array (possibly empty), in which each element of the array can be a single element or a JavaScript array of elements., As a NodeList (for example, the result of querySelectorAll), As an HTMLCollection. + * @param transition The transition description or an array of transition descriptions to apply to element. A transition description is a JavaScript object with these properties: property (string), delay (number), duration (number), timing (string), from (optional), to. The values given in the from and to properties must be valid for the CSS property specified by the property property. For example, if the CSS property is "opacity", then the from and to properties must be numbers between 0 and 1 (inclusive). + * @returns Returns a Promise that completes when the transition is finished. + **/ + function executeTransition(element: HTMLElement, transition: any): Promise; + + /** + * Retrieves the items in the specified index range. + * @param dataSource The data source that contains the items to retrieve. + * @param ranges An array of ISelectionRange objects that have firstIndex and lastIndex values. + * @returns A Promise that contains an array of the requested IItem objects. + **/ + function getItemsFromRanges(dataSource: IListDataSource, ranges: ISelectionRange[]): Promise>; + + /** + * Determines whether the Animations Library and ListView animations will be performed if called. + * @returns Returns true if animations will be performed; otherwise false. + **/ + function isAnimationEnabled(): boolean; + + /** + * Applies declarative control binding to all elements, starting at the specified root element. + * @param rootElement The element at which to start applying the binding. If this parameter is not specified, the binding is applied to the entire document. + * @param skipRoot If true, the elements to be bound skip the specified root element and include only the children. + * @returns A promise that is fulfilled when binding has been applied to all the controls. + **/ + function processAll(rootElement?: Element, skipRoot?: boolean): Promise; + + /** + * Applies declarative control binding to the specified element. + * @param element The element to bind. + * @returns A promise that is fulfilled after the control is activated. The value of the promise is the control that is attached to element. + **/ + function process(element: Element): Promise; + + /** + * Walks the DOM tree from the given element to the root of the document. Whenever a selector scope is encountered, this method performs a lookup within that scope for the specified selector string. The first matching element is returned. + * @param selector The selector string. + * @param element The element to begin walking to the root of the document from. + * @returns The target element, if found. + **/ + function scopedSelect(selector: string, element: HTMLElement): HTMLElement; + + /** + * Adds the set of declaratively specified options (properties and events) to the specified control. If name of the options property begins with "on", the property value is a function and the control supports addEventListener. setControl calls addEventListener on the control. + * @param control The control on which the properties and events are to be applied. + * @param options The set of options that are specified declaratively. + **/ + function setOptions(control: any, options?: any): void; + + //#endregion Functions + +} +/** + * Provides functions to load HTML content programmatically. +**/ +declare module WinJS.UI.Fragments { + //#region Functions + + /** + * Starts loading the fragment at the specified location. The returned promise completes when the fragment is ready to be copied. + * @param href The URI that contains the fragment to be copied. + * @returns A promise that is fulfilled when the fragment has been prepared for copying. + **/ + function cache(href: string): Promise; + + /** + * Removes any cached information about the specified fragment. This method does not unload any scripts or styles that are referenced by the fragment. + * @param href The URI that contains the fragment to be cleared. If no URI is provided, the entire contents of the cache are cleared. + **/ + function clearCache(href: string): void; + + /** + * Loads the contents of the specified URI into the specified element without copying it. + * @param href The URI that contains the fragment to copy. + * @param element Optional. The element to which the fragment is appended. + * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The element is not added to the cache. See also rendercopy, where the element is added to the cache. + **/ + function render(href: string, element?: HTMLElement): Promise; + + /** + * Loads and copies the contents of the specified URI into the specified element. + * @param href The URI that contains the fragment to copy. + * @param target The element to which the fragment is appended. + * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The fragment is added to the cache. See also render, where the element is not added to the cache. + **/ + function renderCopy(href: string, target?: HTMLElement): Promise; + + //#endregion Functions + +} +/** + * Provides methods for defining and displaying PageControl objects. +**/ +declare module WinJS.UI.Pages { + //#region Interfaces + + /** + * Provides members for a PageControl. You implement this interface when defining a new PageControl. + **/ + interface IPageControlMembers { + //#region Methods + + /** + * Called if any error occurs during the processing of the page. + * @param err The error that occurred. + * @returns Nothing if the error was handled, or an error promise if the error was not handled. + **/ + error? (err: any): Promise; + + /** + * Initializes the control before the content of the control is set. Use the processed method for any initialization that should be done after the content of the control has been set. + * @param element The DOM element that will contain all the content for the page. + * @param options The options passed to the constructor of the page. + * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + init? (element: HTMLElement, options: any): Promise; + + /** + * Creates DOM objects from the content in the specified URI. This method is called after the PageControl is defined and before the init method is called. + * @param uri The URI from which to create DOM objects. + * @returns A promise whose fulfilled value is the set of unparented DOM objects. + **/ + load? (uri: string): Promise; + + /** + * Initializes the control after the content of the control is set. + * @param element The DOM element that will contain all the content for the page. + * @param options The options that are to be passed to the constructor of the page. + * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + processed? (element: HTMLElement, options: any): Promise; + + /** + * Called after all initialization and rendering is complete. At this time, the element is ready for use. + * @param element The DOM element that contains all the content for the page. + * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @returns A promise that is fulfilled when the element is ready for use, if asynchronous processing is necessary. If not, returns nothing. + **/ + ready? (element: HTMLElement, options: any): Promise; + + /** + * Takes the elements returned by the load method and attaches them to the specified element. + * @param element The DOM element to which the loadResult elements are appended. + * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @param loadResult A Promise that contains the elements returned from the load method. + **/ + render? (element: HTMLElement, options: any, loadResult: Promise): void; + + //#endregion Methods + + } + + //#endregion Interfaces + + //#region Objects + + /** + * A modular unit of HTML, CSS, and JavaScript that can be navigated to or used as a custom WinJS control. + **/ + class PageControl { + } + + //#endregion Objects + + //#region Functions + + /** + * Creates a new PageControl from the specified URI that contains the specified members. Multiple calls to this method for the same URI are allowed, and all members will be merged. + * @param uri The URI for the content that defines the page. + * @param members An object that defines the members that the control will have. + * @returns A constructor function that creates the PageControl. + **/ + function define(uri: string, members: IPageControlMembers): PageControl; + + /** + * Gets an already-defined page control for the specified URI, or creates a new one. + * @param uri The URI for the content that defines the page. + * @returns A constructor function that creates the page. + **/ + function get(uri: string): Function; + + /** + * Creates a PageControl from the specified URI and inserts it inside the specified element. + * @param uri The URI for the content that defines the page. + * @param element The DOM element to which the PageControl is appended. + * @param options An object that contains one or more property/value pairs to apply to the new PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @param parentedPromise A Promise that is fulfilled when the new PageControl is done rendering and its contents becomes the child of element. + * @returns A promise that is fulfilled when rendering is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + function render(uri: string, element: HTMLElement, options?: any, parentedPromise?: Promise): Promise; + + //#endregion Functions + +} +/** + * Provides methods for detecting when the user tabs to or from DOM elements. +**/ +declare module WinJS.UI.TrackTabBehavior { + //#region Functions + + /** + * Sets the tab order for the specified element within its container. + * @param element The element to update. + * @param tabIndex The index value of the element within its container. + **/ + function attach(element: HTMLElement, tabIndex: number): void; + + /** + * Removes the tab order information from the specified element. + * @param element The element to remove tab information from. + **/ + function detatch(element: HTMLElement): void; + + //#endregion Functions + +} +/** + * Provides helper functions, for example, functions to add and remove CSS classes. +**/ +declare module WinJS.Utilities { + //#region Enumerations + + /** + * Defines a set of keyboard values. + **/ + enum Key { + /** + * The BACKSPACE key. + **/ + backspace, + /** + * The TAB key. + **/ + tab, + /** + * The ENTER key. + **/ + enter, + /** + * The SHIFT key. + **/ + shift, + /** + * The CTRL key. + **/ + ctrl, + /** + * The ALT key. + **/ + alt, + /** + * The PAUSE key. + **/ + pause, + /** + * The CAPS LOCK key. + **/ + capsLock, + /** + * The ESCAPE key. + **/ + escape, + /** + * The SPACE key. + **/ + space, + /** + * The PAGE UP key. + **/ + pageUp, + /** + * The PAGE DOWN key. + **/ + pageDown, + /** + * The END key. + **/ + end, + /** + * The HOME key. + **/ + home, + /** + * The LEFT ARROW key. + **/ + leftArrow, + /** + * The UP ARROW key. + **/ + upArrow, + /** + * The RIGHT ARROW key. + **/ + rightArrow, + /** + * The DOWN ARROW key. + **/ + downArrow, + /** + * The INSERT key. + **/ + insert, + /** + * The DELETE key. + **/ + deleteKey, + /** + * The 0 key. + **/ + num0, + /** + * The 1 key. + **/ + num1, + /** + * The 2 key. + **/ + num2, + /** + * The 3 key. + **/ + num3, + /** + * The 4 key. + **/ + num4, + /** + * The 5 key. + **/ + num5, + /** + * The 6 key. + **/ + num6, + /** + * The 7 key. + **/ + num7, + /** + * The 8 key. + **/ + num8, + /** + * The 9 key. + **/ + num9, + /** + * The a key. + **/ + a, + /** + * The b key. + **/ + b, + /** + * The c key. + **/ + c, + /** + * The d key. + **/ + d, + /** + * The e key. + **/ + e, + /** + * The f key. + **/ + f, + /** + * The g key. + **/ + g, + /** + * The h key. + **/ + h, + /** + * The i key. + **/ + i, + /** + * The j key. + **/ + j, + /** + * The k key. + **/ + k, + /** + * The l key. + **/ + l, + /** + * The m key. + **/ + m, + /** + * The n key. + **/ + n, + /** + * The o key. + **/ + o, + /** + * The p key. + **/ + p, + /** + * The q key. + **/ + q, + /** + * The r key. + **/ + r, + /** + * The s key. + **/ + s, + /** + * The t key. + **/ + t, + /** + * The u key. + **/ + u, + /** + * The v key. + **/ + v, + /** + * The w key. + **/ + w, + /** + * The x key. + **/ + x, + /** + * The y key. + **/ + y, + /** + * The z key. + **/ + z, + /** + * The left Windows key. + **/ + leftWindows, + /** + * The right Windows key. + **/ + rightWindows, + /** + * The menu key. + **/ + menu, + /** + * The 0 key on the numerical keypad. + **/ + numPad0, + /** + * The 1 key on the numerical keypad. + **/ + numPad1, + /** + * The 2 key on the numerical keypad. + **/ + numPad2, + /** + * The 3 key on the numerical keypad. + **/ + numPad3, + /** + * The 4 key on the numerical keypad. + **/ + numPad4, + /** + * The 5 key on the numerical keypad. + **/ + numPad5, + /** + * The 6 key on the numerical keypad. + **/ + numPad6, + /** + * The 7 key on the numerical keypad. + **/ + numPad7, + /** + * The 8 key on the numerical keypad. + **/ + numPad8, + /** + * The 9 key on the numerical keypad. + **/ + numPad9, + /** + * The multiplication key (*). + **/ + multiply, + /** + * The addition key (+). + **/ + add, + /** + * The subtraction key (-). + **/ + subtract, + /** + * The decimal point key (.) + **/ + decimalPoint, + /** + * The division key (/). + **/ + divide, + /** + * The F1 key. + **/ + F1, + /** + * The F2 key. + **/ + F2, + /** + * The F3 key. + **/ + F3, + /** + * The F4 key. + **/ + F4, + /** + * The F5 key. + **/ + F5, + /** + * The F6 key. + **/ + F6, + /** + * The F7 key. + **/ + F7, + /** + * The F8 key. + **/ + F8, + /** + * The F9 key. + **/ + F9, + /** + * The F10 key. + **/ + F10, + /** + * The F11 key. + **/ + F11, + /** + * The F12 key. + **/ + F12, + /** + * The NUMBER LOCK key. + **/ + numLock, + /** + * The SCROLL LOCK key. + **/ + scrollLock, + /** + * The browser BACK key. + **/ + browserBack, + /** + * The browser FORWARD key. + **/ + browserForward, + /** + * The semicolon key (;). + **/ + semicolon, + /** + * The equals key (=). + **/ + equal, + /** + * The comma key (,). + **/ + comma, + /** + * The dash key (-). + **/ + dash, + /** + * The period key (.). + **/ + period, + /** + * The forward slash key (/). + **/ + forwardSlash, + /** + * The grave accent key (`). + **/ + graveAccent, + /** + * The open bracket key ([). + **/ + openBracket, + /** + * The backslash key (\). + **/ + backSlash, + /** + * The close bracket key (]). + **/ + closeBracket, + /** + * The single quote key ('). + **/ + singleQuote + } + + //#endregion Enumerations + + //#region Objects + + /** + * A mixin that contains event-related functions. + **/ + var eventMixin: { + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture If true, initiates capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true if capture is to be initiated, otherwise false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + }; + + /** + * Represents the result of a query selector, and provides various operations that perform actions over the elements of the collection. + **/ + interface QueryCollection extends Array { + //#region Methods + + /** + * Adds the specified class to all the elements in the collection. + * @param name The name of the class to add. + * @returns This QueryCollection object. + **/ + addClass(name: string): QueryCollection; + + /** + * Creates a QueryCollection that contains the children of the specified parent element. + * @param element The parent element. + * @returns The QueryCollection that contains the children of the element. + **/ + children(element: HTMLElement): QueryCollection; + + /** + * Clears the specified style property for all the elements in the collection. + * @param name The name of the style property to be cleared. + * @returns This QueryCollection object. + **/ + clearStyle(name: string): QueryCollection; + + /** + * Creates controls that are attached to the elements in this QueryCollection, if the ctor parameter is a function, or configures the controls that are attached to the elements in this QueryCollection, if the ctor parameter is an object. + * @param ctor If this parameter is a function, it is a constructor function that is used to create controls to attach to the elements. If it is an object, it is the set of options passed to the controls. + * @param options The options passed to the newly-created controls. + * @returns This QueryCollection object. + **/ + control(ctor: any, options?: any): QueryCollection; + + /** + * Performs an action on each item in the QueryCollection. + * @param callbackFn The action to perform on each item. + * @param thisArg The argument to bind to callbackFn. + * @returns The QueryCollection. + **/ + forEach(callbackFn: (value: T, index: number, array: T[]) => void, thisArg?: any): QueryCollection; + + /** + * Gets an item from the QueryCollection. + * @param index The index of the item to return. + * @returns A single item from the collection. + **/ + get(index: number): T; + + /** + * Gets an attribute value from the first element in the collection. + * @param name The name of the attribute. + * @returns The value of the attribute. + **/ + getAttribute(name: string): any; + + /** + * Determines whether the specified class exists on the first element of the collection. + * @param name The name of the class. + * @returns true if the element has the specified class; otherwise, false. + **/ + hasClass(name: string): boolean; + + /** + * Looks up an element by ID and wraps the result in a QueryCollection. + * @param id The ID of the element. + * @returns A QueryCollection that contains the element, if it is found. + **/ + id(id: string): QueryCollection; + + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: T): void; + + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: T[]): void; + + /** + * Registers the listener for the specified event on all the elements in the collection. + * @param eventType The name of the event. + * @param listener The event handler function to be called when the event occurs. + * @param capture true if capture == true is to be passed to addEventListener; otherwise, false. + **/ + listen(eventType: string, listener: Function, capture?: boolean): void; + + /** + * Executes a query selector on all the elements in the collection and aggregates the result into a QueryCollection. + * @param query The query selector string. + * @returns A QueryCollection object containing the aggregate results of executing the query on all the elements in the collection. + **/ + query(query: any): QueryCollection; + + /** + * Removes the specified class from all the elements in the collection. + * @param name The name of the class to be removed. + * @returns his QueryCollection object. + **/ + removeClass(name: string): QueryCollection; + + /** + * Unregisters the listener for the specified event on all the elements in the collection. + * @param eventType The name of the event. + * @param listener The event handler function. + * @param capture true if capture == true; otherwise, false. + * @returns This QueryCollection object. + **/ + removeEventListener(eventType: string, listener: Function, capture?: boolean): QueryCollection; + + /** + * Sets an attribute value on all the items in the collection. + * @param name The name of the attribute to be set. + * @param value The value of the attribute to be set. + * @returns This QueryCollection object. + **/ + setAttribute(name: string, value: any): QueryCollection; + + /** + * Sets the specified style property for all the elements in the collection. + * @param name The name of the style property. + * @param value The value for the property. + * @returns This QueryCollection object. + **/ + setStyle(name: string, value: any): QueryCollection; + + /** + * Renders a template that is bound to the given data and parented to the elements included in the QueryCollection. If the QueryCollection contains multiple elements, the template is rendered multiple times, once at each element in the QueryCollection per item of data passed. + * @param templateElement The DOM element to which the template control is attached. + * @param data The data to render. If the data is an array (or any other object that has a forEach method) then the template is rendered multiple times, once for each item in the collection. + * @param renderDonePromiseCallback If supplied, this function is called each time the template gets rendered, and is passed a promise that is fulfilled when the template rendering is complete. + * @returns The QueryCollection. + **/ + template(templateElement: HTMLElement, data: any, renderDonePromiseCallback: Function): QueryCollection; + + /** + * Toggles (adds or removes) the specified class on all the elements in the collection. If the class is present, it is removed; if it is absent, it is added. + * @param name The name of the class to be toggled. + * @returns This QueryCollection object. + **/ + toggleClass(name: string): QueryCollection; + + //#endregion Methods + + } + + /** + * Constructor support for QueryCollection interface + **/ + export var QueryCollection: { + new (items: T[]): QueryCollection; + prototype: QueryCollection; + } + + //#endregion Objects + + //#region Functions + + /** + * Adds the specified class to the specified element. + * @param e The element to which to add the class. + * @param name The name of the class to add. + * @returns The element. + **/ + function addClass(e: T, name: string): T; + + /** + * Gets a collection of elements that are the direct children of the specified element. + * @param element The parent element. + * @returns The collection of children of the element. + **/ + function children(element: HTMLElement): QueryCollection; + + /** + * Converts a CSS positioning string for the specified element to pixels. + * @param element The element. + * @param value The CSS positioning string. + * @returns The number of pixels. + **/ + function convertToPixels(element: HTMLElement, value: string): number; + + /** + * Creates an object that has one event for each name passed to the function. + * @param events A variable list of property names. + * @returns The object with the specified properties. The names of the properties are prefixed with 'on'. + **/ + function createEventProperties(...events: string[]): any; + + /** + * Gets the data value associated with the specified element. + * @param element The element. + * @returns The value associated with the element. + **/ + function data(element: HTMLElement): any; + + /** + * Removes all the child nodes from the specified element. + * @param element The element. + * @returns The element. + **/ + function empty(element: T): T; + + /** + * Determines whether the specified event occurred within the specified element. + * @param element The element. + * @param event The event. + * @returns true if the event occurred within the element; otherwise, false. + **/ + function eventWithinElement(element: HTMLElement, event: Event): boolean; + + /** + * Adds tags and type to a logging message. + * @param message The message to be formatted. + * @param tag The tag(s) to be applied to the message. Multiple tags should be separated by spaces. + * @param type The type of the message. + * @returns The formatted message. + **/ + function formatLog(message: string, tag: string, type: string): string; + + /** + * Gets the height of the content of the specified element. The content height does not include borders or padding. + * @param element The element. + * @returns The content height of the element. + **/ + function getContentHeight(element: HTMLElement): number; + + /** + * Gets the width of the content of the specified element. The content width does not include borders or padding. + * @param element The element. + * @returns The content width of the element. + **/ + function getContentWidth(element: HTMLElement): number; + + /** + * Gets the leaf-level type or namespace specified by the name parameter. + * @param name The name of the member. + * @param root The root to start in. Defaults to the global object. + * @returns The leaf-level type or namespace in the specified parent namespace. + **/ + function getMember(name: string, root?: any): any; + + /** + * Gets the position of the specified element. + * @param element The element. + * @returns An object that contains the left, top, width and height properties of the element. + **/ + function getPosition(element: HTMLElement): IPosition; + + /** + * Gets the left coordinate of the specified element relative to the specified parent. + * @param element The element. + * @param parent The parent element. + * @returns The relative left coordinate. + **/ + function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number; + + /** + * Gets the top coordinate of the element relative to the specified parent. + * @param element The element. + * @param parent The parent element. + * @returns The relative top coordinate. + **/ + function getRelativeTop(element: HTMLElement, parent: HTMLElement): number; + + /** + * Gets the height of the element, including its margins. + * @param element The element. + * @returns The height of the element including margins. + **/ + function getTotalHeight(element: HTMLElement): number; + + /** + * Gets the width of the element, including margins. + * @param element The element. + * @returns The width of the element including margins. + **/ + function getTotalWidth(element: HTMLElement): number; + + /** + * Determines whether the specified element has the specified class. + * @param e The element. + * @param name The name of the class. + * @returns true if the element has the class, otherwise false. + **/ + function hasClass(e: HTMLElement, name: string): boolean; + + /** + * Returns a collection with zero or one elements matching the specified id. + * @param id The ID of the element (or elements). + * @returns A collection of elements whose id matches the id parameter. + **/ + function id(id: string): QueryCollection; + + /** + * Calls insertAdjacentHTML on the specified element. + * @param element The element on which insertAdjacentHTML is to be called. + * @param position The position relative to the element at which to insert the HTML. Possible values are: beforebegin, afterbegin, beforeend, afterend. + * @param text The text to insert. + **/ + function insertAdjacentHTML(element: HTMLElement, position: string, text: string): void; + + /** + * Calls insertAdjacentHTML on the specified element in the context of MSApp.execUnsafeLocalFunction. + * @param element The element on which insertAdjacentHTML is to be called. + * @param position The position relative to the element at which to insert the HTML. Possible values are: beforebegin, afterbegin, beforeend, afterend. + * @param text Value to be provided to insertAdjacentHTML. + **/ + function insertAdjacentHTMLUnsafe(element: HTMLElement, position: string, text: string): void; + + /** + * Marks a function as being compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. + * @param func The function to be marked as compatible with declarative processing. + * @returns The input function, marked as compatible with declarative processing. + **/ + function markSupportedForProcessing(func: U): U; + + /** + * Returns a QueryCollection with zero or one elements matching the specified selector query. + * @param query The CSS selector to use. See Selectors for more information. + * @param element Optional. The root element at which to start the query. If this parameter is omitted, the scope of the query is the entire document. + * @returns A QueryCollection with zero or one elements matching the specified selector query. + **/ + function query(query: any, element?: HTMLElement): QueryCollection; + + /** + * Ensures that the specified function executes only after the DOMContentLoaded event has fired for the current page. The DOMContentLoaded event occurs after the page has been parsed but before all the resources are loaded. + * @param callback A function that executes after the DOMContentLoaded event has occurred. + * @param async If true, the callback should be executed asynchronously. + * @returns A promise that completes after the DOMContentLoaded event has occurred. + **/ + function ready(callback?: Function, async?: boolean): Promise; + + /** + * Removes the specified class from the specified element. + * @param e The element from which to remove the class. + * @param name The name of the class to remove. + * @returns The element. + **/ + function removeClass(e: T, name: string): T; + + /** + * Asserts that the value is compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. If the value is not compatible, and strictProcessing is on, an exception is thrown. All functions that have been declared using WinJS.Class.define, WinJS.Class.derive, WinJS.UI.Pages.define, or WinJS.Binding.converter are automatically marked as supported for declarative processing. Any other function that you use from a declarative context (that is, a context in which an HTML element has a data-win-control or data-win-options attribute) must be marked manually by calling this function. When you mark a function as supported for declarative processing, you are guaranteeing that the code in the function is secure from injection of third-party content. + * @param value The value to be tested for compatibility with declarative processing. If the value is a function it must be marked with a property supportedForProcessing with a value of true when strictProcessing is on. For more information, see WinJS.Utilities.markSupportedForProcessing. + * @returns The input value. + **/ + function requireSupportedForProcessing(value: T): T; + + /** + * Sets the innerHTML property of the specified element to the specified text. + * @param element The element on which the innerHTML property is to be set. + * @param text The value to be set to the innerHTML property. + **/ + function setInnerHTML(element: HTMLElement, text: string): void; + + /** + * Sets the innerHTML property of the specified element to the specified text. + * @param element The element on which the innerHTML property is to be set. + * @param text The value to be set to the innerHTML property. + **/ + function setInnerHTMLUnsafe(element: HTMLElement, text: string): void; + + /** + * Sets the outerHTML property of the specified element to the specified text. + * @param element The element on which the outerHTML property is to be set. + * @param text The value to be set to the outerHTML property. + **/ + function setOuterHTML(element: HTMLElement, text: string): void; + + /** + * Sets the outerHTML property of the specified element to the specified text in the context of MSApp.execUnsafeLocalFunction. + * @param element The element on which the outerHTML property is to be set. + * @param text The value to be set to the outerHTML property. + **/ + function setOuterHTMLUnsafe(element: HTMLElement, text: string): void; + + /** + * Configures a logger that writes messages containing the specified tags to the JavaScript console. + * @param options The tags for messages to log. Multiple tags should be separated by spaces. May contain type, tags, excludeTags and action properties. + **/ + function startLog(options?: ILogOptions): void; + + /** + * Removes the WinJS logger that had previously been set up. + **/ + function stopLog(): void; + + /** + * Toggles (adds or removes) the specified class on the specified element. If the class is present, it is removed; if it is absent, it is added. + * @param e The element on which to toggle the class. + * @param name The name of the class to toggle. + * @returns The element. + **/ + function toggleClass(e: T, name: string): T; + + //#endregion Functions + + //#region Properties + + /** + * Gets whether the current script context has access to WinRT APIs. + **/ + var hasWinRT: boolean; + + //#endregion Properties + + //#region Interfaces + + interface ILogOptions { + type: string; + action?: (message: string, tags: string, type: string) => void; + excludeTags: string; + tags: string; + } + + interface IPosition { + left: number; + top: number; + width: number; + height: number; + } + + //#endregion Interfaces + +} From f222ca2768c8893c7546a78f765a3025f4cf8bf4 Mon Sep 17 00:00:00 2001 From: Sean Xu Date: Thu, 12 Jun 2014 16:56:57 -0700 Subject: [PATCH 008/324] Created 2.0 definitions file. Fixed a few removals from 1.0. --- winjs/legacy/winjs-1.0.d.ts | 19 + winjs/legacy/winjs-2.0.d.ts | 8554 +++++++++++++++++++++++++++++++++++ 2 files changed, 8573 insertions(+) create mode 100644 winjs/legacy/winjs-2.0.d.ts diff --git a/winjs/legacy/winjs-1.0.d.ts b/winjs/legacy/winjs-1.0.d.ts index 901e86e4b..0952b03fe 100644 --- a/winjs/legacy/winjs-1.0.d.ts +++ b/winjs/legacy/winjs-1.0.d.ts @@ -1326,6 +1326,14 @@ declare module WinJS { //#region Functions + /** + * You can provide an implementation of this method yourself, or use WinJS.Utilities.startLog to create one that logs to the JavaScript console. + * @param message The message to log. + * @param tags The tag or tags to categorize the message (winjs, winjs controls, etc.). + * @param type The type of message (error, warning, info, etc.). + **/ + function log(message: string, tags: string, type: string): void; + /** * This method has been deprecated. Strict processing is always on; you don't have to call this method to turn it on. **/ @@ -3181,6 +3189,12 @@ declare module WinJS.UI { **/ getPanAxis(): string; + /** + * Manages pointer input for the custom control. + * @param pointerId The ID of the pointer. + **/ + handlePointer(pointerId: string): void; + /** * Positions the specified item within the viewport of the child control when panning or zooming begins. * @param item The object to position within the viewport of the child control. item can be a number, a string, or an object with any number of properties. @@ -4910,6 +4924,11 @@ declare module WinJS.UI { **/ enableButton: boolean; + /** + * Determines whether any controls contained in a SemanticZoom should be processed separately. This property is always true, meaning that the SemanticZoom takes care of processing its own controls. + **/ + isDeclarativeControlContainer: boolean; + /** * Gets or sets a value that indicates whether SemanticZoom is locked and zooming between views is disabled. **/ diff --git a/winjs/legacy/winjs-2.0.d.ts b/winjs/legacy/winjs-2.0.d.ts new file mode 100644 index 000000000..b225ded94 --- /dev/null +++ b/winjs/legacy/winjs-2.0.d.ts @@ -0,0 +1,8554 @@ +// Type definitions for WinJS +// Project: http://msdn.microsoft.com/en-us/library/windows/apps/br229773.aspx +// Definitions by: TypeScript samples , Adam Hewitt , Craig Treasure +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +/** + * Defines an Element object. +**/ +interface Element { + winControl: any; // TODO: This should be control? +} + +/** + * Utility class for easy access to operations on application folders +**/ +interface IOHelper { + /** + * Determines whether the specified file exists in the folder. + * @param filename The name of the file. + * @returns A promise that completes with a value of either true (if the file exists) or false. + **/ + exists(filename: string): WinJS.Promise; + + /** + * Reads the specified file. If the file doesn't exist, the specified default value is returned. + * @param fileName The file to read from. + * @param def The default value to be returned if the file failed to open. + * @returns A promise that completes with a value that is either the contents of the file, or the specified default value. + **/ + readText(fileName: string, def?: string): WinJS.Promise; + + /** + * Deletes a file from the folder. + * @param fileName The file to be deleted. + * @returns A promise that is fulfilled when the file has been deleted. + **/ + remove(fileName: string): WinJS.Promise; + + /** + * Writes the specified text to the specified file. + * @param fileName The name of the file. + * @param text The content to be written to the file. + * @returns A promise that completes with a value that is the number of characters written. + **/ + writeText(fileName: string, text: string): WinJS.Promise; +} + +/** + * Provides application-level functionality, for example activation, storage, and application events. +**/ +declare module WinJS.Application { + //#region Objects + + /** + * The local storage of the application. + **/ + var local: IOHelper; + + /** + * The roaming storage of the application. + **/ + var roaming: IOHelper; + + /** + * The temp storage of the application. + **/ + var temp: IOHelper; + + /** + * An object used for storing app information that can be used to restore the app's state after it has been suspended and then resumed. Data that can usefully be contained in this object includes the current navigation page or any information the user has added to the input controls on the page. You should not add information about customization (for example colors) or user-defined lists of content. + **/ + var sessionState: any; + + //#endregion Objects + + //#region Methods + + /** + * Informs the application object that asynchronous work is being performed, and that this event handler should not be considered complete until the promise completes. This function can be set inside the handlers for all WinJS.Application events: onactivated oncheckpoint onerror onloaded onready onsettings onunload. + * @param promise The promise that should complete before processing is complete. + **/ + function setPromise(promise: Promise): void; + + //#endregion Methods + + //#region Functions + + /** + * Adds an event listener for application-level events: activated, checkpoint, error, loaded, ready, settings, and unload. + * @param type The type (name) of the event. You can use any of the following:"activated", "checkpoint", "error", "loaded", "ready", "settings", and" unload". + * @param listener The listener to invoke when the event is raised. + * @param capture true to initiate capture, otherwise false. + **/ + function addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Queues a checkpoint event. + **/ + function checkpoint(): void; + + /** + * Queues an event to be processed by the WinJS.Application event queue. + * @param eventRecord The event object is expected to have a type property that is used as the event name when dispatching on the WinJS.Application event queue. The entire object is provided to event listeners in the detail property of the event. + **/ + function queueEvent(eventRecord: any): void; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture Specifies whether or not to initiate capture. + **/ + function removeEventListener(type: string, listener: Function, useCapture?: any): void; + + /** + * Starts dispatching application events (the activated, checkpoint, error, loaded, ready, settings, and unload events). + **/ + function start(): void; + + /** + * Stops application event processing and resets WinJS.Application to its initial state. All WinJS.Application event listeners (for the activated, checkpoint, error, loaded, ready, settings, and unload events) are removed. + **/ + function stop(): void; + + //#endregion Functions + + //#region Events + + /** + * Occurs when WinRT activation has occurred. The name of this event is "activated" (and also "mainwindowactivated"). This event occurs after the loaded event and before the ready event. + * @param eventInfo An object that contains information about the event. For more information about event arguments, see the WinRT event argument classes: WebUICachedFileUpdaterActivatedEventArgs, WebUICameraSettingsActivatedEventArgs, WebUIContactPickerActivatedEventArgs, WebUIDeviceActivatedEventArgs, WebUIFileActivatedEventArgs, WebUIFileOpenPickerActivatedEventArgs, WebUIFileSavePickerActivatedEventArgs, WebUILaunchActivatedEventArgs, WebUIPrintTaskSettingsActivatedEventArgs, WebUIProtocolActivatedEventArgs, WebUISearchActivatedEventArgs, WebUIShareTargetActivatedEventArgs. + **/ + function onactivated(eventInfo: CustomEvent): void; + + /** + * Occurs when receiving PLM notification or when the checkpoint function is called. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following subproperties: type, setPromise. + **/ + function oncheckpoint(eventInfo: CustomEvent): void; + + /** + * Occurs when an unhandled error has been raised. + * @param eventInfo An object that contains information about the event. + **/ + function onerror(eventInfo: CustomEvent): void; + + /** + * Occurs after the DOMContentLoaded event, which fires after the page has been parsed but before all the resources are loaded. This event occurs before the activated event and the ready event. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following subproperties: type, setPromise. + **/ + function onloaded(eventInfo: CustomEvent): void; + + /** + * Occurs when the application is ready. This event occurs after the loaded event and the activated event. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following sub-properties: type, setPromise. + **/ + function onready(eventInfo: CustomEvent): void; + + /** + * Occurs when the settings charm is invoked. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: type, applicationcommands. + **/ + function onsettings(eventInfo: CustomEvent): void; + + /** + * Occurs when the application is about to be unloaded. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following sub-properties: type, setPromise. + **/ + function onunload(eventInfo: CustomEvent): void; + + //#endregion Events + +} +/** + * Provides functionality for data and template binding. +**/ +declare module WinJS.Binding { + //#region Properties + + /** + * Determines whether or not binding should automatically set the ID of an element. This property should be set to true in apps that use WinJS (WinJS) binding. + **/ + var optimizeBindingReferences: boolean; + + //#endregion Properties + + //#region Objects + + /** + * Allows you to add bindable properties dynamically. + **/ + var dynamicObservableMixin: { + //#region Methods + + /** + * Adds a property with change notification to this object, including a ECMAScript5 property definition. + * @param name The name of the property to add. + * @param value This object is returned. + **/ + addProperty(name: string, value: any): void; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns This object is returned. + **/ + bind(name: string, action: any): Function; + + /** + * Gets a property value by name. + * @param name The name of the property to get. + * @returns The value of the property as an observable object. + **/ + getProperty(name: string): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: string, oldValue: string): Promise; + + /** + * Removes a property value. + * @param name The name of the property to remove. + * @returns This object is returned. + **/ + removeProperty(name: string): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns This object is returned. + **/ + setProperty(name: string, value: any): any; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns A promise that completes when the notifications for this property change have been processed. If multiple notifications are coalesced, the promise may be canceled or the value of the promise may be updated. The fulfilled value of the promise is the new value of the property for which the notifications have been completed. + **/ + updateProperty(name: string, value: any): Promise; + + //#endregion Methods + + }; + + /** + * Do not instantiate. A list returned by the createFiltered method. + **/ + class FilteredListProjection extends ListProjection { + //#region Methods + + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value that was replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + //#endregion Methods + + //#region Properties + + /** + * The length of the list. Returns an integer value one higher than the highest element defined in an list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Do not instantiate. A list of groups. + **/ + class GroupsListProjection extends ListBase { + //#region Methods + + /** + * Gets a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Gets a key/data pair for the specified key. + * @param key The key of the value to retrieve. + * @returns An object with two properties: key and data. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + //#endregion Methods + + //#region Properties + + /** + * The length of the list. Returns an integer value one higher than the highest element defined in an list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Do not instantiate. Sorts the underlying list by group key and within a group respects the position of the item in the underlying list. Returned by createGrouped. + **/ + class GroupedSortedListProjection extends SortedListProjection { + //#region Properties + + /** + * Gets a List, which is a projection of the groups that were identified in this list. + **/ + groups: GroupsListProjection; + + //#endregion Properties + + } + + /** + * Represents a list of objects that can be accessed by index or by a string key. Provides methods to search, sort, filter, and manipulate the data. + **/ + class List extends ListBaseWithMutators { + //#region Constructors + + /** + * Creates a List object. + * @constructor + * @param list The array containing the elements to initalize the list. + * @param options You can set two Boolean options: binding and proxy. If options.binding is true, the list contains the result of calling as on the element values. If options.proxy is true, the list specified as the first parameter is used as the storage for the List. This option should be used with care, because uncoordinated edits to the data storage may result in errors. + **/ + constructor(list?: T[], options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Gets a key/data pair for the specified list index. + * @param index The index of value to retrieve. + * @returns An object with .key and .data properties. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Gets a key/data pair for the list item key specified. + * @param key The key of the value to retrieve. + * @returns An object with .key and .data properties. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Gets the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Moves the value at index to the specified position. + * @param index The original index of the value. + * @param newIndex The index of the value after the move. + **/ + move(index: number, newIndex: number): void; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Returns a list with the elements reversed. This method reverses the elements of a list object in place. It does not create a new list object during execution. + **/ + reverse(): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value that was replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + /** + * Returns a list with the elements sorted. This method sorts the elements of a list object in place. It does not create a new list object during execution. + * @param sortFunction The function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + **/ + sort(sortFunction: (left: T, right: T) => number): void; + + /** + * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the list from which to start removing elements. + * @param howMany The number of elements to remove. + * @param item The elements to insert into the list in place of the deleted elements. + * @returns The deleted elements. + **/ + splice(start: number, howMany?: number, ...item: T[]): T[]; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the length of the list, which is an integer value one higher than the highest element defined in the list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Represents a base class for lists. + **/ + class ListBase { + //#region Events + + /** + * An item in the list has changed its value. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, newItem, newValue, oldItem, oldValue. + **/ + onitemchanged(eventInfo: CustomEvent): void; + + /** + * A new item has been inserted into the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + oniteminserted(eventInfo: CustomEvent): void; + + /** + * An item has been changed locations in the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemmoved(eventInfo: CustomEvent): void; + + /** + * An item has been mutated. This event occurs as a result of calling the notifyMutated method. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemmutated(eventInfo: CustomEvent): void; + + /** + * An item has been removed from the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemremoved(eventInfo: CustomEvent): void; + + /** + * The list has been refreshed. Any references to items in the list may be incorrect. + * @param eventInfo An object that contains information about the event. The detail property of this object is null. + **/ + onreload(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture If true, initiates capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns A reference to this observableMixin object. + **/ + bind(name: string, action: Function): any; + + /** + * Returns a new list consisting of a combination of two arrays. + * @param item Additional items to add to the end of the list. + * @returns An array containing the concatenation of the list and any other supplied items. + **/ + concat(...item: T[]): T[]; + + /** + * Creates a live filtered projection over this list. As the list changes, the filtered projection reacts to those changes and may also change. + * @param predicate A function that accepts a single argument. The createFiltered function calls the callback with each element in the list. If the function returns true, that element will be included in the filtered list. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @returns A filtered projection over the list. + **/ + createFiltered(predicate: (x: T) => boolean): FilteredListProjection; + + /** + * Creates a live grouped projection over this list. As the list changes, the grouped projection reacts to those changes and may also change. The grouped projection sorts all the elements of the list to be in group-contiguous order. The grouped projection also contains a .groups property, which is a List representing the groups that were found in the list. + * @param groupKey A function that accepts a single argument. The function is called with each element in the list, the function should return a string representing the group containing the element. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @param groupData A function that accepts a single argument. The function is called once, on one element per group. It should return the value that should be set as the data of the .groups list element for this group. The data value usually serves as summary or header information for the group. + * @param groupSorter A function that accepts two arguments. The function is called with pairs of group keys found in the list. It must return one of the following numeric values: negative if the first argument is less than the second (sorted before), zero if the two arguments are equivalent, positive if the first argument is greater than the second (sorted after). + * @returns A grouped projection over the list. + **/ + createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter: (left: string, right: string) => number): GroupedSortedListProjection; + + /** + * Creates a live sorted projection over this list. As the list changes, the sorted projection reacts to those changes and may also change. + * @param sorter A function that accepts two arguments. The function is called with elements in the list. It must return one of the following numeric values: negative if the first argument is less than the second, zero if the two arguments are equivalent, positive if the first argument is greater than the second. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @returns A sorted projection over the list. + **/ + createSorted(sorter: (left: T, right: T) => number): SortedListProjection; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Checks whether the specified callback function returns true for all elements in a list. + * @param callback A function that accepts up to three arguments. This function is called for each element in the list until it returns false or the end of the list is reached. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns true if the callback returns true for all elements in the list. + **/ + every(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Returns the elements of a list that meet the condition specified in a callback function. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns An array containing the elements that meet the condition specified in the callback function. + **/ + filter(callback: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; + + /** + * Calls the specified callback function for each element in a list. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. The arguments are as follows: value, index, array. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + **/ + forEach(callback: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + + /** + * Gets the value at the specified index. + * @param index The index of the value to get. + * @returns The value at the specified index. + **/ + getAt(index: number): T; + + /** + * Gets the index of the first occurrence of the specified value in a list. + * @param searchElement The value to locate in the list. + * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + * @returns The index of the first occurrence of a value in a list or -1 if not found. + **/ + indexOf(searchElement: T, fromIndex?: number): number; + + /** + * Returns a string consisting of all the elements of a list separated by the specified separator string. + * @param separator A string used to separate the elements of a list. If this parameter is omitted, the list elements are separated with a comma. + * @returns The elements of a list separated by the specified separator string. + **/ + join(separator: string): string; + + /** + * Gets the index of the last occurrence of the specified value in a list. + * @param searchElement The value to locate in the list. + * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the list. + * @returns The index of the last occurrence of a value in a list, or -1 if not found. + **/ + lastIndexOf(searchElement: T, fromIndex: number): number; + + /** + * Calls the specified callback function on each element of a list, and returns an array that contains the results. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. + * @param thisArg n object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns An array containing the result of calling the callback function on each element in the list. + **/ + map(callback: (value: T, index: number, array: T[]) => G, thisArg?: any): G[]; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: any, oldValue: any): Promise; + + /** + * Forces the list to send a reload notification to any listeners. + **/ + notifyReload(): void; + + /** + * Accumulates a single result by calling the specified callback function for all elements in a list. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callback A function that accepts up to four arguments. These arguments are: previousValue, currentValue, currentIndex, array. The function is called for each element in the list. + * @param initiallValue If initialValue is specified, it is used as the value with which to start the accumulation. The first call to the function provides this value as an argument instead of a list value. + * @returns The return value from the last call to the callback function. + **/ + reduce(callback: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => T, initiallValue?: T): T; + + /** + * Accumulates a single result by calling the specified callback function for all elements in a list, starting with the last member of the list. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callback A function that accepts up to four arguments. These arguments are: previousValue, currentValue, currentIndex, array. The function is called for each element in the list. + * @param initialValue If initialValue is specified, it is used as the value with which to start the accumulation. The first call to the callback function provides this value as an argument instead of a list value. + * @returns The return value from the last call to callback function. + **/ + reduceRight(callback: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => T, initialValue?: T): T; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true if capture is to be initiated, otherwise false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Extracts a section of a list and returns a new list. + * @param begin The index that specifies the beginning of the section. + * @param end The index that specifies the end of the section. + * @returns Returns a section of list. + **/ + slice(begin: number, end: number): T[]; + + /** + * Checks whether the specified callback function returns true for any element of a list. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list until it returns true, or until the end of the list. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns true if callback returns true for any element in the list. + **/ + some(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + //#endregion Methods + + //#region Properties + + /** + * Gets the IListDataSource for the list. The only purpose of this property is to adapt a List to the data model that is used by ListView and FlipView. + **/ + dataSource: WinJS.UI.IListDataSource; + + /** + * Indicates that the object is compatibile with declarative processing. + **/ + static supportedForProcessing: boolean; + + //#endregion Properties + } + + /** + * Represents a base class for normal list modifying operations. + **/ + class ListBaseWithMutators extends ListBase { + //#region Methods + + /** + * Removes the last element from a list and returns it. + * @returns The last element from the list. + **/ + pop(): T; + + /** + * Appends new element(s) to a list, and returns the new length of the list. + * @param value The element to insert at the end of the list. + * @returns The new length of the list. + **/ + push(value: T): number; + + /** + * Removes the first element from a list and returns it. + * @returns The first element from the list. + **/ + shift(): T; + + /** + * Appends new element(s) to a list, and returns the new length of the list. + * @param value The element to insert at the start of the list. + * @returns The new length of the list. + **/ + unshift(value: T): number; + + //#endregion Methods + } + + /** + * Represents a base class for list projections. + **/ + class ListProjection extends ListBaseWithMutators { + //#region Methods + + /** + * Disconnects a WinJS.Binding.List projection from its underlying WinJS.Binding.List. It's only important to call this method when the WinJS.Binding.List projection and the WinJS.Binding.List have different lifetimes. (Call this method on the WinJS.Binding.List projection, not the underlying WinJS.Binding.List.) + **/ + dispose(): void; + + /** + * Gets a key/data pair for the specified key. + * @param key The key of the value to retrieve. + * @returns An object with two properties: key and data. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Moves the value at index to position newIndex. + * @param index The original index of the value. + * @param newIndex The index of the value after the move. + **/ + move(index: number, newIndex: number): void; + + /** + * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the list from which to start removing elements. + * @param howMany The number of elements to remove. + * @param item The elements to insert into the list in place of the deleted elements. + * @returns The deleted elements. + **/ + splice(start: number, howMany?: number, ...item: T[]): T[]; + + //#endregion Methods + } + + /** + * Provides a standard implementation of the bindable contract, as well as a basic storage mechanism that participates in change notification and an asynchronous notification implementation. + **/ + var mixin: { + //#region Methods + + /** + * Adds a property to the object. The property includes change notification and an ECMAScript 5 property definition . + * @param name The name of the property to add. + * @param value The value of the property. + * @returns This object is returned. + **/ + addProperty(name: string, value: any): any; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns This object is returned. + **/ + bind(name: string, action: any): Function; + + /** + * Gets a property value by name. + * @param name The name of the property to get. + * @returns The value of the property as an observable object. + **/ + getProperty(name: string): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: string, oldValue: string): Promise; + + /** + * Removes a property value. + * @param name The name of the property to remove. + * @returns This object is returned. + **/ + removeProperty(name: string): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns This object is returned. + **/ + setProperty(name: string, value: any): any; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns A promise that completes when the notifications for this property change have been processed. If multiple notifications are coalesced, the promise may be canceled or the value of the promise may be updated. The fulfilled value of the promise is the new value of the property for which the notifications have been completed. + **/ + updateProperty(name: string, value: any): Promise; + + //#endregion Methods + + }; + + /** + * Provides functions that can make an object observable. + **/ + var observableMixin: { + //#region Methods + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns A reference to this observableMixin object. + **/ + bind(name: string, action: Function): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: any, oldValue: any): Promise; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + //#endregion Methods + + }; + + /** + * Do not instantiate. Returned by the createSorted method. + **/ + class SortedListProjection extends ListProjection { + //#region Methods + + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value to be replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the length of the list. Returns an integer value one higher than the highest element defined in a list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Provides a reusable declarative binding element. + **/ + class Template { + //#region Constructors + + /** + * Creates a template that provides a reusable declarative binding element. + * @constructor + * @param element The DOM element to convert to a template. + * @param options If this parameter is supplied, the template is loaded from the URI and the content of the element parameter is ignored. You can add the following options: href. + **/ + constructor(element: HTMLElement, options?: string); + + //#endregion Constructors + + //#region Methods + + render: { + /** + * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. + **/ + (dataContext: any, container?: HTMLElement): Promise; + + /** + * Renders a template based on the specified URI (static method). + * @param href The URI from which to load the template. + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. + **/ + value(href: string, dataContext: any, container?: HTMLElement): Promise; + }; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the default binding initializer for the template. + **/ + bindingInitializer: any; + + /** + * Gets or sets a value that specifies whether a debug break is inserted into the first rendering of each template. This property only has an effect when the app is in debug mode. + **/ + debugBreakOnRender: boolean; + + /** + * This property is deprecated and might not be available in future versions of the WinJS. Gets or sets a value that specifies whether optimized template processing has been disabled. + **/ + disableOptimizedProcessing: boolean; + + /** + * Gets the DOM element that is used as the template. + **/ + element: HTMLElement; + + /** + * Gets a value that specifies whether templates should be instantiated without the creation of an additional child element. + **/ + extractChild: boolean; + + /** + * Determines whether the Template contains declarative controls that must be processed separately. This property is always true. The controls that belong to a Template object's children are instantiated when a Template instance is rendered. + **/ + isDeclarativeControlContainer: boolean; + + //#endregion Properties + + } + + //#endregion Objects + + //#region Functions + + /** + * Adds a CSS class from the specified path of the source object to a destination object. + * @param source The source object that has the class to copy. + * @param sourceProperties The path on the source object to the source class. + * @param dest The destination object. + **/ + function addClassOneTime(source: any, sourceProperties: any[], dest: HTMLElement): void; + + /** + * Returns an observable object. This may be an observable proxy for the specified object, an existing proxy, or the specified object itself if it directly supports observation. + * @param data The object to observe. + * @returns The observable object. + **/ + function as(data: U): U; + + /** + * Binds to one or more properties on the observable object or or on child values of that object. + * @param observable The object to bind to. + * @param bindingDescriptor An object literal containing the binding declarations. Binding declarations take the form: { propertyName: (function | bindingDeclaration), ... }. + * @returns An object that contains at least a "cancel" field, which is a function that removes all bindings associated with this bind request. + **/ + function bind(observable: any, bindingDescriptor: any): any; + + /** + * Creates a default binding initializer for binding between a source property and a destination property with the specified converter function that is executed on the value of the source property. + * @param convert The conversion function that takes the source property and produces a value that is set to the destination property. This function must be accessible from the global namespace. + * @returns The binding initializer. + **/ + function converter(convert: Function): Function; + + /** + * Creates a one-way binding between the source object and the destination object. Warning Do not attempt to bind data to the ID of an HTML element. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. + * @returns An object with a cancel method that is used to coalesce bindings. + **/ + function defaultBind(source: any, sourceProperties: any, dest: any, destProperties: any): any; + + /** + * Creates a new constructor function that supports observability with the specified set of properties. + * @param data The object to use as the pattern for defining the set of properties. + * @returns A constructor function with 1 optional argument that is the initial state of the properties. + **/ + function define(data: any): Function; + + /** + * Wraps the specified object so that all its properties are instrumented for binding. This is meant to be used in conjunction with the binding mixin. + * @param shape The specification for the bindable object. + * @returns An object with a set of properties all of which are wired for binding. + **/ + function expandProperties(shape: any): any; + + /** + * Marks a custom initializer function as being compatible with declarative data binding. + * @param customInitializer The custom initializer to be marked as compatible with declarative data binding. + * @returns The input customInitializer. + **/ + function initializer(customInitializer: Function): Function; + + /** + * Sets the destination property to the value of the source property. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. + * @returns An object with a cancel method that is used to coalesce bindings. + **/ + function oneTime(source: any, sourceProperties: any, dest: any, destProperties: any): any; + + /** + * Binds the values of an object to the values of a DOM element that has the data-win-bind attribute. If multiple DOM elements are to be bound, you must set the attribute on all of them. See the example below for details. + * @param rootElement Optional. The element at which to start traversing to find elements to bind to. If this parameter is omitted, the entire document is searched. + * @param dataContext The object that contains the values to which the DOM element should be bound. + * @param skipRoot If true, specifies that only the children of rootElement should be bound, otherwise rootElement should be bound as well. + * @param bindingCache The cached binding data. + * @param defaultInitializer The binding initializer to use in the case that one is not specified in a binding expression. If not provided, the behavior is the same as Binding.defaultBind. + * @returns A Promise that completes when every item that contains the data-win-bind attribute has been processed and the update has started. + **/ + function processAll(rootElement?: Element, dataContext?: any, skipRoot?: boolean, bindingCache?: any, defaultInitializer?: Function): Promise; + + /** + * Creates a one-way binding between the source object and an attribute on the destination element. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. This must be a single name. + * @returns An object with a cancel() method that is used to coalesce bindings. + **/ + function setAttribute(source: any, sourceProperties: any[], dest: Element, destProperties: any[]): any; + + /** + * Sets an attribute on the destination element to the value of the source property. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. This must be a single name. + **/ + function setAttributeOneTime(source: any, sourceProperties: any[], dest: Element, destProperties: any[]): void; + + /** + * Returns the original (non-observable) object is returned if the specified object is an observable proxy, + * @param data The object for which to retrieve the original value. + * @returns If the specified object is an observable proxy, the original object is returned, otherwise the same object is returned. + **/ + function unwrap(data: any): any; + + //#endregion Functions + + //#region Interfaces + + interface IKeyDataPair { + key: string; + data: T; + } + + //#endregion Interfaces + +} +/** + * Provides helper functions for defining Classes. +**/ +declare module WinJS.Class { + //#region Functions + + /** + * Defines a class using the given constructor and the specified instance members. + * @param constructor A constructor function that is used to instantiate this type. + * @param instanceMembers The set of instance fields, properties, and methods made available on the type. + * @param staticMembers The set of static fields, properties, and methods made available on the type. + * @returns The newly-defined type. + **/ + function define(constructor: Function, instanceMembers?: any, staticMembers?: any): any; + + /** + * Creates a sub-class based on the specified baseClass parameter, using prototype inheritance. + * @param baseClass The type to inherit from. + * @param constructor A constructor function that is used to instantiate this type. + * @param instanceMembers The set of instance fields, properties, and methods to be made available on the type. + * @param staticMembers The set of static fields, properties, and methods to be made available on the type. + * @returns The newly-defined type. + **/ + function derive(baseClass: any, constructor: Function, instanceMembers?: any, staticMembers?: any): any; + + /** + * Defines a class using the given constructor and the union of the set of instance members specified by all the mixin objects. The mixin parameter list is of variable length. For more information, see Adding functionality with WinJS mixins. + * @param constructor A constructor function that will be used to instantiate this class. + * @param mixin An object declaring the set of instance members. The mixin parameter list is of variable length. + * @returns The newly defined class. + **/ + function mix(constructor: Function, ...mixin: any[]): any; + + //#endregion Functions + +} +/** + * The WinJS namespace provides special Windows Library for JavaScript functionality, including Promise and xhr. +**/ +declare module WinJS { + //#region Properties + + /** + * Can be set to show the results of a validation process. + **/ + var validation: boolean; + + //#endregion Properties + + //#region Objects + + /** + * An error object. + **/ + class ErrorFromName { + //#region Constructors + + /** + * Creates an Error object with the specified name and message properties. + * @constructor + * @param name The name of this error. The name is meant to be consumed programmatically and should not be localized. + * @param message The message for this error. The message is meant to be consumed by humans and should be localized. + **/ + constructor(name: string, message?: string); + + //#endregion Constructors + + } + + /** + * Provides a mechanism to schedule work to be done on a value that has not yet been computed. It is an abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. + **/ + class Promise { + //#region Constructors + + /** + * A promise provides a mechanism to schedule work to be done on a value that has not yet been computed. It is a convenient abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. + * @constructor + * @param init The function that is called during construction of the Promise that contains the implementation of the operation that the Promise will represent. This can be synchronous or asynchronous, depending on the nature of the operation. Note that placing code within this function does not automatically run it asynchronously; that must be done explicitly with other asynchronous APIs such as setImmediate, setTimeout, requestAnimationFrame, and the Windows Runtime asynchronous APIs. The init function is given three arguments: completeDispatch, errorDispatch, progressDispatch. This parameter is optional. + * @param onCancel The function to call if a consumer of this promise wants to cancel its undone work. Promises are not required to support cancellation. + **/ + constructor(init?: (completeDispatch: any, errorDispatch: any, progressDispatch: any) => void, onCancel?: Function); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when there is an error in processing a promise. + * @param eventInfo An object that contains information about the event. + **/ + onerror(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener for the promise. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event is raised. + * @param capture true to initiate capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Returns a promise that is fulfilled when one of the input promises has been fulfilled. + * @param value An array that contains Promise objects or objects whose property values include Promise objects. + * @returns A promise that on fulfillment yields the value of the input (complete or error). + **/ + static any(value: Promise[]): Promise; + + /** + * Returns a promise. If the object is already a Promise it is returned; otherwise the object is wrapped in a Promise. You can use this function when you need to treat a non-Promise object like a Promise, for example when you are calling a function that expects a promise, but already have the value needed rather than needing to get it asynchronously. + * @param value The value to be treated as a Promise. + * @returns The promise. + **/ + static as(value: U): Promise; + + /** + * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). + **/ + cancel(): void; + + /** + * Raises an event of the specified type and properties. + * @param type The type (name) of the event. + * @param details The set of additional properties to be attached to the event object. + * @returns true if preventDefault was called on the event; otherwise, false. + **/ + dispatchEvent(type: string, details: any): boolean; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + **/ + done(onComplete?: (value: T) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): void; + + /** + * Determines whether a value fulfills the promise contract. + * @param value A value that may be a promise. + * @returns true if the object conforms to the promise contract (has a then function), otherwise false. + **/ + static is(value: any): boolean; + + /** + * Creates a Promise that is fulfilled when all the values are fulfilled. + * @param values An object whose members contain values, some of which may be promises. + * @returns A Promise whose value is an object with the same field names as those of the object in the values parameter, where each field value is the fulfilled value of a promise. + **/ + static join(values: any): Promise; + + /** + * Removes an event listener from the control. + * @param eventType The type (name) of the event. + * @param listener The listener to remove. + * @param capture Specifies whether or not to initiate capture. + **/ + removeEventListener(eventType: string, listener: Function, capture?: boolean): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => Promise, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => Promise, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + + /** + * Performs an operation on all the input promises and returns a promise that has the shape of the input and contains the result of the operation that has been performed on each input. + * @param values A set of values (which could be either an array or an object) of which some or all are promises.. + * @param complete The function to be called if the promise is fulfilled with a value. This function takes a single argument, which is the fulfilled value of the promise. + * @param error The function to be called if the promise is fulfilled with an error. This function takes a single argument, which is the error value of the promise. + * @param progress The function to be called if the promise reports progress. This function takes a single argument, which is the data about the progress of the promise. Promises are not required to support progress. + * @returns A Promise that is the result of calling join on the values parameter. + **/ + static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): Promise; + + /** + * This method has two forms: WinJS.Promise.timeout(timeout) and WinJS.Promise.timeout(timeout, promise). WinJS.Promise.timeout(timeout) creates a promise that is completed asynchronously after the specified timeout, essentially wrapping a call to setTimeout within a promise. WinJS.Promise.timeout(timeout, promise) sets a timeout period for completion of the specified promise, automatically canceling the promise if it is not completed within the timeout period. + * @param timeout The timeout period in milliseconds. If this value is zero or not specified, msSetImmediate is called, otherwise setTimeout is called. + * @param promise Optional. A promise that will be canceled if it doesn't complete within the timeout period. + * @returns If the promise parameter is omitted, returns a promise that will be fulfilled after the timeout period. If the promise paramater is provided, the same promise is returned. + **/ + static timeout(timeout: number, promise?: Promise): Promise; + + /** + * Wraps a non-promise value in a promise. This method is like wrapError, which allows you to produce a Promise in error conditions, in that it allows you to return a Promise in success conditions. + * @param value Some non-promise value to be wrapped in a promise. + * @returns A promise that is successfully fulfilled with the specified value. + **/ + static wrap(value: U): Promise; + + /** + * Wraps a non-promise error value in a promise. You can use this function if you need to pass an error to a function that requires a promise. + * @param error A non-promise error value to be wrapped in a promise. + * @returns A promise that is in an error state with the specified value. + **/ + static wrapError(error: U): Promise; + + //#endregion Methods + + } + + //#endregion Objects + + //#region Functions + + /** + * You can provide an implementation of this method yourself, or use WinJS.Utilities.startLog to create one that logs to the JavaScript console. + * @param message The message to log. + * @param tags The tag or tags to categorize the message (winjs, winjs controls, etc.). + * @param type The type of message (error, warning, info, etc.). + **/ + function log(message: string, tags: string, type: string): void; + + /** + * This method has been deprecated. Strict processing is always on; you don't have to call this method to turn it on. + **/ + function strictProcessing(): void; + + /** + * Wraps calls to XMLHttpRequest in a promise. + * @param options The options that are applied to the XMLHttpRequest object, as follows: type, url, user, password, responseType, headers, data, customRequestInitializer. + * @returns A promise that returns the XMLHttpRequest object when it completes. + **/ + function xhr(options: IXHROptions): Promise; + + //#endregion Functions + + //#region Interfaces + + interface IXHROptions { + type?: string; + url: string; + user?: string; + password?: string; + headers?: any; + data: any; + responseType?: string; + } + + //#endregion Interfaces +} +/** + * Provides helper functions for defining namespaces. For more information, see Organizing your code with WinJS.Namespace. +**/ +declare module WinJS.Namespace { + //#region Functions + + /** + * Defines a new namespace with the specified name. For more information, see Organizing your code with WinJS.Namespace. + * @param name The name of the namespace. This could be a dot-separated name for nested namespaces. + * @param members The members of the new namespace. + * @returns The newly-defined namespace. + **/ + function define(name?: string, members?: any): any; + + /** + * Defines a new namespace with the specified name under the specified parent namespace. For more information, see Organizing your code with WinJS.Namespace. + * @param parentNamespace The parent namespace. + * @param name The name of the new namespace. + * @param members The members of the new namespace. + * @returns The newly-defined namespace. + **/ + function defineWithParent(parentNamespace?: any, name?: string, members?: any): any; + + //#endregion Functions + +} +/** + * Provides functionality for dealing with basic navigation, including the navigation stack. +**/ +declare module WinJS.Navigation { + //#region Properties + + /** + * Determines whether it is possible to navigate backwards. + **/ + var canGoBack: boolean; + + /** + * Determines if it is possible to navigate forwards. + **/ + var canGoForward: boolean; + + /** + * Gets or sets the navigation history. + **/ + var history: any; + + /** + * Gets or sets the current location. + **/ + var location: string; + + /** + * Gets or sets a user-defined object that represents the state associated with the current location. + **/ + var state: any; + + //#endregion Properties + + //#region Functions + + /** + * Adds an event listener to the control. + * @param eventType The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param capture If true, specifies that capture should be initiated, otherwise false. + **/ + function addEventListener(eventType: string, listener: Function, capture?: boolean): void; + + /** + * Navigates backwards. + * @param distance The number of entries to go back into the history. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful. + **/ + function back(distance?: number): Promise; + + /** + * Navigates forwards. + * @param distance The number of entries to go forward. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful. + **/ + function forward(distance?: number): Promise; + + /** + * Navigates to a location. + * @param location The location to navigate to. Generally the location is a string containing the URL, but it may be anything. + * @param initialState A user-defined object that represents the navigation state that may be accessed through state. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful (true if successful, otherwise false). + **/ + function navigate(location: any, initialState?: any): Promise; + + /** + * Removes an event listener from the control. + * @param eventType The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture Specifies whether or not to initiate capture. + **/ + function removeEventListener(eventType: string, listener: Function, useCapture?: boolean): void; + + //#endregion Functions + + //#region Events + + /** + * Occurs before navigation. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onbeforenavigate(eventInfo: CustomEvent): void; + + /** + * Occurs after navigation has taken place. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onnavigated(eventInfo: CustomEvent): void; + + /** + * Occurs when navigation is taking place. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onnavigating(eventInfo: CustomEvent): void; + + //#endregion Events + +} +/** + * Provides functions for accessing resources and localizing content. +**/ +declare module WinJS.Resources { + //#region Functions + + /** + * Registers an event handler for the specified event. Use this method to register for events that are related to resources, such as when the app's language, scale, or contrast changes. + * @param type The name of the event to handle. + * @param listener The listener (event handler function) to associate with the event. + * @param useCapture Set to true to register the listener for the capturing phase; otherwise, set to false to register the listener for the bubbling phase. + **/ + function addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The name of the event to raise. + * @param details The set of additional properties to attach to the event object. + **/ + function dispatchEvent(type: string, details: any): void; + + /** + * Retrieves the resource string that has the specified resource identifier. + * @param resourceId The resource ID of the string to retrieve. + * @returns An object that can contain these properties: value, empty, lang. + **/ + function getString(resourceId: string): { value: string; empty?: boolean; lang?: string; }; + + /** + * Processes data-win-res attributes on elements and replaces attributes and properties with resource strings. + * @param rootElement The element to process. The element and its child elements will be processed. If an element isn't specified, the entire document is processed. + **/ + function processAll(rootElement?: HTMLElement): void; + + /** + * Removes an event listener that the addEventListener method registered. + * @param type The name of the event that the event listener is registered for. + * @param listener The listener (event handler function) to remove. + * @param useCapture Set to true to remove the capturing phase listener; set to false to remove the bubbling phase listener. + **/ + function removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Functions + + //#region Events + + /** + * Occurs when the user changes the system's language or contrast, or the scale of the display, or when the user changes any of the items in the current context's qualifier values list. For more info about the current context's qualifier values list, see the Remarks section. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.qualifier, detail.changed. + **/ + function oncontextchanged(eventInfo: CustomEvent): void; + + //#endregion Events + +} +/** + * Provides access to the Windows animations. These functions provide developers with the ability to use animations in their custom controls that are consistent with animations used by Windows controls. +**/ +declare module WinJS.UI.Animation { + //#region Functions + + /** + * Creates an object that performs an animation that adds an item or items to a list. + * @param added Element or elements to add to the list. + * @param affected Element or elements affected by the added items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createAddToListAnimation(added: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that adds an item or items to a list of search results. + * @param added Element or elements to add to the list. + * @param affected Element or elements affected by the added items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createAddToSearchListAnimation(added: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that collapses a list. + * @param hidden Element or elements hidden as a result of the collapse. + * @param affected Element or elements affected by the hidden items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createCollapseAnimation(hidden: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that removes an item or items from a list. + * @param deleted Element or elements to delete from the list. + * @param remaining Element or elements affected by the removal of the deleted items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createDeleteFromListAnimation(deleted: any, remaining: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that removes an item or items from a list of search results. + * @param deleted Element or elements to delete from the list. + * @param remaining Element or elements affected by the removal of the deleted items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createDeleteFromSearchListAnimation(deleted: any, remaining: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that expands a list. + * @param revealed Element or elements revealed by the expansion. + * @param affected Element or elements affected by the newly revealed items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createExpandAnimation(revealed: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs a peek animation. + * @param element Element or elements involved in the peek. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createPeekAnimation(element: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that moves an item or items. + * @param element Element or elements involved in the reposition. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise object that completes when the animation is finished. + **/ + function createRepositionAnimation(element: any): IAnimationMethodResponse; + + /** + * Performs an animation that fades an item or items in, fading out existing items that occupy the same space. + * @param incoming Element or elements being faded in. + * @param outgoing Element or elements being replaced. + * @returns An object that completes when the animation has finished. + **/ + function crossFade(incoming: any, outgoing: any): Promise; + + /** + * Performs an animation when a dragged object is moved such that dropping it in that position would move other items. The potentially affected items are animated out of the way to show where the object would be dropped. + * @param target Element or elements that the dragged object would cause to be moved if it were dropped. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function dragBetweenEnter(target: any, offset: any): Promise; + + /** + * Performs an animation when a dragged object is moved away from items that it had previously involved in a dragBetweenEnter animation. The affected objects are animated back to their original positions. + * @param target Element or elements that the dragged object would no longer cause to be displaced, due to its moving away. This should be the same element or element collection passed as the target parameter in the dragBetweenEnter animation. + * @returns An object that completes when the animation is finished. + **/ + function dragBetweenLeave(target: any): Promise; + + /** + * Performs an animation when the user finishes dragging an object. + * @param dragSource Element or elements that were dragged. + * @param offset Initial offset from the drop point. The dropped object begins at the offset and animates to its final position at the drop point. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param affected Element or elements whose position the dropped object affects. Typically, this is all other items in a reorderable list. This should be the same element or element collection passed as the affected parameter in the dragSourceStart animation. + * @returns An object that completes when the animation is finished. + **/ + function dragSourceEnd(dragSource: any, offset: any, affected?: any): Promise; + + /** + * Performs an animation when the user begins to drag an object. + * @param dragSource Element or elements being dragged. + * @param affected Element or elements whose position is affected by the movement of the dragged object. Typically, this is all other items in a reorderable list. + * @returns An object that completes when the animation is finished. + **/ + function dragSourceStart(dragSource: any, affected?: any): Promise; + + /** + * Performs an animation that displays one or more elements on a page. + * @param incoming Element or elements that compose the incoming content. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function enterContent(incoming: any, offset: any, options?: any): Promise; + + /** + * Performs an animation that shows a new page of content, either when transitioning between pages in a running app or when displaying the first content in a newly launched app. + * @param element Element or an array of elements that represent the content. If element refers to an array of elements, the elements enter in array order. + * @param offset An initial offset where the element or elements begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function enterPage(element: any, offset: any): Promise; + + /** + * Performs an animation that hides one or more elements on a page. + * @param outgoing Element or elements that compose the outgoing content. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function exitContent(outgoing: any, offset: any): Promise; + + /** + * Performs an animation that dismisses the current page when transitioning between pages in an app. + * @param outgoing Element or elements that compose the outgoing page. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function exitPage(outgoing: any, offset: any): Promise; + + /** + * Performs an animation that fades an item or set of items into view. + * @param shown Element or elements being faded in. + * @returns An object that completes when the animation has finished. Use this object when subsequent actions need this animation to finish before they take place. + **/ + function fadeIn(shown: any): Promise; + + /** + * Performs an animation that fades an item or set of items out of view. + * @param hidden Element or elements being faded out. + * @returns An object that completes when the animation is finished. + **/ + function fadeOut(hidden: any): Promise; + + /** + * Performs an animation that hides edge-based user interface (UI). + * @param element Element or elements that are being hidden. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function hideEdgeUI(element: any, offset: any, options?: any): Promise; + + /** + * Performs an animation that hides a panel. + * @param element Element or elements that are being hidden. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function hidePanel(element: any, offset: any): Promise; + + /** + * Performs an animation that removes pop-up user interface (UI). + * @param element Element or elements that are being hidden. + * @returns An object that completes when the animation is finished. + **/ + function hidePopup(element: any): Promise; + + /** + * Performs an animation when a pointer is pressed on an object. + * @param element Element or elements on which the pointer is pressed. + * @returns An object that completes when the animation is finished. + **/ + function pointerDown(element: any): Promise; + + /** + * Performs an animation when a pointer is released. + * @param element Element or elements that the pointer was pressed on. + * @returns An object that completes when the animation is finished. + **/ + function pointerUp(element: any): Promise; + + /** + * Performs an animation that slides a narrow, edge-based user interface (UI) into view. + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function showEdgeUI(element: any, offset: any, options?: any): Promise; + + /** + * Performs an animation that slides a large panel user interface (UI) into view. + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function showPanel(element: any, offset: any): Promise; + + /** + * Performs an animation that displays a pop-up user interface (UI). + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function showPopup(element: any, offset: any): Promise; + + /** + * Performs a deselection animation in response to a swipe interaction. + * @param deselected Element or elements that become unselected. + * @param selection Element or elements that represent the selection, typically a check mark. + * @returns An object that completes when the animation is finished. + **/ + function swipeDeselect(deselected: any, selection: any): Promise; + + /** + * Performs an animation that reveals an item or items in response to a swipe interaction. + * @param target Element or elements being revealed. + * @param offset An initial offset where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function swipeReveal(target: any, offset: any): Promise; + + /** + * Performs a selection animation in response to a swipe interaction. + * @param selected Element or elements being selected. + * @param selection Element or elements that show that something is selected, typically a check mark. + * @returns An object that completes when the animation is finished. + **/ + function swipeSelect(selected: any, selection: any): Promise; + + /** + * Performs an animation that updates a badge. + * @param incoming Element or elements that comprise the new badge. + * @param offset Initial offsets where incoming animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function updateBadge(incoming: any, offset: any): Promise; + + //#endregion Functions + + //#region Interfaces + + interface IAnimationMethodResponse { + execute(): Promise; + } + + //#endregion Interfaces + +} +/** + * Provides controls and objects that manipulate data. +**/ +declare module WinJS.UI { + //#region Enumerations + + /** + * Specifies an icon that appears in an AppBarCommand object. + **/ + enum AppBarIcon { + previous, + next, + play, + pause, + edit, + save, + clear, + delete, + remove, + add, + cancel, + accept, + more, + redo, + undo, + home, + up, + forward, + right, + back, + left, + favorite, + camera, + settings, + video, + sync, + download, + mail, + find, + help, + upload, + emoji, + twopage, + leavechat, + mailforward, + clock, + send, + crop, + rotatecamera, + people, + closepane, + openpane, + world, + flag, + previewlink, + globe, + trim, + attachcamera, + zoomin, + bookmarks, + document, + protecteddocument, + page, + bullets, + comment, + mail2, + contactinfo, + hangup, + viewall, + mappin, + phone, + videochat, + switch, + contact, + rename, + pin, + musicinfo, + go, + keyboard, + dockleft, + dockright, + dockbottom, + remote, + refresh, + rotate, + shuffle, + list, + shop, + selectall, + orientation, + import, + importall, + browsephotos, + webcam, + pictures, + savelocal, + caption, + stop, + showresults, + volume, + repair, + message, + page2, + calendarday, + calendarweek, + calendar, + characters, + mailreplyall, + read, + link, + accounts, + showbcc, + hidebcc, + cut, + attach, + paste, + filter, + copy, + emoji2, + important, + mailreply, + slideshow, + sort, + manage, + allapps, + disconnectdrive, + mapdrive, + newwindow, + openwith, + contactpresence, + priority, + uploadskydrive, + gototoday, + font, + fontcolor, + contact2, + folder, + audio, + placeholder, + view, + setlockscreen, + settile, + cc, + stopslideshow, + permissions, + highlight, + disableupdates, + unfavorite, + unpin, + openlocal, + mute, + italic, + underline, + bold, + movetofolder, + likedislike, + dislike, + like, + alignright, + aligncenter, + alignleft, + zoom, + zoomout, + openfile, + otheruser, + admin, + street, + map, + clearselection, + fontdecrease, + fontincrease, + fontsize, + cellphone, + reshare, + tag, + repeatone, + repeatall, + outlinestar, + solidstar, + calculator, + directions, + target, + library, + phonebook, + memo, + microphone, + postupdate, + backtowindow, + fullscreen, + newfolder, + calendarreply, + unsyncfolder, + reporthacked, + syncfolder, + blockcontact, + switchapps, + addfriend, + touchpointer, + gotostart, + zerobars, + onebar, + twobars, + threebars, + fourbars, + scan, + preview + } + + /** + * Indicates whether the IListDataAdapter was able to provide a count. + **/ + enum CountResult { + /** + * Indicates no count is available. + **/ + unknown + } + + /** + * Indicates that the IListDataAdapter was unable to provide a count. + **/ + enum CountError { + /** + * An attempt to count items timed out. + **/ + noResponse + } + + /** + * Describes the status of an IListDataSource. + **/ + enum DataSourceStatus { + /** + * The IListDataSource is ready. + **/ + ready, + /** + * The IListDataSource is still loading. + **/ + waiting, + /** + * The IListDataSource failed to load. + **/ + failure + } + + /** + * Specifies the type of error that occurred during an edit operation on a IListDataSource or an IListDataAdapter. + **/ + enum EditError { + /** + * The edit operation timed out. + **/ + noResponse, + /** + * The data source cannot be written to. + **/ + notPermitted, + /** + * The item has changed. + **/ + noLongerMeaningful + } + + /** + * Specifies the type of error encountered when retrieving items from an IListDataAdapter. + **/ + enum FetchError { + /** + * The fetch operation timed out. + **/ + noResponse, + /** + * The specified item could not be located. + **/ + doesNotExist + } + + /** + * Specifies how group headers in a ListView respond to the tap interaction. + **/ + enum GroupHeaderTapBehavior { + /** + * The group is invoked. + **/ + invoke, + /** + * Nothing happens. + **/ + none + } + + /** + * Specifies the position of group headers relative to their items in a ListView. + **/ + enum HeaderPosition { + /** + * Group headers appear to the left of items. + **/ + left, + /** + * Group headers appear above items. + **/ + top + } + + /** + * Specifies that type of animation for which a contentanimating event was raised. + **/ + enum ListViewAnimationType { + /** + * The animation plays when the ListView is first displayed. + **/ + entrance, + /** + * The animation plays when the ListView is changing its content. + **/ + contentTransition + } + + /** + * Describes the type of object in a ListView. + **/ + enum ObjectType { + /** + * The object is a group header in the list. + **/ + groupHeader, + /** + * The object is an item in the list. + **/ + item + } + + /** + * Specifies the orientation of a control. + **/ + enum Orientation { + /** + * A horizontal layout. + **/ + horizontal, + /** + * A vertical layout. + **/ + vertical + } + + /** + * Specifies the selection mode of a ListView. + **/ + enum SelectionMode { + /** + * Items cannot be selected. + **/ + none, + /** + * A single item may be selected. + **/ + single, + /** + * Multiple items may be selected. Clicking additional items adds them to the selection. + **/ + multi + } + + /** + * Specifies whether elements are selected when the user performs a swipe interaction. + **/ + enum SwipeBehavior { + /** + * The swipe interaction selects the elements touched by the swipe. + **/ + select, + /** + * The swipe interaction does not change which elements are selected. + **/ + none + } + + /** + * Specifies how items in a ListView respond to the tap interaction. + **/ + enum TapBehavior { + /** + * The item is selected and invoked. + **/ + directSelect, + /** + * The item is selected if was not already selected, and its deselected if it was already selected. + **/ + toggleSelect, + /** + * The item is invoked but not selected. + **/ + invokeOnly, + /** + * Nothing happens. + **/ + none + } + + //#endregion Enumerations + + //#region Interfaces + + /** + * Contains items that were requested from an IListDataAdapter and provides some information about those items. + **/ + interface IFetchResult { + //#region Properties + + /** + * Gets or sets the index of the requested item in the IListDataAdapter object's data source. + **/ + absoluteIndex: number; + + /** + * Gets or sets a value that indicates whether this IFetchResult contains the last items at the end of the IListDataAdapter object's data source. + **/ + atEnd: boolean; + + /** + * Gets or sets a value that indicates whether this IFetchResult contains the first items at the beginning of the IListDataAdapter object's data source. + **/ + atStart: boolean; + + /** + * Gets or sets the items returned by the fetch operation. + **/ + items: T[]; + + /** + * Gets or sets the location of the requested item within the items array. + **/ + offset: number; + + /** + * Gets or sets the number of items in the IListDataAdapter object's underlying data source. + **/ + totalCount: number; + + //#endregion Properties + + } + + /** + * Represents an item in a list. + **/ + interface IItem { + //#region Properties + + /** + * Gets or sets the item's data. + **/ + data: T; + + /** + * Gets the group key for the item. This property is only available for items that belong to a grouped data source. + **/ + groupKey: string; + + /** + * Gets the temporary ID of the item. + **/ + handle: string; + + /** + * Gets the item's index in the IListDataSource. + **/ + index: number; + + /** + * Gets or sets the key the identifies the item. + **/ + key: string; + + //#endregion Properties + + } + + /** + * Provides a mechanism for retrieving IItem objects asynchronously. + **/ + interface IItemPromise { + //#region Events + + /** + * Occurs when there is an error in processing. + * @param eventInfo An object that contains information about the event. + **/ + onerror(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). + **/ + cancel(): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + **/ + done(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): void; + + /** + * Stops change notification tracking for the IItem that fulfills this IItemPromise. + **/ + release(): void; + + /** + * Begins change notification tracking for the IItem that fulfills this IItemPromise. + **/ + retain(): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function becomes the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the complete or error function. + **/ + then(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): IItemPromise; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the temporary ID of the IItem that fulfills this promise. + **/ + handle: string; + + /** + * Gets or sets the index of the IItem contained by this IItemPromise. + **/ + index: number; + + //#endregion Properties + + } + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. Represents a layout for the ListView. + **/ + interface ILayout { + //#region Methods + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param beginScrollPosition The first visible pixel in the ListView. For horizontal layouts, this is the x-coordinate of the pixel. For vertical layouts, this is the y-coordinate. + * @param wholeItem true if the item must be completely visible; otherwise, false if its ok for the item to be partially visible. Promise. + * @returns A Promise for the index of the first visible item at the specified point. + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param endScrollPosition The last visible pixel in the ListView. For horizontal layouts, this is the x-coordinate of the pixel. For vertical layouts, this is the y-coordinate. + * @param wholeItem true if the item must be completely visible; otherwise, false if its ok for the item to be partially visible. Promise. + * @returns A Promise for the index of the last visible item at the specified point. + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @returns A object that has these properties: animationPromise, newEndIndex. + **/ + endLayout(): any; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param itemIndex The index of the item. + * @returns A Promise that returns an object with these properties: left, top, contentWidth, contentHeight, totalWidth, totalHeight. + **/ + getItemPosition(itemIndex: number): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param itemIndex The data source index of the current item. + * @param element The element for the current item. + * @param keyPressed The key that was pressed. This function must check for the arrow keys (leftArrow, upArrow, rightArrow, downArrow), pageDown, and pageUp and determine which item the user navigated to. + * @returns A Promise that contains the index of the next item (This item becomes the current item). + **/ + getKeyboardNavigatedItem(itemIndex: number, element: HTMLElement, keyPressed: WinJS.Utilities.Key): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @returns A Promise that returns an object that has these properties: beginScrollPosition, endScrollPosition. + **/ + getScrollBarRange(): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param x The x-coordinate to test. + * @param y The y-coordinate to test. + **/ + hitTest(x: number, y: number): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param elements The elements that represent the items that were added. + **/ + itemsAdded(elements: HTMLElement[]): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + **/ + itemsMoved(): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param elements The elements that represent the items that were removed. + **/ + itemsRemoved(elements: HTMLElement[]): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param groupIndex The index of the group in the group data source. + * @param element The element to render for the group header. + **/ + layoutHeader(groupIndex: number, element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param itemIndex The index of the item in the data source. + * @param element The element to render for the item. + **/ + layoutItem(itemIndex: number, element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param element The element that represents a header in the data source. + **/ + prepareHeader(element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param element An element that represents an item in the data source. + **/ + prepareItem(element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param element The element being released. + **/ + releaseItem(element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + **/ + reset(): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param site The layout site for the layout. You can use this object to query the hosting ListView for info you might need to lay out items. + **/ + setSite(site: ILayoutSite): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param beginScrollPosition The starting pixel of the area to which the items are rendered. + * @param endScrollPosition The last pixel of the area to which the items are rendered. + * @param count The upper bound of the number of items to render. + * @returns A Promise that returns an object that has these properties: beginIndex, endIndex. + **/ + startLayout(beginScrollPosition: number, endScrollPosition: number, count: number): Promise; + + //#endregion Methods + + //#region Properties + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + **/ + horizontal: boolean; + + //#endregion Properties + + } + + /** + * Represents a layout for the ListView. + **/ + interface ILayout2 { + //#region Methods + + /** + * Called when the ListView finishes a drag operation. + **/ + dragLeave(): void; + + /** + * Called when the ListView initiates a drag operation. + * @param x The x-coordinate of the drag. + * @param y The y-coordinate of the drag. + * @param dragInfo An object that indicates whether the item is selected. + **/ + dragOver(x: number, y: number, dragInfo: number): void; + + /** + * Called when the ListView requests that the ILayout2 execute animations. + **/ + executeAnimations(): void; + + /** + * Determines the next item to receive keyboard focus. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + + /** + * Gets the item at the specified hit-test coordinates. These coordinates are absolute coordinates (they are not relative to the layout's content area). + * @param x The x-coordinate to test for. + * @param y The y-coordinate to test for. + * @returns An object that describes the item at the hit test coordinates. It has these properties: type, index. + **/ + hitTest(x: number, y: number): any; + + /** + * Sets the rendering site and specifies whether the layout supports groups. This method is called by the ListView to initialize the layout. + * @param site The rendering site for the layout. + * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. + **/ + initialize(site: ILayoutSite2, groupsEnabled: boolean): void; + + /** + * Retrieves the indexes of the items in the specified pixel range. + * @param firstPixel The first pixel the range of items falls between. + * @param lastPixel The last pixel the range of items falls between. + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * Performs a layout pass. + * @param tree A structure representing the layout tree that is returned from the ListView. + * @param changedRange An object that lists the index of the first item in the changed item range. This object has these properties: startIndex. + * @param modifiedItems An object that contains the old and new indexes of the items that have been modified in the tree. + * @param modifiedGroups An object that contains the old and new indexes of the group elements that have been modified in the tree. + * @returns A Promise that executes after layout is complete, or an object that contains two Promise objects: realizedRangeComplete, layoutComplete. + **/ + layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): any; + + /** + * Called when the ListView requests that the ILayout2 set up animations. + **/ + setupAnimations(): void; + + /** + * Releases resources that were obtained during the call to initialize. + **/ + uninitialize(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the orientation of the layout. + **/ + orientation: any; + + //#endregion Properties + + } + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayoutSite2 interface. Represents a rendering site for an ILayout. + **/ + interface ILayoutSite { + //#region Properties + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + animationsDisabled: boolean; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + itemSurface: HTMLElement; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + rtl: boolean; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + scrollbarPos: number; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + surface: HTMLElement; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + viewport: HTMLElement; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + viewportSize: any; + + //#endregion Properties + + } + + /** + * Represents a rendering site for an ILayout2. + **/ + interface ILayoutSite2 { + //#region Properties + + /** + * Gets the number of groups in the site. + **/ + groupCount: number; + + /** + * Gets the number of items in the site. + **/ + itemCount: Promise; + + /** + * Gets the pixel range of the realization area. + **/ + realizedRange: any; + + /** + * Gets the tree for use by an object that implements the ILayout2 interface. + **/ + tree: any; + + /** + * Gets the pixel range of visible items in the site. + **/ + visibleRange: any; + + //#endregion Properties + + } + + /** + * Retrieves items from a IListDataSource, enumerates the contents of a IListDataSource, and can optionally register for change notifications. + **/ + interface IListBinding { + //#region Methods + + /** + * Retrieves the current item. + * @returns An IItemPromise that contains the current item. If the cursor has moved past the start or end of the list, the promise completes with a value of null. If the current item has been moved or deleted, the promise returns an error. + **/ + current(): IItemPromise>; + + /** + * Gets the first item from the IListDataSource and makes it the current item. + * @returns An IItemPromise that contains the requested IItem. If the list is empty, the promise completes with a value of null. + **/ + first(): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified description and makes it the current item. + * @param description A domain-specific description, to be interpreted by the IListDataAdapter, that identifies the item to retrieve. + * @returns An IItemPromise that contains the requested IItem object. If the item wasn't found, the promise completes with a value of null. + **/ + fromDescription(description: string): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified index and makes it the current item. + * @param index A value greater than or equal to 0 that is the index of the item to retrieve. + * @returns An IItemPromise that contains the requested IItem. If the item wasn't found, the promise completes with a value of null. + **/ + fromIndex(index: number): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified key and makes it the current item. + * @param key The key that identifies the item to retrieve. This value must be a non-empty string. + * @param hints Domain-specific information that provides additional information to the IListDataAdapter to improve retrieval time. + * @returns An IItemPromise that contains the requested IItem. If they item couldn't be found, the promise completes with a value of null. + **/ + fromKey(key: string, hints?: any): IItemPromise>; + + /** + * Makes the specified IItem or IItemPromise the current item. + * @param item The IItem or IItemPromise that will become the current item. + * @returns An IItemPromise that contains the specified item, if it exists. If the specified item is not in the list, the promise completes with a value of null. + **/ + jumpToItem(item: IItem): IItemPromise>; + + /** + * Retrieves the last item in the IListDataSource and makes it the current item. + * @returns An IItemPromise that contains the requested IItem. f the list is empty, the promise completes with a value of null. + **/ + last(): IItemPromise>; + + /** + * Retrieves the item after the current item and makes it the current item. + * @returns An IItemPromise that contains the item after the current item. If the cursor moves past the end of the list, the promise completes with a value of null. + **/ + next(): IItemPromise>; + + /** + * Retrieves the item before the current item and makes it the current item. + * @returns An IItemPromise that contains the item before the current item. If the cursor moves past the start of the list, the promise completes with a value of null. + **/ + previous(): IItemPromise>; + + /** + * Releases resources, stops notifications, and cancels outstanding promises for all tracked items returned by this IListBinding. + **/ + release(): void; + + /** + * Creates a request to stop change notifications for the specified item. The change notifications stop when the number of releaseItem calls matches the number of IIItemPromise.retain calls. + * @param item The IItem or IItemPromise that should stop receiving notifications. + **/ + releaseItem(item: IItem): void; + + //#endregion Methods + + } + + /** + * Accesses data for an IListDataSource. + **/ + interface IListDataAdapter { + //#region Methods + + /** + * Overwrites the data of the specified item. + * @param key The key of the item to overwrite. + * @param newData The new data for the item. + * @param indexHint The index of the item, if known. + * @returns A Promise that returns null or undefined when the operation completes. + **/ + change(key: string, newData: T, indexHint: number): Promise; + + /** + * Gets the number of items in the IListDataAdapter object's data source. + * @returns A Promise that contains the number of items the IListDataAdapter contains, or an approximate value if the actual number is unknown. + **/ + getCount(): Promise; + + /** + * Inserts the specified data after the specified item. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @param previousKey The key of an item in the IListDataAdapter object's data source. The new data will be inserted after this item. + * @param previousIndexHint The index of the item to insert the new data after, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAfter(key: string, data: T, previousKey: string, previousIndexHint: number): Promise>; + + /** + * Adds the specified key and data to the end of the IListDataAdapter object's data source. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtEnd(key: string, data: T): Promise>; + + /** + * Adds the specified key and data to the beginning of the IListDataAdapter object's data source. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtStart(key: string, data: T): Promise>; + + /** + * Inserts the specified data before the specified item. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @param nextKey The key of an item in the IListDataAdapter object's data source. The new data will be inserted before this item. + * @param nextIndexHint The index of the item to insert the new data before, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertBefore(key: string, data: T, nextKey: string, nextIndexHint: number): Promise>; + + /** + * Retrieves the item that matches the specified description and also retrieves the specified number of items before and after the matched item. + * @param description A description of the item to locate. + * @param countBefore The number of items before the matched item to retrieve. + * @param countAfter The number of items after the matched item to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromDescription(description: string, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the specified number of items from the end of the IListDataAdapter object's data source. + * @param count The number of items to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromEnd(count: number): Promise>; + + /** + * Retrieves the item at the specified index and also retrieves the specified number of items before and after the selected item. + * @param index The index of the item to retrieve. + * @param countBefore The number of items to retrieve from before the selected item. + * @param countAfter The number of items to retrieve from after the selected item. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromIndex(index: number, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the item that has the specified key and also retrieves the specified number of items before and after the selected item. + * @param key The key of the item to retrieve. + * @param countBefore The number of items to retrieve from before the selected item. + * @param countAfter The number of items to retrieve from after the selected item. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromKey(key: string, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the specified number of items from the beginning of the IListDataAdapter object's data source. + * @param count The number of items to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromStart(count: number): Promise>; + + /** + * Returns a string representation of the specified item that can be used for comparisons. + * @param item The item for which to generate a signature. + * @returns The signature representation of the specified item. + **/ + itemSignature(item: IItem): string; + + /** + * Moves the specified item to just after another item. + * @param key A key of the item to move. + * @param previousKey The key of another item. The item to move will be moved to just after this item. + * @param indexHint The index of the item to move, if known. + * @param previousIndexHint The index to move the item after, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveAfter(key: string, previousKey: any, indexHint: string, previousIndexHint: number): Promise>; + + /** + * Moves the specified item to just before another item. + * @param key A key of the item to move. + * @param nextKey The key of another item. The item to move will be moved to just before this item. + * @param indexHint The index of the item to move, if known. + * @param nextIndexHint The index to move the item before, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveBefore(key: string, nextKey: any, indexHint: string, nextIndexHint: number): Promise>; + + /** + * Moves the specified item to the end of the IListDataAdapter object's data source. + * @param key The key for the item to move. + * @param indexHint The index of the item to move, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveToEnd(key: string, indexHint: number): Promise>; + + /** + * Moves the specified item to the beginning of the IListDataAdapter object's data source. + * @param key The key for the item to move. + * @param indexHint The index of the item to move, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveToStart(key: string, indexHint: number): Promise>; + + /** + * Removes the specified item from the IListDataAdapter object's data source. + * @param key The key of the item to remove. + * @param data The new data for the item. + * @param indexHint The index of the item. + * @returns A Promise that returns null or undefined when the operation completes. + **/ + remove(key: string, data: T, indexHint: number): Promise; + + /** + * Registers a notification handler. The IListDataAdapter uses the handler to notify listening objects when its data changes. + * @param notificationHandler The notification handler that the IListDataAdapter will use to provide change notifications. . + **/ + setNotificationHandler(notificationHandler: IListDataNotificationHandler): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether to use an object's identity to determine if an item has changed. + **/ + compareByIdentity: boolean; + + //#endregion Properties + + } + + /** + * Notifies clients when an IListDataAdapter object's data changes. + **/ + interface IListDataNotificationHandler { + //#region Methods + + /** + * Indicates the start of a notification batch. Objects that are listening for notifications should defer making updates until endNotifications is called. + **/ + beginNotifications(): void; + + /** + * Raises a notification that an item in the IListDataAdapter object's data source has changed. + * @param item The item that changed. + **/ + changed(item: IItem): void; + + /** + * Indicates the end of a notification batch. When the beginNotifications method is called, objects listening for notifications should defer making updates until endNotifications is called. + **/ + endNotifications(): void; + + /** + * Raises a notification that an item has been added to the IListDataAdapter object's data source. + * @param newItem The new item added to the IListDataAdapter object's data source. + * @param previousKey The key of the item that now precedes the new item, or null if the item was inserted at the start of the list. If nextKey is provided, this parameter may be null. + * @param nextKey The key of the item that now follows the new item, or null if the item was inserted at the end of the list. If previousKey is provided, this parameter may be null. + * @param index The index of the new item. + **/ + inserted(newItem: IItem, previousKey: string, nextKey: string, index?: number): void; + + /** + * Indicates that all previous data obtained from the IListDataAdapter is invalid and should be refreshed. + * @returns A Promise that completes when the data has been completely refreshed and all change notifications have been sent. + **/ + invalidateAll(): Promise; + + /** + * Raises a notification that an item was moved within the IListDataAdapter object's data source. + * @param item The item that was moved. + * @param previousKey The key of the item that now precedes the new item, or null if the item was moved to the beginning of the list. If nextKey is provided, this parameter may be null. + * @param nextKey The key of the item that now follows the new item, or null if the item was moved to the end of the list. If previousKey is provided, this parameter may be null. + * @param oldIndex The item's original index. + * @param newIndex The item's new index. + **/ + moved(item: IItem, previousKey: string, nextKey: string, oldIndex?: number, newIndex?: number): void; + + /** + * Reloads data from the IListDataAdapter. + **/ + reload(): void; + + /** + * Raises a notification that an item was removed from the IListDataAdapter object's data source. + * @param key The key of the item that was removed. + * @param index The index of the item that was removed. + **/ + removed(key: string, index?: number): void; + + //#endregion Methods + + } + + /** + * Provides access to a data source and enables you to bind, change, add, remove, and move items in that data source. + **/ + interface IListDataSource { + //#region Events + + /** + * Occurs when the status of the IListDataSource changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: status. + **/ + statuschanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Notifies the IListDataSource that a sequence of edits is about to begin. The IListDataSource will defer notifications until endEdits is called. + **/ + beginEdits(): void; + + /** + * Overwrites the data of the specified item. + * @param key The key for the item to replace. + * @param newData The new data for the item. + * @returns A Promise that contains the IItem that was updated or an EditError if an error was encountered. + **/ + change(key: string, newData: T): Promise>; + + /** + * Creates an IListBinding that can retrieve items from the IListDataSource, enumerate the contents of the IListDataSource object's data, and optionally register for change notifications. + * @param notificationHandler Enables the IListBinding to register for change notifications for individual items obtained from the IListDataSource. If you omit this parameter, change notifications won't be available. + * @returns The new IListBinding. + **/ + createListBinding(notificationHandler?: IListNotificationHandler): IListBinding; + + /** + * Notifies the IListDataSource that the batch of edits that began with the last beginEdits call has completed. The IListDataSource will submit notifications for any changes that occurred between the beginEdits and endEdits calls as a batch and resume normal change notifications. + **/ + endEdits(): void; + + /** + * Retrieves the number of items in the data source. + * @returns A Promise that provides a Number that is the number of items in the data source. + **/ + getCount(): Promise; + + /** + * Inserts a new item after another item. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @param previousKey The key for an item in the data source. The new item will be added after this item. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAfter(key: string, data: T, previousKey: string): Promise>; + + /** + * Adds an item to the end of the data source. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtEnd(key: string, data: T): Promise>; + + /** + * Adds an item to the beginning of the data source. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtStart(key: string, data: T): Promise>; + + /** + * Inserts an item before another item. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @param nextKey The key of an item in the data source. The new item will be inserted before this item. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertBefore(key: string, data: T, nextKey: string): Promise>; + + /** + * Indicates that all previous data obtained from the IListDataAdapter is invalid and should be refreshed. + * @returns A Promise that completes when the data has been completely refreshed and all notifications have been sent. + **/ + invalidateAll(): Promise; + + /** + * Retrieves the item that has the specified description. + * @param description Domain-specific information, to be interpreted by the IListDataAdapter, that describes the item to retrieve. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item wasn't found, the promise completes with a value of null. + **/ + itemFromDescription(description: any): Promise>; + + /** + * Retrieves the item at the specified index. + * @param index A value that is greater than or equal to zero that is the index of the item to retrieve. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item wasn't found, the promise completes with a value of null. + **/ + itemFromIndex(index: number): Promise>; + + /** + * Retrieves the item with the specified key. + * @param key The key of the item to retrieve. It must be a non-empty string. + * @param description Domain-specific information that IListDataAdapter can use to improve the retrieval time. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item was not found, the promise completes with a null value. + **/ + itemFromKey(key: string, description?: any): Promise>; + + /** + * Moves an item to just after another item. + * @param key The key that identifies the item to move. + * @param previousKey The key of another item in the data source. The item specified by the key parameter will be moved after this item. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveAfter(key: string, previousKey: string): Promise>; + + /** + * Moves an item before another item. + * @param key The key that identifies the item to move. + * @param nextKey The key of another item in the data source. The item specified by the key parameter will be moved before this item. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveBefore(key: string, nextKey: string): Promise>; + + /** + * Moves an item to the end of the data source. + * @param key The key that identifies the item to move. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveToEnd(key: string): Promise>; + + /** + * Moves the specified item to the beginning of the data source. + * @param key The key that identifies the item to move. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveToStart(key: string): Promise>; + + /** + * Removes the specified item from the data source. + * @param key The key that identifies the item to remove. + * @returns A Promise that contains nothing if the operation was successful or an EditError if an error was encountered. + **/ + remove(key: string): Promise>; + + //#endregion Methods + + } + + /** + * Used by an IListBinding to provide change notifications when items in a IListDataSource change. + **/ + interface IListNotificationHandler { + //#region Methods + + /** + * Indicates the start of a notification batch. Objects that are listening for notifications should defer making updates until endNotifications is called. + **/ + beginNotifications(): void; + + /** + * Indicates that an item changed. + * @param newItem The updated item. + * @param oldItem The original item. + **/ + changed(newItem: IItem, oldItem: IItem): void; + + /** + * Indicates that the number of items in the IListDataSource has changed. + * @param newCount The updated count. + * @param oldCount The original count. + **/ + countChanged(newCount: number, oldCount: number): void; + + /** + * Indicates the end of a notification batch. When the beginNotifications method is called, objects listening for notifications should defer making updates until endNotifications is called. + **/ + endNotifications(): void; + + /** + * Indicates that the index of an item changed. + * @param handle The temporary ID of the item. + * @param newIndex The new index. + * @param oldIndex The original index. + **/ + indexChanged(handle: string, newIndex: number, oldIndex: number): void; + + /** + * Indicates that an item was added to the IListDataSource. + * @param itemPromise A promise for the new IItem. + * @param previousHandle The temporary ID of the item that precedes the new item. + * @param nextHandle The temporary ID of the item that follows the new item. + **/ + inserted(itemPromise: IItemPromise, previousHandle: string, nextHandle: string): void; + + /** + * Indicates that an IItemPromise was fulfilled and that the item is now available. + * @param item The fulfilled item. + **/ + itemAvailable(item: IItem): void; + + /** + * Indicates that an item was moved. + * @param item A promise for the IItem that was moved. + * @param previousHandle The temporary ID of the item that now precedes the moved item. + * @param nextHandle The temporary ID of the item that now follows the moved item. + **/ + moved(item: IItemPromise, previousHandle: string, nextHandle: string): void; + + /** + * Indicates that an item was removed. + * @param handle The temporary ID of the item that was removed. + * @param mirage true if the item never actually existed; false if the item was actually present in the IListDataSource. + **/ + removed(handle: string, mirage: boolean): void; + + //#endregion Methods + + } + + /** + * Used by ListView's currentItem API + **/ + interface IListViewItem { + /** + * Gets or sets index of the ListView item. + **/ + index?: number; + + /** + * Gets or sets key of the ListView item. + **/ + key?: string; + + /** + * Gets or sets whether the ListView item is focused. + **/ + hasFocus?: boolean; + + /** + * Gets or sets whether the ListView item is focused and is showing its focus visual. + **/ + showFocus?: boolean; + } + + /** + * Represents a selection of ListView items. + **/ + interface ISelection { + //#region Methods + + /** + * Adds one or more items to the selection. + * @param items The indexes or keys of the items to add. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + add(items: any): Promise; + + /** + * Clears the selection. + * @returns A Promise that is fulfilled when the clear operation completes. + **/ + clear(): Promise; + + /** + * Returns the number of items in the selection. + * @returns The number of items in the selection. + **/ + count(): number; + + /** + * Returns a list of the indexes for the items in the selection. + * @returns The list of indexes for the items in the selection as an array of Number objects. + **/ + getIndices(): number[]; + + /** + * Returns an array that contains the items in the selection. + * @returns A Promise that contains an array of the requested IItem objects. + **/ + getItems(): Promise[]>; + + /** + * Gets an array of the index ranges for the selected items. + * @returns An array that contains an ISelectionRange object for each index range in the selection. + **/ + getRanges(): ISelectionRange[]; + + /** + * Returns a value that indicates whether the selection contains every item in the data source. + * @returns true if the selection contains every item in the data source; otherwise, false. + **/ + isEverything(): boolean; + + /** + * Removes the specified items from the selection. + * @param items The indexes or keys of the items to remove. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + remove(items: any): Promise; + + /** + * Adds all the items in the ListView to the selection. + **/ + selectAll(): void; + + /** + * Clears the current selection and replaces it with the specified items. + * @param items The indexes or keys of the items that make up the selection. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + set(items: any): Promise; + + //#endregion Methods + + } + + /** + * Represents a range of indexes or keys in an ISelection. + **/ + interface ISelectionRange { + //#region Properties + + /** + * Gets or sets the index of the first item in the range. + **/ + firstIndex: number; + + /** + * Gets or sets the key of the first item in the range. + **/ + firstKey: any; + + /** + * Gets or sets the index of the last item in the range. + **/ + lastIndex: number; + + /** + * Gets or sets of the key of the last item in the range. + **/ + lastKey: any; + + //#endregion Properties + + } + + /** + * Supports semantic zoom functionality by exposing a control as either the zoomed in or the zoomed out view of the SemanticZoom control. + **/ + interface IZoomableView { + //#region Methods + + /** + * Initiates semantic zoom on the custom control. + **/ + beginZoom(): void; + + /** + * Initializes the semantic zoom state for the custom control. + * @param isZoomedOut True if this is the zoomed out view; otherwise false. + * @param isCurrentView True if this is the current view; otherwise false. + * @param triggerZoom The function that manages semantic zoom behavior. Triggers a zoom in or zoom out if the control is the visible control. + * @param prefetchedPages The number of pages of content to pre-fetch for zooming. This value is dependent on the size of the semantic zoom container. More content can be displayed based on the zoom factor and the size of the container. + **/ + configureForZoom(isZoomedOut: boolean, isCurrentView: boolean, triggerZoom: Function, prefetchedPages: number): void; + + /** + * Terminates semantic zoom on the zoomed in or zoomed out child of the custom control. + * @param isCurrentView True if the control is the visible control; otherwise false. + **/ + endZoom(isCurrentView: boolean): void; + + /** + * Retrieves the current item of the zoomed in or zoomed out child of the custom control. + * @returns An object that represents the selected item. This return value must be a Promise for the following: item, position. + **/ + getCurrentItem(): Promise<{ item: T; position: Utilities.IPosition }>; + + /** + * Retrieves the panning axis of the zoomed-in or zoomed-out child of the custom control. + * @returns Identifies the panning axis of the child control. Implementation specific. + **/ + getPanAxis(): string; + + /** + * Manages pointer input for the custom control. + * @param pointerId The ID of the pointer. + **/ + handlePointer(pointerId: string): void; + + /** + * Positions the specified item within the viewport of the child control when panning or zooming begins. + * @param item The object to position within the viewport of the child control. item can be a number, a string, or an object with any number of properties. + * @param position An object that contains the position data of the item relative to the child control. position must be an object with four number properties: left, top, width, and height. These values specify a rectangle that is typically the bounding box of the current item, though the details are up to the control. The units of the position must be in pixels. And the coordinates must be relative to the top-left of the control viewport (which should occupy the same area as the semantic zoom viewport), except when in RTL mode. In RTL mode, return coordinates relative to the top-right off the control viewport. The rectangle is transformed from the coordinate system of one control to that of the other. + **/ + positionItem(item: T, position: Utilities.IPosition): void; + + /** + * Selects the item closest to the specified screen coordinates. + * @param x The x-coordinate in DIPs relative to the upper-left corner of the SemanticZoom viewport. + * @param y The y-coordinate in DIPs relative to the upper-left corner of the SemanticZoom viewport.. + **/ + setCurrentItem(x: number, y: number): void; + + //#endregion Methods + + } + + //#endregion Interfaces + + //#region Objects + + /** + * Represents an application toolbar for displaying commands. + **/ + class AppBar { + //#region Constructors + + /** + * Creates a new AppBar object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new AppBar. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs immediately after the AppBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Occurs after the AppBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Occurs before the AppBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Occurs before a hidden AppBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this AppBar. Call this method when the AppBar is no longer needed. After calling this method, the AppBar becomes unusable. + **/ + dispose(): void; + + /** + * Returns the AppBarCommand object identified by id. + * @param id The element idenitifier (ID) of the command to be returned. + * @returns The command identified by id. If multiple commands have the same ID, returns an array of all the commands matching the ID. + **/ + getCommandById(id: string): AppBarCommand; + + /** + * Hides the AppBar. + **/ + hide(): void; + + /** + * Hides the specified commands of the AppBar. + * @param commands The commands to hide. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. + **/ + hideCommands(commands: any[], immediate?: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the AppBar if it is not disabled. + **/ + show(): void; + + /** + * Shows the specified commands of the AppBar. + * @param commands The commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. + **/ + showCommands(commands: any[], immediate?: boolean): void; + + /** + * Shows the specified commands of the AppBar while hiding all other commands. + * @param commands The commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. + **/ + showOnlyCommands(commands: any[], immediate?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Sets the AppBarCommand objects that appear in the app bar. + **/ + commands: AppBarCommand[]; + + /** + * Gets or sets a value that indicates whether the AppBar is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the AppBar. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the AppBar is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the layout of the app bar contents. + **/ + layout: string; + + /** + * Gets or sets a value that specifies whether the AppBar appears at the top or bottom of the main view. + **/ + placement: string; + + /** + * Gets or sets a value that indicates whether the AppBar is sticky (won't light dismiss). If not sticky, the app bar dismisses normally when the user touches outside of the appbar. + **/ + sticky: boolean; + + //#endregion Properties + + } + + /** + * Represents a command to be displayed in an app bar. + **/ + class AppBarCommand { + //#region Constructors + + /** + * Creates a new AppBarCommand object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new AppBarCommand. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this AppBarCommand. Call this method when the AppBarCommand is no longer needed. After calling this method, the AppBarCommand becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that indicates whether the AppBarCommand is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the AppBarCommand. + **/ + element: HTMLElement; + + /** + * Adds an extra CSS class during construction. + **/ + extraClass: string; + + /** + * Gets or sets the HTMLElement with a 'content' type AppBarCommand that should receive focus whenever focus moves by the user pressing HOME or the arrow keys, from the previous AppBarCommand to this AppBarCommand. + **/ + firstElementFocus: HTMLElement; + + /** + * Gets or sets the Flyout object displayed by this command. The specified flyout is shown when the AppBarCommand's button is invoked. + **/ + flyout: Flyout; + + /** + * Gets or sets a value that indicates whether the AppBarCommand is hiding or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the icon of the AppBarCommand. + **/ + icon: string; + + /** + * Gets the element identifier (ID) of the command. + **/ + id: string; + + /** + * Gets or sets the label of the command. + **/ + label: string; + + /** + * Gets or sets the HTMLElement with a 'content' type AppBarCommand that should receive focus whenever focus moves by the user pressing END or the arrow keys, from the previous AppBarCommand to this AppBarCommand. + **/ + lastElementFocus: HTMLElement; + + /** + * Gets or sets the function to be invoked when the command is clicked. + **/ + onclick: Function; + + /** + * Gets the section of the app bar that the command is in. + **/ + section: string; + + /** + * Gets or sets the selected state of a toggle button. + **/ + selected: boolean; + + /** + * Gets or sets the tooltip of the command. + **/ + tooltip: string; + + /** + * Gets the type of the command. + **/ + type: string; + + //#endregion Properties + + } + + /** + * Provides backwards navigation in the form of a button. + **/ + class BackButton { + //#region Constructors + + /** + * Creates a new BackButton. + * @constructor + * @param element The DOM element hosts the new BackButton. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this BackButton. Call this method when the BackButton is no longer needed. After calling this method, the BackButton becomes unusable. + **/ + dispose(): void; + + /** + * Checks the current navigation history and updates the value of the control's disabled attribute. + **/ + refresh(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the HTML element that hosts this BackButton. + **/ + element: HTMLElement; + + //#endregion Properties + + } + + /** + * Represents a layout for the ListView in which items are arranged in a grid and items can span multiple grid cells. + **/ + class CellSpanningLayout { + //#region Constructors + + /** + * Creates a new CellSpanningLayout. + * @constructor + * @param options An object that contains one or more property/value pairs to apply to the new CellSpanningLayout. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragLeave(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragOver(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + executeAnimations(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate, or the horizontal position on the screen. + * @param y The y-coordinate, or the vertical position on the screen. + **/ + hitTest(x: number, y: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param site The rendering site for the layout. + * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. + **/ + initialize(site: ILayoutSite2, groupsEnabled: boolean): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param firstPixel The first pixel the range of items falls between. + * @param lastPixel The last pixel the range of items falls between. + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param tree + * @param changedRange + * @param modifiedItems + * @param modifiedGroups + **/ + layout(tree: ILayoutSite2, changedRange: any, modifiedItems: any, modifiedGroups: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + setupAnimations(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + uninitialize(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the position of group headers relative to their items. + **/ + groupHeaderPosition: WinJS.UI.HeaderPosition; + + /** + * Gets or sets a function that enables cell-spanning and establishes base cell dimensions. + **/ + groupInfo: Function; + + /** + * Gets or sets a function that returns the width and height of an item, as well as whether it should appear in a new column. Setting this function improves performance because the ListView can allocate space for an item without having to measure it first. + **/ + itemInfo: Function; + + /** + * Gets or set the maximum number of rows or columns, depending on the orientation, to display before content begins to wrap. + **/ + maximumRowsOrColumns: number; + + /** + * This API supports the Windows Library for JavaScript infrastructure and is not intended to be used directly from your code. + **/ + numberOfItemsPerItemsBlock: any; + + /** + * Gets the orientation of the CellSpanningLayout. For a CellSpanningLayout, this property always returns Orientation.horizontal. + **/ + orientation: WinJS.UI.Orientation; + + //#endregion Properties + + } + + /** + * Allows users to pick a date value. + **/ + class DatePicker { + //#region Constructors + + /** + * Initializes a new instance of the DatePicker control. + * @constructor + * @param element The DOM element associated with the DatePicker control. + * @param options The set of options to be applied initially to the DatePicker control. The options are the following: calendar, current, datePattern, disabled, maxYear, minYear, monthPattern, yearPattern. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when any of the controls are changed by the user. + * @param eventInfo An object that contains information about the event. + **/ + onchange(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener. + * @param type The type (name) of the event. + * @param listener The function that handles the event. + * @param capture If true, specifies that capture should be initiated, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this DatePicker. Call this method when the DatePicker is no longer needed. After calling this method, the DatePicker becomes unusable. + **/ + dispose(): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + raiseEvent(type: string, eventProperties: any): boolean; + + /** + * Removes a listener for the specified event. + * @param type The name of the event for which to remove a listener. + * @param listener The listener. + * @param useCapture Optional. The same value that was passed to addEventListener for this listener. It may be omitted if it was omitted when calling addEventListener. + **/ + removeEventListener(type: string, listener: Function, useCapture?: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the calendar to use. + **/ + calendar: string; + + /** + * Gets or sets the current date of the DatePicker. You can use either a date string or a Date object to set this property. + **/ + current: Date; + + /** + * Gets or sets the display pattern for the date. The default date pattern is day.integer(2). You can change the date pattern by changing the number of integers displayed. + **/ + datePattern: string; + + /** + * Specifies whether the DatePicker is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element for the DatePicker. + **/ + element: HTMLElement; + + /** + * Gets or sets the maximum Gregorian year available for picking. + **/ + maxYear: number; + + /** + * Gets or sets the minimum Gregorian year available for picking. + **/ + minYear: number; + + /** + * Gets or sets the display pattern for the month. The default month pattern is month.abbreviated. You can change the month pattern to the following values: month.full. The full name of the month. month.abbreviated(n). You can use abbreviated with or without specifying the number of letters in the abbreviation. If you do specify the number of letters, the actual length of the month name that appears may vary. month.solo.full. A representation of the month that is suitable for stand-alone display. You can also use month.solo.abbreviated(n). month.integer(n). You can use integer with or without specifying the number of integers. + **/ + monthPattern: string; + + /** + * Gets or sets the display pattern for the year. The default year pattern is year.full. You can change the year pattern to the following values: year.abbreviated(n). You can use abbreviated with or without specifying the number of letters in the abbreviation. + **/ + yearPattern: string; + + //#endregion Properties + + } + + /** + * Adds event-related methods to the control. + **/ + class DOMEventMixin { + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture true to initiate capture; otherwise, false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type, adding the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true to initiate capture; otherwise, false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Adds the set of declaratively specified options (properties and events) to the specified control. If the name of the options property begins with "on", the property value is a function and the control supports addEventListener. This method calls the addEventListener method on the control. + * @param control The control on which the properties and events are to be applied. + * @param options The set of options that are specified declaratively. + **/ + setOptions(control: any, options: any): void; + + //#endregion Methods + + } + + /** + * Displays a collection, such as a set of photos, one item at a time. + **/ + class FlipView { + //#region Constructors + + /** + * Creates a new FlipView. + * @constructor + * @param element The DOM element that hosts the control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the pageselected event, add a property named "onpageselected" and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the datasource count changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: source. + **/ + ondatasourcecountchanged(eventInfo: Event): void; + + /** + * Raised when the FlipView flips to a page and its renderer function completes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source. + **/ + onpagecompleted(eventInfo: CustomEvent): void; + + /** + * Raised when the FlipView flips to a page. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source. + **/ + onpageselected(eventInfo: CustomEvent): void; + + /** + * Occurs when an item becomes invisible or visible. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source, detail.visible. + **/ + onpagevisibilitychanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. For a list of events, see the FlipView object page. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Returns the number of items in the FlipView control's itemDataSource. + * @returns A Promise that contains the number of items in the list or WinJS.UI.CountResult.unknown if the count is unavailable. + **/ + count(): Promise; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this FlipView. Call this method when the FlipView is no longer needed. After calling this method, the FlipView becomes unusable. + **/ + dispose(): void; + + /** + * Forces the FlipView to update its layout. Use this function when making the FlipView visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Navigates to the next page. + * @returns true if the FlipView begins navigating to the next page; false if the FlipView is already at the last item or is in the middle of another navigation animation. + **/ + next(): boolean; + + /** + * Navigates to the previous item. + * @returns true if the FlipView begins navigating to the previous page; nfalse if the FlipView is already at the first page or is in the middle of another navigation animation. + **/ + previous(): boolean; + + /** + * Unregisters an event handler for the specified event. + * @param eventName The name of the event. + * @param eventHandler The event handler function to remove. + * @param useCapture Set to true to unregister the event handler for the capturing phase; otherwise, set to false to unregister the event handler for the bubbling phase. + **/ + removeEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Sets custom animations for the FlipView to use when navigating between pages. + * @param animations An object that contains up to three fields, one for each navigation action: next, previous, and jump. Each of those fields must be a function with this signature: function (outgoingPage, incomingPage) Each function must return a WinJS.Promise that completes once the animations are finished. If a field is null or undefined, the FlipView reverts to its default animation for that action. + **/ + setCustomAnimations(animations: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the index of the currently displayed page. + **/ + currentPage: number; + + /** + * Gets the HTML element that hosts this FlipView. + **/ + element: HTMLElement; + + /** + * Gets or sets the data source that provides the FlipView with items to display. The FlipView displays one item at a time, on its own page. + **/ + itemDataSource: IListDataSource; + + /** + * Gets or sets the spacing between each item, in pixels. + **/ + itemSpacing: number; + + /** + * Gets or sets a Template or function that defines the HTML for each item's page. + **/ + itemTemplate: any; + + /** + * Gets or sets the orientation of the FlipView, horizontal or vertical. + **/ + orientation: string; + + //#endregion Properties + + } + + /** + * Displays lightweight UI that is either information, or requires user interaction. Unlike a dialog, a Flyout can be light dismissed by clicking or tapping off of it. + **/ + class Flyout { + //#region Constructors + + /** + * Creates a new Flyout object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new Flyout. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised immediately after a flyout is fully hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Raised immediately after a flyout is fully shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Raised just before hiding a flyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Raised just before showing a flyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this object. Call this method when the object is no longer needed. After calling this method, the object becomes unusable. + **/ + dispose(): void; + + /** + * Hides the Flyout, if visible, regardless of other states. + **/ + hide(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the Flyout, if hidden, regardless of other states. + * @param anchor Required. The DOM element to anchor the Flyout. + * @param placement The placement of the Flyout to the anchor: the string literal "top", "bottom", "left", or "right". + * @param alignment For "top" or "bottom" placement, the alignment of the Flyout to the anchor's edge: the string literal "center", "left", or "right". + **/ + show(anchor: HTMLElement, placement: string, alignment: string): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the default alignment to be used for this Flyout. + **/ + alignment: string; + + /** + * Gets or sets the default anchor to be used for this Flyout. + **/ + anchor: HTMLElement; + + /** + * Gets the DOM element that hosts the Flyout. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the Flyout is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the default placement to be used for this Flyout. + **/ + placement: string; + + //#endregion Properties + + } + + /** + * Represents a grid layout for the ListView in which items are arranged in a horizontal grid. + **/ + class GridLayout { + //#region Constructors + + /** + * Creates a new GridLayout object. + * @constructor + * @param options The set of properties and values to apply to the new GridLayout. + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param wholeItem + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): void; + + /** + * This method is no longer supported. + * @param endScrollPosition + * @param wholeItem + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragLeave(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragOver(): void; + + /** + * This method is no longer supported. + **/ + endLayout(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + executeAnimations(): void; + + /** + * This method is no longer supported. + * @param itemIndex + **/ + getItemPosition(itemIndex: number): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element + * @param keyPressed + **/ + getKeyboardNavigatedItem(itemIndex: number, element: any, keyPressed: any): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPosition + **/ + getScrollbarRange(beginScrollPosition: number, endScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate, or the horizontal position on the screen. + * @param y The y-coordinate, or the vertical position on the screen. + **/ + hitTest(x: number, y: number): void; + + /** + * This method is no longer supported. + **/ + init(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param site The rendering site for the layout. + * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. + **/ + initialize(site: ILayoutSite2, groupsEnabled: boolean): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsAdded(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param firstPixel The first pixel the range of items falls between. + * @param lastPixel The last pixel the range of items falls between. + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * This method is no longer supported. + **/ + itemsMoved(): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsRemoved(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param tree + * @param changedRange + * @param modifiedItems + * @param modifiedGroups + **/ + layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): void; + + /** + * This method is no longer supported. + * @param groupIndex + * @param element A DOM element. + **/ + layoutHeader(groupIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + layoutItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param element + **/ + prepareHeader(element: HTMLElement): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + prepareItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param item + * @param newItem + **/ + releaseItem(item: any, newItem: any): void; + + /** + * This method is no longer supported. + **/ + reset(): void; + + /** + * This method is no longer supported. + * @param layoutSite + **/ + setSite(layoutSite: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + setupAnimations(): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPositionScrollPosition + **/ + startLayout(beginScrollPosition: number, endScrollPositionScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + uninitialize(): void; + + /** + * This method is no longer supported. + * @param count + **/ + updateBackdrop(count: number): void; + + //#endregion Methods + + //#region Properties + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + backdropColor: string; + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + disableBackdrop: boolean; + + /** + * Gets or sets the position of group headers. + **/ + groupHeaderPosition: WinJS.UI.HeaderPosition; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + groupInfo: Function; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use the orientation property instead. + **/ + horizontal: boolean; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + itemInfo: Function; + + /** + * Gets or set the maximum number of rows or columns, depending on the orientation, to display before content begins to wrap. + **/ + maximumRowsOrColumns: number; + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the maximumRowsOrColumns property. + **/ + maxRows: number; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + numberOfItemsPerItemsBlock: any; + + /** + * Gets or sets the orientation of the GridLayout. + **/ + orientation: WinJS.UI.Orientation; + + //#endregion Properties + + } + + /** + * Creates a hub navigation pattern consisting of sections that can be navigated to. Each section is defined by a HubSection object. + **/ + class Hub { + //#region Constructors + + /** + * Creates a new Hub control. + * @constructor + * @param element The DOM element that will host the Hub control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the contentanimating event, add a property named "oncontentanimating" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the Hub is about to play entrance, content transition, insert, or remove animations. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.type, detail.index, detail.section. + **/ + oncontentanimating(eventInfo: CustomEvent): void; + + /** + * Raised when the user clicks on an interactive header. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.section. + **/ + onheaderinvoked(eventInfo: CustomEvent): void; + + /** + * Raised when the Hub control's loadingState changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: loadingState. + **/ + onloadingstatechanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this Hub. Call this method when the Hub is no longer needed. After calling this method, the Hub becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the Hub control. + **/ + element: HTMLElement; + + /** + * Gets or sets the Template or templating function that creates the DOM elements for each HubSection header. Your HubSection object should provide strings for HubSection.header property. + **/ + headerTemplate: any; + + /** + * Gets or sets the index of the first HubSection at least partially in view. This property is useful for animating the visible content in the Hub. + **/ + indexOfFirstVisible: number; + + /** + * Gets or sets the index of last HubSection at least partially in view. Used for animating the visible content in the Hub. + **/ + indexOfLastVisible: number; + + /** + * Gets a value that indicates whether the hub is still loading or whether loading is complete. The value changes to complete after all the sections and content inside them has loaded. + **/ + loadingState: string; + + /** + * Gets or sets the orientation of sections within the Hub. + **/ + orientation: Orientation; + + /** + * Gets or sets the distance between the start of the Hub and the current viewable area. + **/ + scrollPosition: number; + + /** + * Gets or sets the index of the first visible HubSection. + **/ + sectionOnScreen: number; + + /** + * Gets or sets the List that contains the HubSection objects that belong to this Hub. + **/ + sections: WinJS.Binding.List; + + /** + * This API supports the SemanticZoom infrastructure and is not intended to be used directly from your code. + **/ + zoomableView: IZoomableView; + + //#endregion Properties + + } + + /** + * Defines a section of a Hub. + **/ + class HubSection { + //#region Constructors + + /** + * Creates a new HubSection. + * @constructor + * @param element The DOM element hosts the new HubSection. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Releases resources held by this HubSection. Call this method when the HubSection is no longer needed. After calling this method, the HubSection becomes unusable. + **/ + dispose(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the HubSection control's content. + **/ + contentElement: HTMLElement; + + /** + * Gets the DOM element that hosts this HubSection. + **/ + element: HTMLElement; + + /** + * Gets or sets the header for this HubSection. + **/ + header: string; + + /** + * Gets a value that specifies whether the header is static. + **/ + isHeaderStatic: boolean; + + //#endregion Properties + + } + + /** + * Enables you to include an HTML page dynamically. As part of the constructor, you must include an option indicating the URI of the page. + **/ + class HtmlControl { + //#region Constructors + + /** + * Initializes a new instance of HtmlControl to define a new page control. + * @constructor + * @param element The element that hosts the HtmlControl. + * @param options The options for configuring the page. The uri option is required in order to specify the source document for the content of the page. Other options are the ones used by the WinJS.Pages.render method. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + } + + /** + * Defines an item that can be pressed, swiped, and dragged. + **/ + class ItemContainer { + //#region Constructors + + /** + * Creates a new ItemContainer. + * @constructor + * @param element The DOM element hosts the new ItemContainer. For the ItemContainer to be accessible, this element must have its role attribute set to "list" or "listbox". If tapBehavior is set to none and selectionDisabled is true, then use the "list" role; otherwise, use the "listbox" role. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the item is invoked. (You can use the tapBehavior property to specify whether taps and clicks invoke the item.) + * @param eventInfo An object that contains information about the event. + **/ + oninvoked(eventInfo: CustomEvent): void; + + /** + * Raised after the item is selected or deselected. + * @param eventInfo An object that contains information about the event. + **/ + onselectionchanged(eventInfo: CustomEvent): void; + + /** + * Raised just before the current selection changes. + * @param eventInfo An object that contains information about the event. + **/ + onselectionchanging(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this ItemContainer. Call this method when the ItemContainer is no longer needed. After calling this method, the ItemContainer becomes unusable. + **/ + dispose(): void; + + /** + * Forces the ItemContainer to update its layout. Call this function when the reading direction of the app changes after the control has been initialized. + **/ + forceLayout(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether the item can be dragged. + **/ + draggable: boolean; + + /** + * Gets the element that hosts this ItemContainer. + **/ + element: HTMLElement; + + /** + * Gets or sets a value that specifies whether the item is selected. + **/ + selected: boolean; + + /** + * Gets or sets a value that specifies whether selection of this item is disabled. + **/ + selectionDisabled: boolean; + + /** + * Gets or sets how the ItemContainer reacts to the swipe gesture. The swipe gesture can select the swiped items or can have no effect on the current selection. + **/ + swipeBehavior: WinJS.UI.SwipeBehavior; + + /** + * Gets or sets the orientation of swipe gestures. + **/ + swipeOrientation: Orientation; + + /** + * Gets or sets how the ItemContainer reacts when the user taps or clicks an item. + **/ + tapBehavior: TapBehavior; + + //#endregion Properties + + } + + /** + * This object supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + class Layout { + } + + /** + * Represents a layout for the ListView in which items are arranged in a vertical list. + **/ + class ListLayout { + //#region Constructors + + /** + * Creates a new ListLayout. + * @constructor + * @param options An object that contains one or more property/value pairs to apply to the new ListLayout. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param wholeItem + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): void; + + /** + * This method is no longer supported. + * @param endScrollPosition + * @param wholeItem + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragLeave(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragOver(): void; + + /** + * This method is no longer supported. + **/ + endLayout(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + executeAnimations(): void; + + /** + * This method is no longer supported. + * @param itemIndex + **/ + getItemPosition(itemIndex: number): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element + * @param keyPressed + **/ + getKeyboardNavigatedItem(itemIndex: number, element: HTMLElement, keyPressed: any): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPosition + **/ + getScrollbarRange(beginScrollPosition: number, endScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate, or the horizontal position on the screen. + * @param y The y-coordinate, or the vertical position on the screen. + **/ + hitTest(x: number, y: number): void; + + /** + * This method is no longer supported. + **/ + init(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + initialize(): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsAdded(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param firstPixel + * @param lastPixel + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * This method is no longer supported. + **/ + itemsMoved(): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsRemoved(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param tree + * @param changedRange + * @param modifiedItems + * @param modifiedGroups + **/ + layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): void; + + /** + * This method is no longer supported. + * @param groupIndex + * @param element A DOM element. + **/ + layoutHeader(groupIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + layoutItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param element + **/ + prepareHeader(element: HTMLElement): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + prepareItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param item + * @param newItem + **/ + releaseItem(item: any, newItem: any): void; + + /** + * This method is no longer supported. + **/ + reset(): void; + + /** + * This method is no longer supported. + * @param layoutSite + **/ + setSite(layoutSite: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + setupAnimations(): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPositionScrollPosition + **/ + startLayout(beginScrollPosition: number, endScrollPositionScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + uninitialize(): void; + + /** + * This method is no longer supported. + * @param count + **/ + updateBackdrop(count: number): void; + + //#endregion Methods + + //#region Properties + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + backdropColor: string; + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + disableBackdrop: boolean; + + /** + * Gets or sets the position of group headers. + **/ + groupHeaderPosition: WinJS.UI.HeaderPosition; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + groupInfo: Function; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use the orientation property instead. + **/ + horizontal: boolean; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + itemInfo: Function; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + numberOfItemsPerItemsBlock: any; + + /** + * Gets or sets the orientation of the GridLayout. + **/ + orientation: WinJS.UI.Orientation; + + //#endregion Properties + + } + + /** + * Displays data items in a customizable list or grid. + **/ + class ListView { + //#region Constructors + + /** + * Creates a new ListView. + * @constructor + * @param element The DOM element that hosts the ListView control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the selectionchanged event, add a property named "onselectionchanged" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the ListView is about to play an entrance or contentTransition animation. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.type, detail.setPromise. + **/ + oncontentanimating(eventInfo: CustomEvent): void; + + /** + * Raised when the user taps or clicks a group header. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.groupHeaderIndex, detail.groupHeaderPromise. + **/ + ongroupheaderinvoked(eventInfo: CustomEvent): void; + + /** + * Raised when the ListView is a drop target and the onitemdragenter has been disabled. This is raised every time the cursor is moved between a new pair of items. If you call preventDefault on this event, then the ListView does not move the items slightly above/below the cursor to provide visual feedback for a drop. + * @param eventInfo An object that contains information about the event. The detail property of this object contains additional information about the event. + **/ + onitemdragbetween(eventInfo: CustomEvent): void; + + /** + * Raised when the user is dragging an item from the ListView and the datasource changes while the user is dragging. + * @param eventInfo An object that contains information about the event. The detail property of this object contains additional information about the event. + **/ + onitemdragchanged(eventInfo: CustomEvent): void; + + /** + * Raised when an item is dropped onto the ListView as the result of a drag operation. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.dataTransfer, detail.index, detail.insertAfterIndex. + **/ + onitemdragdrop(eventInfo: CustomEvent): void; + + /** + * Raised when the user drops an item dragged from a ListView. + * @param eventInfo An object that contains information about the event. + **/ + onitemdragend(eventInfo: CustomEvent): void; + + /** + * Raised when an dragged item enters the bounds of the ListView control. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.dataTransfer. + **/ + onitemdragenter(eventInfo: CustomEvent): void; + + /** + * Raised when a draggable item leaves the bounds of a ListView control. + * @param eventInfo An object that contains information about the event. + **/ + onitemdragleave(eventInfo: CustomEvent): void; + + /** + * Raised when the user begins to drag an item from a ListView control. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.dataTransfer, detail.dragInfo. + **/ + onitemdragstart(eventInfo: CustomEvent): void; + + /** + * Occurs when the user taps or clicks an item. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.itemIndex. + **/ + oniteminvoked(eventInfo: CustomEvent): void; + + /** + * Raised when the focused item changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.oldFocus, detail.oldNewFocus. + **/ + onkeyboardnavigating(eventInfo: CustomEvent): void; + + /** + * Occurs when the ListView control's loadingState changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.scrolling. + **/ + onloadingstatechanged(eventInfo: CustomEvent): void; + + /** + * Occurs after the current selection changes. + * @param eventInfo An object that contains information about the event. The detail property of this object is null. To obtain the selected items, use the ListView.selection property. + **/ + onselectionchanged(eventInfo: CustomEvent): void; + + /** + * Occurs just before the current selection changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.newSelection, detail.preventTapBehavior. + **/ + onselectionchanging(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. See the ListView object page for a list of events. Note that you drop the "on" when specifying the event name for the addEventListener method. For example, instead of specifying "onselectionchange", you specify "selectionchange". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this object. Call this method when the object is no longer needed. After calling this method, the object becomes unusable. + **/ + dispose(): void; + + /** + * Returns the DOM element that represents the item at the specified index. + * @param itemIndex The index of the item. + * @returns The DOM element that represents the item at the specified index. + **/ + elementFromIndex(itemIndex: number): HTMLElement; + + /** + * Makes the item at the specified index visible. If necessary, the ListView will scroll to the item. + * @param itemIndex The index of the item to scroll into view. + **/ + ensureVisible(itemIndex: number): void; + + /** + * Forces the ListView to update its layout. Use this function when making the ListView visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Returns the index of the item that the specified DOM element displays. + * @param element The DOM element that displays the item. + * @returns The index of the item displayed by element. + **/ + indexOfElement(element: HTMLElement): number; + + /** + * Loads the next set of pages if the ListView control's loadingBehavior is set to "incremental" (otherwise, it does nothing). The number of pages to be loaded is determined by the pagesToLoad property. + **/ + loadMorePages(): void; + + /** + * Repositions all the visible items in the ListView to adjust for items whose sizes have changed. Most apps won’t ever need to call this method. For more info, see the Remarks section. + **/ + recalculateItemPosition(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + /** + * Triggers the ListView disposal service manually. + **/ + static triggerDispose(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that indicates whether the next set of pages is automatically loaded when the user scrolls beyond the number of pages specified by the pagesToLoadThreshold property. + **/ + automaticallyLoadPages: boolean; + + /** + * Gets or sets an IListViewItem that indicates which item should have keyboard focus and the focus state of that item. + **/ + currentItem: IListViewItem; + + /** + * Gets the HTML element that hosts this ListView. + **/ + element: HTMLElement; + + /** + * Gets or sets the data source that contains the groups for the items in the itemDataSource. + **/ + groupDataSource: IListDataSource; + + /** + * Gets or sets how the ListView reacts when the user taps or clicks a group header. + **/ + groupHeaderTapBehavior: GroupHeaderTapBehavior; + + /** + * Gets or sets the Template or function that creates the DOM elements for each group header in the groupDataSource. Each group header can contain multiple elements, but it must have a single root element. + **/ + groupHeaderTemplate: any; + + /** + * Gets or sets the first visible item. + **/ + indexOfFirstVisible: number; + + /** + * Gets the index of the last visible item in the ListView. + **/ + indexOfLastVisible: number; + + /** + * Gets or sets the data source that provides the ListView with items. + **/ + itemDataSource: IListDataSource; + + /** + * Go Gets or sets a value that specifies whether items can be dragged. When this is set to true the ListView provides built in behaviors related to item dragging. + **/ + itemsDraggable: boolean; + + /** + * Gets or sets whether the ListView control's items can be reordered within itself by dragging and dropping. + **/ + itemsReorderable: boolean; + + /** + * Gets or sets the WinJS.Binding.Template or templating function that creates the DOM elements for each item in the itemDataSource. Each item can contain multiple elements, but it must have a single root element. + **/ + itemTemplate: any; + + /** + * Gets or sets an object that controls the layout of the ListView. + **/ + layout: ILayout2; + + /** + * Gets or sets a value that specifies how the ListView fetches items and adds and removes them to the DOM. Don't change the value of this property after the ListView has begun loading data. + **/ + loadingBehavior: string; + + /** + * Gets a value that indicates whether the ListView is still loading or whether loading is complete. + **/ + loadingState: string; + + /** + * Gets or sets the maximum number of realized items. + **/ + maxDeferredItemCleanup: number; + + /** + * Gets or sets the number of pages to load when the loadingBehavior property is set to "incremental" and the user scrolls beyond the threshold specified by the pagesToLoadThreshold property. + **/ + pagesToLoad: number; + + /** + * Gets or sets the threshold (in pages) for initiating an incremental load. When the last visible item is within the specified number of pages from the end of the loaded portion of the list, and if automaticallyLoadPages is true and loadingBehavior is set to "incremental", the ListView initiates an incremental load. + **/ + pagesToLoadThreshold: number; + + /** + * Gets or sets the function that is called when the ListView discards or recycles the element representation of a group header. + **/ + resetGroupHeader: (header: any, element: HTMLElement) => void; + + /** + * Gets or sets the function that is called when an item is removed, an item is changed, or an item falls outside of the realized range of the ListView. + **/ + resetItem: (item: T, element: HTMLElement) => void; + + /** + * Gets or sets the distance, in pixels, of the start of the viewable area within the viewport. + **/ + scrollPosition: number; + + /** + * Gets an ISelection that contains the range of currently selected items. + **/ + selection: ISelection; + + /** + * Gets or sets the selection mode of the ListView. + **/ + selectionMode: SelectionMode; + + /** + * Gets or sets how the ListView reacts to the swipe gesture. The swipe gesture can select the swiped items or can have no effect on the current selection. + **/ + swipeBehavior: WinJS.UI.SwipeBehavior; + + /** + * Gets or sets how the ListView reacts when the user taps or clicks an item. + **/ + tapBehavior: TapBehavior; + + /** + * Gets a ZoomableView that supports semantic zoom functionality. This API supports the SemanticZoom infrastructure and is not intended to be used directly from your code. + **/ + zoomableView: IZoomableView>; + + //#endregion Properties + + } + + /** + * Represents a menu flyout for displaying commands. + **/ + class Menu { + //#region Constructors + + /** + * Creates a new Menu object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new Menu. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs immediately after the Menu is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Occurs after the Menu is shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Occurs before the Menu is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Occurs before a hidden Menu is shown. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this Menu. Call this method when the Menu is no longer needed. After calling this method, the Menu becomes unusable. + **/ + dispose(): void; + + /** + * Returns the MenuCommand object identified by id. + * @param id The element identifier (ID) of the command to be returned. + * @returns The command identified by id. + **/ + getCommandById(id: string): MenuCommand; + + /** + * Hides the Menu. + **/ + hide(): void; + + /** + * Hides the specified commands of the Menu. + * @param commands The commands to hide. The array elements may be MenuCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. + **/ + hideCommands(commands: any[], immediate: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the Menu, if hidden, regardless of other states. + * @param anchor Required. The DOM element to anchor the Menu. + * @param placement The placement of the Menu to the anchor: top, bottom, left, or right. + * @param alignment For top or bottom placement, the alignment of the Menu to the anchor's edge: center, left, or right. + **/ + show(anchor: HTMLElement, placement: string, alignment: string): void; + + /** + * Shows the specified commands of the Menu. + * @param commands The commands to show. The array elements may be Menu objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. + **/ + showCommands(commands: any[], immediate: boolean): void; + + /** + * Shows the specified commands of the Menu while hiding all other commands. + * @param commands The commands to show. The array elements may be MenuCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. + **/ + showOnlyCommands(commands: any[], immediate: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the default alignment to be used for this Menu. + **/ + alignment: string; + + /** + * Gets or sets the default anchor to be used for this Menu. + **/ + anchor: HTMLElement; + + /** + * Sets the MenuCommand objects that appear in the menu. + **/ + commands: MenuCommand[]; + + /** + * Gets the DOM element that hosts the Menu. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the Menu is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the default placement to be used for this Menu. + **/ + placement: string; + + //#endregion Properties + + } + + /** + * Represents a command to be displayed in a Menu object. + **/ + class MenuCommand { + //#region Constructors + + /** + * Creates a new MenuCommand object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new MenuCommand. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Disposes this control. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that indicates whether the MenuCommand is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the MenuCommand. + **/ + element: HTMLElement; + + /** + * Adds an extra CSS class during construction. + **/ + extraClass: string; + + /** + * Gets or sets the Flyout object displayed by this command. The specified flyout is shown when the MenuCommand's button is invoked. + **/ + flyout: Flyout; + + /** + * Gets a value that indicates whether the MenuCommand is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets the element identifier (ID) of the command. + **/ + id: string; + + /** + * Gets or sets the label of the command. + **/ + label: string; + + /** + * Gets or sets the function to be invoked when the command is clicked. + **/ + onclick: Function; + + /** + * Gets or sets the selected state of a toggle button. + **/ + selected: boolean; + + /** + * Gets the type of the command. + **/ + type: string; + + //#endregion Properties + + } + + /** + * Displays navigation commands in a toolbar that the user can show or hide. + **/ + class NavBar { + //#region Constructors + + /** + * Creates a new NavBar. + * @constructor + * @param element The DOM element that will host the new NavBar. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs immediately after the NavBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Raised after the NavBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Raised just before the NavBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Occurs before a hidden NavBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + /** + * Occurs after the NavBar has finished processing its child elements. + * @param eventInfo An object that contains information about the event. + **/ + onchildrenprocessed(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this NavBar. Call this method when the NavBar is no longer needed. After calling this method, the NavBar becomes unusable. + **/ + dispose(): void; + + /** + * Hides the NavBar. + **/ + hide(): void; + + /** + * Hides the specified commands of the NavBar. + * @param commands The commands to hide. The array elements may be NavBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. + **/ + hideCommands(commands: any[], immediate: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + /** + * Shows the NavBar if it is not disabled. + **/ + show(): void; + + /** + * Shows the specified commands of the NavBar. + * @param commands The commands to show. The array elements may be NavBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. + **/ + showCommands(commands: any[], immediate: boolean): void; + + /** + * Shows the specified commands of the NavBar while hiding all other commands. + * @param commands The commands to show. The array elements may be NavBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. + **/ + showOnlyCommands(commands: any[], immediate: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + commands: AppBarCommand; + + /** + * Gets or sets a value that indicates whether the NavBar is disabled. + **/ + disabled: boolean; + + /** + * Gets the HTML element that hosts this NavBar. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the NavBar is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + layout: string; + + /** + * Gets or sets a value that specifies whether the NavBar appears at the top or bottom of the main view. + **/ + placement: string; + + /** + * Gets or sets a value that indicates whether the NavBar is sticky (won't light dismiss). If not sticky, the NavBar dismisses normally when the user touches outside of the NavBar. + **/ + sticky: boolean; + + //#endregion Properties + + } + + /** + * Represents a navigation command in a NavBarContainer. + **/ + class NavBarCommand { + //#region Constructors + + /** + * Creates a new NavBarCommand. + * @constructor + * @param element The DOM element hosts the new NavBarCommand. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this NavBarCommand. Call this method when the NavBarCommand is no longer needed. After calling this method, the NavBarCommand becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the HTML element that hosts this NavBarCommand. + **/ + element: HTMLElement; + + /** + * Gets or sets the command's icon. + **/ + icon: string; + + /** + * Gets or sets the label of the command. + **/ + label: string; + + /** + * Get or sets the location to navigate to when this command is invoked. + **/ + location: any; + + /** + * Gets or sets a value that specifies whether to show the split tab stop. + **/ + splitButton: boolean; + + /** + * Gets a value that indicates whether the splitButton is open. + **/ + splitOpened: boolean; + + /** + * Gets or sets a user-defined object that represents the state associated with the command's location. + **/ + state: any; + + /** + * Gets or sets the tooltip of the command. + **/ + tooltip: any; + + //#endregion Properties + + } + + /** + * Contains a group of NavBarCommand objects in a NavBar. + **/ + class NavBarContainer { + //#region Constructors + + /** + * Creates a new NavBarContainer. + * @constructor + * @param element The DOM element hosts the new NavBarContainer. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when a child NavBarCommand object's click event fires. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.navbarcommand, detail.data. + **/ + oninvoked(eventInfo: CustomEvent): void; + + /** + * Occurs when the split button of a child NavBarCommand is opened or closed. A split button is toggled when the user navigates to another page or opens another split button. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.opened, detail.index, detail.navbarcommand, detail.data. + **/ + onsplittoggle(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this NavBarCommand. Call this method when the NavBarCommand is no longer needed. After calling this method, the NavBarCommand becomes unusable. + **/ + dispose(): void; + + /** + * Forces the NavBarContainer to update its layout. Use this function when making the NavBarContainer visible again after you set its style.display property to "none". + **/ + forceLayout(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the index of the current item. + **/ + currentIndex: number; + + /** + * Gets or sets a WinJS.Binding.List that generates NavBarCommand objects. + **/ + data: WinJS.Binding.List; + + /** + * Gets the HTML element that hosts this NavBarContainer. + **/ + element: HTMLElement; + + /** + * Gets or sets a value that specifies whether NavBarCommand objects in this container use a fixed or dynamic width. + **/ + fixedSize: boolean; + + /** + * Gets or sets a value that specifies whether the NavBarContainer has a horizontal or vertical layout. + **/ + layout: Orientation; + + /** + * Gets or sets a value that specifies how many rows of navigation commands to display on a page. + **/ + maxRows: number; + + /** + * Gets or sets the WinJS.Binding.Template or templating function that creates the DOM elements for each item in the data source. Each item can contain multiple elements, but it must have a single root element. + **/ + template: WinJS.Binding.Template; + + //#endregion Properties + + } + + /** + * Lets the user rate something by clicking an icon that represents a rating. The Rating control can display three types of ratings: an average rating, a tentative rating, and the user's rating. + **/ + class Rating { + //#region Constructors + + /** + * Creates a new Rating. + * @constructor + * @param element The DOM element hosts the new Rating. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the cancel event, add a property named "oncancel" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the user finishes interacting with the rating control without committing a tentative rating. + * @param eventInfo An object that contains information about the event. + **/ + oncancel(eventInfo: Event): void; + + /** + * Raised when the user commits a change to the userRating. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tentativeRating. + **/ + onchange(eventInfo: CustomEvent): void; + + /** + * Raised when the user is choosing a new tentative Rating. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tentativeRating. + **/ + onpreviewchange(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this Rating. Call this method when the Rating is no longer needed. After calling this method, the Rating becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the average rating. + **/ + averageRating: number; + + /** + * Gets or sets whether the control is disabled. When the control is disabled, the user can't specify a new user rating or modify an existing rating. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the Rating. + **/ + element: HTMLElement; + + /** + * Gets or sets whether control lets the user clear the rating. + **/ + enableClear: boolean; + + /** + * Gets or sets the maximum possible rating value. + **/ + maxRating: number; + + /** + * Gets or sets a set of descriptions to show for rating values in the tooltip. + **/ + tooltipStrings: string[]; + + /** + * Gets or sets the user's rating. + **/ + userRating: number; + + //#endregion Properties + + } + + /** + * Generates HTML from a set of data. Use this control to generate lists of items. + **/ + class Repeater { + //#region Constructors + + /** + * Creates a new Repeater control. + * @constructor + * @param options An object that contains one or more property/value pairs to apply to the new Repeater. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised after an item in the Repeater control's data source changes and after the corresponding DOM element has been updated. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.key, detail.newElement, detail.newItem, detail.newValue, detail.oldElement, detail.oldItem, detail.oldValue, detail.setPromise. + **/ + onitemchanged(eventInfo: CustomEvent): void; + + /** + * Raised after an item in the Repeater control's data source changes but before the corresponding DOM element has been updated. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.key, detail.newElement, detail.newItem, detail.newValue, detail.oldElement, detail.oldItem, detail.oldValue, detail.setPromise. + **/ + onitemchanging(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been added to the Repeater control's data source and after the corresponding DOM element has been added. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.value. + **/ + oniteminserted(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been added to the Repeater control's data source but before the corresponding DOM element has been added. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.value. + **/ + oniteminserting(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been moved from one index to another in the Repeater control's data source and after the corresponding DOM element has been moved. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.oldIndex, detail.newIndex. + **/ + onitemmoved(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been moved from one index to another in the Repeater control's data source but before the corresponding DOM element has been moved. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.oldIndex, detail.newIndex. + **/ + onitemmoving(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been moved from one index to another in the Repeater control's data source and after the corresponding DOM element has been moved. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.item, detail.setPromise. + **/ + onitemremoved(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been removed from the Repeater control's data source but before the corresponding DOM element has been removed. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.item, detail.setPromise. + **/ + onitemremoving(eventInfo: CustomEvent): void; + + /** + * Raised when the Repeater has finished loading a new set of data. This event is only fired on construction. This event is only raised when the Repeater is constructed or its data source or template changes. + * @param eventInfo An object that contains information about the event. + **/ + onitemsloaded(eventInfo: CustomEvent): void; + + /** + * Raised after the Repeater control's underlying data has been updated and after the updated HTML has been reloaded. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElements. + **/ + onitemsreloaded(eventInfo: CustomEvent): void; + + /** + * Raised after the Repeater control's underlying data has been updated but before the updated HTML has been reloaded. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElements, detail.setPromise. + **/ + onitemsreloading(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this Repeater. Call this method when the Repeater is no longer needed. After calling this method, the Repeater becomes unusable. + **/ + dispose(): void; + + /** + * Returns the HTML element for the item at the specified index. + * @param index The index of the item. + * @returns The DOM element for the specified item. + **/ + elementFromIndex(index: number): HTMLElement; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the List that provides the Repeater with items to display. + **/ + data: WinJS.Binding.List; + + /** + * Gets the DOM element that hosts the Repeater. + **/ + element: HTMLElement; + + /** + * Gets the number of items in the Repeater control. + **/ + length: number; + + /** + * Gets or sets a WinJS.Binding.Template or custom rendering function that defines the HTML of each item within the Repeater. + **/ + template: WinJS.Binding.Template; + + //#endregion Properties + + } + + /** + * Enables the user to perform search queries and select suggestions. + **/ + class SearchBox { + //#region Constructors + + /** + * Creates a new SearchBox. + * @constructor + * @param element The DOM element hosts the new SearchBox. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the user or the app changes the queryText. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.language, detail.queryText, detail.linguisticDetails. + **/ + onquerychanged(eventInfo: CustomEvent): void; + + /** + * Raised awhen the user clicks the search glyph or presses Enter. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.language, detail.queryText, detail.linguisticDetails, detail.keyModifiers. + **/ + onquerysubmitted(eventInfo: CustomEvent): void; + + /** + * Raised when the app automatically redirects focus to the search box. This event can only be raised when the focusOnKeyboardInput property is set to true. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.propertyName. + **/ + onreceivingfocusonkeyboardinput(eventInfo: CustomEvent): void; + + /** + * Raised when the user selects a suggested option for the search. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tag, detail.keyModifiers, detail.storageFile. + **/ + onresultsuggestionschosen(eventInfo: CustomEvent): void; + + /** + * Raised when the system requests search suggestions from this app. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.language, detail.linguisticDetails, detail.queryText, detail.searchSuggestionCollection. + **/ + onsuggestionsrequested(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this SearchBox. Call this method when the SearchBox is no longer needed. After calling this method, the SearchBox becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + /** + * Specifies whether suggestions based on local files are automatically displayed in the search pane, and defines the criteria that Windows uses to locate and filter these suggestions. + * @param settings The new settings for local content suggestions. + **/ + setLocalContentSuggestionSettings(settings: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets whether the first suggestion is chosen when the user presses Enter. + **/ + chooseSuggestionOnEnter: boolean; + + /** + * Gets or sets a value that specifies whether the SearchBox is disabled. If the control is disabled, it won't receive focus. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the SearchBox. + **/ + element: HTMLElement; + + /** + * Gets or sets a value that specifies whether the search box automatically receives focus when the user types into the app window. + **/ + focusOnKeyboardInput: boolean; + + /** + * Gets or sets the placeholder text for the SearchBox. This text is displayed if there is no other text in the input box. + **/ + placeholderText: string; + + /** + * Gets or sets the query text for the SearchBox. + **/ + queryText: string; + + /** + * Gets or sets the search history context. This context is used a secondary key (the app ID is the primary key) for storing search history. + **/ + searchHistoryContext: string; + + /** + * Gets or sets a value that specifies whether search history is disabled. + **/ + searchHistoryDisabled: boolean; + + //#endregion Properties + + } + + /** + * Enables the user to zoom between two different views supplied by two child controls. One child control supplies the zoomed-out view and the other provides the zoomed-in view. + **/ + class SemanticZoom { + //#region Constructors + + /** + * Creates a new SemanticZoom. + * @constructor + * @param element The DOM element that hosts the SemanticZoom. + * @param options An object that contains one or more property/value pairs to apply to the new control. This object can contain these properties: initiallyZoomedOut Boolean, zoomFactor 0.2–0.85. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the control zooms in or out. + * @param eventInfo An object that contains information about the event. The detail property of this object is true when the control is zoomed out. Otherwise, it's false. + **/ + onzoomchanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this SemanticZoom. Call this method when the SemanticZoom is no longer needed. After calling this method, the SemanticZoom becomes unusable. + **/ + dispose(): void; + + /** + * Forces the SemanticZoom to update its layout. Use this function when making the SemanticZoom visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Unregisters an event handler for the specified event. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the SemanticZoom control. + **/ + element: HTMLElement; + + /** + * Gets or a sets a value that specifies whether to display the SemanticZoom zoom out button. + **/ + enableButton: boolean; + + /** + * Determines whether any controls contained in a SemanticZoom should be processed separately. This property is always true, meaning that the SemanticZoom takes care of processing its own controls. + **/ + isDeclarativeControlContainer: boolean; + + /** + * Gets or sets a value that indicates whether SemanticZoom is locked and zooming between views is disabled. + **/ + locked: boolean; + + /** + * Gets or sets a value that indicates whether the control is zoomed out. + **/ + zoomedOut: boolean; + + /** + * Gets or sets a value that specifies how much the scaling the cross-fade animation performs when the SemanticZoom transitions between views. + **/ + zoomFactor: number; + + //#endregion Properties + + } + + /** + * Provides users with fast, in-context access to settings that affect the current Windows Store app. + **/ + class SettingsFlyout { + //#region Constructors + + /** + * Creates a new SettingsFlyout object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new SettingsFlyout. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised immediately after the SettingsFlyout is completely hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Raised immediately after a SettingsFlyout is fully shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Raised just before hiding a SettingsFlyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Raised just before showing a SettingsFlyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this SettingsFlyout. Call this method when the SettingsFlyout is no longer needed. After calling this method, the SettingsFlyout becomes unusable. + **/ + dispose(): void; + + /** + * Hides the SettingsFlyout, if visible, regardless of other states. + **/ + hide(): void; + + /** + * Loads a fragment of the SettingsFlyout. Your app calls this when the user invokes a settings command and the WinJS.Application.onsettings event occurs. + * @param e An object that contains information about the event, received from the WinJS.Application.onsettings event. The detail property of this object contains the applicationcommands sub-property that you set to an array of settings commands. You then populate the SettingsFlyout with these commands by a call to populateSettings. + **/ + static populateSettings(e: CustomEvent): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the SettingsPane UI, if hidden. + **/ + show(): void; + + /** + * Shows the SettingsPane UI, if hidden, regardless of other state. + **/ + static show(): void; + + /** + * Show the Settings flyout using the Settings element identifier (ID) and the path of the page that contains the Settings element. + * @param id The ID of the Settings element. + * @param path The path of the page that contains the Settings element. + **/ + static showSettings(id: string, path: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element the SettingsFlyout is attached to. + **/ + element: HTMLElement; + + /** + * Gets whether the SettingsFlyout is hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the settings command Id for the SettingsFlyout control. + **/ + settingsCommandId: string; + + /** + * This property may be unavailable or altered in future versions. Use the CSS width property of the element that has the win-settingsflyout class instead. + **/ + width: string; + + //#endregion Properties + + } + + /** + * A type of IListDataSource that provides read-access to an object that implements the IStorageQueryResultBase interface. A StorageDataSource enables you to query and bind to items in the data source. + **/ + class StorageDataSource { + //#region Constructors + + /** + * Creates a new StorageDataSource object. + * @constructor + * @param query The IStorageQueryResultBase that the StorageDataSource obtains its items from. Instead of IStorageQueryResultBase, you can also pass one of these string values: Music, Pictures, Videos, Documents. + * @param options The set of properties and values to apply to the new StorageDataSource. Properties on this object may include: mode , requestedThumbnailSize , thumbnailOptions , synchronous . + **/ + constructor(query: any, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Draws the thumbnail for the specified item to the specified img element. + * @param item The item to retrieve the thumbnail for. + * @param image The img element that will display the thumbnail. + * @returns A Promise that completes when the full-quality thumbnail is visible. + **/ + loadThumbnail(item: IItem, image: HTMLImageElement): Promise; + + //#endregion Methods + + } + + /** + * Prevents a DOM sub-tree from receiving tab navigations and focus. + **/ + class TabContainer { + //#region Constructors + + /** + * Creates a new TabContainer. + * @constructor + * @param element The DOM element that hosts the TabContainer control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Releases resources held by this TabContainer. Call this method when the TabContainer is no longer needed. After calling this method, the TabContainer becomes unusable. + **/ + dispose(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the child DOM element that receives tab focus. + **/ + childFocus: HTMLElement; + + /** + * Gets or sets the tab index of this container. + **/ + tabIndex: number; + + //#endregion Properties + + } + + /** + * Allows users to select time values. + **/ + class TimePicker { + //#region Constructors + + /** + * Initializes a new instance of a TimePicker control. + * @constructor + * @param element The DOM element associated with the TimePicker control. + * @param options The set of options to be applied initially to the TimePicker control. The options are the following: clock. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when any of the controls are changed by the user. + * @param eventInfo An object that contains information about the event. + **/ + onchange(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener. + * @param type The type (name) of the event. + * @param listener The function that handles the event. + * @param capture If true, specifies that capture should be initiated, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this TimePicker. Call this method when the TimePicker is no longer needed. After calling this method, the TimePicker becomes unusable. + **/ + dispose(): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + raiseEvent(type: string, eventProperties: any): boolean; + + /** + * Removes a listener for the specified event. + * @param type The name of the event for which to remove a listener. + * @param listener The listener. + * @param useCapture Optional. The same value that was passed to addEventListener for this listener. It may be omitted if it was omitted when calling addEventListener. + **/ + removeEventListener(type: string, listener: Function, useCapture?: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the type of clock to display (12HourClock or 24HourClock). It defaults to the user setting. + **/ + clock: string; + + /** + * Gets or sets the current time of the TimePicker. Note that the date value is always July 15, 2011. + **/ + current: Date; + + /** + * Specifies whether the TimePicker is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element for the TimePicker. + **/ + element: HTMLElement; + + /** + * Gets or sets the display pattern for the hour. The default hour pattern is hour.integer(2). You can change the hour pattern by changing the number of integers displayed. + **/ + hourPattern: string; + + /** + * Gets or sets the minute increment. For example, 15 specifies that the TimePicker minute control should display only the choices 00, 15, 30, 45. + **/ + minuteIncrement: number; + + /** + * Gets or sets the display pattern for the minute. The default minute pattern is minute.integer(2). You can change the minute pattern by changing the number of integers displayed. + **/ + minutePattern: string; + + /** + * Gets or sets the display pattern for the period. The default period pattern is period.abbreviated(2). You can change the period pattern by changing the number of integers displayed. + **/ + periodPattern: string; + + //#endregion Properties + + } + + /** + * A control that lets the user switch an option between two states: on (checked is set to true) and off (checked is set to false). + **/ + class ToggleSwitch { + //#region Constructors + + /** + * Creates a new ToggleSwitch. + * @constructor + * @param element The DOM that hosts the control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the change event, add a property named "onchange" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the ToggleSwitch control is flipped to on (checked == true) or off (checked == false). + * @param eventInfo An object that contains information about the event. + **/ + onchange(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this ToggleSwitch. Call this method when the ToggleSwitch is no longer needed. After calling this method, the ToggleSwitch becomes unusable. + **/ + dispose(): void; + + /** + * Handles the specified event. + * @param event The event. + **/ + handleEvent(event: any): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + raiseEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether the control is on or off. + **/ + checked: boolean; + + /** + * Gets or sets a value that specifies whether the control is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the ToggleSwitch. + **/ + element: HTMLElement; + + /** + * Gets or sets the text that displays when the ToggleSwitch is off (checked is set to false). + **/ + labelOff: string; + + /** + * Gets or sets the text that displays when the ToggleSwitch is on (checked is set to true). + **/ + labelOn: string; + + /** + * Gets or sets the main text for the ToggleSwitch control. This text is always displayed, regardless of whether the control is switched on or off. + **/ + title: string; + + //#endregion Properties + + } + + /** + * Displays a tooltip that can contain images and formatting. + **/ + class Tooltip { + //#region Constructors + + /** + * Creates a new Tooltip. + * @constructor + * @param element The DOM element associated that hosts the Tooltip. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the opened event, add a property named "onopened" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised just before the Tooltip is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeclose(eventInfo: CustomEvent): void; + + /** + * Raised just before the Tooltip appears. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeopen(eventInfo: CustomEvent): void; + + /** + * Raised when the Tooltip is no longer displayed. + * @param eventInfo An object that contains information about the event. + **/ + onclosed(eventInfo: CustomEvent): void; + + /** + * Raised when the Tooltip is shown. + * @param eventInfo An object that contains information about the event. + **/ + onopened(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Hides the Tooltip. + **/ + close(): void; + + /** + * Releases resources held by this Tooltip. Call this method when the Tooltip is no longer needed. After calling this method, the Tooltip becomes unusable. + **/ + dispose(): void; + + /** + * Shows the Tooltip. + * @param type A value that specifies when to show the Tooltip. The default value is "mousedown". + **/ + open(type?: string): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the HTML element that is the content of the Tooltip. + **/ + contentElement: HTMLElement; + + /** + * Gets the DOM element that hosts the Tooltip control. + **/ + element: HTMLElement; + + /** + * Gets or appends additional CSS classes to apply to the element that hosts the Tooltip. + **/ + extraClass: string; + + /** + * Gets or sets a value that specifies whether the Tooltip is an infotip, a tooltip that contains a lot of info and should be displayed for longer than a typical Tooltip. + **/ + infotip: boolean; + + /** + * Gets or sets the HTML content of the Tooltip. + **/ + innerHTML: string; + + /** + * Gets or sets the position for the Tooltip relative to its target element: top, bottom, left or right. + **/ + placement: string; + + //#endregion Properties + + } + + /** + * Scales a single child element to fill the available space without resizing it. This control reacts to changes in the size of the container as well as changes in size of the child element. For example, a media query may result in a change in aspect ratio. + **/ + class ViewBox { + //#region Constructors + + /** + * Initializes a new instance of the ViewBox control. + * @constructor + * @param element The DOM element that functions as the scaling box. This element fills 100% of the width and height allotted to it. + * @param options The set of options to be applied initially to the ViewBox control. There are currently no options on this control, and any options included in this parameter are ignored. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Adds an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this ViewBox. Call this method when the ViewBox is no longer needed. After calling this method, the ViewBox becomes unusable. + **/ + dispose(): void; + + /** + * Forces the ViewBox to update its layout. Use this function when making the ViewBox visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that functions as the scaling box. + **/ + element: HTMLElement; + + //#endregion Properties + + } + + /** + * Serves as the base class for a custom IListDataSource. + **/ + class VirtualizedDataSource { + //#region Constructors + + /** + * Initializes the VirtualizedDataSource base class of a custom data source. + * @constructor + * @param listDataAdapter The object that supplies data to the VirtualizedDataSource. + * @param options An object that can contain properties that specify additional options for the VirtualizedDataSource. It supports these properties: cacheSize. + **/ + constructor(listDataAdapter: IListDataAdapter, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the status of the VirtualizedDataSource changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: status. + **/ + statuschanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. See the VirtualizedDataSource object page for a list of events. Note that you drop the "on" when specifying the event name for the addEventListener method. For example, instead of specifying "onstatuschanged", you specify "statuschanged". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. See the VirtualizedDataSource object page for a list of events. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + } + + //#endregion Objects + + //#region Functions + + /** + * Returns a new IListDataSource that adds group information to the items of another IListDataSource. + * @param listDataSource The data source for the individual items to group. + * @param groupKey A callback function that accepts a single argument: an item in the IListDataSource. The function is called for each item in the list and must return the group key for that item as a string. + * @param groupData A callback function that accepts a single argument: an item in the IListDataSource. The function is called on one IListDataSource item for each group and must return an object that represents the header of that group. + * @param options An object that can contain properties that specify additional options: groupCountEstimate, batchSize. + * @returns An IListDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. + **/ + function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListDataSource; + + /** + * Used to disables all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be disabled, as the determination is made based on several factors. + **/ + function disableAnimations(): void; + + /** + * Used to enable all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be enabled, as the determination is made based on several factors. + **/ + function enableAnimations(): void; + + /** + * Marks a event handler function as being compatible with declarative processing. + * @param handler The handler to be marked as compatible with declarative processing. + * @returns The handler, marked as compatible with declarative processing. + **/ + function eventHandler(handler: any): any; + + /** + * Asynchronously executes a collection of CSS animations on a collection of elements. This is the underlying animation mechanism used by the Animations Library. Apps are encouraged to use the Animations Library to conform with the standard look and feel of the rest of the system, rather than calling this function directly. + * @param element Element or elements to be animated. This parameter can be expressed in several ways: As the special value "undefined", which means that the animation has no target, As a single object, As a JavaScript array (possibly empty), in which each element of the array can be a single element or a JavaScript array of elements., As a NodeList (for example, the result of querySelectorAll), As an HTMLCollection. + * @param animation The animation description or an array of animation descriptions to apply to element. An animation description is a JavaScript object with specific properties, listed below. There are two types of animation descriptions: one for keyframe-based animations and one for explicit animations. These types are distinguished by whether the keyframe property has a defined value. The following properties are required for both types of animation descriptions: property (string), delay (number), duration (number), timing (string). If an animation has a keyframe property with a defined, non-null value, then the animation is a keyframe-based animation. A keyframe-based animation description requires the following property in addition to those mentioned above: keyframe (string). If an animation does not have a keyframe property, or if the value of the property is null or undefined, then the animation is an explicit animation. An explicit animation description requires the following properties in addition to the common properties mentioned above: from, to. The values given in the from and to properties must be valid for the CSS property specified by the property property. For example, if the CSS property is "opacity", then the from and to properties must be numbers between 0 and 1 (inclusive). + * @returns Returns a Promise object that completes when the CSS animation is complete. + **/ + function executeAnimation(element: HTMLElement, animation: any): Promise; + + /** + * Asynchronously executes a collection of CSS transitions on a collection of elements. This is the underlying animation mechanism used by the Animations Library. Apps are encouraged to use the Animations Library to conform with the standard look and feel of the rest of the system, rather than calling this function directly. + * @param element Element or elements on which to perform the transition. This parameter can be expressed in several ways: As the special value "undefined", which means that the transition has no target, As a single object, As a JavaScript array (possibly empty), in which each element of the array can be a single element or a JavaScript array of elements., As a NodeList (for example, the result of querySelectorAll), As an HTMLCollection. + * @param transition The transition description or an array of transition descriptions to apply to element. A transition description is a JavaScript object with these properties: property (string), delay (number), duration (number), timing (string), from (optional), to. The values given in the from and to properties must be valid for the CSS property specified by the property property. For example, if the CSS property is "opacity", then the from and to properties must be numbers between 0 and 1 (inclusive). + * @returns Returns a Promise that completes when the transition is finished. + **/ + function executeTransition(element: HTMLElement, transition: any): Promise; + + /** + * Retrieves the items in the specified index range. + * @param dataSource The data source that contains the items to retrieve. + * @param ranges An array of ISelectionRange objects that have firstIndex and lastIndex values. + * @returns A Promise that contains an array of the requested IItem objects. + **/ + function getItemsFromRanges(dataSource: IListDataSource, ranges: ISelectionRange[]): Promise>; + + /** + * Determines whether the Animations Library and ListView animations will be performed if called. + * @returns Returns true if animations will be performed; otherwise false. + **/ + function isAnimationEnabled(): boolean; + + /** + * Applies declarative control binding to all elements, starting at the specified root element. + * @param rootElement The element at which to start applying the binding. If this parameter is not specified, the binding is applied to the entire document. + * @param skipRoot If true, the elements to be bound skip the specified root element and include only the children. + * @returns A promise that is fulfilled when binding has been applied to all the controls. + **/ + function processAll(rootElement?: Element, skipRoot?: boolean): Promise; + + /** + * Applies declarative control binding to the specified element. + * @param element The element to bind. + * @returns A promise that is fulfilled after the control is activated. The value of the promise is the control that is attached to element. + **/ + function process(element: Element): Promise; + + /** + * Walks the DOM tree from the given element to the root of the document. Whenever a selector scope is encountered, this method performs a lookup within that scope for the specified selector string. The first matching element is returned. + * @param selector The selector string. + * @param element The element to begin walking to the root of the document from. + * @returns The target element, if found. + **/ + function scopedSelect(selector: string, element: HTMLElement): HTMLElement; + + /** + * Adds the set of declaratively specified options (properties and events) to the specified control. If name of the options property begins with "on", the property value is a function and the control supports addEventListener. setControl calls addEventListener on the control. + * @param control The control on which the properties and events are to be applied. + * @param options The set of options that are specified declaratively. + **/ + function setOptions(control: any, options?: any): void; + + //#endregion Functions + +} +/** + * Provides functions to load HTML content programmatically. +**/ +declare module WinJS.UI.Fragments { + //#region Functions + + /** + * Starts loading the fragment at the specified location. The returned promise completes when the fragment is ready to be copied. + * @param href The URI that contains the fragment to be copied. + * @returns A promise that is fulfilled when the fragment has been prepared for copying. + **/ + function cache(href: string): Promise; + + /** + * Removes any cached information about the specified fragment. This method does not unload any scripts or styles that are referenced by the fragment. + * @param href The URI that contains the fragment to be cleared. If no URI is provided, the entire contents of the cache are cleared. + **/ + function clearCache(href: string): void; + + /** + * Loads the contents of the specified URI into the specified element without copying it. + * @param href The URI that contains the fragment to copy. + * @param element Optional. The element to which the fragment is appended. + * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The element is not added to the cache. See also rendercopy, where the element is added to the cache. + **/ + function render(href: string, element?: HTMLElement): Promise; + + /** + * Loads and copies the contents of the specified URI into the specified element. + * @param href The URI that contains the fragment to copy. + * @param target The element to which the fragment is appended. + * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The fragment is added to the cache. See also render, where the element is not added to the cache. + **/ + function renderCopy(href: string, target?: HTMLElement): Promise; + + //#endregion Functions + +} +/** + * Provides methods for defining and displaying PageControl objects. +**/ +declare module WinJS.UI.Pages { + //#region Interfaces + + /** + * Provides members for a PageControl. You implement this interface when defining a new PageControl. + **/ + interface IPageControlMembers { + //#region Methods + + /** + * Called if any error occurs during the processing of the page. + * @param err The error that occurred. + * @returns Nothing if the error was handled, or an error promise if the error was not handled. + **/ + error?(err: any): Promise; + + /** + * Initializes the control before the content of the control is set. Use the processed method for any initialization that should be done after the content of the control has been set. + * @param element The DOM element that will contain all the content for the page. + * @param options The options passed to the constructor of the page. + * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + init?(element: HTMLElement, options: any): Promise; + + /** + * Creates DOM objects from the content in the specified URI. This method is called after the PageControl is defined and before the init method is called. + * @param uri The URI from which to create DOM objects. + * @returns A promise whose fulfilled value is the set of unparented DOM objects. + **/ + load?(uri: string): Promise; + + /** + * Initializes the control after the content of the control is set. + * @param element The DOM element that will contain all the content for the page. + * @param options The options that are to be passed to the constructor of the page. + * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + processed?(element: HTMLElement, options: any): Promise; + + /** + * Called after all initialization and rendering is complete. At this time, the element is ready for use. + * @param element The DOM element that contains all the content for the page. + * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @returns A promise that is fulfilled when the element is ready for use, if asynchronous processing is necessary. If not, returns nothing. + **/ + ready?(element: HTMLElement, options: any): Promise; + + /** + * Takes the elements returned by the load method and attaches them to the specified element. + * @param element The DOM element to which the loadResult elements are appended. + * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @param loadResult A Promise that contains the elements returned from the load method. + **/ + render?(element: HTMLElement, options: any, loadResult: Promise): void; + + //#endregion Methods + + } + + //#endregion Interfaces + + //#region Objects + + /** + * A modular unit of HTML, CSS, and JavaScript that can be navigated to or used as a custom WinJS control. + **/ + class PageControl { + } + + //#endregion Objects + + //#region Functions + + /** + * Creates a new PageControl from the specified URI that contains the specified members. Multiple calls to this method for the same URI are allowed, and all members will be merged. + * @param uri The URI for the content that defines the page. + * @param members An object that defines the members that the control will have. + * @returns A constructor function that creates the PageControl. + **/ + function define(uri: string, members: IPageControlMembers): PageControl; + + /** + * Gets an already-defined page control for the specified URI, or creates a new one. + * @param uri The URI for the content that defines the page. + * @returns A constructor function that creates the page. + **/ + function get(uri: string): Function; + + /** + * Creates a PageControl from the specified URI and inserts it inside the specified element. + * @param uri The URI for the content that defines the page. + * @param element The DOM element to which the PageControl is appended. + * @param options An object that contains one or more property/value pairs to apply to the new PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @param parentedPromise A Promise that is fulfilled when the new PageControl is done rendering and its contents becomes the child of element. + * @returns A promise that is fulfilled when rendering is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + function render(uri: string, element: HTMLElement, options?: any, parentedPromise?: Promise): Promise; + + //#endregion Functions + +} +/** + * Provides methods for detecting when the user tabs to or from DOM elements. +**/ +declare module WinJS.UI.TrackTabBehavior { + //#region Functions + + /** + * Sets the tab order for the specified element within its container. + * @param element The element to update. + * @param tabIndex The index value of the element within its container. + **/ + function attach(element: HTMLElement, tabIndex: number): void; + + /** + * Removes the tab order information from the specified element. + * @param element The element to remove tab information from. + **/ + function detatch(element: HTMLElement): void; + + //#endregion Functions + +} +/** + * Provides helper functions, for example, functions to add and remove CSS classes. +**/ +declare module WinJS.Utilities { + //#region Enumerations + + /** + * Defines a set of keyboard values. + **/ + enum Key { + /** + * The BACKSPACE key. + **/ + backspace, + /** + * The TAB key. + **/ + tab, + /** + * The ENTER key. + **/ + enter, + /** + * The SHIFT key. + **/ + shift, + /** + * The CTRL key. + **/ + ctrl, + /** + * The ALT key. + **/ + alt, + /** + * The PAUSE key. + **/ + pause, + /** + * The CAPS LOCK key. + **/ + capsLock, + /** + * The ESCAPE key. + **/ + escape, + /** + * The SPACE key. + **/ + space, + /** + * The PAGE UP key. + **/ + pageUp, + /** + * The PAGE DOWN key. + **/ + pageDown, + /** + * The END key. + **/ + end, + /** + * The HOME key. + **/ + home, + /** + * The LEFT ARROW key. + **/ + leftArrow, + /** + * The UP ARROW key. + **/ + upArrow, + /** + * The RIGHT ARROW key. + **/ + rightArrow, + /** + * The DOWN ARROW key. + **/ + downArrow, + /** + * The INSERT key. + **/ + insert, + /** + * The DELETE key. + **/ + deleteKey, + /** + * The 0 key. + **/ + num0, + /** + * The 1 key. + **/ + num1, + /** + * The 2 key. + **/ + num2, + /** + * The 3 key. + **/ + num3, + /** + * The 4 key. + **/ + num4, + /** + * The 5 key. + **/ + num5, + /** + * The 6 key. + **/ + num6, + /** + * The 7 key. + **/ + num7, + /** + * The 8 key. + **/ + num8, + /** + * The 9 key. + **/ + num9, + /** + * The a key. + **/ + a, + /** + * The b key. + **/ + b, + /** + * The c key. + **/ + c, + /** + * The d key. + **/ + d, + /** + * The e key. + **/ + e, + /** + * The f key. + **/ + f, + /** + * The g key. + **/ + g, + /** + * The h key. + **/ + h, + /** + * The i key. + **/ + i, + /** + * The j key. + **/ + j, + /** + * The k key. + **/ + k, + /** + * The l key. + **/ + l, + /** + * The m key. + **/ + m, + /** + * The n key. + **/ + n, + /** + * The o key. + **/ + o, + /** + * The p key. + **/ + p, + /** + * The q key. + **/ + q, + /** + * The r key. + **/ + r, + /** + * The s key. + **/ + s, + /** + * The t key. + **/ + t, + /** + * The u key. + **/ + u, + /** + * The v key. + **/ + v, + /** + * The w key. + **/ + w, + /** + * The x key. + **/ + x, + /** + * The y key. + **/ + y, + /** + * The z key. + **/ + z, + /** + * The left Windows key. + **/ + leftWindows, + /** + * The right Windows key. + **/ + rightWindows, + /** + * The menu key. + **/ + menu, + /** + * The 0 key on the numerical keypad. + **/ + numPad0, + /** + * The 1 key on the numerical keypad. + **/ + numPad1, + /** + * The 2 key on the numerical keypad. + **/ + numPad2, + /** + * The 3 key on the numerical keypad. + **/ + numPad3, + /** + * The 4 key on the numerical keypad. + **/ + numPad4, + /** + * The 5 key on the numerical keypad. + **/ + numPad5, + /** + * The 6 key on the numerical keypad. + **/ + numPad6, + /** + * The 7 key on the numerical keypad. + **/ + numPad7, + /** + * The 8 key on the numerical keypad. + **/ + numPad8, + /** + * The 9 key on the numerical keypad. + **/ + numPad9, + /** + * The multiplication key (*). + **/ + multiply, + /** + * The addition key (+). + **/ + add, + /** + * The subtraction key (-). + **/ + subtract, + /** + * The decimal point key (.) + **/ + decimalPoint, + /** + * The division key (/). + **/ + divide, + /** + * The F1 key. + **/ + F1, + /** + * The F2 key. + **/ + F2, + /** + * The F3 key. + **/ + F3, + /** + * The F4 key. + **/ + F4, + /** + * The F5 key. + **/ + F5, + /** + * The F6 key. + **/ + F6, + /** + * The F7 key. + **/ + F7, + /** + * The F8 key. + **/ + F8, + /** + * The F9 key. + **/ + F9, + /** + * The F10 key. + **/ + F10, + /** + * The F11 key. + **/ + F11, + /** + * The F12 key. + **/ + F12, + /** + * The NUMBER LOCK key. + **/ + numLock, + /** + * The SCROLL LOCK key. + **/ + scrollLock, + /** + * The browser BACK key. + **/ + browserBack, + /** + * The browser FORWARD key. + **/ + browserForward, + /** + * The semicolon key (;). + **/ + semicolon, + /** + * The equals key (=). + **/ + equal, + /** + * The comma key (,). + **/ + comma, + /** + * The dash key (-). + **/ + dash, + /** + * The period key (.). + **/ + period, + /** + * The forward slash key (/). + **/ + forwardSlash, + /** + * The grave accent key (`). + **/ + graveAccent, + /** + * The open bracket key ([). + **/ + openBracket, + /** + * The backslash key (\). + **/ + backSlash, + /** + * The close bracket key (]). + **/ + closeBracket, + /** + * The single quote key ('). + **/ + singleQuote + } + + //#endregion Enumerations + + //#region Objects + + /** + * A mixin that contains event-related functions. + **/ + var eventMixin: { + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture If true, initiates capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true if capture is to be initiated, otherwise false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + }; + + /** + * Represents the result of a query selector, and provides various operations that perform actions over the elements of the collection. + **/ + interface QueryCollection extends Array { + //#region Methods + + /** + * Adds the specified class to all the elements in the collection. + * @param name The name of the class to add. + * @returns This QueryCollection object. + **/ + addClass(name: string): QueryCollection; + + /** + * Creates a QueryCollection that contains the children of the specified parent element. + * @param element The parent element. + * @returns The QueryCollection that contains the children of the element. + **/ + children(element: HTMLElement): QueryCollection; + + /** + * Clears the specified style property for all the elements in the collection. + * @param name The name of the style property to be cleared. + * @returns This QueryCollection object. + **/ + clearStyle(name: string): QueryCollection; + + /** + * Creates controls that are attached to the elements in this QueryCollection, if the ctor parameter is a function, or configures the controls that are attached to the elements in this QueryCollection, if the ctor parameter is an object. + * @param ctor If this parameter is a function, it is a constructor function that is used to create controls to attach to the elements. If it is an object, it is the set of options passed to the controls. + * @param options The options passed to the newly-created controls. + * @returns This QueryCollection object. + **/ + control(ctor: any, options?: any): QueryCollection; + + /** + * Performs an action on each item in the QueryCollection. + * @param callbackFn The action to perform on each item. + * @param thisArg The argument to bind to callbackFn. + * @returns The QueryCollection. + **/ + forEach(callbackFn: (value: T, index: number, array: T[]) => void, thisArg?: any): QueryCollection; + + /** + * Gets an item from the QueryCollection. + * @param index The index of the item to return. + * @returns A single item from the collection. + **/ + get(index: number): T; + + /** + * Gets an attribute value from the first element in the collection. + * @param name The name of the attribute. + * @returns The value of the attribute. + **/ + getAttribute(name: string): any; + + /** + * Determines whether the specified class exists on the first element of the collection. + * @param name The name of the class. + * @returns true if the element has the specified class; otherwise, false. + **/ + hasClass(name: string): boolean; + + /** + * Looks up an element by ID and wraps the result in a QueryCollection. + * @param id The ID of the element. + * @returns A QueryCollection that contains the element, if it is found. + **/ + id(id: string): QueryCollection; + + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: T): void; + + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: T[]): void; + + /** + * Registers the listener for the specified event on all the elements in the collection. + * @param eventType The name of the event. + * @param listener The event handler function to be called when the event occurs. + * @param capture true if capture == true is to be passed to addEventListener; otherwise, false. + **/ + listen(eventType: string, listener: Function, capture?: boolean): void; + + /** + * Executes a query selector on all the elements in the collection and aggregates the result into a QueryCollection. + * @param query The query selector string. + * @returns A QueryCollection object containing the aggregate results of executing the query on all the elements in the collection. + **/ + query(query: any): QueryCollection; + + /** + * Removes the specified class from all the elements in the collection. + * @param name The name of the class to be removed. + * @returns his QueryCollection object. + **/ + removeClass(name: string): QueryCollection; + + /** + * Unregisters the listener for the specified event on all the elements in the collection. + * @param eventType The name of the event. + * @param listener The event handler function. + * @param capture true if capture == true; otherwise, false. + * @returns This QueryCollection object. + **/ + removeEventListener(eventType: string, listener: Function, capture?: boolean): QueryCollection; + + /** + * Sets an attribute value on all the items in the collection. + * @param name The name of the attribute to be set. + * @param value The value of the attribute to be set. + * @returns This QueryCollection object. + **/ + setAttribute(name: string, value: any): QueryCollection; + + /** + * Sets the specified style property for all the elements in the collection. + * @param name The name of the style property. + * @param value The value for the property. + * @returns This QueryCollection object. + **/ + setStyle(name: string, value: any): QueryCollection; + + /** + * Renders a template that is bound to the given data and parented to the elements included in the QueryCollection. If the QueryCollection contains multiple elements, the template is rendered multiple times, once at each element in the QueryCollection per item of data passed. + * @param templateElement The DOM element to which the template control is attached. + * @param data The data to render. If the data is an array (or any other object that has a forEach method) then the template is rendered multiple times, once for each item in the collection. + * @param renderDonePromiseCallback If supplied, this function is called each time the template gets rendered, and is passed a promise that is fulfilled when the template rendering is complete. + * @returns The QueryCollection. + **/ + template(templateElement: HTMLElement, data: any, renderDonePromiseCallback: Function): QueryCollection; + + /** + * Toggles (adds or removes) the specified class on all the elements in the collection. If the class is present, it is removed; if it is absent, it is added. + * @param name The name of the class to be toggled. + * @returns This QueryCollection object. + **/ + toggleClass(name: string): QueryCollection; + + //#endregion Methods + + } + + /** + * Constructor support for QueryCollection interface + **/ + export var QueryCollection: { + new (items: T[]): QueryCollection; + prototype: QueryCollection; + } + + //#endregion Objects + + //#region Functions + + /** + * Adds the specified class to the specified element. + * @param e The element to which to add the class. + * @param name The name of the class to add. + * @returns The element. + **/ + function addClass(e: T, name: string): T; + + /** + * Gets a collection of elements that are the direct children of the specified element. + * @param element The parent element. + * @returns The collection of children of the element. + **/ + function children(element: HTMLElement): QueryCollection; + + /** + * Converts a CSS positioning string for the specified element to pixels. + * @param element The element. + * @param value The CSS positioning string. + * @returns The number of pixels. + **/ + function convertToPixels(element: HTMLElement, value: string): number; + + /** + * Creates an object that has one event for each name passed to the function. + * @param events A variable list of property names. + * @returns The object with the specified properties. The names of the properties are prefixed with 'on'. + **/ + function createEventProperties(...events: string[]): any; + + /** + * Gets the data value associated with the specified element. + * @param element The element. + * @returns The value associated with the element. + **/ + function data(element: HTMLElement): any; + + /** + * Disposes all first-generation disposable elements that are descendents of the specified element. The specified element itself is not disposed. + * @param element The root element whose sub-tree is to be disposed. + **/ + function disposeSubTree(element: HTMLElement): void; + + /** + * Removes all the child nodes from the specified element. + * @param element The element. + * @returns The element. + **/ + function empty(element: T): T; + + /** + * Determines whether the specified event occurred within the specified element. + * @param element The element. + * @param event The event. + * @returns true if the event occurred within the element; otherwise, false. + **/ + function eventWithinElement(element: HTMLElement, event: Event): boolean; + + /** + * Adds tags and type to a logging message. + * @param message The message to be formatted. + * @param tag The tag(s) to be applied to the message. Multiple tags should be separated by spaces. + * @param type The type of the message. + * @returns The formatted message. + **/ + function formatLog(message: string, tag: string, type: string): string; + + /** + * Gets the height of the content of the specified element. The content height does not include borders or padding. + * @param element The element. + * @returns The content height of the element. + **/ + function getContentHeight(element: HTMLElement): number; + + /** + * Gets the width of the content of the specified element. The content width does not include borders or padding. + * @param element The element. + * @returns The content width of the element. + **/ + function getContentWidth(element: HTMLElement): number; + + /** + * Gets the leaf-level type or namespace specified by the name parameter. + * @param name The name of the member. + * @param root The root to start in. Defaults to the global object. + * @returns The leaf-level type or namespace in the specified parent namespace. + **/ + function getMember(name: string, root?: any): any; + + /** + * Gets the position of the specified element. + * @param element The element. + * @returns An object that contains the left, top, width and height properties of the element. + **/ + function getPosition(element: HTMLElement): IPosition; + + /** + * Gets the left coordinate of the specified element relative to the specified parent. + * @param element The element. + * @param parent The parent element. + * @returns The relative left coordinate. + **/ + function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number; + + /** + * Gets the top coordinate of the element relative to the specified parent. + * @param element The element. + * @param parent The parent element. + * @returns The relative top coordinate. + **/ + function getRelativeTop(element: HTMLElement, parent: HTMLElement): number; + + /** + * Gets the height of the element, including its margins. + * @param element The element. + * @returns The height of the element including margins. + **/ + function getTotalHeight(element: HTMLElement): number; + + /** + * Gets the width of the element, including margins. + * @param element The element. + * @returns The width of the element including margins. + **/ + function getTotalWidth(element: HTMLElement): number; + + /** + * Determines whether the specified element has the specified class. + * @param e The element. + * @param name The name of the class. + * @returns true if the element has the class, otherwise false. + **/ + function hasClass(e: HTMLElement, name: string): boolean; + + /** + * Returns a collection with zero or one elements matching the specified id. + * @param id The ID of the element (or elements). + * @returns A collection of elements whose id matches the id parameter. + **/ + function id(id: string): QueryCollection; + + /** + * Calls insertAdjacentHTML on the specified element. + * @param element The element on which insertAdjacentHTML is to be called. + * @param position The position relative to the element at which to insert the HTML. Possible values are: beforebegin, afterbegin, beforeend, afterend. + * @param text The text to insert. + **/ + function insertAdjacentHTML(element: HTMLElement, position: string, text: string): void; + + /** + * Calls insertAdjacentHTML on the specified element in the context of MSApp.execUnsafeLocalFunction. + * @param element The element on which insertAdjacentHTML is to be called. + * @param position The position relative to the element at which to insert the HTML. Possible values are: beforebegin, afterbegin, beforeend, afterend. + * @param text Value to be provided to insertAdjacentHTML. + **/ + function insertAdjacentHTMLUnsafe(element: HTMLElement, position: string, text: string): void; + + /** + * Attaches the default dispose API wrapping the dispose implementation to the specified element. + * @param element The element to mark as disposable. + * @param disposeImpl The function containing the element-specific dispose logic, called by the dispose function that markDisposable attaches. + **/ + function markDisposable(element: HTMLElement, disposeImpl: Function): void; + + /** + * Marks a function as being compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. + * @param func The function to be marked as compatible with declarative processing. + * @returns The input function, marked as compatible with declarative processing. + **/ + function markSupportedForProcessing(func: U): U; + + /** + * Returns a QueryCollection with zero or one elements matching the specified selector query. + * @param query The CSS selector to use. See Selectors for more information. + * @param element Optional. The root element at which to start the query. If this parameter is omitted, the scope of the query is the entire document. + * @returns A QueryCollection with zero or one elements matching the specified selector query. + **/ + function query(query: any, element?: HTMLElement): QueryCollection; + + /** + * Ensures that the specified function executes only after the DOMContentLoaded event has fired for the current page. The DOMContentLoaded event occurs after the page has been parsed but before all the resources are loaded. + * @param callback A function that executes after the DOMContentLoaded event has occurred. + * @param async If true, the callback should be executed asynchronously. + * @returns A promise that completes after the DOMContentLoaded event has occurred. + **/ + function ready(callback?: Function, async?: boolean): Promise; + + /** + * Removes the specified class from the specified element. + * @param e The element from which to remove the class. + * @param name The name of the class to remove. + * @returns The element. + **/ + function removeClass(e: T, name: string): T; + + /** + * Asserts that the value is compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. If the value is not compatible, and strictProcessing is on, an exception is thrown. All functions that have been declared using WinJS.Class.define, WinJS.Class.derive, WinJS.UI.Pages.define, or WinJS.Binding.converter are automatically marked as supported for declarative processing. Any other function that you use from a declarative context (that is, a context in which an HTML element has a data-win-control or data-win-options attribute) must be marked manually by calling this function. When you mark a function as supported for declarative processing, you are guaranteeing that the code in the function is secure from injection of third-party content. + * @param value The value to be tested for compatibility with declarative processing. If the value is a function it must be marked with a property supportedForProcessing with a value of true when strictProcessing is on. For more information, see WinJS.Utilities.markSupportedForProcessing. + * @returns The input value. + **/ + function requireSupportedForProcessing(value: T): T; + + /** + * Sets the innerHTML property of the specified element to the specified text. + * @param element The element on which the innerHTML property is to be set. + * @param text The value to be set to the innerHTML property. + **/ + function setInnerHTML(element: HTMLElement, text: string): void; + + /** + * Sets the innerHTML property of the specified element to the specified text. + * @param element The element on which the innerHTML property is to be set. + * @param text The value to be set to the innerHTML property. + **/ + function setInnerHTMLUnsafe(element: HTMLElement, text: string): void; + + /** + * Sets the outerHTML property of the specified element to the specified text. + * @param element The element on which the outerHTML property is to be set. + * @param text The value to be set to the outerHTML property. + **/ + function setOuterHTML(element: HTMLElement, text: string): void; + + /** + * Sets the outerHTML property of the specified element to the specified text in the context of MSApp.execUnsafeLocalFunction. + * @param element The element on which the outerHTML property is to be set. + * @param text The value to be set to the outerHTML property. + **/ + function setOuterHTMLUnsafe(element: HTMLElement, text: string): void; + + /** + * Configures a logger that writes messages containing the specified tags to the JavaScript console. + * @param options The tags for messages to log. Multiple tags should be separated by spaces. May contain type, tags, excludeTags and action properties. + **/ + function startLog(options?: ILogOptions): void; + + /** + * Removes the WinJS logger that had previously been set up. + **/ + function stopLog(): void; + + /** + * Toggles (adds or removes) the specified class on the specified element. If the class is present, it is removed; if it is absent, it is added. + * @param e The element on which to toggle the class. + * @param name The name of the class to toggle. + * @returns The element. + **/ + function toggleClass(e: T, name: string): T; + + //#endregion Functions + + //#region Properties + + /** + * Gets whether the current script context has access to WinRT APIs. + **/ + var hasWinRT: boolean; + + //#endregion Properties + + //#region Interfaces + + interface ILogOptions { + type: string; + action?: (message: string, tags: string, type: string) => void; + excludeTags: string; + tags: string; + } + + interface IPosition { + left: number; + top: number; + width: number; + height: number; + } + + //#endregion Interfaces + +} +/** + * Provides functions and objects for scheduling and managing asynchronous tasks. +**/ +declare module WinJS.Utilities.Scheduler { + //#region Enumerations + + /** + * Represents a priority for a job managed by the Scheduler. + **/ + enum Priority { + /** + * A priority higher than the normal priority level. + **/ + aboveNormal, + /** + * A priority less than the normal priority level. + **/ + belowNormal, + /** + * A high priority. + **/ + high, + /** + * The idle priority for work items. + **/ + idle, + /** + * The highest priority. + **/ + max, + /** + * The lowest priority. + **/ + min, + /** + * The normal priority for work items. + **/ + normal + } + + //#endregion Enumerations + + //#region Interfaces + + /** + * Represents a work item that's executed by the Scheduler. + **/ + interface IJob { + //#region Methods + + /** + * Cancels the job. + **/ + cancel(): void; + + /** + * Pauses the job. + **/ + pause(): void; + + /** + * Resumes the job. + **/ + resume(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets a value that indicates whether the job has successfully completed. + **/ + completed: boolean; + + /** + * Gets the unique numeric identifier assigned to the job. + **/ + id: number; + + /** + * Gets or sets the name of the job. + **/ + name: string; + + /** + * Gets or sets the owner of the job. + **/ + owner: IOwnerToken; + + /** + * Gets or sets the priority of the job. + **/ + priority: Priority; + + //#endregion Properties + + } + + /** + * Provides a control mechanism that allows a job to cooperatively yield. This object is passed to your work function when you schedule it. + **/ + interface IJobInfo { + //#region Methods + + /** + * Uses a Promise to determine how long the scheduler should wait before rescheduling the job after it yields. + * @param promise Once the work item yields, the scheduler will wait for this Promise to complete before rescheduling the job. + **/ + setPromise(promise: Promise): void; + + /** + * Specifies the next unit of work to run once this job yields. + * @param work The next unit of work to run once this job yields. + **/ + setWork(work: Function): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the work item associated with this IJobInfo. + **/ + job: IJob; + + /** + * Gets a value that specifies whether the job should yield. + **/ + shouldYield: boolean; + + //#endregion Properties + + } + + /** + * Represents an object that owns jobs. You can use this object to cancel a set of jobs. + **/ + interface IOwnerToken { + //#region Methods + + /** + * Synchronously cancels the job that this token owns, including paused and blocked jobs. + **/ + cancelAll(): void; + + //#endregion Methods + + } + + //#endregion Interfaces + + //#region Functions + + /** + * Creates and returns a new IOwnerToken which can be set to the owner property of one or more jobs. + * @returns A new IOwnerToken which can be set to the owner property of one or more jobs. + **/ + function createOwnerToken(): IOwnerToken; + + /** + * Runs the specified callback in a high priority context. + * @param callback The callback to run in a high priority callback. + * @returns The return value of the callback. + **/ + function execHigh(callback: () => U): U; + + /** + * Returns a string representation of the scheduler's state for diagnostic purposes. The jobs and drain requests are displayed in the order in which they are currently expected to be processed. The current job and drain request are marked by an asterisk. + * @returns A string representation of the scheduler's state for diagnostic purposes. The jobs and drain requests are displayed in the order in which they are currently expected to be processed. The current job and drain request are marked by an asterisk. + **/ + function retrieveState(): string; + + /** + * Runs jobs in the scheduler without timeslicing until all jobs at the specified priority and higher have executed. + * @param priority The priority to which the scheduler should drain. The default is -15. + * @param name An optional description of the drain request for diagnostics. + * @returns A Promise which completes when the drain has finished. Canceling this Promise cancels the drain request. This Promise will never enter an error state. + **/ + function requestDrain(priority?: Priority, name?: string): Promise; + + /** + * Schedules the specified function to execute asynchronously. + * @param work A function that represents the work item to be scheduled. When called the work item will receive as its first argument an object which allows the work item to ask the scheduler if it should yield cooperatively and if so allows the work item to either provide a function to be run as a continuation or a WinJS.Promise which will when complete provide a function to run as a continuation. Provide these fields for the object: shouldYield, setWork(work), setPromise(promise), job. + * @param priority The priority of the work item. If you don't specify a priority, it defaults to WinJS.Utilities.Scheduler.Priority.normal. + * @param thisArg A "this" instance to be bound to the work item. The default value is null. + * @param name A description of the work item for diagnostics. The default value is an empty string. + * @returns The job instance that represents this work item. + **/ + function schedule(work: (jobInfo: IJobInfo) => any, priority?: Priority, thisArg?: any, name?: string): IJob; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.aboveNormal priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of aboveNormal priority. + **/ + function schedulePromiseAboveNormal(promiseValue?: U, jobName?: string): Promise; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.belowNormal priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of belowNormal priority. + **/ + function schedulePromiseBelowNormal(promiseValue?: U, jobName?: string): Promise; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.high priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of high priority. + **/ + function schedulePromiseHigh(promiseValue?: U, jobName?: string): Promise; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.Idle priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of idle priority. + **/ + function schedulePromiseIdle(promiseValue?: U, jobName?: string): Promise; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.normal priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of normal priority. + **/ + function schedulePromiseNormal(promiseValue?: U, jobName?: string): Promise; + + //#endregion Functions + +} From 507a26a9ed6000d3cfed072332495895538229ed Mon Sep 17 00:00:00 2001 From: VILIC VANE Date: Sun, 15 Jun 2014 16:27:36 +0800 Subject: [PATCH 009/324] cheerio v0.17.0 definitions --- cheerio/cheerio-old.d.ts | 81 +++++++++++ cheerio/cheerio-tests.ts | 6 +- cheerio/cheerio-tests.ts.tscparams | 1 - cheerio/cheerio.d.ts | 207 +++++++++++++++++++++++------ cheerio/cheerio.d.ts.tscparams | 1 - 5 files changed, 252 insertions(+), 44 deletions(-) create mode 100644 cheerio/cheerio-old.d.ts delete mode 100644 cheerio/cheerio-tests.ts.tscparams delete mode 100644 cheerio/cheerio.d.ts.tscparams diff --git a/cheerio/cheerio-old.d.ts b/cheerio/cheerio-old.d.ts new file mode 100644 index 000000000..b0e09b778 --- /dev/null +++ b/cheerio/cheerio-old.d.ts @@ -0,0 +1,81 @@ +// Type definitions for Cheerio +// Project: https://github.com/MatthewMueller/cheerio +// Definitions by: Bret Little +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +interface Cheerio { + + addClass(classNames: string): Cheerio; + hasClass(className: string): boolean; + removeClass(className?: any): Cheerio; + + attr(attributeName: string, value: any): Cheerio; + attr(attributeName: string): string; + removeAttr(attributeName: any): Cheerio; + + find(selector: string): Cheerio; + + parent(): Cheerio; + + next(): Cheerio; + prev(): Cheerio; + + siblings(): Cheerio; + + children(selector?: any): Cheerio; + + each(func: (index: any, elem: any) => Cheerio); + + map(callback: (index: any, domElement: Element) =>any): Cheerio; + + filter(selector: string): Cheerio; + filter(func: (index: any) =>any): Cheerio; + + first(): Cheerio; + last(): Cheerio; + + eq(index: number): Cheerio; + + append(...content: any[]): Cheerio; + prepend(...content: any[]): Cheerio; + after(...content: any[]): Cheerio; + before(...content: any[]): Cheerio; + remove(selector: string): Cheerio; + replaceWith(content: string): Cheerio; + empty(): Cheerio; + + html(htmlString: string): Cheerio; + html(): string; + + text(textString: string): Cheerio; + text(): string; + + toArray(): any[]; + + clone() : Cheerio; + root() : Cheerio; + dom(): any; + + contains(container: Element, contained: Element): boolean; + isArray(obj: any): boolean; + inArray(value: any, array: any[], fromIndex?: number): number; + merge(first: any[], second: any[]): any[]; + + +} + +interface CheerioOptionsInterface { + ignoreWhitespace?: boolean; + xmlMode?: boolean; + lowerCaseTags?: boolean; +} + +interface CheerioStatic { + (...selectors: any[]): Cheerio; + (): Cheerio; +} + +declare module "cheerio" { + export function load (html : string, options?: CheerioOptionsInterface) : CheerioStatic; +} diff --git a/cheerio/cheerio-tests.ts b/cheerio/cheerio-tests.ts index 71d54c557..af671cd00 100644 --- a/cheerio/cheerio-tests.ts +++ b/cheerio/cheerio-tests.ts @@ -33,7 +33,7 @@ $el.children().map((index, element) => { }); $el.children().filter((index) => { - return $el.children().eq(index).find('t'); + return $el.children().eq(index).find('t').length >= 0; }); $el.filter('span').filter('li'); @@ -60,6 +60,6 @@ $el.text('some text'); $el.toArray(); $el.clone().find('a').parent(); -$el.root().find('a'); +$.root().find('a'); -$el.dom(); +$el.data(); diff --git a/cheerio/cheerio-tests.ts.tscparams b/cheerio/cheerio-tests.ts.tscparams deleted file mode 100644 index e16c76dff..000000000 --- a/cheerio/cheerio-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/cheerio/cheerio.d.ts b/cheerio/cheerio.d.ts index b0e09b778..92334de45 100644 --- a/cheerio/cheerio.d.ts +++ b/cheerio/cheerio.d.ts @@ -1,81 +1,210 @@ -// Type definitions for Cheerio -// Project: https://github.com/MatthewMueller/cheerio -// Definitions by: Bret Little +// Type definitions for Cheerio v0.17.0 +// Project: https://github.com/cheeriojs/cheerio +// Definitions by: VILIC VANE // Definitions: https://github.com/borisyankov/DefinitelyTyped - interface Cheerio { - - addClass(classNames: string): Cheerio; - hasClass(className: string): boolean; - removeClass(className?: any): Cheerio; + // Document References + // Cheerio https://github.com/cheeriojs/cheerio + // JQuery http://api.jquery.com - attr(attributeName: string, value: any): Cheerio; - attr(attributeName: string): string; - removeAttr(attributeName: any): Cheerio; + [index: number]: CheerioElement; + length: number; + + // Attributes + + attr(name: string): string; + attr(name: string, value: any): Cheerio; + + data(): Object; + + val(): string; + val(value: string): Cheerio; + + removeAttr(name: string): Cheerio; + + hasClass(className: string): boolean; + addClass(classNames: string): Cheerio; + + removeClass(): Cheerio; + removeClass(className: string): Cheerio; + removeClass(func: (index: number, className: string) => string): Cheerio; + + toggleClass(className: string): Cheerio; + toggleClass(className: string, toggleSwitch: boolean): Cheerio; + toggleClass(toggleSwitch?: boolean): Cheerio; + toggleClass(func: (index: number, className: string, toggleSwitch: boolean) => string, toggleSwitch?: boolean): Cheerio; + + is(selector: string): boolean; + is(element: CheerioElement): boolean; + is(element: CheerioElement[]): boolean; + is(selection: Cheerio): boolean; + is(func: (index: number, element: CheerioElement) => boolean): boolean; + + // Traversing find(selector: string): Cheerio; - parent(): Cheerio; + parent(selector?: string): Cheerio; + parents(selector?: string): Cheerio; + parentsUntil(selector?: string, filter?: string): Cheerio; + parentsUntil(element: CheerioElement, filter?: string): Cheerio; + parentsUntil(element: Cheerio, filter?: string): Cheerio; - next(): Cheerio; - prev(): Cheerio; + closest(selector: string): Cheerio; - siblings(): Cheerio; + next(selector?: string): Cheerio; + nextAll(): Cheerio; - children(selector?: any): Cheerio; + nextUntil(selector?: string, filter?: string): Cheerio; + nextUntil(element: CheerioElement, filter?: string): Cheerio; + nextUntil(element: Cheerio, filter?: string): Cheerio; - each(func: (index: any, elem: any) => Cheerio); + prev(selector?: string): Cheerio; + prevAll(): Cheerio; - map(callback: (index: any, domElement: Element) =>any): Cheerio; + prevUntil(selector?: string, filter?: string): Cheerio; + prevUntil(element: CheerioElement, filter?: string): Cheerio; + prevUntil(element: Cheerio, filter?: string): Cheerio; + + slice(start: number, end?: number): Cheerio; + + siblings(selector?: string): Cheerio; + + children(selector?: string): Cheerio; + + each(func: (index: number, element: CheerioElement) => any): Cheerio; + map(func: (index: number, element: CheerioElement) => any): Cheerio; filter(selector: string): Cheerio; - filter(func: (index: any) =>any): Cheerio; + filter(selection: Cheerio): Cheerio; + filter(element: CheerioElement): Cheerio; + filter(elements: CheerioElement[]): Cheerio; + filter(func: (index: number) => boolean): Cheerio; first(): Cheerio; last(): Cheerio; eq(index: number): Cheerio; - append(...content: any[]): Cheerio; - prepend(...content: any[]): Cheerio; - after(...content: any[]): Cheerio; - before(...content: any[]): Cheerio; - remove(selector: string): Cheerio; + get(): Document[]; + get(index: number): Document; + + end(): Cheerio; + + add(selectorOrHtml: string): Cheerio; + add(selector: string, context: Document): Cheerio; + add(element: CheerioElement): Cheerio; + add(elements: CheerioElement[]): Cheerio; + add(selection: Cheerio): Cheerio; + + // Manipulation + + append(content: string, ...contents: any[]): Cheerio; + append(content: Document, ...contents: any[]): Cheerio; + append(content: Document[], ...contents: any[]): Cheerio; + append(content: Cheerio, ...contents: any[]): Cheerio; + + prepend(content: string, ...contents: any[]): Cheerio; + prepend(content: Document, ...contents: any[]): Cheerio; + prepend(content: Document[], ...contents: any[]): Cheerio; + prepend(content: Cheerio, ...contents: any[]): Cheerio; + + after(content: string, ...contents: any[]): Cheerio; + after(content: Document, ...contents: any[]): Cheerio; + after(content: Document[], ...contents: any[]): Cheerio; + after(content: Cheerio, ...contents: any[]): Cheerio; + + before(content: string, ...contents: any[]): Cheerio; + before(content: Document, ...contents: any[]): Cheerio; + before(content: Document[], ...contents: any[]): Cheerio; + before(content: Cheerio, ...contents: any[]): Cheerio; + + remove(selector?: string): Cheerio; + replaceWith(content: string): Cheerio; + replaceWith(content: CheerioElement): Cheerio; + replaceWith(content: CheerioElement[]): Cheerio; + replaceWith(content: Cheerio): Cheerio; + empty(): Cheerio; - html(htmlString: string): Cheerio; html(): string; + html(html: string): Cheerio; - text(textString: string): Cheerio; text(): string; + text(text: string): Cheerio; - toArray(): any[]; + css(propertyName: string): string; + css(propertyNames: string[]): string[]; + css(propertyName: string, value: string): Cheerio; + css(propertyName: string, value: number): Cheerio; + css(propertyName: string, func: (index: number, value: string) => string): Cheerio; + css(propertyName: string, func: (index: number, value: string) => number): Cheerio; + css(properties: Object): Cheerio; - clone() : Cheerio; - root() : Cheerio; - dom(): any; + // Rendering - contains(container: Element, contained: Element): boolean; - isArray(obj: any): boolean; - inArray(value: any, array: any[], fromIndex?: number): number; - merge(first: any[], second: any[]): any[]; + // Miscellaneous + clone(): Cheerio; + // Not Documented + + toArray(): CheerioElement[]; } interface CheerioOptionsInterface { - ignoreWhitespace?: boolean; + // Document References + // Cheerio https://github.com/cheeriojs/cheerio + // HTMLParser2 https://github.com/fb55/htmlparser2/wiki/Parser-options + // DomHandler https://github.com/fb55/DomHandler + xmlMode?: boolean; + decodeEntities?: boolean; lowerCaseTags?: boolean; + lowerCaseAttributeNames?: boolean; + recognizeCDATA?: boolean; + recognizeSelfClosing?: boolean; + normalizeWhitespace?: boolean; } interface CheerioStatic { - (...selectors: any[]): Cheerio; - (): Cheerio; + // Document References + // Cheerio https://github.com/cheeriojs/cheerio + // JQuery http://api.jquery.com + + (selector: string): Cheerio; + (selector: string, context: string): Cheerio; + (selector: string, context: CheerioElement): Cheerio; + (selector: string, context: CheerioElement[]): Cheerio; + (selector: string, context: Cheerio): Cheerio; + (selector: string, context: string, root: string): Cheerio; + (selector: string, context: CheerioElement, root: string): Cheerio; + (selector: string, context: CheerioElement[], root: string): Cheerio; + (selector: string, context: Cheerio, root: string): Cheerio; + (selector: any): Cheerio; + + xml(): string; + root(): Cheerio; + contains(container: CheerioElement, contained: CheerioElement): boolean; + parseHTML(data: string, context?: Document, keepScripts?: boolean): Document[]; +} + +interface CheerioElement { + // Document References + // Node Console + + type: string; + name: string; + attribs: Object; + children: CheerioElement[]; + next: CheerioElement; + prev: CheerioElement; + parent: CheerioElement; + root: CheerioElement; } declare module "cheerio" { - export function load (html : string, options?: CheerioOptionsInterface) : CheerioStatic; -} + export function load(html: string, options?: CheerioOptionsInterface): CheerioStatic; +} \ No newline at end of file diff --git a/cheerio/cheerio.d.ts.tscparams b/cheerio/cheerio.d.ts.tscparams deleted file mode 100644 index e16c76dff..000000000 --- a/cheerio/cheerio.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" From 39c44eb49cbc43f1e6dde2fbca8ed3cfe74f55ce Mon Sep 17 00:00:00 2001 From: Horiuchi_H Date: Tue, 17 Jun 2014 15:23:55 +0900 Subject: [PATCH 010/324] add Profile common interface --- passport-facebook/passport-facebook.d.ts | 31 +++++++++++++++--------- passport/passport.d.ts | 19 +++++++++++++++ 2 files changed, 38 insertions(+), 12 deletions(-) diff --git a/passport-facebook/passport-facebook.d.ts b/passport-facebook/passport-facebook.d.ts index 47c9b68bb..0cf0cfae0 100644 --- a/passport-facebook/passport-facebook.d.ts +++ b/passport-facebook/passport-facebook.d.ts @@ -10,18 +10,25 @@ declare module 'passport-facebook' { import passport = require('passport'); import express = require('express'); - interface Profile { - id:string; - provider:string; - displayName:string; - name:{familyName:string; givenName:string; middleName:string}; - profileUrl:string; + interface Profile extends passport.Profile { + gender: string; + profileUrl: string; } - class Strategy implements passport.Strategy{ - constructor(options:{clientID:string; clientSecret:string; callbackURL:string}, - verify:(accessToken:string, refreshToken:string, profile:Profile, done:(error:any, user?:any) => void) => void); - name: string; - authenticate:(req: express.Request, options?: Object) => void; + interface IStrategyOption { + clientID: string; + clientSecret: string; + callbackURL: string; + + scopeSeparator?: string; + enableProof?: boolean; + profileFields?: string[]; } -} \ No newline at end of file + + class Strategy implements passport.Strategy { + constructor(options: IStrategyOption, + verify: (accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any) => void) => void); + name: string; + authenticate: (req: express.Request, options?: Object) => void; + } +} diff --git a/passport/passport.d.ts b/passport/passport.d.ts index cd86228f6..3b46c7d8f 100644 --- a/passport/passport.d.ts +++ b/passport/passport.d.ts @@ -42,6 +42,24 @@ declare module 'passport' { name?: string; authenticate(req: express.Request, options?: Object): void; } + + interface Profile { + provider: string; + id: string; + displayName: string; + name? : { + familyName: string; + givenName: string; + middleName?: string; + }; + emails?: { + value: string; + type?: string; + }[]; + photos?: { + value: string; + }[]; + } } declare module Express { @@ -60,3 +78,4 @@ declare module Express { isUnauthenticated(): boolean; } } + From cc273d67eca0aa0064c2662ba01a8ae6436b09ae Mon Sep 17 00:00:00 2001 From: VILIC VANE Date: Tue, 17 Jun 2014 14:45:58 +0800 Subject: [PATCH 011/324] remove old one --- cheerio/cheerio-old.d.ts | 81 ---------------------------------------- 1 file changed, 81 deletions(-) delete mode 100644 cheerio/cheerio-old.d.ts diff --git a/cheerio/cheerio-old.d.ts b/cheerio/cheerio-old.d.ts deleted file mode 100644 index b0e09b778..000000000 --- a/cheerio/cheerio-old.d.ts +++ /dev/null @@ -1,81 +0,0 @@ -// Type definitions for Cheerio -// Project: https://github.com/MatthewMueller/cheerio -// Definitions by: Bret Little -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -interface Cheerio { - - addClass(classNames: string): Cheerio; - hasClass(className: string): boolean; - removeClass(className?: any): Cheerio; - - attr(attributeName: string, value: any): Cheerio; - attr(attributeName: string): string; - removeAttr(attributeName: any): Cheerio; - - find(selector: string): Cheerio; - - parent(): Cheerio; - - next(): Cheerio; - prev(): Cheerio; - - siblings(): Cheerio; - - children(selector?: any): Cheerio; - - each(func: (index: any, elem: any) => Cheerio); - - map(callback: (index: any, domElement: Element) =>any): Cheerio; - - filter(selector: string): Cheerio; - filter(func: (index: any) =>any): Cheerio; - - first(): Cheerio; - last(): Cheerio; - - eq(index: number): Cheerio; - - append(...content: any[]): Cheerio; - prepend(...content: any[]): Cheerio; - after(...content: any[]): Cheerio; - before(...content: any[]): Cheerio; - remove(selector: string): Cheerio; - replaceWith(content: string): Cheerio; - empty(): Cheerio; - - html(htmlString: string): Cheerio; - html(): string; - - text(textString: string): Cheerio; - text(): string; - - toArray(): any[]; - - clone() : Cheerio; - root() : Cheerio; - dom(): any; - - contains(container: Element, contained: Element): boolean; - isArray(obj: any): boolean; - inArray(value: any, array: any[], fromIndex?: number): number; - merge(first: any[], second: any[]): any[]; - - -} - -interface CheerioOptionsInterface { - ignoreWhitespace?: boolean; - xmlMode?: boolean; - lowerCaseTags?: boolean; -} - -interface CheerioStatic { - (...selectors: any[]): Cheerio; - (): Cheerio; -} - -declare module "cheerio" { - export function load (html : string, options?: CheerioOptionsInterface) : CheerioStatic; -} From 38466bd67765f7e59488365d67ae093a1083e257 Mon Sep 17 00:00:00 2001 From: VILIC VANE Date: Tue, 17 Jun 2014 16:43:35 +0800 Subject: [PATCH 012/324] change return type of data() to any --- cheerio/cheerio.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cheerio/cheerio.d.ts b/cheerio/cheerio.d.ts index 92334de45..f0bf372f4 100644 --- a/cheerio/cheerio.d.ts +++ b/cheerio/cheerio.d.ts @@ -16,7 +16,7 @@ interface Cheerio { attr(name: string): string; attr(name: string, value: any): Cheerio; - data(): Object; + data(): any; val(): string; val(value: string): Cheerio; From 607b885c201feeceae8270eca8be2cd819c035ab Mon Sep 17 00:00:00 2001 From: VILIC VANE Date: Tue, 17 Jun 2014 16:48:40 +0800 Subject: [PATCH 013/324] add old version of cheerio.d.ts --- cheerio/cheerio-old-test.ts | 65 +++++++++++++++++++++++++++++ cheerio/cheerio-old.d.ts | 81 +++++++++++++++++++++++++++++++++++++ 2 files changed, 146 insertions(+) create mode 100644 cheerio/cheerio-old-test.ts create mode 100644 cheerio/cheerio-old.d.ts diff --git a/cheerio/cheerio-old-test.ts b/cheerio/cheerio-old-test.ts new file mode 100644 index 000000000..99b351165 --- /dev/null +++ b/cheerio/cheerio-old-test.ts @@ -0,0 +1,65 @@ +/// + +import cheerio = require("cheerio"); + +var $ = cheerio.load(""); +var $el = $('selector'); +var $multiEl = $('seletor', 'selector', 'selector'); + +$el.addClass("class").addClass("test"); +$el.hasClass("test"); +$el.removeClass("class").removeClass("test"); + +$el.attr('class'); +$el.attr('class', 'test'); +$el.removeAttr("class").removeAttr("test"); + +$el.find("ul").find("> li"); + +$el.parent().parent(); +$el.next().next(); +$el.prev().prev(); +$el.siblings().siblings(); + +$el.children().children(); +$el.children("li").children("a"); + +$el.children().each((index, element) => { + return $(element).find('t'); +}); + +$el.children().map((index, element) => { + return $(element).find('t'); +}); + +$el.children().filter((index) => { + return $el.children().eq(index).find('t'); +}); + +$el.filter('span').filter('li'); + +$el.first().last().find('t'); + +$('div').eq(0).find('b'); + +$('#id').append("test html", "other html").find('a'); +$('#id').prepend("test html", "other html").find('a'); +$('#id').after("test html", "other html").find('a'); +$('#id').before("test html", "other html").find('a'); + +$el.remove('div').remove('a'); + +$('#id').replaceWith('some html').parent(); +$('#id').empty().parent(); + +$el.html(); +$el.html("").find('div'); + +$el.text(); +$el.text('some text'); + +$el.toArray(); +$el.clone().find('a').parent(); +$el.root().find('a'); + +$el.dom(); \ No newline at end of file diff --git a/cheerio/cheerio-old.d.ts b/cheerio/cheerio-old.d.ts new file mode 100644 index 000000000..8b9542b92 --- /dev/null +++ b/cheerio/cheerio-old.d.ts @@ -0,0 +1,81 @@ +// Type definitions for Cheerio +// Project: https://github.com/MatthewMueller/cheerio +// Definitions by: Bret Little +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +interface Cheerio { + + addClass(classNames: string): Cheerio; + hasClass(className: string): boolean; + removeClass(className?: any): Cheerio; + + attr(attributeName: string, value: any): Cheerio; + attr(attributeName: string): string; + removeAttr(attributeName: any): Cheerio; + + find(selector: string): Cheerio; + + parent(): Cheerio; + + next(): Cheerio; + prev(): Cheerio; + + siblings(): Cheerio; + + children(selector?: any): Cheerio; + + each(func: (index: any, elem: any) => Cheerio); + + map(callback: (index: any, domElement: Element) =>any): Cheerio; + + filter(selector: string): Cheerio; + filter(func: (index: any) =>any): Cheerio; + + first(): Cheerio; + last(): Cheerio; + + eq(index: number): Cheerio; + + append(...content: any[]): Cheerio; + prepend(...content: any[]): Cheerio; + after(...content: any[]): Cheerio; + before(...content: any[]): Cheerio; + remove(selector: string): Cheerio; + replaceWith(content: string): Cheerio; + empty(): Cheerio; + + html(htmlString: string): Cheerio; + html(): string; + + text(textString: string): Cheerio; + text(): string; + + toArray(): any[]; + + clone() : Cheerio; + root() : Cheerio; + dom(): any; + + contains(container: Element, contained: Element): boolean; + isArray(obj: any): boolean; + inArray(value: any, array: any[], fromIndex?: number): number; + merge(first: any[], second: any[]): any[]; + + +} + +interface CheerioOptionsInterface { + ignoreWhitespace?: boolean; + xmlMode?: boolean; + lowerCaseTags?: boolean; +} + +interface CheerioStatic { + (...selectors: any[]): Cheerio; + (): Cheerio; +} + +declare module "cheerio" { + export function load (html : string, options?: CheerioOptionsInterface) : CheerioStatic; +} \ No newline at end of file From 173e516840feff063b507c15ab5b8d93814cb467 Mon Sep 17 00:00:00 2001 From: VILIC VANE Date: Tue, 17 Jun 2014 16:56:37 +0800 Subject: [PATCH 014/324] update reference --- cheerio/cheerio-old-test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cheerio/cheerio-old-test.ts b/cheerio/cheerio-old-test.ts index 99b351165..a20733341 100644 --- a/cheerio/cheerio-old-test.ts +++ b/cheerio/cheerio-old-test.ts @@ -1,4 +1,4 @@ -/// +/// import cheerio = require("cheerio"); From 8b2b1f3f85bce3dc2ffb98da509e64546bfcc2a8 Mon Sep 17 00:00:00 2001 From: VILIC VANE Date: Tue, 17 Jun 2014 16:59:50 +0800 Subject: [PATCH 015/324] remove the old definition files --- cheerio/cheerio-old-test.ts | 65 ----------------------------- cheerio/cheerio-old.d.ts | 81 ------------------------------------- 2 files changed, 146 deletions(-) delete mode 100644 cheerio/cheerio-old-test.ts delete mode 100644 cheerio/cheerio-old.d.ts diff --git a/cheerio/cheerio-old-test.ts b/cheerio/cheerio-old-test.ts deleted file mode 100644 index a20733341..000000000 --- a/cheerio/cheerio-old-test.ts +++ /dev/null @@ -1,65 +0,0 @@ -/// - -import cheerio = require("cheerio"); - -var $ = cheerio.load(""); -var $el = $('selector'); -var $multiEl = $('seletor', 'selector', 'selector'); - -$el.addClass("class").addClass("test"); -$el.hasClass("test"); -$el.removeClass("class").removeClass("test"); - -$el.attr('class'); -$el.attr('class', 'test'); -$el.removeAttr("class").removeAttr("test"); - -$el.find("ul").find("> li"); - -$el.parent().parent(); -$el.next().next(); -$el.prev().prev(); -$el.siblings().siblings(); - -$el.children().children(); -$el.children("li").children("a"); - -$el.children().each((index, element) => { - return $(element).find('t'); -}); - -$el.children().map((index, element) => { - return $(element).find('t'); -}); - -$el.children().filter((index) => { - return $el.children().eq(index).find('t'); -}); - -$el.filter('span').filter('li'); - -$el.first().last().find('t'); - -$('div').eq(0).find('b'); - -$('#id').append("test html", "other html").find('a'); -$('#id').prepend("test html", "other html").find('a'); -$('#id').after("test html", "other html").find('a'); -$('#id').before("test html", "other html").find('a'); - -$el.remove('div').remove('a'); - -$('#id').replaceWith('some html').parent(); -$('#id').empty().parent(); - -$el.html(); -$el.html("").find('div'); - -$el.text(); -$el.text('some text'); - -$el.toArray(); -$el.clone().find('a').parent(); -$el.root().find('a'); - -$el.dom(); \ No newline at end of file diff --git a/cheerio/cheerio-old.d.ts b/cheerio/cheerio-old.d.ts deleted file mode 100644 index 8b9542b92..000000000 --- a/cheerio/cheerio-old.d.ts +++ /dev/null @@ -1,81 +0,0 @@ -// Type definitions for Cheerio -// Project: https://github.com/MatthewMueller/cheerio -// Definitions by: Bret Little -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -interface Cheerio { - - addClass(classNames: string): Cheerio; - hasClass(className: string): boolean; - removeClass(className?: any): Cheerio; - - attr(attributeName: string, value: any): Cheerio; - attr(attributeName: string): string; - removeAttr(attributeName: any): Cheerio; - - find(selector: string): Cheerio; - - parent(): Cheerio; - - next(): Cheerio; - prev(): Cheerio; - - siblings(): Cheerio; - - children(selector?: any): Cheerio; - - each(func: (index: any, elem: any) => Cheerio); - - map(callback: (index: any, domElement: Element) =>any): Cheerio; - - filter(selector: string): Cheerio; - filter(func: (index: any) =>any): Cheerio; - - first(): Cheerio; - last(): Cheerio; - - eq(index: number): Cheerio; - - append(...content: any[]): Cheerio; - prepend(...content: any[]): Cheerio; - after(...content: any[]): Cheerio; - before(...content: any[]): Cheerio; - remove(selector: string): Cheerio; - replaceWith(content: string): Cheerio; - empty(): Cheerio; - - html(htmlString: string): Cheerio; - html(): string; - - text(textString: string): Cheerio; - text(): string; - - toArray(): any[]; - - clone() : Cheerio; - root() : Cheerio; - dom(): any; - - contains(container: Element, contained: Element): boolean; - isArray(obj: any): boolean; - inArray(value: any, array: any[], fromIndex?: number): number; - merge(first: any[], second: any[]): any[]; - - -} - -interface CheerioOptionsInterface { - ignoreWhitespace?: boolean; - xmlMode?: boolean; - lowerCaseTags?: boolean; -} - -interface CheerioStatic { - (...selectors: any[]): Cheerio; - (): Cheerio; -} - -declare module "cheerio" { - export function load (html : string, options?: CheerioOptionsInterface) : CheerioStatic; -} \ No newline at end of file From ae9f9a270720100f2b5ddfe7319a855450e22f0d Mon Sep 17 00:00:00 2001 From: Horiuchi_H Date: Wed, 18 Jun 2014 19:09:57 +0900 Subject: [PATCH 016/324] bugfix & rename test file --- .../{passport-test.ts => passport-tests.ts} | 29 ++++++++++++++++++- passport/passport.d.ts | 4 +-- 2 files changed, 30 insertions(+), 3 deletions(-) rename passport/{passport-test.ts => passport-tests.ts} (61%) diff --git a/passport/passport-test.ts b/passport/passport-tests.ts similarity index 61% rename from passport/passport-test.ts rename to passport/passport-tests.ts index e3ee9d4f2..7542e2e0e 100644 --- a/passport/passport-test.ts +++ b/passport/passport-tests.ts @@ -34,7 +34,7 @@ app.post('/login', }); app.post('/login', function(req, res, next) { - passport.authenticate('local', function(err, user, info) { + passport.authenticate('local', function(err: any, user: { username: string; }, info: { message: string; }) { if (err) { return next(err) } if (!user) { req.session.error = info.message; @@ -52,6 +52,33 @@ app.get('/logout', function(req, res) { res.redirect('/'); }); +function authSetting(): void { + var authOption = { + successRedirect: '/', + failureRedirect: '/login', + }; + var successCallback = (req: express.Request, res: express.Response) => { + res.redirect('/'); + }; + + app.get('/auth/facebook', + passport.authenticate('facebook')); + app.get('/auth/facebook/callback', + passport.authenticate('facebook', authOption), successCallback); + + app.get('/auth/twitter', + passport.authenticate('twitter')); + app.get('/auth/twitter/callback', + passport.authenticate('twitter', authOption)); + + app.get('/auth/google', + passport.authenticate('google', { scope: + [ 'https://www.googleapis.com/auth/userinfo.profile' ] })); + app.get('/auth/google/callback', + passport.authenticate('google', authOption), successCallback); + +} + function ensureAuthenticated(req: express.Request, res: express.Response, next: (err?: any) => void) { if (req.isAuthenticated()) { return next(); } if (req.isUnauthenticated()) { diff --git a/passport/passport.d.ts b/passport/passport.d.ts index 3b46c7d8f..fbb5f1164 100644 --- a/passport/passport.d.ts +++ b/passport/passport.d.ts @@ -15,8 +15,8 @@ declare module 'passport' { function initialize(options?: { userProperty: string; }): express.Handler; function session(options?: { pauseStream: boolean; }): express.Handler; - function authenticate(strategy: string, options: Object, callback?: express.Handler): express.Handler; - function authenticate(strategy: string, callback2: (err: any, user: any, info: any) => void): express.Handler; + function authenticate(strategy: string, callback?: Function): express.Handler; + function authenticate(strategy: string, options: Object, callback?: Function): express.Handler; function authorize(strategy: string, options: Object, callback?: express.Handler): express.Handler; function serializeUser(fn: (user: any, done: (err: any, id: any) => void) => void): void; function deserializeUser(fn: (id: any, done: (err: any, user: any) => void) => void): void; From 3016f859a8c669f66e17c214e5ca847b45cb70d7 Mon Sep 17 00:00:00 2001 From: Steven Date: Wed, 18 Jun 2014 10:46:45 -0700 Subject: [PATCH 017/324] Most return types should be JQuery Since select2 is a JQuery plugin, it support chaining therefore the majority of methods return a JQuery object (typically the original JQuery object besides 'container' which returns the container element). --- select2/select2.d.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/select2/select2.d.ts b/select2/select2.d.ts index 3cf787a95..7e7c9acf4 100644 --- a/select2/select2.d.ts +++ b/select2/select2.d.ts @@ -113,35 +113,35 @@ interface JQuery { /** * Reverts changes to DOM done by Select2. Any selection done via Select2 will be preserved. */ - select2(method: 'destroy'): void; + select2(method: 'destroy'): JQuery; /** * Opens the dropdown */ - select2(method: 'open'): void; + select2(method: 'open'): JQuery; /** * Closes the dropdown */ - select2(method: 'close'): void; + select2(method: 'close'): JQuery; /** * Enables or disables Select2 and its underlying form component * @param value True if it should be enabled false if it should be disabled */ - select2(method: 'enable', value: boolean): void; + select2(method: 'enable', value: boolean): JQuery; /** * Toggles readonly mode on Select2 and its underlying form component * @param value True if it should be readonly false if it should be read write */ - select2(method: 'readonly', value: boolean): void; + select2(method: 'readonly', value: boolean): JQuery; /** * Retrieves the main container element that wraps all of DOM added by Select2 */ - select2(method: 'container'): HTMLElement; + select2(method: 'container'): JQuery; /** * Notifies Select2 that a drag and drop sorting operation has started */ - select2(method: 'onSortStart'): void; + select2(method: 'onSortStart'): JQuery; /** * Notifies Select2 that a drag and drop sorting operation has finished */ - select2(method: 'onSortEnd'): void; + select2(method: 'onSortEnd'): JQuery; } From 492d456a36abef7eea96331d86632b9b67d00439 Mon Sep 17 00:00:00 2001 From: Nathan Brown Date: Wed, 18 Jun 2014 17:49:05 -0700 Subject: [PATCH 018/324] angular.d.ts: new interface IServiceProviderClass Instead of IModule.provider simply accepting an Function for a class constructor, use an interface to enforce the type of class. --- angularjs/angular.d.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 92a02eef8..f2ecbd783 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -18,6 +18,11 @@ interface Function { /////////////////////////////////////////////////////////////////////////////// declare module ng { + // not directly implemented, but ensures that constructed class implements $get + interface IServiceProviderClass { + new(...args: any[]): IServiceProvider; + } + // All service providers extend this interface interface IServiceProvider { $get: any; @@ -140,9 +145,9 @@ declare module ng { filter(name: string, filterFactoryFunction: Function): IModule; filter(name: string, inlineAnnotatedFunction: any[]): IModule; filter(object: Object): IModule; - provider(name: string, serviceProviderConstructor: Function): IModule; + provider(name: string, serviceProviderConstructor: IServiceProviderClass): IModule; provider(name: string, inlineAnnotatedConstructor: any[]): IModule; - provider(name: string, providerObject: auto.IProvider): IModule; + provider(name: string, providerObject: IServiceProvider): IModule; provider(object: Object): IModule; run(initializationFunction: Function): IModule; run(inlineAnnotatedFunction: any[]): IModule; @@ -991,9 +996,6 @@ declare module ng { // AUTO module (angular.js) /////////////////////////////////////////////////////////////////////////// export module auto { - interface IProvider { - $get: any; - } /////////////////////////////////////////////////////////////////////// // InjectorService From 3a36795eb258f1797f7ebea8c496201a5ea1436b Mon Sep 17 00:00:00 2001 From: Nathan Brown Date: Wed, 18 Jun 2014 18:13:14 -0700 Subject: [PATCH 019/324] angular.d.ts: new interface IDirectiveFactory Adds intellisense when constructing directive objects --- angularjs/angular.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index f2ecbd783..cb03b6925 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -124,7 +124,7 @@ declare module ng { */ controller(name: string, inlineAnnotatedConstructor: any[]): IModule; controller(object : Object): IModule; - directive(name: string, directiveFactory: Function): IModule; + directive(name: string, directiveFactory: IDirectiveFactory): IModule; directive(name: string, inlineAnnotatedFunction: any[]): IModule; directive(object: Object): IModule; /** @@ -919,6 +919,11 @@ declare module ng { // and http://docs.angularjs.org/guide/directive /////////////////////////////////////////////////////////////////////////// + interface IDirectiveFactory { + (...args: any[]): IDirective; + } + + interface IDirective{ compile?: (templateElement: IAugmentedJQuery, From ef0e9da858b404c022455cbb38e2e95b3f6fa13c Mon Sep 17 00:00:00 2001 From: Nathan Brown Date: Wed, 18 Jun 2014 18:32:01 -0700 Subject: [PATCH 020/324] angular.d.ts: new interface IServiceProviderFactory Missed provider functions that return objects. Ensure that they also implement ng.IServiceProvider. --- angularjs/angular.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index cb03b6925..e8d1db837 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -22,6 +22,10 @@ declare module ng { interface IServiceProviderClass { new(...args: any[]): IServiceProvider; } + + interface IServiceProviderFactory { + (...args: any[]): IServiceProvider; + } // All service providers extend this interface interface IServiceProvider { @@ -145,6 +149,7 @@ declare module ng { filter(name: string, filterFactoryFunction: Function): IModule; filter(name: string, inlineAnnotatedFunction: any[]): IModule; filter(object: Object): IModule; + provider(name: string, serviceProviderFactory: IServiceProviderFactory): IModule; provider(name: string, serviceProviderConstructor: IServiceProviderClass): IModule; provider(name: string, inlineAnnotatedConstructor: any[]): IModule; provider(name: string, providerObject: IServiceProvider): IModule; From dd4602b27a74218079be508e51ea90f8df68ce44 Mon Sep 17 00:00:00 2001 From: Nathan Brown Date: Wed, 18 Jun 2014 18:41:06 -0700 Subject: [PATCH 021/324] angular-agility need to use ng.IServiceProvider --- angular-agility/angular-agility.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/angular-agility/angular-agility.d.ts b/angular-agility/angular-agility.d.ts index c11aff0b0..872971aed 100644 --- a/angular-agility/angular-agility.d.ts +++ b/angular-agility/angular-agility.d.ts @@ -41,7 +41,7 @@ declare module aa { [settingName: string]: any; } - export interface IFormExtensionsProvider extends ng.auto.IProvider { + export interface IFormExtensionsProvider extends ng.IServiceProvider { defaultLabelStrategy:string; defaultFieldGroupStrategy:string; defaultValMsgPlacementStrategy:string; @@ -88,7 +88,7 @@ declare module aa { message:string; } - export interface INotifyConfigProvider extends ng.auto.IProvider { + export interface INotifyConfigProvider extends ng.IServiceProvider { notifyConfigs:any; defaultTargetContainerName:string; defaultNotifyConfig:string; From 72b9fbed7f7b96de942005c96e23f3535e7d0084 Mon Sep 17 00:00:00 2001 From: Nathan Brown Date: Wed, 18 Jun 2014 19:55:32 -0700 Subject: [PATCH 022/324] angular.d.ts: update test to use class for module Converted the test module, 'http-auth-interceptor', to a class to eliminate error on using anonymous type constructor. --- angularjs/angular-tests.ts | 63 +++++++++++++++++++++++--------------- 1 file changed, 38 insertions(+), 25 deletions(-) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 419bed0d6..bac077131 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -7,27 +7,27 @@ * (c) 2012 Witold Szczerba * License: MIT */ -angular.module('http-auth-interceptor', []) - .provider('authService', function () { - /** - * Holds all the requests which failed due to 401 response, - * so they can be re-requested in future, once login is completed. - */ - var buffer: { config: ng.IRequestConfig; deferred: ng.IDeferred; }[] = []; +class AuthService { + /** + * Holds all the requests which failed due to 401 response, + * so they can be re-requested in future, once login is completed. + */ + buffer: { config: ng.IRequestConfig; deferred: ng.IDeferred; }[] = []; - /** - * Required by HTTP interceptor. - * Function is attached to provider to be invisible for regular users of this service. - */ - this.pushToBuffer = function (config: ng.IRequestConfig, deferred: ng.IDeferred) { - buffer.push({ - config: config, - deferred: deferred - }); - } + /** + * Required by HTTP interceptor. + * Function is attached to provider to be invisible for regular users of this service. + */ + pushToBuffer = function(config: ng.IRequestConfig, deferred: ng.IDeferred) { + this.buffer.push({ + config: config, + deferred: deferred + }); + } - this.$get = ['$rootScope', '$injector', function ($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) { + $get = [ + '$rootScope', '$injector', function($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) { var $http: ng.IHttpService; //initialized later because of circular dependency problem function retry(config: ng.IRequestConfig, deferred: ng.IDeferred) { $http = $http || $injector.get('$http'); @@ -36,20 +36,25 @@ angular.module('http-auth-interceptor', []) }); } function retryAll() { - for (var i = 0; i < buffer.length; ++i) { - retry(buffer[i].config, buffer[i].deferred); + for (var i = 0; i < this.buffer.length; ++i) { + retry(this.buffer[i].config, this.buffer[i].deferred); } - buffer = []; + this.buffer = []; } - return { + return { loginConfirmed: function () { $rootScope.$broadcast('event:auth-loginConfirmed'); retryAll(); } } - }] - }) + } + ]; +} + +angular.module('http-auth-interceptor', []) + + .provider('authService', AuthService) /** * $http interceptor. @@ -176,7 +181,8 @@ mod.factory(My.Namespace); mod.filter('name', function ($scope: ng.IScope) { }) mod.filter('name', ['$scope', function ($scope: ng.IScope) { }]) mod.filter(My.Namespace); -mod.provider('name', function ($scope: ng.IScope) { }) +mod.provider('name', function ($scope: ng.IScope) { return { $get: () => { } } }) +mod.provider('name', TestProvider); mod.provider('name', ['$scope', function ($scope: ng.IScope) { }]) mod.provider(My.Namespace); mod.service('name', function ($scope: ng.IScope) { }) @@ -189,6 +195,13 @@ mod.value('name', 23); mod.value('name', "23"); mod.value(My.Namespace); +class TestProvider implements ng.IServiceProvider { + constructor(private $scope: ng.IScope) { + } + + $get() { + } +} // Promise signature tests var foo: ng.IPromise; From b50af00be53d4b886638218ee703164088206d32 Mon Sep 17 00:00:00 2001 From: zaneli Date: Mon, 23 Jun 2014 11:07:10 +0900 Subject: [PATCH 023/324] Add definitions for jQuery Notify bar --- CONTRIBUTORS.md | 1 + jquery.notifyBar/jquery.notifyBar-test.ts | 66 +++++++++++++++ jquery.notifyBar/jquery.notifyBar.d.ts | 99 +++++++++++++++++++++++ 3 files changed, 166 insertions(+) create mode 100644 jquery.notifyBar/jquery.notifyBar-test.ts create mode 100644 jquery.notifyBar/jquery.notifyBar.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 1d32f8c2f..c69f938bb 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -156,6 +156,7 @@ All definitions files include a header with the author and editors, so at some p * [jQuery.jNotify](http://jnotify.codeplex.com) (by [James Curran](https://github.com/jamescurran/)) * [jQuery.joyride](http://zurb.com/playground/jquery-joyride-feature-tour-plugin) (by [Vincent Bortone](https://github.com/vbortone)) * [jQuery.jSignature](https://github.com/willowsystems/jSignature) (by [Patrick Magee](https://github.com/pjmagee)) +* [jQuery.notifyBar](http://www.whoop.ee/posts/2013-04-05-the-resurrection-of-jquery-notify-bar/) (by [Shunsuke Ohtani](https://github.com/zaneli)) * [jQuery.noty](http://needim.github.io/noty/) (by [Aaron King](https://github.com/kingdango/)) * [jQuery.payment](http://needim.github.io/noty/) (by [Eric J. Smith](https://github.com/ejsmith/)) * [jQuery.pickadate](https://github.com/amsul/pickadate.js) (by [Theodore Brown](https://github.com/theodorejb)) diff --git a/jquery.notifyBar/jquery.notifyBar-test.ts b/jquery.notifyBar/jquery.notifyBar-test.ts new file mode 100644 index 000000000..8338fc830 --- /dev/null +++ b/jquery.notifyBar/jquery.notifyBar-test.ts @@ -0,0 +1,66 @@ +/// + +$(function() { + $.notifyBar({ + html: "Autostart" + }); + + $("#common").click(function () { + $.notifyBar(); + }); + $("#error").click(function () { + $.notifyBar({ cssClass: "error", html: "Error occurred!" }); + }); + $("#success").click(function () { + $.notifyBar({ cssClass: "success", html: "Your data has been changed!" }); + }); + $("#warning").click(function() { + $.notifyBar({ cssClass: "warning", html: "Settings aren't changed!" }); + }) + $("#custom").click(function () { + $.notifyBar({ cssClass: "custom", html: "Your data has been changed!" }); + }); + $("#close").click(function () { + $.notifyBar({ html: "Click 'close' to hide notify bar", close: true, closeOnClick: false }); + }); + $("#position").click(function () { + $.notifyBar({ html: "At bottom", position: "bottom" }); + }); + + $("#events").click(function () { + $.notifyBar({ + html: "Test events", + onBeforeShow: function () { + $("#onBeforeShow").html("onBeforeShow - ok"); + }, + onShow: function () { + $("#onShow").html("onShow - ok"); + }, + onBeforeHide: function () { + $("#onBeforeHide").html("onBeforeHide - ok"); + }, + onHide: function () { + $("#onHide").html("onHide - ok"); + } + }); + }); + + $("#delay").click(function () { + $.notifyBar({ html: "delay 1000000", delay: 1000000 }); + }); + $("#speed-string").click(function () { + $.notifyBar({ html: "speed normal", animationSpeed: "normal" }); + }); + $("#speed-number").click(function () { + $.notifyBar({ html: "speed normal", animationSpeed: 500 }); + }); + $("#jqObject").click(function () { + $.notifyBar({ html: "set jqObject", jqObject: $("#jqObject") }); + }); + $("#closeText").click(function () { + $.notifyBar({ html: "set close text", closeText: "close" }); + }); + $("#closeOnOver").click(function () { + $.notifyBar({ html: "enable close on over", close: false, closeOnClick: false, closeOnOver: true }); + }); +}); diff --git a/jquery.notifyBar/jquery.notifyBar.d.ts b/jquery.notifyBar/jquery.notifyBar.d.ts new file mode 100644 index 000000000..b33c54337 --- /dev/null +++ b/jquery.notifyBar/jquery.notifyBar.d.ts @@ -0,0 +1,99 @@ +// Type definitions for jQuery Notify Bar 1.4 +// Project: http://www.whoop.ee/posts/2013-04-05-the-resurrection-of-jquery-notify-bar/ +// Definitions by: Shunsuke Ohtani +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module JQueryNotifyBar { + + interface NotifyBarOptions { + /** + * What text will be inside bar. Can be HTML or just text. + */ + html?: string; + + /** + * How long bar will be delayed, doesn't count animation time. + */ + delay?: number; + + /** + * Custom jQuery object for notify bar. + */ + jqObject?: JQuery; + + /** + * You can define own CSS class for Notify bar. There are too premade classes "error", "warning" and "success". + */ + cssClass?: string; + + /** + * If set to true close button will be displayed. + */ + close?: boolean; + + /** + * Sets the text to close button. + */ + closeText?: string; + + /** + * If enabled, user can hide notify bar just by click on it. + */ + closeOnClick?: boolean; + + /** + * If enabled, user can hide notify bar just by moving mouse cursor on it. + */ + closeOnOver?: boolean; + + /** + * Callback on before show. + */ + onBeforeShow?: () => any; + + /** + * Callback on show. + */ + onShow?: () => any; + + /** + * Callback on before hide. + */ + onBeforeHide?: () => any; + + /** + * Callback on hide. + */ + onHide?: () => any; + + /** + * Set the position of notify bar. Possible values are "top", "bottom". + */ + position?: string; + } + + interface NotifyBarOptionsForAnimationSpeedString extends NotifyBarOptions { + /** + * How long this bar will be slided up and down. Possible values are "slow", "default", "normal", "fast". + */ + animationSpeed?: string; + } + + interface NotifyBarOptionsForAnimationSpeedNumber extends NotifyBarOptions { + /** + * How long this bar will be slided up and down. + */ + animationSpeed?: number; + } +} + +interface JQueryStatic { + /** + * Show notify bar. + * + * @param notify bar options + */ + notifyBar(options?: JQueryNotifyBar.NotifyBarOptions): void; +} \ No newline at end of file From 6bf9011af7808aa2a6a74c0bf773f7565033d6a0 Mon Sep 17 00:00:00 2001 From: zaneli Date: Mon, 23 Jun 2014 11:31:49 +0900 Subject: [PATCH 024/324] fix param name in comment. --- jquery.notifyBar/jquery.notifyBar.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jquery.notifyBar/jquery.notifyBar.d.ts b/jquery.notifyBar/jquery.notifyBar.d.ts index b33c54337..22e012673 100644 --- a/jquery.notifyBar/jquery.notifyBar.d.ts +++ b/jquery.notifyBar/jquery.notifyBar.d.ts @@ -93,7 +93,7 @@ interface JQueryStatic { /** * Show notify bar. * - * @param notify bar options + * @param options notify bar options */ notifyBar(options?: JQueryNotifyBar.NotifyBarOptions): void; -} \ No newline at end of file +} From 1dd12f188e112d62d47e6ffb8c648a23d2a55a95 Mon Sep 17 00:00:00 2001 From: bolkhovsky Date: Mon, 23 Jun 2014 17:17:08 +0400 Subject: [PATCH 025/324] add KnockoutBindingAccessor interface to extend custom bindings API definition --- knockout/knockout.d.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index 9c4e02bd8..512a6a305 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -123,9 +123,14 @@ interface KnockoutBindingContext { createChildContext(dataItemOrAccessor: any, dataItemAlias?: any, extendCallback?: Function): any; } +interface KnockoutBindingAccessor { + get(name: string): any; + has(name: string): boolean; +} + interface KnockoutBindingHandler { - init?(element: any, valueAccessor: () => any, allBindingsAccessor: () => any, viewModel: any, bindingContext: KnockoutBindingContext): void; - update?(element: any, valueAccessor: () => any, allBindingsAccessor: () => any, viewModel: any, bindingContext: KnockoutBindingContext): void; + init? (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutBindingAccessor, viewModel: any, bindingContext: KnockoutBindingContext): void; + update? (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutBindingAccessor, viewModel: any, bindingContext: KnockoutBindingContext): void; options?: any; } From e7a6ee50c2b6a622841f6708ab9c36357159f44d Mon Sep 17 00:00:00 2001 From: bolkhovsky Date: Mon, 23 Jun 2014 17:47:43 +0400 Subject: [PATCH 026/324] fix definition to support dynamic binding property access --- knockout/knockout.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index 512a6a305..006b83361 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -124,6 +124,7 @@ interface KnockoutBindingContext { } interface KnockoutBindingAccessor { + (): any; get(name: string): any; has(name: string): boolean; } From 361ce9e2f34e4ea805553a41ec80b2d5d545d679 Mon Sep 17 00:00:00 2001 From: bolkhovsky Date: Tue, 24 Jun 2014 00:28:16 +0400 Subject: [PATCH 027/324] change interface name to historical (4 days earlier) version --- knockout/knockout.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index 006b83361..0c57d2ad9 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -123,15 +123,15 @@ interface KnockoutBindingContext { createChildContext(dataItemOrAccessor: any, dataItemAlias?: any, extendCallback?: Function): any; } -interface KnockoutBindingAccessor { +interface KnockoutAllBindingsAccessor { (): any; get(name: string): any; has(name: string): boolean; } interface KnockoutBindingHandler { - init? (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutBindingAccessor, viewModel: any, bindingContext: KnockoutBindingContext): void; - update? (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutBindingAccessor, viewModel: any, bindingContext: KnockoutBindingContext): void; + init? (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext): void; + update? (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext): void; options?: any; } From d1db936207c9b28d1bdff5a081d1f0ac1b94975b Mon Sep 17 00:00:00 2001 From: bolkhovsky Date: Tue, 24 Jun 2014 00:32:47 +0400 Subject: [PATCH 028/324] extend tests for KnockoutAllBindingsAccessor --- knockout/tests/knockout-tests.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/knockout/tests/knockout-tests.ts b/knockout/tests/knockout-tests.ts index da5d1e65a..6d4c9e25d 100644 --- a/knockout/tests/knockout-tests.ts +++ b/knockout/tests/knockout-tests.ts @@ -591,11 +591,15 @@ function test_allBindingsAccessor() { ko.bindingHandlers.allBindingsAccessorTest = { init: (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext) => { var allBindings = allBindingsAccessor(); + var hasBinding = allBindingsAccessor.has("myBindingName"); var myBinding = allBindingsAccessor.get("myBindingName"); + var fnAccessorBinding = allBindingsAccessor().myBindingName; }, update: (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext) => { var allBindings = allBindingsAccessor(); + var hasBinding = allBindingsAccessor.has("myBindingName"); var myBinding = allBindingsAccessor.get("myBindingName"); + var fnAccessorBinding = allBindingsAccessor().myBindingName; } }; } \ No newline at end of file From 2b55cf57dcccfc4952fb4aabea59954f193fea97 Mon Sep 17 00:00:00 2001 From: David Sichau Date: Thu, 26 Jun 2014 17:04:44 +0200 Subject: [PATCH 029/324] added a definition for knockout-amd-helpers --- CONTRIBUTORS.md | 1 + .../knockout-amd-helpers-tests.ts | 23 +++++++++++++ .../knockout-amd-helpers.d.ts | 34 +++++++++++++++++++ 3 files changed, 58 insertions(+) create mode 100644 knockout.amd.helpers/knockout-amd-helpers-tests.ts create mode 100644 knockout.amd.helpers/knockout-amd-helpers.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index ae430f57d..f34a8b244 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -193,6 +193,7 @@ All definitions files include a header with the author and editors, so at some p * [KineticJS](http://kineticjs.com/) (by [Basarat Ali Syed](https://github.com/basarat)) * [Knockback](http://kmalakoff.github.com/knockback/) (by [Marcel Binot](https://github.com/docgit)) * [Knockout.js](http://knockoutjs.com/) (by [Boris Yankov](https://github.com/borisyankov)) +* [Knockout.Amd.Helpers](https://github.com/rniemeyer/knockout-amd-helpers) (by [David Sichau](https://github.com/DavidSichau/)) * [Knockout.DeferredUpdates](https://github.com/mbest/knockout-deferred-updates) (by [Sebastián Galiano](https://github.com/sgaliano)) * [Knockout.ES5](https://github.com/SteveSanderson/knockout-es5) (by [Sebastián Galiano](https://github.com/sgaliano)) * [Knockout.Mapper](https://github.com/LucasLorentz/knockout.mapper) (by [Brandon Meyer](https://github.com/BMeyerKC)) diff --git a/knockout.amd.helpers/knockout-amd-helpers-tests.ts b/knockout.amd.helpers/knockout-amd-helpers-tests.ts new file mode 100644 index 000000000..c5d1b62e0 --- /dev/null +++ b/knockout.amd.helpers/knockout-amd-helpers-tests.ts @@ -0,0 +1,23 @@ +// Tests for knockout.projections.d.ts + +/// +/// + +//The baseDir is used in building the path to use in the require statement. If your modules live in the modules directory, then you can specify it globally here. +ko.bindingHandlers.module.baseDir = "blub"; + +//This allows the ability to globally override the function that the module binding calls after loading an AMD module that does not return a constructor. +ko.bindingHandlers.module.initializer= "initialize"; + +//The dispose method name can be globally overriden. This function is optionally called when a module is being removed/swapped. +ko.bindingHandlers.module.disposeMethod ="dispose"; + +//The templateProperty option can be globally set. If defined, when a module is loaded - if it has a property with the key specified here +// (where the value is a string or function), the value of that property will be used as the template for the module. The result is a fully +// self-contained module (i.e. it has its own template, not an external one). +ko.bindingHandlers.module.templateProperty ="test"; + + +ko.amdTemplateEngine.defaultPath = "your/path/to/templates"; +ko.amdTemplateEngine.defaultSuffix = ".template.html"; +ko.amdTemplateEngine.defaultRequireTextPluginName = "text"; \ No newline at end of file diff --git a/knockout.amd.helpers/knockout-amd-helpers.d.ts b/knockout.amd.helpers/knockout-amd-helpers.d.ts new file mode 100644 index 000000000..34d4eb027 --- /dev/null +++ b/knockout.amd.helpers/knockout-amd-helpers.d.ts @@ -0,0 +1,34 @@ +// Type definitions for knockout-amd-helpers +// Project: https://github.com/rniemeyer/knockout-amd-helpers +// Definitions by: David Sichau +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + + +interface KnockoutAMDModule { + baseDir: string; + initializer: string; + disposeMethod: string; + templateProperty: string; +} + +interface KnockoutAMDTemplate { + defaultPath: string; + defaultSuffix: string; + defaultRequireTextPluginName: string; +} + +interface KnockoutBindingHandlers { + module: KnockoutAMDModule; +} +interface KnockoutStatic { + + amdTemplateEngine: KnockoutAMDTemplate +} + +declare module "knockout-amd-helpers" { + export = ko; +} + +declare var ko: KnockoutStatic; From 57869e481cff2ff12e64690de4b390ffe8b80826 Mon Sep 17 00:00:00 2001 From: Sean Xu Date: Fri, 27 Jun 2014 12:25:38 -0700 Subject: [PATCH 030/324] Created 2.1 definition file. Used 2.0 as a base and changes according to the API change doc ( http://msdn.microsoft.com/en-us/library/windows/apps/dn632432.aspx ) --- winjs/legacy/winjs-2.0.d.ts | 16136 +++++++++++++++++----------------- winjs/legacy/winjs-2.1.d.ts | 7000 +++++++++++++++ 2 files changed, 15068 insertions(+), 8068 deletions(-) create mode 100644 winjs/legacy/winjs-2.1.d.ts diff --git a/winjs/legacy/winjs-2.0.d.ts b/winjs/legacy/winjs-2.0.d.ts index b225ded94..205b41889 100644 --- a/winjs/legacy/winjs-2.0.d.ts +++ b/winjs/legacy/winjs-2.0.d.ts @@ -22,8019 +22,8019 @@ and limitations under the License. * Defines an Element object. **/ interface Element { - winControl: any; // TODO: This should be control? + winControl: any; // TODO: This should be control? } /** * Utility class for easy access to operations on application folders **/ interface IOHelper { - /** - * Determines whether the specified file exists in the folder. - * @param filename The name of the file. - * @returns A promise that completes with a value of either true (if the file exists) or false. - **/ - exists(filename: string): WinJS.Promise; + /** + * Determines whether the specified file exists in the folder. + * @param filename The name of the file. + * @returns A promise that completes with a value of either true (if the file exists) or false. + **/ + exists(filename: string): WinJS.Promise; - /** - * Reads the specified file. If the file doesn't exist, the specified default value is returned. - * @param fileName The file to read from. - * @param def The default value to be returned if the file failed to open. - * @returns A promise that completes with a value that is either the contents of the file, or the specified default value. - **/ - readText(fileName: string, def?: string): WinJS.Promise; + /** + * Reads the specified file. If the file doesn't exist, the specified default value is returned. + * @param fileName The file to read from. + * @param def The default value to be returned if the file failed to open. + * @returns A promise that completes with a value that is either the contents of the file, or the specified default value. + **/ + readText(fileName: string, def?: string): WinJS.Promise; - /** - * Deletes a file from the folder. - * @param fileName The file to be deleted. - * @returns A promise that is fulfilled when the file has been deleted. - **/ - remove(fileName: string): WinJS.Promise; + /** + * Deletes a file from the folder. + * @param fileName The file to be deleted. + * @returns A promise that is fulfilled when the file has been deleted. + **/ + remove(fileName: string): WinJS.Promise; - /** - * Writes the specified text to the specified file. - * @param fileName The name of the file. - * @param text The content to be written to the file. - * @returns A promise that completes with a value that is the number of characters written. - **/ - writeText(fileName: string, text: string): WinJS.Promise; + /** + * Writes the specified text to the specified file. + * @param fileName The name of the file. + * @param text The content to be written to the file. + * @returns A promise that completes with a value that is the number of characters written. + **/ + writeText(fileName: string, text: string): WinJS.Promise; } /** * Provides application-level functionality, for example activation, storage, and application events. **/ declare module WinJS.Application { - //#region Objects + //#region Objects - /** - * The local storage of the application. - **/ - var local: IOHelper; + /** + * The local storage of the application. + **/ + var local: IOHelper; - /** - * The roaming storage of the application. - **/ - var roaming: IOHelper; + /** + * The roaming storage of the application. + **/ + var roaming: IOHelper; - /** - * The temp storage of the application. - **/ - var temp: IOHelper; + /** + * The temp storage of the application. + **/ + var temp: IOHelper; - /** - * An object used for storing app information that can be used to restore the app's state after it has been suspended and then resumed. Data that can usefully be contained in this object includes the current navigation page or any information the user has added to the input controls on the page. You should not add information about customization (for example colors) or user-defined lists of content. - **/ - var sessionState: any; + /** + * An object used for storing app information that can be used to restore the app's state after it has been suspended and then resumed. Data that can usefully be contained in this object includes the current navigation page or any information the user has added to the input controls on the page. You should not add information about customization (for example colors) or user-defined lists of content. + **/ + var sessionState: any; - //#endregion Objects + //#endregion Objects - //#region Methods + //#region Methods - /** - * Informs the application object that asynchronous work is being performed, and that this event handler should not be considered complete until the promise completes. This function can be set inside the handlers for all WinJS.Application events: onactivated oncheckpoint onerror onloaded onready onsettings onunload. - * @param promise The promise that should complete before processing is complete. - **/ - function setPromise(promise: Promise): void; + /** + * Informs the application object that asynchronous work is being performed, and that this event handler should not be considered complete until the promise completes. This function can be set inside the handlers for all WinJS.Application events: onactivated oncheckpoint onerror onloaded onready onsettings onunload. + * @param promise The promise that should complete before processing is complete. + **/ + function setPromise(promise: Promise): void; - //#endregion Methods + //#endregion Methods - //#region Functions + //#region Functions - /** - * Adds an event listener for application-level events: activated, checkpoint, error, loaded, ready, settings, and unload. - * @param type The type (name) of the event. You can use any of the following:"activated", "checkpoint", "error", "loaded", "ready", "settings", and" unload". - * @param listener The listener to invoke when the event is raised. - * @param capture true to initiate capture, otherwise false. - **/ - function addEventListener(type: string, listener: Function, capture?: boolean): void; + /** + * Adds an event listener for application-level events: activated, checkpoint, error, loaded, ready, settings, and unload. + * @param type The type (name) of the event. You can use any of the following:"activated", "checkpoint", "error", "loaded", "ready", "settings", and" unload". + * @param listener The listener to invoke when the event is raised. + * @param capture true to initiate capture, otherwise false. + **/ + function addEventListener(type: string, listener: Function, capture?: boolean): void; - /** - * Queues a checkpoint event. - **/ - function checkpoint(): void; + /** + * Queues a checkpoint event. + **/ + function checkpoint(): void; - /** - * Queues an event to be processed by the WinJS.Application event queue. - * @param eventRecord The event object is expected to have a type property that is used as the event name when dispatching on the WinJS.Application event queue. The entire object is provided to event listeners in the detail property of the event. - **/ - function queueEvent(eventRecord: any): void; + /** + * Queues an event to be processed by the WinJS.Application event queue. + * @param eventRecord The event object is expected to have a type property that is used as the event name when dispatching on the WinJS.Application event queue. The entire object is provided to event listeners in the detail property of the event. + **/ + function queueEvent(eventRecord: any): void; - /** - * Removes an event listener from the control. - * @param type The type (name) of the event. - * @param listener The listener to remove. - * @param useCapture Specifies whether or not to initiate capture. - **/ - function removeEventListener(type: string, listener: Function, useCapture?: any): void; + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture Specifies whether or not to initiate capture. + **/ + function removeEventListener(type: string, listener: Function, useCapture?: any): void; - /** - * Starts dispatching application events (the activated, checkpoint, error, loaded, ready, settings, and unload events). - **/ - function start(): void; + /** + * Starts dispatching application events (the activated, checkpoint, error, loaded, ready, settings, and unload events). + **/ + function start(): void; - /** - * Stops application event processing and resets WinJS.Application to its initial state. All WinJS.Application event listeners (for the activated, checkpoint, error, loaded, ready, settings, and unload events) are removed. - **/ - function stop(): void; + /** + * Stops application event processing and resets WinJS.Application to its initial state. All WinJS.Application event listeners (for the activated, checkpoint, error, loaded, ready, settings, and unload events) are removed. + **/ + function stop(): void; - //#endregion Functions + //#endregion Functions - //#region Events + //#region Events - /** - * Occurs when WinRT activation has occurred. The name of this event is "activated" (and also "mainwindowactivated"). This event occurs after the loaded event and before the ready event. - * @param eventInfo An object that contains information about the event. For more information about event arguments, see the WinRT event argument classes: WebUICachedFileUpdaterActivatedEventArgs, WebUICameraSettingsActivatedEventArgs, WebUIContactPickerActivatedEventArgs, WebUIDeviceActivatedEventArgs, WebUIFileActivatedEventArgs, WebUIFileOpenPickerActivatedEventArgs, WebUIFileSavePickerActivatedEventArgs, WebUILaunchActivatedEventArgs, WebUIPrintTaskSettingsActivatedEventArgs, WebUIProtocolActivatedEventArgs, WebUISearchActivatedEventArgs, WebUIShareTargetActivatedEventArgs. - **/ - function onactivated(eventInfo: CustomEvent): void; + /** + * Occurs when WinRT activation has occurred. The name of this event is "activated" (and also "mainwindowactivated"). This event occurs after the loaded event and before the ready event. + * @param eventInfo An object that contains information about the event. For more information about event arguments, see the WinRT event argument classes: WebUICachedFileUpdaterActivatedEventArgs, WebUICameraSettingsActivatedEventArgs, WebUIContactPickerActivatedEventArgs, WebUIDeviceActivatedEventArgs, WebUIFileActivatedEventArgs, WebUIFileOpenPickerActivatedEventArgs, WebUIFileSavePickerActivatedEventArgs, WebUILaunchActivatedEventArgs, WebUIPrintTaskSettingsActivatedEventArgs, WebUIProtocolActivatedEventArgs, WebUISearchActivatedEventArgs, WebUIShareTargetActivatedEventArgs. + **/ + function onactivated(eventInfo: CustomEvent): void; - /** - * Occurs when receiving PLM notification or when the checkpoint function is called. - * @param eventInfo An object that contains information about the event. The detail property of this object includes the following subproperties: type, setPromise. - **/ - function oncheckpoint(eventInfo: CustomEvent): void; + /** + * Occurs when receiving PLM notification or when the checkpoint function is called. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following subproperties: type, setPromise. + **/ + function oncheckpoint(eventInfo: CustomEvent): void; - /** - * Occurs when an unhandled error has been raised. - * @param eventInfo An object that contains information about the event. - **/ - function onerror(eventInfo: CustomEvent): void; + /** + * Occurs when an unhandled error has been raised. + * @param eventInfo An object that contains information about the event. + **/ + function onerror(eventInfo: CustomEvent): void; - /** - * Occurs after the DOMContentLoaded event, which fires after the page has been parsed but before all the resources are loaded. This event occurs before the activated event and the ready event. - * @param eventInfo An object that contains information about the event. The detail property of this object includes the following subproperties: type, setPromise. - **/ - function onloaded(eventInfo: CustomEvent): void; + /** + * Occurs after the DOMContentLoaded event, which fires after the page has been parsed but before all the resources are loaded. This event occurs before the activated event and the ready event. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following subproperties: type, setPromise. + **/ + function onloaded(eventInfo: CustomEvent): void; - /** - * Occurs when the application is ready. This event occurs after the loaded event and the activated event. - * @param eventInfo An object that contains information about the event. The detail property of this object includes the following sub-properties: type, setPromise. - **/ - function onready(eventInfo: CustomEvent): void; + /** + * Occurs when the application is ready. This event occurs after the loaded event and the activated event. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following sub-properties: type, setPromise. + **/ + function onready(eventInfo: CustomEvent): void; - /** - * Occurs when the settings charm is invoked. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: type, applicationcommands. - **/ - function onsettings(eventInfo: CustomEvent): void; + /** + * Occurs when the settings charm is invoked. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: type, applicationcommands. + **/ + function onsettings(eventInfo: CustomEvent): void; - /** - * Occurs when the application is about to be unloaded. - * @param eventInfo An object that contains information about the event. The detail property of this object includes the following sub-properties: type, setPromise. - **/ - function onunload(eventInfo: CustomEvent): void; + /** + * Occurs when the application is about to be unloaded. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following sub-properties: type, setPromise. + **/ + function onunload(eventInfo: CustomEvent): void; - //#endregion Events + //#endregion Events } /** * Provides functionality for data and template binding. **/ declare module WinJS.Binding { - //#region Properties - - /** - * Determines whether or not binding should automatically set the ID of an element. This property should be set to true in apps that use WinJS (WinJS) binding. - **/ - var optimizeBindingReferences: boolean; - - //#endregion Properties - - //#region Objects - - /** - * Allows you to add bindable properties dynamically. - **/ - var dynamicObservableMixin: { - //#region Methods - - /** - * Adds a property with change notification to this object, including a ECMAScript5 property definition. - * @param name The name of the property to add. - * @param value This object is returned. - **/ - addProperty(name: string, value: any): void; - - /** - * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. - * @param name The name of the property to which to bind the action. - * @param action The function to invoke asynchronously when the property may have changed. - * @returns This object is returned. - **/ - bind(name: string, action: any): Function; - - /** - * Gets a property value by name. - * @param name The name of the property to get. - * @returns The value of the property as an observable object. - **/ - getProperty(name: string): any; - - /** - * Notifies listeners that a property value was updated. - * @param name The name of the property that is being updated. - * @param newValue The new value for the property. - * @param oldValue The old value for the property. - * @returns A promise that is completed when the notifications are complete. - **/ - notify(name: string, newValue: string, oldValue: string): Promise; - - /** - * Removes a property value. - * @param name The name of the property to remove. - * @returns This object is returned. - **/ - removeProperty(name: string): any; - - /** - * Updates a property value and notifies any listeners. - * @param name The name of the property to update. - * @param value The new value of the property. - * @returns This object is returned. - **/ - setProperty(name: string, value: any): any; - - /** - * Removes one or more listeners from the notification list for a given property. - * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. - * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. - * @returns This object is returned. - **/ - unbind(name: string, action: Function): any; - - /** - * Updates a property value and notifies any listeners. - * @param name The name of the property to update. - * @param value The new value of the property. - * @returns A promise that completes when the notifications for this property change have been processed. If multiple notifications are coalesced, the promise may be canceled or the value of the promise may be updated. The fulfilled value of the promise is the new value of the property for which the notifications have been completed. - **/ - updateProperty(name: string, value: any): Promise; - - //#endregion Methods - - }; - - /** - * Do not instantiate. A list returned by the createFiltered method. - **/ - class FilteredListProjection extends ListProjection { - //#region Methods - - /** - * Returns a key/data pair for the specified index. - * @param index The index of the value to retrieve. - * @returns An object that has two properties: key and data. - **/ - getItem(index: number): IKeyDataPair; - - /** - * Returns the index of the first occurrence of a key in a list. - * @param key The key to locate in the list. - * @returns The index of the first occurrence of a key in a list, or -1 if not found. - **/ - indexOfKey(key: string): number; - - /** - * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. - * @param index The index of the value that was mutated. - **/ - notifyMutated(index: number): void; - - /** - * Replaces the value at the specified index with a new value. - * @param index The index of the value that was replaced. - * @param newValue The new value. - **/ - setAt(index: number, newValue: T): void; - - //#endregion Methods - - //#region Properties - - /** - * The length of the list. Returns an integer value one higher than the highest element defined in an list. - **/ - length: number; - - //#endregion Properties - - } - - /** - * Do not instantiate. A list of groups. - **/ - class GroupsListProjection extends ListBase { - //#region Methods - - /** - * Gets a key/data pair for the specified index. - * @param index The index of the value to retrieve. - * @returns An object that has two properties: key and data. - **/ - getItem(index: number): IKeyDataPair; - - /** - * Gets a key/data pair for the specified key. - * @param key The key of the value to retrieve. - * @returns An object with two properties: key and data. - **/ - getItemFromKey(key: string): IKeyDataPair; - - /** - * Returns the index of the first occurrence of a key in a list. - * @param key The key to locate in the list. - * @returns The index of the first occurrence of a key in a list, or -1 if not found. - **/ - indexOfKey(key: string): number; - - //#endregion Methods - - //#region Properties - - /** - * The length of the list. Returns an integer value one higher than the highest element defined in an list. - **/ - length: number; - - //#endregion Properties - - } - - /** - * Do not instantiate. Sorts the underlying list by group key and within a group respects the position of the item in the underlying list. Returned by createGrouped. - **/ - class GroupedSortedListProjection extends SortedListProjection { - //#region Properties - - /** - * Gets a List, which is a projection of the groups that were identified in this list. - **/ - groups: GroupsListProjection; - - //#endregion Properties - - } - - /** - * Represents a list of objects that can be accessed by index or by a string key. Provides methods to search, sort, filter, and manipulate the data. - **/ - class List extends ListBaseWithMutators { - //#region Constructors - - /** - * Creates a List object. - * @constructor - * @param list The array containing the elements to initalize the list. - * @param options You can set two Boolean options: binding and proxy. If options.binding is true, the list contains the result of calling as on the element values. If options.proxy is true, the list specified as the first parameter is used as the storage for the List. This option should be used with care, because uncoordinated edits to the data storage may result in errors. - **/ - constructor(list?: T[], options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * Gets a key/data pair for the specified list index. - * @param index The index of value to retrieve. - * @returns An object with .key and .data properties. - **/ - getItem(index: number): IKeyDataPair; - - /** - * Gets a key/data pair for the list item key specified. - * @param key The key of the value to retrieve. - * @returns An object with .key and .data properties. - **/ - getItemFromKey(key: string): IKeyDataPair; - - /** - * Gets the index of the first occurrence of a key in a list. - * @param key The key to locate in the list. - * @returns The index of the first occurrence of a key in a list, or -1 if not found. - **/ - indexOfKey(key: string): number; - - /** - * Moves the value at index to the specified position. - * @param index The original index of the value. - * @param newIndex The index of the value after the move. - **/ - move(index: number, newIndex: number): void; - - /** - * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. - * @param index The index of the value that was mutated. - **/ - notifyMutated(index: number): void; - - /** - * Returns a list with the elements reversed. This method reverses the elements of a list object in place. It does not create a new list object during execution. - **/ - reverse(): void; - - /** - * Replaces the value at the specified index with a new value. - * @param index The index of the value that was replaced. - * @param newValue The new value. - **/ - setAt(index: number, newValue: T): void; - - /** - * Returns a list with the elements sorted. This method sorts the elements of a list object in place. It does not create a new list object during execution. - * @param sortFunction The function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. - **/ - sort(sortFunction: (left: T, right: T) => number): void; - - /** - * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. - * @param start The zero-based location in the list from which to start removing elements. - * @param howMany The number of elements to remove. - * @param item The elements to insert into the list in place of the deleted elements. - * @returns The deleted elements. - **/ - splice(start: number, howMany?: number, ...item: T[]): T[]; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the length of the list, which is an integer value one higher than the highest element defined in the list. - **/ - length: number; - - //#endregion Properties - - } - - /** - * Represents a base class for lists. - **/ - class ListBase { - //#region Events - - /** - * An item in the list has changed its value. - * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, newItem, newValue, oldItem, oldValue. - **/ - onitemchanged(eventInfo: CustomEvent): void; - - /** - * A new item has been inserted into the list. - * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. - **/ - oniteminserted(eventInfo: CustomEvent): void; - - /** - * An item has been changed locations in the list. - * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. - **/ - onitemmoved(eventInfo: CustomEvent): void; - - /** - * An item has been mutated. This event occurs as a result of calling the notifyMutated method. - * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. - **/ - onitemmutated(eventInfo: CustomEvent): void; - - /** - * An item has been removed from the list. - * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. - **/ - onitemremoved(eventInfo: CustomEvent): void; - - /** - * The list has been refreshed. Any references to items in the list may be incorrect. - * @param eventInfo An object that contains information about the event. The detail property of this object is null. - **/ - onreload(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Adds an event listener to the control. - * @param type The type (name) of the event. - * @param listener The listener to invoke when the event gets raised. - * @param useCapture If true, initiates capture, otherwise false. - **/ - addEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. - * @param name The name of the property to which to bind the action. - * @param action The function to invoke asynchronously when the property may have changed. - * @returns A reference to this observableMixin object. - **/ - bind(name: string, action: Function): any; - - /** - * Returns a new list consisting of a combination of two arrays. - * @param item Additional items to add to the end of the list. - * @returns An array containing the concatenation of the list and any other supplied items. - **/ - concat(...item: T[]): T[]; - - /** - * Creates a live filtered projection over this list. As the list changes, the filtered projection reacts to those changes and may also change. - * @param predicate A function that accepts a single argument. The createFiltered function calls the callback with each element in the list. If the function returns true, that element will be included in the filtered list. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. - * @returns A filtered projection over the list. - **/ - createFiltered(predicate: (x: T) => boolean): FilteredListProjection; - - /** - * Creates a live grouped projection over this list. As the list changes, the grouped projection reacts to those changes and may also change. The grouped projection sorts all the elements of the list to be in group-contiguous order. The grouped projection also contains a .groups property, which is a List representing the groups that were found in the list. - * @param groupKey A function that accepts a single argument. The function is called with each element in the list, the function should return a string representing the group containing the element. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. - * @param groupData A function that accepts a single argument. The function is called once, on one element per group. It should return the value that should be set as the data of the .groups list element for this group. The data value usually serves as summary or header information for the group. - * @param groupSorter A function that accepts two arguments. The function is called with pairs of group keys found in the list. It must return one of the following numeric values: negative if the first argument is less than the second (sorted before), zero if the two arguments are equivalent, positive if the first argument is greater than the second (sorted after). - * @returns A grouped projection over the list. - **/ - createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter: (left: string, right: string) => number): GroupedSortedListProjection; - - /** - * Creates a live sorted projection over this list. As the list changes, the sorted projection reacts to those changes and may also change. - * @param sorter A function that accepts two arguments. The function is called with elements in the list. It must return one of the following numeric values: negative if the first argument is less than the second, zero if the two arguments are equivalent, positive if the first argument is greater than the second. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. - * @returns A sorted projection over the list. - **/ - createSorted(sorter: (left: T, right: T) => number): SortedListProjection; - - /** - * Raises an event of the specified type and with the specified additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Checks whether the specified callback function returns true for all elements in a list. - * @param callback A function that accepts up to three arguments. This function is called for each element in the list until it returns false or the end of the list is reached. - * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. - * @returns true if the callback returns true for all elements in the list. - **/ - every(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - - /** - * Returns the elements of a list that meet the condition specified in a callback function. - * @param callback A function that accepts up to three arguments. The function is called for each element in the list. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. - * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. - * @returns An array containing the elements that meet the condition specified in the callback function. - **/ - filter(callback: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; - - /** - * Calls the specified callback function for each element in a list. - * @param callback A function that accepts up to three arguments. The function is called for each element in the list. The arguments are as follows: value, index, array. - * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. - **/ - forEach(callback: (value: T, index: number, array: T[]) => void, thisArg?: any): void; - - /** - * Gets the value at the specified index. - * @param index The index of the value to get. - * @returns The value at the specified index. - **/ - getAt(index: number): T; - - /** - * Gets the index of the first occurrence of the specified value in a list. - * @param searchElement The value to locate in the list. - * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at index 0. - * @returns The index of the first occurrence of a value in a list or -1 if not found. - **/ - indexOf(searchElement: T, fromIndex?: number): number; - - /** - * Returns a string consisting of all the elements of a list separated by the specified separator string. - * @param separator A string used to separate the elements of a list. If this parameter is omitted, the list elements are separated with a comma. - * @returns The elements of a list separated by the specified separator string. - **/ - join(separator: string): string; - - /** - * Gets the index of the last occurrence of the specified value in a list. - * @param searchElement The value to locate in the list. - * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the list. - * @returns The index of the last occurrence of a value in a list, or -1 if not found. - **/ - lastIndexOf(searchElement: T, fromIndex: number): number; - - /** - * Calls the specified callback function on each element of a list, and returns an array that contains the results. - * @param callback A function that accepts up to three arguments. The function is called for each element in the list. - * @param thisArg n object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. - * @returns An array containing the result of calling the callback function on each element in the list. - **/ - map(callback: (value: T, index: number, array: T[]) => G, thisArg?: any): G[]; - - /** - * Notifies listeners that a property value was updated. - * @param name The name of the property that is being updated. - * @param newValue The new value for the property. - * @param oldValue The old value for the property. - * @returns A promise that is completed when the notifications are complete. - **/ - notify(name: string, newValue: any, oldValue: any): Promise; - - /** - * Forces the list to send a reload notification to any listeners. - **/ - notifyReload(): void; - - /** - * Accumulates a single result by calling the specified callback function for all elements in a list. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callback A function that accepts up to four arguments. These arguments are: previousValue, currentValue, currentIndex, array. The function is called for each element in the list. - * @param initiallValue If initialValue is specified, it is used as the value with which to start the accumulation. The first call to the function provides this value as an argument instead of a list value. - * @returns The return value from the last call to the callback function. - **/ - reduce(callback: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => T, initiallValue?: T): T; - - /** - * Accumulates a single result by calling the specified callback function for all elements in a list, starting with the last member of the list. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callback A function that accepts up to four arguments. These arguments are: previousValue, currentValue, currentIndex, array. The function is called for each element in the list. - * @param initialValue If initialValue is specified, it is used as the value with which to start the accumulation. The first call to the callback function provides this value as an argument instead of a list value. - * @returns The return value from the last call to callback function. - **/ - reduceRight(callback: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => T, initialValue?: T): T; - - /** - * Removes an event listener from the control. - * @param type The type (name) of the event. - * @param listener The listener to remove. - * @param useCapture true if capture is to be initiated, otherwise false. - **/ - removeEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Extracts a section of a list and returns a new list. - * @param begin The index that specifies the beginning of the section. - * @param end The index that specifies the end of the section. - * @returns Returns a section of list. - **/ - slice(begin: number, end: number): T[]; - - /** - * Checks whether the specified callback function returns true for any element of a list. - * @param callback A function that accepts up to three arguments. The function is called for each element in the list until it returns true, or until the end of the list. - * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. - * @returns true if callback returns true for any element in the list. - **/ - some(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - - /** - * Removes one or more listeners from the notification list for a given property. - * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. - * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. - * @returns This object is returned. - **/ - unbind(name: string, action: Function): any; - - //#endregion Methods - - //#region Properties - - /** - * Gets the IListDataSource for the list. The only purpose of this property is to adapt a List to the data model that is used by ListView and FlipView. - **/ - dataSource: WinJS.UI.IListDataSource; - - /** - * Indicates that the object is compatibile with declarative processing. - **/ - static supportedForProcessing: boolean; - - //#endregion Properties - } - - /** - * Represents a base class for normal list modifying operations. - **/ - class ListBaseWithMutators extends ListBase { - //#region Methods - - /** - * Removes the last element from a list and returns it. - * @returns The last element from the list. - **/ - pop(): T; - - /** - * Appends new element(s) to a list, and returns the new length of the list. - * @param value The element to insert at the end of the list. - * @returns The new length of the list. - **/ - push(value: T): number; - - /** - * Removes the first element from a list and returns it. - * @returns The first element from the list. - **/ - shift(): T; - - /** - * Appends new element(s) to a list, and returns the new length of the list. - * @param value The element to insert at the start of the list. - * @returns The new length of the list. - **/ - unshift(value: T): number; - - //#endregion Methods - } - - /** - * Represents a base class for list projections. - **/ - class ListProjection extends ListBaseWithMutators { - //#region Methods - - /** - * Disconnects a WinJS.Binding.List projection from its underlying WinJS.Binding.List. It's only important to call this method when the WinJS.Binding.List projection and the WinJS.Binding.List have different lifetimes. (Call this method on the WinJS.Binding.List projection, not the underlying WinJS.Binding.List.) - **/ - dispose(): void; - - /** - * Gets a key/data pair for the specified key. - * @param key The key of the value to retrieve. - * @returns An object with two properties: key and data. - **/ - getItemFromKey(key: string): IKeyDataPair; - - /** - * Moves the value at index to position newIndex. - * @param index The original index of the value. - * @param newIndex The index of the value after the move. - **/ - move(index: number, newIndex: number): void; - - /** - * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. - * @param start The zero-based location in the list from which to start removing elements. - * @param howMany The number of elements to remove. - * @param item The elements to insert into the list in place of the deleted elements. - * @returns The deleted elements. - **/ - splice(start: number, howMany?: number, ...item: T[]): T[]; - - //#endregion Methods - } - - /** - * Provides a standard implementation of the bindable contract, as well as a basic storage mechanism that participates in change notification and an asynchronous notification implementation. - **/ - var mixin: { - //#region Methods - - /** - * Adds a property to the object. The property includes change notification and an ECMAScript 5 property definition . - * @param name The name of the property to add. - * @param value The value of the property. - * @returns This object is returned. - **/ - addProperty(name: string, value: any): any; - - /** - * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. - * @param name The name of the property to which to bind the action. - * @param action The function to invoke asynchronously when the property may have changed. - * @returns This object is returned. - **/ - bind(name: string, action: any): Function; - - /** - * Gets a property value by name. - * @param name The name of the property to get. - * @returns The value of the property as an observable object. - **/ - getProperty(name: string): any; - - /** - * Notifies listeners that a property value was updated. - * @param name The name of the property that is being updated. - * @param newValue The new value for the property. - * @param oldValue The old value for the property. - * @returns A promise that is completed when the notifications are complete. - **/ - notify(name: string, newValue: string, oldValue: string): Promise; - - /** - * Removes a property value. - * @param name The name of the property to remove. - * @returns This object is returned. - **/ - removeProperty(name: string): any; - - /** - * Updates a property value and notifies any listeners. - * @param name The name of the property to update. - * @param value The new value of the property. - * @returns This object is returned. - **/ - setProperty(name: string, value: any): any; - - /** - * Removes one or more listeners from the notification list for a given property. - * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. - * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. - * @returns This object is returned. - **/ - unbind(name: string, action: Function): any; - - /** - * Updates a property value and notifies any listeners. - * @param name The name of the property to update. - * @param value The new value of the property. - * @returns A promise that completes when the notifications for this property change have been processed. If multiple notifications are coalesced, the promise may be canceled or the value of the promise may be updated. The fulfilled value of the promise is the new value of the property for which the notifications have been completed. - **/ - updateProperty(name: string, value: any): Promise; - - //#endregion Methods - - }; - - /** - * Provides functions that can make an object observable. - **/ - var observableMixin: { - //#region Methods - - /** - * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. - * @param name The name of the property to which to bind the action. - * @param action The function to invoke asynchronously when the property may have changed. - * @returns A reference to this observableMixin object. - **/ - bind(name: string, action: Function): any; - - /** - * Notifies listeners that a property value was updated. - * @param name The name of the property that is being updated. - * @param newValue The new value for the property. - * @param oldValue The old value for the property. - * @returns A promise that is completed when the notifications are complete. - **/ - notify(name: string, newValue: any, oldValue: any): Promise; - - /** - * Removes one or more listeners from the notification list for a given property. - * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. - * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. - * @returns This object is returned. - **/ - unbind(name: string, action: Function): any; - - //#endregion Methods - - }; - - /** - * Do not instantiate. Returned by the createSorted method. - **/ - class SortedListProjection extends ListProjection { - //#region Methods - - /** - * Returns a key/data pair for the specified index. - * @param index The index of the value to retrieve. - * @returns An object that has two properties: key and data. - **/ - getItem(index: number): IKeyDataPair; - - /** - * Returns the index of the first occurrence of a key. - * @param key The key to locate in the list. - * @returns The index of the first occurrence of a key in a list, or -1 if not found. - **/ - indexOfKey(key: string): number; - - /** - * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. - * @param index The index of the value that was mutated. - **/ - notifyMutated(index: number): void; - - /** - * Replaces the value at the specified index with a new value. - * @param index The index of the value to be replaced. - * @param newValue The new value. - **/ - setAt(index: number, newValue: T): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the length of the list. Returns an integer value one higher than the highest element defined in a list. - **/ - length: number; - - //#endregion Properties - - } - - /** - * Provides a reusable declarative binding element. - **/ - class Template { - //#region Constructors - - /** - * Creates a template that provides a reusable declarative binding element. - * @constructor - * @param element The DOM element to convert to a template. - * @param options If this parameter is supplied, the template is loaded from the URI and the content of the element parameter is ignored. You can add the following options: href. - **/ - constructor(element: HTMLElement, options?: string); - - //#endregion Constructors - - //#region Methods - - render: { - /** - * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). - * @param dataContext The object to use for default data binding. - * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. - * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. - **/ - (dataContext: any, container?: HTMLElement): Promise; - - /** - * Renders a template based on the specified URI (static method). - * @param href The URI from which to load the template. - * @param dataContext The object to use for default data binding. - * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. - * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. - **/ - value(href: string, dataContext: any, container?: HTMLElement): Promise; - }; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the default binding initializer for the template. - **/ - bindingInitializer: any; - - /** - * Gets or sets a value that specifies whether a debug break is inserted into the first rendering of each template. This property only has an effect when the app is in debug mode. - **/ - debugBreakOnRender: boolean; - - /** - * This property is deprecated and might not be available in future versions of the WinJS. Gets or sets a value that specifies whether optimized template processing has been disabled. - **/ - disableOptimizedProcessing: boolean; - - /** - * Gets the DOM element that is used as the template. - **/ - element: HTMLElement; - - /** - * Gets a value that specifies whether templates should be instantiated without the creation of an additional child element. - **/ - extractChild: boolean; - - /** - * Determines whether the Template contains declarative controls that must be processed separately. This property is always true. The controls that belong to a Template object's children are instantiated when a Template instance is rendered. - **/ - isDeclarativeControlContainer: boolean; - - //#endregion Properties - - } - - //#endregion Objects - - //#region Functions - - /** - * Adds a CSS class from the specified path of the source object to a destination object. - * @param source The source object that has the class to copy. - * @param sourceProperties The path on the source object to the source class. - * @param dest The destination object. - **/ - function addClassOneTime(source: any, sourceProperties: any[], dest: HTMLElement): void; - - /** - * Returns an observable object. This may be an observable proxy for the specified object, an existing proxy, or the specified object itself if it directly supports observation. - * @param data The object to observe. - * @returns The observable object. - **/ - function as(data: U): U; - - /** - * Binds to one or more properties on the observable object or or on child values of that object. - * @param observable The object to bind to. - * @param bindingDescriptor An object literal containing the binding declarations. Binding declarations take the form: { propertyName: (function | bindingDeclaration), ... }. - * @returns An object that contains at least a "cancel" field, which is a function that removes all bindings associated with this bind request. - **/ - function bind(observable: any, bindingDescriptor: any): any; - - /** - * Creates a default binding initializer for binding between a source property and a destination property with the specified converter function that is executed on the value of the source property. - * @param convert The conversion function that takes the source property and produces a value that is set to the destination property. This function must be accessible from the global namespace. - * @returns The binding initializer. - **/ - function converter(convert: Function): Function; - - /** - * Creates a one-way binding between the source object and the destination object. Warning Do not attempt to bind data to the ID of an HTML element. - * @param source The source object. - * @param sourceProperties The path on the source object to the source property. - * @param dest The destination object. - * @param destProperties The path on the destination object to the destination property. - * @returns An object with a cancel method that is used to coalesce bindings. - **/ - function defaultBind(source: any, sourceProperties: any, dest: any, destProperties: any): any; - - /** - * Creates a new constructor function that supports observability with the specified set of properties. - * @param data The object to use as the pattern for defining the set of properties. - * @returns A constructor function with 1 optional argument that is the initial state of the properties. - **/ - function define(data: any): Function; - - /** - * Wraps the specified object so that all its properties are instrumented for binding. This is meant to be used in conjunction with the binding mixin. - * @param shape The specification for the bindable object. - * @returns An object with a set of properties all of which are wired for binding. - **/ - function expandProperties(shape: any): any; - - /** - * Marks a custom initializer function as being compatible with declarative data binding. - * @param customInitializer The custom initializer to be marked as compatible with declarative data binding. - * @returns The input customInitializer. - **/ - function initializer(customInitializer: Function): Function; - - /** - * Sets the destination property to the value of the source property. - * @param source The source object. - * @param sourceProperties The path on the source object to the source property. - * @param dest The destination object. - * @param destProperties The path on the destination object to the destination property. - * @returns An object with a cancel method that is used to coalesce bindings. - **/ - function oneTime(source: any, sourceProperties: any, dest: any, destProperties: any): any; - - /** - * Binds the values of an object to the values of a DOM element that has the data-win-bind attribute. If multiple DOM elements are to be bound, you must set the attribute on all of them. See the example below for details. - * @param rootElement Optional. The element at which to start traversing to find elements to bind to. If this parameter is omitted, the entire document is searched. - * @param dataContext The object that contains the values to which the DOM element should be bound. - * @param skipRoot If true, specifies that only the children of rootElement should be bound, otherwise rootElement should be bound as well. - * @param bindingCache The cached binding data. - * @param defaultInitializer The binding initializer to use in the case that one is not specified in a binding expression. If not provided, the behavior is the same as Binding.defaultBind. - * @returns A Promise that completes when every item that contains the data-win-bind attribute has been processed and the update has started. - **/ - function processAll(rootElement?: Element, dataContext?: any, skipRoot?: boolean, bindingCache?: any, defaultInitializer?: Function): Promise; - - /** - * Creates a one-way binding between the source object and an attribute on the destination element. - * @param source The source object. - * @param sourceProperties The path on the source object to the source property. - * @param dest The destination object. - * @param destProperties The path on the destination object to the destination property. This must be a single name. - * @returns An object with a cancel() method that is used to coalesce bindings. - **/ - function setAttribute(source: any, sourceProperties: any[], dest: Element, destProperties: any[]): any; - - /** - * Sets an attribute on the destination element to the value of the source property. - * @param source The source object. - * @param sourceProperties The path on the source object to the source property. - * @param dest The destination object. - * @param destProperties The path on the destination object to the destination property. This must be a single name. - **/ - function setAttributeOneTime(source: any, sourceProperties: any[], dest: Element, destProperties: any[]): void; - - /** - * Returns the original (non-observable) object is returned if the specified object is an observable proxy, - * @param data The object for which to retrieve the original value. - * @returns If the specified object is an observable proxy, the original object is returned, otherwise the same object is returned. - **/ - function unwrap(data: any): any; - - //#endregion Functions - - //#region Interfaces - - interface IKeyDataPair { - key: string; - data: T; - } - - //#endregion Interfaces + //#region Properties + + /** + * Determines whether or not binding should automatically set the ID of an element. This property should be set to true in apps that use WinJS (WinJS) binding. + **/ + var optimizeBindingReferences: boolean; + + //#endregion Properties + + //#region Objects + + /** + * Allows you to add bindable properties dynamically. + **/ + var dynamicObservableMixin: { + //#region Methods + + /** + * Adds a property with change notification to this object, including a ECMAScript5 property definition. + * @param name The name of the property to add. + * @param value This object is returned. + **/ + addProperty(name: string, value: any): void; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns This object is returned. + **/ + bind(name: string, action: any): Function; + + /** + * Gets a property value by name. + * @param name The name of the property to get. + * @returns The value of the property as an observable object. + **/ + getProperty(name: string): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: string, oldValue: string): Promise; + + /** + * Removes a property value. + * @param name The name of the property to remove. + * @returns This object is returned. + **/ + removeProperty(name: string): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns This object is returned. + **/ + setProperty(name: string, value: any): any; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns A promise that completes when the notifications for this property change have been processed. If multiple notifications are coalesced, the promise may be canceled or the value of the promise may be updated. The fulfilled value of the promise is the new value of the property for which the notifications have been completed. + **/ + updateProperty(name: string, value: any): Promise; + + //#endregion Methods + + }; + + /** + * Do not instantiate. A list returned by the createFiltered method. + **/ + class FilteredListProjection extends ListProjection { + //#region Methods + + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value that was replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + //#endregion Methods + + //#region Properties + + /** + * The length of the list. Returns an integer value one higher than the highest element defined in an list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Do not instantiate. A list of groups. + **/ + class GroupsListProjection extends ListBase { + //#region Methods + + /** + * Gets a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Gets a key/data pair for the specified key. + * @param key The key of the value to retrieve. + * @returns An object with two properties: key and data. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + //#endregion Methods + + //#region Properties + + /** + * The length of the list. Returns an integer value one higher than the highest element defined in an list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Do not instantiate. Sorts the underlying list by group key and within a group respects the position of the item in the underlying list. Returned by createGrouped. + **/ + class GroupedSortedListProjection extends SortedListProjection { + //#region Properties + + /** + * Gets a List, which is a projection of the groups that were identified in this list. + **/ + groups: GroupsListProjection; + + //#endregion Properties + + } + + /** + * Represents a list of objects that can be accessed by index or by a string key. Provides methods to search, sort, filter, and manipulate the data. + **/ + class List extends ListBaseWithMutators { + //#region Constructors + + /** + * Creates a List object. + * @constructor + * @param list The array containing the elements to initalize the list. + * @param options You can set two Boolean options: binding and proxy. If options.binding is true, the list contains the result of calling as on the element values. If options.proxy is true, the list specified as the first parameter is used as the storage for the List. This option should be used with care, because uncoordinated edits to the data storage may result in errors. + **/ + constructor(list?: T[], options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Gets a key/data pair for the specified list index. + * @param index The index of value to retrieve. + * @returns An object with .key and .data properties. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Gets a key/data pair for the list item key specified. + * @param key The key of the value to retrieve. + * @returns An object with .key and .data properties. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Gets the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Moves the value at index to the specified position. + * @param index The original index of the value. + * @param newIndex The index of the value after the move. + **/ + move(index: number, newIndex: number): void; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Returns a list with the elements reversed. This method reverses the elements of a list object in place. It does not create a new list object during execution. + **/ + reverse(): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value that was replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + /** + * Returns a list with the elements sorted. This method sorts the elements of a list object in place. It does not create a new list object during execution. + * @param sortFunction The function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + **/ + sort(sortFunction: (left: T, right: T) => number): void; + + /** + * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the list from which to start removing elements. + * @param howMany The number of elements to remove. + * @param item The elements to insert into the list in place of the deleted elements. + * @returns The deleted elements. + **/ + splice(start: number, howMany?: number, ...item: T[]): T[]; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the length of the list, which is an integer value one higher than the highest element defined in the list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Represents a base class for lists. + **/ + class ListBase { + //#region Events + + /** + * An item in the list has changed its value. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, newItem, newValue, oldItem, oldValue. + **/ + onitemchanged(eventInfo: CustomEvent): void; + + /** + * A new item has been inserted into the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + oniteminserted(eventInfo: CustomEvent): void; + + /** + * An item has been changed locations in the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemmoved(eventInfo: CustomEvent): void; + + /** + * An item has been mutated. This event occurs as a result of calling the notifyMutated method. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemmutated(eventInfo: CustomEvent): void; + + /** + * An item has been removed from the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemremoved(eventInfo: CustomEvent): void; + + /** + * The list has been refreshed. Any references to items in the list may be incorrect. + * @param eventInfo An object that contains information about the event. The detail property of this object is null. + **/ + onreload(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture If true, initiates capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns A reference to this observableMixin object. + **/ + bind(name: string, action: Function): any; + + /** + * Returns a new list consisting of a combination of two arrays. + * @param item Additional items to add to the end of the list. + * @returns An array containing the concatenation of the list and any other supplied items. + **/ + concat(...item: T[]): T[]; + + /** + * Creates a live filtered projection over this list. As the list changes, the filtered projection reacts to those changes and may also change. + * @param predicate A function that accepts a single argument. The createFiltered function calls the callback with each element in the list. If the function returns true, that element will be included in the filtered list. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @returns A filtered projection over the list. + **/ + createFiltered(predicate: (x: T) => boolean): FilteredListProjection; + + /** + * Creates a live grouped projection over this list. As the list changes, the grouped projection reacts to those changes and may also change. The grouped projection sorts all the elements of the list to be in group-contiguous order. The grouped projection also contains a .groups property, which is a List representing the groups that were found in the list. + * @param groupKey A function that accepts a single argument. The function is called with each element in the list, the function should return a string representing the group containing the element. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @param groupData A function that accepts a single argument. The function is called once, on one element per group. It should return the value that should be set as the data of the .groups list element for this group. The data value usually serves as summary or header information for the group. + * @param groupSorter A function that accepts two arguments. The function is called with pairs of group keys found in the list. It must return one of the following numeric values: negative if the first argument is less than the second (sorted before), zero if the two arguments are equivalent, positive if the first argument is greater than the second (sorted after). + * @returns A grouped projection over the list. + **/ + createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter: (left: string, right: string) => number): GroupedSortedListProjection; + + /** + * Creates a live sorted projection over this list. As the list changes, the sorted projection reacts to those changes and may also change. + * @param sorter A function that accepts two arguments. The function is called with elements in the list. It must return one of the following numeric values: negative if the first argument is less than the second, zero if the two arguments are equivalent, positive if the first argument is greater than the second. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @returns A sorted projection over the list. + **/ + createSorted(sorter: (left: T, right: T) => number): SortedListProjection; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Checks whether the specified callback function returns true for all elements in a list. + * @param callback A function that accepts up to three arguments. This function is called for each element in the list until it returns false or the end of the list is reached. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns true if the callback returns true for all elements in the list. + **/ + every(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Returns the elements of a list that meet the condition specified in a callback function. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns An array containing the elements that meet the condition specified in the callback function. + **/ + filter(callback: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; + + /** + * Calls the specified callback function for each element in a list. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. The arguments are as follows: value, index, array. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + **/ + forEach(callback: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + + /** + * Gets the value at the specified index. + * @param index The index of the value to get. + * @returns The value at the specified index. + **/ + getAt(index: number): T; + + /** + * Gets the index of the first occurrence of the specified value in a list. + * @param searchElement The value to locate in the list. + * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + * @returns The index of the first occurrence of a value in a list or -1 if not found. + **/ + indexOf(searchElement: T, fromIndex?: number): number; + + /** + * Returns a string consisting of all the elements of a list separated by the specified separator string. + * @param separator A string used to separate the elements of a list. If this parameter is omitted, the list elements are separated with a comma. + * @returns The elements of a list separated by the specified separator string. + **/ + join(separator: string): string; + + /** + * Gets the index of the last occurrence of the specified value in a list. + * @param searchElement The value to locate in the list. + * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the list. + * @returns The index of the last occurrence of a value in a list, or -1 if not found. + **/ + lastIndexOf(searchElement: T, fromIndex: number): number; + + /** + * Calls the specified callback function on each element of a list, and returns an array that contains the results. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. + * @param thisArg n object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns An array containing the result of calling the callback function on each element in the list. + **/ + map(callback: (value: T, index: number, array: T[]) => G, thisArg?: any): G[]; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: any, oldValue: any): Promise; + + /** + * Forces the list to send a reload notification to any listeners. + **/ + notifyReload(): void; + + /** + * Accumulates a single result by calling the specified callback function for all elements in a list. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callback A function that accepts up to four arguments. These arguments are: previousValue, currentValue, currentIndex, array. The function is called for each element in the list. + * @param initiallValue If initialValue is specified, it is used as the value with which to start the accumulation. The first call to the function provides this value as an argument instead of a list value. + * @returns The return value from the last call to the callback function. + **/ + reduce(callback: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => T, initiallValue?: T): T; + + /** + * Accumulates a single result by calling the specified callback function for all elements in a list, starting with the last member of the list. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callback A function that accepts up to four arguments. These arguments are: previousValue, currentValue, currentIndex, array. The function is called for each element in the list. + * @param initialValue If initialValue is specified, it is used as the value with which to start the accumulation. The first call to the callback function provides this value as an argument instead of a list value. + * @returns The return value from the last call to callback function. + **/ + reduceRight(callback: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => T, initialValue?: T): T; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true if capture is to be initiated, otherwise false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Extracts a section of a list and returns a new list. + * @param begin The index that specifies the beginning of the section. + * @param end The index that specifies the end of the section. + * @returns Returns a section of list. + **/ + slice(begin: number, end: number): T[]; + + /** + * Checks whether the specified callback function returns true for any element of a list. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list until it returns true, or until the end of the list. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns true if callback returns true for any element in the list. + **/ + some(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + //#endregion Methods + + //#region Properties + + /** + * Gets the IListDataSource for the list. The only purpose of this property is to adapt a List to the data model that is used by ListView and FlipView. + **/ + dataSource: WinJS.UI.IListDataSource; + + /** + * Indicates that the object is compatibile with declarative processing. + **/ + static supportedForProcessing: boolean; + + //#endregion Properties + } + + /** + * Represents a base class for normal list modifying operations. + **/ + class ListBaseWithMutators extends ListBase { + //#region Methods + + /** + * Removes the last element from a list and returns it. + * @returns The last element from the list. + **/ + pop(): T; + + /** + * Appends new element(s) to a list, and returns the new length of the list. + * @param value The element to insert at the end of the list. + * @returns The new length of the list. + **/ + push(value: T): number; + + /** + * Removes the first element from a list and returns it. + * @returns The first element from the list. + **/ + shift(): T; + + /** + * Appends new element(s) to a list, and returns the new length of the list. + * @param value The element to insert at the start of the list. + * @returns The new length of the list. + **/ + unshift(value: T): number; + + //#endregion Methods + } + + /** + * Represents a base class for list projections. + **/ + class ListProjection extends ListBaseWithMutators { + //#region Methods + + /** + * Disconnects a WinJS.Binding.List projection from its underlying WinJS.Binding.List. It's only important to call this method when the WinJS.Binding.List projection and the WinJS.Binding.List have different lifetimes. (Call this method on the WinJS.Binding.List projection, not the underlying WinJS.Binding.List.) + **/ + dispose(): void; + + /** + * Gets a key/data pair for the specified key. + * @param key The key of the value to retrieve. + * @returns An object with two properties: key and data. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Moves the value at index to position newIndex. + * @param index The original index of the value. + * @param newIndex The index of the value after the move. + **/ + move(index: number, newIndex: number): void; + + /** + * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the list from which to start removing elements. + * @param howMany The number of elements to remove. + * @param item The elements to insert into the list in place of the deleted elements. + * @returns The deleted elements. + **/ + splice(start: number, howMany?: number, ...item: T[]): T[]; + + //#endregion Methods + } + + /** + * Provides a standard implementation of the bindable contract, as well as a basic storage mechanism that participates in change notification and an asynchronous notification implementation. + **/ + var mixin: { + //#region Methods + + /** + * Adds a property to the object. The property includes change notification and an ECMAScript 5 property definition . + * @param name The name of the property to add. + * @param value The value of the property. + * @returns This object is returned. + **/ + addProperty(name: string, value: any): any; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns This object is returned. + **/ + bind(name: string, action: any): Function; + + /** + * Gets a property value by name. + * @param name The name of the property to get. + * @returns The value of the property as an observable object. + **/ + getProperty(name: string): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: string, oldValue: string): Promise; + + /** + * Removes a property value. + * @param name The name of the property to remove. + * @returns This object is returned. + **/ + removeProperty(name: string): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns This object is returned. + **/ + setProperty(name: string, value: any): any; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns A promise that completes when the notifications for this property change have been processed. If multiple notifications are coalesced, the promise may be canceled or the value of the promise may be updated. The fulfilled value of the promise is the new value of the property for which the notifications have been completed. + **/ + updateProperty(name: string, value: any): Promise; + + //#endregion Methods + + }; + + /** + * Provides functions that can make an object observable. + **/ + var observableMixin: { + //#region Methods + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns A reference to this observableMixin object. + **/ + bind(name: string, action: Function): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: any, oldValue: any): Promise; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + //#endregion Methods + + }; + + /** + * Do not instantiate. Returned by the createSorted method. + **/ + class SortedListProjection extends ListProjection { + //#region Methods + + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value to be replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the length of the list. Returns an integer value one higher than the highest element defined in a list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Provides a reusable declarative binding element. + **/ + class Template { + //#region Constructors + + /** + * Creates a template that provides a reusable declarative binding element. + * @constructor + * @param element The DOM element to convert to a template. + * @param options If this parameter is supplied, the template is loaded from the URI and the content of the element parameter is ignored. You can add the following options: href. + **/ + constructor(element: HTMLElement, options?: string); + + //#endregion Constructors + + //#region Methods + + render: { + /** + * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. + **/ + (dataContext: any, container?: HTMLElement): Promise; + + /** + * Renders a template based on the specified URI (static method). + * @param href The URI from which to load the template. + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. + **/ + value(href: string, dataContext: any, container?: HTMLElement): Promise; + }; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the default binding initializer for the template. + **/ + bindingInitializer: any; + + /** + * Gets or sets a value that specifies whether a debug break is inserted into the first rendering of each template. This property only has an effect when the app is in debug mode. + **/ + debugBreakOnRender: boolean; + + /** + * This property is deprecated and might not be available in future versions of the WinJS. Gets or sets a value that specifies whether optimized template processing has been disabled. + **/ + disableOptimizedProcessing: boolean; + + /** + * Gets the DOM element that is used as the template. + **/ + element: HTMLElement; + + /** + * Gets a value that specifies whether templates should be instantiated without the creation of an additional child element. + **/ + extractChild: boolean; + + /** + * Determines whether the Template contains declarative controls that must be processed separately. This property is always true. The controls that belong to a Template object's children are instantiated when a Template instance is rendered. + **/ + isDeclarativeControlContainer: boolean; + + //#endregion Properties + + } + + //#endregion Objects + + //#region Functions + + /** + * Adds a CSS class from the specified path of the source object to a destination object. + * @param source The source object that has the class to copy. + * @param sourceProperties The path on the source object to the source class. + * @param dest The destination object. + **/ + function addClassOneTime(source: any, sourceProperties: any[], dest: HTMLElement): void; + + /** + * Returns an observable object. This may be an observable proxy for the specified object, an existing proxy, or the specified object itself if it directly supports observation. + * @param data The object to observe. + * @returns The observable object. + **/ + function as(data: U): U; + + /** + * Binds to one or more properties on the observable object or or on child values of that object. + * @param observable The object to bind to. + * @param bindingDescriptor An object literal containing the binding declarations. Binding declarations take the form: { propertyName: (function | bindingDeclaration), ... }. + * @returns An object that contains at least a "cancel" field, which is a function that removes all bindings associated with this bind request. + **/ + function bind(observable: any, bindingDescriptor: any): any; + + /** + * Creates a default binding initializer for binding between a source property and a destination property with the specified converter function that is executed on the value of the source property. + * @param convert The conversion function that takes the source property and produces a value that is set to the destination property. This function must be accessible from the global namespace. + * @returns The binding initializer. + **/ + function converter(convert: Function): Function; + + /** + * Creates a one-way binding between the source object and the destination object. Warning Do not attempt to bind data to the ID of an HTML element. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. + * @returns An object with a cancel method that is used to coalesce bindings. + **/ + function defaultBind(source: any, sourceProperties: any, dest: any, destProperties: any): any; + + /** + * Creates a new constructor function that supports observability with the specified set of properties. + * @param data The object to use as the pattern for defining the set of properties. + * @returns A constructor function with 1 optional argument that is the initial state of the properties. + **/ + function define(data: any): Function; + + /** + * Wraps the specified object so that all its properties are instrumented for binding. This is meant to be used in conjunction with the binding mixin. + * @param shape The specification for the bindable object. + * @returns An object with a set of properties all of which are wired for binding. + **/ + function expandProperties(shape: any): any; + + /** + * Marks a custom initializer function as being compatible with declarative data binding. + * @param customInitializer The custom initializer to be marked as compatible with declarative data binding. + * @returns The input customInitializer. + **/ + function initializer(customInitializer: Function): Function; + + /** + * Sets the destination property to the value of the source property. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. + * @returns An object with a cancel method that is used to coalesce bindings. + **/ + function oneTime(source: any, sourceProperties: any, dest: any, destProperties: any): any; + + /** + * Binds the values of an object to the values of a DOM element that has the data-win-bind attribute. If multiple DOM elements are to be bound, you must set the attribute on all of them. See the example below for details. + * @param rootElement Optional. The element at which to start traversing to find elements to bind to. If this parameter is omitted, the entire document is searched. + * @param dataContext The object that contains the values to which the DOM element should be bound. + * @param skipRoot If true, specifies that only the children of rootElement should be bound, otherwise rootElement should be bound as well. + * @param bindingCache The cached binding data. + * @param defaultInitializer The binding initializer to use in the case that one is not specified in a binding expression. If not provided, the behavior is the same as Binding.defaultBind. + * @returns A Promise that completes when every item that contains the data-win-bind attribute has been processed and the update has started. + **/ + function processAll(rootElement?: Element, dataContext?: any, skipRoot?: boolean, bindingCache?: any, defaultInitializer?: Function): Promise; + + /** + * Creates a one-way binding between the source object and an attribute on the destination element. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. This must be a single name. + * @returns An object with a cancel() method that is used to coalesce bindings. + **/ + function setAttribute(source: any, sourceProperties: any[], dest: Element, destProperties: any[]): any; + + /** + * Sets an attribute on the destination element to the value of the source property. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. This must be a single name. + **/ + function setAttributeOneTime(source: any, sourceProperties: any[], dest: Element, destProperties: any[]): void; + + /** + * Returns the original (non-observable) object is returned if the specified object is an observable proxy, + * @param data The object for which to retrieve the original value. + * @returns If the specified object is an observable proxy, the original object is returned, otherwise the same object is returned. + **/ + function unwrap(data: any): any; + + //#endregion Functions + + //#region Interfaces + + interface IKeyDataPair { + key: string; + data: T; + } + + //#endregion Interfaces } /** * Provides helper functions for defining Classes. **/ declare module WinJS.Class { - //#region Functions + //#region Functions - /** - * Defines a class using the given constructor and the specified instance members. - * @param constructor A constructor function that is used to instantiate this type. - * @param instanceMembers The set of instance fields, properties, and methods made available on the type. - * @param staticMembers The set of static fields, properties, and methods made available on the type. - * @returns The newly-defined type. - **/ - function define(constructor: Function, instanceMembers?: any, staticMembers?: any): any; + /** + * Defines a class using the given constructor and the specified instance members. + * @param constructor A constructor function that is used to instantiate this type. + * @param instanceMembers The set of instance fields, properties, and methods made available on the type. + * @param staticMembers The set of static fields, properties, and methods made available on the type. + * @returns The newly-defined type. + **/ + function define(constructor: Function, instanceMembers?: any, staticMembers?: any): any; - /** - * Creates a sub-class based on the specified baseClass parameter, using prototype inheritance. - * @param baseClass The type to inherit from. - * @param constructor A constructor function that is used to instantiate this type. - * @param instanceMembers The set of instance fields, properties, and methods to be made available on the type. - * @param staticMembers The set of static fields, properties, and methods to be made available on the type. - * @returns The newly-defined type. - **/ - function derive(baseClass: any, constructor: Function, instanceMembers?: any, staticMembers?: any): any; + /** + * Creates a sub-class based on the specified baseClass parameter, using prototype inheritance. + * @param baseClass The type to inherit from. + * @param constructor A constructor function that is used to instantiate this type. + * @param instanceMembers The set of instance fields, properties, and methods to be made available on the type. + * @param staticMembers The set of static fields, properties, and methods to be made available on the type. + * @returns The newly-defined type. + **/ + function derive(baseClass: any, constructor: Function, instanceMembers?: any, staticMembers?: any): any; - /** - * Defines a class using the given constructor and the union of the set of instance members specified by all the mixin objects. The mixin parameter list is of variable length. For more information, see Adding functionality with WinJS mixins. - * @param constructor A constructor function that will be used to instantiate this class. - * @param mixin An object declaring the set of instance members. The mixin parameter list is of variable length. - * @returns The newly defined class. - **/ - function mix(constructor: Function, ...mixin: any[]): any; + /** + * Defines a class using the given constructor and the union of the set of instance members specified by all the mixin objects. The mixin parameter list is of variable length. For more information, see Adding functionality with WinJS mixins. + * @param constructor A constructor function that will be used to instantiate this class. + * @param mixin An object declaring the set of instance members. The mixin parameter list is of variable length. + * @returns The newly defined class. + **/ + function mix(constructor: Function, ...mixin: any[]): any; - //#endregion Functions + //#endregion Functions } /** * The WinJS namespace provides special Windows Library for JavaScript functionality, including Promise and xhr. **/ declare module WinJS { - //#region Properties + //#region Properties - /** - * Can be set to show the results of a validation process. - **/ - var validation: boolean; + /** + * Can be set to show the results of a validation process. + **/ + var validation: boolean; - //#endregion Properties + //#endregion Properties - //#region Objects + //#region Objects - /** - * An error object. - **/ - class ErrorFromName { - //#region Constructors + /** + * An error object. + **/ + class ErrorFromName { + //#region Constructors - /** - * Creates an Error object with the specified name and message properties. - * @constructor - * @param name The name of this error. The name is meant to be consumed programmatically and should not be localized. - * @param message The message for this error. The message is meant to be consumed by humans and should be localized. - **/ - constructor(name: string, message?: string); + /** + * Creates an Error object with the specified name and message properties. + * @constructor + * @param name The name of this error. The name is meant to be consumed programmatically and should not be localized. + * @param message The message for this error. The message is meant to be consumed by humans and should be localized. + **/ + constructor(name: string, message?: string); - //#endregion Constructors + //#endregion Constructors - } + } - /** - * Provides a mechanism to schedule work to be done on a value that has not yet been computed. It is an abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. - **/ - class Promise { - //#region Constructors + /** + * Provides a mechanism to schedule work to be done on a value that has not yet been computed. It is an abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. + **/ + class Promise { + //#region Constructors - /** - * A promise provides a mechanism to schedule work to be done on a value that has not yet been computed. It is a convenient abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. - * @constructor - * @param init The function that is called during construction of the Promise that contains the implementation of the operation that the Promise will represent. This can be synchronous or asynchronous, depending on the nature of the operation. Note that placing code within this function does not automatically run it asynchronously; that must be done explicitly with other asynchronous APIs such as setImmediate, setTimeout, requestAnimationFrame, and the Windows Runtime asynchronous APIs. The init function is given three arguments: completeDispatch, errorDispatch, progressDispatch. This parameter is optional. - * @param onCancel The function to call if a consumer of this promise wants to cancel its undone work. Promises are not required to support cancellation. - **/ - constructor(init?: (completeDispatch: any, errorDispatch: any, progressDispatch: any) => void, onCancel?: Function); + /** + * A promise provides a mechanism to schedule work to be done on a value that has not yet been computed. It is a convenient abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. + * @constructor + * @param init The function that is called during construction of the Promise that contains the implementation of the operation that the Promise will represent. This can be synchronous or asynchronous, depending on the nature of the operation. Note that placing code within this function does not automatically run it asynchronously; that must be done explicitly with other asynchronous APIs such as setImmediate, setTimeout, requestAnimationFrame, and the Windows Runtime asynchronous APIs. The init function is given three arguments: completeDispatch, errorDispatch, progressDispatch. This parameter is optional. + * @param onCancel The function to call if a consumer of this promise wants to cancel its undone work. Promises are not required to support cancellation. + **/ + constructor(init?: (completeDispatch: any, errorDispatch: any, progressDispatch: any) => void, onCancel?: Function); - //#endregion Constructors + //#endregion Constructors - //#region Events + //#region Events - /** - * Occurs when there is an error in processing a promise. - * @param eventInfo An object that contains information about the event. - **/ - onerror(eventInfo: CustomEvent): void; + /** + * Occurs when there is an error in processing a promise. + * @param eventInfo An object that contains information about the event. + **/ + onerror(eventInfo: CustomEvent): void; - //#endregion Events + //#endregion Events - //#region Methods + //#region Methods - /** - * Adds an event listener for the promise. - * @param type The type (name) of the event. - * @param listener The listener to invoke when the event is raised. - * @param capture true to initiate capture, otherwise false. - **/ - addEventListener(type: string, listener: Function, capture?: boolean): void; + /** + * Adds an event listener for the promise. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event is raised. + * @param capture true to initiate capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; - /** - * Returns a promise that is fulfilled when one of the input promises has been fulfilled. - * @param value An array that contains Promise objects or objects whose property values include Promise objects. - * @returns A promise that on fulfillment yields the value of the input (complete or error). - **/ - static any(value: Promise[]): Promise; + /** + * Returns a promise that is fulfilled when one of the input promises has been fulfilled. + * @param value An array that contains Promise objects or objects whose property values include Promise objects. + * @returns A promise that on fulfillment yields the value of the input (complete or error). + **/ + static any(value: Promise[]): Promise; - /** - * Returns a promise. If the object is already a Promise it is returned; otherwise the object is wrapped in a Promise. You can use this function when you need to treat a non-Promise object like a Promise, for example when you are calling a function that expects a promise, but already have the value needed rather than needing to get it asynchronously. - * @param value The value to be treated as a Promise. - * @returns The promise. - **/ - static as(value: U): Promise; + /** + * Returns a promise. If the object is already a Promise it is returned; otherwise the object is wrapped in a Promise. You can use this function when you need to treat a non-Promise object like a Promise, for example when you are calling a function that expects a promise, but already have the value needed rather than needing to get it asynchronously. + * @param value The value to be treated as a Promise. + * @returns The promise. + **/ + static as(value: U): Promise; - /** - * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). - **/ - cancel(): void; + /** + * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). + **/ + cancel(): void; - /** - * Raises an event of the specified type and properties. - * @param type The type (name) of the event. - * @param details The set of additional properties to be attached to the event object. - * @returns true if preventDefault was called on the event; otherwise, false. - **/ - dispatchEvent(type: string, details: any): boolean; + /** + * Raises an event of the specified type and properties. + * @param type The type (name) of the event. + * @param details The set of additional properties to be attached to the event object. + * @returns true if preventDefault was called on the event; otherwise, false. + **/ + dispatchEvent(type: string, details: any): boolean; - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - **/ - done(onComplete?: (value: T) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): void; + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + **/ + done(onComplete?: (value: T) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): void; - /** - * Determines whether a value fulfills the promise contract. - * @param value A value that may be a promise. - * @returns true if the object conforms to the promise contract (has a then function), otherwise false. - **/ - static is(value: any): boolean; + /** + * Determines whether a value fulfills the promise contract. + * @param value A value that may be a promise. + * @returns true if the object conforms to the promise contract (has a then function), otherwise false. + **/ + static is(value: any): boolean; - /** - * Creates a Promise that is fulfilled when all the values are fulfilled. - * @param values An object whose members contain values, some of which may be promises. - * @returns A Promise whose value is an object with the same field names as those of the object in the values parameter, where each field value is the fulfilled value of a promise. - **/ - static join(values: any): Promise; + /** + * Creates a Promise that is fulfilled when all the values are fulfilled. + * @param values An object whose members contain values, some of which may be promises. + * @returns A Promise whose value is an object with the same field names as those of the object in the values parameter, where each field value is the fulfilled value of a promise. + **/ + static join(values: any): Promise; - /** - * Removes an event listener from the control. - * @param eventType The type (name) of the event. - * @param listener The listener to remove. - * @param capture Specifies whether or not to initiate capture. - **/ - removeEventListener(eventType: string, listener: Function, capture?: boolean): void; + /** + * Removes an event listener from the control. + * @param eventType The type (name) of the event. + * @param listener The listener to remove. + * @param capture Specifies whether or not to initiate capture. + **/ + removeEventListener(eventType: string, listener: Function, capture?: boolean): void; - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - * @returns The promise whose value is the result of executing the onComplete function. - **/ - then(onComplete?: (value: T) => Promise, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => Promise, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - * @returns The promise whose value is the result of executing the onComplete function. - **/ - then(onComplete?: (value: T) => Promise, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => Promise, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - * @returns The promise whose value is the result of executing the onComplete function. - **/ - then(onComplete?: (value: T) => U, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - * @returns The promise whose value is the result of executing the onComplete function. - **/ - then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; - /** - * Performs an operation on all the input promises and returns a promise that has the shape of the input and contains the result of the operation that has been performed on each input. - * @param values A set of values (which could be either an array or an object) of which some or all are promises.. - * @param complete The function to be called if the promise is fulfilled with a value. This function takes a single argument, which is the fulfilled value of the promise. - * @param error The function to be called if the promise is fulfilled with an error. This function takes a single argument, which is the error value of the promise. - * @param progress The function to be called if the promise reports progress. This function takes a single argument, which is the data about the progress of the promise. Promises are not required to support progress. - * @returns A Promise that is the result of calling join on the values parameter. - **/ - static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): Promise; + /** + * Performs an operation on all the input promises and returns a promise that has the shape of the input and contains the result of the operation that has been performed on each input. + * @param values A set of values (which could be either an array or an object) of which some or all are promises.. + * @param complete The function to be called if the promise is fulfilled with a value. This function takes a single argument, which is the fulfilled value of the promise. + * @param error The function to be called if the promise is fulfilled with an error. This function takes a single argument, which is the error value of the promise. + * @param progress The function to be called if the promise reports progress. This function takes a single argument, which is the data about the progress of the promise. Promises are not required to support progress. + * @returns A Promise that is the result of calling join on the values parameter. + **/ + static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): Promise; - /** - * This method has two forms: WinJS.Promise.timeout(timeout) and WinJS.Promise.timeout(timeout, promise). WinJS.Promise.timeout(timeout) creates a promise that is completed asynchronously after the specified timeout, essentially wrapping a call to setTimeout within a promise. WinJS.Promise.timeout(timeout, promise) sets a timeout period for completion of the specified promise, automatically canceling the promise if it is not completed within the timeout period. - * @param timeout The timeout period in milliseconds. If this value is zero or not specified, msSetImmediate is called, otherwise setTimeout is called. - * @param promise Optional. A promise that will be canceled if it doesn't complete within the timeout period. - * @returns If the promise parameter is omitted, returns a promise that will be fulfilled after the timeout period. If the promise paramater is provided, the same promise is returned. - **/ - static timeout(timeout: number, promise?: Promise): Promise; + /** + * This method has two forms: WinJS.Promise.timeout(timeout) and WinJS.Promise.timeout(timeout, promise). WinJS.Promise.timeout(timeout) creates a promise that is completed asynchronously after the specified timeout, essentially wrapping a call to setTimeout within a promise. WinJS.Promise.timeout(timeout, promise) sets a timeout period for completion of the specified promise, automatically canceling the promise if it is not completed within the timeout period. + * @param timeout The timeout period in milliseconds. If this value is zero or not specified, msSetImmediate is called, otherwise setTimeout is called. + * @param promise Optional. A promise that will be canceled if it doesn't complete within the timeout period. + * @returns If the promise parameter is omitted, returns a promise that will be fulfilled after the timeout period. If the promise paramater is provided, the same promise is returned. + **/ + static timeout(timeout: number, promise?: Promise): Promise; - /** - * Wraps a non-promise value in a promise. This method is like wrapError, which allows you to produce a Promise in error conditions, in that it allows you to return a Promise in success conditions. - * @param value Some non-promise value to be wrapped in a promise. - * @returns A promise that is successfully fulfilled with the specified value. - **/ - static wrap(value: U): Promise; + /** + * Wraps a non-promise value in a promise. This method is like wrapError, which allows you to produce a Promise in error conditions, in that it allows you to return a Promise in success conditions. + * @param value Some non-promise value to be wrapped in a promise. + * @returns A promise that is successfully fulfilled with the specified value. + **/ + static wrap(value: U): Promise; - /** - * Wraps a non-promise error value in a promise. You can use this function if you need to pass an error to a function that requires a promise. - * @param error A non-promise error value to be wrapped in a promise. - * @returns A promise that is in an error state with the specified value. - **/ - static wrapError(error: U): Promise; + /** + * Wraps a non-promise error value in a promise. You can use this function if you need to pass an error to a function that requires a promise. + * @param error A non-promise error value to be wrapped in a promise. + * @returns A promise that is in an error state with the specified value. + **/ + static wrapError(error: U): Promise; - //#endregion Methods + //#endregion Methods - } + } - //#endregion Objects + //#endregion Objects - //#region Functions + //#region Functions - /** - * You can provide an implementation of this method yourself, or use WinJS.Utilities.startLog to create one that logs to the JavaScript console. - * @param message The message to log. - * @param tags The tag or tags to categorize the message (winjs, winjs controls, etc.). - * @param type The type of message (error, warning, info, etc.). - **/ - function log(message: string, tags: string, type: string): void; + /** + * You can provide an implementation of this method yourself, or use WinJS.Utilities.startLog to create one that logs to the JavaScript console. + * @param message The message to log. + * @param tags The tag or tags to categorize the message (winjs, winjs controls, etc.). + * @param type The type of message (error, warning, info, etc.). + **/ + function log(message: string, tags: string, type: string): void; - /** - * This method has been deprecated. Strict processing is always on; you don't have to call this method to turn it on. - **/ - function strictProcessing(): void; + /** + * This method has been deprecated. Strict processing is always on; you don't have to call this method to turn it on. + **/ + function strictProcessing(): void; - /** - * Wraps calls to XMLHttpRequest in a promise. - * @param options The options that are applied to the XMLHttpRequest object, as follows: type, url, user, password, responseType, headers, data, customRequestInitializer. - * @returns A promise that returns the XMLHttpRequest object when it completes. - **/ - function xhr(options: IXHROptions): Promise; + /** + * Wraps calls to XMLHttpRequest in a promise. + * @param options The options that are applied to the XMLHttpRequest object, as follows: type, url, user, password, responseType, headers, data, customRequestInitializer. + * @returns A promise that returns the XMLHttpRequest object when it completes. + **/ + function xhr(options: IXHROptions): Promise; - //#endregion Functions + //#endregion Functions - //#region Interfaces + //#region Interfaces - interface IXHROptions { - type?: string; - url: string; - user?: string; - password?: string; - headers?: any; - data: any; - responseType?: string; - } + interface IXHROptions { + type?: string; + url: string; + user?: string; + password?: string; + headers?: any; + data: any; + responseType?: string; + } - //#endregion Interfaces + //#endregion Interfaces } /** * Provides helper functions for defining namespaces. For more information, see Organizing your code with WinJS.Namespace. **/ declare module WinJS.Namespace { - //#region Functions + //#region Functions - /** - * Defines a new namespace with the specified name. For more information, see Organizing your code with WinJS.Namespace. - * @param name The name of the namespace. This could be a dot-separated name for nested namespaces. - * @param members The members of the new namespace. - * @returns The newly-defined namespace. - **/ - function define(name?: string, members?: any): any; + /** + * Defines a new namespace with the specified name. For more information, see Organizing your code with WinJS.Namespace. + * @param name The name of the namespace. This could be a dot-separated name for nested namespaces. + * @param members The members of the new namespace. + * @returns The newly-defined namespace. + **/ + function define(name?: string, members?: any): any; - /** - * Defines a new namespace with the specified name under the specified parent namespace. For more information, see Organizing your code with WinJS.Namespace. - * @param parentNamespace The parent namespace. - * @param name The name of the new namespace. - * @param members The members of the new namespace. - * @returns The newly-defined namespace. - **/ - function defineWithParent(parentNamespace?: any, name?: string, members?: any): any; + /** + * Defines a new namespace with the specified name under the specified parent namespace. For more information, see Organizing your code with WinJS.Namespace. + * @param parentNamespace The parent namespace. + * @param name The name of the new namespace. + * @param members The members of the new namespace. + * @returns The newly-defined namespace. + **/ + function defineWithParent(parentNamespace?: any, name?: string, members?: any): any; - //#endregion Functions + //#endregion Functions } /** * Provides functionality for dealing with basic navigation, including the navigation stack. **/ declare module WinJS.Navigation { - //#region Properties + //#region Properties - /** - * Determines whether it is possible to navigate backwards. - **/ - var canGoBack: boolean; + /** + * Determines whether it is possible to navigate backwards. + **/ + var canGoBack: boolean; - /** - * Determines if it is possible to navigate forwards. - **/ - var canGoForward: boolean; + /** + * Determines if it is possible to navigate forwards. + **/ + var canGoForward: boolean; - /** - * Gets or sets the navigation history. - **/ - var history: any; + /** + * Gets or sets the navigation history. + **/ + var history: any; - /** - * Gets or sets the current location. - **/ - var location: string; + /** + * Gets or sets the current location. + **/ + var location: string; - /** - * Gets or sets a user-defined object that represents the state associated with the current location. - **/ - var state: any; + /** + * Gets or sets a user-defined object that represents the state associated with the current location. + **/ + var state: any; - //#endregion Properties + //#endregion Properties - //#region Functions + //#region Functions - /** - * Adds an event listener to the control. - * @param eventType The type (name) of the event. - * @param listener The listener to invoke when the event gets raised. - * @param capture If true, specifies that capture should be initiated, otherwise false. - **/ - function addEventListener(eventType: string, listener: Function, capture?: boolean): void; + /** + * Adds an event listener to the control. + * @param eventType The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param capture If true, specifies that capture should be initiated, otherwise false. + **/ + function addEventListener(eventType: string, listener: Function, capture?: boolean): void; - /** - * Navigates backwards. - * @param distance The number of entries to go back into the history. - * @returns A promise that is completed with a value that indicates whether or not the navigation was successful. - **/ - function back(distance?: number): Promise; + /** + * Navigates backwards. + * @param distance The number of entries to go back into the history. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful. + **/ + function back(distance?: number): Promise; - /** - * Navigates forwards. - * @param distance The number of entries to go forward. - * @returns A promise that is completed with a value that indicates whether or not the navigation was successful. - **/ - function forward(distance?: number): Promise; + /** + * Navigates forwards. + * @param distance The number of entries to go forward. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful. + **/ + function forward(distance?: number): Promise; - /** - * Navigates to a location. - * @param location The location to navigate to. Generally the location is a string containing the URL, but it may be anything. - * @param initialState A user-defined object that represents the navigation state that may be accessed through state. - * @returns A promise that is completed with a value that indicates whether or not the navigation was successful (true if successful, otherwise false). - **/ - function navigate(location: any, initialState?: any): Promise; + /** + * Navigates to a location. + * @param location The location to navigate to. Generally the location is a string containing the URL, but it may be anything. + * @param initialState A user-defined object that represents the navigation state that may be accessed through state. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful (true if successful, otherwise false). + **/ + function navigate(location: any, initialState?: any): Promise; - /** - * Removes an event listener from the control. - * @param eventType The type (name) of the event. - * @param listener The listener to remove. - * @param useCapture Specifies whether or not to initiate capture. - **/ - function removeEventListener(eventType: string, listener: Function, useCapture?: boolean): void; + /** + * Removes an event listener from the control. + * @param eventType The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture Specifies whether or not to initiate capture. + **/ + function removeEventListener(eventType: string, listener: Function, useCapture?: boolean): void; - //#endregion Functions + //#endregion Functions - //#region Events + //#region Events - /** - * Occurs before navigation. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. - **/ - function onbeforenavigate(eventInfo: CustomEvent): void; + /** + * Occurs before navigation. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onbeforenavigate(eventInfo: CustomEvent): void; - /** - * Occurs after navigation has taken place. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. - **/ - function onnavigated(eventInfo: CustomEvent): void; + /** + * Occurs after navigation has taken place. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onnavigated(eventInfo: CustomEvent): void; - /** - * Occurs when navigation is taking place. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. - **/ - function onnavigating(eventInfo: CustomEvent): void; + /** + * Occurs when navigation is taking place. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onnavigating(eventInfo: CustomEvent): void; - //#endregion Events + //#endregion Events } /** * Provides functions for accessing resources and localizing content. **/ declare module WinJS.Resources { - //#region Functions + //#region Functions - /** - * Registers an event handler for the specified event. Use this method to register for events that are related to resources, such as when the app's language, scale, or contrast changes. - * @param type The name of the event to handle. - * @param listener The listener (event handler function) to associate with the event. - * @param useCapture Set to true to register the listener for the capturing phase; otherwise, set to false to register the listener for the bubbling phase. - **/ - function addEventListener(type: string, listener: Function, useCapture?: boolean): void; + /** + * Registers an event handler for the specified event. Use this method to register for events that are related to resources, such as when the app's language, scale, or contrast changes. + * @param type The name of the event to handle. + * @param listener The listener (event handler function) to associate with the event. + * @param useCapture Set to true to register the listener for the capturing phase; otherwise, set to false to register the listener for the bubbling phase. + **/ + function addEventListener(type: string, listener: Function, useCapture?: boolean): void; - /** - * Raises an event of the specified type and with the specified additional properties. - * @param type The name of the event to raise. - * @param details The set of additional properties to attach to the event object. - **/ - function dispatchEvent(type: string, details: any): void; + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The name of the event to raise. + * @param details The set of additional properties to attach to the event object. + **/ + function dispatchEvent(type: string, details: any): void; - /** - * Retrieves the resource string that has the specified resource identifier. - * @param resourceId The resource ID of the string to retrieve. - * @returns An object that can contain these properties: value, empty, lang. - **/ - function getString(resourceId: string): { value: string; empty?: boolean; lang?: string; }; + /** + * Retrieves the resource string that has the specified resource identifier. + * @param resourceId The resource ID of the string to retrieve. + * @returns An object that can contain these properties: value, empty, lang. + **/ + function getString(resourceId: string): { value: string; empty?: boolean; lang?: string; }; - /** - * Processes data-win-res attributes on elements and replaces attributes and properties with resource strings. - * @param rootElement The element to process. The element and its child elements will be processed. If an element isn't specified, the entire document is processed. - **/ - function processAll(rootElement?: HTMLElement): void; + /** + * Processes data-win-res attributes on elements and replaces attributes and properties with resource strings. + * @param rootElement The element to process. The element and its child elements will be processed. If an element isn't specified, the entire document is processed. + **/ + function processAll(rootElement?: HTMLElement): void; - /** - * Removes an event listener that the addEventListener method registered. - * @param type The name of the event that the event listener is registered for. - * @param listener The listener (event handler function) to remove. - * @param useCapture Set to true to remove the capturing phase listener; set to false to remove the bubbling phase listener. - **/ - function removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + /** + * Removes an event listener that the addEventListener method registered. + * @param type The name of the event that the event listener is registered for. + * @param listener The listener (event handler function) to remove. + * @param useCapture Set to true to remove the capturing phase listener; set to false to remove the bubbling phase listener. + **/ + function removeEventListener(type: string, listener: Function, useCapture?: boolean): void; - //#endregion Functions + //#endregion Functions - //#region Events + //#region Events - /** - * Occurs when the user changes the system's language or contrast, or the scale of the display, or when the user changes any of the items in the current context's qualifier values list. For more info about the current context's qualifier values list, see the Remarks section. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.qualifier, detail.changed. - **/ - function oncontextchanged(eventInfo: CustomEvent): void; + /** + * Occurs when the user changes the system's language or contrast, or the scale of the display, or when the user changes any of the items in the current context's qualifier values list. For more info about the current context's qualifier values list, see the Remarks section. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.qualifier, detail.changed. + **/ + function oncontextchanged(eventInfo: CustomEvent): void; - //#endregion Events + //#endregion Events } /** * Provides access to the Windows animations. These functions provide developers with the ability to use animations in their custom controls that are consistent with animations used by Windows controls. **/ declare module WinJS.UI.Animation { - //#region Functions + //#region Functions - /** - * Creates an object that performs an animation that adds an item or items to a list. - * @param added Element or elements to add to the list. - * @param affected Element or elements affected by the added items. - * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. - **/ - function createAddToListAnimation(added: any, affected: any): IAnimationMethodResponse; + /** + * Creates an object that performs an animation that adds an item or items to a list. + * @param added Element or elements to add to the list. + * @param affected Element or elements affected by the added items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createAddToListAnimation(added: any, affected: any): IAnimationMethodResponse; - /** - * Creates an object that performs an animation that adds an item or items to a list of search results. - * @param added Element or elements to add to the list. - * @param affected Element or elements affected by the added items. - * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. - **/ - function createAddToSearchListAnimation(added: any, affected: any): IAnimationMethodResponse; + /** + * Creates an object that performs an animation that adds an item or items to a list of search results. + * @param added Element or elements to add to the list. + * @param affected Element or elements affected by the added items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createAddToSearchListAnimation(added: any, affected: any): IAnimationMethodResponse; - /** - * Creates an object that performs an animation that collapses a list. - * @param hidden Element or elements hidden as a result of the collapse. - * @param affected Element or elements affected by the hidden items. - * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. - **/ - function createCollapseAnimation(hidden: any, affected: any): IAnimationMethodResponse; + /** + * Creates an object that performs an animation that collapses a list. + * @param hidden Element or elements hidden as a result of the collapse. + * @param affected Element or elements affected by the hidden items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createCollapseAnimation(hidden: any, affected: any): IAnimationMethodResponse; - /** - * Creates an object that performs an animation that removes an item or items from a list. - * @param deleted Element or elements to delete from the list. - * @param remaining Element or elements affected by the removal of the deleted items. - * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. - **/ - function createDeleteFromListAnimation(deleted: any, remaining: any): IAnimationMethodResponse; + /** + * Creates an object that performs an animation that removes an item or items from a list. + * @param deleted Element or elements to delete from the list. + * @param remaining Element or elements affected by the removal of the deleted items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createDeleteFromListAnimation(deleted: any, remaining: any): IAnimationMethodResponse; - /** - * Creates an object that performs an animation that removes an item or items from a list of search results. - * @param deleted Element or elements to delete from the list. - * @param remaining Element or elements affected by the removal of the deleted items. - * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. - **/ - function createDeleteFromSearchListAnimation(deleted: any, remaining: any): IAnimationMethodResponse; + /** + * Creates an object that performs an animation that removes an item or items from a list of search results. + * @param deleted Element or elements to delete from the list. + * @param remaining Element or elements affected by the removal of the deleted items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createDeleteFromSearchListAnimation(deleted: any, remaining: any): IAnimationMethodResponse; - /** - * Creates an object that performs an animation that expands a list. - * @param revealed Element or elements revealed by the expansion. - * @param affected Element or elements affected by the newly revealed items. - * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. - **/ - function createExpandAnimation(revealed: any, affected: any): IAnimationMethodResponse; + /** + * Creates an object that performs an animation that expands a list. + * @param revealed Element or elements revealed by the expansion. + * @param affected Element or elements affected by the newly revealed items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createExpandAnimation(revealed: any, affected: any): IAnimationMethodResponse; - /** - * Creates an object that performs a peek animation. - * @param element Element or elements involved in the peek. - * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. - **/ - function createPeekAnimation(element: any): IAnimationMethodResponse; + /** + * Creates an object that performs a peek animation. + * @param element Element or elements involved in the peek. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createPeekAnimation(element: any): IAnimationMethodResponse; - /** - * Creates an object that performs an animation that moves an item or items. - * @param element Element or elements involved in the reposition. - * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise object that completes when the animation is finished. - **/ - function createRepositionAnimation(element: any): IAnimationMethodResponse; + /** + * Creates an object that performs an animation that moves an item or items. + * @param element Element or elements involved in the reposition. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise object that completes when the animation is finished. + **/ + function createRepositionAnimation(element: any): IAnimationMethodResponse; - /** - * Performs an animation that fades an item or items in, fading out existing items that occupy the same space. - * @param incoming Element or elements being faded in. - * @param outgoing Element or elements being replaced. - * @returns An object that completes when the animation has finished. - **/ - function crossFade(incoming: any, outgoing: any): Promise; + /** + * Performs an animation that fades an item or items in, fading out existing items that occupy the same space. + * @param incoming Element or elements being faded in. + * @param outgoing Element or elements being replaced. + * @returns An object that completes when the animation has finished. + **/ + function crossFade(incoming: any, outgoing: any): Promise; - /** - * Performs an animation when a dragged object is moved such that dropping it in that position would move other items. The potentially affected items are animated out of the way to show where the object would be dropped. - * @param target Element or elements that the dragged object would cause to be moved if it were dropped. - * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @returns An object that completes when the animation is finished. - **/ - function dragBetweenEnter(target: any, offset: any): Promise; + /** + * Performs an animation when a dragged object is moved such that dropping it in that position would move other items. The potentially affected items are animated out of the way to show where the object would be dropped. + * @param target Element or elements that the dragged object would cause to be moved if it were dropped. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function dragBetweenEnter(target: any, offset: any): Promise; - /** - * Performs an animation when a dragged object is moved away from items that it had previously involved in a dragBetweenEnter animation. The affected objects are animated back to their original positions. - * @param target Element or elements that the dragged object would no longer cause to be displaced, due to its moving away. This should be the same element or element collection passed as the target parameter in the dragBetweenEnter animation. - * @returns An object that completes when the animation is finished. - **/ - function dragBetweenLeave(target: any): Promise; + /** + * Performs an animation when a dragged object is moved away from items that it had previously involved in a dragBetweenEnter animation. The affected objects are animated back to their original positions. + * @param target Element or elements that the dragged object would no longer cause to be displaced, due to its moving away. This should be the same element or element collection passed as the target parameter in the dragBetweenEnter animation. + * @returns An object that completes when the animation is finished. + **/ + function dragBetweenLeave(target: any): Promise; - /** - * Performs an animation when the user finishes dragging an object. - * @param dragSource Element or elements that were dragged. - * @param offset Initial offset from the drop point. The dropped object begins at the offset and animates to its final position at the drop point. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @param affected Element or elements whose position the dropped object affects. Typically, this is all other items in a reorderable list. This should be the same element or element collection passed as the affected parameter in the dragSourceStart animation. - * @returns An object that completes when the animation is finished. - **/ - function dragSourceEnd(dragSource: any, offset: any, affected?: any): Promise; + /** + * Performs an animation when the user finishes dragging an object. + * @param dragSource Element or elements that were dragged. + * @param offset Initial offset from the drop point. The dropped object begins at the offset and animates to its final position at the drop point. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param affected Element or elements whose position the dropped object affects. Typically, this is all other items in a reorderable list. This should be the same element or element collection passed as the affected parameter in the dragSourceStart animation. + * @returns An object that completes when the animation is finished. + **/ + function dragSourceEnd(dragSource: any, offset: any, affected?: any): Promise; - /** - * Performs an animation when the user begins to drag an object. - * @param dragSource Element or elements being dragged. - * @param affected Element or elements whose position is affected by the movement of the dragged object. Typically, this is all other items in a reorderable list. - * @returns An object that completes when the animation is finished. - **/ - function dragSourceStart(dragSource: any, affected?: any): Promise; + /** + * Performs an animation when the user begins to drag an object. + * @param dragSource Element or elements being dragged. + * @param affected Element or elements whose position is affected by the movement of the dragged object. Typically, this is all other items in a reorderable list. + * @returns An object that completes when the animation is finished. + **/ + function dragSourceStart(dragSource: any, affected?: any): Promise; - /** - * Performs an animation that displays one or more elements on a page. - * @param incoming Element or elements that compose the incoming content. - * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. - * @returns An object that completes when the animation is finished. - **/ - function enterContent(incoming: any, offset: any, options?: any): Promise; + /** + * Performs an animation that displays one or more elements on a page. + * @param incoming Element or elements that compose the incoming content. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function enterContent(incoming: any, offset: any, options?: any): Promise; - /** - * Performs an animation that shows a new page of content, either when transitioning between pages in a running app or when displaying the first content in a newly launched app. - * @param element Element or an array of elements that represent the content. If element refers to an array of elements, the elements enter in array order. - * @param offset An initial offset where the element or elements begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @returns An object that completes when the animation is finished. - **/ - function enterPage(element: any, offset: any): Promise; + /** + * Performs an animation that shows a new page of content, either when transitioning between pages in a running app or when displaying the first content in a newly launched app. + * @param element Element or an array of elements that represent the content. If element refers to an array of elements, the elements enter in array order. + * @param offset An initial offset where the element or elements begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function enterPage(element: any, offset: any): Promise; - /** - * Performs an animation that hides one or more elements on a page. - * @param outgoing Element or elements that compose the outgoing content. - * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @returns An object that completes when the animation is finished. - **/ - function exitContent(outgoing: any, offset: any): Promise; + /** + * Performs an animation that hides one or more elements on a page. + * @param outgoing Element or elements that compose the outgoing content. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function exitContent(outgoing: any, offset: any): Promise; - /** - * Performs an animation that dismisses the current page when transitioning between pages in an app. - * @param outgoing Element or elements that compose the outgoing page. - * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @returns An object that completes when the animation is finished. - **/ - function exitPage(outgoing: any, offset: any): Promise; + /** + * Performs an animation that dismisses the current page when transitioning between pages in an app. + * @param outgoing Element or elements that compose the outgoing page. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function exitPage(outgoing: any, offset: any): Promise; - /** - * Performs an animation that fades an item or set of items into view. - * @param shown Element or elements being faded in. - * @returns An object that completes when the animation has finished. Use this object when subsequent actions need this animation to finish before they take place. - **/ - function fadeIn(shown: any): Promise; + /** + * Performs an animation that fades an item or set of items into view. + * @param shown Element or elements being faded in. + * @returns An object that completes when the animation has finished. Use this object when subsequent actions need this animation to finish before they take place. + **/ + function fadeIn(shown: any): Promise; - /** - * Performs an animation that fades an item or set of items out of view. - * @param hidden Element or elements being faded out. - * @returns An object that completes when the animation is finished. - **/ - function fadeOut(hidden: any): Promise; + /** + * Performs an animation that fades an item or set of items out of view. + * @param hidden Element or elements being faded out. + * @returns An object that completes when the animation is finished. + **/ + function fadeOut(hidden: any): Promise; - /** - * Performs an animation that hides edge-based user interface (UI). - * @param element Element or elements that are being hidden. - * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. - * @returns An object that completes when the animation is finished. - **/ - function hideEdgeUI(element: any, offset: any, options?: any): Promise; + /** + * Performs an animation that hides edge-based user interface (UI). + * @param element Element or elements that are being hidden. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function hideEdgeUI(element: any, offset: any, options?: any): Promise; - /** - * Performs an animation that hides a panel. - * @param element Element or elements that are being hidden. - * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @returns An object that completes when the animation is finished. - **/ - function hidePanel(element: any, offset: any): Promise; + /** + * Performs an animation that hides a panel. + * @param element Element or elements that are being hidden. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function hidePanel(element: any, offset: any): Promise; - /** - * Performs an animation that removes pop-up user interface (UI). - * @param element Element or elements that are being hidden. - * @returns An object that completes when the animation is finished. - **/ - function hidePopup(element: any): Promise; + /** + * Performs an animation that removes pop-up user interface (UI). + * @param element Element or elements that are being hidden. + * @returns An object that completes when the animation is finished. + **/ + function hidePopup(element: any): Promise; - /** - * Performs an animation when a pointer is pressed on an object. - * @param element Element or elements on which the pointer is pressed. - * @returns An object that completes when the animation is finished. - **/ - function pointerDown(element: any): Promise; + /** + * Performs an animation when a pointer is pressed on an object. + * @param element Element or elements on which the pointer is pressed. + * @returns An object that completes when the animation is finished. + **/ + function pointerDown(element: any): Promise; - /** - * Performs an animation when a pointer is released. - * @param element Element or elements that the pointer was pressed on. - * @returns An object that completes when the animation is finished. - **/ - function pointerUp(element: any): Promise; + /** + * Performs an animation when a pointer is released. + * @param element Element or elements that the pointer was pressed on. + * @returns An object that completes when the animation is finished. + **/ + function pointerUp(element: any): Promise; - /** - * Performs an animation that slides a narrow, edge-based user interface (UI) into view. - * @param element Element or elements that are being shown. - * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. - * @returns An object that completes when the animation is finished. - **/ - function showEdgeUI(element: any, offset: any, options?: any): Promise; + /** + * Performs an animation that slides a narrow, edge-based user interface (UI) into view. + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function showEdgeUI(element: any, offset: any, options?: any): Promise; - /** - * Performs an animation that slides a large panel user interface (UI) into view. - * @param element Element or elements that are being shown. - * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @returns An object that completes when the animation is finished. - **/ - function showPanel(element: any, offset: any): Promise; + /** + * Performs an animation that slides a large panel user interface (UI) into view. + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function showPanel(element: any, offset: any): Promise; - /** - * Performs an animation that displays a pop-up user interface (UI). - * @param element Element or elements that are being shown. - * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @returns An object that completes when the animation is finished. - **/ - function showPopup(element: any, offset: any): Promise; + /** + * Performs an animation that displays a pop-up user interface (UI). + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function showPopup(element: any, offset: any): Promise; - /** - * Performs a deselection animation in response to a swipe interaction. - * @param deselected Element or elements that become unselected. - * @param selection Element or elements that represent the selection, typically a check mark. - * @returns An object that completes when the animation is finished. - **/ - function swipeDeselect(deselected: any, selection: any): Promise; + /** + * Performs a deselection animation in response to a swipe interaction. + * @param deselected Element or elements that become unselected. + * @param selection Element or elements that represent the selection, typically a check mark. + * @returns An object that completes when the animation is finished. + **/ + function swipeDeselect(deselected: any, selection: any): Promise; - /** - * Performs an animation that reveals an item or items in response to a swipe interaction. - * @param target Element or elements being revealed. - * @param offset An initial offset where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @returns An object that completes when the animation is finished. - **/ - function swipeReveal(target: any, offset: any): Promise; + /** + * Performs an animation that reveals an item or items in response to a swipe interaction. + * @param target Element or elements being revealed. + * @param offset An initial offset where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function swipeReveal(target: any, offset: any): Promise; - /** - * Performs a selection animation in response to a swipe interaction. - * @param selected Element or elements being selected. - * @param selection Element or elements that show that something is selected, typically a check mark. - * @returns An object that completes when the animation is finished. - **/ - function swipeSelect(selected: any, selection: any): Promise; + /** + * Performs a selection animation in response to a swipe interaction. + * @param selected Element or elements being selected. + * @param selection Element or elements that show that something is selected, typically a check mark. + * @returns An object that completes when the animation is finished. + **/ + function swipeSelect(selected: any, selection: any): Promise; - /** - * Performs an animation that updates a badge. - * @param incoming Element or elements that comprise the new badge. - * @param offset Initial offsets where incoming animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @returns An object that completes when the animation is finished. - **/ - function updateBadge(incoming: any, offset: any): Promise; + /** + * Performs an animation that updates a badge. + * @param incoming Element or elements that comprise the new badge. + * @param offset Initial offsets where incoming animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function updateBadge(incoming: any, offset: any): Promise; - //#endregion Functions + //#endregion Functions - //#region Interfaces + //#region Interfaces - interface IAnimationMethodResponse { - execute(): Promise; - } + interface IAnimationMethodResponse { + execute(): Promise; + } - //#endregion Interfaces + //#endregion Interfaces } /** * Provides controls and objects that manipulate data. **/ declare module WinJS.UI { - //#region Enumerations - - /** - * Specifies an icon that appears in an AppBarCommand object. - **/ - enum AppBarIcon { - previous, - next, - play, - pause, - edit, - save, - clear, - delete, - remove, - add, - cancel, - accept, - more, - redo, - undo, - home, - up, - forward, - right, - back, - left, - favorite, - camera, - settings, - video, - sync, - download, - mail, - find, - help, - upload, - emoji, - twopage, - leavechat, - mailforward, - clock, - send, - crop, - rotatecamera, - people, - closepane, - openpane, - world, - flag, - previewlink, - globe, - trim, - attachcamera, - zoomin, - bookmarks, - document, - protecteddocument, - page, - bullets, - comment, - mail2, - contactinfo, - hangup, - viewall, - mappin, - phone, - videochat, - switch, - contact, - rename, - pin, - musicinfo, - go, - keyboard, - dockleft, - dockright, - dockbottom, - remote, - refresh, - rotate, - shuffle, - list, - shop, - selectall, - orientation, - import, - importall, - browsephotos, - webcam, - pictures, - savelocal, - caption, - stop, - showresults, - volume, - repair, - message, - page2, - calendarday, - calendarweek, - calendar, - characters, - mailreplyall, - read, - link, - accounts, - showbcc, - hidebcc, - cut, - attach, - paste, - filter, - copy, - emoji2, - important, - mailreply, - slideshow, - sort, - manage, - allapps, - disconnectdrive, - mapdrive, - newwindow, - openwith, - contactpresence, - priority, - uploadskydrive, - gototoday, - font, - fontcolor, - contact2, - folder, - audio, - placeholder, - view, - setlockscreen, - settile, - cc, - stopslideshow, - permissions, - highlight, - disableupdates, - unfavorite, - unpin, - openlocal, - mute, - italic, - underline, - bold, - movetofolder, - likedislike, - dislike, - like, - alignright, - aligncenter, - alignleft, - zoom, - zoomout, - openfile, - otheruser, - admin, - street, - map, - clearselection, - fontdecrease, - fontincrease, - fontsize, - cellphone, - reshare, - tag, - repeatone, - repeatall, - outlinestar, - solidstar, - calculator, - directions, - target, - library, - phonebook, - memo, - microphone, - postupdate, - backtowindow, - fullscreen, - newfolder, - calendarreply, - unsyncfolder, - reporthacked, - syncfolder, - blockcontact, - switchapps, - addfriend, - touchpointer, - gotostart, - zerobars, - onebar, - twobars, - threebars, - fourbars, - scan, - preview - } - - /** - * Indicates whether the IListDataAdapter was able to provide a count. - **/ - enum CountResult { - /** - * Indicates no count is available. - **/ - unknown - } - - /** - * Indicates that the IListDataAdapter was unable to provide a count. - **/ - enum CountError { - /** - * An attempt to count items timed out. - **/ - noResponse - } - - /** - * Describes the status of an IListDataSource. - **/ - enum DataSourceStatus { - /** - * The IListDataSource is ready. - **/ - ready, - /** - * The IListDataSource is still loading. - **/ - waiting, - /** - * The IListDataSource failed to load. - **/ - failure - } - - /** - * Specifies the type of error that occurred during an edit operation on a IListDataSource or an IListDataAdapter. - **/ - enum EditError { - /** - * The edit operation timed out. - **/ - noResponse, - /** - * The data source cannot be written to. - **/ - notPermitted, - /** - * The item has changed. - **/ - noLongerMeaningful - } - - /** - * Specifies the type of error encountered when retrieving items from an IListDataAdapter. - **/ - enum FetchError { - /** - * The fetch operation timed out. - **/ - noResponse, - /** - * The specified item could not be located. - **/ - doesNotExist - } - - /** - * Specifies how group headers in a ListView respond to the tap interaction. - **/ - enum GroupHeaderTapBehavior { - /** - * The group is invoked. - **/ - invoke, - /** - * Nothing happens. - **/ - none - } - - /** - * Specifies the position of group headers relative to their items in a ListView. - **/ - enum HeaderPosition { - /** - * Group headers appear to the left of items. - **/ - left, - /** - * Group headers appear above items. - **/ - top - } - - /** - * Specifies that type of animation for which a contentanimating event was raised. - **/ - enum ListViewAnimationType { - /** - * The animation plays when the ListView is first displayed. - **/ - entrance, - /** - * The animation plays when the ListView is changing its content. - **/ - contentTransition - } - - /** - * Describes the type of object in a ListView. - **/ - enum ObjectType { - /** - * The object is a group header in the list. - **/ - groupHeader, - /** - * The object is an item in the list. - **/ - item - } - - /** - * Specifies the orientation of a control. - **/ - enum Orientation { - /** - * A horizontal layout. - **/ - horizontal, - /** - * A vertical layout. - **/ - vertical - } - - /** - * Specifies the selection mode of a ListView. - **/ - enum SelectionMode { - /** - * Items cannot be selected. - **/ - none, - /** - * A single item may be selected. - **/ - single, - /** - * Multiple items may be selected. Clicking additional items adds them to the selection. - **/ - multi - } - - /** - * Specifies whether elements are selected when the user performs a swipe interaction. - **/ - enum SwipeBehavior { - /** - * The swipe interaction selects the elements touched by the swipe. - **/ - select, - /** - * The swipe interaction does not change which elements are selected. - **/ - none - } - - /** - * Specifies how items in a ListView respond to the tap interaction. - **/ - enum TapBehavior { - /** - * The item is selected and invoked. - **/ - directSelect, - /** - * The item is selected if was not already selected, and its deselected if it was already selected. - **/ - toggleSelect, - /** - * The item is invoked but not selected. - **/ - invokeOnly, - /** - * Nothing happens. - **/ - none - } - - //#endregion Enumerations - - //#region Interfaces - - /** - * Contains items that were requested from an IListDataAdapter and provides some information about those items. - **/ - interface IFetchResult { - //#region Properties - - /** - * Gets or sets the index of the requested item in the IListDataAdapter object's data source. - **/ - absoluteIndex: number; - - /** - * Gets or sets a value that indicates whether this IFetchResult contains the last items at the end of the IListDataAdapter object's data source. - **/ - atEnd: boolean; - - /** - * Gets or sets a value that indicates whether this IFetchResult contains the first items at the beginning of the IListDataAdapter object's data source. - **/ - atStart: boolean; - - /** - * Gets or sets the items returned by the fetch operation. - **/ - items: T[]; - - /** - * Gets or sets the location of the requested item within the items array. - **/ - offset: number; - - /** - * Gets or sets the number of items in the IListDataAdapter object's underlying data source. - **/ - totalCount: number; - - //#endregion Properties - - } - - /** - * Represents an item in a list. - **/ - interface IItem { - //#region Properties - - /** - * Gets or sets the item's data. - **/ - data: T; - - /** - * Gets the group key for the item. This property is only available for items that belong to a grouped data source. - **/ - groupKey: string; - - /** - * Gets the temporary ID of the item. - **/ - handle: string; - - /** - * Gets the item's index in the IListDataSource. - **/ - index: number; - - /** - * Gets or sets the key the identifies the item. - **/ - key: string; - - //#endregion Properties - - } - - /** - * Provides a mechanism for retrieving IItem objects asynchronously. - **/ - interface IItemPromise { - //#region Events - - /** - * Occurs when there is an error in processing. - * @param eventInfo An object that contains information about the event. - **/ - onerror(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). - **/ - cancel(): void; - - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - **/ - done(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): void; - - /** - * Stops change notification tracking for the IItem that fulfills this IItemPromise. - **/ - release(): void; - - /** - * Begins change notification tracking for the IItem that fulfills this IItemPromise. - **/ - retain(): void; - - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function becomes the fulfilled value of the promise returned by then. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - * @returns The promise whose value is the result of executing the complete or error function. - **/ - then(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): IItemPromise; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the temporary ID of the IItem that fulfills this promise. - **/ - handle: string; - - /** - * Gets or sets the index of the IItem contained by this IItemPromise. - **/ - index: number; - - //#endregion Properties - - } - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. Represents a layout for the ListView. - **/ - interface ILayout { - //#region Methods - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param beginScrollPosition The first visible pixel in the ListView. For horizontal layouts, this is the x-coordinate of the pixel. For vertical layouts, this is the y-coordinate. - * @param wholeItem true if the item must be completely visible; otherwise, false if its ok for the item to be partially visible. Promise. - * @returns A Promise for the index of the first visible item at the specified point. - **/ - calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): Promise; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param endScrollPosition The last visible pixel in the ListView. For horizontal layouts, this is the x-coordinate of the pixel. For vertical layouts, this is the y-coordinate. - * @param wholeItem true if the item must be completely visible; otherwise, false if its ok for the item to be partially visible. Promise. - * @returns A Promise for the index of the last visible item at the specified point. - **/ - calculateLastVisible(endScrollPosition: number, wholeItem: boolean): Promise; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @returns A object that has these properties: animationPromise, newEndIndex. - **/ - endLayout(): any; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param itemIndex The index of the item. - * @returns A Promise that returns an object with these properties: left, top, contentWidth, contentHeight, totalWidth, totalHeight. - **/ - getItemPosition(itemIndex: number): Promise; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param itemIndex The data source index of the current item. - * @param element The element for the current item. - * @param keyPressed The key that was pressed. This function must check for the arrow keys (leftArrow, upArrow, rightArrow, downArrow), pageDown, and pageUp and determine which item the user navigated to. - * @returns A Promise that contains the index of the next item (This item becomes the current item). - **/ - getKeyboardNavigatedItem(itemIndex: number, element: HTMLElement, keyPressed: WinJS.Utilities.Key): Promise; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @returns A Promise that returns an object that has these properties: beginScrollPosition, endScrollPosition. - **/ - getScrollBarRange(): Promise; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param x The x-coordinate to test. - * @param y The y-coordinate to test. - **/ - hitTest(x: number, y: number): void; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param elements The elements that represent the items that were added. - **/ - itemsAdded(elements: HTMLElement[]): void; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - **/ - itemsMoved(): void; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param elements The elements that represent the items that were removed. - **/ - itemsRemoved(elements: HTMLElement[]): void; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param groupIndex The index of the group in the group data source. - * @param element The element to render for the group header. - **/ - layoutHeader(groupIndex: number, element: HTMLElement): void; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param itemIndex The index of the item in the data source. - * @param element The element to render for the item. - **/ - layoutItem(itemIndex: number, element: HTMLElement): void; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param element The element that represents a header in the data source. - **/ - prepareHeader(element: HTMLElement): void; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param element An element that represents an item in the data source. - **/ - prepareItem(element: HTMLElement): void; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param element The element being released. - **/ - releaseItem(element: HTMLElement): void; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - **/ - reset(): void; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param site The layout site for the layout. You can use this object to query the hosting ListView for info you might need to lay out items. - **/ - setSite(site: ILayoutSite): void; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param beginScrollPosition The starting pixel of the area to which the items are rendered. - * @param endScrollPosition The last pixel of the area to which the items are rendered. - * @param count The upper bound of the number of items to render. - * @returns A Promise that returns an object that has these properties: beginIndex, endIndex. - **/ - startLayout(beginScrollPosition: number, endScrollPosition: number, count: number): Promise; - - //#endregion Methods - - //#region Properties - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - **/ - horizontal: boolean; - - //#endregion Properties - - } - - /** - * Represents a layout for the ListView. - **/ - interface ILayout2 { - //#region Methods - - /** - * Called when the ListView finishes a drag operation. - **/ - dragLeave(): void; - - /** - * Called when the ListView initiates a drag operation. - * @param x The x-coordinate of the drag. - * @param y The y-coordinate of the drag. - * @param dragInfo An object that indicates whether the item is selected. - **/ - dragOver(x: number, y: number, dragInfo: number): void; - - /** - * Called when the ListView requests that the ILayout2 execute animations. - **/ - executeAnimations(): void; - - /** - * Determines the next item to receive keyboard focus. - * @param currentItem An object that describes the current item. It has these properties: index, type. - * @param pressedKey The key that was pressed. - * @returns An object that describes the next item that should receive focus. It has these properties: index, type. - **/ - getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; - - /** - * Gets the item at the specified hit-test coordinates. These coordinates are absolute coordinates (they are not relative to the layout's content area). - * @param x The x-coordinate to test for. - * @param y The y-coordinate to test for. - * @returns An object that describes the item at the hit test coordinates. It has these properties: type, index. - **/ - hitTest(x: number, y: number): any; - - /** - * Sets the rendering site and specifies whether the layout supports groups. This method is called by the ListView to initialize the layout. - * @param site The rendering site for the layout. - * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. - **/ - initialize(site: ILayoutSite2, groupsEnabled: boolean): void; - - /** - * Retrieves the indexes of the items in the specified pixel range. - * @param firstPixel The first pixel the range of items falls between. - * @param lastPixel The last pixel the range of items falls between. - **/ - itemsFromRange(firstPixel: number, lastPixel: number): void; - - /** - * Performs a layout pass. - * @param tree A structure representing the layout tree that is returned from the ListView. - * @param changedRange An object that lists the index of the first item in the changed item range. This object has these properties: startIndex. - * @param modifiedItems An object that contains the old and new indexes of the items that have been modified in the tree. - * @param modifiedGroups An object that contains the old and new indexes of the group elements that have been modified in the tree. - * @returns A Promise that executes after layout is complete, or an object that contains two Promise objects: realizedRangeComplete, layoutComplete. - **/ - layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): any; - - /** - * Called when the ListView requests that the ILayout2 set up animations. - **/ - setupAnimations(): void; - - /** - * Releases resources that were obtained during the call to initialize. - **/ - uninitialize(): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the orientation of the layout. - **/ - orientation: any; - - //#endregion Properties - - } - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayoutSite2 interface. Represents a rendering site for an ILayout. - **/ - interface ILayoutSite { - //#region Properties - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. - **/ - animationsDisabled: boolean; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. - **/ - itemSurface: HTMLElement; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. - **/ - rtl: boolean; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. - **/ - scrollbarPos: number; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. - **/ - surface: HTMLElement; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. - **/ - viewport: HTMLElement; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. - **/ - viewportSize: any; - - //#endregion Properties - - } - - /** - * Represents a rendering site for an ILayout2. - **/ - interface ILayoutSite2 { - //#region Properties - - /** - * Gets the number of groups in the site. - **/ - groupCount: number; - - /** - * Gets the number of items in the site. - **/ - itemCount: Promise; - - /** - * Gets the pixel range of the realization area. - **/ - realizedRange: any; - - /** - * Gets the tree for use by an object that implements the ILayout2 interface. - **/ - tree: any; - - /** - * Gets the pixel range of visible items in the site. - **/ - visibleRange: any; - - //#endregion Properties - - } - - /** - * Retrieves items from a IListDataSource, enumerates the contents of a IListDataSource, and can optionally register for change notifications. - **/ - interface IListBinding { - //#region Methods - - /** - * Retrieves the current item. - * @returns An IItemPromise that contains the current item. If the cursor has moved past the start or end of the list, the promise completes with a value of null. If the current item has been moved or deleted, the promise returns an error. - **/ - current(): IItemPromise>; - - /** - * Gets the first item from the IListDataSource and makes it the current item. - * @returns An IItemPromise that contains the requested IItem. If the list is empty, the promise completes with a value of null. - **/ - first(): IItemPromise>; - - /** - * Retrieves the item from the IListDataSource that has the specified description and makes it the current item. - * @param description A domain-specific description, to be interpreted by the IListDataAdapter, that identifies the item to retrieve. - * @returns An IItemPromise that contains the requested IItem object. If the item wasn't found, the promise completes with a value of null. - **/ - fromDescription(description: string): IItemPromise>; - - /** - * Retrieves the item from the IListDataSource that has the specified index and makes it the current item. - * @param index A value greater than or equal to 0 that is the index of the item to retrieve. - * @returns An IItemPromise that contains the requested IItem. If the item wasn't found, the promise completes with a value of null. - **/ - fromIndex(index: number): IItemPromise>; - - /** - * Retrieves the item from the IListDataSource that has the specified key and makes it the current item. - * @param key The key that identifies the item to retrieve. This value must be a non-empty string. - * @param hints Domain-specific information that provides additional information to the IListDataAdapter to improve retrieval time. - * @returns An IItemPromise that contains the requested IItem. If they item couldn't be found, the promise completes with a value of null. - **/ - fromKey(key: string, hints?: any): IItemPromise>; - - /** - * Makes the specified IItem or IItemPromise the current item. - * @param item The IItem or IItemPromise that will become the current item. - * @returns An IItemPromise that contains the specified item, if it exists. If the specified item is not in the list, the promise completes with a value of null. - **/ - jumpToItem(item: IItem): IItemPromise>; - - /** - * Retrieves the last item in the IListDataSource and makes it the current item. - * @returns An IItemPromise that contains the requested IItem. f the list is empty, the promise completes with a value of null. - **/ - last(): IItemPromise>; - - /** - * Retrieves the item after the current item and makes it the current item. - * @returns An IItemPromise that contains the item after the current item. If the cursor moves past the end of the list, the promise completes with a value of null. - **/ - next(): IItemPromise>; - - /** - * Retrieves the item before the current item and makes it the current item. - * @returns An IItemPromise that contains the item before the current item. If the cursor moves past the start of the list, the promise completes with a value of null. - **/ - previous(): IItemPromise>; - - /** - * Releases resources, stops notifications, and cancels outstanding promises for all tracked items returned by this IListBinding. - **/ - release(): void; - - /** - * Creates a request to stop change notifications for the specified item. The change notifications stop when the number of releaseItem calls matches the number of IIItemPromise.retain calls. - * @param item The IItem or IItemPromise that should stop receiving notifications. - **/ - releaseItem(item: IItem): void; - - //#endregion Methods - - } - - /** - * Accesses data for an IListDataSource. - **/ - interface IListDataAdapter { - //#region Methods - - /** - * Overwrites the data of the specified item. - * @param key The key of the item to overwrite. - * @param newData The new data for the item. - * @param indexHint The index of the item, if known. - * @returns A Promise that returns null or undefined when the operation completes. - **/ - change(key: string, newData: T, indexHint: number): Promise; - - /** - * Gets the number of items in the IListDataAdapter object's data source. - * @returns A Promise that contains the number of items the IListDataAdapter contains, or an approximate value if the actual number is unknown. - **/ - getCount(): Promise; - - /** - * Inserts the specified data after the specified item. - * @param key A key that can be used to retrieve the new data. - * @param data The new data to add to the IListDataAdapter object's data source. - * @param previousKey The key of an item in the IListDataAdapter object's data source. The new data will be inserted after this item. - * @param previousIndexHint The index of the item to insert the new data after, if known. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - insertAfter(key: string, data: T, previousKey: string, previousIndexHint: number): Promise>; - - /** - * Adds the specified key and data to the end of the IListDataAdapter object's data source. - * @param key A key that can be used to retrieve the new data. - * @param data The new data to add to the IListDataAdapter object's data source. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - insertAtEnd(key: string, data: T): Promise>; - - /** - * Adds the specified key and data to the beginning of the IListDataAdapter object's data source. - * @param key A key that can be used to retrieve the new data. - * @param data The new data to add to the IListDataAdapter object's data source. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - insertAtStart(key: string, data: T): Promise>; - - /** - * Inserts the specified data before the specified item. - * @param key A key that can be used to retrieve the new data. - * @param data The new data to add to the IListDataAdapter object's data source. - * @param nextKey The key of an item in the IListDataAdapter object's data source. The new data will be inserted before this item. - * @param nextIndexHint The index of the item to insert the new data before, if known. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - insertBefore(key: string, data: T, nextKey: string, nextIndexHint: number): Promise>; - - /** - * Retrieves the item that matches the specified description and also retrieves the specified number of items before and after the matched item. - * @param description A description of the item to locate. - * @param countBefore The number of items before the matched item to retrieve. - * @param countAfter The number of items after the matched item to retrieve. - * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. - **/ - itemsFromDescription(description: string, countBefore: number, countAfter: number): Promise>; - - /** - * Retrieves the specified number of items from the end of the IListDataAdapter object's data source. - * @param count The number of items to retrieve. - * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. - **/ - itemsFromEnd(count: number): Promise>; - - /** - * Retrieves the item at the specified index and also retrieves the specified number of items before and after the selected item. - * @param index The index of the item to retrieve. - * @param countBefore The number of items to retrieve from before the selected item. - * @param countAfter The number of items to retrieve from after the selected item. - * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. - **/ - itemsFromIndex(index: number, countBefore: number, countAfter: number): Promise>; - - /** - * Retrieves the item that has the specified key and also retrieves the specified number of items before and after the selected item. - * @param key The key of the item to retrieve. - * @param countBefore The number of items to retrieve from before the selected item. - * @param countAfter The number of items to retrieve from after the selected item. - * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. - **/ - itemsFromKey(key: string, countBefore: number, countAfter: number): Promise>; - - /** - * Retrieves the specified number of items from the beginning of the IListDataAdapter object's data source. - * @param count The number of items to retrieve. - * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. - **/ - itemsFromStart(count: number): Promise>; - - /** - * Returns a string representation of the specified item that can be used for comparisons. - * @param item The item for which to generate a signature. - * @returns The signature representation of the specified item. - **/ - itemSignature(item: IItem): string; - - /** - * Moves the specified item to just after another item. - * @param key A key of the item to move. - * @param previousKey The key of another item. The item to move will be moved to just after this item. - * @param indexHint The index of the item to move, if known. - * @param previousIndexHint The index to move the item after, if known. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - moveAfter(key: string, previousKey: any, indexHint: string, previousIndexHint: number): Promise>; - - /** - * Moves the specified item to just before another item. - * @param key A key of the item to move. - * @param nextKey The key of another item. The item to move will be moved to just before this item. - * @param indexHint The index of the item to move, if known. - * @param nextIndexHint The index to move the item before, if known. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - moveBefore(key: string, nextKey: any, indexHint: string, nextIndexHint: number): Promise>; - - /** - * Moves the specified item to the end of the IListDataAdapter object's data source. - * @param key The key for the item to move. - * @param indexHint The index of the item to move, if known. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - moveToEnd(key: string, indexHint: number): Promise>; - - /** - * Moves the specified item to the beginning of the IListDataAdapter object's data source. - * @param key The key for the item to move. - * @param indexHint The index of the item to move, if known. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - moveToStart(key: string, indexHint: number): Promise>; - - /** - * Removes the specified item from the IListDataAdapter object's data source. - * @param key The key of the item to remove. - * @param data The new data for the item. - * @param indexHint The index of the item. - * @returns A Promise that returns null or undefined when the operation completes. - **/ - remove(key: string, data: T, indexHint: number): Promise; - - /** - * Registers a notification handler. The IListDataAdapter uses the handler to notify listening objects when its data changes. - * @param notificationHandler The notification handler that the IListDataAdapter will use to provide change notifications. . - **/ - setNotificationHandler(notificationHandler: IListDataNotificationHandler): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets a value that specifies whether to use an object's identity to determine if an item has changed. - **/ - compareByIdentity: boolean; - - //#endregion Properties - - } - - /** - * Notifies clients when an IListDataAdapter object's data changes. - **/ - interface IListDataNotificationHandler { - //#region Methods - - /** - * Indicates the start of a notification batch. Objects that are listening for notifications should defer making updates until endNotifications is called. - **/ - beginNotifications(): void; - - /** - * Raises a notification that an item in the IListDataAdapter object's data source has changed. - * @param item The item that changed. - **/ - changed(item: IItem): void; - - /** - * Indicates the end of a notification batch. When the beginNotifications method is called, objects listening for notifications should defer making updates until endNotifications is called. - **/ - endNotifications(): void; - - /** - * Raises a notification that an item has been added to the IListDataAdapter object's data source. - * @param newItem The new item added to the IListDataAdapter object's data source. - * @param previousKey The key of the item that now precedes the new item, or null if the item was inserted at the start of the list. If nextKey is provided, this parameter may be null. - * @param nextKey The key of the item that now follows the new item, or null if the item was inserted at the end of the list. If previousKey is provided, this parameter may be null. - * @param index The index of the new item. - **/ - inserted(newItem: IItem, previousKey: string, nextKey: string, index?: number): void; - - /** - * Indicates that all previous data obtained from the IListDataAdapter is invalid and should be refreshed. - * @returns A Promise that completes when the data has been completely refreshed and all change notifications have been sent. - **/ - invalidateAll(): Promise; - - /** - * Raises a notification that an item was moved within the IListDataAdapter object's data source. - * @param item The item that was moved. - * @param previousKey The key of the item that now precedes the new item, or null if the item was moved to the beginning of the list. If nextKey is provided, this parameter may be null. - * @param nextKey The key of the item that now follows the new item, or null if the item was moved to the end of the list. If previousKey is provided, this parameter may be null. - * @param oldIndex The item's original index. - * @param newIndex The item's new index. - **/ - moved(item: IItem, previousKey: string, nextKey: string, oldIndex?: number, newIndex?: number): void; - - /** - * Reloads data from the IListDataAdapter. - **/ - reload(): void; - - /** - * Raises a notification that an item was removed from the IListDataAdapter object's data source. - * @param key The key of the item that was removed. - * @param index The index of the item that was removed. - **/ - removed(key: string, index?: number): void; - - //#endregion Methods - - } - - /** - * Provides access to a data source and enables you to bind, change, add, remove, and move items in that data source. - **/ - interface IListDataSource { - //#region Events - - /** - * Occurs when the status of the IListDataSource changes. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: status. - **/ - statuschanged(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Notifies the IListDataSource that a sequence of edits is about to begin. The IListDataSource will defer notifications until endEdits is called. - **/ - beginEdits(): void; - - /** - * Overwrites the data of the specified item. - * @param key The key for the item to replace. - * @param newData The new data for the item. - * @returns A Promise that contains the IItem that was updated or an EditError if an error was encountered. - **/ - change(key: string, newData: T): Promise>; - - /** - * Creates an IListBinding that can retrieve items from the IListDataSource, enumerate the contents of the IListDataSource object's data, and optionally register for change notifications. - * @param notificationHandler Enables the IListBinding to register for change notifications for individual items obtained from the IListDataSource. If you omit this parameter, change notifications won't be available. - * @returns The new IListBinding. - **/ - createListBinding(notificationHandler?: IListNotificationHandler): IListBinding; - - /** - * Notifies the IListDataSource that the batch of edits that began with the last beginEdits call has completed. The IListDataSource will submit notifications for any changes that occurred between the beginEdits and endEdits calls as a batch and resume normal change notifications. - **/ - endEdits(): void; - - /** - * Retrieves the number of items in the data source. - * @returns A Promise that provides a Number that is the number of items in the data source. - **/ - getCount(): Promise; - - /** - * Inserts a new item after another item. - * @param key The key that can be used to retrieve the new item, if known. - * @param data The data for the item to add. - * @param previousKey The key for an item in the data source. The new item will be added after this item. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - insertAfter(key: string, data: T, previousKey: string): Promise>; - - /** - * Adds an item to the end of the data source. - * @param key The key that can be used to retrieve the new item, if known. - * @param data The data for the item to add. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - insertAtEnd(key: string, data: T): Promise>; - - /** - * Adds an item to the beginning of the data source. - * @param key The key that can be used to retrieve the new item, if known. - * @param data The data for the item to add. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - insertAtStart(key: string, data: T): Promise>; - - /** - * Inserts an item before another item. - * @param key The key that can be used to retrieve the new item, if known. - * @param data The data for the item to add. - * @param nextKey The key of an item in the data source. The new item will be inserted before this item. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - insertBefore(key: string, data: T, nextKey: string): Promise>; - - /** - * Indicates that all previous data obtained from the IListDataAdapter is invalid and should be refreshed. - * @returns A Promise that completes when the data has been completely refreshed and all notifications have been sent. - **/ - invalidateAll(): Promise; - - /** - * Retrieves the item that has the specified description. - * @param description Domain-specific information, to be interpreted by the IListDataAdapter, that describes the item to retrieve. - * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item wasn't found, the promise completes with a value of null. - **/ - itemFromDescription(description: any): Promise>; - - /** - * Retrieves the item at the specified index. - * @param index A value that is greater than or equal to zero that is the index of the item to retrieve. - * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item wasn't found, the promise completes with a value of null. - **/ - itemFromIndex(index: number): Promise>; - - /** - * Retrieves the item with the specified key. - * @param key The key of the item to retrieve. It must be a non-empty string. - * @param description Domain-specific information that IListDataAdapter can use to improve the retrieval time. - * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item was not found, the promise completes with a null value. - **/ - itemFromKey(key: string, description?: any): Promise>; - - /** - * Moves an item to just after another item. - * @param key The key that identifies the item to move. - * @param previousKey The key of another item in the data source. The item specified by the key parameter will be moved after this item. - * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. - **/ - moveAfter(key: string, previousKey: string): Promise>; - - /** - * Moves an item before another item. - * @param key The key that identifies the item to move. - * @param nextKey The key of another item in the data source. The item specified by the key parameter will be moved before this item. - * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. - **/ - moveBefore(key: string, nextKey: string): Promise>; - - /** - * Moves an item to the end of the data source. - * @param key The key that identifies the item to move. - * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. - **/ - moveToEnd(key: string): Promise>; - - /** - * Moves the specified item to the beginning of the data source. - * @param key The key that identifies the item to move. - * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. - **/ - moveToStart(key: string): Promise>; - - /** - * Removes the specified item from the data source. - * @param key The key that identifies the item to remove. - * @returns A Promise that contains nothing if the operation was successful or an EditError if an error was encountered. - **/ - remove(key: string): Promise>; - - //#endregion Methods - - } - - /** - * Used by an IListBinding to provide change notifications when items in a IListDataSource change. - **/ - interface IListNotificationHandler { - //#region Methods - - /** - * Indicates the start of a notification batch. Objects that are listening for notifications should defer making updates until endNotifications is called. - **/ - beginNotifications(): void; - - /** - * Indicates that an item changed. - * @param newItem The updated item. - * @param oldItem The original item. - **/ - changed(newItem: IItem, oldItem: IItem): void; - - /** - * Indicates that the number of items in the IListDataSource has changed. - * @param newCount The updated count. - * @param oldCount The original count. - **/ - countChanged(newCount: number, oldCount: number): void; - - /** - * Indicates the end of a notification batch. When the beginNotifications method is called, objects listening for notifications should defer making updates until endNotifications is called. - **/ - endNotifications(): void; - - /** - * Indicates that the index of an item changed. - * @param handle The temporary ID of the item. - * @param newIndex The new index. - * @param oldIndex The original index. - **/ - indexChanged(handle: string, newIndex: number, oldIndex: number): void; - - /** - * Indicates that an item was added to the IListDataSource. - * @param itemPromise A promise for the new IItem. - * @param previousHandle The temporary ID of the item that precedes the new item. - * @param nextHandle The temporary ID of the item that follows the new item. - **/ - inserted(itemPromise: IItemPromise, previousHandle: string, nextHandle: string): void; - - /** - * Indicates that an IItemPromise was fulfilled and that the item is now available. - * @param item The fulfilled item. - **/ - itemAvailable(item: IItem): void; - - /** - * Indicates that an item was moved. - * @param item A promise for the IItem that was moved. - * @param previousHandle The temporary ID of the item that now precedes the moved item. - * @param nextHandle The temporary ID of the item that now follows the moved item. - **/ - moved(item: IItemPromise, previousHandle: string, nextHandle: string): void; - - /** - * Indicates that an item was removed. - * @param handle The temporary ID of the item that was removed. - * @param mirage true if the item never actually existed; false if the item was actually present in the IListDataSource. - **/ - removed(handle: string, mirage: boolean): void; - - //#endregion Methods - - } + //#region Enumerations + + /** + * Specifies an icon that appears in an AppBarCommand object. + **/ + enum AppBarIcon { + previous, + next, + play, + pause, + edit, + save, + clear, + delete, + remove, + add, + cancel, + accept, + more, + redo, + undo, + home, + up, + forward, + right, + back, + left, + favorite, + camera, + settings, + video, + sync, + download, + mail, + find, + help, + upload, + emoji, + twopage, + leavechat, + mailforward, + clock, + send, + crop, + rotatecamera, + people, + closepane, + openpane, + world, + flag, + previewlink, + globe, + trim, + attachcamera, + zoomin, + bookmarks, + document, + protecteddocument, + page, + bullets, + comment, + mail2, + contactinfo, + hangup, + viewall, + mappin, + phone, + videochat, + switch, + contact, + rename, + pin, + musicinfo, + go, + keyboard, + dockleft, + dockright, + dockbottom, + remote, + refresh, + rotate, + shuffle, + list, + shop, + selectall, + orientation, + import, + importall, + browsephotos, + webcam, + pictures, + savelocal, + caption, + stop, + showresults, + volume, + repair, + message, + page2, + calendarday, + calendarweek, + calendar, + characters, + mailreplyall, + read, + link, + accounts, + showbcc, + hidebcc, + cut, + attach, + paste, + filter, + copy, + emoji2, + important, + mailreply, + slideshow, + sort, + manage, + allapps, + disconnectdrive, + mapdrive, + newwindow, + openwith, + contactpresence, + priority, + uploadskydrive, + gototoday, + font, + fontcolor, + contact2, + folder, + audio, + placeholder, + view, + setlockscreen, + settile, + cc, + stopslideshow, + permissions, + highlight, + disableupdates, + unfavorite, + unpin, + openlocal, + mute, + italic, + underline, + bold, + movetofolder, + likedislike, + dislike, + like, + alignright, + aligncenter, + alignleft, + zoom, + zoomout, + openfile, + otheruser, + admin, + street, + map, + clearselection, + fontdecrease, + fontincrease, + fontsize, + cellphone, + reshare, + tag, + repeatone, + repeatall, + outlinestar, + solidstar, + calculator, + directions, + target, + library, + phonebook, + memo, + microphone, + postupdate, + backtowindow, + fullscreen, + newfolder, + calendarreply, + unsyncfolder, + reporthacked, + syncfolder, + blockcontact, + switchapps, + addfriend, + touchpointer, + gotostart, + zerobars, + onebar, + twobars, + threebars, + fourbars, + scan, + preview + } + + /** + * Indicates whether the IListDataAdapter was able to provide a count. + **/ + enum CountResult { + /** + * Indicates no count is available. + **/ + unknown + } + + /** + * Indicates that the IListDataAdapter was unable to provide a count. + **/ + enum CountError { + /** + * An attempt to count items timed out. + **/ + noResponse + } + + /** + * Describes the status of an IListDataSource. + **/ + enum DataSourceStatus { + /** + * The IListDataSource is ready. + **/ + ready, + /** + * The IListDataSource is still loading. + **/ + waiting, + /** + * The IListDataSource failed to load. + **/ + failure + } + + /** + * Specifies the type of error that occurred during an edit operation on a IListDataSource or an IListDataAdapter. + **/ + enum EditError { + /** + * The edit operation timed out. + **/ + noResponse, + /** + * The data source cannot be written to. + **/ + notPermitted, + /** + * The item has changed. + **/ + noLongerMeaningful + } + + /** + * Specifies the type of error encountered when retrieving items from an IListDataAdapter. + **/ + enum FetchError { + /** + * The fetch operation timed out. + **/ + noResponse, + /** + * The specified item could not be located. + **/ + doesNotExist + } + + /** + * Specifies how group headers in a ListView respond to the tap interaction. + **/ + enum GroupHeaderTapBehavior { + /** + * The group is invoked. + **/ + invoke, + /** + * Nothing happens. + **/ + none + } + + /** + * Specifies the position of group headers relative to their items in a ListView. + **/ + enum HeaderPosition { + /** + * Group headers appear to the left of items. + **/ + left, + /** + * Group headers appear above items. + **/ + top + } + + /** + * Specifies that type of animation for which a contentanimating event was raised. + **/ + enum ListViewAnimationType { + /** + * The animation plays when the ListView is first displayed. + **/ + entrance, + /** + * The animation plays when the ListView is changing its content. + **/ + contentTransition + } + + /** + * Describes the type of object in a ListView. + **/ + enum ObjectType { + /** + * The object is a group header in the list. + **/ + groupHeader, + /** + * The object is an item in the list. + **/ + item + } + + /** + * Specifies the orientation of a control. + **/ + enum Orientation { + /** + * A horizontal layout. + **/ + horizontal, + /** + * A vertical layout. + **/ + vertical + } + + /** + * Specifies the selection mode of a ListView. + **/ + enum SelectionMode { + /** + * Items cannot be selected. + **/ + none, + /** + * A single item may be selected. + **/ + single, + /** + * Multiple items may be selected. Clicking additional items adds them to the selection. + **/ + multi + } + + /** + * Specifies whether elements are selected when the user performs a swipe interaction. + **/ + enum SwipeBehavior { + /** + * The swipe interaction selects the elements touched by the swipe. + **/ + select, + /** + * The swipe interaction does not change which elements are selected. + **/ + none + } + + /** + * Specifies how items in a ListView respond to the tap interaction. + **/ + enum TapBehavior { + /** + * The item is selected and invoked. + **/ + directSelect, + /** + * The item is selected if was not already selected, and its deselected if it was already selected. + **/ + toggleSelect, + /** + * The item is invoked but not selected. + **/ + invokeOnly, + /** + * Nothing happens. + **/ + none + } + + //#endregion Enumerations + + //#region Interfaces + + /** + * Contains items that were requested from an IListDataAdapter and provides some information about those items. + **/ + interface IFetchResult { + //#region Properties + + /** + * Gets or sets the index of the requested item in the IListDataAdapter object's data source. + **/ + absoluteIndex: number; + + /** + * Gets or sets a value that indicates whether this IFetchResult contains the last items at the end of the IListDataAdapter object's data source. + **/ + atEnd: boolean; + + /** + * Gets or sets a value that indicates whether this IFetchResult contains the first items at the beginning of the IListDataAdapter object's data source. + **/ + atStart: boolean; + + /** + * Gets or sets the items returned by the fetch operation. + **/ + items: T[]; + + /** + * Gets or sets the location of the requested item within the items array. + **/ + offset: number; + + /** + * Gets or sets the number of items in the IListDataAdapter object's underlying data source. + **/ + totalCount: number; + + //#endregion Properties + + } + + /** + * Represents an item in a list. + **/ + interface IItem { + //#region Properties + + /** + * Gets or sets the item's data. + **/ + data: T; + + /** + * Gets the group key for the item. This property is only available for items that belong to a grouped data source. + **/ + groupKey: string; + + /** + * Gets the temporary ID of the item. + **/ + handle: string; + + /** + * Gets the item's index in the IListDataSource. + **/ + index: number; + + /** + * Gets or sets the key the identifies the item. + **/ + key: string; + + //#endregion Properties + + } + + /** + * Provides a mechanism for retrieving IItem objects asynchronously. + **/ + interface IItemPromise { + //#region Events + + /** + * Occurs when there is an error in processing. + * @param eventInfo An object that contains information about the event. + **/ + onerror(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). + **/ + cancel(): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + **/ + done(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): void; + + /** + * Stops change notification tracking for the IItem that fulfills this IItemPromise. + **/ + release(): void; + + /** + * Begins change notification tracking for the IItem that fulfills this IItemPromise. + **/ + retain(): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function becomes the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the complete or error function. + **/ + then(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): IItemPromise; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the temporary ID of the IItem that fulfills this promise. + **/ + handle: string; + + /** + * Gets or sets the index of the IItem contained by this IItemPromise. + **/ + index: number; + + //#endregion Properties + + } + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. Represents a layout for the ListView. + **/ + interface ILayout { + //#region Methods + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param beginScrollPosition The first visible pixel in the ListView. For horizontal layouts, this is the x-coordinate of the pixel. For vertical layouts, this is the y-coordinate. + * @param wholeItem true if the item must be completely visible; otherwise, false if its ok for the item to be partially visible. Promise. + * @returns A Promise for the index of the first visible item at the specified point. + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param endScrollPosition The last visible pixel in the ListView. For horizontal layouts, this is the x-coordinate of the pixel. For vertical layouts, this is the y-coordinate. + * @param wholeItem true if the item must be completely visible; otherwise, false if its ok for the item to be partially visible. Promise. + * @returns A Promise for the index of the last visible item at the specified point. + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @returns A object that has these properties: animationPromise, newEndIndex. + **/ + endLayout(): any; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param itemIndex The index of the item. + * @returns A Promise that returns an object with these properties: left, top, contentWidth, contentHeight, totalWidth, totalHeight. + **/ + getItemPosition(itemIndex: number): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param itemIndex The data source index of the current item. + * @param element The element for the current item. + * @param keyPressed The key that was pressed. This function must check for the arrow keys (leftArrow, upArrow, rightArrow, downArrow), pageDown, and pageUp and determine which item the user navigated to. + * @returns A Promise that contains the index of the next item (This item becomes the current item). + **/ + getKeyboardNavigatedItem(itemIndex: number, element: HTMLElement, keyPressed: WinJS.Utilities.Key): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @returns A Promise that returns an object that has these properties: beginScrollPosition, endScrollPosition. + **/ + getScrollBarRange(): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param x The x-coordinate to test. + * @param y The y-coordinate to test. + **/ + hitTest(x: number, y: number): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param elements The elements that represent the items that were added. + **/ + itemsAdded(elements: HTMLElement[]): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + **/ + itemsMoved(): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param elements The elements that represent the items that were removed. + **/ + itemsRemoved(elements: HTMLElement[]): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param groupIndex The index of the group in the group data source. + * @param element The element to render for the group header. + **/ + layoutHeader(groupIndex: number, element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param itemIndex The index of the item in the data source. + * @param element The element to render for the item. + **/ + layoutItem(itemIndex: number, element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param element The element that represents a header in the data source. + **/ + prepareHeader(element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param element An element that represents an item in the data source. + **/ + prepareItem(element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param element The element being released. + **/ + releaseItem(element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + **/ + reset(): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param site The layout site for the layout. You can use this object to query the hosting ListView for info you might need to lay out items. + **/ + setSite(site: ILayoutSite): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param beginScrollPosition The starting pixel of the area to which the items are rendered. + * @param endScrollPosition The last pixel of the area to which the items are rendered. + * @param count The upper bound of the number of items to render. + * @returns A Promise that returns an object that has these properties: beginIndex, endIndex. + **/ + startLayout(beginScrollPosition: number, endScrollPosition: number, count: number): Promise; + + //#endregion Methods + + //#region Properties + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + **/ + horizontal: boolean; + + //#endregion Properties + + } + + /** + * Represents a layout for the ListView. + **/ + interface ILayout2 { + //#region Methods + + /** + * Called when the ListView finishes a drag operation. + **/ + dragLeave(): void; + + /** + * Called when the ListView initiates a drag operation. + * @param x The x-coordinate of the drag. + * @param y The y-coordinate of the drag. + * @param dragInfo An object that indicates whether the item is selected. + **/ + dragOver(x: number, y: number, dragInfo: number): void; + + /** + * Called when the ListView requests that the ILayout2 execute animations. + **/ + executeAnimations(): void; + + /** + * Determines the next item to receive keyboard focus. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + + /** + * Gets the item at the specified hit-test coordinates. These coordinates are absolute coordinates (they are not relative to the layout's content area). + * @param x The x-coordinate to test for. + * @param y The y-coordinate to test for. + * @returns An object that describes the item at the hit test coordinates. It has these properties: type, index. + **/ + hitTest(x: number, y: number): any; + + /** + * Sets the rendering site and specifies whether the layout supports groups. This method is called by the ListView to initialize the layout. + * @param site The rendering site for the layout. + * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. + **/ + initialize(site: ILayoutSite2, groupsEnabled: boolean): void; + + /** + * Retrieves the indexes of the items in the specified pixel range. + * @param firstPixel The first pixel the range of items falls between. + * @param lastPixel The last pixel the range of items falls between. + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * Performs a layout pass. + * @param tree A structure representing the layout tree that is returned from the ListView. + * @param changedRange An object that lists the index of the first item in the changed item range. This object has these properties: startIndex. + * @param modifiedItems An object that contains the old and new indexes of the items that have been modified in the tree. + * @param modifiedGroups An object that contains the old and new indexes of the group elements that have been modified in the tree. + * @returns A Promise that executes after layout is complete, or an object that contains two Promise objects: realizedRangeComplete, layoutComplete. + **/ + layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): any; + + /** + * Called when the ListView requests that the ILayout2 set up animations. + **/ + setupAnimations(): void; + + /** + * Releases resources that were obtained during the call to initialize. + **/ + uninitialize(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the orientation of the layout. + **/ + orientation: any; + + //#endregion Properties + + } + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayoutSite2 interface. Represents a rendering site for an ILayout. + **/ + interface ILayoutSite { + //#region Properties + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + animationsDisabled: boolean; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + itemSurface: HTMLElement; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + rtl: boolean; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + scrollbarPos: number; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + surface: HTMLElement; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + viewport: HTMLElement; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + viewportSize: any; + + //#endregion Properties + + } + + /** + * Represents a rendering site for an ILayout2. + **/ + interface ILayoutSite2 { + //#region Properties + + /** + * Gets the number of groups in the site. + **/ + groupCount: number; + + /** + * Gets the number of items in the site. + **/ + itemCount: Promise; + + /** + * Gets the pixel range of the realization area. + **/ + realizedRange: any; + + /** + * Gets the tree for use by an object that implements the ILayout2 interface. + **/ + tree: any; + + /** + * Gets the pixel range of visible items in the site. + **/ + visibleRange: any; + + //#endregion Properties + + } + + /** + * Retrieves items from a IListDataSource, enumerates the contents of a IListDataSource, and can optionally register for change notifications. + **/ + interface IListBinding { + //#region Methods + + /** + * Retrieves the current item. + * @returns An IItemPromise that contains the current item. If the cursor has moved past the start or end of the list, the promise completes with a value of null. If the current item has been moved or deleted, the promise returns an error. + **/ + current(): IItemPromise>; + + /** + * Gets the first item from the IListDataSource and makes it the current item. + * @returns An IItemPromise that contains the requested IItem. If the list is empty, the promise completes with a value of null. + **/ + first(): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified description and makes it the current item. + * @param description A domain-specific description, to be interpreted by the IListDataAdapter, that identifies the item to retrieve. + * @returns An IItemPromise that contains the requested IItem object. If the item wasn't found, the promise completes with a value of null. + **/ + fromDescription(description: string): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified index and makes it the current item. + * @param index A value greater than or equal to 0 that is the index of the item to retrieve. + * @returns An IItemPromise that contains the requested IItem. If the item wasn't found, the promise completes with a value of null. + **/ + fromIndex(index: number): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified key and makes it the current item. + * @param key The key that identifies the item to retrieve. This value must be a non-empty string. + * @param hints Domain-specific information that provides additional information to the IListDataAdapter to improve retrieval time. + * @returns An IItemPromise that contains the requested IItem. If they item couldn't be found, the promise completes with a value of null. + **/ + fromKey(key: string, hints?: any): IItemPromise>; + + /** + * Makes the specified IItem or IItemPromise the current item. + * @param item The IItem or IItemPromise that will become the current item. + * @returns An IItemPromise that contains the specified item, if it exists. If the specified item is not in the list, the promise completes with a value of null. + **/ + jumpToItem(item: IItem): IItemPromise>; + + /** + * Retrieves the last item in the IListDataSource and makes it the current item. + * @returns An IItemPromise that contains the requested IItem. f the list is empty, the promise completes with a value of null. + **/ + last(): IItemPromise>; + + /** + * Retrieves the item after the current item and makes it the current item. + * @returns An IItemPromise that contains the item after the current item. If the cursor moves past the end of the list, the promise completes with a value of null. + **/ + next(): IItemPromise>; + + /** + * Retrieves the item before the current item and makes it the current item. + * @returns An IItemPromise that contains the item before the current item. If the cursor moves past the start of the list, the promise completes with a value of null. + **/ + previous(): IItemPromise>; + + /** + * Releases resources, stops notifications, and cancels outstanding promises for all tracked items returned by this IListBinding. + **/ + release(): void; + + /** + * Creates a request to stop change notifications for the specified item. The change notifications stop when the number of releaseItem calls matches the number of IIItemPromise.retain calls. + * @param item The IItem or IItemPromise that should stop receiving notifications. + **/ + releaseItem(item: IItem): void; + + //#endregion Methods + + } + + /** + * Accesses data for an IListDataSource. + **/ + interface IListDataAdapter { + //#region Methods + + /** + * Overwrites the data of the specified item. + * @param key The key of the item to overwrite. + * @param newData The new data for the item. + * @param indexHint The index of the item, if known. + * @returns A Promise that returns null or undefined when the operation completes. + **/ + change(key: string, newData: T, indexHint: number): Promise; + + /** + * Gets the number of items in the IListDataAdapter object's data source. + * @returns A Promise that contains the number of items the IListDataAdapter contains, or an approximate value if the actual number is unknown. + **/ + getCount(): Promise; + + /** + * Inserts the specified data after the specified item. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @param previousKey The key of an item in the IListDataAdapter object's data source. The new data will be inserted after this item. + * @param previousIndexHint The index of the item to insert the new data after, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAfter(key: string, data: T, previousKey: string, previousIndexHint: number): Promise>; + + /** + * Adds the specified key and data to the end of the IListDataAdapter object's data source. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtEnd(key: string, data: T): Promise>; + + /** + * Adds the specified key and data to the beginning of the IListDataAdapter object's data source. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtStart(key: string, data: T): Promise>; + + /** + * Inserts the specified data before the specified item. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @param nextKey The key of an item in the IListDataAdapter object's data source. The new data will be inserted before this item. + * @param nextIndexHint The index of the item to insert the new data before, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertBefore(key: string, data: T, nextKey: string, nextIndexHint: number): Promise>; + + /** + * Retrieves the item that matches the specified description and also retrieves the specified number of items before and after the matched item. + * @param description A description of the item to locate. + * @param countBefore The number of items before the matched item to retrieve. + * @param countAfter The number of items after the matched item to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromDescription(description: string, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the specified number of items from the end of the IListDataAdapter object's data source. + * @param count The number of items to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromEnd(count: number): Promise>; + + /** + * Retrieves the item at the specified index and also retrieves the specified number of items before and after the selected item. + * @param index The index of the item to retrieve. + * @param countBefore The number of items to retrieve from before the selected item. + * @param countAfter The number of items to retrieve from after the selected item. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromIndex(index: number, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the item that has the specified key and also retrieves the specified number of items before and after the selected item. + * @param key The key of the item to retrieve. + * @param countBefore The number of items to retrieve from before the selected item. + * @param countAfter The number of items to retrieve from after the selected item. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromKey(key: string, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the specified number of items from the beginning of the IListDataAdapter object's data source. + * @param count The number of items to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromStart(count: number): Promise>; + + /** + * Returns a string representation of the specified item that can be used for comparisons. + * @param item The item for which to generate a signature. + * @returns The signature representation of the specified item. + **/ + itemSignature(item: IItem): string; + + /** + * Moves the specified item to just after another item. + * @param key A key of the item to move. + * @param previousKey The key of another item. The item to move will be moved to just after this item. + * @param indexHint The index of the item to move, if known. + * @param previousIndexHint The index to move the item after, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveAfter(key: string, previousKey: any, indexHint: string, previousIndexHint: number): Promise>; + + /** + * Moves the specified item to just before another item. + * @param key A key of the item to move. + * @param nextKey The key of another item. The item to move will be moved to just before this item. + * @param indexHint The index of the item to move, if known. + * @param nextIndexHint The index to move the item before, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveBefore(key: string, nextKey: any, indexHint: string, nextIndexHint: number): Promise>; + + /** + * Moves the specified item to the end of the IListDataAdapter object's data source. + * @param key The key for the item to move. + * @param indexHint The index of the item to move, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveToEnd(key: string, indexHint: number): Promise>; + + /** + * Moves the specified item to the beginning of the IListDataAdapter object's data source. + * @param key The key for the item to move. + * @param indexHint The index of the item to move, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveToStart(key: string, indexHint: number): Promise>; + + /** + * Removes the specified item from the IListDataAdapter object's data source. + * @param key The key of the item to remove. + * @param data The new data for the item. + * @param indexHint The index of the item. + * @returns A Promise that returns null or undefined when the operation completes. + **/ + remove(key: string, data: T, indexHint: number): Promise; + + /** + * Registers a notification handler. The IListDataAdapter uses the handler to notify listening objects when its data changes. + * @param notificationHandler The notification handler that the IListDataAdapter will use to provide change notifications. . + **/ + setNotificationHandler(notificationHandler: IListDataNotificationHandler): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether to use an object's identity to determine if an item has changed. + **/ + compareByIdentity: boolean; + + //#endregion Properties + + } + + /** + * Notifies clients when an IListDataAdapter object's data changes. + **/ + interface IListDataNotificationHandler { + //#region Methods + + /** + * Indicates the start of a notification batch. Objects that are listening for notifications should defer making updates until endNotifications is called. + **/ + beginNotifications(): void; + + /** + * Raises a notification that an item in the IListDataAdapter object's data source has changed. + * @param item The item that changed. + **/ + changed(item: IItem): void; + + /** + * Indicates the end of a notification batch. When the beginNotifications method is called, objects listening for notifications should defer making updates until endNotifications is called. + **/ + endNotifications(): void; + + /** + * Raises a notification that an item has been added to the IListDataAdapter object's data source. + * @param newItem The new item added to the IListDataAdapter object's data source. + * @param previousKey The key of the item that now precedes the new item, or null if the item was inserted at the start of the list. If nextKey is provided, this parameter may be null. + * @param nextKey The key of the item that now follows the new item, or null if the item was inserted at the end of the list. If previousKey is provided, this parameter may be null. + * @param index The index of the new item. + **/ + inserted(newItem: IItem, previousKey: string, nextKey: string, index?: number): void; + + /** + * Indicates that all previous data obtained from the IListDataAdapter is invalid and should be refreshed. + * @returns A Promise that completes when the data has been completely refreshed and all change notifications have been sent. + **/ + invalidateAll(): Promise; + + /** + * Raises a notification that an item was moved within the IListDataAdapter object's data source. + * @param item The item that was moved. + * @param previousKey The key of the item that now precedes the new item, or null if the item was moved to the beginning of the list. If nextKey is provided, this parameter may be null. + * @param nextKey The key of the item that now follows the new item, or null if the item was moved to the end of the list. If previousKey is provided, this parameter may be null. + * @param oldIndex The item's original index. + * @param newIndex The item's new index. + **/ + moved(item: IItem, previousKey: string, nextKey: string, oldIndex?: number, newIndex?: number): void; + + /** + * Reloads data from the IListDataAdapter. + **/ + reload(): void; + + /** + * Raises a notification that an item was removed from the IListDataAdapter object's data source. + * @param key The key of the item that was removed. + * @param index The index of the item that was removed. + **/ + removed(key: string, index?: number): void; + + //#endregion Methods + + } + + /** + * Provides access to a data source and enables you to bind, change, add, remove, and move items in that data source. + **/ + interface IListDataSource { + //#region Events + + /** + * Occurs when the status of the IListDataSource changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: status. + **/ + statuschanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Notifies the IListDataSource that a sequence of edits is about to begin. The IListDataSource will defer notifications until endEdits is called. + **/ + beginEdits(): void; + + /** + * Overwrites the data of the specified item. + * @param key The key for the item to replace. + * @param newData The new data for the item. + * @returns A Promise that contains the IItem that was updated or an EditError if an error was encountered. + **/ + change(key: string, newData: T): Promise>; + + /** + * Creates an IListBinding that can retrieve items from the IListDataSource, enumerate the contents of the IListDataSource object's data, and optionally register for change notifications. + * @param notificationHandler Enables the IListBinding to register for change notifications for individual items obtained from the IListDataSource. If you omit this parameter, change notifications won't be available. + * @returns The new IListBinding. + **/ + createListBinding(notificationHandler?: IListNotificationHandler): IListBinding; + + /** + * Notifies the IListDataSource that the batch of edits that began with the last beginEdits call has completed. The IListDataSource will submit notifications for any changes that occurred between the beginEdits and endEdits calls as a batch and resume normal change notifications. + **/ + endEdits(): void; + + /** + * Retrieves the number of items in the data source. + * @returns A Promise that provides a Number that is the number of items in the data source. + **/ + getCount(): Promise; + + /** + * Inserts a new item after another item. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @param previousKey The key for an item in the data source. The new item will be added after this item. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAfter(key: string, data: T, previousKey: string): Promise>; + + /** + * Adds an item to the end of the data source. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtEnd(key: string, data: T): Promise>; + + /** + * Adds an item to the beginning of the data source. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtStart(key: string, data: T): Promise>; + + /** + * Inserts an item before another item. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @param nextKey The key of an item in the data source. The new item will be inserted before this item. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertBefore(key: string, data: T, nextKey: string): Promise>; + + /** + * Indicates that all previous data obtained from the IListDataAdapter is invalid and should be refreshed. + * @returns A Promise that completes when the data has been completely refreshed and all notifications have been sent. + **/ + invalidateAll(): Promise; + + /** + * Retrieves the item that has the specified description. + * @param description Domain-specific information, to be interpreted by the IListDataAdapter, that describes the item to retrieve. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item wasn't found, the promise completes with a value of null. + **/ + itemFromDescription(description: any): Promise>; + + /** + * Retrieves the item at the specified index. + * @param index A value that is greater than or equal to zero that is the index of the item to retrieve. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item wasn't found, the promise completes with a value of null. + **/ + itemFromIndex(index: number): Promise>; + + /** + * Retrieves the item with the specified key. + * @param key The key of the item to retrieve. It must be a non-empty string. + * @param description Domain-specific information that IListDataAdapter can use to improve the retrieval time. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item was not found, the promise completes with a null value. + **/ + itemFromKey(key: string, description?: any): Promise>; + + /** + * Moves an item to just after another item. + * @param key The key that identifies the item to move. + * @param previousKey The key of another item in the data source. The item specified by the key parameter will be moved after this item. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveAfter(key: string, previousKey: string): Promise>; + + /** + * Moves an item before another item. + * @param key The key that identifies the item to move. + * @param nextKey The key of another item in the data source. The item specified by the key parameter will be moved before this item. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveBefore(key: string, nextKey: string): Promise>; + + /** + * Moves an item to the end of the data source. + * @param key The key that identifies the item to move. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveToEnd(key: string): Promise>; + + /** + * Moves the specified item to the beginning of the data source. + * @param key The key that identifies the item to move. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveToStart(key: string): Promise>; + + /** + * Removes the specified item from the data source. + * @param key The key that identifies the item to remove. + * @returns A Promise that contains nothing if the operation was successful or an EditError if an error was encountered. + **/ + remove(key: string): Promise>; + + //#endregion Methods + + } + + /** + * Used by an IListBinding to provide change notifications when items in a IListDataSource change. + **/ + interface IListNotificationHandler { + //#region Methods + + /** + * Indicates the start of a notification batch. Objects that are listening for notifications should defer making updates until endNotifications is called. + **/ + beginNotifications(): void; + + /** + * Indicates that an item changed. + * @param newItem The updated item. + * @param oldItem The original item. + **/ + changed(newItem: IItem, oldItem: IItem): void; + + /** + * Indicates that the number of items in the IListDataSource has changed. + * @param newCount The updated count. + * @param oldCount The original count. + **/ + countChanged(newCount: number, oldCount: number): void; + + /** + * Indicates the end of a notification batch. When the beginNotifications method is called, objects listening for notifications should defer making updates until endNotifications is called. + **/ + endNotifications(): void; + + /** + * Indicates that the index of an item changed. + * @param handle The temporary ID of the item. + * @param newIndex The new index. + * @param oldIndex The original index. + **/ + indexChanged(handle: string, newIndex: number, oldIndex: number): void; + + /** + * Indicates that an item was added to the IListDataSource. + * @param itemPromise A promise for the new IItem. + * @param previousHandle The temporary ID of the item that precedes the new item. + * @param nextHandle The temporary ID of the item that follows the new item. + **/ + inserted(itemPromise: IItemPromise, previousHandle: string, nextHandle: string): void; + + /** + * Indicates that an IItemPromise was fulfilled and that the item is now available. + * @param item The fulfilled item. + **/ + itemAvailable(item: IItem): void; + + /** + * Indicates that an item was moved. + * @param item A promise for the IItem that was moved. + * @param previousHandle The temporary ID of the item that now precedes the moved item. + * @param nextHandle The temporary ID of the item that now follows the moved item. + **/ + moved(item: IItemPromise, previousHandle: string, nextHandle: string): void; + + /** + * Indicates that an item was removed. + * @param handle The temporary ID of the item that was removed. + * @param mirage true if the item never actually existed; false if the item was actually present in the IListDataSource. + **/ + removed(handle: string, mirage: boolean): void; + + //#endregion Methods + + } /** * Used by ListView's currentItem API **/ interface IListViewItem { /** - * Gets or sets index of the ListView item. - **/ + * Gets or sets index of the ListView item. + **/ index?: number; /** - * Gets or sets key of the ListView item. - **/ + * Gets or sets key of the ListView item. + **/ key?: string; /** - * Gets or sets whether the ListView item is focused. - **/ + * Gets or sets whether the ListView item is focused. + **/ hasFocus?: boolean; /** - * Gets or sets whether the ListView item is focused and is showing its focus visual. - **/ + * Gets or sets whether the ListView item is focused and is showing its focus visual. + **/ showFocus?: boolean; } - /** - * Represents a selection of ListView items. - **/ - interface ISelection { - //#region Methods - - /** - * Adds one or more items to the selection. - * @param items The indexes or keys of the items to add. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. - * @returns A Promise that is fulfilled when the operation completes. - **/ - add(items: any): Promise; - - /** - * Clears the selection. - * @returns A Promise that is fulfilled when the clear operation completes. - **/ - clear(): Promise; - - /** - * Returns the number of items in the selection. - * @returns The number of items in the selection. - **/ - count(): number; - - /** - * Returns a list of the indexes for the items in the selection. - * @returns The list of indexes for the items in the selection as an array of Number objects. - **/ - getIndices(): number[]; - - /** - * Returns an array that contains the items in the selection. - * @returns A Promise that contains an array of the requested IItem objects. - **/ - getItems(): Promise[]>; - - /** - * Gets an array of the index ranges for the selected items. - * @returns An array that contains an ISelectionRange object for each index range in the selection. - **/ - getRanges(): ISelectionRange[]; - - /** - * Returns a value that indicates whether the selection contains every item in the data source. - * @returns true if the selection contains every item in the data source; otherwise, false. - **/ - isEverything(): boolean; - - /** - * Removes the specified items from the selection. - * @param items The indexes or keys of the items to remove. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. - * @returns A Promise that is fulfilled when the operation completes. - **/ - remove(items: any): Promise; - - /** - * Adds all the items in the ListView to the selection. - **/ - selectAll(): void; - - /** - * Clears the current selection and replaces it with the specified items. - * @param items The indexes or keys of the items that make up the selection. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. - * @returns A Promise that is fulfilled when the operation completes. - **/ - set(items: any): Promise; - - //#endregion Methods - - } - - /** - * Represents a range of indexes or keys in an ISelection. - **/ - interface ISelectionRange { - //#region Properties - - /** - * Gets or sets the index of the first item in the range. - **/ - firstIndex: number; - - /** - * Gets or sets the key of the first item in the range. - **/ - firstKey: any; - - /** - * Gets or sets the index of the last item in the range. - **/ - lastIndex: number; - - /** - * Gets or sets of the key of the last item in the range. - **/ - lastKey: any; - - //#endregion Properties - - } - - /** - * Supports semantic zoom functionality by exposing a control as either the zoomed in or the zoomed out view of the SemanticZoom control. - **/ - interface IZoomableView { - //#region Methods - - /** - * Initiates semantic zoom on the custom control. - **/ - beginZoom(): void; - - /** - * Initializes the semantic zoom state for the custom control. - * @param isZoomedOut True if this is the zoomed out view; otherwise false. - * @param isCurrentView True if this is the current view; otherwise false. - * @param triggerZoom The function that manages semantic zoom behavior. Triggers a zoom in or zoom out if the control is the visible control. - * @param prefetchedPages The number of pages of content to pre-fetch for zooming. This value is dependent on the size of the semantic zoom container. More content can be displayed based on the zoom factor and the size of the container. - **/ - configureForZoom(isZoomedOut: boolean, isCurrentView: boolean, triggerZoom: Function, prefetchedPages: number): void; - - /** - * Terminates semantic zoom on the zoomed in or zoomed out child of the custom control. - * @param isCurrentView True if the control is the visible control; otherwise false. - **/ - endZoom(isCurrentView: boolean): void; - - /** - * Retrieves the current item of the zoomed in or zoomed out child of the custom control. - * @returns An object that represents the selected item. This return value must be a Promise for the following: item, position. - **/ - getCurrentItem(): Promise<{ item: T; position: Utilities.IPosition }>; - - /** - * Retrieves the panning axis of the zoomed-in or zoomed-out child of the custom control. - * @returns Identifies the panning axis of the child control. Implementation specific. - **/ - getPanAxis(): string; - - /** - * Manages pointer input for the custom control. - * @param pointerId The ID of the pointer. - **/ - handlePointer(pointerId: string): void; - - /** - * Positions the specified item within the viewport of the child control when panning or zooming begins. - * @param item The object to position within the viewport of the child control. item can be a number, a string, or an object with any number of properties. - * @param position An object that contains the position data of the item relative to the child control. position must be an object with four number properties: left, top, width, and height. These values specify a rectangle that is typically the bounding box of the current item, though the details are up to the control. The units of the position must be in pixels. And the coordinates must be relative to the top-left of the control viewport (which should occupy the same area as the semantic zoom viewport), except when in RTL mode. In RTL mode, return coordinates relative to the top-right off the control viewport. The rectangle is transformed from the coordinate system of one control to that of the other. - **/ - positionItem(item: T, position: Utilities.IPosition): void; - - /** - * Selects the item closest to the specified screen coordinates. - * @param x The x-coordinate in DIPs relative to the upper-left corner of the SemanticZoom viewport. - * @param y The y-coordinate in DIPs relative to the upper-left corner of the SemanticZoom viewport.. - **/ - setCurrentItem(x: number, y: number): void; - - //#endregion Methods - - } - - //#endregion Interfaces - - //#region Objects - - /** - * Represents an application toolbar for displaying commands. - **/ - class AppBar { - //#region Constructors - - /** - * Creates a new AppBar object. - * @constructor - * @param element The DOM element that will host the control. - * @param options The set of properties and values to apply to the new AppBar. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Occurs immediately after the AppBar is hidden. - * @param eventInfo An object that contains information about the event. - **/ - onafterhide(eventInfo: Event): void; - - /** - * Occurs after the AppBar is shown. - * @param eventInfo An object that contains information about the event. - **/ - onaftershow(eventInfo: Event): void; - - /** - * Occurs before the AppBar is hidden. - * @param eventInfo An object that contains information about the event. - **/ - onbeforehide(eventInfo: Event): void; - - /** - * Occurs before a hidden AppBar is shown. - * @param eventInfo An object that contains information about the event. - **/ - onbeforeshow(eventInfo: Event): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. - * @param listener The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this AppBar. Call this method when the AppBar is no longer needed. After calling this method, the AppBar becomes unusable. - **/ - dispose(): void; - - /** - * Returns the AppBarCommand object identified by id. - * @param id The element idenitifier (ID) of the command to be returned. - * @returns The command identified by id. If multiple commands have the same ID, returns an array of all the commands matching the ID. - **/ - getCommandById(id: string): AppBarCommand; - - /** - * Hides the AppBar. - **/ - hide(): void; - - /** - * Hides the specified commands of the AppBar. - * @param commands The commands to hide. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. - * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. - **/ - hideCommands(commands: any[], immediate?: boolean): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. - * @param listener The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Shows the AppBar if it is not disabled. - **/ - show(): void; - - /** - * Shows the specified commands of the AppBar. - * @param commands The commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. - * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. - **/ - showCommands(commands: any[], immediate?: boolean): void; - - /** - * Shows the specified commands of the AppBar while hiding all other commands. - * @param commands The commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. - * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. - **/ - showOnlyCommands(commands: any[], immediate?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Sets the AppBarCommand objects that appear in the app bar. - **/ - commands: AppBarCommand[]; - - /** - * Gets or sets a value that indicates whether the AppBar is disabled. - **/ - disabled: boolean; - - /** - * Gets the DOM element that hosts the AppBar. - **/ - element: HTMLElement; - - /** - * Gets a value that indicates whether the AppBar is hidden or in the process of becoming hidden. - **/ - hidden: boolean; - - /** - * Gets or sets the layout of the app bar contents. - **/ - layout: string; - - /** - * Gets or sets a value that specifies whether the AppBar appears at the top or bottom of the main view. - **/ - placement: string; - - /** - * Gets or sets a value that indicates whether the AppBar is sticky (won't light dismiss). If not sticky, the app bar dismisses normally when the user touches outside of the appbar. - **/ - sticky: boolean; - - //#endregion Properties - - } - - /** - * Represents a command to be displayed in an app bar. - **/ - class AppBarCommand { - //#region Constructors - - /** - * Creates a new AppBarCommand object. - * @constructor - * @param element The DOM element that will host the control. - * @param options The set of properties and values to apply to the new AppBarCommand. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param type The event type to register. - * @param listener The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Releases resources held by this AppBarCommand. Call this method when the AppBarCommand is no longer needed. After calling this method, the AppBarCommand becomes unusable. - **/ - dispose(): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. - * @param listener The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(type: string, listener: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets a value that indicates whether the AppBarCommand is disabled. - **/ - disabled: boolean; - - /** - * Gets the DOM element that hosts the AppBarCommand. - **/ - element: HTMLElement; - - /** - * Adds an extra CSS class during construction. - **/ - extraClass: string; - - /** - * Gets or sets the HTMLElement with a 'content' type AppBarCommand that should receive focus whenever focus moves by the user pressing HOME or the arrow keys, from the previous AppBarCommand to this AppBarCommand. - **/ - firstElementFocus: HTMLElement; - - /** - * Gets or sets the Flyout object displayed by this command. The specified flyout is shown when the AppBarCommand's button is invoked. - **/ - flyout: Flyout; - - /** - * Gets or sets a value that indicates whether the AppBarCommand is hiding or in the process of becoming hidden. - **/ - hidden: boolean; - - /** - * Gets or sets the icon of the AppBarCommand. - **/ - icon: string; - - /** - * Gets the element identifier (ID) of the command. - **/ - id: string; - - /** - * Gets or sets the label of the command. - **/ - label: string; - - /** - * Gets or sets the HTMLElement with a 'content' type AppBarCommand that should receive focus whenever focus moves by the user pressing END or the arrow keys, from the previous AppBarCommand to this AppBarCommand. - **/ - lastElementFocus: HTMLElement; - - /** - * Gets or sets the function to be invoked when the command is clicked. - **/ - onclick: Function; - - /** - * Gets the section of the app bar that the command is in. - **/ - section: string; - - /** - * Gets or sets the selected state of a toggle button. - **/ - selected: boolean; - - /** - * Gets or sets the tooltip of the command. - **/ - tooltip: string; - - /** - * Gets the type of the command. - **/ - type: string; - - //#endregion Properties - - } - - /** - * Provides backwards navigation in the form of a button. - **/ - class BackButton { - //#region Constructors - - /** - * Creates a new BackButton. - * @constructor - * @param element The DOM element hosts the new BackButton. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this BackButton. Call this method when the BackButton is no longer needed. After calling this method, the BackButton becomes unusable. - **/ - dispose(): void; - - /** - * Checks the current navigation history and updates the value of the control's disabled attribute. - **/ - refresh(): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets the HTML element that hosts this BackButton. - **/ - element: HTMLElement; - - //#endregion Properties - - } - - /** - * Represents a layout for the ListView in which items are arranged in a grid and items can span multiple grid cells. - **/ - class CellSpanningLayout { - //#region Constructors - - /** - * Creates a new CellSpanningLayout. - * @constructor - * @param options An object that contains one or more property/value pairs to apply to the new CellSpanningLayout. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". - **/ - constructor(options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - dragLeave(): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - dragOver(): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - executeAnimations(): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param currentItem An object that describes the current item. It has these properties: index, type. - * @param pressedKey The key that was pressed. - * @returns An object that describes the next item that should receive focus. It has these properties: index, type. - **/ - getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param x The x-coordinate, or the horizontal position on the screen. - * @param y The y-coordinate, or the vertical position on the screen. - **/ - hitTest(x: number, y: number): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param site The rendering site for the layout. - * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. - **/ - initialize(site: ILayoutSite2, groupsEnabled: boolean): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param firstPixel The first pixel the range of items falls between. - * @param lastPixel The last pixel the range of items falls between. - **/ - itemsFromRange(firstPixel: number, lastPixel: number): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param tree - * @param changedRange - * @param modifiedItems - * @param modifiedGroups - **/ - layout(tree: ILayoutSite2, changedRange: any, modifiedItems: any, modifiedGroups: any): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - setupAnimations(): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - uninitialize(): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the position of group headers relative to their items. - **/ - groupHeaderPosition: WinJS.UI.HeaderPosition; - - /** - * Gets or sets a function that enables cell-spanning and establishes base cell dimensions. - **/ - groupInfo: Function; - - /** - * Gets or sets a function that returns the width and height of an item, as well as whether it should appear in a new column. Setting this function improves performance because the ListView can allocate space for an item without having to measure it first. - **/ - itemInfo: Function; - - /** - * Gets or set the maximum number of rows or columns, depending on the orientation, to display before content begins to wrap. - **/ - maximumRowsOrColumns: number; - - /** - * This API supports the Windows Library for JavaScript infrastructure and is not intended to be used directly from your code. - **/ - numberOfItemsPerItemsBlock: any; - - /** - * Gets the orientation of the CellSpanningLayout. For a CellSpanningLayout, this property always returns Orientation.horizontal. - **/ - orientation: WinJS.UI.Orientation; - - //#endregion Properties - - } - - /** - * Allows users to pick a date value. - **/ - class DatePicker { - //#region Constructors - - /** - * Initializes a new instance of the DatePicker control. - * @constructor - * @param element The DOM element associated with the DatePicker control. - * @param options The set of options to be applied initially to the DatePicker control. The options are the following: calendar, current, datePattern, disabled, maxYear, minYear, monthPattern, yearPattern. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Occurs when any of the controls are changed by the user. - * @param eventInfo An object that contains information about the event. - **/ - onchange(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Adds an event listener. - * @param type The type (name) of the event. - * @param listener The function that handles the event. - * @param capture If true, specifies that capture should be initiated, otherwise false. - **/ - addEventListener(type: string, listener: Function, capture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this DatePicker. Call this method when the DatePicker is no longer needed. After calling this method, the DatePicker becomes unusable. - **/ - dispose(): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - raiseEvent(type: string, eventProperties: any): boolean; - - /** - * Removes a listener for the specified event. - * @param type The name of the event for which to remove a listener. - * @param listener The listener. - * @param useCapture Optional. The same value that was passed to addEventListener for this listener. It may be omitted if it was omitted when calling addEventListener. - **/ - removeEventListener(type: string, listener: Function, useCapture?: any): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the calendar to use. - **/ - calendar: string; - - /** - * Gets or sets the current date of the DatePicker. You can use either a date string or a Date object to set this property. - **/ - current: Date; - - /** - * Gets or sets the display pattern for the date. The default date pattern is day.integer(2). You can change the date pattern by changing the number of integers displayed. - **/ - datePattern: string; - - /** - * Specifies whether the DatePicker is disabled. - **/ - disabled: boolean; - - /** - * Gets the DOM element for the DatePicker. - **/ - element: HTMLElement; - - /** - * Gets or sets the maximum Gregorian year available for picking. - **/ - maxYear: number; - - /** - * Gets or sets the minimum Gregorian year available for picking. - **/ - minYear: number; - - /** - * Gets or sets the display pattern for the month. The default month pattern is month.abbreviated. You can change the month pattern to the following values: month.full. The full name of the month. month.abbreviated(n). You can use abbreviated with or without specifying the number of letters in the abbreviation. If you do specify the number of letters, the actual length of the month name that appears may vary. month.solo.full. A representation of the month that is suitable for stand-alone display. You can also use month.solo.abbreviated(n). month.integer(n). You can use integer with or without specifying the number of integers. - **/ - monthPattern: string; - - /** - * Gets or sets the display pattern for the year. The default year pattern is year.full. You can change the year pattern to the following values: year.abbreviated(n). You can use abbreviated with or without specifying the number of letters in the abbreviation. - **/ - yearPattern: string; - - //#endregion Properties - - } - - /** - * Adds event-related methods to the control. - **/ - class DOMEventMixin { - //#region Methods - - /** - * Adds an event listener to the control. - * @param type The type (name) of the event. - * @param listener The listener to invoke when the event gets raised. - * @param useCapture true to initiate capture; otherwise, false. - **/ - addEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type, adding the specified additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Removes an event listener from the control. - * @param type The type (name) of the event. - * @param listener The listener to remove. - * @param useCapture true to initiate capture; otherwise, false. - **/ - removeEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Adds the set of declaratively specified options (properties and events) to the specified control. If the name of the options property begins with "on", the property value is a function and the control supports addEventListener. This method calls the addEventListener method on the control. - * @param control The control on which the properties and events are to be applied. - * @param options The set of options that are specified declaratively. - **/ - setOptions(control: any, options: any): void; - - //#endregion Methods - - } - - /** - * Displays a collection, such as a set of photos, one item at a time. - **/ - class FlipView { - //#region Constructors - - /** - * Creates a new FlipView. - * @constructor - * @param element The DOM element that hosts the control. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the pageselected event, add a property named "onpageselected" and set its value to the event handler. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Occurs when the datasource count changes. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: source. - **/ - ondatasourcecountchanged(eventInfo: Event): void; - - /** - * Raised when the FlipView flips to a page and its renderer function completes. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source. - **/ - onpagecompleted(eventInfo: CustomEvent): void; - - /** - * Raised when the FlipView flips to a page. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source. - **/ - onpageselected(eventInfo: CustomEvent): void; - - /** - * Occurs when an item becomes invisible or visible. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source, detail.visible. - **/ - onpagevisibilitychanged(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. For a list of events, see the FlipView object page. - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Returns the number of items in the FlipView control's itemDataSource. - * @returns A Promise that contains the number of items in the list or WinJS.UI.CountResult.unknown if the count is unavailable. - **/ - count(): Promise; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this FlipView. Call this method when the FlipView is no longer needed. After calling this method, the FlipView becomes unusable. - **/ - dispose(): void; - - /** - * Forces the FlipView to update its layout. Use this function when making the FlipView visible again after its style.display property had been set to "none". - **/ - forceLayout(): void; - - /** - * Navigates to the next page. - * @returns true if the FlipView begins navigating to the next page; false if the FlipView is already at the last item or is in the middle of another navigation animation. - **/ - next(): boolean; - - /** - * Navigates to the previous item. - * @returns true if the FlipView begins navigating to the previous page; nfalse if the FlipView is already at the first page or is in the middle of another navigation animation. - **/ - previous(): boolean; - - /** - * Unregisters an event handler for the specified event. - * @param eventName The name of the event. - * @param eventHandler The event handler function to remove. - * @param useCapture Set to true to unregister the event handler for the capturing phase; otherwise, set to false to unregister the event handler for the bubbling phase. - **/ - removeEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Sets custom animations for the FlipView to use when navigating between pages. - * @param animations An object that contains up to three fields, one for each navigation action: next, previous, and jump. Each of those fields must be a function with this signature: function (outgoingPage, incomingPage) Each function must return a WinJS.Promise that completes once the animations are finished. If a field is null or undefined, the FlipView reverts to its default animation for that action. - **/ - setCustomAnimations(animations: any): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the index of the currently displayed page. - **/ - currentPage: number; - - /** - * Gets the HTML element that hosts this FlipView. - **/ - element: HTMLElement; - - /** - * Gets or sets the data source that provides the FlipView with items to display. The FlipView displays one item at a time, on its own page. - **/ - itemDataSource: IListDataSource; - - /** - * Gets or sets the spacing between each item, in pixels. - **/ - itemSpacing: number; - - /** - * Gets or sets a Template or function that defines the HTML for each item's page. - **/ - itemTemplate: any; - - /** - * Gets or sets the orientation of the FlipView, horizontal or vertical. - **/ - orientation: string; - - //#endregion Properties - - } - - /** - * Displays lightweight UI that is either information, or requires user interaction. Unlike a dialog, a Flyout can be light dismissed by clicking or tapping off of it. - **/ - class Flyout { - //#region Constructors - - /** - * Creates a new Flyout object. - * @constructor - * @param element The DOM element that will host the control. - * @param options The set of properties and values to apply to the new Flyout. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Raised immediately after a flyout is fully hidden. - * @param eventInfo An object that contains information about the event. - **/ - onafterhide(eventInfo: Event): void; - - /** - * Raised immediately after a flyout is fully shown. - * @param eventInfo An object that contains information about the event. - **/ - onaftershow(eventInfo: Event): void; - - /** - * Raised just before hiding a flyout. - * @param eventInfo An object that contains information about the event. - **/ - onbeforehide(eventInfo: Event): void; - - /** - * Raised just before showing a flyout. - * @param eventInfo An object that contains information about the event. - **/ - onbeforeshow(eventInfo: Event): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. - * @param listener The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Releases resources held by this object. Call this method when the object is no longer needed. After calling this method, the object becomes unusable. - **/ - dispose(): void; - - /** - * Hides the Flyout, if visible, regardless of other states. - **/ - hide(): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. - * @param listener The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Shows the Flyout, if hidden, regardless of other states. - * @param anchor Required. The DOM element to anchor the Flyout. - * @param placement The placement of the Flyout to the anchor: the string literal "top", "bottom", "left", or "right". - * @param alignment For "top" or "bottom" placement, the alignment of the Flyout to the anchor's edge: the string literal "center", "left", or "right". - **/ - show(anchor: HTMLElement, placement: string, alignment: string): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the default alignment to be used for this Flyout. - **/ - alignment: string; - - /** - * Gets or sets the default anchor to be used for this Flyout. - **/ - anchor: HTMLElement; - - /** - * Gets the DOM element that hosts the Flyout. - **/ - element: HTMLElement; - - /** - * Gets a value that indicates whether the Flyout is hidden or in the process of becoming hidden. - **/ - hidden: boolean; - - /** - * Gets or sets the default placement to be used for this Flyout. - **/ - placement: string; - - //#endregion Properties - - } - - /** - * Represents a grid layout for the ListView in which items are arranged in a horizontal grid. - **/ - class GridLayout { - //#region Constructors - - /** - * Creates a new GridLayout object. - * @constructor - * @param options The set of properties and values to apply to the new GridLayout. - **/ - constructor(options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * This method is no longer supported. - * @param beginScrollPosition - * @param wholeItem - **/ - calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): void; - - /** - * This method is no longer supported. - * @param endScrollPosition - * @param wholeItem - **/ - calculateLastVisible(endScrollPosition: number, wholeItem: boolean): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - dragLeave(): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - dragOver(): void; - - /** - * This method is no longer supported. - **/ - endLayout(): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - executeAnimations(): void; - - /** - * This method is no longer supported. - * @param itemIndex - **/ - getItemPosition(itemIndex: number): void; - - /** - * This method is no longer supported. - * @param itemIndex - * @param element - * @param keyPressed - **/ - getKeyboardNavigatedItem(itemIndex: number, element: any, keyPressed: any): void; - - /** - * This method is no longer supported. - * @param beginScrollPosition - * @param endScrollPosition - **/ - getScrollbarRange(beginScrollPosition: number, endScrollPosition: number): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param x The x-coordinate, or the horizontal position on the screen. - * @param y The y-coordinate, or the vertical position on the screen. - **/ - hitTest(x: number, y: number): void; - - /** - * This method is no longer supported. - **/ - init(): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param site The rendering site for the layout. - * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. - **/ - initialize(site: ILayoutSite2, groupsEnabled: boolean): void; - - /** - * This method is no longer supported. - * @param elements - **/ - itemsAdded(elements: any): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param firstPixel The first pixel the range of items falls between. - * @param lastPixel The last pixel the range of items falls between. - **/ - itemsFromRange(firstPixel: number, lastPixel: number): void; - - /** - * This method is no longer supported. - **/ - itemsMoved(): void; - - /** - * This method is no longer supported. - * @param elements - **/ - itemsRemoved(elements: any): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param tree - * @param changedRange - * @param modifiedItems - * @param modifiedGroups - **/ - layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): void; - - /** - * This method is no longer supported. - * @param groupIndex - * @param element A DOM element. - **/ - layoutHeader(groupIndex: number, element: any): void; - - /** - * This method is no longer supported. - * @param itemIndex - * @param element A DOM element. - **/ - layoutItem(itemIndex: number, element: any): void; - - /** - * This method is no longer supported. - * @param element - **/ - prepareHeader(element: HTMLElement): void; - - /** - * This method is no longer supported. - * @param itemIndex - * @param element A DOM element. - **/ - prepareItem(itemIndex: number, element: any): void; - - /** - * This method is no longer supported. - * @param item - * @param newItem - **/ - releaseItem(item: any, newItem: any): void; - - /** - * This method is no longer supported. - **/ - reset(): void; - - /** - * This method is no longer supported. - * @param layoutSite - **/ - setSite(layoutSite: any): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - setupAnimations(): void; - - /** - * This method is no longer supported. - * @param beginScrollPosition - * @param endScrollPositionScrollPosition - **/ - startLayout(beginScrollPosition: number, endScrollPositionScrollPosition: number): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - uninitialize(): void; - - /** - * This method is no longer supported. - * @param count - **/ - updateBackdrop(count: number): void; - - //#endregion Methods - - //#region Properties - - /** - * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. - **/ - backdropColor: string; - - /** - * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. - **/ - disableBackdrop: boolean; - - /** - * Gets or sets the position of group headers. - **/ - groupHeaderPosition: WinJS.UI.HeaderPosition; - - /** - * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. - **/ - groupInfo: Function; - - /** - * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use the orientation property instead. - **/ - horizontal: boolean; - - /** - * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. - **/ - itemInfo: Function; - - /** - * Gets or set the maximum number of rows or columns, depending on the orientation, to display before content begins to wrap. - **/ - maximumRowsOrColumns: number; - - /** - * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the maximumRowsOrColumns property. - **/ - maxRows: number; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - numberOfItemsPerItemsBlock: any; - - /** - * Gets or sets the orientation of the GridLayout. - **/ - orientation: WinJS.UI.Orientation; - - //#endregion Properties - - } - - /** - * Creates a hub navigation pattern consisting of sections that can be navigated to. Each section is defined by a HubSection object. - **/ - class Hub { - //#region Constructors - - /** - * Creates a new Hub control. - * @constructor - * @param element The DOM element that will host the Hub control. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the contentanimating event, add a property named "oncontentanimating" to the options object and set its value to the event handler. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Raised when the Hub is about to play entrance, content transition, insert, or remove animations. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.type, detail.index, detail.section. - **/ - oncontentanimating(eventInfo: CustomEvent): void; - - /** - * Raised when the user clicks on an interactive header. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.section. - **/ - onheaderinvoked(eventInfo: CustomEvent): void; - - /** - * Raised when the Hub control's loadingState changes. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: loadingState. - **/ - onloadingstatechanged(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this Hub. Call this method when the Hub is no longer needed. After calling this method, the Hub becomes unusable. - **/ - dispose(): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets the DOM element that hosts the Hub control. - **/ - element: HTMLElement; - - /** - * Gets or sets the Template or templating function that creates the DOM elements for each HubSection header. Your HubSection object should provide strings for HubSection.header property. - **/ - headerTemplate: any; - - /** - * Gets or sets the index of the first HubSection at least partially in view. This property is useful for animating the visible content in the Hub. - **/ - indexOfFirstVisible: number; - - /** - * Gets or sets the index of last HubSection at least partially in view. Used for animating the visible content in the Hub. - **/ - indexOfLastVisible: number; - - /** - * Gets a value that indicates whether the hub is still loading or whether loading is complete. The value changes to complete after all the sections and content inside them has loaded. - **/ - loadingState: string; - - /** - * Gets or sets the orientation of sections within the Hub. - **/ - orientation: Orientation; - - /** - * Gets or sets the distance between the start of the Hub and the current viewable area. - **/ - scrollPosition: number; - - /** - * Gets or sets the index of the first visible HubSection. - **/ - sectionOnScreen: number; - - /** - * Gets or sets the List that contains the HubSection objects that belong to this Hub. - **/ - sections: WinJS.Binding.List; - - /** - * This API supports the SemanticZoom infrastructure and is not intended to be used directly from your code. - **/ - zoomableView: IZoomableView; - - //#endregion Properties - - } - - /** - * Defines a section of a Hub. - **/ - class HubSection { - //#region Constructors - - /** - * Creates a new HubSection. - * @constructor - * @param element The DOM element hosts the new HubSection. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * Releases resources held by this HubSection. Call this method when the HubSection is no longer needed. After calling this method, the HubSection becomes unusable. - **/ - dispose(): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets the DOM element that hosts the HubSection control's content. - **/ - contentElement: HTMLElement; - - /** - * Gets the DOM element that hosts this HubSection. - **/ - element: HTMLElement; - - /** - * Gets or sets the header for this HubSection. - **/ - header: string; - - /** - * Gets a value that specifies whether the header is static. - **/ - isHeaderStatic: boolean; - - //#endregion Properties - - } - - /** - * Enables you to include an HTML page dynamically. As part of the constructor, you must include an option indicating the URI of the page. - **/ - class HtmlControl { - //#region Constructors - - /** - * Initializes a new instance of HtmlControl to define a new page control. - * @constructor - * @param element The element that hosts the HtmlControl. - * @param options The options for configuring the page. The uri option is required in order to specify the source document for the content of the page. Other options are the ones used by the WinJS.Pages.render method. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - } - - /** - * Defines an item that can be pressed, swiped, and dragged. - **/ - class ItemContainer { - //#region Constructors - - /** - * Creates a new ItemContainer. - * @constructor - * @param element The DOM element hosts the new ItemContainer. For the ItemContainer to be accessible, this element must have its role attribute set to "list" or "listbox". If tapBehavior is set to none and selectionDisabled is true, then use the "list" role; otherwise, use the "listbox" role. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Raised when the item is invoked. (You can use the tapBehavior property to specify whether taps and clicks invoke the item.) - * @param eventInfo An object that contains information about the event. - **/ - oninvoked(eventInfo: CustomEvent): void; - - /** - * Raised after the item is selected or deselected. - * @param eventInfo An object that contains information about the event. - **/ - onselectionchanged(eventInfo: CustomEvent): void; - - /** - * Raised just before the current selection changes. - * @param eventInfo An object that contains information about the event. - **/ - onselectionchanging(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this ItemContainer. Call this method when the ItemContainer is no longer needed. After calling this method, the ItemContainer becomes unusable. - **/ - dispose(): void; - - /** - * Forces the ItemContainer to update its layout. Call this function when the reading direction of the app changes after the control has been initialized. - **/ - forceLayout(): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets a value that specifies whether the item can be dragged. - **/ - draggable: boolean; - - /** - * Gets the element that hosts this ItemContainer. - **/ - element: HTMLElement; - - /** - * Gets or sets a value that specifies whether the item is selected. - **/ - selected: boolean; - - /** - * Gets or sets a value that specifies whether selection of this item is disabled. - **/ - selectionDisabled: boolean; - - /** - * Gets or sets how the ItemContainer reacts to the swipe gesture. The swipe gesture can select the swiped items or can have no effect on the current selection. - **/ - swipeBehavior: WinJS.UI.SwipeBehavior; - - /** - * Gets or sets the orientation of swipe gestures. - **/ - swipeOrientation: Orientation; - - /** - * Gets or sets how the ItemContainer reacts when the user taps or clicks an item. - **/ - tapBehavior: TapBehavior; - - //#endregion Properties - - } - - /** - * This object supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - class Layout { - } - - /** - * Represents a layout for the ListView in which items are arranged in a vertical list. - **/ - class ListLayout { - //#region Constructors - - /** - * Creates a new ListLayout. - * @constructor - * @param options An object that contains one or more property/value pairs to apply to the new ListLayout. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". - **/ - constructor(options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * This method is no longer supported. - * @param beginScrollPosition - * @param wholeItem - **/ - calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): void; - - /** - * This method is no longer supported. - * @param endScrollPosition - * @param wholeItem - **/ - calculateLastVisible(endScrollPosition: number, wholeItem: boolean): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - dragLeave(): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - dragOver(): void; - - /** - * This method is no longer supported. - **/ - endLayout(): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - executeAnimations(): void; - - /** - * This method is no longer supported. - * @param itemIndex - **/ - getItemPosition(itemIndex: number): void; - - /** - * This method is no longer supported. - * @param itemIndex - * @param element - * @param keyPressed - **/ - getKeyboardNavigatedItem(itemIndex: number, element: HTMLElement, keyPressed: any): void; - - /** - * This method is no longer supported. - * @param beginScrollPosition - * @param endScrollPosition - **/ - getScrollbarRange(beginScrollPosition: number, endScrollPosition: number): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param x The x-coordinate, or the horizontal position on the screen. - * @param y The y-coordinate, or the vertical position on the screen. - **/ - hitTest(x: number, y: number): void; - - /** - * This method is no longer supported. - **/ - init(): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - initialize(): void; - - /** - * This method is no longer supported. - * @param elements - **/ - itemsAdded(elements: any): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param firstPixel - * @param lastPixel - **/ - itemsFromRange(firstPixel: number, lastPixel: number): void; - - /** - * This method is no longer supported. - **/ - itemsMoved(): void; - - /** - * This method is no longer supported. - * @param elements - **/ - itemsRemoved(elements: any): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param tree - * @param changedRange - * @param modifiedItems - * @param modifiedGroups - **/ - layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): void; - - /** - * This method is no longer supported. - * @param groupIndex - * @param element A DOM element. - **/ - layoutHeader(groupIndex: number, element: any): void; - - /** - * This method is no longer supported. - * @param itemIndex - * @param element A DOM element. - **/ - layoutItem(itemIndex: number, element: any): void; - - /** - * This method is no longer supported. - * @param element - **/ - prepareHeader(element: HTMLElement): void; - - /** - * This method is no longer supported. - * @param itemIndex - * @param element A DOM element. - **/ - prepareItem(itemIndex: number, element: any): void; - - /** - * This method is no longer supported. - * @param item - * @param newItem - **/ - releaseItem(item: any, newItem: any): void; - - /** - * This method is no longer supported. - **/ - reset(): void; - - /** - * This method is no longer supported. - * @param layoutSite - **/ - setSite(layoutSite: any): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - setupAnimations(): void; - - /** - * This method is no longer supported. - * @param beginScrollPosition - * @param endScrollPositionScrollPosition - **/ - startLayout(beginScrollPosition: number, endScrollPositionScrollPosition: number): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - uninitialize(): void; - - /** - * This method is no longer supported. - * @param count - **/ - updateBackdrop(count: number): void; - - //#endregion Methods - - //#region Properties - - /** - * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. - **/ - backdropColor: string; - - /** - * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. - **/ - disableBackdrop: boolean; - - /** - * Gets or sets the position of group headers. - **/ - groupHeaderPosition: WinJS.UI.HeaderPosition; - - /** - * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. - **/ - groupInfo: Function; - - /** - * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use the orientation property instead. - **/ - horizontal: boolean; - - /** - * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. - **/ - itemInfo: Function; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - numberOfItemsPerItemsBlock: any; - - /** - * Gets or sets the orientation of the GridLayout. - **/ - orientation: WinJS.UI.Orientation; - - //#endregion Properties - - } - - /** - * Displays data items in a customizable list or grid. - **/ + /** + * Represents a selection of ListView items. + **/ + interface ISelection { + //#region Methods + + /** + * Adds one or more items to the selection. + * @param items The indexes or keys of the items to add. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + add(items: any): Promise; + + /** + * Clears the selection. + * @returns A Promise that is fulfilled when the clear operation completes. + **/ + clear(): Promise; + + /** + * Returns the number of items in the selection. + * @returns The number of items in the selection. + **/ + count(): number; + + /** + * Returns a list of the indexes for the items in the selection. + * @returns The list of indexes for the items in the selection as an array of Number objects. + **/ + getIndices(): number[]; + + /** + * Returns an array that contains the items in the selection. + * @returns A Promise that contains an array of the requested IItem objects. + **/ + getItems(): Promise[]>; + + /** + * Gets an array of the index ranges for the selected items. + * @returns An array that contains an ISelectionRange object for each index range in the selection. + **/ + getRanges(): ISelectionRange[]; + + /** + * Returns a value that indicates whether the selection contains every item in the data source. + * @returns true if the selection contains every item in the data source; otherwise, false. + **/ + isEverything(): boolean; + + /** + * Removes the specified items from the selection. + * @param items The indexes or keys of the items to remove. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + remove(items: any): Promise; + + /** + * Adds all the items in the ListView to the selection. + **/ + selectAll(): void; + + /** + * Clears the current selection and replaces it with the specified items. + * @param items The indexes or keys of the items that make up the selection. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + set(items: any): Promise; + + //#endregion Methods + + } + + /** + * Represents a range of indexes or keys in an ISelection. + **/ + interface ISelectionRange { + //#region Properties + + /** + * Gets or sets the index of the first item in the range. + **/ + firstIndex: number; + + /** + * Gets or sets the key of the first item in the range. + **/ + firstKey: any; + + /** + * Gets or sets the index of the last item in the range. + **/ + lastIndex: number; + + /** + * Gets or sets of the key of the last item in the range. + **/ + lastKey: any; + + //#endregion Properties + + } + + /** + * Supports semantic zoom functionality by exposing a control as either the zoomed in or the zoomed out view of the SemanticZoom control. + **/ + interface IZoomableView { + //#region Methods + + /** + * Initiates semantic zoom on the custom control. + **/ + beginZoom(): void; + + /** + * Initializes the semantic zoom state for the custom control. + * @param isZoomedOut True if this is the zoomed out view; otherwise false. + * @param isCurrentView True if this is the current view; otherwise false. + * @param triggerZoom The function that manages semantic zoom behavior. Triggers a zoom in or zoom out if the control is the visible control. + * @param prefetchedPages The number of pages of content to pre-fetch for zooming. This value is dependent on the size of the semantic zoom container. More content can be displayed based on the zoom factor and the size of the container. + **/ + configureForZoom(isZoomedOut: boolean, isCurrentView: boolean, triggerZoom: Function, prefetchedPages: number): void; + + /** + * Terminates semantic zoom on the zoomed in or zoomed out child of the custom control. + * @param isCurrentView True if the control is the visible control; otherwise false. + **/ + endZoom(isCurrentView: boolean): void; + + /** + * Retrieves the current item of the zoomed in or zoomed out child of the custom control. + * @returns An object that represents the selected item. This return value must be a Promise for the following: item, position. + **/ + getCurrentItem(): Promise<{ item: T; position: Utilities.IPosition }>; + + /** + * Retrieves the panning axis of the zoomed-in or zoomed-out child of the custom control. + * @returns Identifies the panning axis of the child control. Implementation specific. + **/ + getPanAxis(): string; + + /** + * Manages pointer input for the custom control. + * @param pointerId The ID of the pointer. + **/ + handlePointer(pointerId: string): void; + + /** + * Positions the specified item within the viewport of the child control when panning or zooming begins. + * @param item The object to position within the viewport of the child control. item can be a number, a string, or an object with any number of properties. + * @param position An object that contains the position data of the item relative to the child control. position must be an object with four number properties: left, top, width, and height. These values specify a rectangle that is typically the bounding box of the current item, though the details are up to the control. The units of the position must be in pixels. And the coordinates must be relative to the top-left of the control viewport (which should occupy the same area as the semantic zoom viewport), except when in RTL mode. In RTL mode, return coordinates relative to the top-right off the control viewport. The rectangle is transformed from the coordinate system of one control to that of the other. + **/ + positionItem(item: T, position: Utilities.IPosition): void; + + /** + * Selects the item closest to the specified screen coordinates. + * @param x The x-coordinate in DIPs relative to the upper-left corner of the SemanticZoom viewport. + * @param y The y-coordinate in DIPs relative to the upper-left corner of the SemanticZoom viewport.. + **/ + setCurrentItem(x: number, y: number): void; + + //#endregion Methods + + } + + //#endregion Interfaces + + //#region Objects + + /** + * Represents an application toolbar for displaying commands. + **/ + class AppBar { + //#region Constructors + + /** + * Creates a new AppBar object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new AppBar. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs immediately after the AppBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Occurs after the AppBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Occurs before the AppBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Occurs before a hidden AppBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this AppBar. Call this method when the AppBar is no longer needed. After calling this method, the AppBar becomes unusable. + **/ + dispose(): void; + + /** + * Returns the AppBarCommand object identified by id. + * @param id The element idenitifier (ID) of the command to be returned. + * @returns The command identified by id. If multiple commands have the same ID, returns an array of all the commands matching the ID. + **/ + getCommandById(id: string): AppBarCommand; + + /** + * Hides the AppBar. + **/ + hide(): void; + + /** + * Hides the specified commands of the AppBar. + * @param commands The commands to hide. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. + **/ + hideCommands(commands: any[], immediate?: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the AppBar if it is not disabled. + **/ + show(): void; + + /** + * Shows the specified commands of the AppBar. + * @param commands The commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. + **/ + showCommands(commands: any[], immediate?: boolean): void; + + /** + * Shows the specified commands of the AppBar while hiding all other commands. + * @param commands The commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. + **/ + showOnlyCommands(commands: any[], immediate?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Sets the AppBarCommand objects that appear in the app bar. + **/ + commands: AppBarCommand[]; + + /** + * Gets or sets a value that indicates whether the AppBar is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the AppBar. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the AppBar is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the layout of the app bar contents. + **/ + layout: string; + + /** + * Gets or sets a value that specifies whether the AppBar appears at the top or bottom of the main view. + **/ + placement: string; + + /** + * Gets or sets a value that indicates whether the AppBar is sticky (won't light dismiss). If not sticky, the app bar dismisses normally when the user touches outside of the appbar. + **/ + sticky: boolean; + + //#endregion Properties + + } + + /** + * Represents a command to be displayed in an app bar. + **/ + class AppBarCommand { + //#region Constructors + + /** + * Creates a new AppBarCommand object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new AppBarCommand. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this AppBarCommand. Call this method when the AppBarCommand is no longer needed. After calling this method, the AppBarCommand becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that indicates whether the AppBarCommand is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the AppBarCommand. + **/ + element: HTMLElement; + + /** + * Adds an extra CSS class during construction. + **/ + extraClass: string; + + /** + * Gets or sets the HTMLElement with a 'content' type AppBarCommand that should receive focus whenever focus moves by the user pressing HOME or the arrow keys, from the previous AppBarCommand to this AppBarCommand. + **/ + firstElementFocus: HTMLElement; + + /** + * Gets or sets the Flyout object displayed by this command. The specified flyout is shown when the AppBarCommand's button is invoked. + **/ + flyout: Flyout; + + /** + * Gets or sets a value that indicates whether the AppBarCommand is hiding or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the icon of the AppBarCommand. + **/ + icon: string; + + /** + * Gets the element identifier (ID) of the command. + **/ + id: string; + + /** + * Gets or sets the label of the command. + **/ + label: string; + + /** + * Gets or sets the HTMLElement with a 'content' type AppBarCommand that should receive focus whenever focus moves by the user pressing END or the arrow keys, from the previous AppBarCommand to this AppBarCommand. + **/ + lastElementFocus: HTMLElement; + + /** + * Gets or sets the function to be invoked when the command is clicked. + **/ + onclick: Function; + + /** + * Gets the section of the app bar that the command is in. + **/ + section: string; + + /** + * Gets or sets the selected state of a toggle button. + **/ + selected: boolean; + + /** + * Gets or sets the tooltip of the command. + **/ + tooltip: string; + + /** + * Gets the type of the command. + **/ + type: string; + + //#endregion Properties + + } + + /** + * Provides backwards navigation in the form of a button. + **/ + class BackButton { + //#region Constructors + + /** + * Creates a new BackButton. + * @constructor + * @param element The DOM element hosts the new BackButton. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this BackButton. Call this method when the BackButton is no longer needed. After calling this method, the BackButton becomes unusable. + **/ + dispose(): void; + + /** + * Checks the current navigation history and updates the value of the control's disabled attribute. + **/ + refresh(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the HTML element that hosts this BackButton. + **/ + element: HTMLElement; + + //#endregion Properties + + } + + /** + * Represents a layout for the ListView in which items are arranged in a grid and items can span multiple grid cells. + **/ + class CellSpanningLayout { + //#region Constructors + + /** + * Creates a new CellSpanningLayout. + * @constructor + * @param options An object that contains one or more property/value pairs to apply to the new CellSpanningLayout. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragLeave(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragOver(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + executeAnimations(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate, or the horizontal position on the screen. + * @param y The y-coordinate, or the vertical position on the screen. + **/ + hitTest(x: number, y: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param site The rendering site for the layout. + * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. + **/ + initialize(site: ILayoutSite2, groupsEnabled: boolean): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param firstPixel The first pixel the range of items falls between. + * @param lastPixel The last pixel the range of items falls between. + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param tree + * @param changedRange + * @param modifiedItems + * @param modifiedGroups + **/ + layout(tree: ILayoutSite2, changedRange: any, modifiedItems: any, modifiedGroups: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + setupAnimations(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + uninitialize(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the position of group headers relative to their items. + **/ + groupHeaderPosition: WinJS.UI.HeaderPosition; + + /** + * Gets or sets a function that enables cell-spanning and establishes base cell dimensions. + **/ + groupInfo: Function; + + /** + * Gets or sets a function that returns the width and height of an item, as well as whether it should appear in a new column. Setting this function improves performance because the ListView can allocate space for an item without having to measure it first. + **/ + itemInfo: Function; + + /** + * Gets or set the maximum number of rows or columns, depending on the orientation, to display before content begins to wrap. + **/ + maximumRowsOrColumns: number; + + /** + * This API supports the Windows Library for JavaScript infrastructure and is not intended to be used directly from your code. + **/ + numberOfItemsPerItemsBlock: any; + + /** + * Gets the orientation of the CellSpanningLayout. For a CellSpanningLayout, this property always returns Orientation.horizontal. + **/ + orientation: WinJS.UI.Orientation; + + //#endregion Properties + + } + + /** + * Allows users to pick a date value. + **/ + class DatePicker { + //#region Constructors + + /** + * Initializes a new instance of the DatePicker control. + * @constructor + * @param element The DOM element associated with the DatePicker control. + * @param options The set of options to be applied initially to the DatePicker control. The options are the following: calendar, current, datePattern, disabled, maxYear, minYear, monthPattern, yearPattern. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when any of the controls are changed by the user. + * @param eventInfo An object that contains information about the event. + **/ + onchange(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener. + * @param type The type (name) of the event. + * @param listener The function that handles the event. + * @param capture If true, specifies that capture should be initiated, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this DatePicker. Call this method when the DatePicker is no longer needed. After calling this method, the DatePicker becomes unusable. + **/ + dispose(): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + raiseEvent(type: string, eventProperties: any): boolean; + + /** + * Removes a listener for the specified event. + * @param type The name of the event for which to remove a listener. + * @param listener The listener. + * @param useCapture Optional. The same value that was passed to addEventListener for this listener. It may be omitted if it was omitted when calling addEventListener. + **/ + removeEventListener(type: string, listener: Function, useCapture?: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the calendar to use. + **/ + calendar: string; + + /** + * Gets or sets the current date of the DatePicker. You can use either a date string or a Date object to set this property. + **/ + current: Date; + + /** + * Gets or sets the display pattern for the date. The default date pattern is day.integer(2). You can change the date pattern by changing the number of integers displayed. + **/ + datePattern: string; + + /** + * Specifies whether the DatePicker is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element for the DatePicker. + **/ + element: HTMLElement; + + /** + * Gets or sets the maximum Gregorian year available for picking. + **/ + maxYear: number; + + /** + * Gets or sets the minimum Gregorian year available for picking. + **/ + minYear: number; + + /** + * Gets or sets the display pattern for the month. The default month pattern is month.abbreviated. You can change the month pattern to the following values: month.full. The full name of the month. month.abbreviated(n). You can use abbreviated with or without specifying the number of letters in the abbreviation. If you do specify the number of letters, the actual length of the month name that appears may vary. month.solo.full. A representation of the month that is suitable for stand-alone display. You can also use month.solo.abbreviated(n). month.integer(n). You can use integer with or without specifying the number of integers. + **/ + monthPattern: string; + + /** + * Gets or sets the display pattern for the year. The default year pattern is year.full. You can change the year pattern to the following values: year.abbreviated(n). You can use abbreviated with or without specifying the number of letters in the abbreviation. + **/ + yearPattern: string; + + //#endregion Properties + + } + + /** + * Adds event-related methods to the control. + **/ + class DOMEventMixin { + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture true to initiate capture; otherwise, false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type, adding the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true to initiate capture; otherwise, false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Adds the set of declaratively specified options (properties and events) to the specified control. If the name of the options property begins with "on", the property value is a function and the control supports addEventListener. This method calls the addEventListener method on the control. + * @param control The control on which the properties and events are to be applied. + * @param options The set of options that are specified declaratively. + **/ + setOptions(control: any, options: any): void; + + //#endregion Methods + + } + + /** + * Displays a collection, such as a set of photos, one item at a time. + **/ + class FlipView { + //#region Constructors + + /** + * Creates a new FlipView. + * @constructor + * @param element The DOM element that hosts the control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the pageselected event, add a property named "onpageselected" and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the datasource count changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: source. + **/ + ondatasourcecountchanged(eventInfo: Event): void; + + /** + * Raised when the FlipView flips to a page and its renderer function completes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source. + **/ + onpagecompleted(eventInfo: CustomEvent): void; + + /** + * Raised when the FlipView flips to a page. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source. + **/ + onpageselected(eventInfo: CustomEvent): void; + + /** + * Occurs when an item becomes invisible or visible. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source, detail.visible. + **/ + onpagevisibilitychanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. For a list of events, see the FlipView object page. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Returns the number of items in the FlipView control's itemDataSource. + * @returns A Promise that contains the number of items in the list or WinJS.UI.CountResult.unknown if the count is unavailable. + **/ + count(): Promise; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this FlipView. Call this method when the FlipView is no longer needed. After calling this method, the FlipView becomes unusable. + **/ + dispose(): void; + + /** + * Forces the FlipView to update its layout. Use this function when making the FlipView visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Navigates to the next page. + * @returns true if the FlipView begins navigating to the next page; false if the FlipView is already at the last item or is in the middle of another navigation animation. + **/ + next(): boolean; + + /** + * Navigates to the previous item. + * @returns true if the FlipView begins navigating to the previous page; nfalse if the FlipView is already at the first page or is in the middle of another navigation animation. + **/ + previous(): boolean; + + /** + * Unregisters an event handler for the specified event. + * @param eventName The name of the event. + * @param eventHandler The event handler function to remove. + * @param useCapture Set to true to unregister the event handler for the capturing phase; otherwise, set to false to unregister the event handler for the bubbling phase. + **/ + removeEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Sets custom animations for the FlipView to use when navigating between pages. + * @param animations An object that contains up to three fields, one for each navigation action: next, previous, and jump. Each of those fields must be a function with this signature: function (outgoingPage, incomingPage) Each function must return a WinJS.Promise that completes once the animations are finished. If a field is null or undefined, the FlipView reverts to its default animation for that action. + **/ + setCustomAnimations(animations: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the index of the currently displayed page. + **/ + currentPage: number; + + /** + * Gets the HTML element that hosts this FlipView. + **/ + element: HTMLElement; + + /** + * Gets or sets the data source that provides the FlipView with items to display. The FlipView displays one item at a time, on its own page. + **/ + itemDataSource: IListDataSource; + + /** + * Gets or sets the spacing between each item, in pixels. + **/ + itemSpacing: number; + + /** + * Gets or sets a Template or function that defines the HTML for each item's page. + **/ + itemTemplate: any; + + /** + * Gets or sets the orientation of the FlipView, horizontal or vertical. + **/ + orientation: string; + + //#endregion Properties + + } + + /** + * Displays lightweight UI that is either information, or requires user interaction. Unlike a dialog, a Flyout can be light dismissed by clicking or tapping off of it. + **/ + class Flyout { + //#region Constructors + + /** + * Creates a new Flyout object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new Flyout. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised immediately after a flyout is fully hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Raised immediately after a flyout is fully shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Raised just before hiding a flyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Raised just before showing a flyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this object. Call this method when the object is no longer needed. After calling this method, the object becomes unusable. + **/ + dispose(): void; + + /** + * Hides the Flyout, if visible, regardless of other states. + **/ + hide(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the Flyout, if hidden, regardless of other states. + * @param anchor Required. The DOM element to anchor the Flyout. + * @param placement The placement of the Flyout to the anchor: the string literal "top", "bottom", "left", or "right". + * @param alignment For "top" or "bottom" placement, the alignment of the Flyout to the anchor's edge: the string literal "center", "left", or "right". + **/ + show(anchor: HTMLElement, placement: string, alignment: string): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the default alignment to be used for this Flyout. + **/ + alignment: string; + + /** + * Gets or sets the default anchor to be used for this Flyout. + **/ + anchor: HTMLElement; + + /** + * Gets the DOM element that hosts the Flyout. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the Flyout is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the default placement to be used for this Flyout. + **/ + placement: string; + + //#endregion Properties + + } + + /** + * Represents a grid layout for the ListView in which items are arranged in a horizontal grid. + **/ + class GridLayout { + //#region Constructors + + /** + * Creates a new GridLayout object. + * @constructor + * @param options The set of properties and values to apply to the new GridLayout. + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param wholeItem + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): void; + + /** + * This method is no longer supported. + * @param endScrollPosition + * @param wholeItem + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragLeave(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragOver(): void; + + /** + * This method is no longer supported. + **/ + endLayout(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + executeAnimations(): void; + + /** + * This method is no longer supported. + * @param itemIndex + **/ + getItemPosition(itemIndex: number): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element + * @param keyPressed + **/ + getKeyboardNavigatedItem(itemIndex: number, element: any, keyPressed: any): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPosition + **/ + getScrollbarRange(beginScrollPosition: number, endScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate, or the horizontal position on the screen. + * @param y The y-coordinate, or the vertical position on the screen. + **/ + hitTest(x: number, y: number): void; + + /** + * This method is no longer supported. + **/ + init(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param site The rendering site for the layout. + * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. + **/ + initialize(site: ILayoutSite2, groupsEnabled: boolean): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsAdded(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param firstPixel The first pixel the range of items falls between. + * @param lastPixel The last pixel the range of items falls between. + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * This method is no longer supported. + **/ + itemsMoved(): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsRemoved(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param tree + * @param changedRange + * @param modifiedItems + * @param modifiedGroups + **/ + layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): void; + + /** + * This method is no longer supported. + * @param groupIndex + * @param element A DOM element. + **/ + layoutHeader(groupIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + layoutItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param element + **/ + prepareHeader(element: HTMLElement): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + prepareItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param item + * @param newItem + **/ + releaseItem(item: any, newItem: any): void; + + /** + * This method is no longer supported. + **/ + reset(): void; + + /** + * This method is no longer supported. + * @param layoutSite + **/ + setSite(layoutSite: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + setupAnimations(): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPositionScrollPosition + **/ + startLayout(beginScrollPosition: number, endScrollPositionScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + uninitialize(): void; + + /** + * This method is no longer supported. + * @param count + **/ + updateBackdrop(count: number): void; + + //#endregion Methods + + //#region Properties + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + backdropColor: string; + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + disableBackdrop: boolean; + + /** + * Gets or sets the position of group headers. + **/ + groupHeaderPosition: WinJS.UI.HeaderPosition; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + groupInfo: Function; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use the orientation property instead. + **/ + horizontal: boolean; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + itemInfo: Function; + + /** + * Gets or set the maximum number of rows or columns, depending on the orientation, to display before content begins to wrap. + **/ + maximumRowsOrColumns: number; + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the maximumRowsOrColumns property. + **/ + maxRows: number; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + numberOfItemsPerItemsBlock: any; + + /** + * Gets or sets the orientation of the GridLayout. + **/ + orientation: WinJS.UI.Orientation; + + //#endregion Properties + + } + + /** + * Creates a hub navigation pattern consisting of sections that can be navigated to. Each section is defined by a HubSection object. + **/ + class Hub { + //#region Constructors + + /** + * Creates a new Hub control. + * @constructor + * @param element The DOM element that will host the Hub control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the contentanimating event, add a property named "oncontentanimating" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the Hub is about to play entrance, content transition, insert, or remove animations. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.type, detail.index, detail.section. + **/ + oncontentanimating(eventInfo: CustomEvent): void; + + /** + * Raised when the user clicks on an interactive header. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.section. + **/ + onheaderinvoked(eventInfo: CustomEvent): void; + + /** + * Raised when the Hub control's loadingState changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: loadingState. + **/ + onloadingstatechanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this Hub. Call this method when the Hub is no longer needed. After calling this method, the Hub becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the Hub control. + **/ + element: HTMLElement; + + /** + * Gets or sets the Template or templating function that creates the DOM elements for each HubSection header. Your HubSection object should provide strings for HubSection.header property. + **/ + headerTemplate: any; + + /** + * Gets or sets the index of the first HubSection at least partially in view. This property is useful for animating the visible content in the Hub. + **/ + indexOfFirstVisible: number; + + /** + * Gets or sets the index of last HubSection at least partially in view. Used for animating the visible content in the Hub. + **/ + indexOfLastVisible: number; + + /** + * Gets a value that indicates whether the hub is still loading or whether loading is complete. The value changes to complete after all the sections and content inside them has loaded. + **/ + loadingState: string; + + /** + * Gets or sets the orientation of sections within the Hub. + **/ + orientation: Orientation; + + /** + * Gets or sets the distance between the start of the Hub and the current viewable area. + **/ + scrollPosition: number; + + /** + * Gets or sets the index of the first visible HubSection. + **/ + sectionOnScreen: number; + + /** + * Gets or sets the List that contains the HubSection objects that belong to this Hub. + **/ + sections: WinJS.Binding.List; + + /** + * This API supports the SemanticZoom infrastructure and is not intended to be used directly from your code. + **/ + zoomableView: IZoomableView; + + //#endregion Properties + + } + + /** + * Defines a section of a Hub. + **/ + class HubSection { + //#region Constructors + + /** + * Creates a new HubSection. + * @constructor + * @param element The DOM element hosts the new HubSection. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Releases resources held by this HubSection. Call this method when the HubSection is no longer needed. After calling this method, the HubSection becomes unusable. + **/ + dispose(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the HubSection control's content. + **/ + contentElement: HTMLElement; + + /** + * Gets the DOM element that hosts this HubSection. + **/ + element: HTMLElement; + + /** + * Gets or sets the header for this HubSection. + **/ + header: string; + + /** + * Gets a value that specifies whether the header is static. + **/ + isHeaderStatic: boolean; + + //#endregion Properties + + } + + /** + * Enables you to include an HTML page dynamically. As part of the constructor, you must include an option indicating the URI of the page. + **/ + class HtmlControl { + //#region Constructors + + /** + * Initializes a new instance of HtmlControl to define a new page control. + * @constructor + * @param element The element that hosts the HtmlControl. + * @param options The options for configuring the page. The uri option is required in order to specify the source document for the content of the page. Other options are the ones used by the WinJS.Pages.render method. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + } + + /** + * Defines an item that can be pressed, swiped, and dragged. + **/ + class ItemContainer { + //#region Constructors + + /** + * Creates a new ItemContainer. + * @constructor + * @param element The DOM element hosts the new ItemContainer. For the ItemContainer to be accessible, this element must have its role attribute set to "list" or "listbox". If tapBehavior is set to none and selectionDisabled is true, then use the "list" role; otherwise, use the "listbox" role. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the item is invoked. (You can use the tapBehavior property to specify whether taps and clicks invoke the item.) + * @param eventInfo An object that contains information about the event. + **/ + oninvoked(eventInfo: CustomEvent): void; + + /** + * Raised after the item is selected or deselected. + * @param eventInfo An object that contains information about the event. + **/ + onselectionchanged(eventInfo: CustomEvent): void; + + /** + * Raised just before the current selection changes. + * @param eventInfo An object that contains information about the event. + **/ + onselectionchanging(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this ItemContainer. Call this method when the ItemContainer is no longer needed. After calling this method, the ItemContainer becomes unusable. + **/ + dispose(): void; + + /** + * Forces the ItemContainer to update its layout. Call this function when the reading direction of the app changes after the control has been initialized. + **/ + forceLayout(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether the item can be dragged. + **/ + draggable: boolean; + + /** + * Gets the element that hosts this ItemContainer. + **/ + element: HTMLElement; + + /** + * Gets or sets a value that specifies whether the item is selected. + **/ + selected: boolean; + + /** + * Gets or sets a value that specifies whether selection of this item is disabled. + **/ + selectionDisabled: boolean; + + /** + * Gets or sets how the ItemContainer reacts to the swipe gesture. The swipe gesture can select the swiped items or can have no effect on the current selection. + **/ + swipeBehavior: WinJS.UI.SwipeBehavior; + + /** + * Gets or sets the orientation of swipe gestures. + **/ + swipeOrientation: Orientation; + + /** + * Gets or sets how the ItemContainer reacts when the user taps or clicks an item. + **/ + tapBehavior: TapBehavior; + + //#endregion Properties + + } + + /** + * This object supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + class Layout { + } + + /** + * Represents a layout for the ListView in which items are arranged in a vertical list. + **/ + class ListLayout { + //#region Constructors + + /** + * Creates a new ListLayout. + * @constructor + * @param options An object that contains one or more property/value pairs to apply to the new ListLayout. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param wholeItem + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): void; + + /** + * This method is no longer supported. + * @param endScrollPosition + * @param wholeItem + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragLeave(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragOver(): void; + + /** + * This method is no longer supported. + **/ + endLayout(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + executeAnimations(): void; + + /** + * This method is no longer supported. + * @param itemIndex + **/ + getItemPosition(itemIndex: number): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element + * @param keyPressed + **/ + getKeyboardNavigatedItem(itemIndex: number, element: HTMLElement, keyPressed: any): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPosition + **/ + getScrollbarRange(beginScrollPosition: number, endScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate, or the horizontal position on the screen. + * @param y The y-coordinate, or the vertical position on the screen. + **/ + hitTest(x: number, y: number): void; + + /** + * This method is no longer supported. + **/ + init(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + initialize(): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsAdded(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param firstPixel + * @param lastPixel + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * This method is no longer supported. + **/ + itemsMoved(): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsRemoved(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param tree + * @param changedRange + * @param modifiedItems + * @param modifiedGroups + **/ + layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): void; + + /** + * This method is no longer supported. + * @param groupIndex + * @param element A DOM element. + **/ + layoutHeader(groupIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + layoutItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param element + **/ + prepareHeader(element: HTMLElement): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + prepareItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param item + * @param newItem + **/ + releaseItem(item: any, newItem: any): void; + + /** + * This method is no longer supported. + **/ + reset(): void; + + /** + * This method is no longer supported. + * @param layoutSite + **/ + setSite(layoutSite: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + setupAnimations(): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPositionScrollPosition + **/ + startLayout(beginScrollPosition: number, endScrollPositionScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + uninitialize(): void; + + /** + * This method is no longer supported. + * @param count + **/ + updateBackdrop(count: number): void; + + //#endregion Methods + + //#region Properties + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + backdropColor: string; + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + disableBackdrop: boolean; + + /** + * Gets or sets the position of group headers. + **/ + groupHeaderPosition: WinJS.UI.HeaderPosition; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + groupInfo: Function; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use the orientation property instead. + **/ + horizontal: boolean; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + itemInfo: Function; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + numberOfItemsPerItemsBlock: any; + + /** + * Gets or sets the orientation of the GridLayout. + **/ + orientation: WinJS.UI.Orientation; + + //#endregion Properties + + } + + /** + * Displays data items in a customizable list or grid. + **/ class ListView { - //#region Constructors + //#region Constructors - /** - * Creates a new ListView. - * @constructor - * @param element The DOM element that hosts the ListView control. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the selectionchanged event, add a property named "onselectionchanged" to the options object and set its value to the event handler. - **/ - constructor(element?: HTMLElement, options?: any); + /** + * Creates a new ListView. + * @constructor + * @param element The DOM element that hosts the ListView control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the selectionchanged event, add a property named "onselectionchanged" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); - //#endregion Constructors + //#endregion Constructors - //#region Events + //#region Events - /** - * Occurs when the ListView is about to play an entrance or contentTransition animation. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.type, detail.setPromise. - **/ - oncontentanimating(eventInfo: CustomEvent): void; + /** + * Occurs when the ListView is about to play an entrance or contentTransition animation. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.type, detail.setPromise. + **/ + oncontentanimating(eventInfo: CustomEvent): void; - /** - * Raised when the user taps or clicks a group header. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.groupHeaderIndex, detail.groupHeaderPromise. - **/ - ongroupheaderinvoked(eventInfo: CustomEvent): void; + /** + * Raised when the user taps or clicks a group header. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.groupHeaderIndex, detail.groupHeaderPromise. + **/ + ongroupheaderinvoked(eventInfo: CustomEvent): void; - /** - * Raised when the ListView is a drop target and the onitemdragenter has been disabled. This is raised every time the cursor is moved between a new pair of items. If you call preventDefault on this event, then the ListView does not move the items slightly above/below the cursor to provide visual feedback for a drop. - * @param eventInfo An object that contains information about the event. The detail property of this object contains additional information about the event. - **/ - onitemdragbetween(eventInfo: CustomEvent): void; + /** + * Raised when the ListView is a drop target and the onitemdragenter has been disabled. This is raised every time the cursor is moved between a new pair of items. If you call preventDefault on this event, then the ListView does not move the items slightly above/below the cursor to provide visual feedback for a drop. + * @param eventInfo An object that contains information about the event. The detail property of this object contains additional information about the event. + **/ + onitemdragbetween(eventInfo: CustomEvent): void; - /** - * Raised when the user is dragging an item from the ListView and the datasource changes while the user is dragging. - * @param eventInfo An object that contains information about the event. The detail property of this object contains additional information about the event. - **/ - onitemdragchanged(eventInfo: CustomEvent): void; + /** + * Raised when the user is dragging an item from the ListView and the datasource changes while the user is dragging. + * @param eventInfo An object that contains information about the event. The detail property of this object contains additional information about the event. + **/ + onitemdragchanged(eventInfo: CustomEvent): void; - /** - * Raised when an item is dropped onto the ListView as the result of a drag operation. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.dataTransfer, detail.index, detail.insertAfterIndex. - **/ - onitemdragdrop(eventInfo: CustomEvent): void; + /** + * Raised when an item is dropped onto the ListView as the result of a drag operation. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.dataTransfer, detail.index, detail.insertAfterIndex. + **/ + onitemdragdrop(eventInfo: CustomEvent): void; - /** - * Raised when the user drops an item dragged from a ListView. - * @param eventInfo An object that contains information about the event. - **/ - onitemdragend(eventInfo: CustomEvent): void; + /** + * Raised when the user drops an item dragged from a ListView. + * @param eventInfo An object that contains information about the event. + **/ + onitemdragend(eventInfo: CustomEvent): void; - /** - * Raised when an dragged item enters the bounds of the ListView control. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.dataTransfer. - **/ - onitemdragenter(eventInfo: CustomEvent): void; + /** + * Raised when an dragged item enters the bounds of the ListView control. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.dataTransfer. + **/ + onitemdragenter(eventInfo: CustomEvent): void; - /** - * Raised when a draggable item leaves the bounds of a ListView control. - * @param eventInfo An object that contains information about the event. - **/ - onitemdragleave(eventInfo: CustomEvent): void; + /** + * Raised when a draggable item leaves the bounds of a ListView control. + * @param eventInfo An object that contains information about the event. + **/ + onitemdragleave(eventInfo: CustomEvent): void; - /** - * Raised when the user begins to drag an item from a ListView control. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.dataTransfer, detail.dragInfo. - **/ - onitemdragstart(eventInfo: CustomEvent): void; + /** + * Raised when the user begins to drag an item from a ListView control. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.dataTransfer, detail.dragInfo. + **/ + onitemdragstart(eventInfo: CustomEvent): void; - /** - * Occurs when the user taps or clicks an item. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.itemIndex. - **/ - oniteminvoked(eventInfo: CustomEvent): void; + /** + * Occurs when the user taps or clicks an item. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.itemIndex. + **/ + oniteminvoked(eventInfo: CustomEvent): void; - /** - * Raised when the focused item changes. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.oldFocus, detail.oldNewFocus. - **/ - onkeyboardnavigating(eventInfo: CustomEvent): void; + /** + * Raised when the focused item changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.oldFocus, detail.oldNewFocus. + **/ + onkeyboardnavigating(eventInfo: CustomEvent): void; - /** - * Occurs when the ListView control's loadingState changes. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.scrolling. - **/ - onloadingstatechanged(eventInfo: CustomEvent): void; + /** + * Occurs when the ListView control's loadingState changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.scrolling. + **/ + onloadingstatechanged(eventInfo: CustomEvent): void; - /** - * Occurs after the current selection changes. - * @param eventInfo An object that contains information about the event. The detail property of this object is null. To obtain the selected items, use the ListView.selection property. - **/ - onselectionchanged(eventInfo: CustomEvent): void; + /** + * Occurs after the current selection changes. + * @param eventInfo An object that contains information about the event. The detail property of this object is null. To obtain the selected items, use the ListView.selection property. + **/ + onselectionchanged(eventInfo: CustomEvent): void; - /** - * Occurs just before the current selection changes. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.newSelection, detail.preventTapBehavior. - **/ - onselectionchanging(eventInfo: CustomEvent): void; + /** + * Occurs just before the current selection changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.newSelection, detail.preventTapBehavior. + **/ + onselectionchanging(eventInfo: CustomEvent): void; - //#endregion Events + //#endregion Events - //#region Methods + //#region Methods - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. See the ListView object page for a list of events. Note that you drop the "on" when specifying the event name for the addEventListener method. For example, instead of specifying "onselectionchange", you specify "selectionchange". - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. See the ListView object page for a list of events. Note that you drop the "on" when specifying the event name for the addEventListener method. For example, instead of specifying "onselectionchange", you specify "selectionchange". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; - /** - * Releases resources held by this object. Call this method when the object is no longer needed. After calling this method, the object becomes unusable. - **/ - dispose(): void; + /** + * Releases resources held by this object. Call this method when the object is no longer needed. After calling this method, the object becomes unusable. + **/ + dispose(): void; - /** - * Returns the DOM element that represents the item at the specified index. - * @param itemIndex The index of the item. - * @returns The DOM element that represents the item at the specified index. - **/ - elementFromIndex(itemIndex: number): HTMLElement; + /** + * Returns the DOM element that represents the item at the specified index. + * @param itemIndex The index of the item. + * @returns The DOM element that represents the item at the specified index. + **/ + elementFromIndex(itemIndex: number): HTMLElement; - /** - * Makes the item at the specified index visible. If necessary, the ListView will scroll to the item. - * @param itemIndex The index of the item to scroll into view. - **/ - ensureVisible(itemIndex: number): void; + /** + * Makes the item at the specified index visible. If necessary, the ListView will scroll to the item. + * @param itemIndex The index of the item to scroll into view. + **/ + ensureVisible(itemIndex: number): void; - /** - * Forces the ListView to update its layout. Use this function when making the ListView visible again after its style.display property had been set to "none". - **/ - forceLayout(): void; + /** + * Forces the ListView to update its layout. Use this function when making the ListView visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; - /** - * Returns the index of the item that the specified DOM element displays. - * @param element The DOM element that displays the item. - * @returns The index of the item displayed by element. - **/ - indexOfElement(element: HTMLElement): number; + /** + * Returns the index of the item that the specified DOM element displays. + * @param element The DOM element that displays the item. + * @returns The index of the item displayed by element. + **/ + indexOfElement(element: HTMLElement): number; - /** - * Loads the next set of pages if the ListView control's loadingBehavior is set to "incremental" (otherwise, it does nothing). The number of pages to be loaded is determined by the pagesToLoad property. - **/ - loadMorePages(): void; + /** + * Loads the next set of pages if the ListView control's loadingBehavior is set to "incremental" (otherwise, it does nothing). The number of pages to be loaded is determined by the pagesToLoad property. + **/ + loadMorePages(): void; - /** - * Repositions all the visible items in the ListView to adjust for items whose sizes have changed. Most apps won’t ever need to call this method. For more info, see the Remarks section. - **/ - recalculateItemPosition(): void; + /** + * Repositions all the visible items in the ListView to adjust for items whose sizes have changed. Most apps won’t ever need to call this method. For more info, see the Remarks section. + **/ + recalculateItemPosition(): void; - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; /** * Triggers the ListView disposal service manually. **/ static triggerDispose(): void; - //#endregion Methods + //#endregion Methods - //#region Properties + //#region Properties - /** - * Gets or sets a value that indicates whether the next set of pages is automatically loaded when the user scrolls beyond the number of pages specified by the pagesToLoadThreshold property. - **/ - automaticallyLoadPages: boolean; + /** + * Gets or sets a value that indicates whether the next set of pages is automatically loaded when the user scrolls beyond the number of pages specified by the pagesToLoadThreshold property. + **/ + automaticallyLoadPages: boolean; /** * Gets or sets an IListViewItem that indicates which item should have keyboard focus and the focus state of that item. **/ currentItem: IListViewItem; - /** - * Gets the HTML element that hosts this ListView. - **/ - element: HTMLElement; - - /** - * Gets or sets the data source that contains the groups for the items in the itemDataSource. - **/ - groupDataSource: IListDataSource; - - /** - * Gets or sets how the ListView reacts when the user taps or clicks a group header. - **/ - groupHeaderTapBehavior: GroupHeaderTapBehavior; - - /** - * Gets or sets the Template or function that creates the DOM elements for each group header in the groupDataSource. Each group header can contain multiple elements, but it must have a single root element. - **/ - groupHeaderTemplate: any; - - /** - * Gets or sets the first visible item. - **/ - indexOfFirstVisible: number; - - /** - * Gets the index of the last visible item in the ListView. - **/ - indexOfLastVisible: number; - - /** - * Gets or sets the data source that provides the ListView with items. - **/ - itemDataSource: IListDataSource; - - /** - * Go Gets or sets a value that specifies whether items can be dragged. When this is set to true the ListView provides built in behaviors related to item dragging. - **/ - itemsDraggable: boolean; - - /** - * Gets or sets whether the ListView control's items can be reordered within itself by dragging and dropping. - **/ - itemsReorderable: boolean; - - /** - * Gets or sets the WinJS.Binding.Template or templating function that creates the DOM elements for each item in the itemDataSource. Each item can contain multiple elements, but it must have a single root element. - **/ - itemTemplate: any; - - /** - * Gets or sets an object that controls the layout of the ListView. - **/ - layout: ILayout2; - - /** - * Gets or sets a value that specifies how the ListView fetches items and adds and removes them to the DOM. Don't change the value of this property after the ListView has begun loading data. - **/ - loadingBehavior: string; - - /** - * Gets a value that indicates whether the ListView is still loading or whether loading is complete. - **/ - loadingState: string; - - /** - * Gets or sets the maximum number of realized items. - **/ - maxDeferredItemCleanup: number; - - /** - * Gets or sets the number of pages to load when the loadingBehavior property is set to "incremental" and the user scrolls beyond the threshold specified by the pagesToLoadThreshold property. - **/ - pagesToLoad: number; - - /** - * Gets or sets the threshold (in pages) for initiating an incremental load. When the last visible item is within the specified number of pages from the end of the loaded portion of the list, and if automaticallyLoadPages is true and loadingBehavior is set to "incremental", the ListView initiates an incremental load. - **/ - pagesToLoadThreshold: number; - - /** - * Gets or sets the function that is called when the ListView discards or recycles the element representation of a group header. - **/ - resetGroupHeader: (header: any, element: HTMLElement) => void; - - /** - * Gets or sets the function that is called when an item is removed, an item is changed, or an item falls outside of the realized range of the ListView. - **/ - resetItem: (item: T, element: HTMLElement) => void; - - /** - * Gets or sets the distance, in pixels, of the start of the viewable area within the viewport. - **/ - scrollPosition: number; - - /** - * Gets an ISelection that contains the range of currently selected items. - **/ - selection: ISelection; - - /** - * Gets or sets the selection mode of the ListView. - **/ - selectionMode: SelectionMode; - - /** - * Gets or sets how the ListView reacts to the swipe gesture. The swipe gesture can select the swiped items or can have no effect on the current selection. - **/ - swipeBehavior: WinJS.UI.SwipeBehavior; - - /** - * Gets or sets how the ListView reacts when the user taps or clicks an item. - **/ - tapBehavior: TapBehavior; - - /** - * Gets a ZoomableView that supports semantic zoom functionality. This API supports the SemanticZoom infrastructure and is not intended to be used directly from your code. - **/ - zoomableView: IZoomableView>; - - //#endregion Properties - - } - - /** - * Represents a menu flyout for displaying commands. - **/ - class Menu { - //#region Constructors - - /** - * Creates a new Menu object. - * @constructor - * @param element The DOM element that will host the control. - * @param options The set of properties and values to apply to the new Menu. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Occurs immediately after the Menu is hidden. - * @param eventInfo An object that contains information about the event. - **/ - onafterhide(eventInfo: Event): void; - - /** - * Occurs after the Menu is shown. - * @param eventInfo An object that contains information about the event. - **/ - onaftershow(eventInfo: Event): void; - - /** - * Occurs before the Menu is hidden. - * @param eventInfo An object that contains information about the event. - **/ - onbeforehide(eventInfo: Event): void; - - /** - * Occurs before a hidden Menu is shown. - * @param eventInfo An object that contains information about the event. - **/ - onbeforeshow(eventInfo: Event): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. - * @param listener The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Releases resources held by this Menu. Call this method when the Menu is no longer needed. After calling this method, the Menu becomes unusable. - **/ - dispose(): void; - - /** - * Returns the MenuCommand object identified by id. - * @param id The element identifier (ID) of the command to be returned. - * @returns The command identified by id. - **/ - getCommandById(id: string): MenuCommand; - - /** - * Hides the Menu. - **/ - hide(): void; - - /** - * Hides the specified commands of the Menu. - * @param commands The commands to hide. The array elements may be MenuCommand objects, or the string identifiers (IDs) of commands. - * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. - **/ - hideCommands(commands: any[], immediate: boolean): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. - * @param listener The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Shows the Menu, if hidden, regardless of other states. - * @param anchor Required. The DOM element to anchor the Menu. - * @param placement The placement of the Menu to the anchor: top, bottom, left, or right. - * @param alignment For top or bottom placement, the alignment of the Menu to the anchor's edge: center, left, or right. - **/ - show(anchor: HTMLElement, placement: string, alignment: string): void; - - /** - * Shows the specified commands of the Menu. - * @param commands The commands to show. The array elements may be Menu objects, or the string identifiers (IDs) of commands. - * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. - **/ - showCommands(commands: any[], immediate: boolean): void; - - /** - * Shows the specified commands of the Menu while hiding all other commands. - * @param commands The commands to show. The array elements may be MenuCommand objects, or the string identifiers (IDs) of commands. - * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. - **/ - showOnlyCommands(commands: any[], immediate: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the default alignment to be used for this Menu. - **/ - alignment: string; - - /** - * Gets or sets the default anchor to be used for this Menu. - **/ - anchor: HTMLElement; - - /** - * Sets the MenuCommand objects that appear in the menu. - **/ - commands: MenuCommand[]; - - /** - * Gets the DOM element that hosts the Menu. - **/ - element: HTMLElement; - - /** - * Gets a value that indicates whether the Menu is hidden or in the process of becoming hidden. - **/ - hidden: boolean; - - /** - * Gets or sets the default placement to be used for this Menu. - **/ - placement: string; - - //#endregion Properties - - } - - /** - * Represents a command to be displayed in a Menu object. - **/ - class MenuCommand { - //#region Constructors - - /** - * Creates a new MenuCommand object. - * @constructor - * @param element The DOM element that will host the control. - * @param options The set of properties and values to apply to the new MenuCommand. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. - * @param listener The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Disposes this control. - **/ - dispose(): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. - * @param listener The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(type: string, listener: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets a value that indicates whether the MenuCommand is disabled. - **/ - disabled: boolean; - - /** - * Gets the DOM element that hosts the MenuCommand. - **/ - element: HTMLElement; - - /** - * Adds an extra CSS class during construction. - **/ - extraClass: string; - - /** - * Gets or sets the Flyout object displayed by this command. The specified flyout is shown when the MenuCommand's button is invoked. - **/ - flyout: Flyout; - - /** - * Gets a value that indicates whether the MenuCommand is hidden or in the process of becoming hidden. - **/ - hidden: boolean; - - /** - * Gets the element identifier (ID) of the command. - **/ - id: string; - - /** - * Gets or sets the label of the command. - **/ - label: string; - - /** - * Gets or sets the function to be invoked when the command is clicked. - **/ - onclick: Function; - - /** - * Gets or sets the selected state of a toggle button. - **/ - selected: boolean; - - /** - * Gets the type of the command. - **/ - type: string; - - //#endregion Properties - - } - - /** - * Displays navigation commands in a toolbar that the user can show or hide. - **/ - class NavBar { - //#region Constructors - - /** - * Creates a new NavBar. - * @constructor - * @param element The DOM element that will host the new NavBar. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Occurs immediately after the NavBar is hidden. - * @param eventInfo An object that contains information about the event. - **/ - onafterhide(eventInfo: Event): void; - - /** - * Raised after the NavBar is shown. - * @param eventInfo An object that contains information about the event. - **/ - onaftershow(eventInfo: Event): void; - - /** - * Raised just before the NavBar is hidden. - * @param eventInfo An object that contains information about the event. - **/ - onbeforehide(eventInfo: Event): void; - - /** - * Occurs before a hidden NavBar is shown. - * @param eventInfo An object that contains information about the event. - **/ - onbeforeshow(eventInfo: Event): void; - - /** - * Occurs after the NavBar has finished processing its child elements. - * @param eventInfo An object that contains information about the event. - **/ - onchildrenprocessed(eventInfo: Event): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this NavBar. Call this method when the NavBar is no longer needed. After calling this method, the NavBar becomes unusable. - **/ - dispose(): void; - - /** - * Hides the NavBar. - **/ - hide(): void; - - /** - * Hides the specified commands of the NavBar. - * @param commands The commands to hide. The array elements may be NavBarCommand objects, or the string identifiers (IDs) of commands. - * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. - **/ - hideCommands(commands: any[], immediate: boolean): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - /** - * Shows the NavBar if it is not disabled. - **/ - show(): void; - - /** - * Shows the specified commands of the NavBar. - * @param commands The commands to show. The array elements may be NavBarCommand objects, or the string identifiers (IDs) of commands. - * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. - **/ - showCommands(commands: any[], immediate: boolean): void; - - /** - * Shows the specified commands of the NavBar while hiding all other commands. - * @param commands The commands to show. The array elements may be NavBarCommand objects, or the string identifiers (IDs) of commands. - * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. - **/ - showOnlyCommands(commands: any[], immediate: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - commands: AppBarCommand; - - /** - * Gets or sets a value that indicates whether the NavBar is disabled. - **/ - disabled: boolean; - - /** - * Gets the HTML element that hosts this NavBar. - **/ - element: HTMLElement; - - /** - * Gets a value that indicates whether the NavBar is hidden or in the process of becoming hidden. - **/ - hidden: boolean; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - layout: string; - - /** - * Gets or sets a value that specifies whether the NavBar appears at the top or bottom of the main view. - **/ - placement: string; - - /** - * Gets or sets a value that indicates whether the NavBar is sticky (won't light dismiss). If not sticky, the NavBar dismisses normally when the user touches outside of the NavBar. - **/ - sticky: boolean; - - //#endregion Properties - - } - - /** - * Represents a navigation command in a NavBarContainer. - **/ - class NavBarCommand { - //#region Constructors - - /** - * Creates a new NavBarCommand. - * @constructor - * @param element The DOM element hosts the new NavBarCommand. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this NavBarCommand. Call this method when the NavBarCommand is no longer needed. After calling this method, the NavBarCommand becomes unusable. - **/ - dispose(): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets the HTML element that hosts this NavBarCommand. - **/ - element: HTMLElement; - - /** - * Gets or sets the command's icon. - **/ - icon: string; - - /** - * Gets or sets the label of the command. - **/ - label: string; - - /** - * Get or sets the location to navigate to when this command is invoked. - **/ - location: any; - - /** - * Gets or sets a value that specifies whether to show the split tab stop. - **/ - splitButton: boolean; - - /** - * Gets a value that indicates whether the splitButton is open. - **/ - splitOpened: boolean; - - /** - * Gets or sets a user-defined object that represents the state associated with the command's location. - **/ - state: any; - - /** - * Gets or sets the tooltip of the command. - **/ - tooltip: any; - - //#endregion Properties - - } - - /** - * Contains a group of NavBarCommand objects in a NavBar. - **/ - class NavBarContainer { - //#region Constructors - - /** - * Creates a new NavBarContainer. - * @constructor - * @param element The DOM element hosts the new NavBarContainer. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Occurs when a child NavBarCommand object's click event fires. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.navbarcommand, detail.data. - **/ - oninvoked(eventInfo: CustomEvent): void; - - /** - * Occurs when the split button of a child NavBarCommand is opened or closed. A split button is toggled when the user navigates to another page or opens another split button. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.opened, detail.index, detail.navbarcommand, detail.data. - **/ - onsplittoggle(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this NavBarCommand. Call this method when the NavBarCommand is no longer needed. After calling this method, the NavBarCommand becomes unusable. - **/ - dispose(): void; - - /** - * Forces the NavBarContainer to update its layout. Use this function when making the NavBarContainer visible again after you set its style.display property to "none". - **/ - forceLayout(): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the index of the current item. - **/ - currentIndex: number; - - /** - * Gets or sets a WinJS.Binding.List that generates NavBarCommand objects. - **/ - data: WinJS.Binding.List; - - /** - * Gets the HTML element that hosts this NavBarContainer. - **/ - element: HTMLElement; - - /** - * Gets or sets a value that specifies whether NavBarCommand objects in this container use a fixed or dynamic width. - **/ - fixedSize: boolean; - - /** - * Gets or sets a value that specifies whether the NavBarContainer has a horizontal or vertical layout. - **/ - layout: Orientation; - - /** - * Gets or sets a value that specifies how many rows of navigation commands to display on a page. - **/ - maxRows: number; - - /** - * Gets or sets the WinJS.Binding.Template or templating function that creates the DOM elements for each item in the data source. Each item can contain multiple elements, but it must have a single root element. - **/ - template: WinJS.Binding.Template; - - //#endregion Properties - - } - - /** - * Lets the user rate something by clicking an icon that represents a rating. The Rating control can display three types of ratings: an average rating, a tentative rating, and the user's rating. - **/ - class Rating { - //#region Constructors - - /** - * Creates a new Rating. - * @constructor - * @param element The DOM element hosts the new Rating. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the cancel event, add a property named "oncancel" to the options object and set its value to the event handler. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Raised when the user finishes interacting with the rating control without committing a tentative rating. - * @param eventInfo An object that contains information about the event. - **/ - oncancel(eventInfo: Event): void; - - /** - * Raised when the user commits a change to the userRating. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tentativeRating. - **/ - onchange(eventInfo: CustomEvent): void; - - /** - * Raised when the user is choosing a new tentative Rating. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tentativeRating. - **/ - onpreviewchange(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Releases resources held by this Rating. Call this method when the Rating is no longer needed. After calling this method, the Rating becomes unusable. - **/ - dispose(): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the average rating. - **/ - averageRating: number; - - /** - * Gets or sets whether the control is disabled. When the control is disabled, the user can't specify a new user rating or modify an existing rating. - **/ - disabled: boolean; - - /** - * Gets the DOM element that hosts the Rating. - **/ - element: HTMLElement; - - /** - * Gets or sets whether control lets the user clear the rating. - **/ - enableClear: boolean; - - /** - * Gets or sets the maximum possible rating value. - **/ - maxRating: number; - - /** - * Gets or sets a set of descriptions to show for rating values in the tooltip. - **/ - tooltipStrings: string[]; - - /** - * Gets or sets the user's rating. - **/ - userRating: number; - - //#endregion Properties - - } - - /** - * Generates HTML from a set of data. Use this control to generate lists of items. - **/ - class Repeater { - //#region Constructors - - /** - * Creates a new Repeater control. - * @constructor - * @param options An object that contains one or more property/value pairs to apply to the new Repeater. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". - **/ - constructor(options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Raised after an item in the Repeater control's data source changes and after the corresponding DOM element has been updated. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.key, detail.newElement, detail.newItem, detail.newValue, detail.oldElement, detail.oldItem, detail.oldValue, detail.setPromise. - **/ - onitemchanged(eventInfo: CustomEvent): void; - - /** - * Raised after an item in the Repeater control's data source changes but before the corresponding DOM element has been updated. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.key, detail.newElement, detail.newItem, detail.newValue, detail.oldElement, detail.oldItem, detail.oldValue, detail.setPromise. - **/ - onitemchanging(eventInfo: CustomEvent): void; - - /** - * Raised after an item has been added to the Repeater control's data source and after the corresponding DOM element has been added. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.value. - **/ - oniteminserted(eventInfo: CustomEvent): void; - - /** - * Raised after an item has been added to the Repeater control's data source but before the corresponding DOM element has been added. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.value. - **/ - oniteminserting(eventInfo: CustomEvent): void; - - /** - * Raised after an item has been moved from one index to another in the Repeater control's data source and after the corresponding DOM element has been moved. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.oldIndex, detail.newIndex. - **/ - onitemmoved(eventInfo: CustomEvent): void; - - /** - * Raised after an item has been moved from one index to another in the Repeater control's data source but before the corresponding DOM element has been moved. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.oldIndex, detail.newIndex. - **/ - onitemmoving(eventInfo: CustomEvent): void; - - /** - * Raised after an item has been moved from one index to another in the Repeater control's data source and after the corresponding DOM element has been moved. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.item, detail.setPromise. - **/ - onitemremoved(eventInfo: CustomEvent): void; - - /** - * Raised after an item has been removed from the Repeater control's data source but before the corresponding DOM element has been removed. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.item, detail.setPromise. - **/ - onitemremoving(eventInfo: CustomEvent): void; - - /** - * Raised when the Repeater has finished loading a new set of data. This event is only fired on construction. This event is only raised when the Repeater is constructed or its data source or template changes. - * @param eventInfo An object that contains information about the event. - **/ - onitemsloaded(eventInfo: CustomEvent): void; - - /** - * Raised after the Repeater control's underlying data has been updated and after the updated HTML has been reloaded. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElements. - **/ - onitemsreloaded(eventInfo: CustomEvent): void; - - /** - * Raised after the Repeater control's underlying data has been updated but before the updated HTML has been reloaded. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElements, detail.setPromise. - **/ - onitemsreloading(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this Repeater. Call this method when the Repeater is no longer needed. After calling this method, the Repeater becomes unusable. - **/ - dispose(): void; - - /** - * Returns the HTML element for the item at the specified index. - * @param index The index of the item. - * @returns The DOM element for the specified item. - **/ - elementFromIndex(index: number): HTMLElement; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the List that provides the Repeater with items to display. - **/ - data: WinJS.Binding.List; - - /** - * Gets the DOM element that hosts the Repeater. - **/ - element: HTMLElement; - - /** - * Gets the number of items in the Repeater control. - **/ - length: number; - - /** - * Gets or sets a WinJS.Binding.Template or custom rendering function that defines the HTML of each item within the Repeater. - **/ - template: WinJS.Binding.Template; - - //#endregion Properties - - } - - /** - * Enables the user to perform search queries and select suggestions. - **/ - class SearchBox { - //#region Constructors - - /** - * Creates a new SearchBox. - * @constructor - * @param element The DOM element hosts the new SearchBox. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Raised when the user or the app changes the queryText. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.language, detail.queryText, detail.linguisticDetails. - **/ - onquerychanged(eventInfo: CustomEvent): void; - - /** - * Raised awhen the user clicks the search glyph or presses Enter. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.language, detail.queryText, detail.linguisticDetails, detail.keyModifiers. - **/ - onquerysubmitted(eventInfo: CustomEvent): void; - - /** - * Raised when the app automatically redirects focus to the search box. This event can only be raised when the focusOnKeyboardInput property is set to true. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.propertyName. - **/ - onreceivingfocusonkeyboardinput(eventInfo: CustomEvent): void; - - /** - * Raised when the user selects a suggested option for the search. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tag, detail.keyModifiers, detail.storageFile. - **/ - onresultsuggestionschosen(eventInfo: CustomEvent): void; - - /** - * Raised when the system requests search suggestions from this app. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.language, detail.linguisticDetails, detail.queryText, detail.searchSuggestionCollection. - **/ - onsuggestionsrequested(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this SearchBox. Call this method when the SearchBox is no longer needed. After calling this method, the SearchBox becomes unusable. - **/ - dispose(): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - /** - * Specifies whether suggestions based on local files are automatically displayed in the search pane, and defines the criteria that Windows uses to locate and filter these suggestions. - * @param settings The new settings for local content suggestions. - **/ - setLocalContentSuggestionSettings(settings: any): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets whether the first suggestion is chosen when the user presses Enter. - **/ - chooseSuggestionOnEnter: boolean; - - /** - * Gets or sets a value that specifies whether the SearchBox is disabled. If the control is disabled, it won't receive focus. - **/ - disabled: boolean; - - /** - * Gets the DOM element that hosts the SearchBox. - **/ - element: HTMLElement; - - /** - * Gets or sets a value that specifies whether the search box automatically receives focus when the user types into the app window. - **/ - focusOnKeyboardInput: boolean; - - /** - * Gets or sets the placeholder text for the SearchBox. This text is displayed if there is no other text in the input box. - **/ - placeholderText: string; - - /** - * Gets or sets the query text for the SearchBox. - **/ - queryText: string; - - /** - * Gets or sets the search history context. This context is used a secondary key (the app ID is the primary key) for storing search history. - **/ - searchHistoryContext: string; - - /** - * Gets or sets a value that specifies whether search history is disabled. - **/ - searchHistoryDisabled: boolean; - - //#endregion Properties - - } - - /** - * Enables the user to zoom between two different views supplied by two child controls. One child control supplies the zoomed-out view and the other provides the zoomed-in view. - **/ - class SemanticZoom { - //#region Constructors - - /** - * Creates a new SemanticZoom. - * @constructor - * @param element The DOM element that hosts the SemanticZoom. - * @param options An object that contains one or more property/value pairs to apply to the new control. This object can contain these properties: initiallyZoomedOut Boolean, zoomFactor 0.2–0.85. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Occurs when the control zooms in or out. - * @param eventInfo An object that contains information about the event. The detail property of this object is true when the control is zoomed out. Otherwise, it's false. - **/ - onzoomchanged(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this SemanticZoom. Call this method when the SemanticZoom is no longer needed. After calling this method, the SemanticZoom becomes unusable. - **/ - dispose(): void; - - /** - * Forces the SemanticZoom to update its layout. Use this function when making the SemanticZoom visible again after its style.display property had been set to "none". - **/ - forceLayout(): void; - - /** - * Unregisters an event handler for the specified event. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets the DOM element that hosts the SemanticZoom control. - **/ - element: HTMLElement; - - /** - * Gets or a sets a value that specifies whether to display the SemanticZoom zoom out button. - **/ - enableButton: boolean; - - /** - * Determines whether any controls contained in a SemanticZoom should be processed separately. This property is always true, meaning that the SemanticZoom takes care of processing its own controls. - **/ - isDeclarativeControlContainer: boolean; - - /** - * Gets or sets a value that indicates whether SemanticZoom is locked and zooming between views is disabled. - **/ - locked: boolean; - - /** - * Gets or sets a value that indicates whether the control is zoomed out. - **/ - zoomedOut: boolean; - - /** - * Gets or sets a value that specifies how much the scaling the cross-fade animation performs when the SemanticZoom transitions between views. - **/ - zoomFactor: number; - - //#endregion Properties - - } - - /** - * Provides users with fast, in-context access to settings that affect the current Windows Store app. - **/ - class SettingsFlyout { - //#region Constructors - - /** - * Creates a new SettingsFlyout object. - * @constructor - * @param element The DOM element that will host the control. - * @param options The set of properties and values to apply to the new SettingsFlyout. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Raised immediately after the SettingsFlyout is completely hidden. - * @param eventInfo An object that contains information about the event. - **/ - onafterhide(eventInfo: Event): void; - - /** - * Raised immediately after a SettingsFlyout is fully shown. - * @param eventInfo An object that contains information about the event. - **/ - onaftershow(eventInfo: Event): void; - - /** - * Raised just before hiding a SettingsFlyout. - * @param eventInfo An object that contains information about the event. - **/ - onbeforehide(eventInfo: Event): void; - - /** - * Raised just before showing a SettingsFlyout. - * @param eventInfo An object that contains information about the event. - **/ - onbeforeshow(eventInfo: Event): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. - * @param listener The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this SettingsFlyout. Call this method when the SettingsFlyout is no longer needed. After calling this method, the SettingsFlyout becomes unusable. - **/ - dispose(): void; - - /** - * Hides the SettingsFlyout, if visible, regardless of other states. - **/ - hide(): void; - - /** - * Loads a fragment of the SettingsFlyout. Your app calls this when the user invokes a settings command and the WinJS.Application.onsettings event occurs. - * @param e An object that contains information about the event, received from the WinJS.Application.onsettings event. The detail property of this object contains the applicationcommands sub-property that you set to an array of settings commands. You then populate the SettingsFlyout with these commands by a call to populateSettings. - **/ - static populateSettings(e: CustomEvent): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. - * @param listener The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Shows the SettingsPane UI, if hidden. - **/ - show(): void; - - /** - * Shows the SettingsPane UI, if hidden, regardless of other state. - **/ - static show(): void; - - /** - * Show the Settings flyout using the Settings element identifier (ID) and the path of the page that contains the Settings element. - * @param id The ID of the Settings element. - * @param path The path of the page that contains the Settings element. - **/ - static showSettings(id: string, path: any): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets the DOM element the SettingsFlyout is attached to. - **/ - element: HTMLElement; - - /** - * Gets whether the SettingsFlyout is hidden. - **/ - hidden: boolean; - - /** - * Gets or sets the settings command Id for the SettingsFlyout control. - **/ - settingsCommandId: string; - - /** - * This property may be unavailable or altered in future versions. Use the CSS width property of the element that has the win-settingsflyout class instead. - **/ - width: string; - - //#endregion Properties - - } - - /** - * A type of IListDataSource that provides read-access to an object that implements the IStorageQueryResultBase interface. A StorageDataSource enables you to query and bind to items in the data source. - **/ - class StorageDataSource { - //#region Constructors - - /** - * Creates a new StorageDataSource object. - * @constructor - * @param query The IStorageQueryResultBase that the StorageDataSource obtains its items from. Instead of IStorageQueryResultBase, you can also pass one of these string values: Music, Pictures, Videos, Documents. - * @param options The set of properties and values to apply to the new StorageDataSource. Properties on this object may include: mode , requestedThumbnailSize , thumbnailOptions , synchronous . - **/ - constructor(query: any, options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * Draws the thumbnail for the specified item to the specified img element. - * @param item The item to retrieve the thumbnail for. - * @param image The img element that will display the thumbnail. - * @returns A Promise that completes when the full-quality thumbnail is visible. - **/ - loadThumbnail(item: IItem, image: HTMLImageElement): Promise; - - //#endregion Methods - - } - - /** - * Prevents a DOM sub-tree from receiving tab navigations and focus. - **/ - class TabContainer { - //#region Constructors - - /** - * Creates a new TabContainer. - * @constructor - * @param element The DOM element that hosts the TabContainer control. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties. - **/ - constructor(element: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * Releases resources held by this TabContainer. Call this method when the TabContainer is no longer needed. After calling this method, the TabContainer becomes unusable. - **/ - dispose(): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the child DOM element that receives tab focus. - **/ - childFocus: HTMLElement; - - /** - * Gets or sets the tab index of this container. - **/ - tabIndex: number; - - //#endregion Properties - - } - - /** - * Allows users to select time values. - **/ - class TimePicker { - //#region Constructors - - /** - * Initializes a new instance of a TimePicker control. - * @constructor - * @param element The DOM element associated with the TimePicker control. - * @param options The set of options to be applied initially to the TimePicker control. The options are the following: clock. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Occurs when any of the controls are changed by the user. - * @param eventInfo An object that contains information about the event. - **/ - onchange(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Adds an event listener. - * @param type The type (name) of the event. - * @param listener The function that handles the event. - * @param capture If true, specifies that capture should be initiated, otherwise false. - **/ - addEventListener(type: string, listener: Function, capture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this TimePicker. Call this method when the TimePicker is no longer needed. After calling this method, the TimePicker becomes unusable. - **/ - dispose(): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - raiseEvent(type: string, eventProperties: any): boolean; - - /** - * Removes a listener for the specified event. - * @param type The name of the event for which to remove a listener. - * @param listener The listener. - * @param useCapture Optional. The same value that was passed to addEventListener for this listener. It may be omitted if it was omitted when calling addEventListener. - **/ - removeEventListener(type: string, listener: Function, useCapture?: any): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the type of clock to display (12HourClock or 24HourClock). It defaults to the user setting. - **/ - clock: string; - - /** - * Gets or sets the current time of the TimePicker. Note that the date value is always July 15, 2011. - **/ - current: Date; - - /** - * Specifies whether the TimePicker is disabled. - **/ - disabled: boolean; - - /** - * Gets the DOM element for the TimePicker. - **/ - element: HTMLElement; - - /** - * Gets or sets the display pattern for the hour. The default hour pattern is hour.integer(2). You can change the hour pattern by changing the number of integers displayed. - **/ - hourPattern: string; - - /** - * Gets or sets the minute increment. For example, 15 specifies that the TimePicker minute control should display only the choices 00, 15, 30, 45. - **/ - minuteIncrement: number; - - /** - * Gets or sets the display pattern for the minute. The default minute pattern is minute.integer(2). You can change the minute pattern by changing the number of integers displayed. - **/ - minutePattern: string; - - /** - * Gets or sets the display pattern for the period. The default period pattern is period.abbreviated(2). You can change the period pattern by changing the number of integers displayed. - **/ - periodPattern: string; - - //#endregion Properties - - } - - /** - * A control that lets the user switch an option between two states: on (checked is set to true) and off (checked is set to false). - **/ - class ToggleSwitch { - //#region Constructors - - /** - * Creates a new ToggleSwitch. - * @constructor - * @param element The DOM that hosts the control. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the change event, add a property named "onchange" to the options object and set its value to the event handler. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Occurs when the ToggleSwitch control is flipped to on (checked == true) or off (checked == false). - * @param eventInfo An object that contains information about the event. - **/ - onchange(eventInfo: Event): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this ToggleSwitch. Call this method when the ToggleSwitch is no longer needed. After calling this method, the ToggleSwitch becomes unusable. - **/ - dispose(): void; - - /** - * Handles the specified event. - * @param event The event. - **/ - handleEvent(event: any): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - raiseEvent(type: string, eventProperties: any): boolean; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets a value that specifies whether the control is on or off. - **/ - checked: boolean; - - /** - * Gets or sets a value that specifies whether the control is disabled. - **/ - disabled: boolean; - - /** - * Gets the DOM element that hosts the ToggleSwitch. - **/ - element: HTMLElement; - - /** - * Gets or sets the text that displays when the ToggleSwitch is off (checked is set to false). - **/ - labelOff: string; - - /** - * Gets or sets the text that displays when the ToggleSwitch is on (checked is set to true). - **/ - labelOn: string; - - /** - * Gets or sets the main text for the ToggleSwitch control. This text is always displayed, regardless of whether the control is switched on or off. - **/ - title: string; - - //#endregion Properties - - } - - /** - * Displays a tooltip that can contain images and formatting. - **/ - class Tooltip { - //#region Constructors - - /** - * Creates a new Tooltip. - * @constructor - * @param element The DOM element associated that hosts the Tooltip. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the opened event, add a property named "onopened" to the options object and set its value to the event handler. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Raised just before the Tooltip is hidden. - * @param eventInfo An object that contains information about the event. - **/ - onbeforeclose(eventInfo: CustomEvent): void; - - /** - * Raised just before the Tooltip appears. - * @param eventInfo An object that contains information about the event. - **/ - onbeforeopen(eventInfo: CustomEvent): void; - - /** - * Raised when the Tooltip is no longer displayed. - * @param eventInfo An object that contains information about the event. - **/ - onclosed(eventInfo: CustomEvent): void; - - /** - * Raised when the Tooltip is shown. - * @param eventInfo An object that contains information about the event. - **/ - onopened(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Adds an event handler for the specified event. - * @param eventName The name of the event to handle. - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Hides the Tooltip. - **/ - close(): void; - - /** - * Releases resources held by this Tooltip. Call this method when the Tooltip is no longer needed. After calling this method, the Tooltip becomes unusable. - **/ - dispose(): void; - - /** - * Shows the Tooltip. - * @param type A value that specifies when to show the Tooltip. The default value is "mousedown". - **/ - open(type?: string): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the HTML element that is the content of the Tooltip. - **/ - contentElement: HTMLElement; - - /** - * Gets the DOM element that hosts the Tooltip control. - **/ - element: HTMLElement; - - /** - * Gets or appends additional CSS classes to apply to the element that hosts the Tooltip. - **/ - extraClass: string; - - /** - * Gets or sets a value that specifies whether the Tooltip is an infotip, a tooltip that contains a lot of info and should be displayed for longer than a typical Tooltip. - **/ - infotip: boolean; - - /** - * Gets or sets the HTML content of the Tooltip. - **/ - innerHTML: string; - - /** - * Gets or sets the position for the Tooltip relative to its target element: top, bottom, left or right. - **/ - placement: string; - - //#endregion Properties - - } - - /** - * Scales a single child element to fill the available space without resizing it. This control reacts to changes in the size of the container as well as changes in size of the child element. For example, a media query may result in a change in aspect ratio. - **/ - class ViewBox { - //#region Constructors - - /** - * Initializes a new instance of the ViewBox control. - * @constructor - * @param element The DOM element that functions as the scaling box. This element fills 100% of the width and height allotted to it. - * @param options The set of options to be applied initially to the ViewBox control. There are currently no options on this control, and any options included in this parameter are ignored. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * Adds an event handler for the specified event. - * @param eventName The name of the event to handle. - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Releases resources held by this ViewBox. Call this method when the ViewBox is no longer needed. After calling this method, the ViewBox becomes unusable. - **/ - dispose(): void; - - /** - * Forces the ViewBox to update its layout. Use this function when making the ViewBox visible again after its style.display property had been set to "none". - **/ - forceLayout(): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets the DOM element that functions as the scaling box. - **/ - element: HTMLElement; - - //#endregion Properties - - } - - /** - * Serves as the base class for a custom IListDataSource. - **/ - class VirtualizedDataSource { - //#region Constructors - - /** - * Initializes the VirtualizedDataSource base class of a custom data source. - * @constructor - * @param listDataAdapter The object that supplies data to the VirtualizedDataSource. - * @param options An object that can contain properties that specify additional options for the VirtualizedDataSource. It supports these properties: cacheSize. - **/ - constructor(listDataAdapter: IListDataAdapter, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Occurs when the status of the VirtualizedDataSource changes. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: status. - **/ - statuschanged(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. See the VirtualizedDataSource object page for a list of events. Note that you drop the "on" when specifying the event name for the addEventListener method. For example, instead of specifying "onstatuschanged", you specify "statuschanged". - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. See the VirtualizedDataSource object page for a list of events. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - } - - //#endregion Objects - - //#region Functions - - /** - * Returns a new IListDataSource that adds group information to the items of another IListDataSource. - * @param listDataSource The data source for the individual items to group. - * @param groupKey A callback function that accepts a single argument: an item in the IListDataSource. The function is called for each item in the list and must return the group key for that item as a string. - * @param groupData A callback function that accepts a single argument: an item in the IListDataSource. The function is called on one IListDataSource item for each group and must return an object that represents the header of that group. - * @param options An object that can contain properties that specify additional options: groupCountEstimate, batchSize. - * @returns An IListDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. - **/ - function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListDataSource; - - /** - * Used to disables all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be disabled, as the determination is made based on several factors. - **/ - function disableAnimations(): void; - - /** - * Used to enable all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be enabled, as the determination is made based on several factors. - **/ - function enableAnimations(): void; - - /** - * Marks a event handler function as being compatible with declarative processing. - * @param handler The handler to be marked as compatible with declarative processing. - * @returns The handler, marked as compatible with declarative processing. - **/ - function eventHandler(handler: any): any; - - /** - * Asynchronously executes a collection of CSS animations on a collection of elements. This is the underlying animation mechanism used by the Animations Library. Apps are encouraged to use the Animations Library to conform with the standard look and feel of the rest of the system, rather than calling this function directly. - * @param element Element or elements to be animated. This parameter can be expressed in several ways: As the special value "undefined", which means that the animation has no target, As a single object, As a JavaScript array (possibly empty), in which each element of the array can be a single element or a JavaScript array of elements., As a NodeList (for example, the result of querySelectorAll), As an HTMLCollection. - * @param animation The animation description or an array of animation descriptions to apply to element. An animation description is a JavaScript object with specific properties, listed below. There are two types of animation descriptions: one for keyframe-based animations and one for explicit animations. These types are distinguished by whether the keyframe property has a defined value. The following properties are required for both types of animation descriptions: property (string), delay (number), duration (number), timing (string). If an animation has a keyframe property with a defined, non-null value, then the animation is a keyframe-based animation. A keyframe-based animation description requires the following property in addition to those mentioned above: keyframe (string). If an animation does not have a keyframe property, or if the value of the property is null or undefined, then the animation is an explicit animation. An explicit animation description requires the following properties in addition to the common properties mentioned above: from, to. The values given in the from and to properties must be valid for the CSS property specified by the property property. For example, if the CSS property is "opacity", then the from and to properties must be numbers between 0 and 1 (inclusive). - * @returns Returns a Promise object that completes when the CSS animation is complete. - **/ - function executeAnimation(element: HTMLElement, animation: any): Promise; - - /** - * Asynchronously executes a collection of CSS transitions on a collection of elements. This is the underlying animation mechanism used by the Animations Library. Apps are encouraged to use the Animations Library to conform with the standard look and feel of the rest of the system, rather than calling this function directly. - * @param element Element or elements on which to perform the transition. This parameter can be expressed in several ways: As the special value "undefined", which means that the transition has no target, As a single object, As a JavaScript array (possibly empty), in which each element of the array can be a single element or a JavaScript array of elements., As a NodeList (for example, the result of querySelectorAll), As an HTMLCollection. - * @param transition The transition description or an array of transition descriptions to apply to element. A transition description is a JavaScript object with these properties: property (string), delay (number), duration (number), timing (string), from (optional), to. The values given in the from and to properties must be valid for the CSS property specified by the property property. For example, if the CSS property is "opacity", then the from and to properties must be numbers between 0 and 1 (inclusive). - * @returns Returns a Promise that completes when the transition is finished. - **/ - function executeTransition(element: HTMLElement, transition: any): Promise; - - /** - * Retrieves the items in the specified index range. - * @param dataSource The data source that contains the items to retrieve. - * @param ranges An array of ISelectionRange objects that have firstIndex and lastIndex values. - * @returns A Promise that contains an array of the requested IItem objects. - **/ - function getItemsFromRanges(dataSource: IListDataSource, ranges: ISelectionRange[]): Promise>; - - /** - * Determines whether the Animations Library and ListView animations will be performed if called. - * @returns Returns true if animations will be performed; otherwise false. - **/ - function isAnimationEnabled(): boolean; - - /** - * Applies declarative control binding to all elements, starting at the specified root element. - * @param rootElement The element at which to start applying the binding. If this parameter is not specified, the binding is applied to the entire document. - * @param skipRoot If true, the elements to be bound skip the specified root element and include only the children. - * @returns A promise that is fulfilled when binding has been applied to all the controls. - **/ - function processAll(rootElement?: Element, skipRoot?: boolean): Promise; - - /** - * Applies declarative control binding to the specified element. - * @param element The element to bind. - * @returns A promise that is fulfilled after the control is activated. The value of the promise is the control that is attached to element. - **/ - function process(element: Element): Promise; - - /** - * Walks the DOM tree from the given element to the root of the document. Whenever a selector scope is encountered, this method performs a lookup within that scope for the specified selector string. The first matching element is returned. - * @param selector The selector string. - * @param element The element to begin walking to the root of the document from. - * @returns The target element, if found. - **/ - function scopedSelect(selector: string, element: HTMLElement): HTMLElement; - - /** - * Adds the set of declaratively specified options (properties and events) to the specified control. If name of the options property begins with "on", the property value is a function and the control supports addEventListener. setControl calls addEventListener on the control. - * @param control The control on which the properties and events are to be applied. - * @param options The set of options that are specified declaratively. - **/ - function setOptions(control: any, options?: any): void; - - //#endregion Functions + /** + * Gets the HTML element that hosts this ListView. + **/ + element: HTMLElement; + + /** + * Gets or sets the data source that contains the groups for the items in the itemDataSource. + **/ + groupDataSource: IListDataSource; + + /** + * Gets or sets how the ListView reacts when the user taps or clicks a group header. + **/ + groupHeaderTapBehavior: GroupHeaderTapBehavior; + + /** + * Gets or sets the Template or function that creates the DOM elements for each group header in the groupDataSource. Each group header can contain multiple elements, but it must have a single root element. + **/ + groupHeaderTemplate: any; + + /** + * Gets or sets the first visible item. + **/ + indexOfFirstVisible: number; + + /** + * Gets the index of the last visible item in the ListView. + **/ + indexOfLastVisible: number; + + /** + * Gets or sets the data source that provides the ListView with items. + **/ + itemDataSource: IListDataSource; + + /** + * Go Gets or sets a value that specifies whether items can be dragged. When this is set to true the ListView provides built in behaviors related to item dragging. + **/ + itemsDraggable: boolean; + + /** + * Gets or sets whether the ListView control's items can be reordered within itself by dragging and dropping. + **/ + itemsReorderable: boolean; + + /** + * Gets or sets the WinJS.Binding.Template or templating function that creates the DOM elements for each item in the itemDataSource. Each item can contain multiple elements, but it must have a single root element. + **/ + itemTemplate: any; + + /** + * Gets or sets an object that controls the layout of the ListView. + **/ + layout: ILayout2; + + /** + * Gets or sets a value that specifies how the ListView fetches items and adds and removes them to the DOM. Don't change the value of this property after the ListView has begun loading data. + **/ + loadingBehavior: string; + + /** + * Gets a value that indicates whether the ListView is still loading or whether loading is complete. + **/ + loadingState: string; + + /** + * Gets or sets the maximum number of realized items. + **/ + maxDeferredItemCleanup: number; + + /** + * Gets or sets the number of pages to load when the loadingBehavior property is set to "incremental" and the user scrolls beyond the threshold specified by the pagesToLoadThreshold property. + **/ + pagesToLoad: number; + + /** + * Gets or sets the threshold (in pages) for initiating an incremental load. When the last visible item is within the specified number of pages from the end of the loaded portion of the list, and if automaticallyLoadPages is true and loadingBehavior is set to "incremental", the ListView initiates an incremental load. + **/ + pagesToLoadThreshold: number; + + /** + * Gets or sets the function that is called when the ListView discards or recycles the element representation of a group header. + **/ + resetGroupHeader: (header: any, element: HTMLElement) => void; + + /** + * Gets or sets the function that is called when an item is removed, an item is changed, or an item falls outside of the realized range of the ListView. + **/ + resetItem: (item: T, element: HTMLElement) => void; + + /** + * Gets or sets the distance, in pixels, of the start of the viewable area within the viewport. + **/ + scrollPosition: number; + + /** + * Gets an ISelection that contains the range of currently selected items. + **/ + selection: ISelection; + + /** + * Gets or sets the selection mode of the ListView. + **/ + selectionMode: SelectionMode; + + /** + * Gets or sets how the ListView reacts to the swipe gesture. The swipe gesture can select the swiped items or can have no effect on the current selection. + **/ + swipeBehavior: WinJS.UI.SwipeBehavior; + + /** + * Gets or sets how the ListView reacts when the user taps or clicks an item. + **/ + tapBehavior: TapBehavior; + + /** + * Gets a ZoomableView that supports semantic zoom functionality. This API supports the SemanticZoom infrastructure and is not intended to be used directly from your code. + **/ + zoomableView: IZoomableView>; + + //#endregion Properties + + } + + /** + * Represents a menu flyout for displaying commands. + **/ + class Menu { + //#region Constructors + + /** + * Creates a new Menu object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new Menu. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs immediately after the Menu is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Occurs after the Menu is shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Occurs before the Menu is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Occurs before a hidden Menu is shown. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this Menu. Call this method when the Menu is no longer needed. After calling this method, the Menu becomes unusable. + **/ + dispose(): void; + + /** + * Returns the MenuCommand object identified by id. + * @param id The element identifier (ID) of the command to be returned. + * @returns The command identified by id. + **/ + getCommandById(id: string): MenuCommand; + + /** + * Hides the Menu. + **/ + hide(): void; + + /** + * Hides the specified commands of the Menu. + * @param commands The commands to hide. The array elements may be MenuCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. + **/ + hideCommands(commands: any[], immediate: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the Menu, if hidden, regardless of other states. + * @param anchor Required. The DOM element to anchor the Menu. + * @param placement The placement of the Menu to the anchor: top, bottom, left, or right. + * @param alignment For top or bottom placement, the alignment of the Menu to the anchor's edge: center, left, or right. + **/ + show(anchor: HTMLElement, placement: string, alignment: string): void; + + /** + * Shows the specified commands of the Menu. + * @param commands The commands to show. The array elements may be Menu objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. + **/ + showCommands(commands: any[], immediate: boolean): void; + + /** + * Shows the specified commands of the Menu while hiding all other commands. + * @param commands The commands to show. The array elements may be MenuCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. + **/ + showOnlyCommands(commands: any[], immediate: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the default alignment to be used for this Menu. + **/ + alignment: string; + + /** + * Gets or sets the default anchor to be used for this Menu. + **/ + anchor: HTMLElement; + + /** + * Sets the MenuCommand objects that appear in the menu. + **/ + commands: MenuCommand[]; + + /** + * Gets the DOM element that hosts the Menu. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the Menu is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the default placement to be used for this Menu. + **/ + placement: string; + + //#endregion Properties + + } + + /** + * Represents a command to be displayed in a Menu object. + **/ + class MenuCommand { + //#region Constructors + + /** + * Creates a new MenuCommand object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new MenuCommand. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Disposes this control. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that indicates whether the MenuCommand is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the MenuCommand. + **/ + element: HTMLElement; + + /** + * Adds an extra CSS class during construction. + **/ + extraClass: string; + + /** + * Gets or sets the Flyout object displayed by this command. The specified flyout is shown when the MenuCommand's button is invoked. + **/ + flyout: Flyout; + + /** + * Gets a value that indicates whether the MenuCommand is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets the element identifier (ID) of the command. + **/ + id: string; + + /** + * Gets or sets the label of the command. + **/ + label: string; + + /** + * Gets or sets the function to be invoked when the command is clicked. + **/ + onclick: Function; + + /** + * Gets or sets the selected state of a toggle button. + **/ + selected: boolean; + + /** + * Gets the type of the command. + **/ + type: string; + + //#endregion Properties + + } + + /** + * Displays navigation commands in a toolbar that the user can show or hide. + **/ + class NavBar { + //#region Constructors + + /** + * Creates a new NavBar. + * @constructor + * @param element The DOM element that will host the new NavBar. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs immediately after the NavBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Raised after the NavBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Raised just before the NavBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Occurs before a hidden NavBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + /** + * Occurs after the NavBar has finished processing its child elements. + * @param eventInfo An object that contains information about the event. + **/ + onchildrenprocessed(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this NavBar. Call this method when the NavBar is no longer needed. After calling this method, the NavBar becomes unusable. + **/ + dispose(): void; + + /** + * Hides the NavBar. + **/ + hide(): void; + + /** + * Hides the specified commands of the NavBar. + * @param commands The commands to hide. The array elements may be NavBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. + **/ + hideCommands(commands: any[], immediate: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + /** + * Shows the NavBar if it is not disabled. + **/ + show(): void; + + /** + * Shows the specified commands of the NavBar. + * @param commands The commands to show. The array elements may be NavBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. + **/ + showCommands(commands: any[], immediate: boolean): void; + + /** + * Shows the specified commands of the NavBar while hiding all other commands. + * @param commands The commands to show. The array elements may be NavBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. + **/ + showOnlyCommands(commands: any[], immediate: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + commands: AppBarCommand; + + /** + * Gets or sets a value that indicates whether the NavBar is disabled. + **/ + disabled: boolean; + + /** + * Gets the HTML element that hosts this NavBar. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the NavBar is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + layout: string; + + /** + * Gets or sets a value that specifies whether the NavBar appears at the top or bottom of the main view. + **/ + placement: string; + + /** + * Gets or sets a value that indicates whether the NavBar is sticky (won't light dismiss). If not sticky, the NavBar dismisses normally when the user touches outside of the NavBar. + **/ + sticky: boolean; + + //#endregion Properties + + } + + /** + * Represents a navigation command in a NavBarContainer. + **/ + class NavBarCommand { + //#region Constructors + + /** + * Creates a new NavBarCommand. + * @constructor + * @param element The DOM element hosts the new NavBarCommand. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this NavBarCommand. Call this method when the NavBarCommand is no longer needed. After calling this method, the NavBarCommand becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the HTML element that hosts this NavBarCommand. + **/ + element: HTMLElement; + + /** + * Gets or sets the command's icon. + **/ + icon: string; + + /** + * Gets or sets the label of the command. + **/ + label: string; + + /** + * Get or sets the location to navigate to when this command is invoked. + **/ + location: any; + + /** + * Gets or sets a value that specifies whether to show the split tab stop. + **/ + splitButton: boolean; + + /** + * Gets a value that indicates whether the splitButton is open. + **/ + splitOpened: boolean; + + /** + * Gets or sets a user-defined object that represents the state associated with the command's location. + **/ + state: any; + + /** + * Gets or sets the tooltip of the command. + **/ + tooltip: any; + + //#endregion Properties + + } + + /** + * Contains a group of NavBarCommand objects in a NavBar. + **/ + class NavBarContainer { + //#region Constructors + + /** + * Creates a new NavBarContainer. + * @constructor + * @param element The DOM element hosts the new NavBarContainer. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when a child NavBarCommand object's click event fires. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.navbarcommand, detail.data. + **/ + oninvoked(eventInfo: CustomEvent): void; + + /** + * Occurs when the split button of a child NavBarCommand is opened or closed. A split button is toggled when the user navigates to another page or opens another split button. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.opened, detail.index, detail.navbarcommand, detail.data. + **/ + onsplittoggle(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this NavBarCommand. Call this method when the NavBarCommand is no longer needed. After calling this method, the NavBarCommand becomes unusable. + **/ + dispose(): void; + + /** + * Forces the NavBarContainer to update its layout. Use this function when making the NavBarContainer visible again after you set its style.display property to "none". + **/ + forceLayout(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the index of the current item. + **/ + currentIndex: number; + + /** + * Gets or sets a WinJS.Binding.List that generates NavBarCommand objects. + **/ + data: WinJS.Binding.List; + + /** + * Gets the HTML element that hosts this NavBarContainer. + **/ + element: HTMLElement; + + /** + * Gets or sets a value that specifies whether NavBarCommand objects in this container use a fixed or dynamic width. + **/ + fixedSize: boolean; + + /** + * Gets or sets a value that specifies whether the NavBarContainer has a horizontal or vertical layout. + **/ + layout: Orientation; + + /** + * Gets or sets a value that specifies how many rows of navigation commands to display on a page. + **/ + maxRows: number; + + /** + * Gets or sets the WinJS.Binding.Template or templating function that creates the DOM elements for each item in the data source. Each item can contain multiple elements, but it must have a single root element. + **/ + template: WinJS.Binding.Template; + + //#endregion Properties + + } + + /** + * Lets the user rate something by clicking an icon that represents a rating. The Rating control can display three types of ratings: an average rating, a tentative rating, and the user's rating. + **/ + class Rating { + //#region Constructors + + /** + * Creates a new Rating. + * @constructor + * @param element The DOM element hosts the new Rating. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the cancel event, add a property named "oncancel" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the user finishes interacting with the rating control without committing a tentative rating. + * @param eventInfo An object that contains information about the event. + **/ + oncancel(eventInfo: Event): void; + + /** + * Raised when the user commits a change to the userRating. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tentativeRating. + **/ + onchange(eventInfo: CustomEvent): void; + + /** + * Raised when the user is choosing a new tentative Rating. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tentativeRating. + **/ + onpreviewchange(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this Rating. Call this method when the Rating is no longer needed. After calling this method, the Rating becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the average rating. + **/ + averageRating: number; + + /** + * Gets or sets whether the control is disabled. When the control is disabled, the user can't specify a new user rating or modify an existing rating. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the Rating. + **/ + element: HTMLElement; + + /** + * Gets or sets whether control lets the user clear the rating. + **/ + enableClear: boolean; + + /** + * Gets or sets the maximum possible rating value. + **/ + maxRating: number; + + /** + * Gets or sets a set of descriptions to show for rating values in the tooltip. + **/ + tooltipStrings: string[]; + + /** + * Gets or sets the user's rating. + **/ + userRating: number; + + //#endregion Properties + + } + + /** + * Generates HTML from a set of data. Use this control to generate lists of items. + **/ + class Repeater { + //#region Constructors + + /** + * Creates a new Repeater control. + * @constructor + * @param options An object that contains one or more property/value pairs to apply to the new Repeater. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised after an item in the Repeater control's data source changes and after the corresponding DOM element has been updated. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.key, detail.newElement, detail.newItem, detail.newValue, detail.oldElement, detail.oldItem, detail.oldValue, detail.setPromise. + **/ + onitemchanged(eventInfo: CustomEvent): void; + + /** + * Raised after an item in the Repeater control's data source changes but before the corresponding DOM element has been updated. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.key, detail.newElement, detail.newItem, detail.newValue, detail.oldElement, detail.oldItem, detail.oldValue, detail.setPromise. + **/ + onitemchanging(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been added to the Repeater control's data source and after the corresponding DOM element has been added. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.value. + **/ + oniteminserted(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been added to the Repeater control's data source but before the corresponding DOM element has been added. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.value. + **/ + oniteminserting(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been moved from one index to another in the Repeater control's data source and after the corresponding DOM element has been moved. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.oldIndex, detail.newIndex. + **/ + onitemmoved(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been moved from one index to another in the Repeater control's data source but before the corresponding DOM element has been moved. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.oldIndex, detail.newIndex. + **/ + onitemmoving(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been moved from one index to another in the Repeater control's data source and after the corresponding DOM element has been moved. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.item, detail.setPromise. + **/ + onitemremoved(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been removed from the Repeater control's data source but before the corresponding DOM element has been removed. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.item, detail.setPromise. + **/ + onitemremoving(eventInfo: CustomEvent): void; + + /** + * Raised when the Repeater has finished loading a new set of data. This event is only fired on construction. This event is only raised when the Repeater is constructed or its data source or template changes. + * @param eventInfo An object that contains information about the event. + **/ + onitemsloaded(eventInfo: CustomEvent): void; + + /** + * Raised after the Repeater control's underlying data has been updated and after the updated HTML has been reloaded. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElements. + **/ + onitemsreloaded(eventInfo: CustomEvent): void; + + /** + * Raised after the Repeater control's underlying data has been updated but before the updated HTML has been reloaded. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElements, detail.setPromise. + **/ + onitemsreloading(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this Repeater. Call this method when the Repeater is no longer needed. After calling this method, the Repeater becomes unusable. + **/ + dispose(): void; + + /** + * Returns the HTML element for the item at the specified index. + * @param index The index of the item. + * @returns The DOM element for the specified item. + **/ + elementFromIndex(index: number): HTMLElement; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the List that provides the Repeater with items to display. + **/ + data: WinJS.Binding.List; + + /** + * Gets the DOM element that hosts the Repeater. + **/ + element: HTMLElement; + + /** + * Gets the number of items in the Repeater control. + **/ + length: number; + + /** + * Gets or sets a WinJS.Binding.Template or custom rendering function that defines the HTML of each item within the Repeater. + **/ + template: WinJS.Binding.Template; + + //#endregion Properties + + } + + /** + * Enables the user to perform search queries and select suggestions. + **/ + class SearchBox { + //#region Constructors + + /** + * Creates a new SearchBox. + * @constructor + * @param element The DOM element hosts the new SearchBox. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the user or the app changes the queryText. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.language, detail.queryText, detail.linguisticDetails. + **/ + onquerychanged(eventInfo: CustomEvent): void; + + /** + * Raised awhen the user clicks the search glyph or presses Enter. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.language, detail.queryText, detail.linguisticDetails, detail.keyModifiers. + **/ + onquerysubmitted(eventInfo: CustomEvent): void; + + /** + * Raised when the app automatically redirects focus to the search box. This event can only be raised when the focusOnKeyboardInput property is set to true. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.propertyName. + **/ + onreceivingfocusonkeyboardinput(eventInfo: CustomEvent): void; + + /** + * Raised when the user selects a suggested option for the search. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tag, detail.keyModifiers, detail.storageFile. + **/ + onresultsuggestionschosen(eventInfo: CustomEvent): void; + + /** + * Raised when the system requests search suggestions from this app. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.language, detail.linguisticDetails, detail.queryText, detail.searchSuggestionCollection. + **/ + onsuggestionsrequested(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this SearchBox. Call this method when the SearchBox is no longer needed. After calling this method, the SearchBox becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + /** + * Specifies whether suggestions based on local files are automatically displayed in the search pane, and defines the criteria that Windows uses to locate and filter these suggestions. + * @param settings The new settings for local content suggestions. + **/ + setLocalContentSuggestionSettings(settings: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets whether the first suggestion is chosen when the user presses Enter. + **/ + chooseSuggestionOnEnter: boolean; + + /** + * Gets or sets a value that specifies whether the SearchBox is disabled. If the control is disabled, it won't receive focus. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the SearchBox. + **/ + element: HTMLElement; + + /** + * Gets or sets a value that specifies whether the search box automatically receives focus when the user types into the app window. + **/ + focusOnKeyboardInput: boolean; + + /** + * Gets or sets the placeholder text for the SearchBox. This text is displayed if there is no other text in the input box. + **/ + placeholderText: string; + + /** + * Gets or sets the query text for the SearchBox. + **/ + queryText: string; + + /** + * Gets or sets the search history context. This context is used a secondary key (the app ID is the primary key) for storing search history. + **/ + searchHistoryContext: string; + + /** + * Gets or sets a value that specifies whether search history is disabled. + **/ + searchHistoryDisabled: boolean; + + //#endregion Properties + + } + + /** + * Enables the user to zoom between two different views supplied by two child controls. One child control supplies the zoomed-out view and the other provides the zoomed-in view. + **/ + class SemanticZoom { + //#region Constructors + + /** + * Creates a new SemanticZoom. + * @constructor + * @param element The DOM element that hosts the SemanticZoom. + * @param options An object that contains one or more property/value pairs to apply to the new control. This object can contain these properties: initiallyZoomedOut Boolean, zoomFactor 0.2–0.85. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the control zooms in or out. + * @param eventInfo An object that contains information about the event. The detail property of this object is true when the control is zoomed out. Otherwise, it's false. + **/ + onzoomchanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this SemanticZoom. Call this method when the SemanticZoom is no longer needed. After calling this method, the SemanticZoom becomes unusable. + **/ + dispose(): void; + + /** + * Forces the SemanticZoom to update its layout. Use this function when making the SemanticZoom visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Unregisters an event handler for the specified event. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the SemanticZoom control. + **/ + element: HTMLElement; + + /** + * Gets or a sets a value that specifies whether to display the SemanticZoom zoom out button. + **/ + enableButton: boolean; + + /** + * Determines whether any controls contained in a SemanticZoom should be processed separately. This property is always true, meaning that the SemanticZoom takes care of processing its own controls. + **/ + isDeclarativeControlContainer: boolean; + + /** + * Gets or sets a value that indicates whether SemanticZoom is locked and zooming between views is disabled. + **/ + locked: boolean; + + /** + * Gets or sets a value that indicates whether the control is zoomed out. + **/ + zoomedOut: boolean; + + /** + * Gets or sets a value that specifies how much the scaling the cross-fade animation performs when the SemanticZoom transitions between views. + **/ + zoomFactor: number; + + //#endregion Properties + + } + + /** + * Provides users with fast, in-context access to settings that affect the current Windows Store app. + **/ + class SettingsFlyout { + //#region Constructors + + /** + * Creates a new SettingsFlyout object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new SettingsFlyout. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised immediately after the SettingsFlyout is completely hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Raised immediately after a SettingsFlyout is fully shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Raised just before hiding a SettingsFlyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Raised just before showing a SettingsFlyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this SettingsFlyout. Call this method when the SettingsFlyout is no longer needed. After calling this method, the SettingsFlyout becomes unusable. + **/ + dispose(): void; + + /** + * Hides the SettingsFlyout, if visible, regardless of other states. + **/ + hide(): void; + + /** + * Loads a fragment of the SettingsFlyout. Your app calls this when the user invokes a settings command and the WinJS.Application.onsettings event occurs. + * @param e An object that contains information about the event, received from the WinJS.Application.onsettings event. The detail property of this object contains the applicationcommands sub-property that you set to an array of settings commands. You then populate the SettingsFlyout with these commands by a call to populateSettings. + **/ + static populateSettings(e: CustomEvent): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the SettingsPane UI, if hidden. + **/ + show(): void; + + /** + * Shows the SettingsPane UI, if hidden, regardless of other state. + **/ + static show(): void; + + /** + * Show the Settings flyout using the Settings element identifier (ID) and the path of the page that contains the Settings element. + * @param id The ID of the Settings element. + * @param path The path of the page that contains the Settings element. + **/ + static showSettings(id: string, path: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element the SettingsFlyout is attached to. + **/ + element: HTMLElement; + + /** + * Gets whether the SettingsFlyout is hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the settings command Id for the SettingsFlyout control. + **/ + settingsCommandId: string; + + /** + * This property may be unavailable or altered in future versions. Use the CSS width property of the element that has the win-settingsflyout class instead. + **/ + width: string; + + //#endregion Properties + + } + + /** + * A type of IListDataSource that provides read-access to an object that implements the IStorageQueryResultBase interface. A StorageDataSource enables you to query and bind to items in the data source. + **/ + class StorageDataSource { + //#region Constructors + + /** + * Creates a new StorageDataSource object. + * @constructor + * @param query The IStorageQueryResultBase that the StorageDataSource obtains its items from. Instead of IStorageQueryResultBase, you can also pass one of these string values: Music, Pictures, Videos, Documents. + * @param options The set of properties and values to apply to the new StorageDataSource. Properties on this object may include: mode , requestedThumbnailSize , thumbnailOptions , synchronous . + **/ + constructor(query: any, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Draws the thumbnail for the specified item to the specified img element. + * @param item The item to retrieve the thumbnail for. + * @param image The img element that will display the thumbnail. + * @returns A Promise that completes when the full-quality thumbnail is visible. + **/ + loadThumbnail(item: IItem, image: HTMLImageElement): Promise; + + //#endregion Methods + + } + + /** + * Prevents a DOM sub-tree from receiving tab navigations and focus. + **/ + class TabContainer { + //#region Constructors + + /** + * Creates a new TabContainer. + * @constructor + * @param element The DOM element that hosts the TabContainer control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Releases resources held by this TabContainer. Call this method when the TabContainer is no longer needed. After calling this method, the TabContainer becomes unusable. + **/ + dispose(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the child DOM element that receives tab focus. + **/ + childFocus: HTMLElement; + + /** + * Gets or sets the tab index of this container. + **/ + tabIndex: number; + + //#endregion Properties + + } + + /** + * Allows users to select time values. + **/ + class TimePicker { + //#region Constructors + + /** + * Initializes a new instance of a TimePicker control. + * @constructor + * @param element The DOM element associated with the TimePicker control. + * @param options The set of options to be applied initially to the TimePicker control. The options are the following: clock. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when any of the controls are changed by the user. + * @param eventInfo An object that contains information about the event. + **/ + onchange(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener. + * @param type The type (name) of the event. + * @param listener The function that handles the event. + * @param capture If true, specifies that capture should be initiated, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this TimePicker. Call this method when the TimePicker is no longer needed. After calling this method, the TimePicker becomes unusable. + **/ + dispose(): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + raiseEvent(type: string, eventProperties: any): boolean; + + /** + * Removes a listener for the specified event. + * @param type The name of the event for which to remove a listener. + * @param listener The listener. + * @param useCapture Optional. The same value that was passed to addEventListener for this listener. It may be omitted if it was omitted when calling addEventListener. + **/ + removeEventListener(type: string, listener: Function, useCapture?: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the type of clock to display (12HourClock or 24HourClock). It defaults to the user setting. + **/ + clock: string; + + /** + * Gets or sets the current time of the TimePicker. Note that the date value is always July 15, 2011. + **/ + current: Date; + + /** + * Specifies whether the TimePicker is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element for the TimePicker. + **/ + element: HTMLElement; + + /** + * Gets or sets the display pattern for the hour. The default hour pattern is hour.integer(2). You can change the hour pattern by changing the number of integers displayed. + **/ + hourPattern: string; + + /** + * Gets or sets the minute increment. For example, 15 specifies that the TimePicker minute control should display only the choices 00, 15, 30, 45. + **/ + minuteIncrement: number; + + /** + * Gets or sets the display pattern for the minute. The default minute pattern is minute.integer(2). You can change the minute pattern by changing the number of integers displayed. + **/ + minutePattern: string; + + /** + * Gets or sets the display pattern for the period. The default period pattern is period.abbreviated(2). You can change the period pattern by changing the number of integers displayed. + **/ + periodPattern: string; + + //#endregion Properties + + } + + /** + * A control that lets the user switch an option between two states: on (checked is set to true) and off (checked is set to false). + **/ + class ToggleSwitch { + //#region Constructors + + /** + * Creates a new ToggleSwitch. + * @constructor + * @param element The DOM that hosts the control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the change event, add a property named "onchange" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the ToggleSwitch control is flipped to on (checked == true) or off (checked == false). + * @param eventInfo An object that contains information about the event. + **/ + onchange(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this ToggleSwitch. Call this method when the ToggleSwitch is no longer needed. After calling this method, the ToggleSwitch becomes unusable. + **/ + dispose(): void; + + /** + * Handles the specified event. + * @param event The event. + **/ + handleEvent(event: any): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + raiseEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether the control is on or off. + **/ + checked: boolean; + + /** + * Gets or sets a value that specifies whether the control is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the ToggleSwitch. + **/ + element: HTMLElement; + + /** + * Gets or sets the text that displays when the ToggleSwitch is off (checked is set to false). + **/ + labelOff: string; + + /** + * Gets or sets the text that displays when the ToggleSwitch is on (checked is set to true). + **/ + labelOn: string; + + /** + * Gets or sets the main text for the ToggleSwitch control. This text is always displayed, regardless of whether the control is switched on or off. + **/ + title: string; + + //#endregion Properties + + } + + /** + * Displays a tooltip that can contain images and formatting. + **/ + class Tooltip { + //#region Constructors + + /** + * Creates a new Tooltip. + * @constructor + * @param element The DOM element associated that hosts the Tooltip. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the opened event, add a property named "onopened" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised just before the Tooltip is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeclose(eventInfo: CustomEvent): void; + + /** + * Raised just before the Tooltip appears. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeopen(eventInfo: CustomEvent): void; + + /** + * Raised when the Tooltip is no longer displayed. + * @param eventInfo An object that contains information about the event. + **/ + onclosed(eventInfo: CustomEvent): void; + + /** + * Raised when the Tooltip is shown. + * @param eventInfo An object that contains information about the event. + **/ + onopened(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Hides the Tooltip. + **/ + close(): void; + + /** + * Releases resources held by this Tooltip. Call this method when the Tooltip is no longer needed. After calling this method, the Tooltip becomes unusable. + **/ + dispose(): void; + + /** + * Shows the Tooltip. + * @param type A value that specifies when to show the Tooltip. The default value is "mousedown". + **/ + open(type?: string): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the HTML element that is the content of the Tooltip. + **/ + contentElement: HTMLElement; + + /** + * Gets the DOM element that hosts the Tooltip control. + **/ + element: HTMLElement; + + /** + * Gets or appends additional CSS classes to apply to the element that hosts the Tooltip. + **/ + extraClass: string; + + /** + * Gets or sets a value that specifies whether the Tooltip is an infotip, a tooltip that contains a lot of info and should be displayed for longer than a typical Tooltip. + **/ + infotip: boolean; + + /** + * Gets or sets the HTML content of the Tooltip. + **/ + innerHTML: string; + + /** + * Gets or sets the position for the Tooltip relative to its target element: top, bottom, left or right. + **/ + placement: string; + + //#endregion Properties + + } + + /** + * Scales a single child element to fill the available space without resizing it. This control reacts to changes in the size of the container as well as changes in size of the child element. For example, a media query may result in a change in aspect ratio. + **/ + class ViewBox { + //#region Constructors + + /** + * Initializes a new instance of the ViewBox control. + * @constructor + * @param element The DOM element that functions as the scaling box. This element fills 100% of the width and height allotted to it. + * @param options The set of options to be applied initially to the ViewBox control. There are currently no options on this control, and any options included in this parameter are ignored. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Adds an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this ViewBox. Call this method when the ViewBox is no longer needed. After calling this method, the ViewBox becomes unusable. + **/ + dispose(): void; + + /** + * Forces the ViewBox to update its layout. Use this function when making the ViewBox visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that functions as the scaling box. + **/ + element: HTMLElement; + + //#endregion Properties + + } + + /** + * Serves as the base class for a custom IListDataSource. + **/ + class VirtualizedDataSource { + //#region Constructors + + /** + * Initializes the VirtualizedDataSource base class of a custom data source. + * @constructor + * @param listDataAdapter The object that supplies data to the VirtualizedDataSource. + * @param options An object that can contain properties that specify additional options for the VirtualizedDataSource. It supports these properties: cacheSize. + **/ + constructor(listDataAdapter: IListDataAdapter, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the status of the VirtualizedDataSource changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: status. + **/ + statuschanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. See the VirtualizedDataSource object page for a list of events. Note that you drop the "on" when specifying the event name for the addEventListener method. For example, instead of specifying "onstatuschanged", you specify "statuschanged". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. See the VirtualizedDataSource object page for a list of events. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + } + + //#endregion Objects + + //#region Functions + + /** + * Returns a new IListDataSource that adds group information to the items of another IListDataSource. + * @param listDataSource The data source for the individual items to group. + * @param groupKey A callback function that accepts a single argument: an item in the IListDataSource. The function is called for each item in the list and must return the group key for that item as a string. + * @param groupData A callback function that accepts a single argument: an item in the IListDataSource. The function is called on one IListDataSource item for each group and must return an object that represents the header of that group. + * @param options An object that can contain properties that specify additional options: groupCountEstimate, batchSize. + * @returns An IListDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. + **/ + function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListDataSource; + + /** + * Used to disables all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be disabled, as the determination is made based on several factors. + **/ + function disableAnimations(): void; + + /** + * Used to enable all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be enabled, as the determination is made based on several factors. + **/ + function enableAnimations(): void; + + /** + * Marks a event handler function as being compatible with declarative processing. + * @param handler The handler to be marked as compatible with declarative processing. + * @returns The handler, marked as compatible with declarative processing. + **/ + function eventHandler(handler: any): any; + + /** + * Asynchronously executes a collection of CSS animations on a collection of elements. This is the underlying animation mechanism used by the Animations Library. Apps are encouraged to use the Animations Library to conform with the standard look and feel of the rest of the system, rather than calling this function directly. + * @param element Element or elements to be animated. This parameter can be expressed in several ways: As the special value "undefined", which means that the animation has no target, As a single object, As a JavaScript array (possibly empty), in which each element of the array can be a single element or a JavaScript array of elements., As a NodeList (for example, the result of querySelectorAll), As an HTMLCollection. + * @param animation The animation description or an array of animation descriptions to apply to element. An animation description is a JavaScript object with specific properties, listed below. There are two types of animation descriptions: one for keyframe-based animations and one for explicit animations. These types are distinguished by whether the keyframe property has a defined value. The following properties are required for both types of animation descriptions: property (string), delay (number), duration (number), timing (string). If an animation has a keyframe property with a defined, non-null value, then the animation is a keyframe-based animation. A keyframe-based animation description requires the following property in addition to those mentioned above: keyframe (string). If an animation does not have a keyframe property, or if the value of the property is null or undefined, then the animation is an explicit animation. An explicit animation description requires the following properties in addition to the common properties mentioned above: from, to. The values given in the from and to properties must be valid for the CSS property specified by the property property. For example, if the CSS property is "opacity", then the from and to properties must be numbers between 0 and 1 (inclusive). + * @returns Returns a Promise object that completes when the CSS animation is complete. + **/ + function executeAnimation(element: HTMLElement, animation: any): Promise; + + /** + * Asynchronously executes a collection of CSS transitions on a collection of elements. This is the underlying animation mechanism used by the Animations Library. Apps are encouraged to use the Animations Library to conform with the standard look and feel of the rest of the system, rather than calling this function directly. + * @param element Element or elements on which to perform the transition. This parameter can be expressed in several ways: As the special value "undefined", which means that the transition has no target, As a single object, As a JavaScript array (possibly empty), in which each element of the array can be a single element or a JavaScript array of elements., As a NodeList (for example, the result of querySelectorAll), As an HTMLCollection. + * @param transition The transition description or an array of transition descriptions to apply to element. A transition description is a JavaScript object with these properties: property (string), delay (number), duration (number), timing (string), from (optional), to. The values given in the from and to properties must be valid for the CSS property specified by the property property. For example, if the CSS property is "opacity", then the from and to properties must be numbers between 0 and 1 (inclusive). + * @returns Returns a Promise that completes when the transition is finished. + **/ + function executeTransition(element: HTMLElement, transition: any): Promise; + + /** + * Retrieves the items in the specified index range. + * @param dataSource The data source that contains the items to retrieve. + * @param ranges An array of ISelectionRange objects that have firstIndex and lastIndex values. + * @returns A Promise that contains an array of the requested IItem objects. + **/ + function getItemsFromRanges(dataSource: IListDataSource, ranges: ISelectionRange[]): Promise>; + + /** + * Determines whether the Animations Library and ListView animations will be performed if called. + * @returns Returns true if animations will be performed; otherwise false. + **/ + function isAnimationEnabled(): boolean; + + /** + * Applies declarative control binding to all elements, starting at the specified root element. + * @param rootElement The element at which to start applying the binding. If this parameter is not specified, the binding is applied to the entire document. + * @param skipRoot If true, the elements to be bound skip the specified root element and include only the children. + * @returns A promise that is fulfilled when binding has been applied to all the controls. + **/ + function processAll(rootElement?: Element, skipRoot?: boolean): Promise; + + /** + * Applies declarative control binding to the specified element. + * @param element The element to bind. + * @returns A promise that is fulfilled after the control is activated. The value of the promise is the control that is attached to element. + **/ + function process(element: Element): Promise; + + /** + * Walks the DOM tree from the given element to the root of the document. Whenever a selector scope is encountered, this method performs a lookup within that scope for the specified selector string. The first matching element is returned. + * @param selector The selector string. + * @param element The element to begin walking to the root of the document from. + * @returns The target element, if found. + **/ + function scopedSelect(selector: string, element: HTMLElement): HTMLElement; + + /** + * Adds the set of declaratively specified options (properties and events) to the specified control. If name of the options property begins with "on", the property value is a function and the control supports addEventListener. setControl calls addEventListener on the control. + * @param control The control on which the properties and events are to be applied. + * @param options The set of options that are specified declaratively. + **/ + function setOptions(control: any, options?: any): void; + + //#endregion Functions } /** * Provides functions to load HTML content programmatically. **/ declare module WinJS.UI.Fragments { - //#region Functions + //#region Functions - /** - * Starts loading the fragment at the specified location. The returned promise completes when the fragment is ready to be copied. - * @param href The URI that contains the fragment to be copied. - * @returns A promise that is fulfilled when the fragment has been prepared for copying. - **/ - function cache(href: string): Promise; + /** + * Starts loading the fragment at the specified location. The returned promise completes when the fragment is ready to be copied. + * @param href The URI that contains the fragment to be copied. + * @returns A promise that is fulfilled when the fragment has been prepared for copying. + **/ + function cache(href: string): Promise; - /** - * Removes any cached information about the specified fragment. This method does not unload any scripts or styles that are referenced by the fragment. - * @param href The URI that contains the fragment to be cleared. If no URI is provided, the entire contents of the cache are cleared. - **/ - function clearCache(href: string): void; + /** + * Removes any cached information about the specified fragment. This method does not unload any scripts or styles that are referenced by the fragment. + * @param href The URI that contains the fragment to be cleared. If no URI is provided, the entire contents of the cache are cleared. + **/ + function clearCache(href: string): void; - /** - * Loads the contents of the specified URI into the specified element without copying it. - * @param href The URI that contains the fragment to copy. - * @param element Optional. The element to which the fragment is appended. - * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The element is not added to the cache. See also rendercopy, where the element is added to the cache. - **/ - function render(href: string, element?: HTMLElement): Promise; + /** + * Loads the contents of the specified URI into the specified element without copying it. + * @param href The URI that contains the fragment to copy. + * @param element Optional. The element to which the fragment is appended. + * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The element is not added to the cache. See also rendercopy, where the element is added to the cache. + **/ + function render(href: string, element?: HTMLElement): Promise; - /** - * Loads and copies the contents of the specified URI into the specified element. - * @param href The URI that contains the fragment to copy. - * @param target The element to which the fragment is appended. - * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The fragment is added to the cache. See also render, where the element is not added to the cache. - **/ - function renderCopy(href: string, target?: HTMLElement): Promise; + /** + * Loads and copies the contents of the specified URI into the specified element. + * @param href The URI that contains the fragment to copy. + * @param target The element to which the fragment is appended. + * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The fragment is added to the cache. See also render, where the element is not added to the cache. + **/ + function renderCopy(href: string, target?: HTMLElement): Promise; - //#endregion Functions + //#endregion Functions } /** * Provides methods for defining and displaying PageControl objects. **/ declare module WinJS.UI.Pages { - //#region Interfaces + //#region Interfaces - /** - * Provides members for a PageControl. You implement this interface when defining a new PageControl. - **/ - interface IPageControlMembers { - //#region Methods + /** + * Provides members for a PageControl. You implement this interface when defining a new PageControl. + **/ + interface IPageControlMembers { + //#region Methods - /** - * Called if any error occurs during the processing of the page. - * @param err The error that occurred. - * @returns Nothing if the error was handled, or an error promise if the error was not handled. - **/ - error?(err: any): Promise; + /** + * Called if any error occurs during the processing of the page. + * @param err The error that occurred. + * @returns Nothing if the error was handled, or an error promise if the error was not handled. + **/ + error? (err: any): Promise; - /** - * Initializes the control before the content of the control is set. Use the processed method for any initialization that should be done after the content of the control has been set. - * @param element The DOM element that will contain all the content for the page. - * @param options The options passed to the constructor of the page. - * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. - **/ - init?(element: HTMLElement, options: any): Promise; + /** + * Initializes the control before the content of the control is set. Use the processed method for any initialization that should be done after the content of the control has been set. + * @param element The DOM element that will contain all the content for the page. + * @param options The options passed to the constructor of the page. + * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + init? (element: HTMLElement, options: any): Promise; - /** - * Creates DOM objects from the content in the specified URI. This method is called after the PageControl is defined and before the init method is called. - * @param uri The URI from which to create DOM objects. - * @returns A promise whose fulfilled value is the set of unparented DOM objects. - **/ - load?(uri: string): Promise; + /** + * Creates DOM objects from the content in the specified URI. This method is called after the PageControl is defined and before the init method is called. + * @param uri The URI from which to create DOM objects. + * @returns A promise whose fulfilled value is the set of unparented DOM objects. + **/ + load? (uri: string): Promise; - /** - * Initializes the control after the content of the control is set. - * @param element The DOM element that will contain all the content for the page. - * @param options The options that are to be passed to the constructor of the page. - * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. - **/ - processed?(element: HTMLElement, options: any): Promise; + /** + * Initializes the control after the content of the control is set. + * @param element The DOM element that will contain all the content for the page. + * @param options The options that are to be passed to the constructor of the page. + * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + processed? (element: HTMLElement, options: any): Promise; - /** - * Called after all initialization and rendering is complete. At this time, the element is ready for use. - * @param element The DOM element that contains all the content for the page. - * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. - * @returns A promise that is fulfilled when the element is ready for use, if asynchronous processing is necessary. If not, returns nothing. - **/ - ready?(element: HTMLElement, options: any): Promise; + /** + * Called after all initialization and rendering is complete. At this time, the element is ready for use. + * @param element The DOM element that contains all the content for the page. + * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @returns A promise that is fulfilled when the element is ready for use, if asynchronous processing is necessary. If not, returns nothing. + **/ + ready? (element: HTMLElement, options: any): Promise; - /** - * Takes the elements returned by the load method and attaches them to the specified element. - * @param element The DOM element to which the loadResult elements are appended. - * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. - * @param loadResult A Promise that contains the elements returned from the load method. - **/ - render?(element: HTMLElement, options: any, loadResult: Promise): void; + /** + * Takes the elements returned by the load method and attaches them to the specified element. + * @param element The DOM element to which the loadResult elements are appended. + * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @param loadResult A Promise that contains the elements returned from the load method. + **/ + render? (element: HTMLElement, options: any, loadResult: Promise): void; - //#endregion Methods + //#endregion Methods - } + } - //#endregion Interfaces + //#endregion Interfaces - //#region Objects + //#region Objects - /** - * A modular unit of HTML, CSS, and JavaScript that can be navigated to or used as a custom WinJS control. - **/ - class PageControl { - } + /** + * A modular unit of HTML, CSS, and JavaScript that can be navigated to or used as a custom WinJS control. + **/ + class PageControl { + } - //#endregion Objects + //#endregion Objects - //#region Functions + //#region Functions - /** - * Creates a new PageControl from the specified URI that contains the specified members. Multiple calls to this method for the same URI are allowed, and all members will be merged. - * @param uri The URI for the content that defines the page. - * @param members An object that defines the members that the control will have. - * @returns A constructor function that creates the PageControl. - **/ - function define(uri: string, members: IPageControlMembers): PageControl; + /** + * Creates a new PageControl from the specified URI that contains the specified members. Multiple calls to this method for the same URI are allowed, and all members will be merged. + * @param uri The URI for the content that defines the page. + * @param members An object that defines the members that the control will have. + * @returns A constructor function that creates the PageControl. + **/ + function define(uri: string, members: IPageControlMembers): PageControl; - /** - * Gets an already-defined page control for the specified URI, or creates a new one. - * @param uri The URI for the content that defines the page. - * @returns A constructor function that creates the page. - **/ - function get(uri: string): Function; + /** + * Gets an already-defined page control for the specified URI, or creates a new one. + * @param uri The URI for the content that defines the page. + * @returns A constructor function that creates the page. + **/ + function get(uri: string): Function; - /** - * Creates a PageControl from the specified URI and inserts it inside the specified element. - * @param uri The URI for the content that defines the page. - * @param element The DOM element to which the PageControl is appended. - * @param options An object that contains one or more property/value pairs to apply to the new PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. - * @param parentedPromise A Promise that is fulfilled when the new PageControl is done rendering and its contents becomes the child of element. - * @returns A promise that is fulfilled when rendering is complete, if asynchronous processing is necessary. If not, returns nothing. - **/ - function render(uri: string, element: HTMLElement, options?: any, parentedPromise?: Promise): Promise; + /** + * Creates a PageControl from the specified URI and inserts it inside the specified element. + * @param uri The URI for the content that defines the page. + * @param element The DOM element to which the PageControl is appended. + * @param options An object that contains one or more property/value pairs to apply to the new PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @param parentedPromise A Promise that is fulfilled when the new PageControl is done rendering and its contents becomes the child of element. + * @returns A promise that is fulfilled when rendering is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + function render(uri: string, element: HTMLElement, options?: any, parentedPromise?: Promise): Promise; - //#endregion Functions + //#endregion Functions } /** * Provides methods for detecting when the user tabs to or from DOM elements. **/ declare module WinJS.UI.TrackTabBehavior { - //#region Functions + //#region Functions - /** - * Sets the tab order for the specified element within its container. - * @param element The element to update. - * @param tabIndex The index value of the element within its container. - **/ - function attach(element: HTMLElement, tabIndex: number): void; + /** + * Sets the tab order for the specified element within its container. + * @param element The element to update. + * @param tabIndex The index value of the element within its container. + **/ + function attach(element: HTMLElement, tabIndex: number): void; - /** - * Removes the tab order information from the specified element. - * @param element The element to remove tab information from. - **/ - function detatch(element: HTMLElement): void; + /** + * Removes the tab order information from the specified element. + * @param element The element to remove tab information from. + **/ + function detatch(element: HTMLElement): void; - //#endregion Functions + //#endregion Functions } /** * Provides helper functions, for example, functions to add and remove CSS classes. **/ declare module WinJS.Utilities { - //#region Enumerations + //#region Enumerations - /** - * Defines a set of keyboard values. - **/ - enum Key { - /** - * The BACKSPACE key. - **/ - backspace, - /** - * The TAB key. - **/ - tab, - /** - * The ENTER key. - **/ - enter, - /** - * The SHIFT key. - **/ - shift, - /** - * The CTRL key. - **/ - ctrl, - /** - * The ALT key. - **/ - alt, - /** - * The PAUSE key. - **/ - pause, - /** - * The CAPS LOCK key. - **/ - capsLock, - /** - * The ESCAPE key. - **/ - escape, - /** - * The SPACE key. - **/ - space, - /** - * The PAGE UP key. - **/ - pageUp, - /** - * The PAGE DOWN key. - **/ - pageDown, - /** - * The END key. - **/ - end, - /** - * The HOME key. - **/ - home, - /** - * The LEFT ARROW key. - **/ - leftArrow, - /** - * The UP ARROW key. - **/ - upArrow, - /** - * The RIGHT ARROW key. - **/ - rightArrow, - /** - * The DOWN ARROW key. - **/ - downArrow, - /** - * The INSERT key. - **/ - insert, - /** - * The DELETE key. - **/ - deleteKey, - /** - * The 0 key. - **/ - num0, - /** - * The 1 key. - **/ - num1, - /** - * The 2 key. - **/ - num2, - /** - * The 3 key. - **/ - num3, - /** - * The 4 key. - **/ - num4, - /** - * The 5 key. - **/ - num5, - /** - * The 6 key. - **/ - num6, - /** - * The 7 key. - **/ - num7, - /** - * The 8 key. - **/ - num8, - /** - * The 9 key. - **/ - num9, - /** - * The a key. - **/ - a, - /** - * The b key. - **/ - b, - /** - * The c key. - **/ - c, - /** - * The d key. - **/ - d, - /** - * The e key. - **/ - e, - /** - * The f key. - **/ - f, - /** - * The g key. - **/ - g, - /** - * The h key. - **/ - h, - /** - * The i key. - **/ - i, - /** - * The j key. - **/ - j, - /** - * The k key. - **/ - k, - /** - * The l key. - **/ - l, - /** - * The m key. - **/ - m, - /** - * The n key. - **/ - n, - /** - * The o key. - **/ - o, - /** - * The p key. - **/ - p, - /** - * The q key. - **/ - q, - /** - * The r key. - **/ - r, - /** - * The s key. - **/ - s, - /** - * The t key. - **/ - t, - /** - * The u key. - **/ - u, - /** - * The v key. - **/ - v, - /** - * The w key. - **/ - w, - /** - * The x key. - **/ - x, - /** - * The y key. - **/ - y, - /** - * The z key. - **/ - z, - /** - * The left Windows key. - **/ - leftWindows, - /** - * The right Windows key. - **/ - rightWindows, - /** - * The menu key. - **/ - menu, - /** - * The 0 key on the numerical keypad. - **/ - numPad0, - /** - * The 1 key on the numerical keypad. - **/ - numPad1, - /** - * The 2 key on the numerical keypad. - **/ - numPad2, - /** - * The 3 key on the numerical keypad. - **/ - numPad3, - /** - * The 4 key on the numerical keypad. - **/ - numPad4, - /** - * The 5 key on the numerical keypad. - **/ - numPad5, - /** - * The 6 key on the numerical keypad. - **/ - numPad6, - /** - * The 7 key on the numerical keypad. - **/ - numPad7, - /** - * The 8 key on the numerical keypad. - **/ - numPad8, - /** - * The 9 key on the numerical keypad. - **/ - numPad9, - /** - * The multiplication key (*). - **/ - multiply, - /** - * The addition key (+). - **/ - add, - /** - * The subtraction key (-). - **/ - subtract, - /** - * The decimal point key (.) - **/ - decimalPoint, - /** - * The division key (/). - **/ - divide, - /** - * The F1 key. - **/ - F1, - /** - * The F2 key. - **/ - F2, - /** - * The F3 key. - **/ - F3, - /** - * The F4 key. - **/ - F4, - /** - * The F5 key. - **/ - F5, - /** - * The F6 key. - **/ - F6, - /** - * The F7 key. - **/ - F7, - /** - * The F8 key. - **/ - F8, - /** - * The F9 key. - **/ - F9, - /** - * The F10 key. - **/ - F10, - /** - * The F11 key. - **/ - F11, - /** - * The F12 key. - **/ - F12, - /** - * The NUMBER LOCK key. - **/ - numLock, - /** - * The SCROLL LOCK key. - **/ - scrollLock, - /** - * The browser BACK key. - **/ - browserBack, - /** - * The browser FORWARD key. - **/ - browserForward, - /** - * The semicolon key (;). - **/ - semicolon, - /** - * The equals key (=). - **/ - equal, - /** - * The comma key (,). - **/ - comma, - /** - * The dash key (-). - **/ - dash, - /** - * The period key (.). - **/ - period, - /** - * The forward slash key (/). - **/ - forwardSlash, - /** - * The grave accent key (`). - **/ - graveAccent, - /** - * The open bracket key ([). - **/ - openBracket, - /** - * The backslash key (\). - **/ - backSlash, - /** - * The close bracket key (]). - **/ - closeBracket, - /** - * The single quote key ('). - **/ - singleQuote - } + /** + * Defines a set of keyboard values. + **/ + enum Key { + /** + * The BACKSPACE key. + **/ + backspace, + /** + * The TAB key. + **/ + tab, + /** + * The ENTER key. + **/ + enter, + /** + * The SHIFT key. + **/ + shift, + /** + * The CTRL key. + **/ + ctrl, + /** + * The ALT key. + **/ + alt, + /** + * The PAUSE key. + **/ + pause, + /** + * The CAPS LOCK key. + **/ + capsLock, + /** + * The ESCAPE key. + **/ + escape, + /** + * The SPACE key. + **/ + space, + /** + * The PAGE UP key. + **/ + pageUp, + /** + * The PAGE DOWN key. + **/ + pageDown, + /** + * The END key. + **/ + end, + /** + * The HOME key. + **/ + home, + /** + * The LEFT ARROW key. + **/ + leftArrow, + /** + * The UP ARROW key. + **/ + upArrow, + /** + * The RIGHT ARROW key. + **/ + rightArrow, + /** + * The DOWN ARROW key. + **/ + downArrow, + /** + * The INSERT key. + **/ + insert, + /** + * The DELETE key. + **/ + deleteKey, + /** + * The 0 key. + **/ + num0, + /** + * The 1 key. + **/ + num1, + /** + * The 2 key. + **/ + num2, + /** + * The 3 key. + **/ + num3, + /** + * The 4 key. + **/ + num4, + /** + * The 5 key. + **/ + num5, + /** + * The 6 key. + **/ + num6, + /** + * The 7 key. + **/ + num7, + /** + * The 8 key. + **/ + num8, + /** + * The 9 key. + **/ + num9, + /** + * The a key. + **/ + a, + /** + * The b key. + **/ + b, + /** + * The c key. + **/ + c, + /** + * The d key. + **/ + d, + /** + * The e key. + **/ + e, + /** + * The f key. + **/ + f, + /** + * The g key. + **/ + g, + /** + * The h key. + **/ + h, + /** + * The i key. + **/ + i, + /** + * The j key. + **/ + j, + /** + * The k key. + **/ + k, + /** + * The l key. + **/ + l, + /** + * The m key. + **/ + m, + /** + * The n key. + **/ + n, + /** + * The o key. + **/ + o, + /** + * The p key. + **/ + p, + /** + * The q key. + **/ + q, + /** + * The r key. + **/ + r, + /** + * The s key. + **/ + s, + /** + * The t key. + **/ + t, + /** + * The u key. + **/ + u, + /** + * The v key. + **/ + v, + /** + * The w key. + **/ + w, + /** + * The x key. + **/ + x, + /** + * The y key. + **/ + y, + /** + * The z key. + **/ + z, + /** + * The left Windows key. + **/ + leftWindows, + /** + * The right Windows key. + **/ + rightWindows, + /** + * The menu key. + **/ + menu, + /** + * The 0 key on the numerical keypad. + **/ + numPad0, + /** + * The 1 key on the numerical keypad. + **/ + numPad1, + /** + * The 2 key on the numerical keypad. + **/ + numPad2, + /** + * The 3 key on the numerical keypad. + **/ + numPad3, + /** + * The 4 key on the numerical keypad. + **/ + numPad4, + /** + * The 5 key on the numerical keypad. + **/ + numPad5, + /** + * The 6 key on the numerical keypad. + **/ + numPad6, + /** + * The 7 key on the numerical keypad. + **/ + numPad7, + /** + * The 8 key on the numerical keypad. + **/ + numPad8, + /** + * The 9 key on the numerical keypad. + **/ + numPad9, + /** + * The multiplication key (*). + **/ + multiply, + /** + * The addition key (+). + **/ + add, + /** + * The subtraction key (-). + **/ + subtract, + /** + * The decimal point key (.) + **/ + decimalPoint, + /** + * The division key (/). + **/ + divide, + /** + * The F1 key. + **/ + F1, + /** + * The F2 key. + **/ + F2, + /** + * The F3 key. + **/ + F3, + /** + * The F4 key. + **/ + F4, + /** + * The F5 key. + **/ + F5, + /** + * The F6 key. + **/ + F6, + /** + * The F7 key. + **/ + F7, + /** + * The F8 key. + **/ + F8, + /** + * The F9 key. + **/ + F9, + /** + * The F10 key. + **/ + F10, + /** + * The F11 key. + **/ + F11, + /** + * The F12 key. + **/ + F12, + /** + * The NUMBER LOCK key. + **/ + numLock, + /** + * The SCROLL LOCK key. + **/ + scrollLock, + /** + * The browser BACK key. + **/ + browserBack, + /** + * The browser FORWARD key. + **/ + browserForward, + /** + * The semicolon key (;). + **/ + semicolon, + /** + * The equals key (=). + **/ + equal, + /** + * The comma key (,). + **/ + comma, + /** + * The dash key (-). + **/ + dash, + /** + * The period key (.). + **/ + period, + /** + * The forward slash key (/). + **/ + forwardSlash, + /** + * The grave accent key (`). + **/ + graveAccent, + /** + * The open bracket key ([). + **/ + openBracket, + /** + * The backslash key (\). + **/ + backSlash, + /** + * The close bracket key (]). + **/ + closeBracket, + /** + * The single quote key ('). + **/ + singleQuote + } - //#endregion Enumerations + //#endregion Enumerations - //#region Objects + //#region Objects - /** - * A mixin that contains event-related functions. - **/ - var eventMixin: { - //#region Methods + /** + * A mixin that contains event-related functions. + **/ + var eventMixin: { + //#region Methods - /** - * Adds an event listener to the control. - * @param type The type (name) of the event. - * @param listener The listener to invoke when the event gets raised. - * @param useCapture If true, initiates capture, otherwise false. - **/ - addEventListener(type: string, listener: Function, useCapture?: boolean): void; + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture If true, initiates capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; - /** - * Raises an event of the specified type and with the specified additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; - /** - * Removes an event listener from the control. - * @param type The type (name) of the event. - * @param listener The listener to remove. - * @param useCapture true if capture is to be initiated, otherwise false. - **/ - removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true if capture is to be initiated, otherwise false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; - //#endregion Methods + //#endregion Methods - }; + }; - /** - * Represents the result of a query selector, and provides various operations that perform actions over the elements of the collection. - **/ - interface QueryCollection extends Array { - //#region Methods + /** + * Represents the result of a query selector, and provides various operations that perform actions over the elements of the collection. + **/ + interface QueryCollection extends Array { + //#region Methods - /** - * Adds the specified class to all the elements in the collection. - * @param name The name of the class to add. - * @returns This QueryCollection object. - **/ - addClass(name: string): QueryCollection; + /** + * Adds the specified class to all the elements in the collection. + * @param name The name of the class to add. + * @returns This QueryCollection object. + **/ + addClass(name: string): QueryCollection; - /** - * Creates a QueryCollection that contains the children of the specified parent element. - * @param element The parent element. - * @returns The QueryCollection that contains the children of the element. - **/ - children(element: HTMLElement): QueryCollection; + /** + * Creates a QueryCollection that contains the children of the specified parent element. + * @param element The parent element. + * @returns The QueryCollection that contains the children of the element. + **/ + children(element: HTMLElement): QueryCollection; - /** - * Clears the specified style property for all the elements in the collection. - * @param name The name of the style property to be cleared. - * @returns This QueryCollection object. - **/ - clearStyle(name: string): QueryCollection; + /** + * Clears the specified style property for all the elements in the collection. + * @param name The name of the style property to be cleared. + * @returns This QueryCollection object. + **/ + clearStyle(name: string): QueryCollection; - /** - * Creates controls that are attached to the elements in this QueryCollection, if the ctor parameter is a function, or configures the controls that are attached to the elements in this QueryCollection, if the ctor parameter is an object. - * @param ctor If this parameter is a function, it is a constructor function that is used to create controls to attach to the elements. If it is an object, it is the set of options passed to the controls. - * @param options The options passed to the newly-created controls. - * @returns This QueryCollection object. - **/ - control(ctor: any, options?: any): QueryCollection; + /** + * Creates controls that are attached to the elements in this QueryCollection, if the ctor parameter is a function, or configures the controls that are attached to the elements in this QueryCollection, if the ctor parameter is an object. + * @param ctor If this parameter is a function, it is a constructor function that is used to create controls to attach to the elements. If it is an object, it is the set of options passed to the controls. + * @param options The options passed to the newly-created controls. + * @returns This QueryCollection object. + **/ + control(ctor: any, options?: any): QueryCollection; - /** - * Performs an action on each item in the QueryCollection. - * @param callbackFn The action to perform on each item. - * @param thisArg The argument to bind to callbackFn. - * @returns The QueryCollection. - **/ - forEach(callbackFn: (value: T, index: number, array: T[]) => void, thisArg?: any): QueryCollection; + /** + * Performs an action on each item in the QueryCollection. + * @param callbackFn The action to perform on each item. + * @param thisArg The argument to bind to callbackFn. + * @returns The QueryCollection. + **/ + forEach(callbackFn: (value: T, index: number, array: T[]) => void, thisArg?: any): QueryCollection; - /** - * Gets an item from the QueryCollection. - * @param index The index of the item to return. - * @returns A single item from the collection. - **/ - get(index: number): T; + /** + * Gets an item from the QueryCollection. + * @param index The index of the item to return. + * @returns A single item from the collection. + **/ + get(index: number): T; - /** - * Gets an attribute value from the first element in the collection. - * @param name The name of the attribute. - * @returns The value of the attribute. - **/ - getAttribute(name: string): any; + /** + * Gets an attribute value from the first element in the collection. + * @param name The name of the attribute. + * @returns The value of the attribute. + **/ + getAttribute(name: string): any; - /** - * Determines whether the specified class exists on the first element of the collection. - * @param name The name of the class. - * @returns true if the element has the specified class; otherwise, false. - **/ - hasClass(name: string): boolean; + /** + * Determines whether the specified class exists on the first element of the collection. + * @param name The name of the class. + * @returns true if the element has the specified class; otherwise, false. + **/ + hasClass(name: string): boolean; - /** - * Looks up an element by ID and wraps the result in a QueryCollection. - * @param id The ID of the element. - * @returns A QueryCollection that contains the element, if it is found. - **/ - id(id: string): QueryCollection; + /** + * Looks up an element by ID and wraps the result in a QueryCollection. + * @param id The ID of the element. + * @returns A QueryCollection that contains the element, if it is found. + **/ + id(id: string): QueryCollection; - /** - * Adds a set of items to this QueryCollection. - * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. - **/ - include(items: T): void; + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: T): void; - /** - * Adds a set of items to this QueryCollection. - * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. - **/ - include(items: T[]): void; + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: T[]): void; - /** - * Registers the listener for the specified event on all the elements in the collection. - * @param eventType The name of the event. - * @param listener The event handler function to be called when the event occurs. - * @param capture true if capture == true is to be passed to addEventListener; otherwise, false. - **/ - listen(eventType: string, listener: Function, capture?: boolean): void; + /** + * Registers the listener for the specified event on all the elements in the collection. + * @param eventType The name of the event. + * @param listener The event handler function to be called when the event occurs. + * @param capture true if capture == true is to be passed to addEventListener; otherwise, false. + **/ + listen(eventType: string, listener: Function, capture?: boolean): void; - /** - * Executes a query selector on all the elements in the collection and aggregates the result into a QueryCollection. - * @param query The query selector string. - * @returns A QueryCollection object containing the aggregate results of executing the query on all the elements in the collection. - **/ - query(query: any): QueryCollection; + /** + * Executes a query selector on all the elements in the collection and aggregates the result into a QueryCollection. + * @param query The query selector string. + * @returns A QueryCollection object containing the aggregate results of executing the query on all the elements in the collection. + **/ + query(query: any): QueryCollection; - /** - * Removes the specified class from all the elements in the collection. - * @param name The name of the class to be removed. - * @returns his QueryCollection object. - **/ - removeClass(name: string): QueryCollection; + /** + * Removes the specified class from all the elements in the collection. + * @param name The name of the class to be removed. + * @returns his QueryCollection object. + **/ + removeClass(name: string): QueryCollection; - /** - * Unregisters the listener for the specified event on all the elements in the collection. - * @param eventType The name of the event. - * @param listener The event handler function. - * @param capture true if capture == true; otherwise, false. - * @returns This QueryCollection object. - **/ - removeEventListener(eventType: string, listener: Function, capture?: boolean): QueryCollection; + /** + * Unregisters the listener for the specified event on all the elements in the collection. + * @param eventType The name of the event. + * @param listener The event handler function. + * @param capture true if capture == true; otherwise, false. + * @returns This QueryCollection object. + **/ + removeEventListener(eventType: string, listener: Function, capture?: boolean): QueryCollection; - /** - * Sets an attribute value on all the items in the collection. - * @param name The name of the attribute to be set. - * @param value The value of the attribute to be set. - * @returns This QueryCollection object. - **/ - setAttribute(name: string, value: any): QueryCollection; + /** + * Sets an attribute value on all the items in the collection. + * @param name The name of the attribute to be set. + * @param value The value of the attribute to be set. + * @returns This QueryCollection object. + **/ + setAttribute(name: string, value: any): QueryCollection; - /** - * Sets the specified style property for all the elements in the collection. - * @param name The name of the style property. - * @param value The value for the property. - * @returns This QueryCollection object. - **/ - setStyle(name: string, value: any): QueryCollection; + /** + * Sets the specified style property for all the elements in the collection. + * @param name The name of the style property. + * @param value The value for the property. + * @returns This QueryCollection object. + **/ + setStyle(name: string, value: any): QueryCollection; - /** - * Renders a template that is bound to the given data and parented to the elements included in the QueryCollection. If the QueryCollection contains multiple elements, the template is rendered multiple times, once at each element in the QueryCollection per item of data passed. - * @param templateElement The DOM element to which the template control is attached. - * @param data The data to render. If the data is an array (or any other object that has a forEach method) then the template is rendered multiple times, once for each item in the collection. - * @param renderDonePromiseCallback If supplied, this function is called each time the template gets rendered, and is passed a promise that is fulfilled when the template rendering is complete. - * @returns The QueryCollection. - **/ - template(templateElement: HTMLElement, data: any, renderDonePromiseCallback: Function): QueryCollection; + /** + * Renders a template that is bound to the given data and parented to the elements included in the QueryCollection. If the QueryCollection contains multiple elements, the template is rendered multiple times, once at each element in the QueryCollection per item of data passed. + * @param templateElement The DOM element to which the template control is attached. + * @param data The data to render. If the data is an array (or any other object that has a forEach method) then the template is rendered multiple times, once for each item in the collection. + * @param renderDonePromiseCallback If supplied, this function is called each time the template gets rendered, and is passed a promise that is fulfilled when the template rendering is complete. + * @returns The QueryCollection. + **/ + template(templateElement: HTMLElement, data: any, renderDonePromiseCallback: Function): QueryCollection; - /** - * Toggles (adds or removes) the specified class on all the elements in the collection. If the class is present, it is removed; if it is absent, it is added. - * @param name The name of the class to be toggled. - * @returns This QueryCollection object. - **/ - toggleClass(name: string): QueryCollection; + /** + * Toggles (adds or removes) the specified class on all the elements in the collection. If the class is present, it is removed; if it is absent, it is added. + * @param name The name of the class to be toggled. + * @returns This QueryCollection object. + **/ + toggleClass(name: string): QueryCollection; - //#endregion Methods + //#endregion Methods - } + } /** * Constructor support for QueryCollection interface **/ export var QueryCollection: { - new (items: T[]): QueryCollection; - prototype: QueryCollection; - } + new (items: T[]): QueryCollection; + prototype: QueryCollection; + } //#endregion Objects @@ -8048,248 +8048,248 @@ declare module WinJS.Utilities { **/ function addClass(e: T, name: string): T; - /** - * Gets a collection of elements that are the direct children of the specified element. - * @param element The parent element. - * @returns The collection of children of the element. - **/ - function children(element: HTMLElement): QueryCollection; + /** + * Gets a collection of elements that are the direct children of the specified element. + * @param element The parent element. + * @returns The collection of children of the element. + **/ + function children(element: HTMLElement): QueryCollection; - /** - * Converts a CSS positioning string for the specified element to pixels. - * @param element The element. - * @param value The CSS positioning string. - * @returns The number of pixels. - **/ - function convertToPixels(element: HTMLElement, value: string): number; + /** + * Converts a CSS positioning string for the specified element to pixels. + * @param element The element. + * @param value The CSS positioning string. + * @returns The number of pixels. + **/ + function convertToPixels(element: HTMLElement, value: string): number; - /** - * Creates an object that has one event for each name passed to the function. - * @param events A variable list of property names. - * @returns The object with the specified properties. The names of the properties are prefixed with 'on'. - **/ - function createEventProperties(...events: string[]): any; + /** + * Creates an object that has one event for each name passed to the function. + * @param events A variable list of property names. + * @returns The object with the specified properties. The names of the properties are prefixed with 'on'. + **/ + function createEventProperties(...events: string[]): any; - /** - * Gets the data value associated with the specified element. - * @param element The element. - * @returns The value associated with the element. - **/ - function data(element: HTMLElement): any; + /** + * Gets the data value associated with the specified element. + * @param element The element. + * @returns The value associated with the element. + **/ + function data(element: HTMLElement): any; - /** - * Disposes all first-generation disposable elements that are descendents of the specified element. The specified element itself is not disposed. - * @param element The root element whose sub-tree is to be disposed. - **/ - function disposeSubTree(element: HTMLElement): void; + /** + * Disposes all first-generation disposable elements that are descendents of the specified element. The specified element itself is not disposed. + * @param element The root element whose sub-tree is to be disposed. + **/ + function disposeSubTree(element: HTMLElement): void; - /** - * Removes all the child nodes from the specified element. - * @param element The element. - * @returns The element. - **/ - function empty(element: T): T; + /** + * Removes all the child nodes from the specified element. + * @param element The element. + * @returns The element. + **/ + function empty(element: T): T; - /** - * Determines whether the specified event occurred within the specified element. - * @param element The element. - * @param event The event. - * @returns true if the event occurred within the element; otherwise, false. - **/ - function eventWithinElement(element: HTMLElement, event: Event): boolean; + /** + * Determines whether the specified event occurred within the specified element. + * @param element The element. + * @param event The event. + * @returns true if the event occurred within the element; otherwise, false. + **/ + function eventWithinElement(element: HTMLElement, event: Event): boolean; - /** - * Adds tags and type to a logging message. - * @param message The message to be formatted. - * @param tag The tag(s) to be applied to the message. Multiple tags should be separated by spaces. - * @param type The type of the message. - * @returns The formatted message. - **/ - function formatLog(message: string, tag: string, type: string): string; + /** + * Adds tags and type to a logging message. + * @param message The message to be formatted. + * @param tag The tag(s) to be applied to the message. Multiple tags should be separated by spaces. + * @param type The type of the message. + * @returns The formatted message. + **/ + function formatLog(message: string, tag: string, type: string): string; - /** - * Gets the height of the content of the specified element. The content height does not include borders or padding. - * @param element The element. - * @returns The content height of the element. - **/ - function getContentHeight(element: HTMLElement): number; + /** + * Gets the height of the content of the specified element. The content height does not include borders or padding. + * @param element The element. + * @returns The content height of the element. + **/ + function getContentHeight(element: HTMLElement): number; - /** - * Gets the width of the content of the specified element. The content width does not include borders or padding. - * @param element The element. - * @returns The content width of the element. - **/ - function getContentWidth(element: HTMLElement): number; + /** + * Gets the width of the content of the specified element. The content width does not include borders or padding. + * @param element The element. + * @returns The content width of the element. + **/ + function getContentWidth(element: HTMLElement): number; - /** - * Gets the leaf-level type or namespace specified by the name parameter. - * @param name The name of the member. - * @param root The root to start in. Defaults to the global object. - * @returns The leaf-level type or namespace in the specified parent namespace. - **/ - function getMember(name: string, root?: any): any; + /** + * Gets the leaf-level type or namespace specified by the name parameter. + * @param name The name of the member. + * @param root The root to start in. Defaults to the global object. + * @returns The leaf-level type or namespace in the specified parent namespace. + **/ + function getMember(name: string, root?: any): any; - /** - * Gets the position of the specified element. - * @param element The element. - * @returns An object that contains the left, top, width and height properties of the element. - **/ - function getPosition(element: HTMLElement): IPosition; + /** + * Gets the position of the specified element. + * @param element The element. + * @returns An object that contains the left, top, width and height properties of the element. + **/ + function getPosition(element: HTMLElement): IPosition; - /** - * Gets the left coordinate of the specified element relative to the specified parent. - * @param element The element. - * @param parent The parent element. - * @returns The relative left coordinate. - **/ - function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number; + /** + * Gets the left coordinate of the specified element relative to the specified parent. + * @param element The element. + * @param parent The parent element. + * @returns The relative left coordinate. + **/ + function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number; - /** - * Gets the top coordinate of the element relative to the specified parent. - * @param element The element. - * @param parent The parent element. - * @returns The relative top coordinate. - **/ - function getRelativeTop(element: HTMLElement, parent: HTMLElement): number; + /** + * Gets the top coordinate of the element relative to the specified parent. + * @param element The element. + * @param parent The parent element. + * @returns The relative top coordinate. + **/ + function getRelativeTop(element: HTMLElement, parent: HTMLElement): number; - /** - * Gets the height of the element, including its margins. - * @param element The element. - * @returns The height of the element including margins. - **/ - function getTotalHeight(element: HTMLElement): number; + /** + * Gets the height of the element, including its margins. + * @param element The element. + * @returns The height of the element including margins. + **/ + function getTotalHeight(element: HTMLElement): number; - /** - * Gets the width of the element, including margins. - * @param element The element. - * @returns The width of the element including margins. - **/ - function getTotalWidth(element: HTMLElement): number; + /** + * Gets the width of the element, including margins. + * @param element The element. + * @returns The width of the element including margins. + **/ + function getTotalWidth(element: HTMLElement): number; - /** - * Determines whether the specified element has the specified class. - * @param e The element. - * @param name The name of the class. - * @returns true if the element has the class, otherwise false. - **/ - function hasClass(e: HTMLElement, name: string): boolean; + /** + * Determines whether the specified element has the specified class. + * @param e The element. + * @param name The name of the class. + * @returns true if the element has the class, otherwise false. + **/ + function hasClass(e: HTMLElement, name: string): boolean; - /** - * Returns a collection with zero or one elements matching the specified id. - * @param id The ID of the element (or elements). - * @returns A collection of elements whose id matches the id parameter. - **/ - function id(id: string): QueryCollection; + /** + * Returns a collection with zero or one elements matching the specified id. + * @param id The ID of the element (or elements). + * @returns A collection of elements whose id matches the id parameter. + **/ + function id(id: string): QueryCollection; - /** - * Calls insertAdjacentHTML on the specified element. - * @param element The element on which insertAdjacentHTML is to be called. - * @param position The position relative to the element at which to insert the HTML. Possible values are: beforebegin, afterbegin, beforeend, afterend. - * @param text The text to insert. - **/ - function insertAdjacentHTML(element: HTMLElement, position: string, text: string): void; + /** + * Calls insertAdjacentHTML on the specified element. + * @param element The element on which insertAdjacentHTML is to be called. + * @param position The position relative to the element at which to insert the HTML. Possible values are: beforebegin, afterbegin, beforeend, afterend. + * @param text The text to insert. + **/ + function insertAdjacentHTML(element: HTMLElement, position: string, text: string): void; - /** - * Calls insertAdjacentHTML on the specified element in the context of MSApp.execUnsafeLocalFunction. - * @param element The element on which insertAdjacentHTML is to be called. - * @param position The position relative to the element at which to insert the HTML. Possible values are: beforebegin, afterbegin, beforeend, afterend. - * @param text Value to be provided to insertAdjacentHTML. - **/ - function insertAdjacentHTMLUnsafe(element: HTMLElement, position: string, text: string): void; + /** + * Calls insertAdjacentHTML on the specified element in the context of MSApp.execUnsafeLocalFunction. + * @param element The element on which insertAdjacentHTML is to be called. + * @param position The position relative to the element at which to insert the HTML. Possible values are: beforebegin, afterbegin, beforeend, afterend. + * @param text Value to be provided to insertAdjacentHTML. + **/ + function insertAdjacentHTMLUnsafe(element: HTMLElement, position: string, text: string): void; - /** - * Attaches the default dispose API wrapping the dispose implementation to the specified element. - * @param element The element to mark as disposable. - * @param disposeImpl The function containing the element-specific dispose logic, called by the dispose function that markDisposable attaches. - **/ - function markDisposable(element: HTMLElement, disposeImpl: Function): void; + /** + * Attaches the default dispose API wrapping the dispose implementation to the specified element. + * @param element The element to mark as disposable. + * @param disposeImpl The function containing the element-specific dispose logic, called by the dispose function that markDisposable attaches. + **/ + function markDisposable(element: HTMLElement, disposeImpl: Function): void; - /** - * Marks a function as being compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. - * @param func The function to be marked as compatible with declarative processing. - * @returns The input function, marked as compatible with declarative processing. - **/ - function markSupportedForProcessing(func: U): U; + /** + * Marks a function as being compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. + * @param func The function to be marked as compatible with declarative processing. + * @returns The input function, marked as compatible with declarative processing. + **/ + function markSupportedForProcessing(func: U): U; - /** - * Returns a QueryCollection with zero or one elements matching the specified selector query. - * @param query The CSS selector to use. See Selectors for more information. - * @param element Optional. The root element at which to start the query. If this parameter is omitted, the scope of the query is the entire document. - * @returns A QueryCollection with zero or one elements matching the specified selector query. - **/ - function query(query: any, element?: HTMLElement): QueryCollection; + /** + * Returns a QueryCollection with zero or one elements matching the specified selector query. + * @param query The CSS selector to use. See Selectors for more information. + * @param element Optional. The root element at which to start the query. If this parameter is omitted, the scope of the query is the entire document. + * @returns A QueryCollection with zero or one elements matching the specified selector query. + **/ + function query(query: any, element?: HTMLElement): QueryCollection; - /** - * Ensures that the specified function executes only after the DOMContentLoaded event has fired for the current page. The DOMContentLoaded event occurs after the page has been parsed but before all the resources are loaded. - * @param callback A function that executes after the DOMContentLoaded event has occurred. - * @param async If true, the callback should be executed asynchronously. - * @returns A promise that completes after the DOMContentLoaded event has occurred. - **/ - function ready(callback?: Function, async?: boolean): Promise; + /** + * Ensures that the specified function executes only after the DOMContentLoaded event has fired for the current page. The DOMContentLoaded event occurs after the page has been parsed but before all the resources are loaded. + * @param callback A function that executes after the DOMContentLoaded event has occurred. + * @param async If true, the callback should be executed asynchronously. + * @returns A promise that completes after the DOMContentLoaded event has occurred. + **/ + function ready(callback?: Function, async?: boolean): Promise; - /** - * Removes the specified class from the specified element. - * @param e The element from which to remove the class. - * @param name The name of the class to remove. - * @returns The element. - **/ - function removeClass(e: T, name: string): T; + /** + * Removes the specified class from the specified element. + * @param e The element from which to remove the class. + * @param name The name of the class to remove. + * @returns The element. + **/ + function removeClass(e: T, name: string): T; - /** - * Asserts that the value is compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. If the value is not compatible, and strictProcessing is on, an exception is thrown. All functions that have been declared using WinJS.Class.define, WinJS.Class.derive, WinJS.UI.Pages.define, or WinJS.Binding.converter are automatically marked as supported for declarative processing. Any other function that you use from a declarative context (that is, a context in which an HTML element has a data-win-control or data-win-options attribute) must be marked manually by calling this function. When you mark a function as supported for declarative processing, you are guaranteeing that the code in the function is secure from injection of third-party content. - * @param value The value to be tested for compatibility with declarative processing. If the value is a function it must be marked with a property supportedForProcessing with a value of true when strictProcessing is on. For more information, see WinJS.Utilities.markSupportedForProcessing. - * @returns The input value. - **/ - function requireSupportedForProcessing(value: T): T; + /** + * Asserts that the value is compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. If the value is not compatible, and strictProcessing is on, an exception is thrown. All functions that have been declared using WinJS.Class.define, WinJS.Class.derive, WinJS.UI.Pages.define, or WinJS.Binding.converter are automatically marked as supported for declarative processing. Any other function that you use from a declarative context (that is, a context in which an HTML element has a data-win-control or data-win-options attribute) must be marked manually by calling this function. When you mark a function as supported for declarative processing, you are guaranteeing that the code in the function is secure from injection of third-party content. + * @param value The value to be tested for compatibility with declarative processing. If the value is a function it must be marked with a property supportedForProcessing with a value of true when strictProcessing is on. For more information, see WinJS.Utilities.markSupportedForProcessing. + * @returns The input value. + **/ + function requireSupportedForProcessing(value: T): T; - /** - * Sets the innerHTML property of the specified element to the specified text. - * @param element The element on which the innerHTML property is to be set. - * @param text The value to be set to the innerHTML property. - **/ - function setInnerHTML(element: HTMLElement, text: string): void; + /** + * Sets the innerHTML property of the specified element to the specified text. + * @param element The element on which the innerHTML property is to be set. + * @param text The value to be set to the innerHTML property. + **/ + function setInnerHTML(element: HTMLElement, text: string): void; - /** - * Sets the innerHTML property of the specified element to the specified text. - * @param element The element on which the innerHTML property is to be set. - * @param text The value to be set to the innerHTML property. - **/ - function setInnerHTMLUnsafe(element: HTMLElement, text: string): void; + /** + * Sets the innerHTML property of the specified element to the specified text. + * @param element The element on which the innerHTML property is to be set. + * @param text The value to be set to the innerHTML property. + **/ + function setInnerHTMLUnsafe(element: HTMLElement, text: string): void; - /** - * Sets the outerHTML property of the specified element to the specified text. - * @param element The element on which the outerHTML property is to be set. - * @param text The value to be set to the outerHTML property. - **/ - function setOuterHTML(element: HTMLElement, text: string): void; + /** + * Sets the outerHTML property of the specified element to the specified text. + * @param element The element on which the outerHTML property is to be set. + * @param text The value to be set to the outerHTML property. + **/ + function setOuterHTML(element: HTMLElement, text: string): void; - /** - * Sets the outerHTML property of the specified element to the specified text in the context of MSApp.execUnsafeLocalFunction. - * @param element The element on which the outerHTML property is to be set. - * @param text The value to be set to the outerHTML property. - **/ - function setOuterHTMLUnsafe(element: HTMLElement, text: string): void; + /** + * Sets the outerHTML property of the specified element to the specified text in the context of MSApp.execUnsafeLocalFunction. + * @param element The element on which the outerHTML property is to be set. + * @param text The value to be set to the outerHTML property. + **/ + function setOuterHTMLUnsafe(element: HTMLElement, text: string): void; - /** - * Configures a logger that writes messages containing the specified tags to the JavaScript console. - * @param options The tags for messages to log. Multiple tags should be separated by spaces. May contain type, tags, excludeTags and action properties. - **/ + /** + * Configures a logger that writes messages containing the specified tags to the JavaScript console. + * @param options The tags for messages to log. Multiple tags should be separated by spaces. May contain type, tags, excludeTags and action properties. + **/ function startLog(options?: ILogOptions): void; - /** - * Removes the WinJS logger that had previously been set up. - **/ - function stopLog(): void; + /** + * Removes the WinJS logger that had previously been set up. + **/ + function stopLog(): void; - /** - * Toggles (adds or removes) the specified class on the specified element. If the class is present, it is removed; if it is absent, it is added. - * @param e The element on which to toggle the class. - * @param name The name of the class to toggle. - * @returns The element. - **/ - function toggleClass(e: T, name: string): T; + /** + * Toggles (adds or removes) the specified class on the specified element. If the class is present, it is removed; if it is absent, it is added. + * @param e The element on which to toggle the class. + * @param name The name of the class to toggle. + * @returns The element. + **/ + function toggleClass(e: T, name: string): T; - //#endregion Functions + //#endregion Functions //#region Properties @@ -8300,7 +8300,7 @@ declare module WinJS.Utilities { //#endregion Properties - //#region Interfaces + //#region Interfaces interface ILogOptions { type: string; @@ -8309,246 +8309,246 @@ declare module WinJS.Utilities { tags: string; } - interface IPosition { - left: number; - top: number; - width: number; - height: number; - } + interface IPosition { + left: number; + top: number; + width: number; + height: number; + } - //#endregion Interfaces + //#endregion Interfaces } /** * Provides functions and objects for scheduling and managing asynchronous tasks. **/ declare module WinJS.Utilities.Scheduler { - //#region Enumerations + //#region Enumerations - /** - * Represents a priority for a job managed by the Scheduler. - **/ - enum Priority { - /** - * A priority higher than the normal priority level. - **/ - aboveNormal, - /** - * A priority less than the normal priority level. - **/ - belowNormal, - /** - * A high priority. - **/ - high, - /** - * The idle priority for work items. - **/ - idle, - /** - * The highest priority. - **/ - max, - /** - * The lowest priority. - **/ - min, - /** - * The normal priority for work items. - **/ - normal - } + /** + * Represents a priority for a job managed by the Scheduler. + **/ + enum Priority { + /** + * A priority higher than the normal priority level. + **/ + aboveNormal, + /** + * A priority less than the normal priority level. + **/ + belowNormal, + /** + * A high priority. + **/ + high, + /** + * The idle priority for work items. + **/ + idle, + /** + * The highest priority. + **/ + max, + /** + * The lowest priority. + **/ + min, + /** + * The normal priority for work items. + **/ + normal + } - //#endregion Enumerations + //#endregion Enumerations - //#region Interfaces + //#region Interfaces - /** - * Represents a work item that's executed by the Scheduler. - **/ - interface IJob { - //#region Methods + /** + * Represents a work item that's executed by the Scheduler. + **/ + interface IJob { + //#region Methods - /** - * Cancels the job. - **/ - cancel(): void; + /** + * Cancels the job. + **/ + cancel(): void; - /** - * Pauses the job. - **/ - pause(): void; + /** + * Pauses the job. + **/ + pause(): void; - /** - * Resumes the job. - **/ - resume(): void; + /** + * Resumes the job. + **/ + resume(): void; - //#endregion Methods + //#endregion Methods - //#region Properties + //#region Properties - /** - * Gets a value that indicates whether the job has successfully completed. - **/ - completed: boolean; + /** + * Gets a value that indicates whether the job has successfully completed. + **/ + completed: boolean; - /** - * Gets the unique numeric identifier assigned to the job. - **/ - id: number; + /** + * Gets the unique numeric identifier assigned to the job. + **/ + id: number; - /** - * Gets or sets the name of the job. - **/ - name: string; + /** + * Gets or sets the name of the job. + **/ + name: string; - /** - * Gets or sets the owner of the job. - **/ - owner: IOwnerToken; + /** + * Gets or sets the owner of the job. + **/ + owner: IOwnerToken; - /** - * Gets or sets the priority of the job. - **/ - priority: Priority; + /** + * Gets or sets the priority of the job. + **/ + priority: Priority; - //#endregion Properties + //#endregion Properties - } + } - /** - * Provides a control mechanism that allows a job to cooperatively yield. This object is passed to your work function when you schedule it. - **/ - interface IJobInfo { - //#region Methods + /** + * Provides a control mechanism that allows a job to cooperatively yield. This object is passed to your work function when you schedule it. + **/ + interface IJobInfo { + //#region Methods - /** - * Uses a Promise to determine how long the scheduler should wait before rescheduling the job after it yields. - * @param promise Once the work item yields, the scheduler will wait for this Promise to complete before rescheduling the job. - **/ - setPromise(promise: Promise): void; + /** + * Uses a Promise to determine how long the scheduler should wait before rescheduling the job after it yields. + * @param promise Once the work item yields, the scheduler will wait for this Promise to complete before rescheduling the job. + **/ + setPromise(promise: Promise): void; - /** - * Specifies the next unit of work to run once this job yields. - * @param work The next unit of work to run once this job yields. - **/ - setWork(work: Function): void; + /** + * Specifies the next unit of work to run once this job yields. + * @param work The next unit of work to run once this job yields. + **/ + setWork(work: Function): void; - //#endregion Methods + //#endregion Methods - //#region Properties + //#region Properties - /** - * Gets the work item associated with this IJobInfo. - **/ - job: IJob; + /** + * Gets the work item associated with this IJobInfo. + **/ + job: IJob; - /** - * Gets a value that specifies whether the job should yield. - **/ - shouldYield: boolean; + /** + * Gets a value that specifies whether the job should yield. + **/ + shouldYield: boolean; - //#endregion Properties + //#endregion Properties - } + } - /** - * Represents an object that owns jobs. You can use this object to cancel a set of jobs. - **/ - interface IOwnerToken { - //#region Methods + /** + * Represents an object that owns jobs. You can use this object to cancel a set of jobs. + **/ + interface IOwnerToken { + //#region Methods - /** - * Synchronously cancels the job that this token owns, including paused and blocked jobs. - **/ - cancelAll(): void; + /** + * Synchronously cancels the job that this token owns, including paused and blocked jobs. + **/ + cancelAll(): void; - //#endregion Methods + //#endregion Methods - } + } - //#endregion Interfaces + //#endregion Interfaces - //#region Functions + //#region Functions - /** - * Creates and returns a new IOwnerToken which can be set to the owner property of one or more jobs. - * @returns A new IOwnerToken which can be set to the owner property of one or more jobs. - **/ - function createOwnerToken(): IOwnerToken; + /** + * Creates and returns a new IOwnerToken which can be set to the owner property of one or more jobs. + * @returns A new IOwnerToken which can be set to the owner property of one or more jobs. + **/ + function createOwnerToken(): IOwnerToken; - /** - * Runs the specified callback in a high priority context. - * @param callback The callback to run in a high priority callback. - * @returns The return value of the callback. - **/ - function execHigh(callback: () => U): U; + /** + * Runs the specified callback in a high priority context. + * @param callback The callback to run in a high priority callback. + * @returns The return value of the callback. + **/ + function execHigh(callback: () => U): U; - /** - * Returns a string representation of the scheduler's state for diagnostic purposes. The jobs and drain requests are displayed in the order in which they are currently expected to be processed. The current job and drain request are marked by an asterisk. - * @returns A string representation of the scheduler's state for diagnostic purposes. The jobs and drain requests are displayed in the order in which they are currently expected to be processed. The current job and drain request are marked by an asterisk. - **/ - function retrieveState(): string; + /** + * Returns a string representation of the scheduler's state for diagnostic purposes. The jobs and drain requests are displayed in the order in which they are currently expected to be processed. The current job and drain request are marked by an asterisk. + * @returns A string representation of the scheduler's state for diagnostic purposes. The jobs and drain requests are displayed in the order in which they are currently expected to be processed. The current job and drain request are marked by an asterisk. + **/ + function retrieveState(): string; - /** - * Runs jobs in the scheduler without timeslicing until all jobs at the specified priority and higher have executed. - * @param priority The priority to which the scheduler should drain. The default is -15. - * @param name An optional description of the drain request for diagnostics. - * @returns A Promise which completes when the drain has finished. Canceling this Promise cancels the drain request. This Promise will never enter an error state. - **/ - function requestDrain(priority?: Priority, name?: string): Promise; + /** + * Runs jobs in the scheduler without timeslicing until all jobs at the specified priority and higher have executed. + * @param priority The priority to which the scheduler should drain. The default is -15. + * @param name An optional description of the drain request for diagnostics. + * @returns A Promise which completes when the drain has finished. Canceling this Promise cancels the drain request. This Promise will never enter an error state. + **/ + function requestDrain(priority?: Priority, name?: string): Promise; - /** - * Schedules the specified function to execute asynchronously. - * @param work A function that represents the work item to be scheduled. When called the work item will receive as its first argument an object which allows the work item to ask the scheduler if it should yield cooperatively and if so allows the work item to either provide a function to be run as a continuation or a WinJS.Promise which will when complete provide a function to run as a continuation. Provide these fields for the object: shouldYield, setWork(work), setPromise(promise), job. - * @param priority The priority of the work item. If you don't specify a priority, it defaults to WinJS.Utilities.Scheduler.Priority.normal. - * @param thisArg A "this" instance to be bound to the work item. The default value is null. - * @param name A description of the work item for diagnostics. The default value is an empty string. - * @returns The job instance that represents this work item. - **/ - function schedule(work: (jobInfo: IJobInfo) => any, priority?: Priority, thisArg?: any, name?: string): IJob; + /** + * Schedules the specified function to execute asynchronously. + * @param work A function that represents the work item to be scheduled. When called the work item will receive as its first argument an object which allows the work item to ask the scheduler if it should yield cooperatively and if so allows the work item to either provide a function to be run as a continuation or a WinJS.Promise which will when complete provide a function to run as a continuation. Provide these fields for the object: shouldYield, setWork(work), setPromise(promise), job. + * @param priority The priority of the work item. If you don't specify a priority, it defaults to WinJS.Utilities.Scheduler.Priority.normal. + * @param thisArg A "this" instance to be bound to the work item. The default value is null. + * @param name A description of the work item for diagnostics. The default value is an empty string. + * @returns The job instance that represents this work item. + **/ + function schedule(work: (jobInfo: IJobInfo) => any, priority?: Priority, thisArg?: any, name?: string): IJob; - /** - * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.aboveNormal priority. - * @param promiseValue The value returned by the completed Promise. - * @param jobName A string that describes the job for diagnostic purposes. - * @returns A Promise that completes within a job of aboveNormal priority. - **/ - function schedulePromiseAboveNormal(promiseValue?: U, jobName?: string): Promise; + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.aboveNormal priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of aboveNormal priority. + **/ + function schedulePromiseAboveNormal(promiseValue?: U, jobName?: string): Promise; - /** - * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.belowNormal priority. - * @param promiseValue The value returned by the completed Promise. - * @param jobName A string that describes the job for diagnostic purposes. - * @returns A Promise that completes within a job of belowNormal priority. - **/ - function schedulePromiseBelowNormal(promiseValue?: U, jobName?: string): Promise; + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.belowNormal priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of belowNormal priority. + **/ + function schedulePromiseBelowNormal(promiseValue?: U, jobName?: string): Promise; - /** - * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.high priority. - * @param promiseValue The value returned by the completed Promise. - * @param jobName A string that describes the job for diagnostic purposes. - * @returns A Promise that completes within a job of high priority. - **/ - function schedulePromiseHigh(promiseValue?: U, jobName?: string): Promise; + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.high priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of high priority. + **/ + function schedulePromiseHigh(promiseValue?: U, jobName?: string): Promise; - /** - * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.Idle priority. - * @param promiseValue The value returned by the completed Promise. - * @param jobName A string that describes the job for diagnostic purposes. - * @returns A Promise that completes within a job of idle priority. - **/ - function schedulePromiseIdle(promiseValue?: U, jobName?: string): Promise; + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.Idle priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of idle priority. + **/ + function schedulePromiseIdle(promiseValue?: U, jobName?: string): Promise; - /** - * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.normal priority. - * @param promiseValue The value returned by the completed Promise. - * @param jobName A string that describes the job for diagnostic purposes. - * @returns A Promise that completes within a job of normal priority. - **/ - function schedulePromiseNormal(promiseValue?: U, jobName?: string): Promise; + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.normal priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of normal priority. + **/ + function schedulePromiseNormal(promiseValue?: U, jobName?: string): Promise; - //#endregion Functions + //#endregion Functions } diff --git a/winjs/legacy/winjs-2.1.d.ts b/winjs/legacy/winjs-2.1.d.ts new file mode 100644 index 000000000..717e3d1a6 --- /dev/null +++ b/winjs/legacy/winjs-2.1.d.ts @@ -0,0 +1,7000 @@ +// Type definitions for WinJS +// Project: http://msdn.microsoft.com/en-us/library/windows/apps/br229773.aspx +// Definitions by: TypeScript samples , Adam Hewitt , Craig Treasure +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +/** + * Defines an Element object. +**/ +interface Element { + winControl: any; // TODO: This should be control? +} + +/** + * Utility class for easy access to operations on application folders +**/ +interface IOHelper { + /** + * Determines whether the specified file exists in the folder. + * @param filename The name of the file. + * @returns A promise that completes with a value of either true (if the file exists) or false. + **/ + exists(filename: string): WinJS.Promise; + + /** + * Reads the specified file. If the file doesn't exist, the specified default value is returned. + * @param fileName The file to read from. + * @param def The default value to be returned if the file failed to open. + * @returns A promise that completes with a value that is either the contents of the file, or the specified default value. + **/ + readText(fileName: string, def?: string): WinJS.Promise; + + /** + * Deletes a file from the folder. + * @param fileName The file to be deleted. + * @returns A promise that is fulfilled when the file has been deleted. + **/ + remove(fileName: string): WinJS.Promise; + + /** + * Writes the specified text to the specified file. + * @param fileName The name of the file. + * @param text The content to be written to the file. + * @returns A promise that completes with a value that is the number of characters written. + **/ + writeText(fileName: string, text: string): WinJS.Promise; +} + +/** + * Provides application-level functionality, for example activation, storage, and application events. +**/ +declare module WinJS.Application { + //#region Objects + + /** + * The local storage of the application. + **/ + var local: IOHelper; + + /** + * The roaming storage of the application. + **/ + var roaming: IOHelper; + + /** + * The temp storage of the application. + **/ + var temp: IOHelper; + + /** + * An object used for storing app information that can be used to restore the app's state after it has been suspended and then resumed. Data that can usefully be contained in this object includes the current navigation page or any information the user has added to the input controls on the page. You should not add information about customization (for example colors) or user-defined lists of content. + **/ + var sessionState: any; + + //#endregion Objects + + //#region Methods + + /** + * Informs the application object that asynchronous work is being performed, and that this event handler should not be considered complete until the promise completes. This function can be set inside the handlers for all WinJS.Application events: onactivated oncheckpoint onerror onloaded onready onsettings onunload. + * @param promise The promise that should complete before processing is complete. + **/ + function setPromise(promise: Promise): void; + + //#endregion Methods + + //#region Functions + + /** + * Adds an event listener for application-level events: activated, checkpoint, error, loaded, ready, settings, and unload. + * @param type The type (name) of the event. You can use any of the following:"activated", "checkpoint", "error", "loaded", "ready", "settings", and" unload". + * @param listener The listener to invoke when the event is raised. + * @param capture true to initiate capture, otherwise false. + **/ + function addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Queues a checkpoint event. + **/ + function checkpoint(): void; + + /** + * Queues an event to be processed by the WinJS.Application event queue. + * @param eventRecord The event object is expected to have a type property that is used as the event name when dispatching on the WinJS.Application event queue. The entire object is provided to event listeners in the detail property of the event. + **/ + function queueEvent(eventRecord: any): void; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture Specifies whether or not to initiate capture. + **/ + function removeEventListener(type: string, listener: Function, useCapture?: any): void; + + /** + * Starts dispatching application events (the activated, checkpoint, error, loaded, ready, settings, and unload events). + **/ + function start(): void; + + /** + * Stops application event processing and resets WinJS.Application to its initial state. All WinJS.Application event listeners (for the activated, checkpoint, error, loaded, ready, settings, and unload events) are removed. + **/ + function stop(): void; + + //#endregion Functions + + //#region Events + + /** + * Occurs when WinRT activation has occurred. The name of this event is "activated" (and also "mainwindowactivated"). This event occurs after the loaded event and before the ready event. + * @param eventInfo An object that contains information about the event. For more information about event arguments, see the WinRT event argument classes: WebUICachedFileUpdaterActivatedEventArgs, WebUICameraSettingsActivatedEventArgs, WebUIContactPickerActivatedEventArgs, WebUIDeviceActivatedEventArgs, WebUIFileActivatedEventArgs, WebUIFileOpenPickerActivatedEventArgs, WebUIFileSavePickerActivatedEventArgs, WebUILaunchActivatedEventArgs, WebUIPrintTaskSettingsActivatedEventArgs, WebUIProtocolActivatedEventArgs, WebUISearchActivatedEventArgs, WebUIShareTargetActivatedEventArgs. + **/ + function onactivated(eventInfo: CustomEvent): void; + + /** + * Raised when the users clicks the backbutton on a Windows Phone. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.type + **/ + function onbackclick(eventInfo: CustomEvent): void; + + /** + * Occurs when receiving PLM notification or when the checkpoint function is called. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following subproperties: type, setPromise. + **/ + function oncheckpoint(eventInfo: CustomEvent): void; + + /** + * Occurs when an unhandled error has been raised. + * @param eventInfo An object that contains information about the event. + **/ + function onerror(eventInfo: CustomEvent): void; + + /** + * Occurs after the DOMContentLoaded event, which fires after the page has been parsed but before all the resources are loaded. This event occurs before the activated event and the ready event. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following subproperties: type, setPromise. + **/ + function onloaded(eventInfo: CustomEvent): void; + + /** + * Occurs when the application is ready. This event occurs after the loaded event and the activated event. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following sub-properties: type, setPromise. + **/ + function onready(eventInfo: CustomEvent): void; + + /** + * Occurs when the settings charm is invoked. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: type, applicationcommands. + **/ + function onsettings(eventInfo: CustomEvent): void; + + /** + * Occurs when the application is about to be unloaded. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following sub-properties: type, setPromise. + **/ + function onunload(eventInfo: CustomEvent): void; + + //#endregion Events + +} +/** + * Provides functionality for data and template binding. +**/ +declare module WinJS.Binding { + //#region Properties + + /** + * Determines whether or not binding should automatically set the ID of an element. This property should be set to true in apps that use WinJS (WinJS) binding. + **/ + var optimizeBindingReferences: boolean; + + //#endregion Properties + + //#region Objects + + /** + * Allows you to add bindable properties dynamically. + **/ + var dynamicObservableMixin: { + //#region Methods + + /** + * Adds a property with change notification to this object, including a ECMAScript5 property definition. + * @param name The name of the property to add. + * @param value This object is returned. + **/ + addProperty(name: string, value: any): void; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns This object is returned. + **/ + bind(name: string, action: any): Function; + + /** + * Gets a property value by name. + * @param name The name of the property to get. + * @returns The value of the property as an observable object. + **/ + getProperty(name: string): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: string, oldValue: string): Promise; + + /** + * Removes a property value. + * @param name The name of the property to remove. + * @returns This object is returned. + **/ + removeProperty(name: string): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns This object is returned. + **/ + setProperty(name: string, value: any): any; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns A promise that completes when the notifications for this property change have been processed. If multiple notifications are coalesced, the promise may be canceled or the value of the promise may be updated. The fulfilled value of the promise is the new value of the property for which the notifications have been completed. + **/ + updateProperty(name: string, value: any): Promise; + + //#endregion Methods + + }; + + /** + * Do not instantiate. A list returned by the createFiltered method. + **/ + class FilteredListProjection extends ListProjection { + //#region Methods + + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value that was replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + //#endregion Methods + + //#region Properties + + /** + * The length of the list. Returns an integer value one higher than the highest element defined in an list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Do not instantiate. A list of groups. + **/ + class GroupsListProjection extends ListBase { + //#region Methods + + /** + * Gets a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Gets a key/data pair for the specified key. + * @param key The key of the value to retrieve. + * @returns An object with two properties: key and data. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + //#endregion Methods + + //#region Properties + + /** + * The length of the list. Returns an integer value one higher than the highest element defined in an list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Do not instantiate. Sorts the underlying list by group key and within a group respects the position of the item in the underlying list. Returned by createGrouped. + **/ + class GroupedSortedListProjection extends SortedListProjection { + //#region Properties + + /** + * Gets a List, which is a projection of the groups that were identified in this list. + **/ + groups: GroupsListProjection; + + //#endregion Properties + + } + + /** + * Represents a list of objects that can be accessed by index or by a string key. Provides methods to search, sort, filter, and manipulate the data. + **/ + class List extends ListBaseWithMutators { + //#region Constructors + + /** + * Creates a List object. + * @constructor + * @param list The array containing the elements to initalize the list. + * @param options You can set two Boolean options: binding and proxy. If options.binding is true, the list contains the result of calling as on the element values. If options.proxy is true, the list specified as the first parameter is used as the storage for the List. This option should be used with care, because uncoordinated edits to the data storage may result in errors. + **/ + constructor(list?: T[], options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Gets a key/data pair for the specified list index. + * @param index The index of value to retrieve. + * @returns An object with .key and .data properties. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Gets a key/data pair for the list item key specified. + * @param key The key of the value to retrieve. + * @returns An object with .key and .data properties. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Gets the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Moves the value at index to the specified position. + * @param index The original index of the value. + * @param newIndex The index of the value after the move. + **/ + move(index: number, newIndex: number): void; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Returns a list with the elements reversed. This method reverses the elements of a list object in place. It does not create a new list object during execution. + **/ + reverse(): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value that was replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + /** + * Returns a list with the elements sorted. This method sorts the elements of a list object in place. It does not create a new list object during execution. + * @param sortFunction The function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + **/ + sort(sortFunction: (left: T, right: T) => number): void; + + /** + * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the list from which to start removing elements. + * @param howMany The number of elements to remove. + * @param item The elements to insert into the list in place of the deleted elements. + * @returns The deleted elements. + **/ + splice(start: number, howMany?: number, ...item: T[]): T[]; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the length of the list, which is an integer value one higher than the highest element defined in the list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Represents a base class for lists. + **/ + class ListBase { + //#region Events + + /** + * An item in the list has changed its value. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, newItem, newValue, oldItem, oldValue. + **/ + onitemchanged(eventInfo: CustomEvent): void; + + /** + * A new item has been inserted into the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + oniteminserted(eventInfo: CustomEvent): void; + + /** + * An item has been changed locations in the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemmoved(eventInfo: CustomEvent): void; + + /** + * An item has been mutated. This event occurs as a result of calling the notifyMutated method. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemmutated(eventInfo: CustomEvent): void; + + /** + * An item has been removed from the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemremoved(eventInfo: CustomEvent): void; + + /** + * The list has been refreshed. Any references to items in the list may be incorrect. + * @param eventInfo An object that contains information about the event. The detail property of this object is null. + **/ + onreload(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture If true, initiates capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns A reference to this observableMixin object. + **/ + bind(name: string, action: Function): any; + + /** + * Returns a new list consisting of a combination of two arrays. + * @param item Additional items to add to the end of the list. + * @returns An array containing the concatenation of the list and any other supplied items. + **/ + concat(...item: T[]): T[]; + + /** + * Creates a live filtered projection over this list. As the list changes, the filtered projection reacts to those changes and may also change. + * @param predicate A function that accepts a single argument. The createFiltered function calls the callback with each element in the list. If the function returns true, that element will be included in the filtered list. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @returns A filtered projection over the list. + **/ + createFiltered(predicate: (x: T) => boolean): FilteredListProjection; + + /** + * Creates a live grouped projection over this list. As the list changes, the grouped projection reacts to those changes and may also change. The grouped projection sorts all the elements of the list to be in group-contiguous order. The grouped projection also contains a .groups property, which is a List representing the groups that were found in the list. + * @param groupKey A function that accepts a single argument. The function is called with each element in the list, the function should return a string representing the group containing the element. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @param groupData A function that accepts a single argument. The function is called once, on one element per group. It should return the value that should be set as the data of the .groups list element for this group. The data value usually serves as summary or header information for the group. + * @param groupSorter A function that accepts two arguments. The function is called with pairs of group keys found in the list. It must return one of the following numeric values: negative if the first argument is less than the second (sorted before), zero if the two arguments are equivalent, positive if the first argument is greater than the second (sorted after). + * @returns A grouped projection over the list. + **/ + createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter: (left: string, right: string) => number): GroupedSortedListProjection; + + /** + * Creates a live sorted projection over this list. As the list changes, the sorted projection reacts to those changes and may also change. + * @param sorter A function that accepts two arguments. The function is called with elements in the list. It must return one of the following numeric values: negative if the first argument is less than the second, zero if the two arguments are equivalent, positive if the first argument is greater than the second. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @returns A sorted projection over the list. + **/ + createSorted(sorter: (left: T, right: T) => number): SortedListProjection; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Checks whether the specified callback function returns true for all elements in a list. + * @param callback A function that accepts up to three arguments. This function is called for each element in the list until it returns false or the end of the list is reached. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns true if the callback returns true for all elements in the list. + **/ + every(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Returns the elements of a list that meet the condition specified in a callback function. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns An array containing the elements that meet the condition specified in the callback function. + **/ + filter(callback: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; + + /** + * Calls the specified callback function for each element in a list. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. The arguments are as follows: value, index, array. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + **/ + forEach(callback: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + + /** + * Gets the value at the specified index. + * @param index The index of the value to get. + * @returns The value at the specified index. + **/ + getAt(index: number): T; + + /** + * Gets the index of the first occurrence of the specified value in a list. + * @param searchElement The value to locate in the list. + * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + * @returns The index of the first occurrence of a value in a list or -1 if not found. + **/ + indexOf(searchElement: T, fromIndex?: number): number; + + /** + * Returns a string consisting of all the elements of a list separated by the specified separator string. + * @param separator A string used to separate the elements of a list. If this parameter is omitted, the list elements are separated with a comma. + * @returns The elements of a list separated by the specified separator string. + **/ + join(separator: string): string; + + /** + * Gets the index of the last occurrence of the specified value in a list. + * @param searchElement The value to locate in the list. + * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the list. + * @returns The index of the last occurrence of a value in a list, or -1 if not found. + **/ + lastIndexOf(searchElement: T, fromIndex: number): number; + + /** + * Calls the specified callback function on each element of a list, and returns an array that contains the results. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. + * @param thisArg n object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns An array containing the result of calling the callback function on each element in the list. + **/ + map(callback: (value: T, index: number, array: T[]) => G, thisArg?: any): G[]; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: any, oldValue: any): Promise; + + /** + * Forces the list to send a reload notification to any listeners. + **/ + notifyReload(): void; + + /** + * Accumulates a single result by calling the specified callback function for all elements in a list. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callback A function that accepts up to four arguments. These arguments are: previousValue, currentValue, currentIndex, array. The function is called for each element in the list. + * @param initiallValue If initialValue is specified, it is used as the value with which to start the accumulation. The first call to the function provides this value as an argument instead of a list value. + * @returns The return value from the last call to the callback function. + **/ + reduce(callback: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => T, initiallValue?: T): T; + + /** + * Accumulates a single result by calling the specified callback function for all elements in a list, starting with the last member of the list. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callback A function that accepts up to four arguments. These arguments are: previousValue, currentValue, currentIndex, array. The function is called for each element in the list. + * @param initialValue If initialValue is specified, it is used as the value with which to start the accumulation. The first call to the callback function provides this value as an argument instead of a list value. + * @returns The return value from the last call to callback function. + **/ + reduceRight(callback: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => T, initialValue?: T): T; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true if capture is to be initiated, otherwise false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Extracts a section of a list and returns a new list. + * @param begin The index that specifies the beginning of the section. + * @param end The index that specifies the end of the section. + * @returns Returns a section of list. + **/ + slice(begin: number, end: number): T[]; + + /** + * Checks whether the specified callback function returns true for any element of a list. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list until it returns true, or until the end of the list. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns true if callback returns true for any element in the list. + **/ + some(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + //#endregion Methods + + //#region Properties + + /** + * Gets the IListDataSource for the list. The only purpose of this property is to adapt a List to the data model that is used by ListView and FlipView. + **/ + dataSource: WinJS.UI.IListDataSource; + + /** + * Indicates that the object is compatibile with declarative processing. + **/ + static supportedForProcessing: boolean; + + //#endregion Properties + } + + /** + * Represents a base class for normal list modifying operations. + **/ + class ListBaseWithMutators extends ListBase { + //#region Methods + + /** + * Removes the last element from a list and returns it. + * @returns The last element from the list. + **/ + pop(): T; + + /** + * Appends new element(s) to a list, and returns the new length of the list. + * @param value The element to insert at the end of the list. + * @returns The new length of the list. + **/ + push(value: T): number; + + /** + * Removes the first element from a list and returns it. + * @returns The first element from the list. + **/ + shift(): T; + + /** + * Appends new element(s) to a list, and returns the new length of the list. + * @param value The element to insert at the start of the list. + * @returns The new length of the list. + **/ + unshift(value: T): number; + + //#endregion Methods + } + + /** + * Represents a base class for list projections. + **/ + class ListProjection extends ListBaseWithMutators { + //#region Methods + + /** + * Disconnects a WinJS.Binding.List projection from its underlying WinJS.Binding.List. It's only important to call this method when the WinJS.Binding.List projection and the WinJS.Binding.List have different lifetimes. (Call this method on the WinJS.Binding.List projection, not the underlying WinJS.Binding.List.) + **/ + dispose(): void; + + /** + * Gets a key/data pair for the specified key. + * @param key The key of the value to retrieve. + * @returns An object with two properties: key and data. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Moves the value at index to position newIndex. + * @param index The original index of the value. + * @param newIndex The index of the value after the move. + **/ + move(index: number, newIndex: number): void; + + /** + * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the list from which to start removing elements. + * @param howMany The number of elements to remove. + * @param item The elements to insert into the list in place of the deleted elements. + * @returns The deleted elements. + **/ + splice(start: number, howMany?: number, ...item: T[]): T[]; + + //#endregion Methods + } + + /** + * Provides a standard implementation of the bindable contract, as well as a basic storage mechanism that participates in change notification and an asynchronous notification implementation. + **/ + var mixin: { + //#region Methods + + /** + * Adds a property to the object. The property includes change notification and an ECMAScript 5 property definition . + * @param name The name of the property to add. + * @param value The value of the property. + * @returns This object is returned. + **/ + addProperty(name: string, value: any): any; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns This object is returned. + **/ + bind(name: string, action: any): Function; + + /** + * Gets a property value by name. + * @param name The name of the property to get. + * @returns The value of the property as an observable object. + **/ + getProperty(name: string): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: string, oldValue: string): Promise; + + /** + * Removes a property value. + * @param name The name of the property to remove. + * @returns This object is returned. + **/ + removeProperty(name: string): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns This object is returned. + **/ + setProperty(name: string, value: any): any; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns A promise that completes when the notifications for this property change have been processed. If multiple notifications are coalesced, the promise may be canceled or the value of the promise may be updated. The fulfilled value of the promise is the new value of the property for which the notifications have been completed. + **/ + updateProperty(name: string, value: any): Promise; + + //#endregion Methods + + }; + + /** + * Provides functions that can make an object observable. + **/ + var observableMixin: { + //#region Methods + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns A reference to this observableMixin object. + **/ + bind(name: string, action: Function): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: any, oldValue: any): Promise; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + //#endregion Methods + + }; + + /** + * Do not instantiate. Returned by the createSorted method. + **/ + class SortedListProjection extends ListProjection { + //#region Methods + + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value to be replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the length of the list. Returns an integer value one higher than the highest element defined in a list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Provides a reusable declarative binding element. + **/ + class Template { + //#region Constructors + + /** + * Creates a template that provides a reusable declarative binding element. + * @constructor + * @param element The DOM element to convert to a template. + * @param options If this parameter is supplied, the template is loaded from the URI and the content of the element parameter is ignored. You can add the following options: href. + **/ + constructor(element: HTMLElement, options?: string); + + //#endregion Constructors + + //#region Methods + + render: { + /** + * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. + **/ + (dataContext: any, container?: HTMLElement): Promise; + + /** + * Renders a template based on the specified URI (static method). + * @param href The URI from which to load the template. + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. + **/ + value(href: string, dataContext: any, container?: HTMLElement): Promise; + }; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the default binding initializer for the template. + **/ + bindingInitializer: any; + + /** + * Gets or sets a value that specifies whether a debug break is inserted into the first rendering of each template. This property only has an effect when the app is in debug mode. + **/ + debugBreakOnRender: boolean; + + /** + * This property is deprecated and might not be available in future versions of the WinJS. Gets or sets a value that specifies whether optimized template processing has been disabled. + **/ + disableOptimizedProcessing: boolean; + + /** + * Gets the DOM element that is used as the template. + **/ + element: HTMLElement; + + /** + * Gets a value that specifies whether templates should be instantiated without the creation of an additional child element. + **/ + extractChild: boolean; + + /** + * Determines whether the Template contains declarative controls that must be processed separately. This property is always true. The controls that belong to a Template object's children are instantiated when a Template instance is rendered. + **/ + isDeclarativeControlContainer: boolean; + + //#endregion Properties + + } + + //#endregion Objects + + //#region Functions + + /** + * Adds a CSS class from the specified path of the source object to a destination object. + * @param source The source object that has the class to copy. + * @param sourceProperties The path on the source object to the source class. + * @param dest The destination object. + **/ + function addClassOneTime(source: any, sourceProperties: any[], dest: HTMLElement): void; + + /** + * Returns an observable object. This may be an observable proxy for the specified object, an existing proxy, or the specified object itself if it directly supports observation. + * @param data The object to observe. + * @returns The observable object. + **/ + function as(data: U): U; + + /** + * Binds to one or more properties on the observable object or or on child values of that object. + * @param observable The object to bind to. + * @param bindingDescriptor An object literal containing the binding declarations. Binding declarations take the form: { propertyName: (function | bindingDeclaration), ... }. + * @returns An object that contains at least a "cancel" field, which is a function that removes all bindings associated with this bind request. + **/ + function bind(observable: any, bindingDescriptor: any): any; + + /** + * Creates a default binding initializer for binding between a source property and a destination property with the specified converter function that is executed on the value of the source property. + * @param convert The conversion function that takes the source property and produces a value that is set to the destination property. This function must be accessible from the global namespace. + * @returns The binding initializer. + **/ + function converter(convert: Function): Function; + + /** + * Creates a one-way binding between the source object and the destination object. Warning Do not attempt to bind data to the ID of an HTML element. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. + * @returns An object with a cancel method that is used to coalesce bindings. + **/ + function defaultBind(source: any, sourceProperties: any, dest: any, destProperties: any): any; + + /** + * Creates a new constructor function that supports observability with the specified set of properties. + * @param data The object to use as the pattern for defining the set of properties. + * @returns A constructor function with 1 optional argument that is the initial state of the properties. + **/ + function define(data: any): Function; + + /** + * Wraps the specified object so that all its properties are instrumented for binding. This is meant to be used in conjunction with the binding mixin. + * @param shape The specification for the bindable object. + * @returns An object with a set of properties all of which are wired for binding. + **/ + function expandProperties(shape: any): any; + + /** + * Marks a custom initializer function as being compatible with declarative data binding. + * @param customInitializer The custom initializer to be marked as compatible with declarative data binding. + * @returns The input customInitializer. + **/ + function initializer(customInitializer: Function): Function; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + function notify(name: string, newValue: string, oldValue: string): Promise; + + /** + * Sets the destination property to the value of the source property. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. + * @returns An object with a cancel method that is used to coalesce bindings. + **/ + function oneTime(source: any, sourceProperties: any, dest: any, destProperties: any): any; + + /** + * Binds the values of an object to the values of a DOM element that has the data-win-bind attribute. If multiple DOM elements are to be bound, you must set the attribute on all of them. See the example below for details. + * @param rootElement Optional. The element at which to start traversing to find elements to bind to. If this parameter is omitted, the entire document is searched. + * @param dataContext The object that contains the values to which the DOM element should be bound. + * @param skipRoot If true, specifies that only the children of rootElement should be bound, otherwise rootElement should be bound as well. + * @param bindingCache The cached binding data. + * @param defaultInitializer The binding initializer to use in the case that one is not specified in a binding expression. If not provided, the behavior is the same as Binding.defaultBind. + * @returns A Promise that completes when every item that contains the data-win-bind attribute has been processed and the update has started. + **/ + function processAll(rootElement?: Element, dataContext?: any, skipRoot?: boolean, bindingCache?: any, defaultInitializer?: Function): Promise; + + /** + * Creates a one-way binding between the source object and an attribute on the destination element. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. This must be a single name. + * @returns An object with a cancel() method that is used to coalesce bindings. + **/ + function setAttribute(source: any, sourceProperties: any[], dest: Element, destProperties: any[]): any; + + /** + * Sets an attribute on the destination element to the value of the source property. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. This must be a single name. + **/ + function setAttributeOneTime(source: any, sourceProperties: any[], dest: Element, destProperties: any[]): void; + + /** + * Returns the original (non-observable) object is returned if the specified object is an observable proxy, + * @param data The object for which to retrieve the original value. + * @returns If the specified object is an observable proxy, the original object is returned, otherwise the same object is returned. + **/ + function unwrap(data: any): any; + + //#endregion Functions + + //#region Interfaces + + interface IKeyDataPair { + key: string; + data: T; + } + + //#endregion Interfaces + +} +/** + * Provides helper functions for defining Classes. +**/ +declare module WinJS.Class { + //#region Functions + + /** + * Defines a class using the given constructor and the specified instance members. + * @param constructor A constructor function that is used to instantiate this type. + * @param instanceMembers The set of instance fields, properties, and methods made available on the type. + * @param staticMembers The set of static fields, properties, and methods made available on the type. + * @returns The newly-defined type. + **/ + function define(constructor: Function, instanceMembers?: any, staticMembers?: any): any; + + /** + * Creates a sub-class based on the specified baseClass parameter, using prototype inheritance. + * @param baseClass The type to inherit from. + * @param constructor A constructor function that is used to instantiate this type. + * @param instanceMembers The set of instance fields, properties, and methods to be made available on the type. + * @param staticMembers The set of static fields, properties, and methods to be made available on the type. + * @returns The newly-defined type. + **/ + function derive(baseClass: any, constructor: Function, instanceMembers?: any, staticMembers?: any): any; + + /** + * Defines a class using the given constructor and the union of the set of instance members specified by all the mixin objects. The mixin parameter list is of variable length. For more information, see Adding functionality with WinJS mixins. + * @param constructor A constructor function that will be used to instantiate this class. + * @param mixin An object declaring the set of instance members. The mixin parameter list is of variable length. + * @returns The newly defined class. + **/ + function mix(constructor: Function, ...mixin: any[]): any; + + //#endregion Functions + +} +/** + * The WinJS namespace provides special Windows Library for JavaScript functionality, including Promise and xhr. +**/ +declare module WinJS { + //#region Properties + + /** + * Can be set to show the results of a validation process. + **/ + var validation: boolean; + + //#endregion Properties + + //#region Objects + + /** + * An error object. + **/ + class ErrorFromName { + //#region Constructors + + /** + * Creates an Error object with the specified name and message properties. + * @constructor + * @param name The name of this error. The name is meant to be consumed programmatically and should not be localized. + * @param message The message for this error. The message is meant to be consumed by humans and should be localized. + **/ + constructor(name: string, message?: string); + + //#endregion Constructors + + } + + /** + * Provides a mechanism to schedule work to be done on a value that has not yet been computed. It is an abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. + **/ + class Promise { + //#region Constructors + + /** + * A promise provides a mechanism to schedule work to be done on a value that has not yet been computed. It is a convenient abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. + * @constructor + * @param init The function that is called during construction of the Promise that contains the implementation of the operation that the Promise will represent. This can be synchronous or asynchronous, depending on the nature of the operation. Note that placing code within this function does not automatically run it asynchronously; that must be done explicitly with other asynchronous APIs such as setImmediate, setTimeout, requestAnimationFrame, and the Windows Runtime asynchronous APIs. The init function is given three arguments: completeDispatch, errorDispatch, progressDispatch. This parameter is optional. + * @param onCancel The function to call if a consumer of this promise wants to cancel its undone work. Promises are not required to support cancellation. + **/ + constructor(init?: (completeDispatch: any, errorDispatch: any, progressDispatch: any) => void, onCancel?: Function); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when there is an error in processing a promise. + * @param eventInfo An object that contains information about the event. + **/ + onerror(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener for the promise. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event is raised. + * @param capture true to initiate capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Returns a promise that is fulfilled when one of the input promises has been fulfilled. + * @param value An array that contains Promise objects or objects whose property values include Promise objects. + * @returns A promise that on fulfillment yields the value of the input (complete or error). + **/ + static any(value: Promise[]): Promise; + + /** + * Returns a promise. If the object is already a Promise it is returned; otherwise the object is wrapped in a Promise. You can use this function when you need to treat a non-Promise object like a Promise, for example when you are calling a function that expects a promise, but already have the value needed rather than needing to get it asynchronously. + * @param value The value to be treated as a Promise. + * @returns The promise. + **/ + static as(value: U): Promise; + + /** + * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). + **/ + cancel(): void; + + /** + * Raises an event of the specified type and properties. + * @param type The type (name) of the event. + * @param details The set of additional properties to be attached to the event object. + * @returns true if preventDefault was called on the event; otherwise, false. + **/ + dispatchEvent(type: string, details: any): boolean; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + **/ + done(onComplete?: (value: T) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): void; + + /** + * Determines whether a value fulfills the promise contract. + * @param value A value that may be a promise. + * @returns true if the object conforms to the promise contract (has a then function), otherwise false. + **/ + static is(value: any): boolean; + + /** + * Creates a Promise that is fulfilled when all the values are fulfilled. + * @param values An object whose members contain values, some of which may be promises. + * @returns A Promise whose value is an object with the same field names as those of the object in the values parameter, where each field value is the fulfilled value of a promise. + **/ + static join(values: any): Promise; + + /** + * Removes an event listener from the control. + * @param eventType The type (name) of the event. + * @param listener The listener to remove. + * @param capture Specifies whether or not to initiate capture. + **/ + removeEventListener(eventType: string, listener: Function, capture?: boolean): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => Promise, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => Promise, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + + /** + * Performs an operation on all the input promises and returns a promise that has the shape of the input and contains the result of the operation that has been performed on each input. + * @param values A set of values (which could be either an array or an object) of which some or all are promises.. + * @param complete The function to be called if the promise is fulfilled with a value. This function takes a single argument, which is the fulfilled value of the promise. + * @param error The function to be called if the promise is fulfilled with an error. This function takes a single argument, which is the error value of the promise. + * @param progress The function to be called if the promise reports progress. This function takes a single argument, which is the data about the progress of the promise. Promises are not required to support progress. + * @returns A Promise that is the result of calling join on the values parameter. + **/ + static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): Promise; + + /** + * This method has two forms: WinJS.Promise.timeout(timeout) and WinJS.Promise.timeout(timeout, promise). WinJS.Promise.timeout(timeout) creates a promise that is completed asynchronously after the specified timeout, essentially wrapping a call to setTimeout within a promise. WinJS.Promise.timeout(timeout, promise) sets a timeout period for completion of the specified promise, automatically canceling the promise if it is not completed within the timeout period. + * @param timeout The timeout period in milliseconds. If this value is zero or not specified, msSetImmediate is called, otherwise setTimeout is called. + * @param promise Optional. A promise that will be canceled if it doesn't complete within the timeout period. + * @returns If the promise parameter is omitted, returns a promise that will be fulfilled after the timeout period. If the promise paramater is provided, the same promise is returned. + **/ + static timeout(timeout: number, promise?: Promise): Promise; + + /** + * Wraps a non-promise value in a promise. This method is like wrapError, which allows you to produce a Promise in error conditions, in that it allows you to return a Promise in success conditions. + * @param value Some non-promise value to be wrapped in a promise. + * @returns A promise that is successfully fulfilled with the specified value. + **/ + static wrap(value: U): Promise; + + /** + * Wraps a non-promise error value in a promise. You can use this function if you need to pass an error to a function that requires a promise. + * @param error A non-promise error value to be wrapped in a promise. + * @returns A promise that is in an error state with the specified value. + **/ + static wrapError(error: U): Promise; + + //#endregion Methods + + } + + //#endregion Objects + + //#region Functions + + /** + * You can provide an implementation of this method yourself, or use WinJS.Utilities.startLog to create one that logs to the JavaScript console. + * @param message The message to log. + * @param tags The tag or tags to categorize the message (winjs, winjs controls, etc.). + * @param type The type of message (error, warning, info, etc.). + **/ + function log(message: string, tags: string, type: string): void; + + /** + * This method has been deprecated. Strict processing is always on; you don't have to call this method to turn it on. + **/ + function strictProcessing(): void; + + /** + * Wraps calls to XMLHttpRequest in a promise. + * @param options The options that are applied to the XMLHttpRequest object, as follows: type, url, user, password, responseType, headers, data, customRequestInitializer. + * @returns A promise that returns the XMLHttpRequest object when it completes. + **/ + function xhr(options: IXHROptions): Promise; + + //#endregion Functions + + //#region Interfaces + + interface IXHROptions { + type?: string; + url: string; + user?: string; + password?: string; + headers?: any; + data: any; + responseType?: string; + } + + //#endregion Interfaces +} +/** + * Provides helper functions for defining namespaces. For more information, see Organizing your code with WinJS.Namespace. +**/ +declare module WinJS.Namespace { + //#region Functions + + /** + * Defines a new namespace with the specified name. For more information, see Organizing your code with WinJS.Namespace. + * @param name The name of the namespace. This could be a dot-separated name for nested namespaces. + * @param members The members of the new namespace. + * @returns The newly-defined namespace. + **/ + function define(name?: string, members?: any): any; + + /** + * Defines a new namespace with the specified name under the specified parent namespace. For more information, see Organizing your code with WinJS.Namespace. + * @param parentNamespace The parent namespace. + * @param name The name of the new namespace. + * @param members The members of the new namespace. + * @returns The newly-defined namespace. + **/ + function defineWithParent(parentNamespace?: any, name?: string, members?: any): any; + + //#endregion Functions + +} +/** + * Provides functionality for dealing with basic navigation, including the navigation stack. +**/ +declare module WinJS.Navigation { + //#region Properties + + /** + * Determines whether it is possible to navigate backwards. + **/ + var canGoBack: boolean; + + /** + * Determines if it is possible to navigate forwards. + **/ + var canGoForward: boolean; + + /** + * Gets or sets the navigation history. + **/ + var history: any; + + /** + * Gets or sets the current location. + **/ + var location: string; + + /** + * Gets or sets a user-defined object that represents the state associated with the current location. + **/ + var state: any; + + //#endregion Properties + + //#region Functions + + /** + * Adds an event listener to the control. + * @param eventType The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param capture If true, specifies that capture should be initiated, otherwise false. + **/ + function addEventListener(eventType: string, listener: Function, capture?: boolean): void; + + /** + * Navigates backwards. + * @param distance The number of entries to go back into the history. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful. + **/ + function back(distance?: number): Promise; + + /** + * Navigates forwards. + * @param distance The number of entries to go forward. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful. + **/ + function forward(distance?: number): Promise; + + /** + * Navigates to a location. + * @param location The location to navigate to. Generally the location is a string containing the URL, but it may be anything. + * @param initialState A user-defined object that represents the navigation state that may be accessed through state. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful (true if successful, otherwise false). + **/ + function navigate(location: any, initialState?: any): Promise; + + /** + * Removes an event listener from the control. + * @param eventType The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture Specifies whether or not to initiate capture. + **/ + function removeEventListener(eventType: string, listener: Function, useCapture?: boolean): void; + + //#endregion Functions + + //#region Events + + /** + * Occurs before navigation. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onbeforenavigate(eventInfo: CustomEvent): void; + + /** + * Occurs after navigation has taken place. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onnavigated(eventInfo: CustomEvent): void; + + /** + * Occurs when navigation is taking place. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onnavigating(eventInfo: CustomEvent): void; + + //#endregion Events + +} +/** + * Provides functions for accessing resources and localizing content. +**/ +declare module WinJS.Resources { + //#region Functions + + /** + * Registers an event handler for the specified event. Use this method to register for events that are related to resources, such as when the app's language, scale, or contrast changes. + * @param type The name of the event to handle. + * @param listener The listener (event handler function) to associate with the event. + * @param useCapture Set to true to register the listener for the capturing phase; otherwise, set to false to register the listener for the bubbling phase. + **/ + function addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The name of the event to raise. + * @param details The set of additional properties to attach to the event object. + **/ + function dispatchEvent(type: string, details: any): void; + + /** + * Retrieves the resource string that has the specified resource identifier. + * @param resourceId The resource ID of the string to retrieve. + * @returns An object that can contain these properties: value, empty, lang. + **/ + function getString(resourceId: string): { value: string; empty?: boolean; lang?: string; }; + + /** + * Processes data-win-res attributes on elements and replaces attributes and properties with resource strings. + * @param rootElement The element to process. The element and its child elements will be processed. If an element isn't specified, the entire document is processed. + **/ + function processAll(rootElement?: HTMLElement): void; + + /** + * Removes an event listener that the addEventListener method registered. + * @param type The name of the event that the event listener is registered for. + * @param listener The listener (event handler function) to remove. + * @param useCapture Set to true to remove the capturing phase listener; set to false to remove the bubbling phase listener. + **/ + function removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Functions + + //#region Events + + /** + * Occurs when the user changes the system's language or contrast, or the scale of the display, or when the user changes any of the items in the current context's qualifier values list. For more info about the current context's qualifier values list, see the Remarks section. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.qualifier, detail.changed. + **/ + function oncontextchanged(eventInfo: CustomEvent): void; + + //#endregion Events + +} +/** + * Provides access to the Windows animations. These functions provide developers with the ability to use animations in their custom controls that are consistent with animations used by Windows controls. +**/ +declare module WinJS.UI.Animation { + //#region Functions + + /** + * Scales up an incoming page while scaling, rotating (clockwise), and translating an incoming item into place. + * @param incomingPage A single element to be scaled up that is the page root and does not contain the incoming item. + * @param incomingItemRoot The root of the item. This is translated during the continuum animation. + * @param incomingItemContent The content of the item. This is scaled and rotated during the continuum animation. + * @returns An object that returns when the animation has finished. + **/ + function continuumForwardIn(incomingPage: any, incomingItemRoot: any, incomingItemContent: any): Promise; + + /** + * Scales down a page while scaling, rotating (clockwise), and translating an outgoing item. + * @param outgoingPage A single element to be scaled down that is the page root and contains the outgoing item. + * @param outgoingItem A single element to be scaled, rotated, and translated away from the outgoing page. + * @returns An object that returns when the animation has finished. + **/ + function continuumForwardOut(outgoingPage: any, outgoingItem: any): Promise; + + /** + * Scales down an incoming page while scaling, rotating (counterclockwise), and translating an incoming item into place. + * @param incomingPage A single element to be scaled down that is the page root and contains the incoming item. + * @param incomingItem A single element to be scaled, rotated, and translated into its final position on the page. + * @returns An object that returns when the animation has finished. + **/ + function continuumBackwardIn(incomingPage: any, incomingItem: any): Promise; + + /** + * Scales, rotates (counterclockwise), and translates an outgoing page as it is removed. + * @param incomingPage A single element to be scaled down that is the page root. + * @returns An object that returns when the animation has finished. + **/ + function continuumBackwardOut(outgoingPage: any): Promise; + + /** + * Creates an object that performs an animation that adds an item or items to a list. + * @param added Element or elements to add to the list. + * @param affected Element or elements affected by the added items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createAddToListAnimation(added: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that adds an item or items to a list of search results. + * @param added Element or elements to add to the list. + * @param affected Element or elements affected by the added items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createAddToSearchListAnimation(added: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that collapses a list. + * @param hidden Element or elements hidden as a result of the collapse. + * @param affected Element or elements affected by the hidden items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createCollapseAnimation(hidden: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that removes an item or items from a list. + * @param deleted Element or elements to delete from the list. + * @param remaining Element or elements affected by the removal of the deleted items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createDeleteFromListAnimation(deleted: any, remaining: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that removes an item or items from a list of search results. + * @param deleted Element or elements to delete from the list. + * @param remaining Element or elements affected by the removal of the deleted items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createDeleteFromSearchListAnimation(deleted: any, remaining: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that expands a list. + * @param revealed Element or elements revealed by the expansion. + * @param affected Element or elements affected by the newly revealed items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createExpandAnimation(revealed: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an exit and entrance animation to play for a page navigation given the current and incoming pages' animation preferences and whether the pages are navigating forwards or backwards. + * @param currentPreferredAnimation Describes the animation the current page prefers to use. + * @param nextPreferredAnimation Describes the animation the incoming page prefers to use. + * @param movingBackwards Determines whether the navigation is moving backwards + * @returns An object that contains an exit method used for animating exiting pages and an enter method used for animating entering pages. + **/ + function createPageNavigationAnimation(currentPreferredAnimation: PageNavigationAnimation, nextPreferredAnimation: PageNavigationAnimation, movingBackwards: boolean): { enter: () => any, exit: () => any }; + + /** + * Creates an object that performs a peek animation. + * @param element Element or elements involved in the peek. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createPeekAnimation(element: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that moves an item or items. + * @param element Element or elements involved in the reposition. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise object that completes when the animation is finished. + **/ + function createRepositionAnimation(element: any): IAnimationMethodResponse; + + /** + * Performs an animation that fades an item or items in, fading out existing items that occupy the same space. + * @param incoming Element or elements being faded in. + * @param outgoing Element or elements being replaced. + * @returns An object that completes when the animation has finished. + **/ + function crossFade(incoming: any, outgoing: any): Promise; + + /** + * Performs an animation when a dragged object is moved such that dropping it in that position would move other items. The potentially affected items are animated out of the way to show where the object would be dropped. + * @param target Element or elements that the dragged object would cause to be moved if it were dropped. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function dragBetweenEnter(target: any, offset: any): Promise; + + /** + * Performs an animation when a dragged object is moved away from items that it had previously involved in a dragBetweenEnter animation. The affected objects are animated back to their original positions. + * @param target Element or elements that the dragged object would no longer cause to be displaced, due to its moving away. This should be the same element or element collection passed as the target parameter in the dragBetweenEnter animation. + * @returns An object that completes when the animation is finished. + **/ + function dragBetweenLeave(target: any): Promise; + + /** + * Performs an animation when the user finishes dragging an object. + * @param dragSource Element or elements that were dragged. + * @param offset Initial offset from the drop point. The dropped object begins at the offset and animates to its final position at the drop point. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param affected Element or elements whose position the dropped object affects. Typically, this is all other items in a reorderable list. This should be the same element or element collection passed as the affected parameter in the dragSourceStart animation. + * @returns An object that completes when the animation is finished. + **/ + function dragSourceEnd(dragSource: any, offset: any, affected?: any): Promise; + + /** + * Performs an animation when the user begins to drag an object. + * @param dragSource Element or elements being dragged. + * @param affected Element or elements whose position is affected by the movement of the dragged object. Typically, this is all other items in a reorderable list. + * @returns An object that completes when the animation is finished. + **/ + function dragSourceStart(dragSource: any, affected?: any): Promise; + + /** + * Performs an animation that displays one or more elements on a page. + * @param incoming Element or elements that compose the incoming content. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function enterContent(incoming: any, offset: any, options?: any): Promise; + + /** + * Performs an animation that shows a new page of content, either when transitioning between pages in a running app or when displaying the first content in a newly launched app. + * @param element Element or an array of elements that represent the content. If element refers to an array of elements, the elements enter in array order. + * @param offset An initial offset where the element or elements begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function enterPage(element: any, offset: any): Promise; + + /** + * Performs an animation that hides one or more elements on a page. + * @param outgoing Element or elements that compose the outgoing content. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function exitContent(outgoing: any, offset: any): Promise; + + /** + * Performs an animation that dismisses the current page when transitioning between pages in an app. + * @param outgoing Element or elements that compose the outgoing page. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function exitPage(outgoing: any, offset: any): Promise; + + /** + * Performs an animation that fades an item or set of items into view. + * @param shown Element or elements being faded in. + * @returns An object that completes when the animation has finished. Use this object when subsequent actions need this animation to finish before they take place. + **/ + function fadeIn(shown: any): Promise; + + /** + * Performs an animation that fades an item or set of items out of view. + * @param hidden Element or elements being faded out. + * @returns An object that completes when the animation is finished. + **/ + function fadeOut(hidden: any): Promise; + + /** + * Performs an animation that hides edge-based user interface (UI). + * @param element Element or elements that are being hidden. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function hideEdgeUI(element: any, offset: any, options?: any): Promise; + + /** + * Performs an animation that hides a panel. + * @param element Element or elements that are being hidden. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function hidePanel(element: any, offset: any): Promise; + + /** + * Performs an animation that removes pop-up user interface (UI). + * @param element Element or elements that are being hidden. + * @returns An object that completes when the animation is finished. + **/ + function hidePopup(element: any): Promise; + + /** + * Performs an animation when a pointer is pressed on an object. + * @param element Element or elements on which the pointer is pressed. + * @returns An object that completes when the animation is finished. + **/ + function pointerDown(element: any): Promise; + + /** + * Performs an animation when a pointer is released. + * @param element Element or elements that the pointer was pressed on. + * @returns An object that completes when the animation is finished. + **/ + function pointerUp(element: any): Promise; + + /** + * Performs an animation that slides a narrow, edge-based user interface (UI) into view. + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function showEdgeUI(element: any, offset: any, options?: any): Promise; + + /** + * Performs an animation that slides a large panel user interface (UI) into view. + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function showPanel(element: any, offset: any): Promise; + + /** + * Performs an animation that displays a pop-up user interface (UI). + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function showPopup(element: any, offset: any): Promise; + + /** + * Slides elements off through the bottom of the screen. + * @param outgoing Single element or an array of elements that represent the content. If an array of elements, the elements exit in array order. + * @returns An object that completes when the animation is finished. + **/ + function slideDown(outgoing: any): Promise; + + /** + * Slides elements up into view from the bottom of the screen. + * @param incoming Single element or an array of elements that represent the content. If an array of elements, the elements exit in array order. + * @returns An object that completes when the animation is finished. + **/ + function slideUp(outgoing: any): Promise; + + /** + * Slides elements in from the right side of the screen. + * @param page A page that contains all of the elements to slide in. + * @param firstIncomingElements A single element or an array of elements to slide in first. If this is an array of elements, all elements enter at once. + * @param secondIncomingElements A single element or an array of elements to slide in once the firstIncomingElements are in place. If this is an array of elements, all elements enter at once. These elements are offset slightly more than the firstIncomingElements. + * @param thirdIncomingElements A single element or an array of elements to slide in once the secondIncomingElements are in place. If this is an array of elements, all elements enter at once. These elements are offset slightly more than the secondIncomingElements. + * @returns An object that completes when the animation is finished. + **/ + function slideRightIn(page: any, firstIncomingElements: any, secondIncomingElements: any, thirdIncomingElements: any): Promise; + + /** + * Slides elements out through the right side of the screen. + * @param page A page that contains all of the elements to slide out. + * @param firstOutgoingElements A single element or an array of elements to slide out first. If this is an array of elements, the elements exit in array order. + * @param secondOutgoingElements A single element or an array of elements to slide out once the firstOutgoingElements are gone. If this is an array of elements, the elements exit simultaneously. These elements are offset slightly more than the firstOutgoingElements. + * @param thirdOutgoingElements A single element or an array of elements to slide out once the secondOutgoingElements are gone. If this is an array of elements, the elements exit simultaneously. These elements are offset slightly more than the secondOutgoingElements. + * @returns An object that completes when the animation is finished. + **/ + function slideRightOut(page: any, firstOutgoingElements: any, secondOutgoingElements: any, thirdOutgoingElements: any): Promise; + + /** + * Slides elements in from the left side of the screen. + * @param page A page that contains all of the elements to slide in. + * @param firstIncomingElements A single element or an array of elements to slide in first. If this is an array of elements, all elements enter at once. + * @param secondIncomingElements A single element or an array of elements to slide in once the firstIncomingElements are in place. If this is an array of elements, all elements enter at once. These elements are offset slightly more than the firstIncomingElements. + * @param thirdIncomingElements A single element or an array of elements to slide in once the secondIncomingElements are in place. If this is an array of elements, all elements enter at once. These elements are offset slightly more than the secondIncomingElements. + * @returns An object that completes when the animation is finished. + **/ + function slideLeftIn(page: any, firstIncomingElements: any, secondIncomingElements: any, thirdIncomingElements: any): Promise; + + /** + * Slides elements out through the left side of the screen. + * @param page A page that contains all of the elements to slide out. + * @param firstOutgoingElements A single element or an array of elements to slide out first. If this is an array of elements, the elements exit in array order. + * @param secondOutgoingElements A single element or an array of elements to slide out once the firstOutgoingElements are gone. If this is an array of elements, the elements exit simultaneously. These elements are offset slightly more than the firstOutgoingElements. + * @param thirdOutgoingElements A single element or an array of elements to slide out once the secondOutgoingElements are gone. If this is an array of elements, the elements exit simultaneously. These elements are offset slightly more than the secondOutgoingElements. + * @returns An object that completes when the animation is finished. + **/ + function slideLeftOut(page: any, firstOutgoingElements: any, secondOutgoingElements: any, thirdOutgoingElements: any): Promise; + + /** + * Performs a deselection animation in response to a swipe interaction. + * @param deselected Element or elements that become unselected. + * @param selection Element or elements that represent the selection, typically a check mark. + * @returns An object that completes when the animation is finished. + **/ + function swipeDeselect(deselected: any, selection: any): Promise; + + /** + * Performs an animation that reveals an item or items in response to a swipe interaction. + * @param target Element or elements being revealed. + * @param offset An initial offset where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function swipeReveal(target: any, offset: any): Promise; + + /** + * Performs a selection animation in response to a swipe interaction. + * @param selected Element or elements being selected. + * @param selection Element or elements that show that something is selected, typically a check mark. + * @returns An object that completes when the animation is finished. + **/ + function swipeSelect(selected: any, selection: any): Promise; + + /** + * Rotates an element clockwise onto the page. + * @param incoming Single element or an array of elements that represent the content. If an array of elements, the elements enter in array order.. + * @returns An promise that completes when the animation has finished. + **/ + function turnstileForwardIn(incoming: any): Promise; + + /** + * Rotates an element clockwise off the page. + * @param outgoing Single element or an array of elements that represent the content. If an array of elements, the elements enter in array order.. + * @returns An promise that completes when the animation has finished. + **/ + function turnstileForwardOut(outgoing: any): Promise; + + /** + * Rotates an element counterclockwise onto the page. + * @param incoming Single element or an array of elements that represent the content. If an array of elements, the elements enter in array order.. + * @returns An promise that completes when the animation has finished. + **/ + function turnstileBackwardIn(incoming: any): Promise; + + /** + * Rotates an element counterclockwise off the page. + * @param outgoing Single element or an array of elements that represent the content. If an array of elements, the elements enter in array order.. + * @returns An promise that completes when the animation has finished. + **/ + function turnstileBackwardOut(outgoing: any): Promise; + + + /** + * Performs an animation that updates a badge. + * @param incoming Element or elements that comprise the new badge. + * @param offset Initial offsets where incoming animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function updateBadge(incoming: any, offset: any): Promise; + + //#endregion Functions + + //#region Interfaces + + interface IAnimationMethodResponse { + execute(): Promise; + } + + //#endregion Interfaces + +} +/** + * Provides controls and objects that manipulate data. +**/ +declare module WinJS.UI { + //#region Enumerations + + /** + * Specifies an icon that appears in an AppBarCommand object. + **/ + enum AppBarIcon { + previous, + next, + play, + pause, + edit, + save, + clear, + delete, + remove, + add, + cancel, + accept, + more, + redo, + undo, + home, + up, + forward, + right, + back, + left, + favorite, + camera, + settings, + video, + sync, + download, + mail, + find, + help, + upload, + emoji, + twopage, + leavechat, + mailforward, + clock, + send, + crop, + rotatecamera, + people, + closepane, + openpane, + world, + flag, + previewlink, + globe, + trim, + attachcamera, + zoomin, + bookmarks, + document, + protecteddocument, + page, + bullets, + comment, + mail2, + contactinfo, + hangup, + viewall, + mappin, + phone, + videochat, + switch, + contact, + rename, + pin, + musicinfo, + go, + keyboard, + dockleft, + dockright, + dockbottom, + remote, + refresh, + rotate, + shuffle, + list, + shop, + selectall, + orientation, + import, + importall, + browsephotos, + webcam, + pictures, + savelocal, + caption, + stop, + showresults, + volume, + repair, + message, + page2, + calendarday, + calendarweek, + calendar, + characters, + mailreplyall, + read, + link, + accounts, + showbcc, + hidebcc, + cut, + attach, + paste, + filter, + copy, + emoji2, + important, + mailreply, + slideshow, + sort, + manage, + allapps, + disconnectdrive, + mapdrive, + newwindow, + openwith, + contactpresence, + priority, + uploadskydrive, + gototoday, + font, + fontcolor, + contact2, + folder, + audio, + placeholder, + view, + setlockscreen, + settile, + cc, + stopslideshow, + permissions, + highlight, + disableupdates, + unfavorite, + unpin, + openlocal, + mute, + italic, + underline, + bold, + movetofolder, + likedislike, + dislike, + like, + alignright, + aligncenter, + alignleft, + zoom, + zoomout, + openfile, + otheruser, + admin, + street, + map, + clearselection, + fontdecrease, + fontincrease, + fontsize, + cellphone, + reshare, + tag, + repeatone, + repeatall, + outlinestar, + solidstar, + calculator, + directions, + target, + library, + phonebook, + memo, + microphone, + postupdate, + backtowindow, + fullscreen, + newfolder, + calendarreply, + unsyncfolder, + reporthacked, + syncfolder, + blockcontact, + switchapps, + addfriend, + touchpointer, + gotostart, + zerobars, + onebar, + twobars, + threebars, + fourbars, + scan, + preview + } + + /** + * Indicates whether the IListDataAdapter was able to provide a count. + **/ + enum CountResult { + /** + * Indicates no count is available. + **/ + unknown + } + + /** + * Indicates that the IListDataAdapter was unable to provide a count. + **/ + enum CountError { + /** + * An attempt to count items timed out. + **/ + noResponse + } + + /** + * Describes the status of an IListDataSource. + **/ + enum DataSourceStatus { + /** + * The IListDataSource is ready. + **/ + ready, + /** + * The IListDataSource is still loading. + **/ + waiting, + /** + * The IListDataSource failed to load. + **/ + failure + } + + /** + * Specifies the type of error that occurred during an edit operation on a IListDataSource or an IListDataAdapter. + **/ + enum EditError { + /** + * The edit operation timed out. + **/ + noResponse, + /** + * The data source cannot be written to. + **/ + notPermitted, + /** + * The item has changed. + **/ + noLongerMeaningful + } + + /** + * Specifies the type of error encountered when retrieving items from an IListDataAdapter. + **/ + enum FetchError { + /** + * The fetch operation timed out. + **/ + noResponse, + /** + * The specified item could not be located. + **/ + doesNotExist + } + + /** + * Specifies how group headers in a ListView respond to the tap interaction. + **/ + enum GroupHeaderTapBehavior { + /** + * The group is invoked. + **/ + invoke, + /** + * Nothing happens. + **/ + none + } + + /** + * Specifies the position of group headers relative to their items in a ListView. + **/ + enum HeaderPosition { + /** + * Group headers appear to the left of items. + **/ + left, + /** + * Group headers appear above items. + **/ + top + } + + /** + * Specifies that type of animation for which a contentanimating event was raised. + **/ + enum ListViewAnimationType { + /** + * The animation plays when the ListView is first displayed. + **/ + entrance, + /** + * The animation plays when the ListView is changing its content. + **/ + contentTransition + } + + /** + * Describes the type of object in a ListView. + **/ + enum ObjectType { + /** + * The object is a group header in the list. + **/ + groupHeader, + /** + * The object is an item in the list. + **/ + item + } + + /** + * Specifies the orientation of a control. + **/ + enum Orientation { + /** + * A horizontal layout. + **/ + horizontal, + /** + * A vertical layout. + **/ + vertical + } + + enum PageNavigationAnimation { + /** + * The pages exit and enter using a turnstile animation. + **/ + turnstile, + /** + * The pages exit and enter using an animation that slides up/down. + **/ + slide, + /** + * The pages enter using an enterPage animation, and exit with no animation. + **/ + enterPage, + /** + * The pages exit and enter using a continuum animation. + **/ + continuum + } + + /** + * Specifies the selection mode of a ListView. + **/ + enum SelectionMode { + /** + * Items cannot be selected. + **/ + none, + /** + * Multiple items may be selected. Clicking additional items adds them to the selection. + **/ + multi + } + + /** + * Specifies how items in a ListView respond to the tap interaction. + **/ + enum TapBehavior { + /** + * The item is selected and invoked. + **/ + directSelect, + /** + * The item is selected if was not already selected, and its deselected if it was already selected. + **/ + toggleSelect, + /** + * The item is invoked but not selected. + **/ + invokeOnly, + /** + * Nothing happens. + **/ + none + } + + //#endregion Enumerations + + //#region Interfaces + + /** + * Contains items that were requested from an IListDataAdapter and provides some information about those items. + **/ + interface IFetchResult { + //#region Properties + + /** + * Gets or sets the index of the requested item in the IListDataAdapter object's data source. + **/ + absoluteIndex: number; + + /** + * Gets or sets a value that indicates whether this IFetchResult contains the last items at the end of the IListDataAdapter object's data source. + **/ + atEnd: boolean; + + /** + * Gets or sets a value that indicates whether this IFetchResult contains the first items at the beginning of the IListDataAdapter object's data source. + **/ + atStart: boolean; + + /** + * Gets or sets the items returned by the fetch operation. + **/ + items: T[]; + + /** + * Gets or sets the location of the requested item within the items array. + **/ + offset: number; + + /** + * Gets or sets the number of items in the IListDataAdapter object's underlying data source. + **/ + totalCount: number; + + //#endregion Properties + + } + + /** + * Represents an item in a list. + **/ + interface IItem { + //#region Properties + + /** + * Gets or sets the item's data. + **/ + data: T; + + /** + * Gets the group key for the item. This property is only available for items that belong to a grouped data source. + **/ + groupKey: string; + + /** + * Gets the temporary ID of the item. + **/ + handle: string; + + /** + * Gets the item's index in the IListDataSource. + **/ + index: number; + + /** + * Gets or sets the key the identifies the item. + **/ + key: string; + + //#endregion Properties + + } + + /** + * Provides a mechanism for retrieving IItem objects asynchronously. + **/ + interface IItemPromise { + //#region Events + + /** + * Occurs when there is an error in processing. + * @param eventInfo An object that contains information about the event. + **/ + onerror(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). + **/ + cancel(): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + **/ + done(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): void; + + /** + * Stops change notification tracking for the IItem that fulfills this IItemPromise. + **/ + release(): void; + + /** + * Begins change notification tracking for the IItem that fulfills this IItemPromise. + **/ + retain(): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function becomes the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the complete or error function. + **/ + then(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): IItemPromise; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the temporary ID of the IItem that fulfills this promise. + **/ + handle: string; + + /** + * Gets or sets the index of the IItem contained by this IItemPromise. + **/ + index: number; + + //#endregion Properties + + } + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. Represents a layout for the ListView. + **/ + interface ILayout { + //#region Methods + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param beginScrollPosition The first visible pixel in the ListView. For horizontal layouts, this is the x-coordinate of the pixel. For vertical layouts, this is the y-coordinate. + * @param wholeItem true if the item must be completely visible; otherwise, false if its ok for the item to be partially visible. Promise. + * @returns A Promise for the index of the first visible item at the specified point. + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param endScrollPosition The last visible pixel in the ListView. For horizontal layouts, this is the x-coordinate of the pixel. For vertical layouts, this is the y-coordinate. + * @param wholeItem true if the item must be completely visible; otherwise, false if its ok for the item to be partially visible. Promise. + * @returns A Promise for the index of the last visible item at the specified point. + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @returns A object that has these properties: animationPromise, newEndIndex. + **/ + endLayout(): any; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param itemIndex The index of the item. + * @returns A Promise that returns an object with these properties: left, top, contentWidth, contentHeight, totalWidth, totalHeight. + **/ + getItemPosition(itemIndex: number): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param itemIndex The data source index of the current item. + * @param element The element for the current item. + * @param keyPressed The key that was pressed. This function must check for the arrow keys (leftArrow, upArrow, rightArrow, downArrow), pageDown, and pageUp and determine which item the user navigated to. + * @returns A Promise that contains the index of the next item (This item becomes the current item). + **/ + getKeyboardNavigatedItem(itemIndex: number, element: HTMLElement, keyPressed: WinJS.Utilities.Key): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @returns A Promise that returns an object that has these properties: beginScrollPosition, endScrollPosition. + **/ + getScrollBarRange(): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param x The x-coordinate to test. + * @param y The y-coordinate to test. + **/ + hitTest(x: number, y: number): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param elements The elements that represent the items that were added. + **/ + itemsAdded(elements: HTMLElement[]): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + **/ + itemsMoved(): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param elements The elements that represent the items that were removed. + **/ + itemsRemoved(elements: HTMLElement[]): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param groupIndex The index of the group in the group data source. + * @param element The element to render for the group header. + **/ + layoutHeader(groupIndex: number, element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param itemIndex The index of the item in the data source. + * @param element The element to render for the item. + **/ + layoutItem(itemIndex: number, element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param element The element that represents a header in the data source. + **/ + prepareHeader(element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param element An element that represents an item in the data source. + **/ + prepareItem(element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param element The element being released. + **/ + releaseItem(element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + **/ + reset(): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param site The layout site for the layout. You can use this object to query the hosting ListView for info you might need to lay out items. + **/ + setSite(site: ILayoutSite): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param beginScrollPosition The starting pixel of the area to which the items are rendered. + * @param endScrollPosition The last pixel of the area to which the items are rendered. + * @param count The upper bound of the number of items to render. + * @returns A Promise that returns an object that has these properties: beginIndex, endIndex. + **/ + startLayout(beginScrollPosition: number, endScrollPosition: number, count: number): Promise; + + //#endregion Methods + + //#region Properties + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + **/ + horizontal: boolean; + + //#endregion Properties + + } + + /** + * Represents a layout for the ListView. + **/ + interface ILayout2 { + //#region Methods + + /** + * Called when the ListView finishes a drag operation. + **/ + dragLeave(): void; + + /** + * Called when the ListView initiates a drag operation. + * @param x The x-coordinate of the drag. + * @param y The y-coordinate of the drag. + * @param dragInfo An object that indicates whether the item is selected. + **/ + dragOver(x: number, y: number, dragInfo: number): void; + + /** + * Called when the ListView requests that the ILayout2 execute animations. + **/ + executeAnimations(): void; + + /** + * Determines the next item to receive keyboard focus. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + + /** + * Gets the item at the specified hit-test coordinates. These coordinates are absolute coordinates (they are not relative to the layout's content area). + * @param x The x-coordinate to test for. + * @param y The y-coordinate to test for. + * @returns An object that describes the item at the hit test coordinates. It has these properties: type, index. + **/ + hitTest(x: number, y: number): any; + + /** + * Sets the rendering site and specifies whether the layout supports groups. This method is called by the ListView to initialize the layout. + * @param site The rendering site for the layout. + * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. + **/ + initialize(site: ILayoutSite2, groupsEnabled: boolean): void; + + /** + * Retrieves the indexes of the items in the specified pixel range. + * @param firstPixel The first pixel the range of items falls between. + * @param lastPixel The last pixel the range of items falls between. + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * Performs a layout pass. + * @param tree A structure representing the layout tree that is returned from the ListView. + * @param changedRange An object that lists the index of the first item in the changed item range. This object has these properties: startIndex. + * @param modifiedItems An object that contains the old and new indexes of the items that have been modified in the tree. + * @param modifiedGroups An object that contains the old and new indexes of the group elements that have been modified in the tree. + * @returns A Promise that executes after layout is complete, or an object that contains two Promise objects: realizedRangeComplete, layoutComplete. + **/ + layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): any; + + /** + * Called when the ListView requests that the ILayout2 set up animations. + **/ + setupAnimations(): void; + + /** + * Releases resources that were obtained during the call to initialize. + **/ + uninitialize(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the orientation of the layout. + **/ + orientation: any; + + //#endregion Properties + + } + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayoutSite2 interface. Represents a rendering site for an ILayout. + **/ + interface ILayoutSite { + //#region Properties + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + animationsDisabled: boolean; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + itemSurface: HTMLElement; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + rtl: boolean; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + scrollbarPos: number; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + surface: HTMLElement; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + viewport: HTMLElement; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + viewportSize: any; + + //#endregion Properties + + } + + /** + * Represents a rendering site for an ILayout2. + **/ + interface ILayoutSite2 { + //#region Properties + + /** + * Gets the number of groups in the site. + **/ + groupCount: number; + + /** + * Gets the number of items in the site. + **/ + itemCount: Promise; + + /** + * Gets the pixel range of the realization area. + **/ + realizedRange: any; + + /** + * Gets the tree for use by an object that implements the ILayout2 interface. + **/ + tree: any; + + /** + * Gets the pixel range of visible items in the site. + **/ + visibleRange: any; + + //#endregion Properties + + } + + /** + * Retrieves items from a IListDataSource, enumerates the contents of a IListDataSource, and can optionally register for change notifications. + **/ + interface IListBinding { + //#region Methods + + /** + * Retrieves the current item. + * @returns An IItemPromise that contains the current item. If the cursor has moved past the start or end of the list, the promise completes with a value of null. If the current item has been moved or deleted, the promise returns an error. + **/ + current(): IItemPromise>; + + /** + * Gets the first item from the IListDataSource and makes it the current item. + * @returns An IItemPromise that contains the requested IItem. If the list is empty, the promise completes with a value of null. + **/ + first(): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified description and makes it the current item. + * @param description A domain-specific description, to be interpreted by the IListDataAdapter, that identifies the item to retrieve. + * @returns An IItemPromise that contains the requested IItem object. If the item wasn't found, the promise completes with a value of null. + **/ + fromDescription(description: string): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified index and makes it the current item. + * @param index A value greater than or equal to 0 that is the index of the item to retrieve. + * @returns An IItemPromise that contains the requested IItem. If the item wasn't found, the promise completes with a value of null. + **/ + fromIndex(index: number): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified key and makes it the current item. + * @param key The key that identifies the item to retrieve. This value must be a non-empty string. + * @param hints Domain-specific information that provides additional information to the IListDataAdapter to improve retrieval time. + * @returns An IItemPromise that contains the requested IItem. If they item couldn't be found, the promise completes with a value of null. + **/ + fromKey(key: string, hints?: any): IItemPromise>; + + /** + * Makes the specified IItem or IItemPromise the current item. + * @param item The IItem or IItemPromise that will become the current item. + * @returns An IItemPromise that contains the specified item, if it exists. If the specified item is not in the list, the promise completes with a value of null. + **/ + jumpToItem(item: IItem): IItemPromise>; + + /** + * Retrieves the last item in the IListDataSource and makes it the current item. + * @returns An IItemPromise that contains the requested IItem. f the list is empty, the promise completes with a value of null. + **/ + last(): IItemPromise>; + + /** + * Retrieves the item after the current item and makes it the current item. + * @returns An IItemPromise that contains the item after the current item. If the cursor moves past the end of the list, the promise completes with a value of null. + **/ + next(): IItemPromise>; + + /** + * Retrieves the item before the current item and makes it the current item. + * @returns An IItemPromise that contains the item before the current item. If the cursor moves past the start of the list, the promise completes with a value of null. + **/ + previous(): IItemPromise>; + + /** + * Releases resources, stops notifications, and cancels outstanding promises for all tracked items returned by this IListBinding. + **/ + release(): void; + + /** + * Creates a request to stop change notifications for the specified item. The change notifications stop when the number of releaseItem calls matches the number of IIItemPromise.retain calls. + * @param item The IItem or IItemPromise that should stop receiving notifications. + **/ + releaseItem(item: IItem): void; + + //#endregion Methods + + } + + /** + * Accesses data for an IListDataSource. + **/ + interface IListDataAdapter { + //#region Methods + + /** + * Overwrites the data of the specified item. + * @param key The key of the item to overwrite. + * @param newData The new data for the item. + * @param indexHint The index of the item, if known. + * @returns A Promise that returns null or undefined when the operation completes. + **/ + change(key: string, newData: T, indexHint: number): Promise; + + /** + * Gets the number of items in the IListDataAdapter object's data source. + * @returns A Promise that contains the number of items the IListDataAdapter contains, or an approximate value if the actual number is unknown. + **/ + getCount(): Promise; + + /** + * Inserts the specified data after the specified item. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @param previousKey The key of an item in the IListDataAdapter object's data source. The new data will be inserted after this item. + * @param previousIndexHint The index of the item to insert the new data after, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAfter(key: string, data: T, previousKey: string, previousIndexHint: number): Promise>; + + /** + * Adds the specified key and data to the end of the IListDataAdapter object's data source. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtEnd(key: string, data: T): Promise>; + + /** + * Adds the specified key and data to the beginning of the IListDataAdapter object's data source. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtStart(key: string, data: T): Promise>; + + /** + * Inserts the specified data before the specified item. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @param nextKey The key of an item in the IListDataAdapter object's data source. The new data will be inserted before this item. + * @param nextIndexHint The index of the item to insert the new data before, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertBefore(key: string, data: T, nextKey: string, nextIndexHint: number): Promise>; + + /** + * Retrieves the item that matches the specified description and also retrieves the specified number of items before and after the matched item. + * @param description A description of the item to locate. + * @param countBefore The number of items before the matched item to retrieve. + * @param countAfter The number of items after the matched item to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromDescription(description: string, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the specified number of items from the end of the IListDataAdapter object's data source. + * @param count The number of items to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromEnd(count: number): Promise>; + + /** + * Retrieves the item at the specified index and also retrieves the specified number of items before and after the selected item. + * @param index The index of the item to retrieve. + * @param countBefore The number of items to retrieve from before the selected item. + * @param countAfter The number of items to retrieve from after the selected item. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromIndex(index: number, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the item that has the specified key and also retrieves the specified number of items before and after the selected item. + * @param key The key of the item to retrieve. + * @param countBefore The number of items to retrieve from before the selected item. + * @param countAfter The number of items to retrieve from after the selected item. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromKey(key: string, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the specified number of items from the beginning of the IListDataAdapter object's data source. + * @param count The number of items to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromStart(count: number): Promise>; + + /** + * Returns a string representation of the specified item that can be used for comparisons. + * @param item The item for which to generate a signature. + * @returns The signature representation of the specified item. + **/ + itemSignature(item: IItem): string; + + /** + * Moves the specified item to just after another item. + * @param key A key of the item to move. + * @param previousKey The key of another item. The item to move will be moved to just after this item. + * @param indexHint The index of the item to move, if known. + * @param previousIndexHint The index to move the item after, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveAfter(key: string, previousKey: any, indexHint: string, previousIndexHint: number): Promise>; + + /** + * Moves the specified item to just before another item. + * @param key A key of the item to move. + * @param nextKey The key of another item. The item to move will be moved to just before this item. + * @param indexHint The index of the item to move, if known. + * @param nextIndexHint The index to move the item before, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveBefore(key: string, nextKey: any, indexHint: string, nextIndexHint: number): Promise>; + + /** + * Moves the specified item to the end of the IListDataAdapter object's data source. + * @param key The key for the item to move. + * @param indexHint The index of the item to move, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveToEnd(key: string, indexHint: number): Promise>; + + /** + * Moves the specified item to the beginning of the IListDataAdapter object's data source. + * @param key The key for the item to move. + * @param indexHint The index of the item to move, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveToStart(key: string, indexHint: number): Promise>; + + /** + * Removes the specified item from the IListDataAdapter object's data source. + * @param key The key of the item to remove. + * @param data The new data for the item. + * @param indexHint The index of the item. + * @returns A Promise that returns null or undefined when the operation completes. + **/ + remove(key: string, data: T, indexHint: number): Promise; + + /** + * Registers a notification handler. The IListDataAdapter uses the handler to notify listening objects when its data changes. + * @param notificationHandler The notification handler that the IListDataAdapter will use to provide change notifications. . + **/ + setNotificationHandler(notificationHandler: IListDataNotificationHandler): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether to use an object's identity to determine if an item has changed. + **/ + compareByIdentity: boolean; + + //#endregion Properties + + } + + /** + * Notifies clients when an IListDataAdapter object's data changes. + **/ + interface IListDataNotificationHandler { + //#region Methods + + /** + * Indicates the start of a notification batch. Objects that are listening for notifications should defer making updates until endNotifications is called. + **/ + beginNotifications(): void; + + /** + * Raises a notification that an item in the IListDataAdapter object's data source has changed. + * @param item The item that changed. + **/ + changed(item: IItem): void; + + /** + * Indicates the end of a notification batch. When the beginNotifications method is called, objects listening for notifications should defer making updates until endNotifications is called. + **/ + endNotifications(): void; + + /** + * Raises a notification that an item has been added to the IListDataAdapter object's data source. + * @param newItem The new item added to the IListDataAdapter object's data source. + * @param previousKey The key of the item that now precedes the new item, or null if the item was inserted at the start of the list. If nextKey is provided, this parameter may be null. + * @param nextKey The key of the item that now follows the new item, or null if the item was inserted at the end of the list. If previousKey is provided, this parameter may be null. + * @param index The index of the new item. + **/ + inserted(newItem: IItem, previousKey: string, nextKey: string, index?: number): void; + + /** + * Indicates that all previous data obtained from the IListDataAdapter is invalid and should be refreshed. + * @returns A Promise that completes when the data has been completely refreshed and all change notifications have been sent. + **/ + invalidateAll(): Promise; + + /** + * Raises a notification that an item was moved within the IListDataAdapter object's data source. + * @param item The item that was moved. + * @param previousKey The key of the item that now precedes the new item, or null if the item was moved to the beginning of the list. If nextKey is provided, this parameter may be null. + * @param nextKey The key of the item that now follows the new item, or null if the item was moved to the end of the list. If previousKey is provided, this parameter may be null. + * @param oldIndex The item's original index. + * @param newIndex The item's new index. + **/ + moved(item: IItem, previousKey: string, nextKey: string, oldIndex?: number, newIndex?: number): void; + + /** + * Reloads data from the IListDataAdapter. + **/ + reload(): void; + + /** + * Raises a notification that an item was removed from the IListDataAdapter object's data source. + * @param key The key of the item that was removed. + * @param index The index of the item that was removed. + **/ + removed(key: string, index?: number): void; + + //#endregion Methods + + } + + /** + * Provides access to a data source and enables you to bind, change, add, remove, and move items in that data source. + **/ + interface IListDataSource { + //#region Events + + /** + * Occurs when the status of the IListDataSource changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: status. + **/ + statuschanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Notifies the IListDataSource that a sequence of edits is about to begin. The IListDataSource will defer notifications until endEdits is called. + **/ + beginEdits(): void; + + /** + * Overwrites the data of the specified item. + * @param key The key for the item to replace. + * @param newData The new data for the item. + * @returns A Promise that contains the IItem that was updated or an EditError if an error was encountered. + **/ + change(key: string, newData: T): Promise>; + + /** + * Creates an IListBinding that can retrieve items from the IListDataSource, enumerate the contents of the IListDataSource object's data, and optionally register for change notifications. + * @param notificationHandler Enables the IListBinding to register for change notifications for individual items obtained from the IListDataSource. If you omit this parameter, change notifications won't be available. + * @returns The new IListBinding. + **/ + createListBinding(notificationHandler?: IListNotificationHandler): IListBinding; + + /** + * Notifies the IListDataSource that the batch of edits that began with the last beginEdits call has completed. The IListDataSource will submit notifications for any changes that occurred between the beginEdits and endEdits calls as a batch and resume normal change notifications. + **/ + endEdits(): void; + + /** + * Retrieves the number of items in the data source. + * @returns A Promise that provides a Number that is the number of items in the data source. + **/ + getCount(): Promise; + + /** + * Inserts a new item after another item. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @param previousKey The key for an item in the data source. The new item will be added after this item. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAfter(key: string, data: T, previousKey: string): Promise>; + + /** + * Adds an item to the end of the data source. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtEnd(key: string, data: T): Promise>; + + /** + * Adds an item to the beginning of the data source. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtStart(key: string, data: T): Promise>; + + /** + * Inserts an item before another item. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @param nextKey The key of an item in the data source. The new item will be inserted before this item. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertBefore(key: string, data: T, nextKey: string): Promise>; + + /** + * Indicates that all previous data obtained from the IListDataAdapter is invalid and should be refreshed. + * @returns A Promise that completes when the data has been completely refreshed and all notifications have been sent. + **/ + invalidateAll(): Promise; + + /** + * Retrieves the item that has the specified description. + * @param description Domain-specific information, to be interpreted by the IListDataAdapter, that describes the item to retrieve. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item wasn't found, the promise completes with a value of null. + **/ + itemFromDescription(description: any): Promise>; + + /** + * Retrieves the item at the specified index. + * @param index A value that is greater than or equal to zero that is the index of the item to retrieve. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item wasn't found, the promise completes with a value of null. + **/ + itemFromIndex(index: number): Promise>; + + /** + * Retrieves the item with the specified key. + * @param key The key of the item to retrieve. It must be a non-empty string. + * @param description Domain-specific information that IListDataAdapter can use to improve the retrieval time. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item was not found, the promise completes with a null value. + **/ + itemFromKey(key: string, description?: any): Promise>; + + /** + * Moves an item to just after another item. + * @param key The key that identifies the item to move. + * @param previousKey The key of another item in the data source. The item specified by the key parameter will be moved after this item. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveAfter(key: string, previousKey: string): Promise>; + + /** + * Moves an item before another item. + * @param key The key that identifies the item to move. + * @param nextKey The key of another item in the data source. The item specified by the key parameter will be moved before this item. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveBefore(key: string, nextKey: string): Promise>; + + /** + * Moves an item to the end of the data source. + * @param key The key that identifies the item to move. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveToEnd(key: string): Promise>; + + /** + * Moves the specified item to the beginning of the data source. + * @param key The key that identifies the item to move. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveToStart(key: string): Promise>; + + /** + * Removes the specified item from the data source. + * @param key The key that identifies the item to remove. + * @returns A Promise that contains nothing if the operation was successful or an EditError if an error was encountered. + **/ + remove(key: string): Promise>; + + //#endregion Methods + + } + + /** + * Used by an IListBinding to provide change notifications when items in a IListDataSource change. + **/ + interface IListNotificationHandler { + //#region Methods + + /** + * Indicates the start of a notification batch. Objects that are listening for notifications should defer making updates until endNotifications is called. + **/ + beginNotifications(): void; + + /** + * Indicates that an item changed. + * @param newItem The updated item. + * @param oldItem The original item. + **/ + changed(newItem: IItem, oldItem: IItem): void; + + /** + * Indicates that the number of items in the IListDataSource has changed. + * @param newCount The updated count. + * @param oldCount The original count. + **/ + countChanged(newCount: number, oldCount: number): void; + + /** + * Indicates the end of a notification batch. When the beginNotifications method is called, objects listening for notifications should defer making updates until endNotifications is called. + **/ + endNotifications(): void; + + /** + * Indicates that the index of an item changed. + * @param handle The temporary ID of the item. + * @param newIndex The new index. + * @param oldIndex The original index. + **/ + indexChanged(handle: string, newIndex: number, oldIndex: number): void; + + /** + * Indicates that an item was added to the IListDataSource. + * @param itemPromise A promise for the new IItem. + * @param previousHandle The temporary ID of the item that precedes the new item. + * @param nextHandle The temporary ID of the item that follows the new item. + **/ + inserted(itemPromise: IItemPromise, previousHandle: string, nextHandle: string): void; + + /** + * Indicates that an IItemPromise was fulfilled and that the item is now available. + * @param item The fulfilled item. + **/ + itemAvailable(item: IItem): void; + + /** + * Indicates that an item was moved. + * @param item A promise for the IItem that was moved. + * @param previousHandle The temporary ID of the item that now precedes the moved item. + * @param nextHandle The temporary ID of the item that now follows the moved item. + **/ + moved(item: IItemPromise, previousHandle: string, nextHandle: string): void; + + /** + * Indicates that an item was removed. + * @param handle The temporary ID of the item that was removed. + * @param mirage true if the item never actually existed; false if the item was actually present in the IListDataSource. + **/ + removed(handle: string, mirage: boolean): void; + + //#endregion Methods + + } + + /** + * Used by ListView's currentItem API + **/ + interface IListViewItem { + /** + * Gets or sets index of the ListView item. + **/ + index?: number; + + /** + * Gets or sets key of the ListView item. + **/ + key?: string; + + /** + * Gets or sets whether the ListView item is focused. + **/ + hasFocus?: boolean; + + /** + * Gets or sets whether the ListView item is focused and is showing its focus visual. + **/ + showFocus?: boolean; + } + + /** + * Represents a selection of ListView items. + **/ + interface ISelection { + //#region Methods + + /** + * Adds one or more items to the selection. + * @param items The indexes or keys of the items to add. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + add(items: any): Promise; + + /** + * Clears the selection. + * @returns A Promise that is fulfilled when the clear operation completes. + **/ + clear(): Promise; + + /** + * Returns the number of items in the selection. + * @returns The number of items in the selection. + **/ + count(): number; + + /** + * Returns a list of the indexes for the items in the selection. + * @returns The list of indexes for the items in the selection as an array of Number objects. + **/ + getIndices(): number[]; + + /** + * Returns an array that contains the items in the selection. + * @returns A Promise that contains an array of the requested IItem objects. + **/ + getItems(): Promise[]>; + + /** + * Gets an array of the index ranges for the selected items. + * @returns An array that contains an ISelectionRange object for each index range in the selection. + **/ + getRanges(): ISelectionRange[]; + + /** + * Returns a value that indicates whether the selection contains every item in the data source. + * @returns true if the selection contains every item in the data source; otherwise, false. + **/ + isEverything(): boolean; + + /** + * Removes the specified items from the selection. + * @param items The indexes or keys of the items to remove. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + remove(items: any): Promise; + + /** + * Adds all the items in the ListView to the selection. + **/ + selectAll(): void; + + /** + * Clears the current selection and replaces it with the specified items. + * @param items The indexes or keys of the items that make up the selection. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + set(items: any): Promise; + + //#endregion Methods + + } + + /** + * Represents a range of indexes or keys in an ISelection. + **/ + interface ISelectionRange { + //#region Properties + + /** + * Gets or sets the index of the first item in the range. + **/ + firstIndex: number; + + /** + * Gets or sets the key of the first item in the range. + **/ + firstKey: any; + + /** + * Gets or sets the index of the last item in the range. + **/ + lastIndex: number; + + /** + * Gets or sets of the key of the last item in the range. + **/ + lastKey: any; + + //#endregion Properties + + } + + /** + * Supports semantic zoom functionality by exposing a control as either the zoomed in or the zoomed out view of the SemanticZoom control. + **/ + interface IZoomableView { + //#region Methods + + /** + * Initiates semantic zoom on the custom control. + **/ + beginZoom(): void; + + /** + * Initializes the semantic zoom state for the custom control. + * @param isZoomedOut True if this is the zoomed out view; otherwise false. + * @param isCurrentView True if this is the current view; otherwise false. + * @param triggerZoom The function that manages semantic zoom behavior. Triggers a zoom in or zoom out if the control is the visible control. + * @param prefetchedPages The number of pages of content to pre-fetch for zooming. This value is dependent on the size of the semantic zoom container. More content can be displayed based on the zoom factor and the size of the container. + **/ + configureForZoom(isZoomedOut: boolean, isCurrentView: boolean, triggerZoom: Function, prefetchedPages: number): void; + + /** + * Terminates semantic zoom on the zoomed in or zoomed out child of the custom control. + * @param isCurrentView True if the control is the visible control; otherwise false. + **/ + endZoom(isCurrentView: boolean): void; + + /** + * Retrieves the current item of the zoomed in or zoomed out child of the custom control. + * @returns An object that represents the selected item. This return value must be a Promise for the following: item, position. + **/ + getCurrentItem(): Promise<{ item: T; position: Utilities.IPosition }>; + + /** + * Retrieves the panning axis of the zoomed-in or zoomed-out child of the custom control. + * @returns Identifies the panning axis of the child control. Implementation specific. + **/ + getPanAxis(): string; + + /** + * Manages pointer input for the custom control. + * @param pointerId The ID of the pointer. + **/ + handlePointer(pointerId: string): void; + + /** + * Positions the specified item within the viewport of the child control when panning or zooming begins. + * @param item The object to position within the viewport of the child control. item can be a number, a string, or an object with any number of properties. + * @param position An object that contains the position data of the item relative to the child control. position must be an object with four number properties: left, top, width, and height. These values specify a rectangle that is typically the bounding box of the current item, though the details are up to the control. The units of the position must be in pixels. And the coordinates must be relative to the top-left of the control viewport (which should occupy the same area as the semantic zoom viewport), except when in RTL mode. In RTL mode, return coordinates relative to the top-right off the control viewport. The rectangle is transformed from the coordinate system of one control to that of the other. + **/ + positionItem(item: T, position: Utilities.IPosition): void; + + /** + * Selects the item closest to the specified screen coordinates. + * @param x The x-coordinate in DIPs relative to the upper-left corner of the SemanticZoom viewport. + * @param y The y-coordinate in DIPs relative to the upper-left corner of the SemanticZoom viewport.. + **/ + setCurrentItem(x: number, y: number): void; + + //#endregion Methods + + } + + //#endregion Interfaces + + //#region Objects + + /** + * Represents an application toolbar for displaying commands. + **/ + class AppBar { + //#region Constructors + + /** + * Creates a new AppBar object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new AppBar. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the AppBar goes to its closed state. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Occurs when the AppBar goes to its opened state. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Occurs before the AppBar goes to its closed state. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Occurs before the AppBar goes to its opened state. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this AppBar. Call this method when the AppBar is no longer needed. After calling this method, the AppBar becomes unusable. + **/ + dispose(): void; + + /** + * Returns the AppBarCommand object identified by id. + * @param id The element idenitifier (ID) of the command to be returned. + * @returns The command identified by id. If multiple commands have the same ID, returns an array of all the commands matching the ID. + **/ + getCommandById(id: string): AppBarCommand; + + /** + * Makes the AppBar go to its closed state. + **/ + hide(): void; + + /** + * Hides the specified commands of the AppBar. + * @param commands The commands to hide. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. + **/ + hideCommands(commands: any[], immediate?: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Makes the AppBar go to its opened state. + **/ + show(): void; + + /** + * Shows the specified commands of the AppBar. + * @param commands The commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. + **/ + showCommands(commands: any[], immediate?: boolean): void; + + /** + * Shows the specified commands of the AppBar while hiding all other commands. + * @param commands The commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. + **/ + showOnlyCommands(commands: any[], immediate?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets how the app bar is displayed when hidden is true. + **/ + closedDisplayMode: string; + + /** + * Sets the AppBarCommand objects that appear in the app bar. + **/ + commands: AppBarCommand[]; + + /** + * Gets or sets a value that indicates whether the AppBar is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the AppBar. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the AppBar control is in its closed state. + **/ + hidden: boolean; + + /** + * Gets or sets the layout of the app bar contents. + **/ + layout: string; + + /** + * Gets or sets a value that specifies whether the AppBar appears at the top or bottom of the main view. + **/ + placement: string; + + /** + * Gets or sets a value that indicates whether the AppBar is sticky (won't light dismiss). If not sticky, the app bar dismisses normally when the user touches outside of the appbar. + **/ + sticky: boolean; + + //#endregion Properties + + } + + /** + * Represents a command to be displayed in an app bar. + **/ + class AppBarCommand { + //#region Constructors + + /** + * Creates a new AppBarCommand object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new AppBarCommand. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this AppBarCommand. Call this method when the AppBarCommand is no longer needed. After calling this method, the AppBarCommand becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that indicates whether the AppBarCommand is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the AppBarCommand. + **/ + element: HTMLElement; + + /** + * Adds an extra CSS class during construction. + **/ + extraClass: string; + + /** + * Gets or sets the HTMLElement with a 'content' type AppBarCommand that should receive focus whenever focus moves by the user pressing HOME or the arrow keys, from the previous AppBarCommand to this AppBarCommand. + **/ + firstElementFocus: HTMLElement; + + /** + * Gets or sets a value that indicates whether the AppBarCommand is hiding or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the icon of the AppBarCommand. + **/ + icon: string; + + /** + * Gets the element identifier (ID) of the command. + **/ + id: string; + + /** + * Gets or sets the label of the command. + **/ + label: string; + + /** + * Gets or sets the HTMLElement with a 'content' type AppBarCommand that should receive focus whenever focus moves by the user pressing END or the arrow keys, from the previous AppBarCommand to this AppBarCommand. + **/ + lastElementFocus: HTMLElement; + + /** + * Gets or sets the function to be invoked when the command is clicked. + **/ + onclick: Function; + + /** + * Gets the section of the app bar that the command is in. + **/ + section: string; + + /** + * Gets or sets the selected state of a toggle button. + **/ + selected: boolean; + + /** + * Gets or sets the tooltip of the command. + **/ + tooltip: string; + + /** + * Gets the type of the command. + **/ + type: string; + + //#endregion Properties + + } + + /** + * Adds event-related methods to the control. + **/ + class DOMEventMixin { + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture true to initiate capture; otherwise, false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type, adding the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true to initiate capture; otherwise, false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Adds the set of declaratively specified options (properties and events) to the specified control. If the name of the options property begins with "on", the property value is a function and the control supports addEventListener. This method calls the addEventListener method on the control. + * @param control The control on which the properties and events are to be applied. + * @param options The set of options that are specified declaratively. + **/ + setOptions(control: any, options: any): void; + + //#endregion Methods + + } + + /** + * Displays a collection, such as a set of photos, one item at a time. + **/ + class FlipView { + //#region Constructors + + /** + * Creates a new FlipView. + * @constructor + * @param element The DOM element that hosts the control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the pageselected event, add a property named "onpageselected" and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the datasource count changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: source. + **/ + ondatasourcecountchanged(eventInfo: Event): void; + + /** + * Raised when the FlipView flips to a page and its renderer function completes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source. + **/ + onpagecompleted(eventInfo: CustomEvent): void; + + /** + * Raised when the FlipView flips to a page. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source. + **/ + onpageselected(eventInfo: CustomEvent): void; + + /** + * Occurs when an item becomes invisible or visible. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source, detail.visible. + **/ + onpagevisibilitychanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. For a list of events, see the FlipView object page. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Returns the number of items in the FlipView control's itemDataSource. + * @returns A Promise that contains the number of items in the list or WinJS.UI.CountResult.unknown if the count is unavailable. + **/ + count(): Promise; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this FlipView. Call this method when the FlipView is no longer needed. After calling this method, the FlipView becomes unusable. + **/ + dispose(): void; + + /** + * Forces the FlipView to update its layout. Use this function when making the FlipView visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Navigates to the next page. + * @returns true if the FlipView begins navigating to the next page; false if the FlipView is already at the last item or is in the middle of another navigation animation. + **/ + next(): boolean; + + /** + * Navigates to the previous item. + * @returns true if the FlipView begins navigating to the previous page; nfalse if the FlipView is already at the first page or is in the middle of another navigation animation. + **/ + previous(): boolean; + + /** + * Unregisters an event handler for the specified event. + * @param eventName The name of the event. + * @param eventHandler The event handler function to remove. + * @param useCapture Set to true to unregister the event handler for the capturing phase; otherwise, set to false to unregister the event handler for the bubbling phase. + **/ + removeEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Sets custom animations for the FlipView to use when navigating between pages. + * @param animations An object that contains up to three fields, one for each navigation action: next, previous, and jump. Each of those fields must be a function with this signature: function (outgoingPage, incomingPage) Each function must return a WinJS.Promise that completes once the animations are finished. If a field is null or undefined, the FlipView reverts to its default animation for that action. + **/ + setCustomAnimations(animations: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the index of the currently displayed page. + **/ + currentPage: number; + + /** + * Gets the HTML element that hosts this FlipView. + **/ + element: HTMLElement; + + /** + * Gets or sets the data source that provides the FlipView with items to display. The FlipView displays one item at a time, on its own page. + **/ + itemDataSource: IListDataSource; + + /** + * Gets or sets the spacing between each item, in pixels. + **/ + itemSpacing: number; + + /** + * Gets or sets a Template or function that defines the HTML for each item's page. + **/ + itemTemplate: any; + + /** + * Gets or sets the orientation of the FlipView, horizontal or vertical. + **/ + orientation: string; + + //#endregion Properties + + } + + /** + * Represents a grid layout for the ListView in which items are arranged in a horizontal grid. + **/ + class GridLayout { + //#region Constructors + + /** + * Creates a new GridLayout object. + * @constructor + * @param options The set of properties and values to apply to the new GridLayout. + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param wholeItem + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): void; + + /** + * This method is no longer supported. + * @param endScrollPosition + * @param wholeItem + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragLeave(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragOver(): void; + + /** + * This method is no longer supported. + **/ + endLayout(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + executeAnimations(): void; + + /** + * This method is no longer supported. + * @param itemIndex + **/ + getItemPosition(itemIndex: number): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element + * @param keyPressed + **/ + getKeyboardNavigatedItem(itemIndex: number, element: any, keyPressed: any): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPosition + **/ + getScrollbarRange(beginScrollPosition: number, endScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate, or the horizontal position on the screen. + * @param y The y-coordinate, or the vertical position on the screen. + **/ + hitTest(x: number, y: number): void; + + /** + * This method is no longer supported. + **/ + init(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param site The rendering site for the layout. + * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. + **/ + initialize(site: ILayoutSite2, groupsEnabled: boolean): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsAdded(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param firstPixel The first pixel the range of items falls between. + * @param lastPixel The last pixel the range of items falls between. + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * This method is no longer supported. + **/ + itemsMoved(): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsRemoved(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param tree + * @param changedRange + * @param modifiedItems + * @param modifiedGroups + **/ + layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): void; + + /** + * This method is no longer supported. + * @param groupIndex + * @param element A DOM element. + **/ + layoutHeader(groupIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + layoutItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param element + **/ + prepareHeader(element: HTMLElement): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + prepareItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param item + * @param newItem + **/ + releaseItem(item: any, newItem: any): void; + + /** + * This method is no longer supported. + **/ + reset(): void; + + /** + * This method is no longer supported. + * @param layoutSite + **/ + setSite(layoutSite: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + setupAnimations(): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPositionScrollPosition + **/ + startLayout(beginScrollPosition: number, endScrollPositionScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + uninitialize(): void; + + /** + * This method is no longer supported. + * @param count + **/ + updateBackdrop(count: number): void; + + //#endregion Methods + + //#region Properties + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + backdropColor: string; + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + disableBackdrop: boolean; + + /** + * Gets or sets the position of group headers. + **/ + groupHeaderPosition: WinJS.UI.HeaderPosition; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + groupInfo: Function; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use the orientation property instead. + **/ + horizontal: boolean; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + itemInfo: Function; + + /** + * Gets or set the maximum number of rows or columns, depending on the orientation, to display before content begins to wrap. + **/ + maximumRowsOrColumns: number; + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the maximumRowsOrColumns property. + **/ + maxRows: number; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + numberOfItemsPerItemsBlock: any; + + /** + * Gets or sets the orientation of the GridLayout. + **/ + orientation: WinJS.UI.Orientation; + + //#endregion Properties + + } + + /** + * Enables you to include an HTML page dynamically. As part of the constructor, you must include an option indicating the URI of the page. + **/ + class HtmlControl { + //#region Constructors + + /** + * Initializes a new instance of HtmlControl to define a new page control. + * @constructor + * @param element The element that hosts the HtmlControl. + * @param options The options for configuring the page. The uri option is required in order to specify the source document for the content of the page. Other options are the ones used by the WinJS.Pages.render method. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + } + + /** + * Defines an item that can be pressed, swiped, and dragged. + **/ + class ItemContainer { + //#region Constructors + + /** + * Creates a new ItemContainer. + * @constructor + * @param element The DOM element hosts the new ItemContainer. For the ItemContainer to be accessible, this element must have its role attribute set to "list" or "listbox". If tapBehavior is set to none and selectionDisabled is true, then use the "list" role; otherwise, use the "listbox" role. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the item is invoked. (You can use the tapBehavior property to specify whether taps and clicks invoke the item.) + * @param eventInfo An object that contains information about the event. + **/ + oninvoked(eventInfo: CustomEvent): void; + + /** + * Raised after the item is selected or deselected. + * @param eventInfo An object that contains information about the event. + **/ + onselectionchanged(eventInfo: CustomEvent): void; + + /** + * Raised just before the current selection changes. + * @param eventInfo An object that contains information about the event. + **/ + onselectionchanging(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this ItemContainer. Call this method when the ItemContainer is no longer needed. After calling this method, the ItemContainer becomes unusable. + **/ + dispose(): void; + + /** + * Forces the ItemContainer to update its layout. Call this function when the reading direction of the app changes after the control has been initialized. + **/ + forceLayout(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether the item can be dragged. + **/ + draggable: boolean; + + /** + * Gets the element that hosts this ItemContainer. + **/ + element: HTMLElement; + + /** + * Gets or sets a value that specifies whether the item is selected. + **/ + selected: boolean; + + /** + * Gets or sets a value that specifies whether selection of this item is disabled. + **/ + selectionDisabled: boolean; + + /** + * Gets or sets the orientation of swipe gestures. + **/ + swipeOrientation: Orientation; + + /** + * Gets or sets how the ItemContainer reacts when the user taps or clicks an item. + **/ + tapBehavior: TapBehavior; + + //#endregion Properties + + } + + /** + * This object supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + class Layout { + } + + /** + * Represents a layout for the ListView in which items are arranged in a vertical list. + **/ + class ListLayout { + //#region Constructors + + /** + * Creates a new ListLayout. + * @constructor + * @param options An object that contains one or more property/value pairs to apply to the new ListLayout. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param wholeItem + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): void; + + /** + * This method is no longer supported. + * @param endScrollPosition + * @param wholeItem + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragLeave(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragOver(): void; + + /** + * This method is no longer supported. + **/ + endLayout(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + executeAnimations(): void; + + /** + * This method is no longer supported. + * @param itemIndex + **/ + getItemPosition(itemIndex: number): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element + * @param keyPressed + **/ + getKeyboardNavigatedItem(itemIndex: number, element: HTMLElement, keyPressed: any): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPosition + **/ + getScrollbarRange(beginScrollPosition: number, endScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate, or the horizontal position on the screen. + * @param y The y-coordinate, or the vertical position on the screen. + **/ + hitTest(x: number, y: number): void; + + /** + * This method is no longer supported. + **/ + init(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + initialize(): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsAdded(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param firstPixel + * @param lastPixel + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * This method is no longer supported. + **/ + itemsMoved(): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsRemoved(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param tree + * @param changedRange + * @param modifiedItems + * @param modifiedGroups + **/ + layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): void; + + /** + * This method is no longer supported. + * @param groupIndex + * @param element A DOM element. + **/ + layoutHeader(groupIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + layoutItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param element + **/ + prepareHeader(element: HTMLElement): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + prepareItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param item + * @param newItem + **/ + releaseItem(item: any, newItem: any): void; + + /** + * This method is no longer supported. + **/ + reset(): void; + + /** + * This method is no longer supported. + * @param layoutSite + **/ + setSite(layoutSite: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + setupAnimations(): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPositionScrollPosition + **/ + startLayout(beginScrollPosition: number, endScrollPositionScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + uninitialize(): void; + + /** + * This method is no longer supported. + * @param count + **/ + updateBackdrop(count: number): void; + + //#endregion Methods + + //#region Properties + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + backdropColor: string; + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + disableBackdrop: boolean; + + /** + * Gets or sets the position of group headers. + **/ + groupHeaderPosition: WinJS.UI.HeaderPosition; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + groupInfo: Function; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use the orientation property instead. + **/ + horizontal: boolean; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + itemInfo: Function; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + numberOfItemsPerItemsBlock: any; + + /** + * Gets or sets the orientation of the GridLayout. + **/ + orientation: WinJS.UI.Orientation; + + //#endregion Properties + + } + + /** + * Displays data items in a customizable list or grid. + **/ + class ListView { + //#region Constructors + + /** + * Creates a new ListView. + * @constructor + * @param element The DOM element that hosts the ListView control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the selectionchanged event, add a property named "onselectionchanged" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the ListView is about to play an entrance or contentTransition animation. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.type, detail.setPromise. + **/ + oncontentanimating(eventInfo: CustomEvent): void; + + /** + * Raised when the user taps or clicks a group header. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.groupHeaderIndex, detail.groupHeaderPromise. + **/ + ongroupheaderinvoked(eventInfo: CustomEvent): void; + + /** + * Occurs when the user taps or clicks an item. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.itemIndex. + **/ + oniteminvoked(eventInfo: CustomEvent): void; + + /** + * Raised when the focused item changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.oldFocus, detail.oldNewFocus. + **/ + onkeyboardnavigating(eventInfo: CustomEvent): void; + + /** + * Occurs when the ListView control's loadingState changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.scrolling. + **/ + onloadingstatechanged(eventInfo: CustomEvent): void; + + /** + * Occurs after the current selection changes. + * @param eventInfo An object that contains information about the event. The detail property of this object is null. To obtain the selected items, use the ListView.selection property. + **/ + onselectionchanged(eventInfo: CustomEvent): void; + + /** + * Occurs just before the current selection changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.newSelection, detail.preventTapBehavior. + **/ + onselectionchanging(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. See the ListView object page for a list of events. Note that you drop the "on" when specifying the event name for the addEventListener method. For example, instead of specifying "onselectionchange", you specify "selectionchange". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this object. Call this method when the object is no longer needed. After calling this method, the object becomes unusable. + **/ + dispose(): void; + + /** + * Returns the DOM element that represents the item at the specified index. + * @param itemIndex The index of the item. + * @returns The DOM element that represents the item at the specified index. + **/ + elementFromIndex(itemIndex: number): HTMLElement; + + /** + * Makes the item at the specified index visible. If necessary, the ListView will scroll to the item. + * @param itemIndex The index of the item to scroll into view. + **/ + ensureVisible(itemIndex: number): void; + + /** + * Forces the ListView to update its layout. Use this function when making the ListView visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Returns the index of the item that the specified DOM element displays. + * @param element The DOM element that displays the item. + * @returns The index of the item displayed by element. + **/ + indexOfElement(element: HTMLElement): number; + + /** + * Loads the next set of pages if the ListView control's loadingBehavior is set to "incremental" (otherwise, it does nothing). The number of pages to be loaded is determined by the pagesToLoad property. + **/ + loadMorePages(): void; + + /** + * Repositions all the visible items in the ListView to adjust for items whose sizes have changed. Most apps won’t ever need to call this method. For more info, see the Remarks section. + **/ + recalculateItemPosition(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + /** + * Triggers the ListView disposal service manually. + **/ + static triggerDispose(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that indicates whether the next set of pages is automatically loaded when the user scrolls beyond the number of pages specified by the pagesToLoadThreshold property. + **/ + automaticallyLoadPages: boolean; + + /** + * Gets or sets an IListViewItem that indicates which item should have keyboard focus and the focus state of that item. + **/ + currentItem: IListViewItem; + + /** + * Gets the HTML element that hosts this ListView. + **/ + element: HTMLElement; + + /** + * Gets or sets the data source that contains the groups for the items in the itemDataSource. + **/ + groupDataSource: IListDataSource; + + /** + * Gets or sets how the ListView reacts when the user taps or clicks a group header. + **/ + groupHeaderTapBehavior: GroupHeaderTapBehavior; + + /** + * Gets or sets the Template or function that creates the DOM elements for each group header in the groupDataSource. Each group header can contain multiple elements, but it must have a single root element. + **/ + groupHeaderTemplate: any; + + /** + * Gets or sets the first visible item. + **/ + indexOfFirstVisible: number; + + /** + * Gets the index of the last visible item in the ListView. + **/ + indexOfLastVisible: number; + + /** + * Gets or sets the data source that provides the ListView with items. + **/ + itemDataSource: IListDataSource; + + /** + * Gets or sets whether the ListView control's items can be reordered within itself by dragging and dropping. + **/ + itemsReorderable: boolean; + + /** + * Gets or sets the WinJS.Binding.Template or templating function that creates the DOM elements for each item in the itemDataSource. Each item can contain multiple elements, but it must have a single root element. + **/ + itemTemplate: any; + + /** + * Gets or sets an object that controls the layout of the ListView. + **/ + layout: ILayout2; + + /** + * Gets or sets a value that specifies how the ListView fetches items and adds and removes them to the DOM. Don't change the value of this property after the ListView has begun loading data. + **/ + loadingBehavior: string; + + /** + * Gets a value that indicates whether the ListView is still loading or whether loading is complete. + **/ + loadingState: string; + + /** + * Gets or sets the maximum number of realized items. + **/ + maxDeferredItemCleanup: number; + + /** + * Gets or sets the number of pages to load when the loadingBehavior property is set to "incremental" and the user scrolls beyond the threshold specified by the pagesToLoadThreshold property. + **/ + pagesToLoad: number; + + /** + * Gets or sets the threshold (in pages) for initiating an incremental load. When the last visible item is within the specified number of pages from the end of the loaded portion of the list, and if automaticallyLoadPages is true and loadingBehavior is set to "incremental", the ListView initiates an incremental load. + **/ + pagesToLoadThreshold: number; + + /** + * Gets or sets the function that is called when the ListView discards or recycles the element representation of a group header. + **/ + resetGroupHeader: (header: any, element: HTMLElement) => void; + + /** + * Gets or sets the function that is called when an item is removed, an item is changed, or an item falls outside of the realized range of the ListView. + **/ + resetItem: (item: T, element: HTMLElement) => void; + + /** + * Gets or sets the distance, in pixels, of the start of the viewable area within the viewport. + **/ + scrollPosition: number; + + /** + * Gets an ISelection that contains the range of currently selected items. + **/ + selection: ISelection; + + /** + * Gets or sets the selection mode of the ListView. + **/ + selectionMode: SelectionMode; + + /** + * Gets or sets how the ListView reacts when the user taps or clicks an item. + **/ + tapBehavior: TapBehavior; + + /** + * Gets a ZoomableView that supports semantic zoom functionality. This API supports the SemanticZoom infrastructure and is not intended to be used directly from your code. + **/ + zoomableView: IZoomableView>; + + //#endregion Properties + + } + + /** + * A tab control that displays multiple items. + **/ + class Pivot { + //#region Constructors + + /** + * Creates a new Pivot. + * @constructor + * @param element The DOM element hosts the new Pivot. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the cancel event, add a property named "oncancel" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when a PivotItem control's animation ends. + * @param eventInfo An object that contains information about the event. + **/ + onitemanimationend(eventInfo: Event): void; + + /** + * Raised when a PivotItem control's animation starts. + * @param eventInfo An object that contains information about the event. + **/ + onitemanimationstart(eventInfo: Event): void; + + /** + * Raised when the user navigates to a different PivotItem. + * @param eventInfo An object that contains information about the event. + **/ + onselectionchanged(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this Pivot. Call this method when the Pivot is no longer needed. After calling this method, the Pivot becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the Pivot control. + **/ + element: HTMLElement; + + /** + * Gets or sets the Binding.List that contains the PivotItem objects that belong to this Pivot. + **/ + items: Binding.List; + + /** + * Gets or sets a value that specifies whether the Pivot control is locked to the current item. + **/ + locked: boolean; + + /** + * Gets or sets the index of the PivotItem control in view. + **/ + selectedIndex: number; + + /** + * Gets or sets the PivotItem control in view within the Pivot control. + **/ + selectedItem: PivotItem; + + /** + * Gets or sets the title displayed above the PivotItem controls. + **/ + title: string; + + //#endregion Properties + } + + /** + * An item within a Pivot control. + **/ + class PivotItem { + //#region Constructors + + /** + * Creates a new PivotItem. + * @constructor + * @param element The DOM element hosts the new PivotItem. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the cancel event, add a property named "oncancel" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Releases resources held by this PivotItem. Call this method when the PivotItem is no longer needed. After calling this method, the PivotItem becomes unusable. + **/ + dispose(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the PivotItem control's content. + **/ + contentElement: HTMLElement; + + /** + * Gets the DOM element that hosts the PivotItem control. + **/ + element: HTMLElement; + + /** + * Gets or sets the header for this PivotItem. + **/ + header: HTMLElement; + + //#endregion Properties + } + + /** + * Generates HTML from a set of data. Use this control to generate lists of items. + **/ + class Repeater { + //#region Constructors + + /** + * Creates a new Repeater control. + * @constructor + * @param options An object that contains one or more property/value pairs to apply to the new Repeater. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised after an item in the Repeater control's data source changes and after the corresponding DOM element has been updated. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.key, detail.newElement, detail.newItem, detail.newValue, detail.oldElement, detail.oldItem, detail.oldValue, detail.setPromise. + **/ + onitemchanged(eventInfo: CustomEvent): void; + + /** + * Raised after an item in the Repeater control's data source changes but before the corresponding DOM element has been updated. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.key, detail.newElement, detail.newItem, detail.newValue, detail.oldElement, detail.oldItem, detail.oldValue, detail.setPromise. + **/ + onitemchanging(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been added to the Repeater control's data source and after the corresponding DOM element has been added. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.value. + **/ + oniteminserted(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been added to the Repeater control's data source but before the corresponding DOM element has been added. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.value. + **/ + oniteminserting(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been moved from one index to another in the Repeater control's data source and after the corresponding DOM element has been moved. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.oldIndex, detail.newIndex. + **/ + onitemmoved(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been moved from one index to another in the Repeater control's data source but before the corresponding DOM element has been moved. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.oldIndex, detail.newIndex. + **/ + onitemmoving(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been moved from one index to another in the Repeater control's data source and after the corresponding DOM element has been moved. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.item, detail.setPromise. + **/ + onitemremoved(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been removed from the Repeater control's data source but before the corresponding DOM element has been removed. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.item, detail.setPromise. + **/ + onitemremoving(eventInfo: CustomEvent): void; + + /** + * Raised when the Repeater has finished loading a new set of data. This event is only fired on construction. This event is only raised when the Repeater is constructed or its data source or template changes. + * @param eventInfo An object that contains information about the event. + **/ + onitemsloaded(eventInfo: CustomEvent): void; + + /** + * Raised after the Repeater control's underlying data has been updated and after the updated HTML has been reloaded. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElements. + **/ + onitemsreloaded(eventInfo: CustomEvent): void; + + /** + * Raised after the Repeater control's underlying data has been updated but before the updated HTML has been reloaded. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElements, detail.setPromise. + **/ + onitemsreloading(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this Repeater. Call this method when the Repeater is no longer needed. After calling this method, the Repeater becomes unusable. + **/ + dispose(): void; + + /** + * Returns the HTML element for the item at the specified index. + * @param index The index of the item. + * @returns The DOM element for the specified item. + **/ + elementFromIndex(index: number): HTMLElement; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the List that provides the Repeater with items to display. + **/ + data: WinJS.Binding.List; + + /** + * Gets the DOM element that hosts the Repeater. + **/ + element: HTMLElement; + + /** + * Gets the number of items in the Repeater control. + **/ + length: number; + + /** + * Gets or sets a WinJS.Binding.Template or custom rendering function that defines the HTML of each item within the Repeater. + **/ + template: WinJS.Binding.Template; + + //#endregion Properties + + } + + /** + * Enables the user to zoom between two different views supplied by two child controls. One child control supplies the zoomed-out view and the other provides the zoomed-in view. + **/ + class SemanticZoom { + //#region Constructors + + /** + * Creates a new SemanticZoom. + * @constructor + * @param element The DOM element that hosts the SemanticZoom. + * @param options An object that contains one or more property/value pairs to apply to the new control. This object can contain these properties: initiallyZoomedOut Boolean, zoomFactor 0.2–0.85. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the control zooms in or out. + * @param eventInfo An object that contains information about the event. The detail property of this object is true when the control is zoomed out. Otherwise, it's false. + **/ + onzoomchanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this SemanticZoom. Call this method when the SemanticZoom is no longer needed. After calling this method, the SemanticZoom becomes unusable. + **/ + dispose(): void; + + /** + * Forces the SemanticZoom to update its layout. Use this function when making the SemanticZoom visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Unregisters an event handler for the specified event. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the SemanticZoom control. + **/ + element: HTMLElement; + + /** + * Determines whether any controls contained in a SemanticZoom should be processed separately. This property is always true, meaning that the SemanticZoom takes care of processing its own controls. + **/ + isDeclarativeControlContainer: boolean; + + /** + * Gets or sets a value that indicates whether SemanticZoom is locked and zooming between views is disabled. + **/ + locked: boolean; + + /** + * Gets or sets a value that indicates whether the control is zoomed out. + **/ + zoomedOut: boolean; + + /** + * Gets or sets a value that specifies how much the scaling the cross-fade animation performs when the SemanticZoom transitions between views. + **/ + zoomFactor: number; + + //#endregion Properties + + } + + /** + * A type of IListDataSource that provides read-access to an object that implements the IStorageQueryResultBase interface. A StorageDataSource enables you to query and bind to items in the data source. + **/ + class StorageDataSource { + //#region Constructors + + /** + * Creates a new StorageDataSource object. + * @constructor + * @param query The IStorageQueryResultBase that the StorageDataSource obtains its items from. Instead of IStorageQueryResultBase, you can also pass one of these string values: Music, Pictures, Videos, Documents. + * @param options The set of properties and values to apply to the new StorageDataSource. Properties on this object may include: mode , requestedThumbnailSize , thumbnailOptions , synchronous . + **/ + constructor(query: any, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Draws the thumbnail for the specified item to the specified img element. + * @param item The item to retrieve the thumbnail for. + * @param image The img element that will display the thumbnail. + * @returns A Promise that completes when the full-quality thumbnail is visible. + **/ + loadThumbnail(item: IItem, image: HTMLImageElement): Promise; + + //#endregion Methods + + } + + /** + * Prevents a DOM sub-tree from receiving tab navigations and focus. + **/ + class TabContainer { + //#region Constructors + + /** + * Creates a new TabContainer. + * @constructor + * @param element The DOM element that hosts the TabContainer control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Releases resources held by this TabContainer. Call this method when the TabContainer is no longer needed. After calling this method, the TabContainer becomes unusable. + **/ + dispose(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the child DOM element that receives tab focus. + **/ + childFocus: HTMLElement; + + /** + * Gets or sets the tab index of this container. + **/ + tabIndex: number; + + //#endregion Properties + + } + + /** + * A control that lets the user switch an option between two states: on (checked is set to true) and off (checked is set to false). + **/ + class ToggleSwitch { + //#region Constructors + + /** + * Creates a new ToggleSwitch. + * @constructor + * @param element The DOM that hosts the control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the change event, add a property named "onchange" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the ToggleSwitch control is flipped to on (checked == true) or off (checked == false). + * @param eventInfo An object that contains information about the event. + **/ + onchange(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this ToggleSwitch. Call this method when the ToggleSwitch is no longer needed. After calling this method, the ToggleSwitch becomes unusable. + **/ + dispose(): void; + + /** + * Handles the specified event. + * @param event The event. + **/ + handleEvent(event: any): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + raiseEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether the control is on or off. + **/ + checked: boolean; + + /** + * Gets or sets a value that specifies whether the control is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the ToggleSwitch. + **/ + element: HTMLElement; + + /** + * Gets or sets the text that displays when the ToggleSwitch is off (checked is set to false). + **/ + labelOff: string; + + /** + * Gets or sets the text that displays when the ToggleSwitch is on (checked is set to true). + **/ + labelOn: string; + + /** + * Gets or sets the main text for the ToggleSwitch control. This text is always displayed, regardless of whether the control is switched on or off. + **/ + title: string; + + //#endregion Properties + + } + + /** + * Scales a single child element to fill the available space without resizing it. This control reacts to changes in the size of the container as well as changes in size of the child element. For example, a media query may result in a change in aspect ratio. + **/ + class ViewBox { + //#region Constructors + + /** + * Initializes a new instance of the ViewBox control. + * @constructor + * @param element The DOM element that functions as the scaling box. This element fills 100% of the width and height allotted to it. + * @param options The set of options to be applied initially to the ViewBox control. There are currently no options on this control, and any options included in this parameter are ignored. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Adds an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this ViewBox. Call this method when the ViewBox is no longer needed. After calling this method, the ViewBox becomes unusable. + **/ + dispose(): void; + + /** + * Forces the ViewBox to update its layout. Use this function when making the ViewBox visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that functions as the scaling box. + **/ + element: HTMLElement; + + //#endregion Properties + + } + + /** + * Serves as the base class for a custom IListDataSource. + **/ + class VirtualizedDataSource { + //#region Constructors + + /** + * Initializes the VirtualizedDataSource base class of a custom data source. + * @constructor + * @param listDataAdapter The object that supplies data to the VirtualizedDataSource. + * @param options An object that can contain properties that specify additional options for the VirtualizedDataSource. It supports these properties: cacheSize. + **/ + constructor(listDataAdapter: IListDataAdapter, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the status of the VirtualizedDataSource changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: status. + **/ + statuschanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. See the VirtualizedDataSource object page for a list of events. Note that you drop the "on" when specifying the event name for the addEventListener method. For example, instead of specifying "onstatuschanged", you specify "statuschanged". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. See the VirtualizedDataSource object page for a list of events. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + } + + //#endregion Objects + + //#region Functions + + /** + * Returns a new IListDataSource that adds group information to the items of another IListDataSource. + * @param listDataSource The data source for the individual items to group. + * @param groupKey A callback function that accepts a single argument: an item in the IListDataSource. The function is called for each item in the list and must return the group key for that item as a string. + * @param groupData A callback function that accepts a single argument: an item in the IListDataSource. The function is called on one IListDataSource item for each group and must return an object that represents the header of that group. + * @param options An object that can contain properties that specify additional options: groupCountEstimate, batchSize. + * @returns An IListDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. + **/ + function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListDataSource; + + /** + * Used to disables all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be disabled, as the determination is made based on several factors. + **/ + function disableAnimations(): void; + + /** + * Used to enable all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be enabled, as the determination is made based on several factors. + **/ + function enableAnimations(): void; + + /** + * Marks a event handler function as being compatible with declarative processing. + * @param handler The handler to be marked as compatible with declarative processing. + * @returns The handler, marked as compatible with declarative processing. + **/ + function eventHandler(handler: any): any; + + /** + * Asynchronously executes a collection of CSS animations on a collection of elements. This is the underlying animation mechanism used by the Animations Library. Apps are encouraged to use the Animations Library to conform with the standard look and feel of the rest of the system, rather than calling this function directly. + * @param element Element or elements to be animated. This parameter can be expressed in several ways: As the special value "undefined", which means that the animation has no target, As a single object, As a JavaScript array (possibly empty), in which each element of the array can be a single element or a JavaScript array of elements., As a NodeList (for example, the result of querySelectorAll), As an HTMLCollection. + * @param animation The animation description or an array of animation descriptions to apply to element. An animation description is a JavaScript object with specific properties, listed below. There are two types of animation descriptions: one for keyframe-based animations and one for explicit animations. These types are distinguished by whether the keyframe property has a defined value. The following properties are required for both types of animation descriptions: property (string), delay (number), duration (number), timing (string). If an animation has a keyframe property with a defined, non-null value, then the animation is a keyframe-based animation. A keyframe-based animation description requires the following property in addition to those mentioned above: keyframe (string). If an animation does not have a keyframe property, or if the value of the property is null or undefined, then the animation is an explicit animation. An explicit animation description requires the following properties in addition to the common properties mentioned above: from, to. The values given in the from and to properties must be valid for the CSS property specified by the property property. For example, if the CSS property is "opacity", then the from and to properties must be numbers between 0 and 1 (inclusive). + * @returns Returns a Promise object that completes when the CSS animation is complete. + **/ + function executeAnimation(element: HTMLElement, animation: any): Promise; + + /** + * Asynchronously executes a collection of CSS transitions on a collection of elements. This is the underlying animation mechanism used by the Animations Library. Apps are encouraged to use the Animations Library to conform with the standard look and feel of the rest of the system, rather than calling this function directly. + * @param element Element or elements on which to perform the transition. This parameter can be expressed in several ways: As the special value "undefined", which means that the transition has no target, As a single object, As a JavaScript array (possibly empty), in which each element of the array can be a single element or a JavaScript array of elements., As a NodeList (for example, the result of querySelectorAll), As an HTMLCollection. + * @param transition The transition description or an array of transition descriptions to apply to element. A transition description is a JavaScript object with these properties: property (string), delay (number), duration (number), timing (string), from (optional), to. The values given in the from and to properties must be valid for the CSS property specified by the property property. For example, if the CSS property is "opacity", then the from and to properties must be numbers between 0 and 1 (inclusive). + * @returns Returns a Promise that completes when the transition is finished. + **/ + function executeTransition(element: HTMLElement, transition: any): Promise; + + /** + * Retrieves the items in the specified index range. + * @param dataSource The data source that contains the items to retrieve. + * @param ranges An array of ISelectionRange objects that have firstIndex and lastIndex values. + * @returns A Promise that contains an array of the requested IItem objects. + **/ + function getItemsFromRanges(dataSource: IListDataSource, ranges: ISelectionRange[]): Promise>; + + /** + * Determines whether the Animations Library and ListView animations will be performed if called. + * @returns Returns true if animations will be performed; otherwise false. + **/ + function isAnimationEnabled(): boolean; + + /** + * Applies declarative control binding to all elements, starting at the specified root element. + * @param rootElement The element at which to start applying the binding. If this parameter is not specified, the binding is applied to the entire document. + * @param skipRoot If true, the elements to be bound skip the specified root element and include only the children. + * @returns A promise that is fulfilled when binding has been applied to all the controls. + **/ + function processAll(rootElement?: Element, skipRoot?: boolean): Promise; + + /** + * Applies declarative control binding to the specified element. + * @param element The element to bind. + * @returns A promise that is fulfilled after the control is activated. The value of the promise is the control that is attached to element. + **/ + function process(element: Element): Promise; + + /** + * Walks the DOM tree from the given element to the root of the document. Whenever a selector scope is encountered, this method performs a lookup within that scope for the specified selector string. The first matching element is returned. + * @param selector The selector string. + * @param element The element to begin walking to the root of the document from. + * @returns The target element, if found. + **/ + function scopedSelect(selector: string, element: HTMLElement): HTMLElement; + + /** + * Given a DOM element and a control, attaches the control to the element. + * @param element Element to associate with the control. + * @param control The control to attach to the element. + **/ + function setControl(element: HTMLElement, control: any): void; + + /** + * Adds the set of declaratively specified options (properties and events) to the specified control. If name of the options property begins with "on", the property value is a function and the control supports addEventListener. setControl calls addEventListener on the control. + * @param control The control on which the properties and events are to be applied. + * @param options The set of options that are specified declaratively. + **/ + function setOptions(control: any, options?: any): void; + + //#endregion Functions + +} +/** + * Provides functions to load HTML content programmatically. +**/ +declare module WinJS.UI.Fragments { + //#region Functions + + /** + * Starts loading the fragment at the specified location. The returned promise completes when the fragment is ready to be copied. + * @param href The URI that contains the fragment to be copied. + * @returns A promise that is fulfilled when the fragment has been prepared for copying. + **/ + function cache(href: string): Promise; + + /** + * Removes any cached information about the specified fragment. This method does not unload any scripts or styles that are referenced by the fragment. + * @param href The URI that contains the fragment to be cleared. If no URI is provided, the entire contents of the cache are cleared. + **/ + function clearCache(href: string): void; + + /** + * Loads the contents of the specified URI into the specified element without copying it. + * @param href The URI that contains the fragment to copy. + * @param element Optional. The element to which the fragment is appended. + * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The element is not added to the cache. See also rendercopy, where the element is added to the cache. + **/ + function render(href: string, element?: HTMLElement): Promise; + + /** + * Loads and copies the contents of the specified URI into the specified element. + * @param href The URI that contains the fragment to copy. + * @param target The element to which the fragment is appended. + * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The fragment is added to the cache. See also render, where the element is not added to the cache. + **/ + function renderCopy(href: string, target?: HTMLElement): Promise; + + //#endregion Functions + +} +/** + * Provides methods for defining and displaying PageControl objects. +**/ +declare module WinJS.UI.Pages { + //#region Interfaces + + /** + * Provides members for a PageControl. You implement this interface when defining a new PageControl. + **/ + interface IPageControlMembers { + //#region Methods + + /** + * Called if any error occurs during the processing of the page. + * @param err The error that occurred. + * @returns Nothing if the error was handled, or an error promise if the error was not handled. + **/ + error? (err: any): Promise; + + /** + * Initializes the control before the content of the control is set. Use the processed method for any initialization that should be done after the content of the control has been set. + * @param element The DOM element that will contain all the content for the page. + * @param options The options passed to the constructor of the page. + * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + init? (element: HTMLElement, options: any): Promise; + + /** + * Creates DOM objects from the content in the specified URI. This method is called after the PageControl is defined and before the init method is called. + * @param uri The URI from which to create DOM objects. + * @returns A promise whose fulfilled value is the set of unparented DOM objects. + **/ + load? (uri: string): Promise; + + /** + * Initializes the control after the content of the control is set. + * @param element The DOM element that will contain all the content for the page. + * @param options The options that are to be passed to the constructor of the page. + * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + processed? (element: HTMLElement, options: any): Promise; + + /** + * Called after all initialization and rendering is complete. At this time, the element is ready for use. + * @param element The DOM element that contains all the content for the page. + * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @returns A promise that is fulfilled when the element is ready for use, if asynchronous processing is necessary. If not, returns nothing. + **/ + ready? (element: HTMLElement, options: any): Promise; + + /** + * Takes the elements returned by the load method and attaches them to the specified element. + * @param element The DOM element to which the loadResult elements are appended. + * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @param loadResult A Promise that contains the elements returned from the load method. + **/ + render? (element: HTMLElement, options: any, loadResult: Promise): void; + + //#endregion Methods + + } + + //#endregion Interfaces + + //#region Objects + + /** + * A modular unit of HTML, CSS, and JavaScript that can be navigated to or used as a custom WinJS control. + **/ + class PageControl { + } + + //#endregion Objects + + //#region Functions + + /** + * Creates a new PageControl from the specified URI that contains the specified members. Multiple calls to this method for the same URI are allowed, and all members will be merged. + * @param uri The URI for the content that defines the page. + * @param members An object that defines the members that the control will have. + * @returns A constructor function that creates the PageControl. + **/ + function define(uri: string, members: IPageControlMembers): PageControl; + + /** + * Gets an already-defined page control for the specified URI, or creates a new one. + * @param uri The URI for the content that defines the page. + * @returns A constructor function that creates the page. + **/ + function get(uri: string): Function; + + /** + * Creates a PageControl from the specified URI and inserts it inside the specified element. + * @param uri The URI for the content that defines the page. + * @param element The DOM element to which the PageControl is appended. + * @param options An object that contains one or more property/value pairs to apply to the new PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @param parentedPromise A Promise that is fulfilled when the new PageControl is done rendering and its contents becomes the child of element. + * @returns A promise that is fulfilled when rendering is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + function render(uri: string, element: HTMLElement, options?: any, parentedPromise?: Promise): Promise; + + //#endregion Functions + +} +/** + * Provides methods for detecting when the user tabs to or from DOM elements. +**/ +declare module WinJS.UI.TrackTabBehavior { + //#region Functions + + /** + * Sets the tab order for the specified element within its container. + * @param element The element to update. + * @param tabIndex The index value of the element within its container. + **/ + function attach(element: HTMLElement, tabIndex: number): void; + + /** + * Removes the tab order information from the specified element. + * @param element The element to remove tab information from. + **/ + function detatch(element: HTMLElement): void; + + //#endregion Functions + +} +/** + * Provides helper functions, for example, functions to add and remove CSS classes. +**/ +declare module WinJS.Utilities { + //#region Enumerations + + /** + * Defines a set of keyboard values. + **/ + enum Key { + /** + * The BACKSPACE key. + **/ + backspace, + /** + * The TAB key. + **/ + tab, + /** + * The ENTER key. + **/ + enter, + /** + * The SHIFT key. + **/ + shift, + /** + * The CTRL key. + **/ + ctrl, + /** + * The ALT key. + **/ + alt, + /** + * The PAUSE key. + **/ + pause, + /** + * The CAPS LOCK key. + **/ + capsLock, + /** + * The ESCAPE key. + **/ + escape, + /** + * The SPACE key. + **/ + space, + /** + * The PAGE UP key. + **/ + pageUp, + /** + * The PAGE DOWN key. + **/ + pageDown, + /** + * The END key. + **/ + end, + /** + * The HOME key. + **/ + home, + /** + * The LEFT ARROW key. + **/ + leftArrow, + /** + * The UP ARROW key. + **/ + upArrow, + /** + * The RIGHT ARROW key. + **/ + rightArrow, + /** + * The DOWN ARROW key. + **/ + downArrow, + /** + * The INSERT key. + **/ + insert, + /** + * The DELETE key. + **/ + deleteKey, + /** + * The 0 key. + **/ + num0, + /** + * The 1 key. + **/ + num1, + /** + * The 2 key. + **/ + num2, + /** + * The 3 key. + **/ + num3, + /** + * The 4 key. + **/ + num4, + /** + * The 5 key. + **/ + num5, + /** + * The 6 key. + **/ + num6, + /** + * The 7 key. + **/ + num7, + /** + * The 8 key. + **/ + num8, + /** + * The 9 key. + **/ + num9, + /** + * The a key. + **/ + a, + /** + * The b key. + **/ + b, + /** + * The c key. + **/ + c, + /** + * The d key. + **/ + d, + /** + * The e key. + **/ + e, + /** + * The f key. + **/ + f, + /** + * The g key. + **/ + g, + /** + * The h key. + **/ + h, + /** + * The i key. + **/ + i, + /** + * The j key. + **/ + j, + /** + * The k key. + **/ + k, + /** + * The l key. + **/ + l, + /** + * The m key. + **/ + m, + /** + * The n key. + **/ + n, + /** + * The o key. + **/ + o, + /** + * The p key. + **/ + p, + /** + * The q key. + **/ + q, + /** + * The r key. + **/ + r, + /** + * The s key. + **/ + s, + /** + * The t key. + **/ + t, + /** + * The u key. + **/ + u, + /** + * The v key. + **/ + v, + /** + * The w key. + **/ + w, + /** + * The x key. + **/ + x, + /** + * The y key. + **/ + y, + /** + * The z key. + **/ + z, + /** + * The left Windows key. + **/ + leftWindows, + /** + * The right Windows key. + **/ + rightWindows, + /** + * The menu key. + **/ + menu, + /** + * The 0 key on the numerical keypad. + **/ + numPad0, + /** + * The 1 key on the numerical keypad. + **/ + numPad1, + /** + * The 2 key on the numerical keypad. + **/ + numPad2, + /** + * The 3 key on the numerical keypad. + **/ + numPad3, + /** + * The 4 key on the numerical keypad. + **/ + numPad4, + /** + * The 5 key on the numerical keypad. + **/ + numPad5, + /** + * The 6 key on the numerical keypad. + **/ + numPad6, + /** + * The 7 key on the numerical keypad. + **/ + numPad7, + /** + * The 8 key on the numerical keypad. + **/ + numPad8, + /** + * The 9 key on the numerical keypad. + **/ + numPad9, + /** + * The multiplication key (*). + **/ + multiply, + /** + * The addition key (+). + **/ + add, + /** + * The subtraction key (-). + **/ + subtract, + /** + * The decimal point key (.) + **/ + decimalPoint, + /** + * The division key (/). + **/ + divide, + /** + * The F1 key. + **/ + F1, + /** + * The F2 key. + **/ + F2, + /** + * The F3 key. + **/ + F3, + /** + * The F4 key. + **/ + F4, + /** + * The F5 key. + **/ + F5, + /** + * The F6 key. + **/ + F6, + /** + * The F7 key. + **/ + F7, + /** + * The F8 key. + **/ + F8, + /** + * The F9 key. + **/ + F9, + /** + * The F10 key. + **/ + F10, + /** + * The F11 key. + **/ + F11, + /** + * The F12 key. + **/ + F12, + /** + * The NUMBER LOCK key. + **/ + numLock, + /** + * The SCROLL LOCK key. + **/ + scrollLock, + /** + * The browser BACK key. + **/ + browserBack, + /** + * The browser FORWARD key. + **/ + browserForward, + /** + * The semicolon key (;). + **/ + semicolon, + /** + * The equals key (=). + **/ + equal, + /** + * The comma key (,). + **/ + comma, + /** + * The dash key (-). + **/ + dash, + /** + * The period key (.). + **/ + period, + /** + * The forward slash key (/). + **/ + forwardSlash, + /** + * The grave accent key (`). + **/ + graveAccent, + /** + * The open bracket key ([). + **/ + openBracket, + /** + * The backslash key (\). + **/ + backSlash, + /** + * The close bracket key (]). + **/ + closeBracket, + /** + * The single quote key ('). + **/ + singleQuote + } + + //#endregion Enumerations + + //#region Objects + + /** + * A mixin that contains event-related functions. + **/ + var eventMixin: { + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture If true, initiates capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true if capture is to be initiated, otherwise false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + }; + + /** + * Represents the result of a query selector, and provides various operations that perform actions over the elements of the collection. + **/ + interface QueryCollection extends Array { + //#region Methods + + /** + * Adds the specified class to all the elements in the collection. + * @param name The name of the class to add. + * @returns This QueryCollection object. + **/ + addClass(name: string): QueryCollection; + + /** + * Creates a QueryCollection that contains the children of the specified parent element. + * @param element The parent element. + * @returns The QueryCollection that contains the children of the element. + **/ + children(element: HTMLElement): QueryCollection; + + /** + * Clears the specified style property for all the elements in the collection. + * @param name The name of the style property to be cleared. + * @returns This QueryCollection object. + **/ + clearStyle(name: string): QueryCollection; + + /** + * Creates controls that are attached to the elements in this QueryCollection, if the ctor parameter is a function, or configures the controls that are attached to the elements in this QueryCollection, if the ctor parameter is an object. + * @param ctor If this parameter is a function, it is a constructor function that is used to create controls to attach to the elements. If it is an object, it is the set of options passed to the controls. + * @param options The options passed to the newly-created controls. + * @returns This QueryCollection object. + **/ + control(ctor: any, options?: any): QueryCollection; + + /** + * Performs an action on each item in the QueryCollection. + * @param callbackFn The action to perform on each item. + * @param thisArg The argument to bind to callbackFn. + * @returns The QueryCollection. + **/ + forEach(callbackFn: (value: T, index: number, array: T[]) => void, thisArg?: any): QueryCollection; + + /** + * Gets an item from the QueryCollection. + * @param index The index of the item to return. + * @returns A single item from the collection. + **/ + get(index: number): T; + + /** + * Gets an attribute value from the first element in the collection. + * @param name The name of the attribute. + * @returns The value of the attribute. + **/ + getAttribute(name: string): any; + + /** + * Determines whether the specified class exists on the first element of the collection. + * @param name The name of the class. + * @returns true if the element has the specified class; otherwise, false. + **/ + hasClass(name: string): boolean; + + /** + * Looks up an element by ID and wraps the result in a QueryCollection. + * @param id The ID of the element. + * @returns A QueryCollection that contains the element, if it is found. + **/ + id(id: string): QueryCollection; + + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: T): void; + + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: T[]): void; + + /** + * Registers the listener for the specified event on all the elements in the collection. + * @param eventType The name of the event. + * @param listener The event handler function to be called when the event occurs. + * @param capture true if capture == true is to be passed to addEventListener; otherwise, false. + **/ + listen(eventType: string, listener: Function, capture?: boolean): void; + + /** + * Executes a query selector on all the elements in the collection and aggregates the result into a QueryCollection. + * @param query The query selector string. + * @returns A QueryCollection object containing the aggregate results of executing the query on all the elements in the collection. + **/ + query(query: any): QueryCollection; + + /** + * Removes the specified class from all the elements in the collection. + * @param name The name of the class to be removed. + * @returns his QueryCollection object. + **/ + removeClass(name: string): QueryCollection; + + /** + * Unregisters the listener for the specified event on all the elements in the collection. + * @param eventType The name of the event. + * @param listener The event handler function. + * @param capture true if capture == true; otherwise, false. + * @returns This QueryCollection object. + **/ + removeEventListener(eventType: string, listener: Function, capture?: boolean): QueryCollection; + + /** + * Sets an attribute value on all the items in the collection. + * @param name The name of the attribute to be set. + * @param value The value of the attribute to be set. + * @returns This QueryCollection object. + **/ + setAttribute(name: string, value: any): QueryCollection; + + /** + * Sets the specified style property for all the elements in the collection. + * @param name The name of the style property. + * @param value The value for the property. + * @returns This QueryCollection object. + **/ + setStyle(name: string, value: any): QueryCollection; + + /** + * Renders a template that is bound to the given data and parented to the elements included in the QueryCollection. If the QueryCollection contains multiple elements, the template is rendered multiple times, once at each element in the QueryCollection per item of data passed. + * @param templateElement The DOM element to which the template control is attached. + * @param data The data to render. If the data is an array (or any other object that has a forEach method) then the template is rendered multiple times, once for each item in the collection. + * @param renderDonePromiseCallback If supplied, this function is called each time the template gets rendered, and is passed a promise that is fulfilled when the template rendering is complete. + * @returns The QueryCollection. + **/ + template(templateElement: HTMLElement, data: any, renderDonePromiseCallback: Function): QueryCollection; + + /** + * Toggles (adds or removes) the specified class on all the elements in the collection. If the class is present, it is removed; if it is absent, it is added. + * @param name The name of the class to be toggled. + * @returns This QueryCollection object. + **/ + toggleClass(name: string): QueryCollection; + + //#endregion Methods + + } + + /** + * Constructor support for QueryCollection interface + **/ + export var QueryCollection: { + new (items: T[]): QueryCollection; + prototype: QueryCollection; + } + + //#endregion Objects + + //#region Functions + + /** + * Adds the specified class to the specified element. + * @param e The element to which to add the class. + * @param name The name of the class to add. + * @returns The element. + **/ + function addClass(e: T, name: string): T; + + /** + * Gets a collection of elements that are the direct children of the specified element. + * @param element The parent element. + * @returns The collection of children of the element. + **/ + function children(element: HTMLElement): QueryCollection; + + /** + * Converts a CSS positioning string for the specified element to pixels. + * @param element The element. + * @param value The CSS positioning string. + * @returns The number of pixels. + **/ + function convertToPixels(element: HTMLElement, value: string): number; + + /** + * Creates an object that has one event for each name passed to the function. + * @param events A variable list of property names. + * @returns The object with the specified properties. The names of the properties are prefixed with 'on'. + **/ + function createEventProperties(...events: string[]): any; + + /** + * Gets the data value associated with the specified element. + * @param element The element. + * @returns The value associated with the element. + **/ + function data(element: HTMLElement): any; + + /** + * Disposes all first-generation disposable elements that are descendents of the specified element. The specified element itself is not disposed. + * @param element The root element whose sub-tree is to be disposed. + **/ + function disposeSubTree(element: HTMLElement): void; + + /** + * Removes all the child nodes from the specified element. + * @param element The element. + * @returns The element. + **/ + function empty(element: T): T; + + /** + * Determines whether the specified event occurred within the specified element. + * @param element The element. + * @param event The event. + * @returns true if the event occurred within the element; otherwise, false. + **/ + function eventWithinElement(element: HTMLElement, event: Event): boolean; + + /** + * Adds tags and type to a logging message. + * @param message The message to be formatted. + * @param tag The tag(s) to be applied to the message. Multiple tags should be separated by spaces. + * @param type The type of the message. + * @returns The formatted message. + **/ + function formatLog(message: string, tag: string, type: string): string; + + /** + * Gets the height of the content of the specified element. The content height does not include borders or padding. + * @param element The element. + * @returns The content height of the element. + **/ + function getContentHeight(element: HTMLElement): number; + + /** + * Gets the width of the content of the specified element. The content width does not include borders or padding. + * @param element The element. + * @returns The content width of the element. + **/ + function getContentWidth(element: HTMLElement): number; + + /** + * Gets the leaf-level type or namespace specified by the name parameter. + * @param name The name of the member. + * @param root The root to start in. Defaults to the global object. + * @returns The leaf-level type or namespace in the specified parent namespace. + **/ + function getMember(name: string, root?: any): any; + + /** + * Gets the position of the specified element. + * @param element The element. + * @returns An object that contains the left, top, width and height properties of the element. + **/ + function getPosition(element: HTMLElement): IPosition; + + /** + * Gets the left coordinate of the specified element relative to the specified parent. + * @param element The element. + * @param parent The parent element. + * @returns The relative left coordinate. + **/ + function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number; + + /** + * Gets the top coordinate of the element relative to the specified parent. + * @param element The element. + * @param parent The parent element. + * @returns The relative top coordinate. + **/ + function getRelativeTop(element: HTMLElement, parent: HTMLElement): number; + + /** + * Gets the height of the element, including its margins. + * @param element The element. + * @returns The height of the element including margins. + **/ + function getTotalHeight(element: HTMLElement): number; + + /** + * Gets the width of the element, including margins. + * @param element The element. + * @returns The width of the element including margins. + **/ + function getTotalWidth(element: HTMLElement): number; + + /** + * Determines whether the specified element has the specified class. + * @param e The element. + * @param name The name of the class. + * @returns true if the element has the class, otherwise false. + **/ + function hasClass(e: HTMLElement, name: string): boolean; + + /** + * Returns a collection with zero or one elements matching the specified id. + * @param id The ID of the element (or elements). + * @returns A collection of elements whose id matches the id parameter. + **/ + function id(id: string): QueryCollection; + + /** + * Calls insertAdjacentHTML on the specified element. + * @param element The element on which insertAdjacentHTML is to be called. + * @param position The position relative to the element at which to insert the HTML. Possible values are: beforebegin, afterbegin, beforeend, afterend. + * @param text The text to insert. + **/ + function insertAdjacentHTML(element: HTMLElement, position: string, text: string): void; + + /** + * Calls insertAdjacentHTML on the specified element in the context of MSApp.execUnsafeLocalFunction. + * @param element The element on which insertAdjacentHTML is to be called. + * @param position The position relative to the element at which to insert the HTML. Possible values are: beforebegin, afterbegin, beforeend, afterend. + * @param text Value to be provided to insertAdjacentHTML. + **/ + function insertAdjacentHTMLUnsafe(element: HTMLElement, position: string, text: string): void; + + /** + * Attaches the default dispose API wrapping the dispose implementation to the specified element. + * @param element The element to mark as disposable. + * @param disposeImpl The function containing the element-specific dispose logic, called by the dispose function that markDisposable attaches. + **/ + function markDisposable(element: HTMLElement, disposeImpl: Function): void; + + /** + * Marks a function as being compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. + * @param func The function to be marked as compatible with declarative processing. + * @returns The input function, marked as compatible with declarative processing. + **/ + function markSupportedForProcessing(func: U): U; + + /** + * Returns a QueryCollection with zero or one elements matching the specified selector query. + * @param query The CSS selector to use. See Selectors for more information. + * @param element Optional. The root element at which to start the query. If this parameter is omitted, the scope of the query is the entire document. + * @returns A QueryCollection with zero or one elements matching the specified selector query. + **/ + function query(query: any, element?: HTMLElement): QueryCollection; + + /** + * Ensures that the specified function executes only after the DOMContentLoaded event has fired for the current page. The DOMContentLoaded event occurs after the page has been parsed but before all the resources are loaded. + * @param callback A function that executes after the DOMContentLoaded event has occurred. + * @param async If true, the callback should be executed asynchronously. + * @returns A promise that completes after the DOMContentLoaded event has occurred. + **/ + function ready(callback?: Function, async?: boolean): Promise; + + /** + * Removes the specified class from the specified element. + * @param e The element from which to remove the class. + * @param name The name of the class to remove. + * @returns The element. + **/ + function removeClass(e: T, name: string): T; + + /** + * Asserts that the value is compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. If the value is not compatible, and strictProcessing is on, an exception is thrown. All functions that have been declared using WinJS.Class.define, WinJS.Class.derive, WinJS.UI.Pages.define, or WinJS.Binding.converter are automatically marked as supported for declarative processing. Any other function that you use from a declarative context (that is, a context in which an HTML element has a data-win-control or data-win-options attribute) must be marked manually by calling this function. When you mark a function as supported for declarative processing, you are guaranteeing that the code in the function is secure from injection of third-party content. + * @param value The value to be tested for compatibility with declarative processing. If the value is a function it must be marked with a property supportedForProcessing with a value of true when strictProcessing is on. For more information, see WinJS.Utilities.markSupportedForProcessing. + * @returns The input value. + **/ + function requireSupportedForProcessing(value: T): T; + + /** + * Sets the innerHTML property of the specified element to the specified text. + * @param element The element on which the innerHTML property is to be set. + * @param text The value to be set to the innerHTML property. + **/ + function setInnerHTML(element: HTMLElement, text: string): void; + + /** + * Sets the innerHTML property of the specified element to the specified text. + * @param element The element on which the innerHTML property is to be set. + * @param text The value to be set to the innerHTML property. + **/ + function setInnerHTMLUnsafe(element: HTMLElement, text: string): void; + + /** + * Sets the outerHTML property of the specified element to the specified text. + * @param element The element on which the outerHTML property is to be set. + * @param text The value to be set to the outerHTML property. + **/ + function setOuterHTML(element: HTMLElement, text: string): void; + + /** + * Sets the outerHTML property of the specified element to the specified text in the context of MSApp.execUnsafeLocalFunction. + * @param element The element on which the outerHTML property is to be set. + * @param text The value to be set to the outerHTML property. + **/ + function setOuterHTMLUnsafe(element: HTMLElement, text: string): void; + + /** + * Configures a logger that writes messages containing the specified tags to the JavaScript console. + * @param options The tags for messages to log. Multiple tags should be separated by spaces. May contain type, tags, excludeTags and action properties. + **/ + function startLog(options?: ILogOptions): void; + + /** + * Removes the WinJS logger that had previously been set up. + **/ + function stopLog(): void; + + /** + * Toggles (adds or removes) the specified class on the specified element. If the class is present, it is removed; if it is absent, it is added. + * @param e The element on which to toggle the class. + * @param name The name of the class to toggle. + * @returns The element. + **/ + function toggleClass(e: T, name: string): T; + + //#endregion Functions + + //#region Properties + + /** + * Gets whether the current script context has access to WinRT APIs. + **/ + var hasWinRT: boolean; + + /** + * Indicates whether the app is running on Windows Phone. + **/ + var isPhone: boolean; + + //#endregion Properties + + //#region Interfaces + + interface ILogOptions { + type: string; + action?: (message: string, tags: string, type: string) => void; + excludeTags: string; + tags: string; + } + + interface IPosition { + left: number; + top: number; + width: number; + height: number; + } + + //#endregion Interfaces + +} +/** + * Provides functions and objects for scheduling and managing asynchronous tasks. +**/ +declare module WinJS.Utilities.Scheduler { + //#region Enumerations + + /** + * Represents a priority for a job managed by the Scheduler. + **/ + enum Priority { + /** + * A priority higher than the normal priority level. + **/ + aboveNormal, + /** + * A priority less than the normal priority level. + **/ + belowNormal, + /** + * A high priority. + **/ + high, + /** + * The idle priority for work items. + **/ + idle, + /** + * The highest priority. + **/ + max, + /** + * The lowest priority. + **/ + min, + /** + * The normal priority for work items. + **/ + normal + } + + //#endregion Enumerations + + //#region Interfaces + + /** + * Represents a work item that's executed by the Scheduler. + **/ + interface IJob { + //#region Methods + + /** + * Cancels the job. + **/ + cancel(): void; + + /** + * Pauses the job. + **/ + pause(): void; + + /** + * Resumes the job. + **/ + resume(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets a value that indicates whether the job has successfully completed. + **/ + completed: boolean; + + /** + * Gets the unique numeric identifier assigned to the job. + **/ + id: number; + + /** + * Gets or sets the name of the job. + **/ + name: string; + + /** + * Gets or sets the owner of the job. + **/ + owner: IOwnerToken; + + /** + * Gets or sets the priority of the job. + **/ + priority: Priority; + + //#endregion Properties + + } + + /** + * Provides a control mechanism that allows a job to cooperatively yield. This object is passed to your work function when you schedule it. + **/ + interface IJobInfo { + //#region Methods + + /** + * Uses a Promise to determine how long the scheduler should wait before rescheduling the job after it yields. + * @param promise Once the work item yields, the scheduler will wait for this Promise to complete before rescheduling the job. + **/ + setPromise(promise: Promise): void; + + /** + * Specifies the next unit of work to run once this job yields. + * @param work The next unit of work to run once this job yields. + **/ + setWork(work: Function): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the work item associated with this IJobInfo. + **/ + job: IJob; + + /** + * Gets a value that specifies whether the job should yield. + **/ + shouldYield: boolean; + + //#endregion Properties + + } + + /** + * Represents an object that owns jobs. You can use this object to cancel a set of jobs. + **/ + interface IOwnerToken { + //#region Methods + + /** + * Synchronously cancels the job that this token owns, including paused and blocked jobs. + **/ + cancelAll(): void; + + //#endregion Methods + + } + + //#endregion Interfaces + + //#region Functions + + /** + * Creates and returns a new IOwnerToken which can be set to the owner property of one or more jobs. + * @returns A new IOwnerToken which can be set to the owner property of one or more jobs. + **/ + function createOwnerToken(): IOwnerToken; + + /** + * Runs the specified callback in a high priority context. + * @param callback The callback to run in a high priority callback. + * @returns The return value of the callback. + **/ + function execHigh(callback: () => U): U; + + /** + * Returns a string representation of the scheduler's state for diagnostic purposes. The jobs and drain requests are displayed in the order in which they are currently expected to be processed. The current job and drain request are marked by an asterisk. + * @returns A string representation of the scheduler's state for diagnostic purposes. The jobs and drain requests are displayed in the order in which they are currently expected to be processed. The current job and drain request are marked by an asterisk. + **/ + function retrieveState(): string; + + /** + * Runs jobs in the scheduler without timeslicing until all jobs at the specified priority and higher have executed. + * @param priority The priority to which the scheduler should drain. The default is -15. + * @param name An optional description of the drain request for diagnostics. + * @returns A Promise which completes when the drain has finished. Canceling this Promise cancels the drain request. This Promise will never enter an error state. + **/ + function requestDrain(priority?: Priority, name?: string): Promise; + + /** + * Schedules the specified function to execute asynchronously. + * @param work A function that represents the work item to be scheduled. When called the work item will receive as its first argument an object which allows the work item to ask the scheduler if it should yield cooperatively and if so allows the work item to either provide a function to be run as a continuation or a WinJS.Promise which will when complete provide a function to run as a continuation. Provide these fields for the object: shouldYield, setWork(work), setPromise(promise), job. + * @param priority The priority of the work item. If you don't specify a priority, it defaults to WinJS.Utilities.Scheduler.Priority.normal. + * @param thisArg A "this" instance to be bound to the work item. The default value is null. + * @param name A description of the work item for diagnostics. The default value is an empty string. + * @returns The job instance that represents this work item. + **/ + function schedule(work: (jobInfo: IJobInfo) => any, priority?: Priority, thisArg?: any, name?: string): IJob; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.aboveNormal priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of aboveNormal priority. + **/ + function schedulePromiseAboveNormal(promiseValue?: U, jobName?: string): Promise; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.belowNormal priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of belowNormal priority. + **/ + function schedulePromiseBelowNormal(promiseValue?: U, jobName?: string): Promise; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.high priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of high priority. + **/ + function schedulePromiseHigh(promiseValue?: U, jobName?: string): Promise; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.Idle priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of idle priority. + **/ + function schedulePromiseIdle(promiseValue?: U, jobName?: string): Promise; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.normal priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of normal priority. + **/ + function schedulePromiseNormal(promiseValue?: U, jobName?: string): Promise; + + //#endregion Functions + +} From adcbed64b13e72d3a4a7cd0b8247aa1b0d6854cd Mon Sep 17 00:00:00 2001 From: Sean Xu Date: Fri, 27 Jun 2014 15:22:21 -0700 Subject: [PATCH 031/324] Renamed 'legacy' folder to 'releases'. --- winjs/{legacy => releases}/winjs-1.0.d.ts | 0 winjs/{legacy => releases}/winjs-2.0.d.ts | 0 winjs/{legacy => releases}/winjs-2.1.d.ts | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename winjs/{legacy => releases}/winjs-1.0.d.ts (100%) rename winjs/{legacy => releases}/winjs-2.0.d.ts (100%) rename winjs/{legacy => releases}/winjs-2.1.d.ts (100%) diff --git a/winjs/legacy/winjs-1.0.d.ts b/winjs/releases/winjs-1.0.d.ts similarity index 100% rename from winjs/legacy/winjs-1.0.d.ts rename to winjs/releases/winjs-1.0.d.ts diff --git a/winjs/legacy/winjs-2.0.d.ts b/winjs/releases/winjs-2.0.d.ts similarity index 100% rename from winjs/legacy/winjs-2.0.d.ts rename to winjs/releases/winjs-2.0.d.ts diff --git a/winjs/legacy/winjs-2.1.d.ts b/winjs/releases/winjs-2.1.d.ts similarity index 100% rename from winjs/legacy/winjs-2.1.d.ts rename to winjs/releases/winjs-2.1.d.ts From 4bc469d06c87f2e6609147a57784d8a695740507 Mon Sep 17 00:00:00 2001 From: Sean Xu Date: Fri, 27 Jun 2014 15:29:38 -0700 Subject: [PATCH 032/324] Missing semicolon. --- winjs/releases/winjs-2.1.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/winjs/releases/winjs-2.1.d.ts b/winjs/releases/winjs-2.1.d.ts index 717e3d1a6..66afeb69e 100644 --- a/winjs/releases/winjs-2.1.d.ts +++ b/winjs/releases/winjs-2.1.d.ts @@ -1692,7 +1692,7 @@ declare module WinJS.UI.Animation { * @param movingBackwards Determines whether the navigation is moving backwards * @returns An object that contains an exit method used for animating exiting pages and an enter method used for animating entering pages. **/ - function createPageNavigationAnimation(currentPreferredAnimation: PageNavigationAnimation, nextPreferredAnimation: PageNavigationAnimation, movingBackwards: boolean): { enter: () => any, exit: () => any }; + function createPageNavigationAnimation(currentPreferredAnimation: PageNavigationAnimation, nextPreferredAnimation: PageNavigationAnimation, movingBackwards: boolean): { enter: () => any; exit: () => any; }; /** * Creates an object that performs a peek animation. From a001147307a688fe0f11ee0053b8e3321a167778 Mon Sep 17 00:00:00 2001 From: Jason Zhao Date: Fri, 27 Jun 2014 17:58:58 -0700 Subject: [PATCH 033/324] added definitions for angular-hotkeys --- angular-hotkeys/angular-hotkeys-tests.ts | 13 ++++++++++ angular-hotkeys/angular-hotkeys.d.ts | 30 ++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 angular-hotkeys/angular-hotkeys-tests.ts create mode 100644 angular-hotkeys/angular-hotkeys.d.ts diff --git a/angular-hotkeys/angular-hotkeys-tests.ts b/angular-hotkeys/angular-hotkeys-tests.ts new file mode 100644 index 000000000..4e63b32fa --- /dev/null +++ b/angular-hotkeys/angular-hotkeys-tests.ts @@ -0,0 +1,13 @@ +/// + +var hotkeyProvider: ng.hotkeys.HotkeysProvider; +var hotkeyObj: ng.hotkeys.Hotkey; + +hotkeyProvider.add("mod+s", "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => {} ); +hotkeyProvider.add(hotkeyObj); +hotkeyProvider.del("mod+s"); +hotkeyProvider.get("mod+s"); +hotkeyProvider.toggleCheatSheet(); + +hotkeyProvider.add(hotkeyObj.combo, hotkeyObj.description ,hotkeyObj.callback); + diff --git a/angular-hotkeys/angular-hotkeys.d.ts b/angular-hotkeys/angular-hotkeys.d.ts new file mode 100644 index 000000000..8c2e1ff1c --- /dev/null +++ b/angular-hotkeys/angular-hotkeys.d.ts @@ -0,0 +1,30 @@ +// Type definitions for angular-hotkeys +// Project: https://github.com/chieffancypants/angular-hotkeys +// Definitions by: Jason Zhao +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module ng.hotkeys { + + interface HotkeysProvider { + template: string; + includeCheatSheet: boolean; + cheatSheetHotkey: string; + cheatSheetDescription: string; + + add(combo: string, description: string, callback: (event: Event, hotkeys: ng.hotkeys.Hotkey) => void): void; + + add(hotkeyObj: ng.hotkeys.Hotkey): void; + + del(combo: string): void; + + get(combo: string): ng.hotkeys.Hotkey; + + toggleCheatSheet(): void; + } + + interface Hotkey { + combo: string; + description?: string; + callback: (event: Event, hotkey: ng.hotkeys.Hotkey) => void; + } +} From b0df0aafff0cab97f5411c912381b13527c8ba89 Mon Sep 17 00:00:00 2001 From: Douglas Eichelberger Date: Sat, 28 Jun 2014 14:31:59 -0700 Subject: [PATCH 034/324] create interact.d.ts --- CONTRIBUTORS.md | 1 + interactjs/interact-tests.ts | 107 +++++++++++++++ interactjs/interact.d.ts | 245 +++++++++++++++++++++++++++++++++++ 3 files changed, 353 insertions(+) create mode 100644 interactjs/interact-tests.ts create mode 100644 interactjs/interact.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 42cdffabe..01d716502 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -122,6 +122,7 @@ All definitions files include a header with the author and editors, so at some p * [iCheck](http://damirfoy.com/iCheck/) (by [Dániel Tar](https://github.com/qcz)) * [Impress.js](https://github.com/bartaz/impress.js) (by [Boris Yankov](https://github.com/borisyankov)) * [Imagemagick](http://github.com/rsms/node-imagemagick) (by [Carlos Ballesteros Velasco](https://github.com/soywiz)) +* [interact.js](http://github.com/taye/interact.js) (by [Douglas Eichelberger](https://github.com/dduugg)) * [iScroll](http://cubiq.org/iscroll-4) (by [Boris Yankov](https://github.com/borisyankov) and [Christiaan Rakowski](https://github.com/csrakowski)) * [IxJS (Interactive extensions)](https://github.com/Reactive-Extensions/IxJS) (by [Igor Oleinikov](https://github.com/Igorbek)) * [jake](https://github.com/mde/jake) (by [Kon](http://phyzkit.net/)) diff --git a/interactjs/interact-tests.ts b/interactjs/interact-tests.ts new file mode 100644 index 000000000..e658f1275 --- /dev/null +++ b/interactjs/interact-tests.ts @@ -0,0 +1,107 @@ +/// + +import interact = require("interact"); + +var button: HTMLElement = document.createElement("BUTTON"); +var rectangle: ClientRect = { + left: 100, + width: 100, + right: 100, + top: 100, + bottom: 100, + height: 100 +}; +var interactable = interact(button); + +interactable.draggable(); +interactable.draggable(true); +interactable.draggable({ + onstart: (event: InteractEvent) => {}, + onmove : (event: InteractEvent) => {}, + onend : (event: InteractEvent) => {} +}); +interactable.dropzone(); +interactable.dropzone(true); +interactable.dropChecker(() => {}); +interactable.accept(); +interactable.accept("button"); +interactable.accept(button); +interactable.resizable(); +interactable.resizable(true); +interactable.squareResize(); +interactable.squareResize(true); +interactable.gesturable(); +interactable.gesturable(true); +interactable.gesturable({ + onmove: () => {} +}); +interactable.autoScroll(); +interactable.autoScroll(true); +interactable.snap(); +interactable.snap(true); +interactable.inertia(); +interactable.inertia({ + resistance: 1 +}); +interactable.inertia(true); +interactable.actionChecker(); +interactable.actionChecker((event: MouseEvent, defaultAction: string, interactable2: Interactable) => defaultAction); +var rect: ClientRect = interactable.getRect(); +interactable.rectChecker(); +interactable.styleCursor(); +interactable.origin(); +interactable.origin({x: 0, y: 0}); +interactable.origin(button); +interactable.deltaSource(); +interactable.deltaSource("client"); +interactable.restrict(); +interactable.restrict({ + "drag": button, + "resize": button, + "gesture": button +}); +interactable.context(); +interactable.ignoreFrom(); +interactable.ignoreFrom("button"); +interactable.ignoreFrom(button); +interactable.validateSetting("restrict", "drag", button); +interactable.element(); +interactable.on("click", () => {}, true); +interactable.off("click", () => {}, true); +interactable.unset(); + +interact.isSet(button); +interact.on("click", () => {}, true); +interact.off("click", () => {}, true); +interact.enableDragging(); +interact.enableDragging(true); +interact.enableResizing(); +interact.enableResizing(true); +interact.enableGesturing(); +interact.enableGesturing(true); +interact.debug(); +interact.margin(); +interact.margin(10); +interact.styleCursor(); +interact.styleCursor(true); +interact.autoScroll(true); +interact.autoScroll(); +interact.snap(); +interact.snap(true); +interact.snap({ + mode: "grid" +}); +interact.inertia(); +interact.inertia(true); +interact.supportsTouch(); +interact.currentAction(); +interact.dynamicDrop(); +interact.dynamicDrop(true); +interact.deltaSource(); +interact.deltaSource("page"); + +interact.restrict({ + "drag": rectangle, + "resize": rectangle, + "gesture": rectangle +}); diff --git a/interactjs/interact.d.ts b/interactjs/interact.d.ts new file mode 100644 index 000000000..8189d6415 --- /dev/null +++ b/interactjs/interact.d.ts @@ -0,0 +1,245 @@ +// Type definitions for Interacting for interact.js v1.0.17 +// Project: https://github.com/taye/interact.js +// Definitions by: Douglas Eichelberger +// Definitions: https://github.com/borisyankov/DefinitelyType + +// API documentation: http://interactjs.io/docs + +interface Interactable { + // returns Element or string + accept(): any; + accept(newValue: Element): Interactable; + accept(newValue: string): Interactable; + actionChecker(): Function; + actionChecker(checker: Function): Interactable; + // returns boolean or {[key: string]: any} + autoScroll(): any; + autoScroll(options: boolean): Interactable; + autoScroll(options: {[key: string]: any}): Interactable; + context(): Node; + defaultActionChecker(event: any): string; + deltaSource(): string; + // returns Interactable if newValue is "page" or "client", otherwise returns string + deltaSource(newValue: String): Interactable; + draggable(): boolean; + draggable(options: boolean): Interactable; + draggable(options: {[key: string]: any}): Interactable; + dropCheck(event: MouseEvent): boolean; + dropCheck(event: TouchEvent): boolean; + dropChecker(): Function; + dropChecker(checker: Function): Interactable; + // returns boolean or {[key: string]: any} + dropzone(): any; + dropzone(options: boolean): Interactable; + dropzone(options: {[key: string]: any}): Interactable; + // return HTMLElement or SVGElement + element(): Element; + fire(iEvent: InteractEvent): Interactable; + // returns boolean or {[key: string]: any} + gesturable(): any; + gesturable(options: boolean): Interactable; + gesturable(options: {[key: string]: any}): Interactable; + getRect(): ClientRect; + // returns Element or string + ignoreFrom(): any; + ignoreFrom(newValue: string): Interactable; + ignoreFrom(newValue: Element): Interactable; + // returns boolean or {[key: string]: any} + inertia(): any; + inertia(options: boolean): Interactable; + inertia(options: {[key: string]: any}): Interactable; + off(eventType: string, listener: Function, useCapture?: boolean): Interactable; + on(eventType: string, listener: Function, useCapture?: boolean): Interactable; + origin(): Point; + origin(newValue: HTMLElement): Interactable; + origin(newValue: SVGElement): Interactable; + origin(newValue: Point): Interactable; + rectChecker(): Function; + rectChecker(newValue: Function): Interactable; + resizable(): Interactable; + resizable(options: boolean): Interactable; + resizable(options: {[key: string]: any}): Interactable; + restrict(): Restrict; + restrict(newValue: Restrict): Interactable; + set(options: {[key: string]: any}): Interactable; + // returns boolean or {[key: string]: any} + snap(): any; + snap(options: boolean): Interactable; + snap(options: {[key: string]: any}): Interactable; + squareResize(): boolean; + squareResize(newValue: boolean): Interactable; + styleCursor(): boolean; + styleCursor(newValue: boolean): Interactable; + unset(): InteractStatic; + validateSetting(context: string, option: string, value: any): any; +} + +interface Coordinates { + clientX: number; + clientY: number; + pageX: number; + pageY: number; + timeStamp: number; +} + +interface Debug { + target: any; + dragging: any; + resizing: any; + gesturing: any; + prepared: any; + + prevCoords: Coordinates; + downCoords: Coordinates; + + pointerIds: any[]; + pointerMoves: any[]; + addPointer: any; + removePointer: any; + recordPointers: any; + + inertia: InertiaStatus; + + downTime: any; + downEvent: any; + prevEvent: any; + + Interactable: any; + IOptions: any; + interactables: any; + dropzones: any; + pointerIsDown: any; + defaultOptions: any; + defaultActionChecker: any; + + actions: any; + dragMove: any; + resizeMove: any; + gestureMove: any; + pointerUp: any; + pointerDown: any; + pointerMove: any; + pointerHover: any; + + events: any; + globalEvents: any; + delegatedEvents: any; +} + +interface InertiaStatus { + active: boolean; + target: any; + targetElement: any; + + startEvent: any; + pointerUp: any + + xe: number; + ye: number; + duration: number; + + t0: number; + vx0: number; + vys: number; + + lambda_v0: number; + one_ve_v0: number; + i: any; +} + +interface Point { + x: number; + y: number; +} + +// value types are either ClientRect or Element +interface Restrict { + drag?: any; + gesture?: any; + resize?: any; +} + +interface InteractEvent { + altKey: boolean; + axes: string; + button: number + clientX0: number; + clientX: number + clientY0: number; + clientY: number + ctrlKey: boolean + dt: number; + duration: number; + dx: number; + dy: number; + metaKey: boolean; + pageX: number; + pageY: number; + shiftKey: boolean; + speed: number; + t0: number; + target: any; + timeStamp: number; + type: string; + velocityX: number; + velocityY: number; + x0: number; + y0: number; +} + +interface TouchEvent { + changedTouches: any[]; + pageX: number; + pageY: number; + touches: any[]; + type: string; +} + +interface InteractStatic { + (element: HTMLElement): Interactable; + (element: SVGElement): Interactable; + (element: string): Interactable; + // returns boolean or {[key: string]: any} + autoScroll(): any; + autoScroll(options: boolean): InteractStatic; + autoScroll(options: {[key: string]: any}): InteractStatic; + currentAction(): string + debug(): Debug; + deltaSource(): string; + // "page" and "client" are the valid parameters + deltaSource(newValue: string): InteractStatic; + dynamicDrop(): boolean; + dynamicDrop(newValue: boolean): InteractStatic; + enableDragging(): boolean; + enableDragging(newValue: boolean): InteractStatic; + enableGesturing(): boolean; + enableGesturing(newValue: boolean): InteractStatic; + enableResizing(): boolean; + enableResizing(newValue: boolean): InteractStatic; + // returns boolean or {[key: string]: any} + inertia(): any; + inertia(options: boolean): InteractStatic; + inertia(options: {[key: string]: any}): InteractStatic; + isSet(element: Element): boolean; + margin(): number; + margin(newvalue: number): InteractStatic; + off(type: string, listener: Function, useCapture?: boolean): InteractStatic; + on(type: string, listener: Function, useCapture?: boolean): InteractStatic; + restrict(): Restrict; + restrict(newValue: Restrict): InteractStatic; + simulate(action: string, element: Element, pointerEvent?: any): InteractStatic; + // returns boolean or {[key: string]: any} + snap(): any; + snap(options: boolean): InteractStatic; + snap(options: {[key: string]: any}): InteractStatic; + stop(event: Event): InteractStatic; + styleCursor(): boolean; + styleCursor(newValue: boolean): InteractStatic; + supportsTouch(): boolean +} + +declare var interact: InteractStatic; + +declare module "interact" { + export = interact; +} From 7756dea3fa0dddcba3449557858bdcc16d11f0fc Mon Sep 17 00:00:00 2001 From: nitram509 Date: Sun, 29 Jun 2014 12:51:03 +0200 Subject: [PATCH 035/324] fixed test filename according to http://definitelytyped.org/guides/contributing.html --- hellojs/{hellojs-test.ts => hellojs-tests.ts} | 0 jstree/{jstree-test.ts => jstree-tests.ts} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename hellojs/{hellojs-test.ts => hellojs-tests.ts} (100%) rename jstree/{jstree-test.ts => jstree-tests.ts} (100%) diff --git a/hellojs/hellojs-test.ts b/hellojs/hellojs-tests.ts similarity index 100% rename from hellojs/hellojs-test.ts rename to hellojs/hellojs-tests.ts diff --git a/jstree/jstree-test.ts b/jstree/jstree-tests.ts similarity index 100% rename from jstree/jstree-test.ts rename to jstree/jstree-tests.ts From e9b80d02b55bf51c6de791b77c619855f522687e Mon Sep 17 00:00:00 2001 From: nitram509 Date: Sun, 29 Jun 2014 12:51:36 +0200 Subject: [PATCH 036/324] added Type definitions for keymaster v1.6.2, Project: https://github.com/madrobby/keymaster --- CONTRIBUTORS.md | 1 + keymaster/keymaster-tests.ts | 14 +++++++++ keymaster/keymaster.d.ts | 60 ++++++++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+) create mode 100644 keymaster/keymaster-tests.ts create mode 100644 keymaster/keymaster.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 42cdffabe..63eff9011 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -190,6 +190,7 @@ All definitions files include a header with the author and editors, so at some p * [jsTree](http://www.jstree.com/) (by [Adam Pluciński](https://github.com/adaskothebeast)) * [JWPlayer](http://developer.longtailvideo.com/trac/) (by [Martin Duparc](https://github.com/martinduparc/)) * [KeyboardJS](https://github.com/RobertWHurst/KeyboardJS) (by [Vincent Bortone](https://github.com/vbortone/)) +* [keymaster.js](https://github.com/madrobby/keymaster) (by [Marting W. Kirst](https://github.com/nitram509/)) * [KineticJS](http://kineticjs.com/) (by [Basarat Ali Syed](https://github.com/basarat)) * [Knockback](http://kmalakoff.github.com/knockback/) (by [Marcel Binot](https://github.com/docgit)) * [Knockout.js](http://knockoutjs.com/) (by [Boris Yankov](https://github.com/borisyankov)) diff --git a/keymaster/keymaster-tests.ts b/keymaster/keymaster-tests.ts new file mode 100644 index 000000000..4c7cf3c5b --- /dev/null +++ b/keymaster/keymaster-tests.ts @@ -0,0 +1,14 @@ +/// + +// simple key binding without scope +key('shift+a', function (keyboardEvent: KeyboardEvent, keymasterEvent: KeymasterEvent) { +}); + +// simple key binding with scope +key('shift+b', 'aScope', (keyboardEvent, keymasterEvent) => { +}); + +// possible combinations of filtering +key.filter({target: { tagName: 'propertytest'}}); +key.filter({srcElement: { tagName: 'propertytest'}}); + diff --git a/keymaster/keymaster.d.ts b/keymaster/keymaster.d.ts new file mode 100644 index 000000000..d749f76d1 --- /dev/null +++ b/keymaster/keymaster.d.ts @@ -0,0 +1,60 @@ +// Type definitions for keymaster v1.6.2 +// Project: https://github.com/madrobby/keymaster +// Definitions by: Martin W. Kirst +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// A simple micro-library for defining and dispatching keyboard shortcuts. It has no dependencies. + +interface KeymasterEvent { + key: string; + method: KeyHandler; + mods: number[]; + scope: string; + shortcut: string; +} + +interface KeyHandler { + (keyboardEvent: KeyboardEvent, keymasterEvent: KeymasterEvent) : void; +} + +interface FilterEvent { + target?: { + tagName?: string; + } + srcElement?: { + tagName?: string; + } +} + +interface Keymaster { + + (key: string, callback: KeyHandler): void; + (key: string, scope: string, callback: KeyHandler): void; + + shift: boolean; + alt: boolean; + option: boolean; + ctrl: boolean; + control: boolean; + command: boolean; + + setScope(scopeName: string): void; + getScope():string; + deleteScope(scopeName: string): void; + + noConflict(): void; + + unbind(key: string): void; + unbind(key: string, scopeName: string): void; + + isPressed(keyCode: number): boolean; + getPressedKeyCodes(): number[]; + + filter(event: FilterEvent): void; +} + +declare var key: Keymaster; + +declare module "keymaster" { +export = key; +} From f57d1bfc3a85c306a6bd89042fd55d13f6560db6 Mon Sep 17 00:00:00 2001 From: Lucas Dixon Date: Sun, 9 Mar 2014 23:21:13 -0400 Subject: [PATCH 037/324] added optional media constraints --- webrtc/RTCPeerConnection.d.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/webrtc/RTCPeerConnection.d.ts b/webrtc/RTCPeerConnection.d.ts index d66ad6cf0..bdea29d3e 100644 --- a/webrtc/RTCPeerConnection.d.ts +++ b/webrtc/RTCPeerConnection.d.ts @@ -38,9 +38,19 @@ declare var IceState: { new (): IceState; } +// For Chrome, look at the code here: https://code.google.com/p/chromium/codesearch#chromium/src/third_party/libjingle/source/talk/app/webrtc/webrtcsession.cc&sq=package:chromium&dr=C&l=63 +interface OptionalMediaConstraint { + // When true, will use DTLS/SCTP data channels + DtlsSrtpKeyAgreement?: boolean; + // When true will use Rtp-based data channels (depreicated) + RtpDataChannels?: boolean; +} + // ks 12/20/12 - There's more here that doesn't seem to be documented very well yet. +// http://www.w3.org/TR/2013/WD-webrtc-20130910/ interface MediaConstraints { - mandatory: MediaOfferConstraints; + mandatory?: MediaOfferConstraints; + optional?: OptionalMediaConstraint[] } interface MediaOfferConstraints { From 1bf6a0748ee6cb262367740d0c24297b2c85c323 Mon Sep 17 00:00:00 2001 From: Lucas Dixon Date: Sun, 29 Jun 2014 14:52:43 -0400 Subject: [PATCH 038/324] Initial addition of webcrypto --- webcrypto/WebCrypto.d.ts | 13 +++++++++++++ webcrypto/readme.md | 17 +++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 webcrypto/WebCrypto.d.ts create mode 100644 webcrypto/readme.md diff --git a/webcrypto/WebCrypto.d.ts b/webcrypto/WebCrypto.d.ts new file mode 100644 index 000000000..069f0ca25 --- /dev/null +++ b/webcrypto/WebCrypto.d.ts @@ -0,0 +1,13 @@ +// Type definitions for WebCrypto +// Project: http://www.w3.org/TR/WebCryptoAPI/ +// Definitions by: Lucas Dixon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module crypto { + + // A cryptographically strong pseudo-random number generator seeded with + // truly random values. The buffer passed in is modified, and a reference to + // argument is returned for convenience. + function getRandomValues(array: ArrayBufferView) : ArrayBufferView + +} diff --git a/webcrypto/readme.md b/webcrypto/readme.md new file mode 100644 index 000000000..420dc479f --- /dev/null +++ b/webcrypto/readme.md @@ -0,0 +1,17 @@ +# WebCrypto Definition Notes + +## The WebCrypto specification + +The WebCrypto specification is for performing basic cryptographic operations in +web applications, such as hashing, signature generation and verification, and +encryption and decryption. The API is also for applications to generate and/or +manage the keying material necessary to perform these operations. Uses for this +API range from user or service authentication, document or code signing, and the confidentiality and integrity of communications. + +The latest version of the specification can be found at: http://www.w3.org/TR/WebCryptoAPI/ + +## Adding the reference to your project + +``` +/// +``` From ec15376306be5ee164e0bb7c24894e91bb8ea640 Mon Sep 17 00:00:00 2001 From: Lucas Dixon Date: Sun, 29 Jun 2014 22:53:17 -0400 Subject: [PATCH 039/324] * Added TODOs for things that can be done when/if typescript is improved with links in case people want typescript to be better and want to vote on the issue. * Removed unused IceState * Added moz specific prefixes * Fixed broken use of enum for things that are actually strings and added a TypeScript issue for the fix * Added comments with WebIDL spec for enums * Added RTCMessageEvent for data channels * Support send with ArrayBufferView --- webrtc/RTCPeerConnection.d.ts | 155 +++++++++++++++++++++++----------- 1 file changed, 105 insertions(+), 50 deletions(-) diff --git a/webrtc/RTCPeerConnection.d.ts b/webrtc/RTCPeerConnection.d.ts index bdea29d3e..ac05dbcba 100644 --- a/webrtc/RTCPeerConnection.d.ts +++ b/webrtc/RTCPeerConnection.d.ts @@ -2,11 +2,27 @@ // Project: http://dev.w3.org/2011/webrtc/ // Definitions by: Ken Smith // Definitions: https://github.com/borisyankov/DefinitelyTyped - +// // Definitions taken from http://dev.w3.org/2011/webrtc/editor/webrtc.html +// +// For example code see: +// https://code.google.com/p/webrtc/source/browse/stable/samples/js/apprtc/js/main.js +// +// For a generic implementation see that deals with browser differences, see: +// https://code.google.com/p/webrtc/source/browse/stable/samples/js/base/adapter.js /// +// TODO(1): Get Typescript to have string-enum types as WebRtc is full of string +// enums. +// https://typescript.codeplex.com/discussions/549207 + +// TODO(2): get Typescript to have union types as WebRtc uses them. +// https://typescript.codeplex.com/workitem/1364 + +// TODO(3): Typescript type-abbreviations fail to be structural. +// https://typescript.codeplex.com/workitem/2587 + interface RTCConfiguration { iceServers: RTCIceServer[]; } @@ -24,6 +40,14 @@ declare var RTCIceServer: { new (): RTCIceServer; } +// moz (Firefox) specific prefixes. +interface mozRTCPeerConnection extends RTCPeerConnection { +} +declare var mozRTCPeerConnection: { + prototype: mozRTCPeerConnection; + new (settings: RTCPeerConnectionConfig, constraints?:MediaConstraints): mozRTCPeerConnection; +} +// webkit (Chrome) specific prefixes. interface webkitRTCPeerConnection extends RTCPeerConnection { } declare var webkitRTCPeerConnection: { @@ -31,13 +55,6 @@ declare var webkitRTCPeerConnection: { new (settings: RTCPeerConnectionConfig, constraints?:MediaConstraints): webkitRTCPeerConnection; } -interface IceState { -} -declare var IceState: { - prototype: IceState; - new (): IceState; -} - // For Chrome, look at the code here: https://code.google.com/p/chromium/codesearch#chromium/src/third_party/libjingle/source/talk/app/webrtc/webrtcsession.cc&sq=package:chromium&dr=C&l=63 interface OptionalMediaConstraint { // When true, will use DTLS/SCTP data channels @@ -59,7 +76,7 @@ interface MediaOfferConstraints { } interface RTCSessionDescription { - type?: RTCSdpType; + type?: string; // RTCSdpType; See TODO(3) sdp?: string; } declare var RTCSessionDescription: { @@ -68,7 +85,7 @@ declare var RTCSessionDescription: { } interface RTCSessionDescriptionInit { - type: RTCSdpType; + type: string; // RTCSdpType; See TODO(3) sdp: string; } declare var RTCSessionDescriptionInit: { @@ -76,42 +93,57 @@ declare var RTCSessionDescriptionInit: { new (): RTCSessionDescriptionInit; } -interface SdpType { -} - -interface RTCPeerState { -} - interface RTCDataChannelInit { - reliable: boolean; + ordered ?: boolean; // messages must be sent in-order. + maxPacketLifeTime ?: number; // unsigned short + maxRetransmits ?: number; // unsigned short + protocol ?: string; // default = '' + negotiated ?: boolean; // default = false; + id ?: number; // unsigned short } -declare enum RTCSdpType { - offer, - pranswer, - answer +interface RTCSdpType { + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#rtcsdptype + // enum RTCSdpType { + // "offer", + // "pranswer", + // "answer" + // }; + string; } -declare enum RTCDataChannelState { - connecting, - open, - closing, - closed +interface RTCMessageEvent { + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#event-datachannel-message + // At present, this can be an: ArrayBuffer, a string, or a Blob. + // See TODO(2) + data: any; +} + +interface RTCDataChannelState { + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCDataChannelState + // enum RTCDataChannelState { + // "connecting", + // "open", + // "closing", + // "closed" + // }; + string; } interface RTCDataChannel extends EventTarget { label: string; reliable: boolean; - readyState: RTCDataChannelState; + readyState: string; // RTCDataChannelState; see TODO(3) bufferedAmount: number; - onopen: (event: Event)=> void; - onerror: (event: Event)=> void; - onclose: (event: Event)=> void; + onopen: (event: Event) => void; + onerror: (event: Event) => void; + onclose: (event: Event) => void; close(): void; - onmessage: (event: Event)=> void; + onmessage: (event: RTCMessageEvent) => void; binaryType: string; send(data: string); send(data: ArrayBuffer); + send(data: ArrayBufferView); send(data: Blob); } declare var RTCDataChannel: { @@ -128,7 +160,7 @@ declare var RTCDataChannelEvent: { new (eventInitDict: RTCDataChannelEventInit); } -interface RTCIceCandidateEvent extends Event{ +interface RTCIceCandidateEvent extends Event { candidate: RTCIceCandidate; } @@ -150,21 +182,43 @@ interface RTCSessionDescriptionCallback { (sdp: RTCSessionDescription): void; } interface RTCPeerConnectionErrorCallback { - (errorInformation: string): void; + (errorInformation: DOMError): void; } -/** This should be an enum */ interface RTCIceGatheringState { + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#rtcicegatheringstate-enum + // enum RTCIceGatheringState { + // "new", + // "gathering", + // "complete" + // }; string; } -/** This should be an enum */ interface RTCIceConnectionState { + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCIceConnectionState + // enum RTCIceConnectionState { + // "new", + // "checking", + // "connected", + // "completed", + // "failed", + // "disconnected", + // "closed" + // }; string; } -/** This should be an enum */ -interface RTCSignalingState{ +interface RTCSignalingState { + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCSignalingState + // enum RTCSignalingState { + // "stable", + // "have-local-offer", + // "have-remote-offer", + // "have-local-pranswer", + // "have-remote-pranswer", + // "closed" + // }; string; } @@ -175,27 +229,28 @@ interface RTCPeerConnection { localDescription: RTCSessionDescription; setRemoteDescription(description: RTCSessionDescription, successCallback?: RTCVoidCallback, failureCallback?: RTCPeerConnectionErrorCallback): void; remoteDescription: RTCSessionDescription; - signalingState: RTCSignalingState; + signalingState: string; // RTCSignalingState; see TODO(3) updateIce(configuration?: RTCConfiguration, constraints?: MediaConstraints): void; addIceCandidate(candidate: RTCIceCandidate): void; - iceGatheringState: RTCIceGatheringState; - iceConnectionState: RTCIceConnectionState; + iceGatheringState: string; // RTCIceGatheringState; see TODO(3) + iceConnectionState: string; // RTCIceConnectionState; see TODO(3) getLocalStreams(): MediaStream[]; getRemoteStreams(): MediaStream[]; createDataChannel(label?: string, dataChannelDict?: RTCDataChannelInit): RTCDataChannel; - ondatachannel: (event: Event)=> void; + ondatachannel: (event: Event) => void; addStream(stream: MediaStream, constraints?: MediaConstraints): void; removeStream(stream: MediaStream): void; close(): void; - onnegotiationneeded: (event: Event)=> void; - onconnecting: (event: Event)=> void; - onopen: (event: Event)=> void; - onaddstream: (event: RTCMediaStreamEvent)=> void; - onremovestream: (event: RTCMediaStreamEvent)=> void; - onstatechange: (event: Event)=> void; - onicechange: (event: Event)=> void; - onicecandidate: (event: RTCIceCandidateEvent)=> void; - onidentityresult: (event: Event)=> void; + onnegotiationneeded: (event: Event) => void; + onconnecting: (event: Event) => void; + onopen: (event: Event) => void; + onaddstream: (event: RTCMediaStreamEvent) => void; + onremovestream: (event: RTCMediaStreamEvent) => void; + onstatechange: (event: Event) => void; + onicechange: (event: Event) => void; + onicecandidate: (event: RTCIceCandidateEvent) => void; + onidentityresult: (event: Event) => void; + onsignalingstatechange: (event: Event) => void; } declare var RTCPeerConnection: { prototype: RTCPeerConnection; From 1088ed067655e9110325b3559ff27bcf7e32039f Mon Sep 17 00:00:00 2001 From: Saftpresse99 Date: Mon, 30 Jun 2014 12:12:22 +0200 Subject: [PATCH 040/324] Update angular-translate.d.ts Add definitions for https://github.com/angular-translate/angular-translate/blob/master/src/service/loader-partial.js --- angular-translate/angular-translate.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts index 47dfa63a5..ce2e28779 100644 --- a/angular-translate/angular-translate.d.ts +++ b/angular-translate/angular-translate.d.ts @@ -6,6 +6,13 @@ /// declare module ng.translate { + + interface ITranslatePartialLoader{ + addPart(name: string): ITranslatePartialLoader; + deletePart(name: string, removeData?: boolean): ITranslatePartialLoader; + isPartAvailable(name: string): boolean; + } + interface ITranslationTable { [key: string]: string; } From 371e57f2c9b4895be2fd78267d4200c4318e9fd2 Mon Sep 17 00:00:00 2001 From: Steven Date: Mon, 30 Jun 2014 20:26:58 -0700 Subject: [PATCH 041/324] Dropzone constructor takes any The docs say that the constructor can take a string selector, HtmlElement, or JQuery type as seen here: http://www.dropzonejs.com/#toc_15 --- dropzone/dropzone.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dropzone/dropzone.d.ts b/dropzone/dropzone.d.ts index ac630c9d4..c19bcca88 100644 --- a/dropzone/dropzone.d.ts +++ b/dropzone/dropzone.d.ts @@ -54,7 +54,7 @@ interface DropzoneOptions { } declare class Dropzone { - constructor(container: string, options?: DropzoneOptions); + constructor(container: any, options?: DropzoneOptions); static autoDiscover: boolean; static options: any; static confirm: (question: string, accepted: () => void, rejected?: () => void) => void; From 013410fc78f4fd4a08aab6eca49ab75ea0ac72d6 Mon Sep 17 00:00:00 2001 From: Lucas Dixon Date: Tue, 1 Jul 2014 12:11:32 -0400 Subject: [PATCH 042/324] fixed to make it pass tests with --noImplicitAny --- webrtc/MediaStream-tests.ts | 6 +- webrtc/MediaStream.d.ts | 18 +++- webrtc/RTCPeerConnection-tests.ts | 2 +- webrtc/RTCPeerConnection.d.ts | 165 +++++++++++++++--------------- 4 files changed, 100 insertions(+), 91 deletions(-) diff --git a/webrtc/MediaStream-tests.ts b/webrtc/MediaStream-tests.ts index 290e2ff3c..4dcde91fe 100644 --- a/webrtc/MediaStream-tests.ts +++ b/webrtc/MediaStream-tests.ts @@ -9,7 +9,7 @@ navigator.getUserMedia(mediaStreamConstraints, stream => { console.log('label:' + stream.label); console.log('ended:' + stream.ended); - stream.onended = event => console.log('Stream ended'); + stream.onended = (event:Event) => console.log('Stream ended'); var objectUrl = URL.createObjectURL(stream); var wkObjectUrl = webkitURL.createObjectURL(stream); }, @@ -22,11 +22,11 @@ navigator.webkitGetUserMedia(mediaStreamConstraints, stream => { console.log('label:' + stream.label); console.log('ended:' + stream.ended); - stream.onended = event => console.log('Stream ended'); + stream.onended = (event:Event) => console.log('Stream ended'); var objectUrl = URL.createObjectURL(stream); var wkObjectUrl = webkitURL.createObjectURL(stream); }, error => { console.log('Error message: ' + error.message); console.log('Error name: ' + error.name); - }); \ No newline at end of file + }); diff --git a/webrtc/MediaStream.d.ts b/webrtc/MediaStream.d.ts index f9f549ed0..12e0a253a 100644 --- a/webrtc/MediaStream.d.ts +++ b/webrtc/MediaStream.d.ts @@ -40,13 +40,19 @@ declare var MediaTrackConstraint: { } interface Navigator { - getUserMedia(constraints: MediaStreamConstraints, successCallback: (stream: any) => void, errorCallback: (error: Error) => void); - webkitGetUserMedia(constraints: MediaStreamConstraints, successCallback: (stream: any) => void, errorCallback: (error: Error) => void); + getUserMedia(constraints: MediaStreamConstraints, + successCallback: (stream: any) => void, + errorCallback: (error: Error) => void) : void; + webkitGetUserMedia(constraints: MediaStreamConstraints, + successCallback: (stream: any) => void, + errorCallback: (error: Error) => void): void; } interface EventHandler { (event: Event): void; } -interface NavigatorUserMediaSuccessCallback { (stream: LocalMediaStream): void; } +interface NavigatorUserMediaSuccessCallback { + (stream: LocalMediaStream): void; +} interface NavigatorUserMediaError { PERMISSION_DENIED: number; // = 1; @@ -58,7 +64,9 @@ declare var NavigatorUserMediaError: { PERMISSION_DENIED: number; // = 1; } -interface NavigatorUserMediaErrorCallback { (error: NavigatorUserMediaError): void; } +interface NavigatorUserMediaErrorCallback { + (error: NavigatorUserMediaError): void; +} interface MediaStreamTrackList { length: number; @@ -152,4 +160,4 @@ declare var webkitURL: { new (): streamURL; createObjectURL(stream: MediaStream): string; } - + diff --git a/webrtc/RTCPeerConnection-tests.ts b/webrtc/RTCPeerConnection-tests.ts index d7b5a07f7..d85728c5c 100644 --- a/webrtc/RTCPeerConnection-tests.ts +++ b/webrtc/RTCPeerConnection-tests.ts @@ -32,7 +32,7 @@ peerConnection.createOffer( }, error => console.log("Error creating offer: " + error)); -var type: RTCSdpType = RTCSdpType.offer; +var type: string = RTCSdpType[RTCSdpType.offer]; var offer: RTCSessionDescriptionInit = { type: type, sdp: "some sdp" }; var sessionDescription = new RTCSessionDescription(offer); diff --git a/webrtc/RTCPeerConnection.d.ts b/webrtc/RTCPeerConnection.d.ts index ac05dbcba..e123b69bd 100644 --- a/webrtc/RTCPeerConnection.d.ts +++ b/webrtc/RTCPeerConnection.d.ts @@ -11,7 +11,7 @@ // For a generic implementation see that deals with browser differences, see: // https://code.google.com/p/webrtc/source/browse/stable/samples/js/base/adapter.js -/// +/// // TODO(1): Get Typescript to have string-enum types as WebRtc is full of string // enums. @@ -20,9 +20,6 @@ // TODO(2): get Typescript to have union types as WebRtc uses them. // https://typescript.codeplex.com/workitem/1364 -// TODO(3): Typescript type-abbreviations fail to be structural. -// https://typescript.codeplex.com/workitem/2587 - interface RTCConfiguration { iceServers: RTCIceServer[]; } @@ -45,17 +42,20 @@ interface mozRTCPeerConnection extends RTCPeerConnection { } declare var mozRTCPeerConnection: { prototype: mozRTCPeerConnection; - new (settings: RTCPeerConnectionConfig, constraints?:MediaConstraints): mozRTCPeerConnection; + new (settings: RTCPeerConnectionConfig, + constraints?:MediaConstraints): mozRTCPeerConnection; } // webkit (Chrome) specific prefixes. interface webkitRTCPeerConnection extends RTCPeerConnection { } declare var webkitRTCPeerConnection: { prototype: webkitRTCPeerConnection; - new (settings: RTCPeerConnectionConfig, constraints?:MediaConstraints): webkitRTCPeerConnection; + new (settings: RTCPeerConnectionConfig, + constraints?:MediaConstraints): webkitRTCPeerConnection; } -// For Chrome, look at the code here: https://code.google.com/p/chromium/codesearch#chromium/src/third_party/libjingle/source/talk/app/webrtc/webrtcsession.cc&sq=package:chromium&dr=C&l=63 +// For Chrome, look at the code here: +// https://code.google.com/p/chromium/codesearch#chromium/src/third_party/libjingle/source/talk/app/webrtc/webrtcsession.cc&sq=package:chromium&dr=C&l=63 interface OptionalMediaConstraint { // When true, will use DTLS/SCTP data channels DtlsSrtpKeyAgreement?: boolean; @@ -75,22 +75,20 @@ interface MediaOfferConstraints { OfferToReceiveVideo: boolean; } +interface RTCSessionDescriptionInit { + type: string; // RTCSdpType; See TODO(1) + sdp: string; +} + interface RTCSessionDescription { - type?: string; // RTCSdpType; See TODO(3) + type?: string; // RTCSdpType; See TODO(1) sdp?: string; } declare var RTCSessionDescription: { prototype: RTCSessionDescription; new (descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; -} - -interface RTCSessionDescriptionInit { - type: string; // RTCSdpType; See TODO(3) - sdp: string; -} -declare var RTCSessionDescriptionInit: { - prototype: RTCSessionDescriptionInit; - new (): RTCSessionDescriptionInit; + // TODO: Add serializer. + // See: http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCSdpType) } interface RTCDataChannelInit { @@ -102,14 +100,12 @@ interface RTCDataChannelInit { id ?: number; // unsigned short } -interface RTCSdpType { - // http://dev.w3.org/2011/webrtc/editor/webrtc.html#rtcsdptype - // enum RTCSdpType { - // "offer", - // "pranswer", - // "answer" - // }; - string; +// TODO(1) +declare enum RTCSdpType { + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#rtcsdptype + 'offer', + 'pranswer', + 'answer' } interface RTCMessageEvent { @@ -119,32 +115,33 @@ interface RTCMessageEvent { data: any; } -interface RTCDataChannelState { +// TODO(1) +declare enum RTCDataChannelState { // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCDataChannelState - // enum RTCDataChannelState { - // "connecting", - // "open", - // "closing", - // "closed" - // }; - string; + 'connecting', + 'open', + 'closing', + 'closed' } interface RTCDataChannel extends EventTarget { label: string; reliable: boolean; - readyState: string; // RTCDataChannelState; see TODO(3) + readyState: string; // RTCDataChannelState; see TODO(1) bufferedAmount: number; + binaryType: string; + onopen: (event: Event) => void; onerror: (event: Event) => void; onclose: (event: Event) => void; - close(): void; onmessage: (event: RTCMessageEvent) => void; - binaryType: string; - send(data: string); - send(data: ArrayBuffer); - send(data: ArrayBufferView); - send(data: Blob); + + close(): void; + + send(data: string): void ; + send(data: ArrayBuffer): void; + send(data: ArrayBufferView): void; + send(data: Blob): void; } declare var RTCDataChannel: { prototype: RTCDataChannel; @@ -152,12 +149,11 @@ declare var RTCDataChannel: { } interface RTCDataChannelEvent extends Event { - constructor (eventInitDict: RTCDataChannelEventInit); channel: RTCDataChannel; } declare var RTCDataChannelEvent: { prototype: RTCDataChannelEvent; - new (eventInitDict: RTCDataChannelEventInit); + new (eventInitDict: RTCDataChannelEventInit): RTCDataChannelEvent; } interface RTCIceCandidateEvent extends Event { @@ -185,58 +181,62 @@ interface RTCPeerConnectionErrorCallback { (errorInformation: DOMError): void; } -interface RTCIceGatheringState { +// TODO(1) +declare enum RTCIceGatheringState { // http://dev.w3.org/2011/webrtc/editor/webrtc.html#rtcicegatheringstate-enum - // enum RTCIceGatheringState { - // "new", - // "gathering", - // "complete" - // }; - string; + 'new', + 'gathering', + 'complete' } -interface RTCIceConnectionState { +// TODO(1) +declare enum RTCIceConnectionState { // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCIceConnectionState - // enum RTCIceConnectionState { - // "new", - // "checking", - // "connected", - // "completed", - // "failed", - // "disconnected", - // "closed" - // }; - string; + 'new', + 'checking', + 'connected', + 'completed', + 'failed', + 'disconnected', + 'closed' } -interface RTCSignalingState { - // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCSignalingState - // enum RTCSignalingState { - // "stable", - // "have-local-offer", - // "have-remote-offer", - // "have-local-pranswer", - // "have-remote-pranswer", - // "closed" - // }; - string; +// TODO(1) +declare enum RTCSignalingState { + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCSignalingState + 'stable', + 'have-local-offer', + 'have-remote-offer', + 'have-local-pranswer', + 'have-remote-pranswer', + 'closed' } interface RTCPeerConnection { - createOffer(successCallback: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback, constraints?: MediaConstraints): void; - createAnswer(successCallback: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback, constraints?: MediaConstraints): void; - setLocalDescription(description: RTCSessionDescription, successCallback?: RTCVoidCallback, failureCallback?: RTCPeerConnectionErrorCallback): void; + createOffer(successCallback: RTCSessionDescriptionCallback, + failureCallback?: RTCPeerConnectionErrorCallback, + constraints?: MediaConstraints): void; + createAnswer(successCallback: RTCSessionDescriptionCallback, + failureCallback?: RTCPeerConnectionErrorCallback, + constraints?: MediaConstraints): void; + setLocalDescription(description: RTCSessionDescription, + successCallback?: RTCVoidCallback, + failureCallback?: RTCPeerConnectionErrorCallback): void; localDescription: RTCSessionDescription; - setRemoteDescription(description: RTCSessionDescription, successCallback?: RTCVoidCallback, failureCallback?: RTCPeerConnectionErrorCallback): void; + setRemoteDescription(description: RTCSessionDescription, + successCallback?: RTCVoidCallback, + failureCallback?: RTCPeerConnectionErrorCallback): void; remoteDescription: RTCSessionDescription; - signalingState: string; // RTCSignalingState; see TODO(3) - updateIce(configuration?: RTCConfiguration, constraints?: MediaConstraints): void; + signalingState: string; // RTCSignalingState; see TODO(1) + updateIce(configuration?: RTCConfiguration, + constraints?: MediaConstraints): void; addIceCandidate(candidate: RTCIceCandidate): void; - iceGatheringState: string; // RTCIceGatheringState; see TODO(3) - iceConnectionState: string; // RTCIceConnectionState; see TODO(3) + iceGatheringState: string; // RTCIceGatheringState; see TODO(1) + iceConnectionState: string; // RTCIceConnectionState; see TODO(1) getLocalStreams(): MediaStream[]; getRemoteStreams(): MediaStream[]; - createDataChannel(label?: string, dataChannelDict?: RTCDataChannelInit): RTCDataChannel; + createDataChannel(label?: string, + dataChannelDict?: RTCDataChannelInit): RTCDataChannel; ondatachannel: (event: Event) => void; addStream(stream: MediaStream, constraints?: MediaConstraints): void; removeStream(stream: MediaStream): void; @@ -254,7 +254,8 @@ interface RTCPeerConnection { } declare var RTCPeerConnection: { prototype: RTCPeerConnection; - new (configuration: RTCConfiguration, constraints?: MediaConstraints): RTCPeerConnection; + new (configuration: RTCConfiguration, + constraints?: MediaConstraints): RTCPeerConnection; } interface RTCIceCandidate { @@ -264,7 +265,7 @@ interface RTCIceCandidate { } declare var RTCIceCandidate: { prototype: RTCIceCandidate; - new (candidateInitDict?: RTCIceCandidate); + new (candidateInitDict?: RTCIceCandidate): RTCIceCandidate; } interface RTCIceCandidateInit { From 51dd52165b78ac063c9ab129be9aecc21bf8a036 Mon Sep 17 00:00:00 2001 From: Stuart Moore Date: Tue, 1 Jul 2014 17:31:44 +0100 Subject: [PATCH 043/324] Corrected the microsoft-ajax PageLoadingEventArgs class. Note that although the documentation sometimes incorrectly refers to get_panelsDeleted() - e.g. on http://msdn.microsoft.com/en-us/library/bb397684%28v=vs.100%29.aspx - the actual function is get_panelsDeleting() - see http://msdn.microsoft.com/en-us/library/bb310960%28v=vs.100%29.aspx --- microsoft-ajax/microsoft.ajax-tests.ts | 2 +- microsoft-ajax/microsoft.ajax.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/microsoft-ajax/microsoft.ajax-tests.ts b/microsoft-ajax/microsoft.ajax-tests.ts index 763c1e7fb..7544b1c9f 100644 --- a/microsoft-ajax/microsoft.ajax-tests.ts +++ b/microsoft-ajax/microsoft.ajax-tests.ts @@ -660,7 +660,7 @@ function Sys_WebForms_PageRequestManager_Tests() { } var pageLoadingRequestHandler = (sender: any, args: Sys.WebForms.PageLoadingEventArgs) => { var dataItems: any = args.get_dataItems(); - var panelsDeleted: HTMLDivElement[] = args.get_panelsDeleted(); + var panelsDeleted: HTMLDivElement[] = args.get_panelsDeleting(); var panelsUpdating = args.get_panelsUpdating(); var empty: Sys.EventArgs = args.Empty; } diff --git a/microsoft-ajax/microsoft.ajax.d.ts b/microsoft-ajax/microsoft.ajax.d.ts index 1c8968f44..513488bd1 100644 --- a/microsoft-ajax/microsoft.ajax.d.ts +++ b/microsoft-ajax/microsoft.ajax.d.ts @@ -3829,7 +3829,7 @@ declare module Sys { * The pageLoading event of the Sys.WebForms.PageRequestManager class uses a PageLoadingEventArgs object to return its event data. * @return An array of
elements that will be deleted from the DOM. If no elements will be deleted, the property returns null. */ - get_panelsDeleted(): HTMLDivElement[]; + get_panelsDeleting(): HTMLDivElement[]; /** * Gets an array of HTML
elements that represent UpdatePanel controls that will be updated in the DOM as a result of the current asynchronous postback. * If the contents of any UpdatePanel controls will be updated as the result of a partial-page update, the panelsUpdating property contains an array that references the corresponding
elements. From e1b2093b33b4b8d2d44af64f85e47cc1997e4c4e Mon Sep 17 00:00:00 2001 From: Steven Date: Tue, 1 Jul 2014 10:33:28 -0700 Subject: [PATCH 044/324] More specific constructor for string or HTMLElement --- dropzone/dropzone.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dropzone/dropzone.d.ts b/dropzone/dropzone.d.ts index c19bcca88..81596d88a 100644 --- a/dropzone/dropzone.d.ts +++ b/dropzone/dropzone.d.ts @@ -54,7 +54,8 @@ interface DropzoneOptions { } declare class Dropzone { - constructor(container: any, options?: DropzoneOptions); + constructor(container: string, options?: DropzoneOptions); + constructor(container: HTMLElement, options?: DropzoneOptions); static autoDiscover: boolean; static options: any; static confirm: (question: string, accepted: () => void, rejected?: () => void) => void; From 1017123fb4f718ab63eedc67df24b92790f983af Mon Sep 17 00:00:00 2001 From: Saftpresse99 Date: Wed, 2 Jul 2014 13:03:37 +0200 Subject: [PATCH 045/324] Update angular-translate.d.ts Fix Bug. registerAvailableLanguageKeys accepts ILanguageKeyAlias object hash, not array of ILanguageKeyAlias --- angular-translate/angular-translate.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts index ce2e28779..6f5c9ca06 100644 --- a/angular-translate/angular-translate.d.ts +++ b/angular-translate/angular-translate.d.ts @@ -86,6 +86,6 @@ declare module ng.translate { usePostCompiling(value: boolean): ITranslateProvider; determinePreferredLanguage(fn?: () => void): ITranslateProvider; registerAvailableLanguageKeys(): string[]; - registerAvailableLanguageKeys(languageKeys: string[], aliases?: ILanguageKeyAlias[]): ITranslateProvider; + registerAvailableLanguageKeys(languageKeys: string[], aliases?: ILanguageKeyAlias): ITranslateProvider; } } From e4ad51734d487fc798b0cc852b76b948661cd3a8 Mon Sep 17 00:00:00 2001 From: Tom Crockett Date: Wed, 2 Jul 2014 15:02:39 -0700 Subject: [PATCH 046/324] Add multi-scale time format method --- d3/d3-tests.ts | 37 +++++++++++++++++++++++++++++++++++++ d3/d3.d.ts | 24 ++++++++++++++++++++++-- 2 files changed, 59 insertions(+), 2 deletions(-) diff --git a/d3/d3-tests.ts b/d3/d3-tests.ts index 1a1acc324..3607dec23 100644 --- a/d3/d3-tests.ts +++ b/d3/d3-tests.ts @@ -2587,4 +2587,41 @@ function extentTest() { d3.extent(["20", 3], (d) => { return d; }); d3.extent([3, "20"], (d) => { return d; }); d3.extent(["3", 20], (d) => { return d; }); +} + +// Tests for d3.time.format.multi +function multiTest() { + var customTimeFormat = d3.time.format.multi([ + [".%L", function(d) { return d.getMilliseconds(); }], + [":%S", function(d) { return d.getSeconds(); }], + ["%I:%M", function(d) { return d.getMinutes(); }], + ["%I %p", function(d) { return d.getHours(); }], + ["%a %d", function(d) { return d.getDay() && d.getDate() != 1; }], + ["%b %d", function(d) { return d.getDate() != 1; }], + ["%B", function(d) { return d.getMonth(); }], + ["%Y", function() { return true; }] + ]); + + var margin = {top: 250, right: 40, bottom: 250, left: 40}, + width = 960 - margin.left - margin.right, + height = 500 - margin.top - margin.bottom; + + var x = d3.time.scale() + .domain([new Date(2012, 0, 1), new Date(2013, 0, 1)]) + .range([0, width]); + + var xAxis = d3.svg.axis() + .scale(x) + .tickFormat(customTimeFormat); + + var svg = d3.select("body").append("svg") + .attr("width", width + margin.left + margin.right) + .attr("height", height + margin.top + margin.bottom) + .append("g") + .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); + + svg.append("g") + .attr("class", "x axis") + .attr("transform", "translate(0," + height + ")") + .call(xAxis); } \ No newline at end of file diff --git a/d3/d3.d.ts b/d3/d3.d.ts index b2f0bf1c9..3ab571b87 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -1003,9 +1003,29 @@ declare module D3 { fridays: Range; saturdays: Range; format: { - + /** + * Constructs a new local time formatter using the given specifier. + */ (specifier: string): TimeFormat; - utc: (specifier: string) => TimeFormat; + /** + * Returns a new multi-resolution time format given the specified array of predicated formats. + */ + multi: (formats: any[][]) => TimeFormat; + + utc: { + /** + * Constructs a new local time formatter using the given specifier. + */ + (specifier: string): TimeFormat; + /** + * Returns a new multi-resolution UTC time format given the specified array of predicated formats. + */ + multi: (formats: any[][]) => TimeFormat; + }; + + /** + * The full ISO 8601 UTC time format: "%Y-%m-%dT%H:%M:%S.%LZ". + */ iso: TimeFormat; }; From 4e3c8af9e0db2d407439516210bbf0be3241c34d Mon Sep 17 00:00:00 2001 From: Tom Crockett Date: Wed, 2 Jul 2014 15:06:15 -0700 Subject: [PATCH 047/324] Add URL to example from which testcase is drawn --- d3/d3-tests.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/d3/d3-tests.ts b/d3/d3-tests.ts index 3607dec23..1a2b5f1c5 100644 --- a/d3/d3-tests.ts +++ b/d3/d3-tests.ts @@ -2590,6 +2590,7 @@ function extentTest() { } // Tests for d3.time.format.multi +// Adopted from http://bl.ocks.org/mbostock/4149176 function multiTest() { var customTimeFormat = d3.time.format.multi([ [".%L", function(d) { return d.getMilliseconds(); }], From 423febb7d5a9a186846f8b83817893a5b16523f3 Mon Sep 17 00:00:00 2001 From: Lior Mualem Date: Mon, 19 May 2014 18:34:02 +0300 Subject: [PATCH 048/324] Added Binary class to mongodb. --- mongodb/mongodb.d.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/mongodb/mongodb.d.ts b/mongodb/mongodb.d.ts index 0805e832a..01b31e538 100644 --- a/mongodb/mongodb.d.ts +++ b/mongodb/mongodb.d.ts @@ -129,6 +129,26 @@ declare module "mongodb" { public static createFromHexString(hexString: string): ObjectID; } + // Class documentation : http://mongodb.github.io/node-mongodb-native/api-bson-generated/binary.html + export class Binary { + constructor (buffer: Buffer, subType?: number); + + // Updates this binary with byte_value + put(byte_value: any): void; + + // Writes a buffer or string to the binary + write(buffer: any, offset: number): void; + + // Reads length bytes starting at position. + read(position: number, length: number): Buffer; + + // Returns the value of this binary as a string. + value(): string; + + // The length of the binary. + length(): number; + } + export interface SocketOptions { //= set seconds before connection times out default:0 timeout?: number; From 150bb126d3e70789d735243dc676a4cc2e71827a Mon Sep 17 00:00:00 2001 From: Lior Mualem Date: Tue, 20 May 2014 08:05:22 +0300 Subject: [PATCH 049/324] Added createIndex and ensureIndex overloads to mongodb.Collection. --- mongodb/mongodb.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/mongodb/mongodb.d.ts b/mongodb/mongodb.d.ts index 01b31e538..05f71d20a 100644 --- a/mongodb/mongodb.d.ts +++ b/mongodb/mongodb.d.ts @@ -302,8 +302,12 @@ declare module "mongodb" { findOne(selector: Object, fields: any, skip: number, limit: number, callback?: (err: Error, result: any) => void): Cursor; findOne(selector: Object, fields: any, skip: number, limit: number, timeout: number, callback?: (err: Error, result: any) => void): Cursor; + createIndex(fieldOrSpec: any, callback: (err: Error, indexName: string) => void): void; createIndex(fieldOrSpec: any, options: IndexOptions, callback: (err: Error, indexName: string) => void): void; + + ensureIndex(fieldOrSpec: any, callback: (err: Error, indexName: string) => void): void; ensureIndex(fieldOrSpec: any, options: IndexOptions, callback: (err: Error, indexName: string) => void): void; + indexInformation(options: any, callback: Function): void; dropIndex(name: string, callback: Function): void; dropAllIndexes(callback: Function): void; From 842e595c53447ccf07a965a95e43377f6f8c7ca8 Mon Sep 17 00:00:00 2001 From: Renzo Slijp Date: Thu, 3 Jul 2014 11:34:14 +0200 Subject: [PATCH 050/324] Changed generic type of IHttpPromiseCallback for error callback to allow for difrent return type. It's likely that the error return type is different from the regular result type --- angularjs/angular.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index e2de2a0b0..368e638e3 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -820,7 +820,7 @@ declare module ng { interface IHttpPromise extends IPromise { success(callback: IHttpPromiseCallback): IHttpPromise; - error(callback: IHttpPromiseCallback): IHttpPromise; + error(callback: IHttpPromiseCallback): IHttpPromise; then(successCallback: (response: IHttpPromiseCallbackArg) => IPromise, errorCallback?: (response: IHttpPromiseCallbackArg) => any): IPromise; then(successCallback: (response: IHttpPromiseCallbackArg) => TResult, errorCallback?: (response: IHttpPromiseCallbackArg) => any): IPromise; } From ce9e9dc11a75a384aa5ca7dfd81c87f06fafc3d3 Mon Sep 17 00:00:00 2001 From: Tim Klingeleers Date: Thu, 3 Jul 2014 12:08:26 +0200 Subject: [PATCH 051/324] Update jquery.address.d.ts Added the complete jQuery address API to the definition file. Reordered them to be consistent with the documentation (http://www.asual.com/jquery/address/docs/) and included the same documentation in the code (for use with Visual Studio for example). Also fixed the existing methods where return types in the definition file were incorrect. For example: method chaining was not supported. --- jquery.address/jquery.address.d.ts | 168 +++++++++++++++++++++++++++-- 1 file changed, 157 insertions(+), 11 deletions(-) diff --git a/jquery.address/jquery.address.d.ts b/jquery.address/jquery.address.d.ts index 09d76cb0c..be745fbe4 100644 --- a/jquery.address/jquery.address.d.ts +++ b/jquery.address/jquery.address.d.ts @@ -1,27 +1,173 @@ // Type definitions for jQuery.Address 1.5 // Project: https://github.com/asual/jquery-address -// Definitions by: Martin Duparc +// Definitions by: Martin Duparc and Tim Klingeleers // Definitions: https://github.com/borisyankov/DefinitelyTyped/ /// interface JQueryAddressStatic { (); - change(callback: any): void; - value(url: any): void; - update(): void; - path(): string; - path(value: string): void; - internalChange(eventhandler: Function): void; - externalChange(eventhandler: Function): void; - parameter(name: string, value?: string): string; - value(): string; - history(value: boolean): void; + /** + * Binds any supported event type to a function with support for an optional map of data. + */ + bind(type: any, data: any, callback: Function): JQueryAddressStatic; + /** + * Binds a function to be executed whenever the address is changed. + * The function receives a single event object parameter that contains the following properties: + * value, path, pathNames, parameterNames, parameters and queryString. + */ + change(callback: Function): JQueryAddressStatic; + /** + * Binds a function to be executed once when the address is initiated. + * The function receives a single event object parameter that contains the following properties: + * value, path, pathNames, parameterNames, parameters and queryString. + */ + init(callback: Function): JQueryAddressStatic; + /** + * Binds a function to be executed when the address is changed from inside the page that uses the plugin. + * The function receives a single event object parameter that contains the following properties: + * value, path, pathNames, parameterNames, parameters and queryString. + */ + internalChange(eventhandler: Function): JQueryAddressStatic; + /** + * Binds a function to be executed when the address is changed from the browser usually when entering the page or using the back and forward buttons. + * The function receives a single event object parameter that contains the following properties: + * value, path, pathNames, parameterNames, parameters and queryString. + */ + externalChange(eventhandler: Function): JQueryAddressStatic; + /** + * Provides the base address of the document. + */ baseURL(): string; + /** + * Provides the state of the auto update mode. Enabled by default. + */ + autoUpdate(): boolean; + /** + * Enables or disables the auto update mode which can be turned off when multiple parameters values have to be changed at once. + */ + autoUpdate(value: boolean): JQueryAddressStatic; + /** + * Provides the state of the crawling mode. Disables by default. + */ + crawlable(): boolean; + /** + * Enables or disables the crawling mode which will automatically convert the values into a Google Ajax Crawling friendly format. + */ + crawlable(value: boolean): JQueryAddressStatic; + /** + * Provides the hash fragment part of the deep linking value. + */ + hash(): string; + /** + * Sets the hash fragment part of the deep linking value. + */ + hash(value: string): JQueryAddressStatic; + /** + * Provides the state of the history mode setting. Enabled by default. + */ + history(): boolean; + /** + * Enables or disables the history mode which generated entries in the browser history. + */ + history(value: boolean): void; + /** + * Provides the value of a specific query parameter. + */ + parameter(name: string): string; + /** + * Sets a query parameter value. Appending is disabled by default but can be enabled for array values. + */ + parameter(name: string, value: string, append: boolean): JQueryAddressStatic; + /** + * Provides a list of all the query parameter names. + */ + parameterNames(): Array; + /** + * Provides the deep linking value without the query string and the hash fragment. + */ + path(): string; + /** + * Sets the deep linking value without the query string and the hash fragment. + */ + path(value: string): JQueryAddressStatic; + /** + * Provides a list of all the folders in the deep linking path. + */ + pathNames(): Array; + /** + * Provides the query string part of the deep linking value. + */ + queryString(): string; + /** + * Sets the query string part of the deep linking value. + */ + queryString(value: string): JQueryAddressStatic; + /** + * Provides the value used as a base path for the HTML5 state management. + */ + state(): string; + /** + * Sets the base path of the website that is utilized in HTML5 state management. + */ + state(value: string): JQueryAddressStatic; + /** + * Provides the state of the strict mode setting. Enabled by default. + */ + strict(): boolean; + /** + * Enables or disables the strict mode which automatically appends a slash in the beginning of the deep linking value. + */ + strict(value: boolean): JQueryAddressStatic; + /** + * Provides the title of the HTML document. + */ + title(): string; + /** + * Sets the title of the HTML document. + */ + title(value: string): JQueryAddressStatic; + /** + * Provides the currently set page view tracking function. + */ + tracker(): any; + /** + * Sets a function for page view tracking. Google Analytics tracking is automatically invoked if it exists in the page. + */ + tracker(value: Function): JQueryAddressStatic; + /** + * Provides the current deep linking value. + */ + value(): string; + /** + * Sets the current deep linking value. + */ + value(url: string): JQueryAddressStatic; + /** + * Updates the value when auto updating is disabled. + */ + update(): JQueryAddressStatic; + /** + * Provides the state of the wrap mode. Disabled by default. + */ + wrap(): boolean; + /** + * Enables or disables the wrap mode which generates a DIV wrapper around the page content and fixes any scroll issues caused by the use of hash fragments. + */ + wrap(value: boolean): JQueryAddressStatic; } interface JQueryAddress { + /** + * Adds the plugin functionality to a DOM element and disables the default behavior. Designed primarily to support links and forms. + * Accepts an optional function parameter that allows custom processing of the deep link value. + */ (): JQuery; + /** + * Adds the plugin functionality to a DOM element and disables the default behavior. Designed primarily to support links and forms. + * Accepts an optional function parameter that allows custom processing of the deep link value. + */ + (fn: Function): JQuery; } interface JQueryStatic { From ccd9a6b4d9d98f5da01642e57d699160be0a6cf7 Mon Sep 17 00:00:00 2001 From: Tim Klingeleers Date: Thu, 3 Jul 2014 12:09:58 +0200 Subject: [PATCH 052/324] Update CONTRIBUTORS.md --- CONTRIBUTORS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 42cdffabe..c645bca65 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -133,7 +133,7 @@ All definitions files include a header with the author and editors, so at some p * [jQuery](http://jquery.com/) (from TypeScript samples) * [jQuery Mobile](http://jquerymobile.com) (by [Boris Yankov](https://github.com/borisyankov)) * [jQuery UI](http://jqueryui.com/) (by [Boris Yankov](https://github.com/borisyankov)) -* [jQuery.Address](https://github.com/asual/jquery-address) (by [Martin Duparc](https://github.com/martinduparc/)) +* [jQuery.Address](https://github.com/asual/jquery-address) (by [Martin Duparc](https://github.com/martinduparc/) and [Tim Klingeleers](https://github.com/mardaneus86/)) * [jQuery.areYouSure](https://github.com/codedance/jquery.AreYouSure) (by [Jon Egerton](https://github.com/jonegerton)) * [jQuery.autosize](http://www.jacklmoore.com/autosize/) (by [Jack Moore](http://www.jacklmoore.com/)) * [jQuery.BBQ](http://benalman.com/projects/jquery-bbq-plugin/) (by [Adam R. Smith](https://github.com/sunetos)) From cf4c8b193a0261d3ca898274fc27d6c6719ecbe2 Mon Sep 17 00:00:00 2001 From: Tim Klingeleers Date: Thu, 3 Jul 2014 12:21:52 +0200 Subject: [PATCH 053/324] Update jquery.address.d.ts CI seems to fail because of header format --- jquery.address/jquery.address.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jquery.address/jquery.address.d.ts b/jquery.address/jquery.address.d.ts index be745fbe4..43a666e3e 100644 --- a/jquery.address/jquery.address.d.ts +++ b/jquery.address/jquery.address.d.ts @@ -1,6 +1,6 @@ // Type definitions for jQuery.Address 1.5 // Project: https://github.com/asual/jquery-address -// Definitions by: Martin Duparc and Tim Klingeleers +// Definitions by: Martin Duparc , Tim Klingeleers // Definitions: https://github.com/borisyankov/DefinitelyTyped/ /// From 4e1c39e76e7dd1ae3eef1b07163eac0e88be7d0c Mon Sep 17 00:00:00 2001 From: Renzo Slijp Date: Thu, 3 Jul 2014 15:47:51 +0200 Subject: [PATCH 054/324] Changed generic type of IHttpPromiseCallback for error callback in then chaining --- angularjs/angular.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 368e638e3..11763d608 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -821,8 +821,8 @@ declare module ng { interface IHttpPromise extends IPromise { success(callback: IHttpPromiseCallback): IHttpPromise; error(callback: IHttpPromiseCallback): IHttpPromise; - then(successCallback: (response: IHttpPromiseCallbackArg) => IPromise, errorCallback?: (response: IHttpPromiseCallbackArg) => any): IPromise; - then(successCallback: (response: IHttpPromiseCallbackArg) => TResult, errorCallback?: (response: IHttpPromiseCallbackArg) => any): IPromise; + then(successCallback: (response: IHttpPromiseCallbackArg) => IPromise, errorCallback?: (response: IHttpPromiseCallbackArg) => any): IPromise; + then(successCallback: (response: IHttpPromiseCallbackArg) => TResult, errorCallback?: (response: IHttpPromiseCallbackArg) => any): IPromise; } interface IHttpProvider extends IServiceProvider { From 180f50f89ffc88732b7dda722177f38f776ac2a0 Mon Sep 17 00:00:00 2001 From: "killalau1988@hotmail.com" Date: Thu, 3 Jul 2014 22:45:39 +0800 Subject: [PATCH 055/324] Add missing API for underscore Add utility function unescape() --- underscore/underscore.d.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/underscore/underscore.d.ts b/underscore/underscore.d.ts index c9c699326..5b64aceb1 100644 --- a/underscore/underscore.d.ts +++ b/underscore/underscore.d.ts @@ -1442,6 +1442,13 @@ interface UnderscoreStatic { **/ escape(str: string): string; + /** + * The opposite of escape, replaces &, <, >, ", and ' with their unescaped counterparts. + * @param str HTML escaped string. + * @return `str` Raw string. + **/ + unescape(str: string): string; + /** * If the value of the named property is a function then invoke it; otherwise, return it. * @param object Object to maybe invoke function `property` on. @@ -2283,6 +2290,12 @@ interface Underscore { **/ escape(): string; + /** + * Wrapped type `string`. + * @see _.unescape + **/ + unescape(): string; + /** * Wrapped type `object`. * @see _.result @@ -3106,6 +3119,12 @@ interface _Chain { **/ escape(): _Chain; + /** + * Wrapped type `string`. + * @see _.unescape + **/ + unescape(): _Chain; + /** * Wrapped type `object`. * @see _.result From d4ab82b0130814af61f2d8b7ce260d38849dff2a Mon Sep 17 00:00:00 2001 From: "killalau1988@hotmail.com" Date: Thu, 3 Jul 2014 22:45:39 +0800 Subject: [PATCH 056/324] Add missing API for underscore Add utility function unescape() --- underscore/underscore.d.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/underscore/underscore.d.ts b/underscore/underscore.d.ts index c9c699326..5b64aceb1 100644 --- a/underscore/underscore.d.ts +++ b/underscore/underscore.d.ts @@ -1442,6 +1442,13 @@ interface UnderscoreStatic { **/ escape(str: string): string; + /** + * The opposite of escape, replaces &, <, >, ", and ' with their unescaped counterparts. + * @param str HTML escaped string. + * @return `str` Raw string. + **/ + unescape(str: string): string; + /** * If the value of the named property is a function then invoke it; otherwise, return it. * @param object Object to maybe invoke function `property` on. @@ -2283,6 +2290,12 @@ interface Underscore { **/ escape(): string; + /** + * Wrapped type `string`. + * @see _.unescape + **/ + unescape(): string; + /** * Wrapped type `object`. * @see _.result @@ -3106,6 +3119,12 @@ interface _Chain { **/ escape(): _Chain; + /** + * Wrapped type `string`. + * @see _.unescape + **/ + unescape(): _Chain; + /** * Wrapped type `object`. * @see _.result From a44c7d653b04b19477181c62fa80e6c823060ee0 Mon Sep 17 00:00:00 2001 From: Kenneth Kouot Date: Thu, 3 Jul 2014 13:45:42 -0700 Subject: [PATCH 057/324] ember-RSVP Add typing for Ember.RSVP.Promise constructor --- ember/ember.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/ember/ember.d.ts b/ember/ember.d.ts index 40d2f9859..03bce98f7 100644 --- a/ember/ember.d.ts +++ b/ember/ember.d.ts @@ -1501,6 +1501,7 @@ declare module Ember { } module RSVP { class Promise { + constructor(resolver: Function, label?: string); then(done?: Function, fail?: Function): Promise; } } From 8e49b8e8c8ee4b197c2f4e972716227d253b11b4 Mon Sep 17 00:00:00 2001 From: Kenneth Kouot Date: Thu, 3 Jul 2014 13:50:55 -0700 Subject: [PATCH 058/324] Add tests for Ember.RSVP.Promise from Ember docs --- ember/ember-tests.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/ember/ember-tests.ts b/ember/ember-tests.ts index 254e1682c..39e960e00 100644 --- a/ember/ember-tests.ts +++ b/ember/ember-tests.ts @@ -193,3 +193,18 @@ people2.some((person: Em.Object) => { }); people2.everyProperty('isHappy', true); people2.someProperty('isHappy', true); + +// Examples taken from http://emberjs.com/api/classes/Ember.RSVP.Promise.html +var promise = new Ember.RSVP.Promise(function(resolve, reject) { + // on success + resolve('ok!'); + + // on failure + reject('no-k!'); +}); + +promise.then(function(value) { + // on fulfillment +}, function(reason) { + // on rejection +}); From 290d4da01002f6bf10cb74f9d9e482d70e02c368 Mon Sep 17 00:00:00 2001 From: Kenneth Kouot Date: Thu, 3 Jul 2014 13:53:34 -0700 Subject: [PATCH 059/324] tabs to spaces --- ember/ember.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ember/ember.d.ts b/ember/ember.d.ts index 03bce98f7..bbb555e8a 100644 --- a/ember/ember.d.ts +++ b/ember/ember.d.ts @@ -1501,7 +1501,7 @@ declare module Ember { } module RSVP { class Promise { - constructor(resolver: Function, label?: string); + constructor(resolver: Function, label?: string); then(done?: Function, fail?: Function): Promise; } } From b395e7ec1971dd1cf5a1c3b78ddb2ce081a989e6 Mon Sep 17 00:00:00 2001 From: Georgie Date: Thu, 3 Jul 2014 16:48:56 -0700 Subject: [PATCH 060/324] Remove redundant type --- google.visualization/google.visualization.d.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/google.visualization/google.visualization.d.ts b/google.visualization/google.visualization.d.ts index 38a08ef55..11a1f780c 100644 --- a/google.visualization/google.visualization.d.ts +++ b/google.visualization/google.visualization.d.ts @@ -270,6 +270,7 @@ declare module google { direction?: number; // The direction in which the values along the horizontal axis grow. Specify -1 to reverse the order of the values. format?: string; // icu pattern set http://icu-project.org/apiref/icu4c/classDecimalFormat.html#_details gridlines?: ChartGridlines; + minorGridlines?: ChartGridlines; logScale?: boolean; textPosition?: string; textStyle?: ChartTextStyle; @@ -292,12 +293,6 @@ declare module google { export interface ChartGridlines { color?: string; count?: number; - minorGridlines?: ChartMinorGridlines; - } - - export interface ChartMinorGridlines { - color?: string; - count?: number; } export interface ChartViewWindow { From 845070d832d016c6c74bbbbdda4019c2f1cf05d2 Mon Sep 17 00:00:00 2001 From: TessenR Date: Fri, 4 Jul 2014 16:00:31 +0400 Subject: [PATCH 061/324] Field name fix According to official documentation correct name is bServerSide doc: http://datatables.net/docs/DataTables/1.9.0/DataTable.models.oSettings.oFeatures.html --- jquery.dataTables/jquery.dataTables.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jquery.dataTables/jquery.dataTables.d.ts b/jquery.dataTables/jquery.dataTables.d.ts index d9524cf01..9884b78e2 100755 --- a/jquery.dataTables/jquery.dataTables.d.ts +++ b/jquery.dataTables/jquery.dataTables.d.ts @@ -343,7 +343,7 @@ declare module DataTables bLengthChange: boolean; bPaginate: boolean; bProcessing: boolean; - bServerSize: boolean; + bServerSide: boolean; bSort: boolean; bSortClasses: boolean; bStateSave: boolean; From 66799b44294558c2ae627e4c2f88b6508844d355 Mon Sep 17 00:00:00 2001 From: Mariusz Kierski Date: Fri, 4 Jul 2014 15:08:04 +0200 Subject: [PATCH 062/324] Fixed chai bindings so that now they work with CommonJS; added tests --- chai/chai-assert.d.ts | 4 ---- chai/chai.d.ts | 4 ++++ 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/chai/chai-assert.d.ts b/chai/chai-assert.d.ts index 0790cb17f..30ae2deb7 100644 --- a/chai/chai-assert.d.ts +++ b/chai/chai-assert.d.ts @@ -129,7 +129,3 @@ declare module chai { //browser global declare var assert:chai.Assert; - -declare module 'chai' { -export = chai; -} diff --git a/chai/chai.d.ts b/chai/chai.d.ts index 54d5770c9..058d55196 100644 --- a/chai/chai.d.ts +++ b/chai/chai.d.ts @@ -162,3 +162,7 @@ declare module chai { (constructor: Function, expected?: RegExp, message?: string): Expect; } } + +declare module "chai" { + export = chai; +} From df6f0353d0fdc6c7a1b2aefe41c3d49fc2a3e369 Mon Sep 17 00:00:00 2001 From: Lucas Dixon Date: Fri, 4 Jul 2014 15:15:29 -0400 Subject: [PATCH 063/324] standardized tabs & spaces --- webrtc/MediaStream-tests.ts | 44 +++--- webrtc/MediaStream.d.ts | 160 +++++++++---------- webrtc/RTCPeerConnection-tests.ts | 40 ++--- webrtc/RTCPeerConnection.d.ts | 254 +++++++++++++++--------------- 4 files changed, 249 insertions(+), 249 deletions(-) diff --git a/webrtc/MediaStream-tests.ts b/webrtc/MediaStream-tests.ts index 4dcde91fe..14c2fab7c 100644 --- a/webrtc/MediaStream-tests.ts +++ b/webrtc/MediaStream-tests.ts @@ -6,27 +6,27 @@ var mediaTrackConstraintArray: MediaTrackConstraint[] = []; var mediaTrackConstraints: MediaTrackConstraints = { mandatory: mediaTrackConstraintSet, optional: mediaTrackConstraintArray } navigator.getUserMedia(mediaStreamConstraints, - stream => { - console.log('label:' + stream.label); - console.log('ended:' + stream.ended); - stream.onended = (event:Event) => console.log('Stream ended'); - var objectUrl = URL.createObjectURL(stream); - var wkObjectUrl = webkitURL.createObjectURL(stream); - }, - error => { - console.log('Error message: ' + error.message); - console.log('Error name: ' + error.name); - }); + stream => { + console.log('label:' + stream.label); + console.log('ended:' + stream.ended); + stream.onended = (event:Event) => console.log('Stream ended'); + var objectUrl = URL.createObjectURL(stream); + var wkObjectUrl = webkitURL.createObjectURL(stream); + }, + error => { + console.log('Error message: ' + error.message); + console.log('Error name: ' + error.name); + }); navigator.webkitGetUserMedia(mediaStreamConstraints, - stream => { - console.log('label:' + stream.label); - console.log('ended:' + stream.ended); - stream.onended = (event:Event) => console.log('Stream ended'); - var objectUrl = URL.createObjectURL(stream); - var wkObjectUrl = webkitURL.createObjectURL(stream); - }, - error => { - console.log('Error message: ' + error.message); - console.log('Error name: ' + error.name); - }); + stream => { + console.log('label:' + stream.label); + console.log('ended:' + stream.ended); + stream.onended = (event:Event) => console.log('Stream ended'); + var objectUrl = URL.createObjectURL(stream); + var wkObjectUrl = webkitURL.createObjectURL(stream); + }, + error => { + console.log('Error message: ' + error.message); + console.log('Error name: ' + error.name); + }); diff --git a/webrtc/MediaStream.d.ts b/webrtc/MediaStream.d.ts index 12e0a253a..e159dff29 100644 --- a/webrtc/MediaStream.d.ts +++ b/webrtc/MediaStream.d.ts @@ -6,158 +6,158 @@ // Taken from http://dev.w3.org/2011/webrtc/editor/getusermedia.html interface MediaStreamConstraints { - audio: any; - video: any; + audio: any; + video: any; } declare var MediaStreamConstraints: { - prototype: MediaStreamConstraints; - new (): MediaStreamConstraints; + prototype: MediaStreamConstraints; + new (): MediaStreamConstraints; } interface MediaTrackConstraints { - mandatory: MediaTrackConstraintSet; - optional: MediaTrackConstraint[]; + mandatory: MediaTrackConstraintSet; + optional: MediaTrackConstraint[]; } declare var MediaTrackConstraints: { - prototype: MediaTrackConstraints; - new (): MediaTrackConstraints; + prototype: MediaTrackConstraints; + new (): MediaTrackConstraints; } // ks - Not defined in the source doc. interface MediaTrackConstraintSet { } declare var MediaTrackConstraintSet: { - prototype: MediaTrackConstraintSet; - new (): MediaTrackConstraintSet; + prototype: MediaTrackConstraintSet; + new (): MediaTrackConstraintSet; } // ks - Not defined in the source doc. interface MediaTrackConstraint { } declare var MediaTrackConstraint: { - prototype: MediaTrackConstraint; - new (): MediaTrackConstraints; + prototype: MediaTrackConstraint; + new (): MediaTrackConstraints; } interface Navigator { - getUserMedia(constraints: MediaStreamConstraints, - successCallback: (stream: any) => void, - errorCallback: (error: Error) => void) : void; - webkitGetUserMedia(constraints: MediaStreamConstraints, - successCallback: (stream: any) => void, - errorCallback: (error: Error) => void): void; + getUserMedia(constraints: MediaStreamConstraints, + successCallback: (stream: any) => void, + errorCallback: (error: Error) => void) : void; + webkitGetUserMedia(constraints: MediaStreamConstraints, + successCallback: (stream: any) => void, + errorCallback: (error: Error) => void): void; } interface EventHandler { (event: Event): void; } interface NavigatorUserMediaSuccessCallback { - (stream: LocalMediaStream): void; + (stream: LocalMediaStream): void; } interface NavigatorUserMediaError { - PERMISSION_DENIED: number; // = 1; - code: number; + PERMISSION_DENIED: number; // = 1; + code: number; } declare var NavigatorUserMediaError: { - prototype: NavigatorUserMediaError; - new (): NavigatorUserMediaError; - PERMISSION_DENIED: number; // = 1; + prototype: NavigatorUserMediaError; + new (): NavigatorUserMediaError; + PERMISSION_DENIED: number; // = 1; } interface NavigatorUserMediaErrorCallback { - (error: NavigatorUserMediaError): void; + (error: NavigatorUserMediaError): void; } interface MediaStreamTrackList { - length: number; - item: MediaStreamTrack; - add(track: MediaStreamTrack): void; - remove(track: MediaStreamTrack): void; - onaddtrack: (event: Event) => void; - onremovetrack: (event: Event) => void; + length: number; + item: MediaStreamTrack; + add(track: MediaStreamTrack): void; + remove(track: MediaStreamTrack): void; + onaddtrack: (event: Event) => void; + onremovetrack: (event: Event) => void; } declare var MediaStreamTrackList: { - prototype: MediaStreamTrackList; - new (): MediaStreamTrackList; + prototype: MediaStreamTrackList; + new (): MediaStreamTrackList; } declare var webkitMediaStreamTrackList: { - prototype: MediaStreamTrackList; - new (): MediaStreamTrackList; + prototype: MediaStreamTrackList; + new (): MediaStreamTrackList; } interface MediaStream { - label: string; - id: string; - getAudioTracks(): MediaStreamTrackList; - getVideoTracks(): MediaStreamTrackList; - ended: boolean; - onended: (event: Event) => void; + label: string; + id: string; + getAudioTracks(): MediaStreamTrackList; + getVideoTracks(): MediaStreamTrackList; + ended: boolean; + onended: (event: Event) => void; } declare var MediaStream: { - prototype: MediaStream; - new (): MediaStream; - new (trackContainers: MediaStream[]): MediaStream; - new (trackContainers: MediaStreamTrackList[]): MediaStream; - new (trackContainers: MediaStreamTrack[]): MediaStream; + prototype: MediaStream; + new (): MediaStream; + new (trackContainers: MediaStream[]): MediaStream; + new (trackContainers: MediaStreamTrackList[]): MediaStream; + new (trackContainers: MediaStreamTrack[]): MediaStream; } declare var webkitMediaStream: { - prototype: MediaStream; - new (): MediaStream; - new (trackContainers: MediaStream[]): MediaStream; - new (trackContainers: MediaStreamTrackList[]): MediaStream; - new (trackContainers: MediaStreamTrack[]): MediaStream; + prototype: MediaStream; + new (): MediaStream; + new (trackContainers: MediaStream[]): MediaStream; + new (trackContainers: MediaStreamTrackList[]): MediaStream; + new (trackContainers: MediaStreamTrack[]): MediaStream; } // an - not defined in source doc. interface SourceInfo { - label: string; - id: string; - kind: string; - facing: string; + label: string; + id: string; + kind: string; + facing: string; } declare var SourceInfo: { - prototype: SourceInfo; + prototype: SourceInfo; } interface LocalMediaStream extends MediaStream { - stop(): void; + stop(): void; } interface MediaStreamTrack { - kind: string; - label: string; - enabled: boolean; - LIVE: number; // = 0; - MUTED: number; // = 1; - ENDED: number; // = 2; - readyState: number; - onmute: (event: Event) => void; - onunmute: (event: Event) => void; - onended: (event: Event) => void; + kind: string; + label: string; + enabled: boolean; + LIVE: number; // = 0; + MUTED: number; // = 1; + ENDED: number; // = 2; + readyState: number; + onmute: (event: Event) => void; + onunmute: (event: Event) => void; + onended: (event: Event) => void; } declare var MediaStreamTrack: { - prototype: MediaStreamTrack; - new (): MediaStreamTrack; - LIVE: number; // = 0; - MUTED: number; // = 1; - ENDED: number; // = 2; - getSources: (callback: (sources: SourceInfo[]) => void) => void; + prototype: MediaStreamTrack; + new (): MediaStreamTrack; + LIVE: number; // = 0; + MUTED: number; // = 1; + ENDED: number; // = 2; + getSources: (callback: (sources: SourceInfo[]) => void) => void; } interface streamURL extends URL { - createObjectURL(stream: MediaStream): string; + createObjectURL(stream: MediaStream): string; } //declare var URL: { -// prototype: MediaStreamTrack; -// new (): URL; -// createObjectURL(stream: MediaStream): string; +// prototype: MediaStreamTrack; +// new (): URL; +// createObjectURL(stream: MediaStream): string; //} interface WebkitURL extends streamURL { } declare var webkitURL: { - prototype: WebkitURL; - new (): streamURL; - createObjectURL(stream: MediaStream): string; + prototype: WebkitURL; + new (): streamURL; + createObjectURL(stream: MediaStream): string; } diff --git a/webrtc/RTCPeerConnection-tests.ts b/webrtc/RTCPeerConnection-tests.ts index d85728c5c..3b35efad5 100644 --- a/webrtc/RTCPeerConnection-tests.ts +++ b/webrtc/RTCPeerConnection-tests.ts @@ -7,13 +7,13 @@ var constraints: MediaConstraints = { mandatory: { OfferToReceiveAudio: true, Of var peerConnection: RTCPeerConnection = new RTCPeerConnection(config, constraints); navigator.getUserMedia({ audio: true, video: true }, - stream => { - peerConnection.addStream(stream); - }, - error => { - console.log('Error message: ' + error.message); - console.log('Error name: ' + error.name); - }); + stream => { + peerConnection.addStream(stream); + }, + error => { + console.log('Error message: ' + error.message); + console.log('Error name: ' + error.name); + }); peerConnection.onaddstream = ev => console.log(ev.type); peerConnection.ondatachannel = ev => console.log(ev.type); @@ -25,25 +25,25 @@ peerConnection.onremovestream = ev => console.log(ev.type); peerConnection.onstatechange = ev => console.log(ev.type); peerConnection.createOffer( - offer => { - peerConnection.setLocalDescription(offer, - () => console.log("set local description"), - error => console.log("Error setting local description: " + error)); - }, - error => console.log("Error creating offer: " + error)); + offer => { + peerConnection.setLocalDescription(offer, + () => console.log("set local description"), + error => console.log("Error setting local description: " + error)); + }, + error => console.log("Error creating offer: " + error)); var type: string = RTCSdpType[RTCSdpType.offer]; var offer: RTCSessionDescriptionInit = { type: type, sdp: "some sdp" }; var sessionDescription = new RTCSessionDescription(offer); peerConnection.setRemoteDescription(sessionDescription, () => { - peerConnection.createAnswer( - answer => { - peerConnection.setLocalDescription(answer, - () => console.log('Set local description'), - error => console.log("Error setting local description from created answer: " + error + "; answer.sdp=" + answer.sdp)); - }, - error => console.log("Error creating answer: " + error)); + peerConnection.createAnswer( + answer => { + peerConnection.setLocalDescription(answer, + () => console.log('Set local description'), + error => console.log("Error setting local description from created answer: " + error + "; answer.sdp=" + answer.sdp)); + }, + error => console.log("Error creating answer: " + error)); }, error => console.log('Error setting remote description: ' + error + "; offer.sdp=" + offer.sdp)); diff --git a/webrtc/RTCPeerConnection.d.ts b/webrtc/RTCPeerConnection.d.ts index e123b69bd..bc2c6205d 100644 --- a/webrtc/RTCPeerConnection.d.ts +++ b/webrtc/RTCPeerConnection.d.ts @@ -21,78 +21,78 @@ // https://typescript.codeplex.com/workitem/1364 interface RTCConfiguration { - iceServers: RTCIceServer[]; + iceServers: RTCIceServer[]; } declare var RTCConfiguration: { - prototype: RTCConfiguration; - new (): RTCConfiguration; + prototype: RTCConfiguration; + new (): RTCConfiguration; } interface RTCIceServer { - url: string; - credential?: string; + url: string; + credential?: string; } declare var RTCIceServer: { - prototype: RTCIceServer; - new (): RTCIceServer; + prototype: RTCIceServer; + new (): RTCIceServer; } // moz (Firefox) specific prefixes. interface mozRTCPeerConnection extends RTCPeerConnection { } declare var mozRTCPeerConnection: { - prototype: mozRTCPeerConnection; - new (settings: RTCPeerConnectionConfig, - constraints?:MediaConstraints): mozRTCPeerConnection; + prototype: mozRTCPeerConnection; + new (settings: RTCPeerConnectionConfig, + constraints?:MediaConstraints): mozRTCPeerConnection; } // webkit (Chrome) specific prefixes. interface webkitRTCPeerConnection extends RTCPeerConnection { } declare var webkitRTCPeerConnection: { - prototype: webkitRTCPeerConnection; - new (settings: RTCPeerConnectionConfig, - constraints?:MediaConstraints): webkitRTCPeerConnection; + prototype: webkitRTCPeerConnection; + new (settings: RTCPeerConnectionConfig, + constraints?:MediaConstraints): webkitRTCPeerConnection; } // For Chrome, look at the code here: // https://code.google.com/p/chromium/codesearch#chromium/src/third_party/libjingle/source/talk/app/webrtc/webrtcsession.cc&sq=package:chromium&dr=C&l=63 interface OptionalMediaConstraint { - // When true, will use DTLS/SCTP data channels - DtlsSrtpKeyAgreement?: boolean; - // When true will use Rtp-based data channels (depreicated) - RtpDataChannels?: boolean; + // When true, will use DTLS/SCTP data channels + DtlsSrtpKeyAgreement?: boolean; + // When true will use Rtp-based data channels (depreicated) + RtpDataChannels?: boolean; } // ks 12/20/12 - There's more here that doesn't seem to be documented very well yet. // http://www.w3.org/TR/2013/WD-webrtc-20130910/ interface MediaConstraints { - mandatory?: MediaOfferConstraints; - optional?: OptionalMediaConstraint[] + mandatory?: MediaOfferConstraints; + optional?: OptionalMediaConstraint[] } interface MediaOfferConstraints { - OfferToReceiveAudio: boolean; - OfferToReceiveVideo: boolean; + OfferToReceiveAudio: boolean; + OfferToReceiveVideo: boolean; } interface RTCSessionDescriptionInit { - type: string; // RTCSdpType; See TODO(1) - sdp: string; + type: string; // RTCSdpType; See TODO(1) + sdp: string; } interface RTCSessionDescription { - type?: string; // RTCSdpType; See TODO(1) - sdp?: string; + type?: string; // RTCSdpType; See TODO(1) + sdp?: string; } declare var RTCSessionDescription: { - prototype: RTCSessionDescription; - new (descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; - // TODO: Add serializer. - // See: http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCSdpType) + prototype: RTCSessionDescription; + new (descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; + // TODO: Add serializer. + // See: http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCSdpType) } interface RTCDataChannelInit { - ordered ?: boolean; // messages must be sent in-order. + ordered ?: boolean; // messages must be sent in-order. maxPacketLifeTime ?: number; // unsigned short maxRetransmits ?: number; // unsigned short protocol ?: string; // default = '' @@ -109,89 +109,89 @@ declare enum RTCSdpType { } interface RTCMessageEvent { - // http://dev.w3.org/2011/webrtc/editor/webrtc.html#event-datachannel-message - // At present, this can be an: ArrayBuffer, a string, or a Blob. - // See TODO(2) - data: any; + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#event-datachannel-message + // At present, this can be an: ArrayBuffer, a string, or a Blob. + // See TODO(2) + data: any; } // TODO(1) declare enum RTCDataChannelState { - // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCDataChannelState - 'connecting', - 'open', - 'closing', - 'closed' + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCDataChannelState + 'connecting', + 'open', + 'closing', + 'closed' } interface RTCDataChannel extends EventTarget { - label: string; - reliable: boolean; - readyState: string; // RTCDataChannelState; see TODO(1) - bufferedAmount: number; - binaryType: string; + label: string; + reliable: boolean; + readyState: string; // RTCDataChannelState; see TODO(1) + bufferedAmount: number; + binaryType: string; - onopen: (event: Event) => void; - onerror: (event: Event) => void; - onclose: (event: Event) => void; - onmessage: (event: RTCMessageEvent) => void; + onopen: (event: Event) => void; + onerror: (event: Event) => void; + onclose: (event: Event) => void; + onmessage: (event: RTCMessageEvent) => void; - close(): void; + close(): void; - send(data: string): void ; - send(data: ArrayBuffer): void; - send(data: ArrayBufferView): void; - send(data: Blob): void; + send(data: string): void ; + send(data: ArrayBuffer): void; + send(data: ArrayBufferView): void; + send(data: Blob): void; } declare var RTCDataChannel: { - prototype: RTCDataChannel; - new (): RTCDataChannel; + prototype: RTCDataChannel; + new (): RTCDataChannel; } interface RTCDataChannelEvent extends Event { - channel: RTCDataChannel; + channel: RTCDataChannel; } declare var RTCDataChannelEvent: { - prototype: RTCDataChannelEvent; - new (eventInitDict: RTCDataChannelEventInit): RTCDataChannelEvent; + prototype: RTCDataChannelEvent; + new (eventInitDict: RTCDataChannelEventInit): RTCDataChannelEvent; } interface RTCIceCandidateEvent extends Event { - candidate: RTCIceCandidate; + candidate: RTCIceCandidate; } interface RTCMediaStreamEvent extends Event { - stream: MediaStream; + stream: MediaStream; } interface EventInit { } interface RTCDataChannelEventInit extends EventInit { - channel: RTCDataChannel; + channel: RTCDataChannel; } interface RTCVoidCallback { - (): void; + (): void; } interface RTCSessionDescriptionCallback { - (sdp: RTCSessionDescription): void; + (sdp: RTCSessionDescription): void; } interface RTCPeerConnectionErrorCallback { - (errorInformation: DOMError): void; + (errorInformation: DOMError): void; } // TODO(1) declare enum RTCIceGatheringState { - // http://dev.w3.org/2011/webrtc/editor/webrtc.html#rtcicegatheringstate-enum - 'new', - 'gathering', - 'complete' + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#rtcicegatheringstate-enum + 'new', + 'gathering', + 'complete' } // TODO(1) declare enum RTCIceConnectionState { - // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCIceConnectionState + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCIceConnectionState 'new', 'checking', 'connected', @@ -213,84 +213,84 @@ declare enum RTCSignalingState { } interface RTCPeerConnection { - createOffer(successCallback: RTCSessionDescriptionCallback, - failureCallback?: RTCPeerConnectionErrorCallback, - constraints?: MediaConstraints): void; - createAnswer(successCallback: RTCSessionDescriptionCallback, - failureCallback?: RTCPeerConnectionErrorCallback, - constraints?: MediaConstraints): void; - setLocalDescription(description: RTCSessionDescription, - successCallback?: RTCVoidCallback, - failureCallback?: RTCPeerConnectionErrorCallback): void; - localDescription: RTCSessionDescription; - setRemoteDescription(description: RTCSessionDescription, - successCallback?: RTCVoidCallback, - failureCallback?: RTCPeerConnectionErrorCallback): void; - remoteDescription: RTCSessionDescription; - signalingState: string; // RTCSignalingState; see TODO(1) - updateIce(configuration?: RTCConfiguration, - constraints?: MediaConstraints): void; - addIceCandidate(candidate: RTCIceCandidate): void; - iceGatheringState: string; // RTCIceGatheringState; see TODO(1) - iceConnectionState: string; // RTCIceConnectionState; see TODO(1) - getLocalStreams(): MediaStream[]; - getRemoteStreams(): MediaStream[]; - createDataChannel(label?: string, - dataChannelDict?: RTCDataChannelInit): RTCDataChannel; - ondatachannel: (event: Event) => void; - addStream(stream: MediaStream, constraints?: MediaConstraints): void; - removeStream(stream: MediaStream): void; - close(): void; - onnegotiationneeded: (event: Event) => void; - onconnecting: (event: Event) => void; - onopen: (event: Event) => void; - onaddstream: (event: RTCMediaStreamEvent) => void; - onremovestream: (event: RTCMediaStreamEvent) => void; - onstatechange: (event: Event) => void; - onicechange: (event: Event) => void; - onicecandidate: (event: RTCIceCandidateEvent) => void; - onidentityresult: (event: Event) => void; - onsignalingstatechange: (event: Event) => void; + createOffer(successCallback: RTCSessionDescriptionCallback, + failureCallback?: RTCPeerConnectionErrorCallback, + constraints?: MediaConstraints): void; + createAnswer(successCallback: RTCSessionDescriptionCallback, + failureCallback?: RTCPeerConnectionErrorCallback, + constraints?: MediaConstraints): void; + setLocalDescription(description: RTCSessionDescription, + successCallback?: RTCVoidCallback, + failureCallback?: RTCPeerConnectionErrorCallback): void; + localDescription: RTCSessionDescription; + setRemoteDescription(description: RTCSessionDescription, + successCallback?: RTCVoidCallback, + failureCallback?: RTCPeerConnectionErrorCallback): void; + remoteDescription: RTCSessionDescription; + signalingState: string; // RTCSignalingState; see TODO(1) + updateIce(configuration?: RTCConfiguration, + constraints?: MediaConstraints): void; + addIceCandidate(candidate: RTCIceCandidate): void; + iceGatheringState: string; // RTCIceGatheringState; see TODO(1) + iceConnectionState: string; // RTCIceConnectionState; see TODO(1) + getLocalStreams(): MediaStream[]; + getRemoteStreams(): MediaStream[]; + createDataChannel(label?: string, + dataChannelDict?: RTCDataChannelInit): RTCDataChannel; + ondatachannel: (event: Event) => void; + addStream(stream: MediaStream, constraints?: MediaConstraints): void; + removeStream(stream: MediaStream): void; + close(): void; + onnegotiationneeded: (event: Event) => void; + onconnecting: (event: Event) => void; + onopen: (event: Event) => void; + onaddstream: (event: RTCMediaStreamEvent) => void; + onremovestream: (event: RTCMediaStreamEvent) => void; + onstatechange: (event: Event) => void; + onicechange: (event: Event) => void; + onicecandidate: (event: RTCIceCandidateEvent) => void; + onidentityresult: (event: Event) => void; + onsignalingstatechange: (event: Event) => void; } declare var RTCPeerConnection: { - prototype: RTCPeerConnection; - new (configuration: RTCConfiguration, - constraints?: MediaConstraints): RTCPeerConnection; + prototype: RTCPeerConnection; + new (configuration: RTCConfiguration, + constraints?: MediaConstraints): RTCPeerConnection; } interface RTCIceCandidate { - candidate?: string; - sdpMid?: string; - sdpMLineIndex?: number; + candidate?: string; + sdpMid?: string; + sdpMLineIndex?: number; } declare var RTCIceCandidate: { - prototype: RTCIceCandidate; - new (candidateInitDict?: RTCIceCandidate): RTCIceCandidate; + prototype: RTCIceCandidate; + new (candidateInitDict?: RTCIceCandidate): RTCIceCandidate; } interface RTCIceCandidateInit { - candidate: string; - sdpMid: string; - sdpMLineIndex: number; + candidate: string; + sdpMid: string; + sdpMLineIndex: number; } declare var RTCIceCandidateInit:{ - prototype: RTCIceCandidateInit; - new (): RTCIceCandidateInit; + prototype: RTCIceCandidateInit; + new (): RTCIceCandidateInit; } interface PeerConnectionIceEvent { - peer: RTCPeerConnection; - candidate: RTCIceCandidate; + peer: RTCPeerConnection; + candidate: RTCIceCandidate; } declare var PeerConnectionIceEvent: { - prototype: PeerConnectionIceEvent; - new (): PeerConnectionIceEvent; + prototype: PeerConnectionIceEvent; + new (): PeerConnectionIceEvent; } interface RTCPeerConnectionConfig { - iceServers: RTCIceServer[]; + iceServers: RTCIceServer[]; } declare var RTCPeerConnectionConfig: { - prototype: RTCPeerConnectionConfig; - new (): RTCPeerConnectionConfig; + prototype: RTCPeerConnectionConfig; + new (): RTCPeerConnectionConfig; } From d0cbf02b269c680d6affb2c28ecddaf4e724cf8c Mon Sep 17 00:00:00 2001 From: Lucas Dixon Date: Fri, 4 Jul 2014 18:13:39 -0400 Subject: [PATCH 064/324] made RTC prefix standard for all interfaces --- webrtc/RTCPeerConnection-tests.ts | 19 +++++++++++++------ webrtc/RTCPeerConnection.d.ts | 24 ++++++++++++------------ 2 files changed, 25 insertions(+), 18 deletions(-) diff --git a/webrtc/RTCPeerConnection-tests.ts b/webrtc/RTCPeerConnection-tests.ts index 3b35efad5..0b05fcdd8 100644 --- a/webrtc/RTCPeerConnection-tests.ts +++ b/webrtc/RTCPeerConnection-tests.ts @@ -1,10 +1,13 @@ /// /// -var config: RTCConfiguration = { iceServers: [{ url: "stun.l.google.com:19302" }] }; -var constraints: MediaConstraints = { mandatory: { OfferToReceiveAudio: true, OfferToReceiveVideo: true } }; +var config: RTCConfiguration = + { iceServers: [{ url: "stun.l.google.com:19302" }] }; +var constraints: RTCMediaConstraints = + { mandatory: { OfferToReceiveAudio: true, OfferToReceiveVideo: true } }; -var peerConnection: RTCPeerConnection = new RTCPeerConnection(config, constraints); +var peerConnection: RTCPeerConnection = + new RTCPeerConnection(config, constraints); navigator.getUserMedia({ audio: true, video: true }, stream => { @@ -41,11 +44,15 @@ peerConnection.setRemoteDescription(sessionDescription, () => { answer => { peerConnection.setLocalDescription(answer, () => console.log('Set local description'), - error => console.log("Error setting local description from created answer: " + error + "; answer.sdp=" + answer.sdp)); + error => console.log( + "Error setting local description from created answer: " + error + + "; answer.sdp=" + answer.sdp)); }, error => console.log("Error creating answer: " + error)); }, -error => console.log('Error setting remote description: ' + error + "; offer.sdp=" + offer.sdp)); +error => console.log('Error setting remote description: ' + error + + "; offer.sdp=" + offer.sdp)); -var wkPeerConnection: webkitRTCPeerConnection = new webkitRTCPeerConnection(config, constraints); +var wkPeerConnection: webkitRTCPeerConnection = + new webkitRTCPeerConnection(config, constraints); diff --git a/webrtc/RTCPeerConnection.d.ts b/webrtc/RTCPeerConnection.d.ts index bc2c6205d..e0e75ad61 100644 --- a/webrtc/RTCPeerConnection.d.ts +++ b/webrtc/RTCPeerConnection.d.ts @@ -43,7 +43,7 @@ interface mozRTCPeerConnection extends RTCPeerConnection { declare var mozRTCPeerConnection: { prototype: mozRTCPeerConnection; new (settings: RTCPeerConnectionConfig, - constraints?:MediaConstraints): mozRTCPeerConnection; + constraints?:RTCMediaConstraints): mozRTCPeerConnection; } // webkit (Chrome) specific prefixes. interface webkitRTCPeerConnection extends RTCPeerConnection { @@ -51,12 +51,12 @@ interface webkitRTCPeerConnection extends RTCPeerConnection { declare var webkitRTCPeerConnection: { prototype: webkitRTCPeerConnection; new (settings: RTCPeerConnectionConfig, - constraints?:MediaConstraints): webkitRTCPeerConnection; + constraints?:RTCMediaConstraints): webkitRTCPeerConnection; } // For Chrome, look at the code here: // https://code.google.com/p/chromium/codesearch#chromium/src/third_party/libjingle/source/talk/app/webrtc/webrtcsession.cc&sq=package:chromium&dr=C&l=63 -interface OptionalMediaConstraint { +interface RTCOptionalMediaConstraint { // When true, will use DTLS/SCTP data channels DtlsSrtpKeyAgreement?: boolean; // When true will use Rtp-based data channels (depreicated) @@ -65,12 +65,12 @@ interface OptionalMediaConstraint { // ks 12/20/12 - There's more here that doesn't seem to be documented very well yet. // http://www.w3.org/TR/2013/WD-webrtc-20130910/ -interface MediaConstraints { - mandatory?: MediaOfferConstraints; - optional?: OptionalMediaConstraint[] +interface RTCMediaConstraints { + mandatory?: RTCMediaOfferConstraints; + optional?: RTCOptionalMediaConstraint[] } -interface MediaOfferConstraints { +interface RTCMediaOfferConstraints { OfferToReceiveAudio: boolean; OfferToReceiveVideo: boolean; } @@ -215,10 +215,10 @@ declare enum RTCSignalingState { interface RTCPeerConnection { createOffer(successCallback: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback, - constraints?: MediaConstraints): void; + constraints?: RTCMediaConstraints): void; createAnswer(successCallback: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback, - constraints?: MediaConstraints): void; + constraints?: RTCMediaConstraints): void; setLocalDescription(description: RTCSessionDescription, successCallback?: RTCVoidCallback, failureCallback?: RTCPeerConnectionErrorCallback): void; @@ -229,7 +229,7 @@ interface RTCPeerConnection { remoteDescription: RTCSessionDescription; signalingState: string; // RTCSignalingState; see TODO(1) updateIce(configuration?: RTCConfiguration, - constraints?: MediaConstraints): void; + constraints?: RTCMediaConstraints): void; addIceCandidate(candidate: RTCIceCandidate): void; iceGatheringState: string; // RTCIceGatheringState; see TODO(1) iceConnectionState: string; // RTCIceConnectionState; see TODO(1) @@ -238,7 +238,7 @@ interface RTCPeerConnection { createDataChannel(label?: string, dataChannelDict?: RTCDataChannelInit): RTCDataChannel; ondatachannel: (event: Event) => void; - addStream(stream: MediaStream, constraints?: MediaConstraints): void; + addStream(stream: MediaStream, constraints?: RTCMediaConstraints): void; removeStream(stream: MediaStream): void; close(): void; onnegotiationneeded: (event: Event) => void; @@ -255,7 +255,7 @@ interface RTCPeerConnection { declare var RTCPeerConnection: { prototype: RTCPeerConnection; new (configuration: RTCConfiguration, - constraints?: MediaConstraints): RTCPeerConnection; + constraints?: RTCMediaConstraints): RTCPeerConnection; } interface RTCIceCandidate { From c8015453b5836157aef4efff1c7471372297ace2 Mon Sep 17 00:00:00 2001 From: Basarat Ali Syed Date: Sat, 5 Jul 2014 21:06:34 +1000 Subject: [PATCH 065/324] Update es6-promises.d.ts --- es6-promises/es6-promises.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/es6-promises/es6-promises.d.ts b/es6-promises/es6-promises.d.ts index 34ee4fae2..632276822 100644 --- a/es6-promises/es6-promises.d.ts +++ b/es6-promises/es6-promises.d.ts @@ -1,5 +1,5 @@ -// Type definitions for es6-promises -// Project: https://github.com/jakearchibald/ES6-Promises +// Type definitions for es6-promise +// Project: https://github.com/jakearchibald/ES6-Promise // Definitions by: François de Campredon // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -132,10 +132,10 @@ declare module Promise { function race(promises: Promise[]): Promise; } -declare module 'es6-promises' { +declare module 'es6-promise' { var foo: typeof Promise; // Temp variable to reference Promise in local context module rsvp { export var Promise: typeof foo; } export = rsvp; -} \ No newline at end of file +} From eeea727f5a2c927c7c52db3ae4229dd1a3b59869 Mon Sep 17 00:00:00 2001 From: Basarat Ali Syed Date: Sat, 5 Jul 2014 21:06:52 +1000 Subject: [PATCH 066/324] Update es6-promises-commonjs-tests.ts --- es6-promises/es6-promises-commonjs-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es6-promises/es6-promises-commonjs-tests.ts b/es6-promises/es6-promises-commonjs-tests.ts index 70e35c594..688dd3c2f 100644 --- a/es6-promises/es6-promises-commonjs-tests.ts +++ b/es6-promises/es6-promises-commonjs-tests.ts @@ -1,6 +1,6 @@ /// -import rsvp = require('es6-promises'); +import rsvp = require('es6-promise'); var Promise = rsvp.Promise; var promiseString: Promise, From ceda8851c9c0b3cff4c50a871f4c2b26ae033ad5 Mon Sep 17 00:00:00 2001 From: basarat Date: Sat, 5 Jul 2014 21:11:49 +1000 Subject: [PATCH 067/324] chore(es6-promise) rename files/folder to match the npm name --- .../es6-promise-commonjs-tests.ts | 2 +- .../es6-promises-tests.ts => es6-promise/es6-promise-tests.ts | 2 +- es6-promises/es6-promises.d.ts => es6-promise/es6-promise.d.ts | 0 3 files changed, 2 insertions(+), 2 deletions(-) rename es6-promises/es6-promises-commonjs-tests.ts => es6-promise/es6-promise-commonjs-tests.ts (99%) rename es6-promises/es6-promises-tests.ts => es6-promise/es6-promise-tests.ts (99%) rename es6-promises/es6-promises.d.ts => es6-promise/es6-promise.d.ts (100%) diff --git a/es6-promises/es6-promises-commonjs-tests.ts b/es6-promise/es6-promise-commonjs-tests.ts similarity index 99% rename from es6-promises/es6-promises-commonjs-tests.ts rename to es6-promise/es6-promise-commonjs-tests.ts index 688dd3c2f..4bcb4d057 100644 --- a/es6-promises/es6-promises-commonjs-tests.ts +++ b/es6-promise/es6-promise-commonjs-tests.ts @@ -1,4 +1,4 @@ -/// +/// import rsvp = require('es6-promise'); var Promise = rsvp.Promise; diff --git a/es6-promises/es6-promises-tests.ts b/es6-promise/es6-promise-tests.ts similarity index 99% rename from es6-promises/es6-promises-tests.ts rename to es6-promise/es6-promise-tests.ts index 774d3763e..549527372 100644 --- a/es6-promises/es6-promises-tests.ts +++ b/es6-promise/es6-promise-tests.ts @@ -1,4 +1,4 @@ -/// +/// var promiseString: Promise, diff --git a/es6-promises/es6-promises.d.ts b/es6-promise/es6-promise.d.ts similarity index 100% rename from es6-promises/es6-promises.d.ts rename to es6-promise/es6-promise.d.ts From c532d8da2bf656d3de7277a6001c6cc7695b0196 Mon Sep 17 00:00:00 2001 From: basarat Date: Sat, 5 Jul 2014 21:15:43 +1000 Subject: [PATCH 068/324] fix tests --- promises-a-plus/promises-a-plus-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/promises-a-plus/promises-a-plus-tests.ts b/promises-a-plus/promises-a-plus-tests.ts index 29ca0989b..042c4f066 100644 --- a/promises-a-plus/promises-a-plus-tests.ts +++ b/promises-a-plus/promises-a-plus-tests.ts @@ -1,6 +1,6 @@ /// /// -/// +/// /// import When = require("../when/when"); From 95cc23ad611e0ec722e59833ae5b8ec79ffabd13 Mon Sep 17 00:00:00 2001 From: basarat Date: Sat, 5 Jul 2014 21:37:34 +1000 Subject: [PATCH 069/324] chore(es6-promise) re-enable es6-promises def temporarily while people update --- es6-promises/es6-promises-tests.ts | 10 ++++++++++ es6-promises/es6-promises.d.ts | 9 +++++++++ 2 files changed, 19 insertions(+) create mode 100644 es6-promises/es6-promises-tests.ts create mode 100644 es6-promises/es6-promises.d.ts diff --git a/es6-promises/es6-promises-tests.ts b/es6-promises/es6-promises-tests.ts new file mode 100644 index 000000000..465b3045c --- /dev/null +++ b/es6-promises/es6-promises-tests.ts @@ -0,0 +1,10 @@ +/// + +// This is a makeshift definition because the project was renamed to es6-promise +// This file may be deleted at some point. Please use es6-promise package in future projects +// This test simply makes sure that the reference from es6-promises -> es6-promise works fine + +// constructor test +var constructResult = new Promise((resolve, reject) => { + resolve('a string'); +}); diff --git a/es6-promises/es6-promises.d.ts b/es6-promises/es6-promises.d.ts new file mode 100644 index 000000000..682bdb0de --- /dev/null +++ b/es6-promises/es6-promises.d.ts @@ -0,0 +1,9 @@ +// Type definitions for es6-promise +// Project: https://github.com/jakearchibald/ES6-Promise +// Definitions by: François de Campredon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +// This is a makeshift definition because the project was renamed to es6-promise +// This file may be deleted at some point. Please use es6-promise package in future projects \ No newline at end of file From 935d511133fbfecf9f7b0a62235051bacd41584d Mon Sep 17 00:00:00 2001 From: Luke Forder Date: Sat, 5 Jul 2014 15:01:12 +0200 Subject: [PATCH 070/324] added definitions for ngprogress-lite --- ngprogress-lite/ngprogress-lite-tests.ts | 30 ++++++++++++++++++++++++ ngprogress-lite/ngprogress-lite.d.ts | 28 ++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 ngprogress-lite/ngprogress-lite-tests.ts create mode 100644 ngprogress-lite/ngprogress-lite.d.ts diff --git a/ngprogress-lite/ngprogress-lite-tests.ts b/ngprogress-lite/ngprogress-lite-tests.ts new file mode 100644 index 000000000..a6d68f08f --- /dev/null +++ b/ngprogress-lite/ngprogress-lite-tests.ts @@ -0,0 +1,30 @@ +/// +/// + +var app = angular.module('testApp', ['ngProgressLite']); + +app.config( + ['ngProgressLiteProvider', + (ngProgressLiteProvider: ng.progressLite.INgProgressLiteProvider) => { + ngProgressLiteProvider.settings.ease = 'ease'; + ngProgressLiteProvider.settings.minimum = 0.08, + ngProgressLiteProvider.settings.speed = 300; + ngProgressLiteProvider.settings.trickleRate = 0.02; + ngProgressLiteProvider.settings.trickleSpeed = 500; + ngProgressLiteProvider.settings.template = '
'; + } + ]); + +app.controller('testCtrl', ($scope: ng.IScope, ngProgressLite : ng.progressLite.INgProgressLite) => { + + ngProgressLite.set(0.4); + + ngProgressLite.get(); + + ngProgressLite.inc(); + ngProgressLite.inc(0.1); + + ngProgressLite.start(); + + ngProgressLite.done(); +}); \ No newline at end of file diff --git a/ngprogress-lite/ngprogress-lite.d.ts b/ngprogress-lite/ngprogress-lite.d.ts new file mode 100644 index 000000000..bdee71673 --- /dev/null +++ b/ngprogress-lite/ngprogress-lite.d.ts @@ -0,0 +1,28 @@ +// Type definitions for ngprogress-lite +// Project: https://github.com/voronianski/ngprogress-lite +// Definitions by: Luke Forder +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module ng.progressLite { + + export interface INgProgressLite { + set(num: number): INgProgressLite; + get(): number; + start(): INgProgressLite; + inc(amount?: number): INgProgressLite; + done(): void; + } + + export interface IConfigurationOptions { + minimum: number; + speed: number; + ease: string; + trickleRate: number; + trickleSpeed: number; + template: string; + } + + export interface INgProgressLiteProvider { + settings: IConfigurationOptions; + } +} \ No newline at end of file From f8f170dd81835096e774886a353a823711d273e3 Mon Sep 17 00:00:00 2001 From: tarh Date: Sat, 5 Jul 2014 14:23:33 +0100 Subject: [PATCH 071/324] Uniform naming parameters --- es6-promise/es6-promise.d.ts | 202 +++++++++++++++++------------------ 1 file changed, 98 insertions(+), 104 deletions(-) diff --git a/es6-promise/es6-promise.d.ts b/es6-promise/es6-promise.d.ts index 632276822..202d30d29 100644 --- a/es6-promise/es6-promise.d.ts +++ b/es6-promise/es6-promise.d.ts @@ -3,139 +3,133 @@ // Definitions by: François de Campredon // Definitions: https://github.com/borisyankov/DefinitelyTyped - interface Thenable { - then(onFulfilled: (value: R) => Thenable, onRejected: (error: any) => Thenable): Thenable; - then(onFulfilled: (value: R) => Thenable, onRejected?: (error: any) => U): Thenable; - then(onFulfilled: (value: R) => U, onRejected: (error: any) => Thenable): Thenable; - then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): Thenable; - + then(onResolve: (value: R) => Thenable, onReject: (error: any) => Thenable): Thenable; + then(onResolve: (value: R) => Thenable, onReject?: (error: any) => U): Thenable; + then(onResolve: (value: R) => U, onReject: (error: any) => Thenable): Thenable; + then(onResolve?: (value: R) => U, onReject?: (error: any) => U): Thenable; } declare class Promise implements Thenable { - /** - * If you call resolve in the body of the callback passed to the constructor, - * your promise is fulfilled with result object passed to resolve. - * If you call reject your promise is rejected with the object passed to resolve. - * For consistency and debugging (eg stack traces), obj should be an instanceof Error. - * Any errors thrown in the constructor callback will be implicitly passed to reject(). - */ + /** + * If you call resolve in the body of the callback passed to the constructor, + * your promise is fulfilled with result object passed to resolve. + * If you call reject your promise is rejected with the object passed to resolve. + * For consistency and debugging (eg stack traces), obj should be an instanceof Error. + * Any errors thrown in the constructor callback will be implicitly passed to reject(). + */ constructor(callback: (resolve : (result: R) => void, reject: (error: any) => void) => void); - /** - * If you call resolve in the body of the callback passed to the constructor, - * your promise will be fulfilled/rejected with the outcome of thenable passed to resolve. - * If you call reject your promise is rejected with the object passed to resolve. - * For consistency and debugging (eg stack traces), obj should be an instanceof Error. - * Any errors thrown in the constructor callback will be implicitly passed to reject(). - */ - constructor(callback: (resolve : (thenable: Thenable) => void, reject: (error: any) => void) => void); + /** + * If you call resolve in the body of the callback passed to the constructor, + * your promise will be fulfilled/rejected with the outcome of thenable passed to resolve. + * If you call reject your promise is rejected with the object passed to resolve. + * For consistency and debugging (eg stack traces), obj should be an instanceof Error. + * Any errors thrown in the constructor callback will be implicitly passed to reject(). + */ + constructor(callback: (resolve : (result: Thenable) => void, reject: (error: any) => void) => void); + + /** + * onResolve is called when/if "promise" resolves. onReject is called when/if "promise" rejects. + * Both are optional, if either/both are omitted the next onResolve/onReject in the chain is called. + * Both callbacks have a single parameter , the fulfillment value or rejection reason. + * "then" returns a new promise equivalent to the value you return from onResolve/onReject after being passed through Promise.resolve. + * If an error is thrown in the callback, the returned promise rejects with that error. + * + * @param onResolve called when/if "promise" resolves + * @param onReject called when/if "promise" rejects + */ + then(onResolve: (value: R) => Thenable, onReject: (error: any) => Thenable): Promise; + /** + * onResolve is called when/if "promise" resolves. onReject is called when/if "promise" rejects. + * Both are optional, if either/both are omitted the next onResolve/onReject in the chain is called. + * Both callbacks have a single parameter , the fulfillment value or rejection reason. + * "then" returns a new promise equivalent to the value you return from onResolve/onReject after being passed through Promise.resolve. + * If an error is thrown in the callback, the returned promise rejects with that error. + * + * @param onResolve called when/if "promise" resolves + * @param onReject called when/if "promise" rejects + */ + then(onResolve: (value: R) => Thenable, onReject?: (error: any) => U): Promise; + /** + * onResolve is called when/if "promise" resolves. onReject is called when/if "promise" rejects. + * Both are optional, if either/both are omitted the next onResolve/onReject in the chain is called. + * Both callbacks have a single parameter , the fulfillment value or rejection reason. + * "then" returns a new promise equivalent to the value you return from onResolve/onReject after being passed through Promise.resolve. + * If an error is thrown in the callback, the returned promise rejects with that error. + * + * @param onResolve called when/if "promise" resolves + * @param onReject called when/if "promise" rejects + */ + then(onResolve: (value: R) => U, onReject: (error: any) => Thenable): Promise; + /** + * onResolve is called when/if "promise" resolves. onReject is called when/if "promise" rejects. + * Both are optional, if either/both are omitted the next onResolve/onReject in the chain is called. + * Both callbacks have a single parameter , the fulfillment value or rejection reason. + * "then" returns a new promise equivalent to the value you return from onResolve/onReject after being passed through Promise.resolve. + * If an error is thrown in the callback, the returned promise rejects with that error. + * + * @param onResolve called when/if "promise" resolves + * @param onReject called when/if "promise" rejects + */ + then(onResolve?: (value: R) => U, onReject?: (error: any) => U): Promise; - - /** - * onFulFill is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. - * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. - * Both callbacks have a single parameter , the fulfillment value or rejection reason. - * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. - * If an error is thrown in the callback, the returned promise rejects with that error. - * - * @param onFulFill called when/if "promise" resolves - * @param onReject called when/if "promise" rejects - */ - then(onFulfill: (value: R) => Thenable, onReject: (error: any) => Thenable): Promise; - /** - * onFulFill is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. - * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. - * Both callbacks have a single parameter , the fulfillment value or rejection reason. - * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. - * If an error is thrown in the callback, the returned promise rejects with that error. - * - * @param onFulFill called when/if "promise" resolves - * @param onReject called when/if "promise" rejects - */ - then(onFulfill: (value: R) => Thenable, onReject?: (error: any) => U): Promise; - /** - * onFulFill is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. - * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. - * Both callbacks have a single parameter , the fulfillment value or rejection reason. - * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. - * If an error is thrown in the callback, the returned promise rejects with that error. - * - * @param onFulFill called when/if "promise" resolves - * @param onReject called when/if "promise" rejects - */ - then(onFulfill: (value: R) => U, onReject: (error: any) => Thenable): Promise; - /** - * onFulFill is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. - * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. - * Both callbacks have a single parameter , the fulfillment value or rejection reason. - * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. - * If an error is thrown in the callback, the returned promise rejects with that error. - * - * @param onFulFill called when/if "promise" resolves - * @param onReject called when/if "promise" rejects - */ - then(onFulfill?: (value: R) => U, onReject?: (error: any) => U): Promise; - - - /** - * Sugar for promise.then(undefined, onRejected) - * - * @param onReject called when/if "promise" rejects - */ + /** + * Sugar for promise.then(undefined, onReject) + * + * @param onReject called when/if "promise" rejects + */ catch(onReject?: (error: any) => Thenable): Promise; - /** - * Sugar for promise.then(undefined, onRejected) - * - * @param onReject called when/if "promise" rejects - */ + /** + * Sugar for promise.then(undefined, onReject) + * + * @param onReject called when/if "promise" rejects + */ catch(onReject?: (error: any) => U): Promise; } declare module Promise { - /** * Returns promise (only if promise.constructor == Promise) */ function cast(promise: Promise): Promise; - /** + /** * Make a promise that fulfills to obj. */ function cast(object?: R): Promise; - - - /** - * Make a new promise from the thenable. - * A thenable is promise-like in as far as it has a "then" method. - * This also creates a new promise if you pass it a genuine JavaScript promise, making it less efficient for casting than Promise.cast. - */ + + /** + * Make a new promise from the thenable. + * A thenable is promise-like in as far as it has a "then" method. + * This also creates a new promise if you pass it a genuine JavaScript promise, making it less efficient for casting than Promise.cast. + */ function resolve(thenable: Thenable): Promise; - /** - * Make a promise that fulfills to obj. Same as Promise.cast(obj) in this situation. - */ + /** + * Make a promise that fulfills to obj. Same as Promise.cast(obj) in this situation. + */ function resolve(object?: R): Promise; - + /** * Make a promise that rejects to obj. For consistency and debugging (eg stack traces), obj should be an instanceof Error */ function reject(error?: any): Promise; - /** - * Make a promise that fulfills when every item in the array fulfills, and rejects if (and when) any item rejects. - * the array passed to all can be a mixture of promise-like objects and other objects. - * The fulfillment value is an array (in order) of fulfillment values. The rejection value is the first rejection value. - */ + /** + * Make a promise that fulfills when every item in the array fulfills, and rejects if (and when) any item rejects. + * the array passed to all can be a mixture of promise-like objects and other objects. + * The fulfillment value is an array (in order) of fulfillment values. The rejection value is the first rejection value. + */ function all(promises: Promise[]): Promise; - /** - * Make a Promise that fulfills when any item fulfills, and rejects if any item rejects. - */ + /** + * Make a Promise that fulfills when any item fulfills, and rejects if any item rejects. + */ function race(promises: Promise[]): Promise; } declare module 'es6-promise' { - var foo: typeof Promise; // Temp variable to reference Promise in local context - module rsvp { - export var Promise: typeof foo; - } - export = rsvp; + var foo: typeof Promise; // Temp variable to reference Promise in local context + module rsvp { + export var Promise: typeof foo; + } + export = rsvp; } From a685b7db7a80a10d3ffb7575be2e6881d55c0f15 Mon Sep 17 00:00:00 2001 From: tarh Date: Sat, 5 Jul 2014 14:25:56 +0100 Subject: [PATCH 072/324] Works with more use cases --- es6-promise/es6-promise.d.ts | 54 ++++++++++++++++++++++++++++-------- 1 file changed, 42 insertions(+), 12 deletions(-) diff --git a/es6-promise/es6-promise.d.ts b/es6-promise/es6-promise.d.ts index 202d30d29..4e8d27d4d 100644 --- a/es6-promise/es6-promise.d.ts +++ b/es6-promise/es6-promise.d.ts @@ -4,10 +4,12 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped interface Thenable { - then(onResolve: (value: R) => Thenable, onReject: (error: any) => Thenable): Thenable; - then(onResolve: (value: R) => Thenable, onReject?: (error: any) => U): Thenable; - then(onResolve: (value: R) => U, onReject: (error: any) => Thenable): Thenable; + then(onResolve?: (value: R) => Thenable, onReject?: (error: any) => Thenable): Thenable; + then(onResolve?: (value: R) => Thenable, onReject?: (error: any) => U): Thenable; + then(onResolve?: (value: R) => Thenable, onReject?: (error: any) => void): Thenable; + then(onResolve?: (value: R) => U, onReject?: (error: any) => Thenable): Thenable; then(onResolve?: (value: R) => U, onReject?: (error: any) => U): Thenable; + then(onResolve?: (value: R) => U, onReject?: (error: any) => void): Thenable; } declare class Promise implements Thenable { @@ -18,7 +20,7 @@ declare class Promise implements Thenable { * For consistency and debugging (eg stack traces), obj should be an instanceof Error. * Any errors thrown in the constructor callback will be implicitly passed to reject(). */ - constructor(callback: (resolve : (result: R) => void, reject: (error: any) => void) => void); + constructor(callback: (resolve : (result?: R) => void, reject: (error: any) => void) => void); /** * If you call resolve in the body of the callback passed to the constructor, * your promise will be fulfilled/rejected with the outcome of thenable passed to resolve. @@ -26,7 +28,7 @@ declare class Promise implements Thenable { * For consistency and debugging (eg stack traces), obj should be an instanceof Error. * Any errors thrown in the constructor callback will be implicitly passed to reject(). */ - constructor(callback: (resolve : (result: Thenable) => void, reject: (error: any) => void) => void); + constructor(callback: (resolve : (result?: Thenable) => void, reject: (error: any) => void) => void); /** * onResolve is called when/if "promise" resolves. onReject is called when/if "promise" rejects. @@ -38,7 +40,7 @@ declare class Promise implements Thenable { * @param onResolve called when/if "promise" resolves * @param onReject called when/if "promise" rejects */ - then(onResolve: (value: R) => Thenable, onReject: (error: any) => Thenable): Promise; + then(onResolve?: (value: R) => Thenable, onReject?: (error: any) => Thenable): Promise; /** * onResolve is called when/if "promise" resolves. onReject is called when/if "promise" rejects. * Both are optional, if either/both are omitted the next onResolve/onReject in the chain is called. @@ -49,7 +51,18 @@ declare class Promise implements Thenable { * @param onResolve called when/if "promise" resolves * @param onReject called when/if "promise" rejects */ - then(onResolve: (value: R) => Thenable, onReject?: (error: any) => U): Promise; + then(onResolve?: (value: R) => Thenable, onReject?: (error: any) => U): Promise; + /** + * onResolve is called when/if "promise" resolves. onReject is called when/if "promise" rejects. + * Both are optional, if either/both are omitted the next onResolve/onReject in the chain is called. + * Both callbacks have a single parameter , the fulfillment value or rejection reason. + * "then" returns a new promise equivalent to the value you return from onResolve/onReject after being passed through Promise.resolve. + * If an error is thrown in the callback, the returned promise rejects with that error. + * + * @param onResolve called when/if "promise" resolves + * @param onReject called when/if "promise" rejects + */ + then(onResolve?: (value: R) => Thenable, onReject?: (error: any) => void): Promise; /** * onResolve is called when/if "promise" resolves. onReject is called when/if "promise" rejects. * Both are optional, if either/both are omitted the next onResolve/onReject in the chain is called. @@ -60,7 +73,7 @@ declare class Promise implements Thenable { * @param onResolve called when/if "promise" resolves * @param onReject called when/if "promise" rejects */ - then(onResolve: (value: R) => U, onReject: (error: any) => Thenable): Promise; + then(onResolve?: (value: R) => U, onReject?: (error: any) => Thenable): Promise; /** * onResolve is called when/if "promise" resolves. onReject is called when/if "promise" rejects. * Both are optional, if either/both are omitted the next onResolve/onReject in the chain is called. @@ -72,7 +85,18 @@ declare class Promise implements Thenable { * @param onReject called when/if "promise" rejects */ then(onResolve?: (value: R) => U, onReject?: (error: any) => U): Promise; - + /** + * onResolve is called when/if "promise" resolves. onReject is called when/if "promise" rejects. + * Both are optional, if either/both are omitted the next onResolve/onReject in the chain is called. + * Both callbacks have a single parameter , the fulfillment value or rejection reason. + * "then" returns a new promise equivalent to the value you return from onResolve/onReject after being passed through Promise.resolve. + * If an error is thrown in the callback, the returned promise rejects with that error. + * + * @param onResolve called when/if "promise" resolves + * @param onReject called when/if "promise" rejects + */ + then(onResolve?: (value: R) => U, onReject?: (error: any) => void): Promise; + /** * Sugar for promise.then(undefined, onReject) * @@ -85,6 +109,12 @@ declare class Promise implements Thenable { * @param onReject called when/if "promise" rejects */ catch(onReject?: (error: any) => U): Promise; + /** + * Sugar for promise.then(undefined, onReject) + * + * @param onReject called when/if "promise" rejects + */ + catch(onReject?: (error: any) => void): Promise; } declare module Promise { @@ -95,14 +125,14 @@ declare module Promise { /** * Make a promise that fulfills to obj. */ - function cast(object?: R): Promise; + function cast(object: R): Promise; /** * Make a new promise from the thenable. * A thenable is promise-like in as far as it has a "then" method. * This also creates a new promise if you pass it a genuine JavaScript promise, making it less efficient for casting than Promise.cast. */ - function resolve(thenable: Thenable): Promise; + function resolve(thenable?: Thenable): Promise; /** * Make a promise that fulfills to obj. Same as Promise.cast(obj) in this situation. */ @@ -111,7 +141,7 @@ declare module Promise { /** * Make a promise that rejects to obj. For consistency and debugging (eg stack traces), obj should be an instanceof Error */ - function reject(error?: any): Promise; + function reject(error: any): Promise; /** * Make a promise that fulfills when every item in the array fulfills, and rejects if (and when) any item rejects. From 47e1dccd775791c430f8816c82f8df7de378232a Mon Sep 17 00:00:00 2001 From: Lucas Dixon Date: Sat, 5 Jul 2014 19:17:35 -0400 Subject: [PATCH 073/324] added missing getStats --- webrtc/RTCPeerConnection.d.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/webrtc/RTCPeerConnection.d.ts b/webrtc/RTCPeerConnection.d.ts index e0e75ad61..edde45ae0 100644 --- a/webrtc/RTCPeerConnection.d.ts +++ b/webrtc/RTCPeerConnection.d.ts @@ -212,6 +212,17 @@ declare enum RTCSignalingState { 'closed' } +// This is based on the current implementation of WebRtc in Chrome; the spec is +// a little unclear on this. +// http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCStatsReport +interface RTCStatsReport { + stat(id: string): string; +} + +interface RTCStatsCallback { + (report: RTCStatsReport): void; +} + interface RTCPeerConnection { createOffer(successCallback: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback, @@ -251,6 +262,8 @@ interface RTCPeerConnection { onicecandidate: (event: RTCIceCandidateEvent) => void; onidentityresult: (event: Event) => void; onsignalingstatechange: (event: Event) => void; + getStats: (successCallback: RTCStatsCallback, + failureCallback: RTCPeerConnectionErrorCallback) => void; } declare var RTCPeerConnection: { prototype: RTCPeerConnection; From 36a701008e4f9f2e07b3e894936b36f42be5b4cc Mon Sep 17 00:00:00 2001 From: tarh Date: Sun, 6 Jul 2014 08:35:29 +0100 Subject: [PATCH 074/324] Parameter names conform to http://promises-aplus.github.io/promises-spec/ --- es6-promise/es6-promise-tests.ts | 3 + es6-promise/es6-promise.d.ts | 104 +++++++++++++++---------------- 2 files changed, 55 insertions(+), 52 deletions(-) diff --git a/es6-promise/es6-promise-tests.ts b/es6-promise/es6-promise-tests.ts index 549527372..402328eb5 100644 --- a/es6-promise/es6-promise-tests.ts +++ b/es6-promise/es6-promise-tests.ts @@ -74,6 +74,8 @@ promiseNumber = thenWithUndefinedFullFillAndPromiseReject; var thenWithNoResultAndNoReject = promiseString.then(); promiseNumber = thenWithNoResultAndNoReject; +var voidPromise = new Promise(function (resolve) { resolve(); }); + //catch test var catchWithSimpleResult = promiseString.catch(error => 10); promiseNumber = catchWithSimpleResult; @@ -81,6 +83,7 @@ promiseNumber = catchWithSimpleResult; var catchWithPromiseResult = promiseString.catch(error => Promise.resolve(10)); promiseNumber = catchWithPromiseResult; +promiseString = promiseString.catch(function () { throw new Error('Better error msg'); }); //examples coming from http://www.html5rocks.com/en/tutorials/es6/promises/ diff --git a/es6-promise/es6-promise.d.ts b/es6-promise/es6-promise.d.ts index 4e8d27d4d..9bb8d79f2 100644 --- a/es6-promise/es6-promise.d.ts +++ b/es6-promise/es6-promise.d.ts @@ -4,12 +4,12 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped interface Thenable { - then(onResolve?: (value: R) => Thenable, onReject?: (error: any) => Thenable): Thenable; - then(onResolve?: (value: R) => Thenable, onReject?: (error: any) => U): Thenable; - then(onResolve?: (value: R) => Thenable, onReject?: (error: any) => void): Thenable; - then(onResolve?: (value: R) => U, onReject?: (error: any) => Thenable): Thenable; - then(onResolve?: (value: R) => U, onReject?: (error: any) => U): Thenable; - then(onResolve?: (value: R) => U, onReject?: (error: any) => void): Thenable; + then(onFulfilled?: (value: R) => Thenable, onRejected?: (error: any) => Thenable): Thenable; + then(onFulfilled?: (value: R) => Thenable, onRejected?: (error: any) => U): Thenable; + then(onFulfilled?: (value: R) => Thenable, onRejected?: (error: any) => void): Thenable; + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => Thenable): Thenable; + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): Thenable; + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => void): Thenable; } declare class Promise implements Thenable { @@ -28,93 +28,93 @@ declare class Promise implements Thenable { * For consistency and debugging (eg stack traces), obj should be an instanceof Error. * Any errors thrown in the constructor callback will be implicitly passed to reject(). */ - constructor(callback: (resolve : (result?: Thenable) => void, reject: (error: any) => void) => void); + constructor(callback: (resolve : (thenable?: Thenable) => void, reject: (error: any) => void) => void); /** - * onResolve is called when/if "promise" resolves. onReject is called when/if "promise" rejects. - * Both are optional, if either/both are omitted the next onResolve/onReject in the chain is called. + * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. + * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. * Both callbacks have a single parameter , the fulfillment value or rejection reason. - * "then" returns a new promise equivalent to the value you return from onResolve/onReject after being passed through Promise.resolve. + * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. * If an error is thrown in the callback, the returned promise rejects with that error. * - * @param onResolve called when/if "promise" resolves - * @param onReject called when/if "promise" rejects + * @param onFulfilled called when/if "promise" resolves + * @param onRejected called when/if "promise" rejects */ - then(onResolve?: (value: R) => Thenable, onReject?: (error: any) => Thenable): Promise; + then(onFulfilled?: (value: R) => Thenable, onRejected?: (error: any) => Thenable): Promise; /** - * onResolve is called when/if "promise" resolves. onReject is called when/if "promise" rejects. - * Both are optional, if either/both are omitted the next onResolve/onReject in the chain is called. + * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. + * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. * Both callbacks have a single parameter , the fulfillment value or rejection reason. - * "then" returns a new promise equivalent to the value you return from onResolve/onReject after being passed through Promise.resolve. + * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. * If an error is thrown in the callback, the returned promise rejects with that error. * - * @param onResolve called when/if "promise" resolves - * @param onReject called when/if "promise" rejects + * @param onFulfilled called when/if "promise" resolves + * @param onRejected called when/if "promise" rejects */ - then(onResolve?: (value: R) => Thenable, onReject?: (error: any) => U): Promise; + then(onFulfilled?: (value: R) => Thenable, onRejected?: (error: any) => U): Promise; /** - * onResolve is called when/if "promise" resolves. onReject is called when/if "promise" rejects. - * Both are optional, if either/both are omitted the next onResolve/onReject in the chain is called. + * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. + * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. * Both callbacks have a single parameter , the fulfillment value or rejection reason. - * "then" returns a new promise equivalent to the value you return from onResolve/onReject after being passed through Promise.resolve. + * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. * If an error is thrown in the callback, the returned promise rejects with that error. * - * @param onResolve called when/if "promise" resolves - * @param onReject called when/if "promise" rejects + * @param onFulfilled called when/if "promise" resolves + * @param onRejected called when/if "promise" rejects */ - then(onResolve?: (value: R) => Thenable, onReject?: (error: any) => void): Promise; + then(onFulfilled?: (value: R) => Thenable, onRejected?: (error: any) => void): Promise; /** - * onResolve is called when/if "promise" resolves. onReject is called when/if "promise" rejects. - * Both are optional, if either/both are omitted the next onResolve/onReject in the chain is called. + * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. + * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. * Both callbacks have a single parameter , the fulfillment value or rejection reason. - * "then" returns a new promise equivalent to the value you return from onResolve/onReject after being passed through Promise.resolve. + * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. * If an error is thrown in the callback, the returned promise rejects with that error. * - * @param onResolve called when/if "promise" resolves - * @param onReject called when/if "promise" rejects + * @param onFulfilled called when/if "promise" resolves + * @param onRejected called when/if "promise" rejects */ - then(onResolve?: (value: R) => U, onReject?: (error: any) => Thenable): Promise; + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => Thenable): Promise; /** - * onResolve is called when/if "promise" resolves. onReject is called when/if "promise" rejects. - * Both are optional, if either/both are omitted the next onResolve/onReject in the chain is called. + * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. + * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. * Both callbacks have a single parameter , the fulfillment value or rejection reason. - * "then" returns a new promise equivalent to the value you return from onResolve/onReject after being passed through Promise.resolve. + * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. * If an error is thrown in the callback, the returned promise rejects with that error. * - * @param onResolve called when/if "promise" resolves - * @param onReject called when/if "promise" rejects + * @param onFulfilled called when/if "promise" resolves + * @param onRejected called when/if "promise" rejects */ - then(onResolve?: (value: R) => U, onReject?: (error: any) => U): Promise; + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): Promise; /** - * onResolve is called when/if "promise" resolves. onReject is called when/if "promise" rejects. - * Both are optional, if either/both are omitted the next onResolve/onReject in the chain is called. + * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. + * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. * Both callbacks have a single parameter , the fulfillment value or rejection reason. - * "then" returns a new promise equivalent to the value you return from onResolve/onReject after being passed through Promise.resolve. + * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. * If an error is thrown in the callback, the returned promise rejects with that error. * - * @param onResolve called when/if "promise" resolves - * @param onReject called when/if "promise" rejects + * @param onFulfilled called when/if "promise" resolves + * @param onRejected called when/if "promise" rejects */ - then(onResolve?: (value: R) => U, onReject?: (error: any) => void): Promise; + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => void): Promise; /** - * Sugar for promise.then(undefined, onReject) + * Sugar for promise.then(undefined, onRejected) * - * @param onReject called when/if "promise" rejects + * @param onRejected called when/if "promise" rejects */ - catch(onReject?: (error: any) => Thenable): Promise; + catch(onRejected?: (error: any) => Thenable): Promise; /** - * Sugar for promise.then(undefined, onReject) + * Sugar for promise.then(undefined, onRejected) * - * @param onReject called when/if "promise" rejects + * @param onRejected called when/if "promise" rejects */ - catch(onReject?: (error: any) => U): Promise; + catch(onRejected?: (error: any) => U): Promise; /** - * Sugar for promise.then(undefined, onReject) + * Sugar for promise.then(undefined, onRejected) * - * @param onReject called when/if "promise" rejects + * @param onRejected called when/if "promise" rejects */ - catch(onReject?: (error: any) => void): Promise; + catch(onRejected?: (error: any) => void): Promise; } declare module Promise { From 6adad430a16778115b4c4f24acaa5d173284a872 Mon Sep 17 00:00:00 2001 From: Rogier Schouten Date: Mon, 7 Jul 2014 10:07:53 +0200 Subject: [PATCH 075/324] Support for timezonezomplete-1.3.0 --- .../timezonecomplete-1.2.0-tests.ts | 169 ++++ timezonecomplete/timezonecomplete-1.2.0.d.ts | 681 ++++++++++++++ timezonecomplete/timezonecomplete-tests.ts | 5 + timezonecomplete/timezonecomplete.d.ts | 865 +++++++++--------- 4 files changed, 1298 insertions(+), 422 deletions(-) create mode 100644 timezonecomplete/timezonecomplete-1.2.0-tests.ts create mode 100644 timezonecomplete/timezonecomplete-1.2.0.d.ts diff --git a/timezonecomplete/timezonecomplete-1.2.0-tests.ts b/timezonecomplete/timezonecomplete-1.2.0-tests.ts new file mode 100644 index 000000000..03f94e44b --- /dev/null +++ b/timezonecomplete/timezonecomplete-1.2.0-tests.ts @@ -0,0 +1,169 @@ +/// + +import tc = require("timezonecomplete"); + +var b: boolean = tc.isLeapYear(2014); +var n: number = tc.daysInMonth(2014, 10); +var s: string = tc.isoString(2014, 6, 30, 22, 10, 11, 230); + +// DURATION + +var d: tc.Duration; +var d1: tc.Duration = tc.Duration.hours(24); +var d2: tc.Duration = tc.Duration.minutes(24); +var d3: tc.Duration = tc.Duration.seconds(24); +var d4: tc.Duration = tc.Duration.milliseconds(24); +var d5: tc.Duration = new tc.Duration(24); +var d6: tc.Duration = new tc.Duration("00:01"); +var d7: tc.Duration = d6.clone(); + +n = d7.wholeHours(); +n = d7.hours(); +n = d7.minutes(); +n = d7.minute(); +n = d7.seconds(); +n = d7.second(); +n = d7.milliseconds(); +n = d7.millisecond(); +s = d7.sign(); +b = d7.lessThan(d6); +b = d7.greaterThan(d6); +d = d7.min(d6); +d = d7.max(d6); +d = d7.multiply(3); +d = d7.add(d6); +d = d7.sub(d6); +s = d7.toString(); + +// TIMEZONE + +var t: tc.TimeZone; +var k: tc.TimeZoneKind; + +t = tc.TimeZone.local(); +t = tc.TimeZone.utc(); +t = tc.TimeZone.zone(2); +t = tc.TimeZone.zone("+01:00"); +s = t.name(); +k = t.kind(); +b = t.equals(t); +b = t.isUtc(); +n = t.offsetForUtc(2014, 1, 1, 13, 0, 5, 123); +n = t.offsetForZone(2014, 1, 1, 13, 0, 5, 123); +n = t.offsetForUtcDate(new Date(2014, 1, 1, 13, 0, 5, 123), tc.DateFunctions.Get); +n = t.offsetForZoneDate(new Date(2014, 1, 1, 13, 0, 5, 123), tc.DateFunctions.GetUTC); +s = t.toString(); +s = tc.TimeZone.offsetToString(2); +n = tc.TimeZone.stringToOffset("+00:01"); + +// REALTIMESOURCE + +var date: Date = (new tc.RealTimeSource()).now(); + +// DATETIME + +var dt: tc.DateTime; + +var ts: tc.TimeSource = tc.DateTime.timeSource; + +dt = tc.DateTime.nowLocal(); +dt = tc.DateTime.nowUtc(); +dt = tc.DateTime.now(tc.TimeZone.local()); +dt = new tc.DateTime(); +dt = new tc.DateTime("2014-01-01T13:05:01.123 UTC"); +dt = new tc.DateTime("2014-01-01T13:05:01.123", tc.TimeZone.utc()); +dt = new tc.DateTime(date, tc.DateFunctions.Get); +dt = new tc.DateTime(date, tc.DateFunctions.Get, tc.TimeZone.utc()); +dt = new tc.DateTime(2014, 1, 1, 13, 5, 1, 123); +dt = new tc.DateTime(2014, 1, 1, 13, 5, 1, 123, tc.TimeZone.utc()); +dt = new tc.DateTime(89949284); +dt = new tc.DateTime(89949284, tc.TimeZone.utc()); +dt = dt.clone(); +t = dt.zone(); +n = dt.offset(); +n = dt.year(); +n = dt.month(); +n = dt.day(); +n = dt.hour(); +n = dt.minute(); +n = dt.second(); +n = dt.millisecond(); +n = dt.unixUtcMillis(); +n = dt.utcYear(); +n = dt.utcMonth(); +n = dt.utcDay(); +n = dt.utcHour(); +n = dt.utcMinute(); +n = dt.utcSecond(); +n = dt.utcMillisecond(); +dt.convert(tc.TimeZone.local()); +dt = dt.toZone(tc.TimeZone.utc()); +date = dt.toDate(); +dt = dt.add(tc.Duration.seconds(2)); +dt = dt.add(2, tc.TimeUnit.Year); +dt = dt.add(2, tc.TimeUnit.Month); +dt = dt.add(2, tc.TimeUnit.Week); +dt = dt.add(2, tc.TimeUnit.Day); +dt = dt.add(2, tc.TimeUnit.Hour); +dt = dt.add(2, tc.TimeUnit.Minute); +dt = dt.add(2, tc.TimeUnit.Second); +dt = dt.addLocal(2, tc.TimeUnit.Second); +dt = dt.sub(tc.Duration.seconds(2)); +dt = dt.sub(2, tc.TimeUnit.Year); +dt = dt.sub(2, tc.TimeUnit.Month); +dt = dt.sub(2, tc.TimeUnit.Week); +dt = dt.sub(2, tc.TimeUnit.Day); +dt = dt.sub(2, tc.TimeUnit.Hour); +dt = dt.sub(2, tc.TimeUnit.Minute); +dt = dt.sub(2, tc.TimeUnit.Second); +dt = dt.subLocal(2, tc.TimeUnit.Second); +d = dt.diff(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.lessThan(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.lessEqual(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.greaterThan(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.greaterEqual(new tc.DateTime(9289234, tc.TimeZone.local())); +s = dt.toIsoString(); +s = dt.toString(); +s = dt.toUtcString(); + +// PERIOD + +s = tc.periodDstToString(tc.PeriodDst.RegularIntervals); +s = tc.periodDstToString(tc.PeriodDst.RegularLocalTime); + +var p: tc.Period; + +p = new tc.Period(tc.DateTime.nowLocal(), 1, tc.TimeUnit.Hour, tc.PeriodDst.RegularLocalTime); +dt = p.start(); +n = p.amount(); +var tu: tc.TimeUnit = p.unit(); +var pd: tc.PeriodDst = p.dst(); +dt = p.findFirst(tc.DateTime.nowLocal()); +dt = p.findNext(dt); +s = p.toIsoString(); +s = p.toString(); + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/timezonecomplete/timezonecomplete-1.2.0.d.ts b/timezonecomplete/timezonecomplete-1.2.0.d.ts new file mode 100644 index 000000000..2f1b969bc --- /dev/null +++ b/timezonecomplete/timezonecomplete-1.2.0.d.ts @@ -0,0 +1,681 @@ +// Type definitions for timezonecomplete +// Project: https://github.com/SpiritIT/timezonecomplete +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Generated by dts-bundle 0.1.1 + +declare module 'timezonecomplete' { + /** + * @return True iff the given year is a leap year. + */ + export function isLeapYear(year: number): boolean; + /** + * @param year The full year + * @param month The month 1-12 + * @return The number of days in the given month + */ + export function daysInMonth(year: number, month: number): number; + /** + * Returns an ISO time string. Note that months are 1-12. + */ + export function isoString(year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number): string; + /** + * Time units + */ + export enum TimeUnit { + Second = 0, + Minute = 1, + Hour = 2, + Day = 3, + Week = 4, + Month = 5, + Year = 6, + } + /** + * Time duration. Create one e.g. like this: var d = Duration.hours(1). + * Note that time durations do not take leap seconds etc. into account: + * one hour is simply represented as 3600000 milliseconds. + */ + export class Duration { + /** + * Positive number of milliseconds + * Stored positive because otherwise we constantly have to choose + * between Math.floor() and Math.ceil() + */ + /** + * Sign: 1 or -1 + */ + /** + * Construct a time duration + * @param n Number of hours + * @return A duration of n hours + */ + static hours(n: number): Duration; + /** + * Construct a time duration + * @param n Number of minutes + * @return A duration of n minutes + */ + static minutes(n: number): Duration; + /** + * Construct a time duration + * @param n Number of seconds + * @return A duration of n seconds + */ + static seconds(n: number): Duration; + /** + * Construct a time duration + * @param n Number of milliseconds + * @return A duration of n milliseconds + */ + static milliseconds(n: number): Duration; + /** + * Construct a time duration of 0 + */ + constructor(); + /** + * Construct a time duration from a number of milliseconds + */ + constructor(milliseconds: number); + /** + * Construct a time duration from a string in format + * [-]h[:m[:s[.n]]] e.g. -01:00:30.501 + */ + constructor(input: string); + /** + * @return another instance of Duration with the same value. + */ + clone(): Duration; + /** + * The entire duration in milliseconds (negative or positive) + */ + milliseconds(): number; + /** + * The millisecond part of the duration (always positive) + * @return e.g. 400 for a -01:02:03.400 duration + */ + millisecond(): number; + /** + * The entire duration in seconds (negative or positive, fractional) + * @return e.g. 1.5 for a 1500 milliseconds duration + */ + seconds(): number; + /** + * The second part of the duration (always positive) + * @return e.g. 3 for a -01:02:03.400 duration + */ + second(): number; + /** + * The entire duration in minutes (negative or positive, fractional) + * @return e.g. 1.5 for a 90000 milliseconds duration + */ + minutes(): number; + /** + * The minute part of the duration (always positive) + * @return e.g. 2 for a -01:02:03.400 duration + */ + minute(): number; + /** + * The entire duration in hours (negative or positive, fractional) + * @return e.g. 1.5 for a 5400000 milliseconds duration + */ + hours(): number; + /** + * The hour part of the duration (always positive). + * Note that this part can exceed 23 hours, because for + * now, we do not have a days() function + * @return e.g. 25 for a -25:02:03.400 duration + */ + wholeHours(): number; + /** + * Sign + * @return "-" if the duration is negative + */ + sign(): string; + /** + * @return True iff (this < other) + */ + lessThan(other: Duration): boolean; + /** + * @return True iff this and other represent the same time duration + */ + equals(other: Duration): boolean; + /** + * @return True iff this > other + */ + greaterThan(other: Duration): boolean; + /** + * @return The minimum (most negative) of this and other + */ + min(other: Duration): Duration; + /** + * @return The maximum (most positive) of this and other + */ + max(other: Duration): Duration; + /** + * @return a new Duration of (this * value) + */ + multiply(value: number): Duration; + /** + * Add a duration. + * @return a new Duration of (this + value) + */ + add(value: Duration): Duration; + /** + * Subtract a duration. + * @return a new Duration of (this - value) + */ + sub(value: Duration): Duration; + /** + * String in [-]hh:mm:ss.nnn notation. All fields are + * always present except the sign. + */ + toFullString(): string; + /** + * String in [-]hh[:mm[:ss[.nnn]]] notation. Fields are + * added as necessary + */ + toString(): string; + } + /** + * The type of time zone + */ + export enum TimeZoneKind { + /** + * Local time offset as determined by JavaScript Date class. + */ + Local = 0, + /** + * Fixed offset from UTC, without DST. + */ + Offset = 1, + /** + * IANA timezone managed through Olsen TZ database. Includes + * DST if applicable. + */ + Proper = 2, + } + /** + * Time zone. The object is immutable because it is cached: + * requesting a time zone twice yields the very same object. + * Note that we use time zone offsets inverted w.r.t. JavaScript Date.getTimezoneOffset(), + * i.e. offset 90 means +01:30. + * + * Time zones come in three flavors: the local time zone, as calculated by JavaScript Date, + * a fixed offset ("+01:30") without DST, or a IANA timezone ("Europe/Amsterdam") with DST + * applied depending on the time zone rules. + */ + export class TimeZone { + /** + * The local time zone for a given date. Note that + * the time zone varies with the date: amsterdam time for + * 2014-01-01 is +01:00 and amsterdam time for 2014-07-01 is +02:00 + */ + static local(): TimeZone; + /** + * The UTC time zone. + */ + static utc(): TimeZone; + /** + * Returns a time zone object from the cache. If it does not exist, it is created. + * @return The time zone with the given offset w.r.t. UTC in minutes, e.g. 90 for +01:30 + */ + static zone(offset: number): TimeZone; + /** + * Returns a time zone object from the cache. If it does not exist, it is created. + * @param s: Empty string for local time, a TZ database time zone name (e.g. Europe/Amsterdam) + * or an offset string (either +01:30, +0130, +01, Z). For a full list of names, see: + * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones + */ + static zone(s: string): TimeZone; + /** + * The time zone identifier. Can be an offset "-01:30" or an + * IANA time zone name "Europe/Amsterdam", or "localtime" for + * the local time zone. + */ + name(): string; + /** + * The kind of time zone (Local/Offset/Proper) + */ + kind(): TimeZoneKind; + /** + * Equality operator. Maps zero offsets and different names for UTC onto + * each other. Other time zones are not mapped onto each other. + */ + equals(other: TimeZone): boolean; + /** + * Is this zone equivalent to UTC? + */ + isUtc(): boolean; + /** + * Calculate timezone offset from a UTC time. + * @param year local full year + * @param month local month 1-12 (note this deviates from JavaScript date) + * @param day local day of month 1-31 + * @param hour local hour 0-23 + * @param minute local minute 0-59 + * @param second local second 0-59 + * @param millisecond local millisecond 0-999 + * @return the offset of this time zone with respect to UTC at the given time. + */ + offsetForUtc(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; + /** + * Calculate timezone offset from a zone-local time (NOT a UTC time). + * @param year local full year + * @param month local month 1-12 (note this deviates from JavaScript date) + * @param day local day of month 1-31 + * @param hour local hour 0-23 + * @param minute local minute 0-59 + * @param second local second 0-59 + * @param millisecond local millisecond 0-999 + * @return the offset of this time zone with respect to UTC at the given time. + */ + offsetForZone(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; + /** + * Convenience function, takes values from a Javascript Date + * Calls offsetForUtc() with the contents of the date + * @param date: the date + * @param funcs: the set of functions to use: get() or getUTC() + */ + offsetForUtcDate(date: Date, funcs: DateFunctions): number; + /** + * Convenience function, takes values from a Javascript Date + * Calls offsetForUtc() with the contents of the date + * @param date: the date + * @param funcs: the set of functions to use: get() or getUTC() + */ + offsetForZoneDate(date: Date, funcs: DateFunctions): number; + /** + * The time zone identifier (normalized). + * Either "localtime", IANA name, or "+hh:mm" offset. + */ + toString(): string; + /** + * Convert an offset number into an offset string + * @param offset The offset in minutes from UTC e.g. 90 minutes + * @return the offset in ISO notation "+01:30" for +90 minutes + */ + static offsetToString(offset: number): string; + /** + * String to offset conversion. + * @param s Formats: "-01:00", "-0100", "-01", "Z" + * @return offset w.r.t. UTC in minutes + */ + static stringToOffset(s: string): number; + } + /** + * For testing purposes, we often need to manipulate what the current + * time is. This is an interface for a custom time source object + * so in tests you can use a custom time source. + */ + export interface TimeSource { + /** + * Return the current date+time as a javascript Date object + */ + now(): Date; + } + /** + * Default time source, returns actual time + */ + export class RealTimeSource implements TimeSource { + now(): Date; + } + /** + * Indicates how a Date object should be interpreted. + * Either we can take getYear(), getMonth() etc for our field + * values, or we can take getUTCYear() etc to do that. + */ + export enum DateFunctions { + /** + * Use the Date.getFullYear(), Date.getMonth(), ... functions. + */ + Get = 0, + /** + * Use the Date.getUTCFullYear(), Date.getUTCMonth(), ... functions. + */ + GetUTC = 1, + } + /** + * Our very own DateTime class which is time zone-aware + * and which can be mocked for testing purposes + */ + export class DateTime { + /** + * Actual time source in use. Setting this property allows to + * fake time in tests. DateTime.nowLocal() and DateTime.nowUtc() + * use this property for obtaining the current time. + */ + static timeSource: TimeSource; + /** + * Current date+time in local time (derived from DateTime.timeSource.now()). + */ + static nowLocal(): DateTime; + /** + * Current date+time in UTC time (derived from DateTime.timeSource.now()). + */ + static nowUtc(): DateTime; + /** + * Current date+time in the given time zone (derived from DateTime.timeSource.now()). + * @param timeZone The desired time zone. + */ + static now(timeZone: TimeZone): DateTime; + /** + * Constructor. Creates current time in local timezone. + */ + constructor(); + /** + * Constructor + * @param isoString String in ISO 8601 format. Instead of ISO time zone, + * it may include a space and then and IANA time zone. + * e.g. "2007-04-05T12:30:40.500" (no time zone, naive date) + * e.g. "2007-04-05T12:30:40.500+01:00" (UTC offset without daylight saving time) + * or "2007-04-05T12:30:40.500Z" (UTC) + * or "2007-04-05T12:30:40.500 Europe/Amsterdam" (IANA time zone, with daylight saving time if applicable) + * @param timeZone if given, the date in the string is assumed to be in this time zone. + * Note that it is NOT CONVERTED to the time zone. Useful + * for strings without a time zone + */ + constructor(isoString: string, timeZone?: TimeZone); + /** + * Constructor. You provide a date, then you say whether to take the + * date.getYear()/getXxx methods or the date.getUTCYear()/date.getUTCXxx methods, + * and then you state which time zone that date is in. + * + * @param date A date object. + * @param getters Specifies which set of Date getters contains the date in the given time zone: the + * Date.getXxx() methods or the Date.getUTCXxx() methods. + * @param timeZone The time zone that the given date is assumed to be in (may be null for unaware dates) + */ + constructor(date: Date, getFuncs: DateFunctions, timeZone?: TimeZone); + /** + * Constructor. Note that unlike JavaScript dates we require fields to be in normal ranges. + * Use the add(duration) or sub(duration) for arithmetic. + * @param year The full year (e.g. 2014) + * @param month The month [1-12] (note this deviates from JavaScript Date) + * @param day The day of the month [1-31] + * @param hour The hour of the day [0-24) + * @param minute The minute of the hour [0-59] + * @param second The second of the minute [0-59] + * @param millisecond The millisecond of the second [0-999] + * @param timeZone The time zone, or null (for unaware dates) + */ + constructor(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number, timeZone?: TimeZone); + /** + * Constructor + * @param unixTimestamp milliseconds since 1970-01-01T00:00:00.000 + * @param timeZone the time zone that the timestamp is assumed to be in (usually UTC). + */ + constructor(unixTimestamp: number, timeZone?: TimeZone); + /** + * @return a copy of this object + */ + clone(): DateTime; + /** + * @return The time zone that the date is in. May be null for unaware dates. + */ + zone(): TimeZone; + /** + * @return the offset w.r.t. UTC in minutes. Returns 0 for unaware dates and for UTC dates. + */ + offset(): number; + /** + * @return The full year e.g. 2014 + */ + year(): number; + /** + * @return The month 1-12 (note this deviates from JavaScript Date) + */ + month(): number; + /** + * @return The day of the month 1-31 + */ + day(): number; + /** + * @return The hour 0-23 + */ + hour(): number; + /** + * @return the minutes 0-59 + */ + minute(): number; + /** + * @return the seconds 0-59 + */ + second(): number; + /** + * @return the milliseconds 0-999 + */ + millisecond(): number; + /** + * @return Milliseconds since 1970-01-01T00:00:00.000Z + */ + unixUtcMillis(): number; + /** + * @return The full year e.g. 2014 + */ + utcYear(): number; + /** + * @return The UTC month 1-12 (note this deviates from JavaScript Date) + */ + utcMonth(): number; + /** + * @return The UTC day of the month 1-31 + */ + utcDay(): number; + /** + * @return The UTC hour 0-23 + */ + utcHour(): number; + /** + * @return The UTC minutes 0-59 + */ + utcMinute(): number; + /** + * @return The UTC seconds 0-59 + */ + utcSecond(): number; + /** + * @return The UTC milliseconds 0-999 + */ + utcMillisecond(): number; + /** + * Convert this date to the given time zone (in-place). + * Throws if this date does not have a time zone. + * @return this (for chaining) + */ + convert(zone?: TimeZone): DateTime; + /** + * Returns this date converted to the given time zone. + * Unaware dates can only be converted to unaware dates (clone) + * For unaware dates, an exception is thrown + * @param zone The new time zone. This may be null to create unaware date. + * @return The converted date + */ + toZone(zone?: TimeZone): DateTime; + /** + * Convert to JavaScript date with the zone time in the getX() methods. + * Unless the timezone is local, the Date.getUTCX() methods will NOT be correct. + */ + toDate(): Date; + /** + * Add a time duration. Note that this simply adds a number + * of milliseconds to UTC and converts back to zone(), + * so in the presence of e.g. leap seconds there may be a + * shift in the seconds field if you add an hour. + * There is not DST handling and no leap second handling. + * @return this + duration + */ + add(duration: Duration): DateTime; + /** + * Add an amount of time to UTC, taking leap seconds etc into account. + * Adding e.g. 1 hour will increment the utcHour() field + * date by one. In case of DST changes, the local hour() field + * may not increase or increase by 2 hours. So if you add a month, the + * local time may vary by an hour. There will not be a shift + * in seconds due to leap seconds. + */ + add(amount: number, unit: TimeUnit): DateTime; + /** + * Add an amount of time to the zone time, as regularly as possible. + * Adding e.g. 1 hour will increment the hour() field of the zone + * date by one. In case of DST changes, the utcHour() field may + * increase by 1 or increase by 2. Adding a day will leave the time portion + * intact. However, adding an hour around a forward DST change adds two hours, + * since there is a zone time (2AM in Holland) that does not exist. + */ + addLocal(amount: number, unit: TimeUnit): DateTime; + /** + * Same as add(-1*duration); + */ + sub(duration: Duration): DateTime; + /** + * Same as add(-1*amount, unit); + */ + sub(amount: number, unit: TimeUnit): DateTime; + /** + * Same as addLocal(-1*amount, unit); + */ + subLocal(amount: number, unit: TimeUnit): DateTime; + /** + * Time difference between two DateTimes + * @return this - other + */ + diff(other: DateTime): Duration; + /** + * @return True iff (this < other) + */ + lessThan(other: DateTime): boolean; + /** + * @return True iff (this <= other) + */ + lessEqual(other: DateTime): boolean; + /** + * @return True iff this and other represent the same time in UTC + */ + equals(other: DateTime): boolean; + /** + * @return True iff this and other represent the same time and + * have the same zone + */ + identical(other: DateTime): boolean; + /** + * @return True iff this > other + */ + greaterThan(other: DateTime): boolean; + /** + * @return True iff this >= other + */ + greaterEqual(other: DateTime): boolean; + /** + * Proper ISO 8601 format string with any IANA zone converted to ISO offset + * E.g. "2014-01-01T23:15:33+01:00" for Europe/Amsterdam + */ + toIsoString(): string; + /** + * Modified ISO 8601 format string with IANA name if applicable. + * E.g. "2014-01-01T23:15:33.000 Europe/Amsterdam" + */ + toString(): string; + /** + * Modified ISO 8601 format string in UTC without time zone info + */ + toUtcString(): string; + } + /** + * Specifies how the period should repeat across the day + * during DST changes. + */ + export enum PeriodDst { + /** + * Keep repeating in similar intervals measured in UTC, + * unaffected by Daylight Saving Time. + * E.g. a repetition of one hour will take one real hour + * every time, even in a time zone with DST. + * Leap seconds, leap days and month length + * differences will still make the intervals different. + */ + RegularIntervals = 0, + /** + * Ensure that the time at which the intervals occur stay + * at the same place in the day, local time. So e.g. + * a period of one day, starting at 8:05AM Europe/Amsterdam time + * will always start at 8:05 Europe/Amsterdam. This means that + * in UTC time, some intervals will be 25 hours and some + * 23 hours during DST changes. + * Another example: an hourly interval will be hourly in local time, + * skipping an hour in UTC for a DST backward change. + */ + RegularLocalTime = 1, + } + /** + * Convert a PeriodDst to a string: "regular intervals" or "regular local time" + */ + export function periodDstToString(p: PeriodDst): string; + /** + * Repeating time period: consists of a starting point and + * a time length. This class accounts for leap seconds and leap days. + */ + export class Period { + /** + * Constructor + * LIMITATION: if dst equals RegularLocalTime, and unit is Second, Minute or Hour, + * then the amount must be a factor of 24. So 120 seconds is allowed while 121 seconds is not. + * This is due to the enormous processing power required by these cases. They are not + * implemented and you will get an assert. + * + * @param start The start of the period. If the period is in Months or Years, and + * the day is 29 or 30 or 31, the results are maximised to end-of-month. + * @param amount The amount of units. + * @param unit The unit. + * @param dst Specifies how to handle Daylight Saving Time. Not relevant + * if the time zone of the start datetime does not have DST. + */ + constructor(start: DateTime, amount: number, unit: TimeUnit, dst: PeriodDst); + /** + * The start date + */ + start(): DateTime; + /** + * The amount of units + */ + amount(): number; + /** + * The unit + */ + unit(): TimeUnit; + /** + * The dst handling mode + */ + dst(): PeriodDst; + /** + * The first occurrence of the period greater than + * the given date. The given date need not be at a period boundary. + * Pre: the fromdate and startdate must either both have timezones or not + * @param fromDate: the date after which to return the next date + * @return the first date matching the period after fromDate, given + * in the same zone as the fromDate. + */ + findFirst(fromDate: DateTime): DateTime; + /** + * Returns the next timestamp in the period. The given timestamp must + * be at a period boundary, otherwise the answer is incorrect. + * This function has MUCH better performance than findFirst. + * Returns the datetime "count" times away from the given datetime. + * @param prev Boundary date. Must have a time zone (any time zone) iff the period start date has one. + * @param count Optional, must be >= 1 and whole. + * @return (prev + count * period), in the same timezone as prev. + */ + findNext(prev: DateTime, count?: number): DateTime; + /** + * Returns an ISO duration string + * P[n]Y[n]M[n]DT[n]H[n]M[n][.n]S or P[n]W + */ + toIsoString(): string; + /** + * A string representation e.g. + * "10 years, starting at 2014-03-01T12:00:00 Europe/Amsterdam keeping regular intervals". + */ + toString(): string; + } +} + diff --git a/timezonecomplete/timezonecomplete-tests.ts b/timezonecomplete/timezonecomplete-tests.ts index 03f94e44b..142b3f25a 100644 --- a/timezonecomplete/timezonecomplete-tests.ts +++ b/timezonecomplete/timezonecomplete-tests.ts @@ -31,6 +31,7 @@ b = d7.greaterThan(d6); d = d7.min(d6); d = d7.max(d6); d = d7.multiply(3); +d = d7.divide(0.3); d = d7.add(d6); d = d7.sub(d6); s = d7.toString(); @@ -126,6 +127,10 @@ s = dt.toIsoString(); s = dt.toString(); s = dt.toUtcString(); +var wd: tc.WeekDay; +wd = dt.weekDay(); +wd = dt.utcWeekDay(); + // PERIOD s = tc.periodDstToString(tc.PeriodDst.RegularIntervals); diff --git a/timezonecomplete/timezonecomplete.d.ts b/timezonecomplete/timezonecomplete.d.ts index 2f1b969bc..6fbea6f6f 100644 --- a/timezonecomplete/timezonecomplete.d.ts +++ b/timezonecomplete/timezonecomplete.d.ts @@ -1,27 +1,27 @@ -// Type definitions for timezonecomplete +// Type definitions for timezonecomplete 1.3.0 // Project: https://github.com/SpiritIT/timezonecomplete // Definitions by: Rogier Schouten // Definitions: https://github.com/borisyankov/DefinitelyTyped -// Generated by dts-bundle 0.1.1 +// Generated by dts-bundle v0.2.0 declare module 'timezonecomplete' { /** - * @return True iff the given year is a leap year. - */ + * @return True iff the given year is a leap year. + */ export function isLeapYear(year: number): boolean; /** - * @param year The full year - * @param month The month 1-12 - * @return The number of days in the given month - */ + * @param year The full year + * @param month The month 1-12 + * @return The number of days in the given month + */ export function daysInMonth(year: number, month: number): number; /** - * Returns an ISO time string. Note that months are 1-12. - */ + * Returns an ISO time string. Note that months are 1-12. + */ export function isoString(year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number): string; /** - * Time units - */ + * Time units + */ export enum TimeUnit { Second = 0, Minute = 1, @@ -32,649 +32,670 @@ declare module 'timezonecomplete' { Year = 6, } /** - * Time duration. Create one e.g. like this: var d = Duration.hours(1). - * Note that time durations do not take leap seconds etc. into account: - * one hour is simply represented as 3600000 milliseconds. - */ + * Time duration. Create one e.g. like this: var d = Duration.hours(1). + * Note that time durations do not take leap seconds etc. into account: + * one hour is simply represented as 3600000 milliseconds. + */ export class Duration { /** - * Positive number of milliseconds - * Stored positive because otherwise we constantly have to choose - * between Math.floor() and Math.ceil() - */ - /** - * Sign: 1 or -1 - */ - /** - * Construct a time duration - * @param n Number of hours - * @return A duration of n hours - */ + * Construct a time duration + * @param n Number of hours + * @return A duration of n hours + */ static hours(n: number): Duration; /** - * Construct a time duration - * @param n Number of minutes - * @return A duration of n minutes - */ + * Construct a time duration + * @param n Number of minutes + * @return A duration of n minutes + */ static minutes(n: number): Duration; /** - * Construct a time duration - * @param n Number of seconds - * @return A duration of n seconds - */ + * Construct a time duration + * @param n Number of seconds + * @return A duration of n seconds + */ static seconds(n: number): Duration; /** - * Construct a time duration - * @param n Number of milliseconds - * @return A duration of n milliseconds - */ + * Construct a time duration + * @param n Number of milliseconds + * @return A duration of n milliseconds + */ static milliseconds(n: number): Duration; /** - * Construct a time duration of 0 - */ + * Construct a time duration of 0 + */ constructor(); /** - * Construct a time duration from a number of milliseconds - */ + * Construct a time duration from a number of milliseconds + */ constructor(milliseconds: number); /** - * Construct a time duration from a string in format - * [-]h[:m[:s[.n]]] e.g. -01:00:30.501 - */ + * Construct a time duration from a string in format + * [-]h[:m[:s[.n]]] e.g. -01:00:30.501 + */ constructor(input: string); /** - * @return another instance of Duration with the same value. - */ + * @return another instance of Duration with the same value. + */ clone(): Duration; /** - * The entire duration in milliseconds (negative or positive) - */ + * The entire duration in milliseconds (negative or positive) + */ milliseconds(): number; /** - * The millisecond part of the duration (always positive) - * @return e.g. 400 for a -01:02:03.400 duration - */ + * The millisecond part of the duration (always positive) + * @return e.g. 400 for a -01:02:03.400 duration + */ millisecond(): number; /** - * The entire duration in seconds (negative or positive, fractional) - * @return e.g. 1.5 for a 1500 milliseconds duration - */ + * The entire duration in seconds (negative or positive, fractional) + * @return e.g. 1.5 for a 1500 milliseconds duration + */ seconds(): number; /** - * The second part of the duration (always positive) - * @return e.g. 3 for a -01:02:03.400 duration - */ + * The second part of the duration (always positive) + * @return e.g. 3 for a -01:02:03.400 duration + */ second(): number; /** - * The entire duration in minutes (negative or positive, fractional) - * @return e.g. 1.5 for a 90000 milliseconds duration - */ + * The entire duration in minutes (negative or positive, fractional) + * @return e.g. 1.5 for a 90000 milliseconds duration + */ minutes(): number; /** - * The minute part of the duration (always positive) - * @return e.g. 2 for a -01:02:03.400 duration - */ + * The minute part of the duration (always positive) + * @return e.g. 2 for a -01:02:03.400 duration + */ minute(): number; /** - * The entire duration in hours (negative or positive, fractional) - * @return e.g. 1.5 for a 5400000 milliseconds duration - */ + * The entire duration in hours (negative or positive, fractional) + * @return e.g. 1.5 for a 5400000 milliseconds duration + */ hours(): number; /** - * The hour part of the duration (always positive). - * Note that this part can exceed 23 hours, because for - * now, we do not have a days() function - * @return e.g. 25 for a -25:02:03.400 duration - */ + * The hour part of the duration (always positive). + * Note that this part can exceed 23 hours, because for + * now, we do not have a days() function + * @return e.g. 25 for a -25:02:03.400 duration + */ wholeHours(): number; /** - * Sign - * @return "-" if the duration is negative - */ + * Sign + * @return "-" if the duration is negative + */ sign(): string; /** - * @return True iff (this < other) - */ + * @return True iff (this < other) + */ lessThan(other: Duration): boolean; /** - * @return True iff this and other represent the same time duration - */ + * @return True iff this and other represent the same time duration + */ equals(other: Duration): boolean; /** - * @return True iff this > other - */ + * @return True iff this > other + */ greaterThan(other: Duration): boolean; /** - * @return The minimum (most negative) of this and other - */ + * @return The minimum (most negative) of this and other + */ min(other: Duration): Duration; /** - * @return The maximum (most positive) of this and other - */ + * @return The maximum (most positive) of this and other + */ max(other: Duration): Duration; /** - * @return a new Duration of (this * value) - */ + * Multiply with a fixed number. + * @return a new Duration of (this * value) + */ multiply(value: number): Duration; - /** - * Add a duration. - * @return a new Duration of (this + value) - */ - add(value: Duration): Duration; - /** - * Subtract a duration. - * @return a new Duration of (this - value) - */ - sub(value: Duration): Duration; /** - * String in [-]hh:mm:ss.nnn notation. All fields are - * always present except the sign. - */ + * Divide by a fixed number. + * @return a new Duration of (this / value) + */ + divide(value: number): Duration; + /** + * Add a duration. + * @return a new Duration of (this + value) + */ + add(value: Duration): Duration; + /** + * Subtract a duration. + * @return a new Duration of (this - value) + */ + sub(value: Duration): Duration; + /** + * String in [-]hh:mm:ss.nnn notation. All fields are + * always present except the sign. + */ toFullString(): string; /** - * String in [-]hh[:mm[:ss[.nnn]]] notation. Fields are - * added as necessary - */ + * String in [-]hh[:mm[:ss[.nnn]]] notation. Fields are + * added as necessary + */ toString(): string; } /** - * The type of time zone - */ + * The type of time zone + */ export enum TimeZoneKind { /** - * Local time offset as determined by JavaScript Date class. - */ + * Local time offset as determined by JavaScript Date class. + */ Local = 0, /** - * Fixed offset from UTC, without DST. - */ + * Fixed offset from UTC, without DST. + */ Offset = 1, /** - * IANA timezone managed through Olsen TZ database. Includes - * DST if applicable. - */ + * IANA timezone managed through Olsen TZ database. Includes + * DST if applicable. + */ Proper = 2, } /** - * Time zone. The object is immutable because it is cached: - * requesting a time zone twice yields the very same object. - * Note that we use time zone offsets inverted w.r.t. JavaScript Date.getTimezoneOffset(), - * i.e. offset 90 means +01:30. - * - * Time zones come in three flavors: the local time zone, as calculated by JavaScript Date, - * a fixed offset ("+01:30") without DST, or a IANA timezone ("Europe/Amsterdam") with DST - * applied depending on the time zone rules. - */ + * Time zone. The object is immutable because it is cached: + * requesting a time zone twice yields the very same object. + * Note that we use time zone offsets inverted w.r.t. JavaScript Date.getTimezoneOffset(), + * i.e. offset 90 means +01:30. + * + * Time zones come in three flavors: the local time zone, as calculated by JavaScript Date, + * a fixed offset ("+01:30") without DST, or a IANA timezone ("Europe/Amsterdam") with DST + * applied depending on the time zone rules. + */ export class TimeZone { /** - * The local time zone for a given date. Note that - * the time zone varies with the date: amsterdam time for - * 2014-01-01 is +01:00 and amsterdam time for 2014-07-01 is +02:00 - */ + * The local time zone for a given date. Note that + * the time zone varies with the date: amsterdam time for + * 2014-01-01 is +01:00 and amsterdam time for 2014-07-01 is +02:00 + */ static local(): TimeZone; /** - * The UTC time zone. - */ + * The UTC time zone. + */ static utc(): TimeZone; /** - * Returns a time zone object from the cache. If it does not exist, it is created. - * @return The time zone with the given offset w.r.t. UTC in minutes, e.g. 90 for +01:30 - */ + * Returns a time zone object from the cache. If it does not exist, it is created. + * @return The time zone with the given offset w.r.t. UTC in minutes, e.g. 90 for +01:30 + */ static zone(offset: number): TimeZone; /** - * Returns a time zone object from the cache. If it does not exist, it is created. - * @param s: Empty string for local time, a TZ database time zone name (e.g. Europe/Amsterdam) - * or an offset string (either +01:30, +0130, +01, Z). For a full list of names, see: - * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones - */ + * Returns a time zone object from the cache. If it does not exist, it is created. + * @param s: Empty string for local time, a TZ database time zone name (e.g. Europe/Amsterdam) + * or an offset string (either +01:30, +0130, +01, Z). For a full list of names, see: + * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones + */ static zone(s: string): TimeZone; /** - * The time zone identifier. Can be an offset "-01:30" or an - * IANA time zone name "Europe/Amsterdam", or "localtime" for - * the local time zone. - */ + * The time zone identifier. Can be an offset "-01:30" or an + * IANA time zone name "Europe/Amsterdam", or "localtime" for + * the local time zone. + */ name(): string; /** - * The kind of time zone (Local/Offset/Proper) - */ + * The kind of time zone (Local/Offset/Proper) + */ kind(): TimeZoneKind; /** - * Equality operator. Maps zero offsets and different names for UTC onto - * each other. Other time zones are not mapped onto each other. - */ + * Equality operator. Maps zero offsets and different names for UTC onto + * each other. Other time zones are not mapped onto each other. + */ equals(other: TimeZone): boolean; /** - * Is this zone equivalent to UTC? - */ + * Is this zone equivalent to UTC? + */ isUtc(): boolean; /** - * Calculate timezone offset from a UTC time. - * @param year local full year - * @param month local month 1-12 (note this deviates from JavaScript date) - * @param day local day of month 1-31 - * @param hour local hour 0-23 - * @param minute local minute 0-59 - * @param second local second 0-59 - * @param millisecond local millisecond 0-999 - * @return the offset of this time zone with respect to UTC at the given time. - */ + * Calculate timezone offset from a UTC time. + * @param year local full year + * @param month local month 1-12 (note this deviates from JavaScript date) + * @param day local day of month 1-31 + * @param hour local hour 0-23 + * @param minute local minute 0-59 + * @param second local second 0-59 + * @param millisecond local millisecond 0-999 + * @return the offset of this time zone with respect to UTC at the given time. + */ offsetForUtc(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; /** - * Calculate timezone offset from a zone-local time (NOT a UTC time). - * @param year local full year - * @param month local month 1-12 (note this deviates from JavaScript date) - * @param day local day of month 1-31 - * @param hour local hour 0-23 - * @param minute local minute 0-59 - * @param second local second 0-59 - * @param millisecond local millisecond 0-999 - * @return the offset of this time zone with respect to UTC at the given time. - */ + * Calculate timezone offset from a zone-local time (NOT a UTC time). + * @param year local full year + * @param month local month 1-12 (note this deviates from JavaScript date) + * @param day local day of month 1-31 + * @param hour local hour 0-23 + * @param minute local minute 0-59 + * @param second local second 0-59 + * @param millisecond local millisecond 0-999 + * @return the offset of this time zone with respect to UTC at the given time. + */ offsetForZone(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; /** - * Convenience function, takes values from a Javascript Date - * Calls offsetForUtc() with the contents of the date - * @param date: the date - * @param funcs: the set of functions to use: get() or getUTC() - */ + * Convenience function, takes values from a Javascript Date + * Calls offsetForUtc() with the contents of the date + * @param date: the date + * @param funcs: the set of functions to use: get() or getUTC() + */ offsetForUtcDate(date: Date, funcs: DateFunctions): number; /** - * Convenience function, takes values from a Javascript Date - * Calls offsetForUtc() with the contents of the date - * @param date: the date - * @param funcs: the set of functions to use: get() or getUTC() - */ + * Convenience function, takes values from a Javascript Date + * Calls offsetForUtc() with the contents of the date + * @param date: the date + * @param funcs: the set of functions to use: get() or getUTC() + */ offsetForZoneDate(date: Date, funcs: DateFunctions): number; /** - * The time zone identifier (normalized). - * Either "localtime", IANA name, or "+hh:mm" offset. - */ + * The time zone identifier (normalized). + * Either "localtime", IANA name, or "+hh:mm" offset. + */ toString(): string; /** - * Convert an offset number into an offset string - * @param offset The offset in minutes from UTC e.g. 90 minutes - * @return the offset in ISO notation "+01:30" for +90 minutes - */ + * Convert an offset number into an offset string + * @param offset The offset in minutes from UTC e.g. 90 minutes + * @return the offset in ISO notation "+01:30" for +90 minutes + */ static offsetToString(offset: number): string; /** - * String to offset conversion. - * @param s Formats: "-01:00", "-0100", "-01", "Z" - * @return offset w.r.t. UTC in minutes - */ + * String to offset conversion. + * @param s Formats: "-01:00", "-0100", "-01", "Z" + * @return offset w.r.t. UTC in minutes + */ static stringToOffset(s: string): number; } /** - * For testing purposes, we often need to manipulate what the current - * time is. This is an interface for a custom time source object - * so in tests you can use a custom time source. - */ + * For testing purposes, we often need to manipulate what the current + * time is. This is an interface for a custom time source object + * so in tests you can use a custom time source. + */ export interface TimeSource { /** - * Return the current date+time as a javascript Date object - */ + * Return the current date+time as a javascript Date object + */ now(): Date; } /** - * Default time source, returns actual time - */ + * Default time source, returns actual time + */ export class RealTimeSource implements TimeSource { now(): Date; } /** - * Indicates how a Date object should be interpreted. - * Either we can take getYear(), getMonth() etc for our field - * values, or we can take getUTCYear() etc to do that. - */ + * Indicates how a Date object should be interpreted. + * Either we can take getYear(), getMonth() etc for our field + * values, or we can take getUTCYear() etc to do that. + */ export enum DateFunctions { /** - * Use the Date.getFullYear(), Date.getMonth(), ... functions. - */ + * Use the Date.getFullYear(), Date.getMonth(), ... functions. + */ Get = 0, /** - * Use the Date.getUTCFullYear(), Date.getUTCMonth(), ... functions. - */ + * Use the Date.getUTCFullYear(), Date.getUTCMonth(), ... functions. + */ GetUTC = 1, } /** - * Our very own DateTime class which is time zone-aware - * and which can be mocked for testing purposes - */ + * Day-of-week. Note the enum values correspond to JavaScript day-of-week: + * Sunday = 0, Monday = 1 etc + */ + export enum WeekDay { + Sunday = 0, + Monday = 1, + Tuesday = 2, + Wednesday = 3, + Thursday = 4, + Friday = 5, + Saturday = 6, + } + /** + * Our very own DateTime class which is time zone-aware + * and which can be mocked for testing purposes + */ export class DateTime { /** - * Actual time source in use. Setting this property allows to - * fake time in tests. DateTime.nowLocal() and DateTime.nowUtc() - * use this property for obtaining the current time. - */ + * Actual time source in use. Setting this property allows to + * fake time in tests. DateTime.nowLocal() and DateTime.nowUtc() + * use this property for obtaining the current time. + */ static timeSource: TimeSource; /** - * Current date+time in local time (derived from DateTime.timeSource.now()). - */ + * Current date+time in local time (derived from DateTime.timeSource.now()). + */ static nowLocal(): DateTime; /** - * Current date+time in UTC time (derived from DateTime.timeSource.now()). - */ + * Current date+time in UTC time (derived from DateTime.timeSource.now()). + */ static nowUtc(): DateTime; /** - * Current date+time in the given time zone (derived from DateTime.timeSource.now()). - * @param timeZone The desired time zone. - */ + * Current date+time in the given time zone (derived from DateTime.timeSource.now()). + * @param timeZone The desired time zone. + */ static now(timeZone: TimeZone): DateTime; /** - * Constructor. Creates current time in local timezone. - */ + * Constructor. Creates current time in local timezone. + */ constructor(); /** - * Constructor - * @param isoString String in ISO 8601 format. Instead of ISO time zone, - * it may include a space and then and IANA time zone. - * e.g. "2007-04-05T12:30:40.500" (no time zone, naive date) - * e.g. "2007-04-05T12:30:40.500+01:00" (UTC offset without daylight saving time) - * or "2007-04-05T12:30:40.500Z" (UTC) - * or "2007-04-05T12:30:40.500 Europe/Amsterdam" (IANA time zone, with daylight saving time if applicable) - * @param timeZone if given, the date in the string is assumed to be in this time zone. - * Note that it is NOT CONVERTED to the time zone. Useful - * for strings without a time zone - */ + * Constructor + * @param isoString String in ISO 8601 format. Instead of ISO time zone, + * it may include a space and then and IANA time zone. + * e.g. "2007-04-05T12:30:40.500" (no time zone, naive date) + * e.g. "2007-04-05T12:30:40.500+01:00" (UTC offset without daylight saving time) + * or "2007-04-05T12:30:40.500Z" (UTC) + * or "2007-04-05T12:30:40.500 Europe/Amsterdam" (IANA time zone, with daylight saving time if applicable) + * @param timeZone if given, the date in the string is assumed to be in this time zone. + * Note that it is NOT CONVERTED to the time zone. Useful + * for strings without a time zone + */ constructor(isoString: string, timeZone?: TimeZone); /** - * Constructor. You provide a date, then you say whether to take the - * date.getYear()/getXxx methods or the date.getUTCYear()/date.getUTCXxx methods, - * and then you state which time zone that date is in. - * - * @param date A date object. - * @param getters Specifies which set of Date getters contains the date in the given time zone: the - * Date.getXxx() methods or the Date.getUTCXxx() methods. - * @param timeZone The time zone that the given date is assumed to be in (may be null for unaware dates) - */ + * Constructor. You provide a date, then you say whether to take the + * date.getYear()/getXxx methods or the date.getUTCYear()/date.getUTCXxx methods, + * and then you state which time zone that date is in. + * + * @param date A date object. + * @param getters Specifies which set of Date getters contains the date in the given time zone: the + * Date.getXxx() methods or the Date.getUTCXxx() methods. + * @param timeZone The time zone that the given date is assumed to be in (may be null for unaware dates) + */ constructor(date: Date, getFuncs: DateFunctions, timeZone?: TimeZone); /** - * Constructor. Note that unlike JavaScript dates we require fields to be in normal ranges. - * Use the add(duration) or sub(duration) for arithmetic. - * @param year The full year (e.g. 2014) - * @param month The month [1-12] (note this deviates from JavaScript Date) - * @param day The day of the month [1-31] - * @param hour The hour of the day [0-24) - * @param minute The minute of the hour [0-59] - * @param second The second of the minute [0-59] - * @param millisecond The millisecond of the second [0-999] - * @param timeZone The time zone, or null (for unaware dates) - */ + * Constructor. Note that unlike JavaScript dates we require fields to be in normal ranges. + * Use the add(duration) or sub(duration) for arithmetic. + * @param year The full year (e.g. 2014) + * @param month The month [1-12] (note this deviates from JavaScript Date) + * @param day The day of the month [1-31] + * @param hour The hour of the day [0-24) + * @param minute The minute of the hour [0-59] + * @param second The second of the minute [0-59] + * @param millisecond The millisecond of the second [0-999] + * @param timeZone The time zone, or null (for unaware dates) + */ constructor(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number, timeZone?: TimeZone); /** - * Constructor - * @param unixTimestamp milliseconds since 1970-01-01T00:00:00.000 - * @param timeZone the time zone that the timestamp is assumed to be in (usually UTC). - */ + * Constructor + * @param unixTimestamp milliseconds since 1970-01-01T00:00:00.000 + * @param timeZone the time zone that the timestamp is assumed to be in (usually UTC). + */ constructor(unixTimestamp: number, timeZone?: TimeZone); /** - * @return a copy of this object - */ + * @return a copy of this object + */ clone(): DateTime; /** - * @return The time zone that the date is in. May be null for unaware dates. - */ + * @return The time zone that the date is in. May be null for unaware dates. + */ zone(): TimeZone; /** - * @return the offset w.r.t. UTC in minutes. Returns 0 for unaware dates and for UTC dates. - */ + * @return the offset w.r.t. UTC in minutes. Returns 0 for unaware dates and for UTC dates. + */ offset(): number; /** - * @return The full year e.g. 2014 - */ + * @return The full year e.g. 2014 + */ year(): number; /** - * @return The month 1-12 (note this deviates from JavaScript Date) - */ + * @return The month 1-12 (note this deviates from JavaScript Date) + */ month(): number; /** - * @return The day of the month 1-31 - */ + * @return The day of the month 1-31 + */ day(): number; /** - * @return The hour 0-23 - */ + * @return The hour 0-23 + */ hour(): number; /** - * @return the minutes 0-59 - */ + * @return the minutes 0-59 + */ minute(): number; /** - * @return the seconds 0-59 - */ + * @return the seconds 0-59 + */ second(): number; /** - * @return the milliseconds 0-999 - */ + * @return the milliseconds 0-999 + */ millisecond(): number; /** - * @return Milliseconds since 1970-01-01T00:00:00.000Z - */ + * @return the day-of-week (the enum values correspond to JavaScript + * week day numbers) + */ + weekDay(): WeekDay; + /** + * @return Milliseconds since 1970-01-01T00:00:00.000Z + */ unixUtcMillis(): number; /** - * @return The full year e.g. 2014 - */ + * @return The full year e.g. 2014 + */ utcYear(): number; /** - * @return The UTC month 1-12 (note this deviates from JavaScript Date) - */ + * @return The UTC month 1-12 (note this deviates from JavaScript Date) + */ utcMonth(): number; /** - * @return The UTC day of the month 1-31 - */ + * @return The UTC day of the month 1-31 + */ utcDay(): number; /** - * @return The UTC hour 0-23 - */ + * @return The UTC hour 0-23 + */ utcHour(): number; /** - * @return The UTC minutes 0-59 - */ + * @return The UTC minutes 0-59 + */ utcMinute(): number; /** - * @return The UTC seconds 0-59 - */ + * @return The UTC seconds 0-59 + */ utcSecond(): number; /** - * @return The UTC milliseconds 0-999 - */ + * @return The UTC milliseconds 0-999 + */ utcMillisecond(): number; /** - * Convert this date to the given time zone (in-place). - * Throws if this date does not have a time zone. - * @return this (for chaining) - */ + * @return the UTC day-of-week (the enum values correspond to JavaScript + * week day numbers) + */ + utcWeekDay(): WeekDay; + /** + * Convert this date to the given time zone (in-place). + * Throws if this date does not have a time zone. + * @return this (for chaining) + */ convert(zone?: TimeZone): DateTime; /** - * Returns this date converted to the given time zone. - * Unaware dates can only be converted to unaware dates (clone) - * For unaware dates, an exception is thrown - * @param zone The new time zone. This may be null to create unaware date. - * @return The converted date - */ + * Returns this date converted to the given time zone. + * Unaware dates can only be converted to unaware dates (clone) + * For unaware dates, an exception is thrown + * @param zone The new time zone. This may be null to create unaware date. + * @return The converted date + */ toZone(zone?: TimeZone): DateTime; /** - * Convert to JavaScript date with the zone time in the getX() methods. - * Unless the timezone is local, the Date.getUTCX() methods will NOT be correct. - */ + * Convert to JavaScript date with the zone time in the getX() methods. + * Unless the timezone is local, the Date.getUTCX() methods will NOT be correct. + */ toDate(): Date; /** - * Add a time duration. Note that this simply adds a number - * of milliseconds to UTC and converts back to zone(), - * so in the presence of e.g. leap seconds there may be a - * shift in the seconds field if you add an hour. - * There is not DST handling and no leap second handling. - * @return this + duration - */ + * Add a time duration. Note that this simply adds a number + * of milliseconds to UTC and converts back to zone(), + * so in the presence of e.g. leap seconds there may be a + * shift in the seconds field if you add an hour. + * There is not DST handling and no leap second handling. + * @return this + duration + */ add(duration: Duration): DateTime; /** - * Add an amount of time to UTC, taking leap seconds etc into account. - * Adding e.g. 1 hour will increment the utcHour() field - * date by one. In case of DST changes, the local hour() field - * may not increase or increase by 2 hours. So if you add a month, the - * local time may vary by an hour. There will not be a shift - * in seconds due to leap seconds. - */ + * Add an amount of time to UTC, taking leap seconds etc into account. + * Adding e.g. 1 hour will increment the utcHour() field + * date by one. In case of DST changes, the local hour() field + * may not increase or increase by 2 hours. So if you add a month, the + * local time may vary by an hour. There will not be a shift + * in seconds due to leap seconds. + */ add(amount: number, unit: TimeUnit): DateTime; /** - * Add an amount of time to the zone time, as regularly as possible. - * Adding e.g. 1 hour will increment the hour() field of the zone - * date by one. In case of DST changes, the utcHour() field may - * increase by 1 or increase by 2. Adding a day will leave the time portion - * intact. However, adding an hour around a forward DST change adds two hours, - * since there is a zone time (2AM in Holland) that does not exist. - */ + * Add an amount of time to the zone time, as regularly as possible. + * Adding e.g. 1 hour will increment the hour() field of the zone + * date by one. In case of DST changes, the utcHour() field may + * increase by 1 or increase by 2. Adding a day will leave the time portion + * intact. However, adding an hour around a forward DST change adds two hours, + * since there is a zone time (2AM in Holland) that does not exist. + */ addLocal(amount: number, unit: TimeUnit): DateTime; /** - * Same as add(-1*duration); - */ + * Same as add(-1*duration); + */ sub(duration: Duration): DateTime; /** - * Same as add(-1*amount, unit); - */ + * Same as add(-1*amount, unit); + */ sub(amount: number, unit: TimeUnit): DateTime; /** - * Same as addLocal(-1*amount, unit); - */ + * Same as addLocal(-1*amount, unit); + */ subLocal(amount: number, unit: TimeUnit): DateTime; /** - * Time difference between two DateTimes - * @return this - other - */ + * Time difference between two DateTimes + * @return this - other + */ diff(other: DateTime): Duration; /** - * @return True iff (this < other) - */ + * @return True iff (this < other) + */ lessThan(other: DateTime): boolean; /** - * @return True iff (this <= other) - */ + * @return True iff (this <= other) + */ lessEqual(other: DateTime): boolean; /** - * @return True iff this and other represent the same time in UTC - */ + * @return True iff this and other represent the same time in UTC + */ equals(other: DateTime): boolean; /** - * @return True iff this and other represent the same time and - * have the same zone - */ + * @return True iff this and other represent the same time and + * have the same zone + */ identical(other: DateTime): boolean; /** - * @return True iff this > other - */ + * @return True iff this > other + */ greaterThan(other: DateTime): boolean; /** - * @return True iff this >= other - */ + * @return True iff this >= other + */ greaterEqual(other: DateTime): boolean; /** - * Proper ISO 8601 format string with any IANA zone converted to ISO offset - * E.g. "2014-01-01T23:15:33+01:00" for Europe/Amsterdam - */ + * Proper ISO 8601 format string with any IANA zone converted to ISO offset + * E.g. "2014-01-01T23:15:33+01:00" for Europe/Amsterdam + */ toIsoString(): string; /** - * Modified ISO 8601 format string with IANA name if applicable. - * E.g. "2014-01-01T23:15:33.000 Europe/Amsterdam" - */ + * Modified ISO 8601 format string with IANA name if applicable. + * E.g. "2014-01-01T23:15:33.000 Europe/Amsterdam" + */ toString(): string; /** - * Modified ISO 8601 format string in UTC without time zone info - */ + * Modified ISO 8601 format string in UTC without time zone info + */ toUtcString(): string; } /** - * Specifies how the period should repeat across the day - * during DST changes. - */ + * Specifies how the period should repeat across the day + * during DST changes. + */ export enum PeriodDst { /** - * Keep repeating in similar intervals measured in UTC, - * unaffected by Daylight Saving Time. - * E.g. a repetition of one hour will take one real hour - * every time, even in a time zone with DST. - * Leap seconds, leap days and month length - * differences will still make the intervals different. - */ + * Keep repeating in similar intervals measured in UTC, + * unaffected by Daylight Saving Time. + * E.g. a repetition of one hour will take one real hour + * every time, even in a time zone with DST. + * Leap seconds, leap days and month length + * differences will still make the intervals different. + */ RegularIntervals = 0, /** - * Ensure that the time at which the intervals occur stay - * at the same place in the day, local time. So e.g. - * a period of one day, starting at 8:05AM Europe/Amsterdam time - * will always start at 8:05 Europe/Amsterdam. This means that - * in UTC time, some intervals will be 25 hours and some - * 23 hours during DST changes. - * Another example: an hourly interval will be hourly in local time, - * skipping an hour in UTC for a DST backward change. - */ + * Ensure that the time at which the intervals occur stay + * at the same place in the day, local time. So e.g. + * a period of one day, starting at 8:05AM Europe/Amsterdam time + * will always start at 8:05 Europe/Amsterdam. This means that + * in UTC time, some intervals will be 25 hours and some + * 23 hours during DST changes. + * Another example: an hourly interval will be hourly in local time, + * skipping an hour in UTC for a DST backward change. + */ RegularLocalTime = 1, } /** - * Convert a PeriodDst to a string: "regular intervals" or "regular local time" - */ + * Convert a PeriodDst to a string: "regular intervals" or "regular local time" + */ export function periodDstToString(p: PeriodDst): string; /** - * Repeating time period: consists of a starting point and - * a time length. This class accounts for leap seconds and leap days. - */ + * Repeating time period: consists of a starting point and + * a time length. This class accounts for leap seconds and leap days. + */ export class Period { /** - * Constructor - * LIMITATION: if dst equals RegularLocalTime, and unit is Second, Minute or Hour, - * then the amount must be a factor of 24. So 120 seconds is allowed while 121 seconds is not. - * This is due to the enormous processing power required by these cases. They are not - * implemented and you will get an assert. - * - * @param start The start of the period. If the period is in Months or Years, and - * the day is 29 or 30 or 31, the results are maximised to end-of-month. - * @param amount The amount of units. - * @param unit The unit. - * @param dst Specifies how to handle Daylight Saving Time. Not relevant - * if the time zone of the start datetime does not have DST. - */ + * Constructor + * LIMITATION: if dst equals RegularLocalTime, and unit is Second, Minute or Hour, + * then the amount must be a factor of 24. So 120 seconds is allowed while 121 seconds is not. + * This is due to the enormous processing power required by these cases. They are not + * implemented and you will get an assert. + * + * @param start The start of the period. If the period is in Months or Years, and + * the day is 29 or 30 or 31, the results are maximised to end-of-month. + * @param amount The amount of units. + * @param unit The unit. + * @param dst Specifies how to handle Daylight Saving Time. Not relevant + * if the time zone of the start datetime does not have DST. + */ constructor(start: DateTime, amount: number, unit: TimeUnit, dst: PeriodDst); /** - * The start date - */ + * The start date + */ start(): DateTime; /** - * The amount of units - */ + * The amount of units + */ amount(): number; /** - * The unit - */ + * The unit + */ unit(): TimeUnit; /** - * The dst handling mode - */ + * The dst handling mode + */ dst(): PeriodDst; /** - * The first occurrence of the period greater than - * the given date. The given date need not be at a period boundary. - * Pre: the fromdate and startdate must either both have timezones or not - * @param fromDate: the date after which to return the next date - * @return the first date matching the period after fromDate, given - * in the same zone as the fromDate. - */ + * The first occurrence of the period greater than + * the given date. The given date need not be at a period boundary. + * Pre: the fromdate and startdate must either both have timezones or not + * @param fromDate: the date after which to return the next date + * @return the first date matching the period after fromDate, given + * in the same zone as the fromDate. + */ findFirst(fromDate: DateTime): DateTime; /** - * Returns the next timestamp in the period. The given timestamp must - * be at a period boundary, otherwise the answer is incorrect. - * This function has MUCH better performance than findFirst. - * Returns the datetime "count" times away from the given datetime. - * @param prev Boundary date. Must have a time zone (any time zone) iff the period start date has one. - * @param count Optional, must be >= 1 and whole. - * @return (prev + count * period), in the same timezone as prev. - */ + * Returns the next timestamp in the period. The given timestamp must + * be at a period boundary, otherwise the answer is incorrect. + * This function has MUCH better performance than findFirst. + * Returns the datetime "count" times away from the given datetime. + * @param prev Boundary date. Must have a time zone (any time zone) iff the period start date has one. + * @param count Optional, must be >= 1 and whole. + * @return (prev + count * period), in the same timezone as prev. + */ findNext(prev: DateTime, count?: number): DateTime; /** - * Returns an ISO duration string - * P[n]Y[n]M[n]DT[n]H[n]M[n][.n]S or P[n]W - */ + * Returns an ISO duration string + * P[n]Y[n]M[n]DT[n]H[n]M[n][.n]S or P[n]W + */ toIsoString(): string; /** - * A string representation e.g. - * "10 years, starting at 2014-03-01T12:00:00 Europe/Amsterdam keeping regular intervals". - */ + * A string representation e.g. + * "10 years, starting at 2014-03-01T12:00:00 Europe/Amsterdam keeping regular intervals". + */ toString(): string; } } From 4596e7450b79826fb46adb5a19f8d34036ee9a16 Mon Sep 17 00:00:00 2001 From: Hendrik Maus Date: Mon, 7 Jul 2014 18:35:04 +0200 Subject: [PATCH 076/324] Add cordovarduino --- cordovarduino/cordovarduino-tests.ts | 38 +++++++++++++ cordovarduino/cordovarduino.d.ts | 84 ++++++++++++++++++++++++++++ 2 files changed, 122 insertions(+) create mode 100644 cordovarduino/cordovarduino-tests.ts create mode 100644 cordovarduino/cordovarduino.d.ts diff --git a/cordovarduino/cordovarduino-tests.ts b/cordovarduino/cordovarduino-tests.ts new file mode 100644 index 000000000..a4fd60878 --- /dev/null +++ b/cordovarduino/cordovarduino-tests.ts @@ -0,0 +1,38 @@ +/// + +serial.requestPermission(function success() {}, function error() {}); +serial.open({}, function success() {}, function error() {}); +serial.write('data_string', function success() {}, function error() {}); +serial.read(function success() {}, function error() {}); +serial.registerReadCallback( + function success(data:any) { + var view = new Uint8Array(data); + console.log(view); + }, + function error() { + new Error("Failed to register read callback"); + }); +serial.close(function success() {}, function error() {}); + +var errorCallback = function (message:string) { + alert('Error: ' + message); +}; + +serial.requestPermission( + function (successMessage:string) { + serial.open( + {baudRate: 9600}, + function (successMessage:string) { + serial.write( + '1', + function (successMessage:string) { + alert(successMessage); + }, + errorCallback + ); + }, + errorCallback + ); + }, + errorCallback +); diff --git a/cordovarduino/cordovarduino.d.ts b/cordovarduino/cordovarduino.d.ts new file mode 100644 index 000000000..bcbee1d1c --- /dev/null +++ b/cordovarduino/cordovarduino.d.ts @@ -0,0 +1,84 @@ +// Type definitions for Cordovarduino plugin. +// Project: https://github.com/stereolux/cordovarduino +// Definitions by: Hendrik Maus +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Cordovardunio { + interface Serial { + /** + * Request permission to interact with the serial port. + * + * @param successCallback Function to call on success + * @param errorCallback Function to call on error + */ + requestPermission(successCallback:Function, errorCallback:Function): void; + + /** + * Open a connection. + * + * @param opts SerialOptions object + * @param successCallback Function to call on success + * @param errorCallback Function to call on error + */ + open(opts:SerialOptions, successCallback:Function, errorCallback:Function): void + + /** + * Write to the serial port. + * + * @param data String data to write to serial port + * @param successCallback Function to call on success + * @param errorCallback Function to call on error + */ + write(data:string, successCallback:Function, errorCallback:Function): void; + + /** + * Read from the serial port. + * + * @param successCallback Function to call on success + * @param errorCallback Function to call on error + */ + read(successCallback:Function, errorCallback:Function): void; + + /** + * Close connection. + * + * @param successCallback Function to call on success + * @param errorCallback Function to call on error + */ + close(successCallback:Function, errorCallback:Function): void; + + /** + * Register a callback for the driver reading incoming data from the serial device + * + * @param successCallback Function to call on success + * @param errorCallback Function to call on error + */ + registerReadCallback(successCallback:Function, errorCallback:Function): void; + } + + interface SerialOptions { + /** + * @defaultValue 9600 + */ + baudRate?: number; + + /** + * @defaultValue 8 + */ + dataBits?: number; + + /** + * @defaultValue 1 + */ + stopBits?: number; + + /** + * @defaultValue 0 + */ + parity?: number; + } +} + + +// Plugin will be surfaced as window.serial +declare var serial:Cordovardunio.Serial; From ee15f119667280e7df2da59a8fccbb7ba3dc5d19 Mon Sep 17 00:00:00 2001 From: Hendrik Maus Date: Mon, 7 Jul 2014 18:35:37 +0200 Subject: [PATCH 077/324] Start ionic-cordova package and add keyboard plugin as a start --- cordova-ionic/cordova-ionic-tests.ts | 10 +++++++++ cordova-ionic/cordova-ionic.d.ts | 14 ++++++++++++ cordova-ionic/plugins/keyboard.d.ts | 33 ++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+) create mode 100644 cordova-ionic/cordova-ionic-tests.ts create mode 100644 cordova-ionic/cordova-ionic.d.ts create mode 100644 cordova-ionic/plugins/keyboard.d.ts diff --git a/cordova-ionic/cordova-ionic-tests.ts b/cordova-ionic/cordova-ionic-tests.ts new file mode 100644 index 000000000..69d1a3d82 --- /dev/null +++ b/cordova-ionic/cordova-ionic-tests.ts @@ -0,0 +1,10 @@ +/// +/// + +// Keyboard +cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); +cordova.plugins.Keyboard.hideKeyboardAccessoryBar(false); +cordova.plugins.Keyboard.close(); +cordova.plugins.Keyboard.disableScroll(true); +cordova.plugins.Keyboard.disableScroll(false); +console.log(cordova.plugins.Keyboard.isVisible); diff --git a/cordova-ionic/cordova-ionic.d.ts b/cordova-ionic/cordova-ionic.d.ts new file mode 100644 index 000000000..892d487cf --- /dev/null +++ b/cordova-ionic/cordova-ionic.d.ts @@ -0,0 +1,14 @@ +// Type definitions for Ionic Corodva plugins. +// Project: https://github.com/driftyco +// Definitions by: Hendrik Maus +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface Cordova { + plugins:Plugins; +} + +interface Plugins { + Keyboard:Ionic.Keyboard; +} diff --git a/cordova-ionic/plugins/keyboard.d.ts b/cordova-ionic/plugins/keyboard.d.ts new file mode 100644 index 000000000..b992887fa --- /dev/null +++ b/cordova-ionic/plugins/keyboard.d.ts @@ -0,0 +1,33 @@ +// Type definitions for Cordova Keyboard plugin. +// Project: https://github.com/driftyco/ionic-plugins-keyboard +// Definitions by: Hendrik Maus +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Ionic { + interface Keyboard { + + /** + * Hide the keyboard accessory bar with the next, previous and done buttons. + * + * @param hide + */ + hideKeyboardAccessoryBar(hide:boolean): void; + + /** + * Close the keyboard if it is open. + */ + close(): void; + + /** + * Disable native scrolling, useful if you are using JavaScript to scroll + * + * @param disbale + */ + disableScroll(disbale:boolean): void; + + /** + * Whether or not the keyboard is currently visible. + */ + isVisible: boolean; + } +} From 7b06ef774071b0e1318d2c5429344959c005c11c Mon Sep 17 00:00:00 2001 From: Hendrik Maus Date: Mon, 7 Jul 2014 18:43:41 +0200 Subject: [PATCH 078/324] Run `npm test` and fix files to pass tests --- cordova-ionic/cordova-ionic.d.ts | 4 ++-- cordova-ionic/plugins/keyboard.d.ts | 4 ++-- cordovarduino/cordovarduino.d.ts | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/cordova-ionic/cordova-ionic.d.ts b/cordova-ionic/cordova-ionic.d.ts index 892d487cf..c9b1e635b 100644 --- a/cordova-ionic/cordova-ionic.d.ts +++ b/cordova-ionic/cordova-ionic.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Ionic Corodva plugins. +// Type definitions for Ionic Cordova plugins // Project: https://github.com/driftyco -// Definitions by: Hendrik Maus +// Definitions by: Hendrik Maus // Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/cordova-ionic/plugins/keyboard.d.ts b/cordova-ionic/plugins/keyboard.d.ts index b992887fa..4ff9e293d 100644 --- a/cordova-ionic/plugins/keyboard.d.ts +++ b/cordova-ionic/plugins/keyboard.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Cordova Keyboard plugin. +// Type definitions for Cordova Keyboard plugin // Project: https://github.com/driftyco/ionic-plugins-keyboard -// Definitions by: Hendrik Maus +// Definitions by: Hendrik Maus // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module Ionic { diff --git a/cordovarduino/cordovarduino.d.ts b/cordovarduino/cordovarduino.d.ts index bcbee1d1c..0fccff2ad 100644 --- a/cordovarduino/cordovarduino.d.ts +++ b/cordovarduino/cordovarduino.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Cordovarduino plugin. +// Type definitions for Cordovarduino plugin // Project: https://github.com/stereolux/cordovarduino -// Definitions by: Hendrik Maus +// Definitions by: Hendrik Maus // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module Cordovardunio { From 1b1b0b38eb153c636ed8336f84e358de6db216de Mon Sep 17 00:00:00 2001 From: Hendrik Maus Date: Mon, 7 Jul 2014 18:53:34 +0200 Subject: [PATCH 079/324] Add myself to the list of contributors --- CONTRIBUTORS.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index c645bca65..723bb1d2b 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -49,6 +49,7 @@ All definitions files include a header with the author and editors, so at some p * [Commander](http://github.com/visionmedia/commander.js) (by [Marcelo Dezem](https://github.com/mdezem)) * [configstore](http://github.com/yeoman/configstore) (by [Bart van der Schoor](https://github.com/Bartvds)) * [Cordova](http://cordova.apache.org) (by [Microsoft Open Technologies, Inc.](http://msopentech.com/)) +* [Cordovarduino](https://github.com/stereolux/cordovarduino) (by [Hendrik Maus](https://github.com/hendrikmaus)) * [Couchbase / Couchnode](https://github.com/couchbase/couchnode) (by [Basarat Ali Syed](https://github.com/basarat)) * [Crossfilter](https://github.com/square/crossfilter) (by [Schmulik Raskin](https://github.com/schmuli)) * [crypto-js](https://code.google.com/p/crypto-js/) (by [Gia Bảo @ Sân Đình](https://github.com/giabao)). @see [cryptojs.d.ts repo](https://github.com/giabao/cryptojs.d.ts) @@ -122,6 +123,7 @@ All definitions files include a header with the author and editors, so at some p * [iCheck](http://damirfoy.com/iCheck/) (by [Dániel Tar](https://github.com/qcz)) * [Impress.js](https://github.com/bartaz/impress.js) (by [Boris Yankov](https://github.com/borisyankov)) * [Imagemagick](http://github.com/rsms/node-imagemagick) (by [Carlos Ballesteros Velasco](https://github.com/soywiz)) +* [Ionic-Cordova](https://github.com/driftyco/) (by [Hendrik Maus](https://github.com/hendrikmaus)) * [iScroll](http://cubiq.org/iscroll-4) (by [Boris Yankov](https://github.com/borisyankov) and [Christiaan Rakowski](https://github.com/csrakowski)) * [IxJS (Interactive extensions)](https://github.com/Reactive-Extensions/IxJS) (by [Igor Oleinikov](https://github.com/Igorbek)) * [jake](https://github.com/mde/jake) (by [Kon](http://phyzkit.net/)) From 2646c36929495221dc4295b5b387c5eb931e6525 Mon Sep 17 00:00:00 2001 From: Sean Xu Date: Mon, 7 Jul 2014 12:51:19 -0700 Subject: [PATCH 080/324] Moved released versions into the root folder. --- winjs/{releases => }/winjs-1.0.d.ts | 0 winjs/{releases => }/winjs-2.0.d.ts | 0 winjs/{releases => }/winjs-2.1.d.ts | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename winjs/{releases => }/winjs-1.0.d.ts (100%) rename winjs/{releases => }/winjs-2.0.d.ts (100%) rename winjs/{releases => }/winjs-2.1.d.ts (100%) diff --git a/winjs/releases/winjs-1.0.d.ts b/winjs/winjs-1.0.d.ts similarity index 100% rename from winjs/releases/winjs-1.0.d.ts rename to winjs/winjs-1.0.d.ts diff --git a/winjs/releases/winjs-2.0.d.ts b/winjs/winjs-2.0.d.ts similarity index 100% rename from winjs/releases/winjs-2.0.d.ts rename to winjs/winjs-2.0.d.ts diff --git a/winjs/releases/winjs-2.1.d.ts b/winjs/winjs-2.1.d.ts similarity index 100% rename from winjs/releases/winjs-2.1.d.ts rename to winjs/winjs-2.1.d.ts From 750cb6d14e179a7b469bce13f4a68bf6c55b84cc Mon Sep 17 00:00:00 2001 From: Jozef Izso Date: Mon, 7 Jul 2014 23:14:55 +0200 Subject: [PATCH 081/324] Updated async.queue definitions to v0.9.0 --- async/async-tests.ts | 47 +++++++++++++++++++++++++++++++++++++++++--- async/async.d.ts | 15 +++++++++++--- 2 files changed, 56 insertions(+), 6 deletions(-) diff --git a/async/async-tests.ts b/async/async-tests.ts index 169bc9cb1..9b0c8e7ee 100644 --- a/async/async-tests.ts +++ b/async/async-tests.ts @@ -145,9 +145,8 @@ q.drain = function () { console.log('all items have been processed'); } -q.push({ name: 'foo' }, function (err) { - console.log('finished processing foo'); -}); +q.push({ name: 'foo' }); + q.push({ name: 'bar' }, function (err) { console.log('finished processing bar'); }); @@ -156,6 +155,38 @@ q.push([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (err) { console.log('finished processing bar'); }); +q.unshift({ name: 'foo' }); + +q.unshift({ name: 'bar' }, function (err) { + console.log('finished processing bar'); +}); + +q.unshift([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (err) { + console.log('finished processing bar'); +}); + +var qLength : number = q.length(); +var qStarted : boolean = q.started; +var qPaused : boolean = q.paused; +var qProcessingCount : number = q.running(); +var qIsIdle : boolean = q.idle(); + +q.saturated = function() { + console.log('queue is saturated.'); +} + +q.empty = function() { + console.log('queue is empty.'); +} + +q.drain = function() { + console.log('queue was drained.'); +} + +q.pause(); +q.resume(); +q.kill(); + // tests for strongly typed tasks var q2 = async.queue(function (task: string, callback) { console.log('Task: ' + task); @@ -172,6 +203,16 @@ q2.push(['task3', 'task4', 'task5'], function (error, results: string[]) { console.log('Finished tasks: ' + results.join(', ')); }); +q2.unshift('task1'); + +q2.unshift('task2', function (error, results: string[]) { + console.log('Finished tasks: ' + results.join(', ')); +}); + +q2.unshift(['task3', 'task4', 'task5'], function (error, results: string[]) { + console.log('Finished tasks: ' + results.join(', ')); +}); + var filename = ''; async.auto({ get_data: function (callback) { }, diff --git a/async/async.d.ts b/async/async.d.ts index 25736941f..d1d592629 100644 --- a/async/async.d.ts +++ b/async/async.d.ts @@ -15,11 +15,20 @@ interface AsyncWorker { (task: T, callback: Function): void; } interface AsyncQueue { length(): number; concurrency: number; + started: boolean; + paused: boolean; push(task: T, callback?: AsyncMultipleResultsCallback): void; push(task: T[], callback?: AsyncMultipleResultsCallback): void; - saturated: AsyncMultipleResultsCallback; - empty: AsyncMultipleResultsCallback; - drain: AsyncMultipleResultsCallback; + unshift(task: T, callback?: AsyncMultipleResultsCallback): void; + unshift(task: T[], callback?: AsyncMultipleResultsCallback): void; + saturated: () => any; + empty: () => any; + drain: () => any; + running(): number; + idle(): boolean; + pause(): void; + resume(): void; + kill(): void; } interface Async { From e259b160937319e9b7c43a098c9b7667647e5d42 Mon Sep 17 00:00:00 2001 From: dsuket Date: Tue, 8 Jul 2014 08:35:06 +0900 Subject: [PATCH 082/324] fixed bug. change Collection.collection to Model.collection --- backbone/backbone-tests.ts | 8 ++++++++ backbone/backbone.d.ts | 3 ++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/backbone/backbone-tests.ts b/backbone/backbone-tests.ts index bf44c56f7..6b40bb509 100644 --- a/backbone/backbone-tests.ts +++ b/backbone/backbone-tests.ts @@ -140,6 +140,14 @@ function test_collection() { var alphabetical = books.sortBy((book: Book): number => { return null; }); + + var model: Book = new Book({title: "Test", author: "Mike"}); + books.add(model); + var model2: Book = model.collection.first(); + if (model !== model2) { + throw new Error("Error"); + } + } ////////// diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index b58c4652f..db104f480 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -95,6 +95,8 @@ declare module Backbone { attributes: any; changed: any[]; cid: string; + collection: Collection; + /** * Default attributes for the model. It can be an object hash or a method returning an object hash. * For assigning an object hash, do it like this: this.defaults = { attribute: value, ... }; @@ -156,7 +158,6 @@ declare module Backbone { //model: typeof TModel; model: { new(): TModel; }; // workaround models: TModel[]; - collection: TModel; length: number; constructor(models?: TModel[], options?: any); From b5acb56359b426fd4410fc491add9cda01da16e3 Mon Sep 17 00:00:00 2001 From: Rogier Schouten Date: Tue, 8 Jul 2014 11:58:11 +0200 Subject: [PATCH 083/324] Improve Node dgram signatures. --- node/node-tests.ts | 15 ++++++++++++++- node/node.d.ts | 16 ++++++++++++++-- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/node/node-tests.ts b/node/node-tests.ts index c36f0da1e..e9ef58dbb 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -9,6 +9,7 @@ import util = require("util"); import crypto = require("crypto"); import http = require("http"); import net = require("net"); +import dgram = require("dgram"); assert(1 + 1 - 2 === 0, "The universe isn't how it should."); @@ -109,4 +110,16 @@ module http_tests { var code = 100; var codeMessage = http.STATUS_CODES['400']; var codeMessage = http.STATUS_CODES[400]; -} \ No newline at end of file +} + +//////////////////////////////////////////////////// +/// Dgram tests : http://nodejs.org/api/dgram.html +//////////////////////////////////////////////////// + +var ds: dgram.Socket = dgram.createSocket("udp4", (msg: Buffer, rinfo: dgram.RemoteInfo): void => { +}); +var ai: dgram.AddressInfo = ds.address(); +ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { +}); + + diff --git a/node/node.d.ts b/node/node.d.ts index af61b3df8..d7c06203b 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -760,13 +760,25 @@ declare module "net" { declare module "dgram" { import events = require("events"); - export function createSocket(type: string, callback?: Function): Socket; + interface RemoteInfo { + address: string; + port: number; + size: number; + } + + interface AddressInfo { + address: string; + family: string; + port: number; + } + + export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; interface Socket extends events.EventEmitter { send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; bind(port: number, address?: string, callback?: () => void): void; close(): void; - address: { address: string; family: string; port: number; }; + address(): AddressInfo; setBroadcast(flag: boolean): void; setMulticastTTL(ttl: number): void; setMulticastLoopback(flag: boolean): void; From a795ca109da0fc41095a0bbebb7303b1bda92bbc Mon Sep 17 00:00:00 2001 From: SHTrassEr Date: Tue, 8 Jul 2014 23:45:28 +0900 Subject: [PATCH 084/324] Add IPackage interface, fix IPackageManager --- atom/atom.d.ts | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/atom/atom.d.ts b/atom/atom.d.ts index 1b5e55f2a..e19e70ab6 100644 --- a/atom/atom.d.ts +++ b/atom/atom.d.ts @@ -941,6 +941,19 @@ declare module AtomCore { // TBD } + interface IPackage { + enable(): void; + disable(): void; + isTheme(): boolean; + getType(): string; + getStylesheetType(): string; + load(): IPackage; + reset(): void; + activate(): Q.Promise; + activateNow(): void; + // TBD + } + interface IPackageManager extends Emissary.IEmitter { packageDirPaths:string[]; loadedPackages:any; @@ -957,7 +970,7 @@ declare module AtomCore { activate():void; registerPackageActivator(activator:any, types:any):void; activatePackages(packages:any):void; - activatePackage(name:string):void; + activatePackage(name:string):Q.Promise; deactivatePackages():void; deactivatePackage(name:string):void; getActivePackages():any; @@ -1010,14 +1023,14 @@ declare module AtomCore { interface IAtomStatic extends ISerializationStatic { version: number; loadSettings: IAtomSettings; - + /* Load or create the Atom environment in the given mode */ loadOrCreate(mode:'editor'):IAtom; /* Load or create the Atom environment in the given mode */ loadOrCreate(mode:'spec'):IAtom; /* Load or create the Atom environment in the given mode */ loadOrCreate(mode:string):IAtom; - + loadState(mode:any):void; getStatePath(mode:any):string; getConfigDirPath():string; From ddd01efbe94a9d44d07cab80adde959ae350c534 Mon Sep 17 00:00:00 2001 From: Austin Brunkhorst Date: Tue, 8 Jul 2014 13:48:05 -0700 Subject: [PATCH 085/324] Fix isImmediatePropagationStopped() typo. isImmediatePropogationStopped -> isImmediatePropagationStopped --- jquery/jquery.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index 55f3dc0c8..ad60f9670 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -545,7 +545,7 @@ interface BaseJQueryEventObject extends Event { data: any; delegateTarget: Element; isDefaultPrevented(): boolean; - isImmediatePropogationStopped(): boolean; + isImmediatePropagationStopped(): boolean; isPropagationStopped(): boolean; namespace: string; preventDefault(): any; From 935a7a1cc2025110643c867bba9ebbdbd6f4ca80 Mon Sep 17 00:00:00 2001 From: Izzy Cecil Date: Tue, 8 Jul 2014 20:05:15 -0600 Subject: [PATCH 086/324] Made D3Events inherit from lib.d.ts Event interface. --- d3/d3.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 3ab571b87..7cb854a85 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -42,14 +42,14 @@ declare module D3 { }; } - export interface Event { + export interface D3Event extends Event{ dx: number; dy: number; clientX: number; clientY: number; translate: number[]; scale: number; - sourceEvent: Event; + sourceEvent: D3Event; x: number; y: number; keyCode: number; @@ -65,7 +65,7 @@ declare module D3 { /** * Access the current user event for interaction */ - event: Event; + event: D3Event; /** * Compare two values for sorting. From 994c3dcd66bd8ccbcb8b04fe7aa065fad43e05ce Mon Sep 17 00:00:00 2001 From: Lior Mualem Date: Wed, 9 Jul 2014 10:23:20 +0300 Subject: [PATCH 087/324] Added definition for passport-strategy module. --- CONTRIBUTORS.md | 1 + passport-strategy/passport-strategy.d.ts | 98 ++++++++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 passport-strategy/passport-strategy.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 723bb1d2b..917645686 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -253,6 +253,7 @@ All definitions files include a header with the author and editors, so at some p * [OpenLayers](https://github.com/openlayers/openlayers) (by [Ilya Bolkhovsky](https://github.com/bolhovsky/)) * [Optimist](https://github.com/substack/node-optimist) (by [Carlos Ballesteros Velasco](https://github.com/soywiz)) * [Passport](http://passportjs.org/) (by [Hiroki Horiuchi](https://github.com/horiuchi/)) +* [passport-strategy](http://passportjs.org/) (by [Lior Mualem](https://github.com/liorm)) * [pathwatcher](http://atom.github.io/node-pathwatcher/) (by [vvakame](https://github.com/vvakame)) * [Parallel.js](https://github.com/adambom/parallel.js) (by [Josh Baldwin](https://github.com/jbaldwin)) * [Parsimmon](https://github.com/jayferd/parsimmon) (by [Bart van der Schoor](https://github.com/Bartvds)) diff --git a/passport-strategy/passport-strategy.d.ts b/passport-strategy/passport-strategy.d.ts new file mode 100644 index 000000000..da8b9db8e --- /dev/null +++ b/passport-strategy/passport-strategy.d.ts @@ -0,0 +1,98 @@ +// Type definitions for Passport v0.2.0 Strategy module. +// Project: http://passportjs.org +// Definitions by: Lior Mualem +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +/** + * Using this module, one can easily implement a strategy using typescript by + * inheriting the 'Strategy' class and reimplementing the 'authenticate' method. + */ + +declare module 'passport-strategy' { + + import passport = require('passport'); + import express = require('express'); + + class Strategy implements passport.Strategy { + /** + * Performs authentication for the request. + * Note: Virtual function - re-implement in the strategy. + * @param req The request to authenticate. + * @param options Options passed to the strategy. + */ + authenticate(req: express.Request, options?: any): void; + + // + // Augmented strategy functions. + // These are available only from the 'authenticate' function. + // They are added manually by the passport framework. + // + + /** + * Authenticate `user`, with optional `info`. + * + * Strategies should call this function to successfully authenticate a + * user. `user` should be an object supplied by the application after it + * has been given an opportunity to verify credentials. `info` is an + * optional argument containing additional user information. This is + * useful for third-party authentication strategies to pass profile + * details. + * + * @param {Object} user + * @param {Object} info + * @api public + */ + success(user: any, info: any): void; + + /** + * Fail authentication, with optional `challenge` and `status`, defaulting + * to 401. + * + * Strategies should call this function to fail an authentication attempt. + * + * @param {String} challenge (Can also be an object with 'message' and 'type' fields). + * @param {Number} status + * @api public + */ + fail(challenge: any, status: number): void; + fail(status: number): void; + + /** + * Redirect to `url` with optional `status`, defaulting to 302. + * + * Strategies should call this function to redirect the user (via their + * user agent) to a third-party website for authentication. + * + * @param {String} url + * @param {Number} status + * @api public + */ + redirect(url: string, status?: number): void; + + /** + * Pass without making a success or fail decision. + * + * Under most circumstances, Strategies should not need to call this + * function. It exists primarily to allow previous authentication state + * to be restored, for example from an HTTP session. + * + * @api public + */ + pass(): void; + + /** + * Internal error while performing authentication. + * + * Strategies should call this function when an internal error occurs + * during the process of performing authentication; for example, if the + * user directory is not available. + * + * @param {Error} err + * @api public + */ + error(err: Error): void; + } +} From 2845495b23ba7b33c434cd61a13678c2709022dc Mon Sep 17 00:00:00 2001 From: Lior Mualem Date: Wed, 9 Jul 2014 10:23:35 +0300 Subject: [PATCH 088/324] Added tests for passport-strategy module. --- passport-strategy/passport-strategy-test.ts | 48 +++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 passport-strategy/passport-strategy-test.ts diff --git a/passport-strategy/passport-strategy-test.ts b/passport-strategy/passport-strategy-test.ts new file mode 100644 index 000000000..e9c6fd604 --- /dev/null +++ b/passport-strategy/passport-strategy-test.ts @@ -0,0 +1,48 @@ + +import express = require('express'); +import passport = require('passport-strategy'); + + +export class Strategy extends passport.Strategy { + constructor(options: any, verify?: Function) { + if (typeof options == 'function') { + verify = options; + options = {}; + } + if (!verify) { + throw new TypeError('DummyStrategy requires a verify callback'); + } + + super(); + + this.name = 'dummy'; + this._verify = verify; + this._passReqToCallback = options.passReqToCallback; + } + + name: string; + + _verify: Function; + _passReqToCallback: boolean; + + authenticate(req: express.Request, options?: any): void { + options = options || {}; + + // Test fail method. + this.fail({ message: options.missingTokenMessage || 'Missing token' }, 400); + + var self = this; + + function verified(err: Error, user: any, info: any) { + if (err) { + return self.error(err); + } + if (!user) { + return self.fail(info); + } + self.success(user, info); + } + + verified(null, {}, {}); + } +} From 18f6be190d00cd4dbe60b48d81a226de5c69fee9 Mon Sep 17 00:00:00 2001 From: Lior Mualem Date: Wed, 9 Jul 2014 10:31:28 +0300 Subject: [PATCH 089/324] Fixed test syntax errors. --- passport-strategy/passport-strategy.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/passport-strategy/passport-strategy.d.ts b/passport-strategy/passport-strategy.d.ts index da8b9db8e..2e5d0e309 100644 --- a/passport-strategy/passport-strategy.d.ts +++ b/passport-strategy/passport-strategy.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Passport v0.2.0 Strategy module. +// Type definitions for Passport Strategy module v0.2.0 // Project: http://passportjs.org // Definitions by: Lior Mualem // Definitions: https://github.com/borisyankov/DefinitelyTyped From 5e885cd60fc1d14489bec687b678bfbd96fd693c Mon Sep 17 00:00:00 2001 From: Maxim Efremov Date: Wed, 9 Jul 2014 13:00:04 +0400 Subject: [PATCH 090/324] d3.js: Improve D3.Svg.Symbol --- d3/d3.d.ts | 1 + 1 file changed, 1 insertion(+) mode change 100644 => 100755 d3/d3.d.ts diff --git a/d3/d3.d.ts b/d3/d3.d.ts old mode 100644 new mode 100755 index 7cb854a85..598cd9f34 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -1620,6 +1620,7 @@ declare module D3 { export interface Symbol { type: (string:string) => Symbol; size: (number:number) => Symbol; + (datum:any, index:number): string; } export interface Brush { From 153a630fd19762bc890cf0c7bb7ebec8f9c05341 Mon Sep 17 00:00:00 2001 From: SHTrassEr Date: Wed, 9 Jul 2014 21:50:17 +0900 Subject: [PATCH 091/324] add main module to package --- atom/atom.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/atom/atom.d.ts b/atom/atom.d.ts index e19e70ab6..67c30f788 100644 --- a/atom/atom.d.ts +++ b/atom/atom.d.ts @@ -942,6 +942,8 @@ declare module AtomCore { } interface IPackage { + mainModulePath: string; + mainModule: any; enable(): void; disable(): void; isTheme(): boolean; From e579babc1d074f7d06f700b69f3b4eb32333bd4c Mon Sep 17 00:00:00 2001 From: SHTrassEr Date: Wed, 9 Jul 2014 21:57:32 +0900 Subject: [PATCH 092/324] fix indent --- atom/atom.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/atom/atom.d.ts b/atom/atom.d.ts index 67c30f788..00f55ef02 100644 --- a/atom/atom.d.ts +++ b/atom/atom.d.ts @@ -944,7 +944,7 @@ declare module AtomCore { interface IPackage { mainModulePath: string; mainModule: any; - enable(): void; + enable(): void; disable(): void; isTheme(): boolean; getType(): string; From ff9365dc084d64c948e9c4276291ba0a25c0d006 Mon Sep 17 00:00:00 2001 From: Steven Date: Wed, 9 Jul 2014 16:08:20 -0700 Subject: [PATCH 093/324] Fix interface for getIdxById in SlickGrid It is clear by the name of this method that it takes an id (string) and returns and index (number). --- slickgrid/SlickGrid.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/slickgrid/SlickGrid.d.ts b/slickgrid/SlickGrid.d.ts index 9e66b9647..4c75fbf1f 100644 --- a/slickgrid/SlickGrid.d.ts +++ b/slickgrid/SlickGrid.d.ts @@ -1539,7 +1539,7 @@ declare module Slick { */ public expandGroup(...varArgs: string[]): void; public getGroups(): Group[]; - public getIdxById(): string; + public getIdxById(string): number; public getRowById(): T; public getItemById(id: any): T; public getItemByIdx(): T; From ea9eedcc07d475b1a2adbe8bc1477812d9fa7248 Mon Sep 17 00:00:00 2001 From: Steven Date: Wed, 9 Jul 2014 16:18:23 -0700 Subject: [PATCH 094/324] Added test for getIdxById --- slickgrid/SlickGrid-tests.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/slickgrid/SlickGrid-tests.ts b/slickgrid/SlickGrid-tests.ts index 1b41d1a0b..50db88b52 100644 --- a/slickgrid/SlickGrid-tests.ts +++ b/slickgrid/SlickGrid-tests.ts @@ -196,3 +196,7 @@ grid.setCellCssStyles("test", { } }); +// Begin DataView tests +var dataView = new Slick.Data.DataView(); +var gridWithDataView = new Slick.Grid('#grid2', dataView, columns, options); +dataView.getIdxById('foo') + 5; From e448b8cbf60872f5876179f30c9bb004d8465a3c Mon Sep 17 00:00:00 2001 From: Steven Date: Wed, 9 Jul 2014 16:31:41 -0700 Subject: [PATCH 095/324] Changed to explicit ID parameter --- slickgrid/SlickGrid.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/slickgrid/SlickGrid.d.ts b/slickgrid/SlickGrid.d.ts index 4c75fbf1f..90aa9cf13 100644 --- a/slickgrid/SlickGrid.d.ts +++ b/slickgrid/SlickGrid.d.ts @@ -1539,7 +1539,7 @@ declare module Slick { */ public expandGroup(...varArgs: string[]): void; public getGroups(): Group[]; - public getIdxById(string): number; + public getIdxById(id: string): number; public getRowById(): T; public getItemById(id: any): T; public getItemByIdx(): T; From 05545a15867f0c12ca7d1d7154cc26bf16796cae Mon Sep 17 00:00:00 2001 From: vvakame Date: Thu, 10 Jul 2014 14:10:22 +0900 Subject: [PATCH 096/324] restore cheerio.d.ts's 1st author --- cheerio/cheerio.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cheerio/cheerio.d.ts b/cheerio/cheerio.d.ts index f0bf372f4..df5058f20 100644 --- a/cheerio/cheerio.d.ts +++ b/cheerio/cheerio.d.ts @@ -1,5 +1,6 @@ // Type definitions for Cheerio v0.17.0 // Project: https://github.com/cheeriojs/cheerio +// Definitions by: Bret Little // Definitions by: VILIC VANE // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -207,4 +208,4 @@ interface CheerioElement { declare module "cheerio" { export function load(html: string, options?: CheerioOptionsInterface): CheerioStatic; -} \ No newline at end of file +} From fd0af903c6bffde5a69b07376e9d3fc9de67f84e Mon Sep 17 00:00:00 2001 From: Lior Mualem Date: Thu, 10 Jul 2014 09:16:22 +0300 Subject: [PATCH 097/324] Updated passport-strategy website. --- CONTRIBUTORS.md | 2 +- passport-strategy/passport-strategy.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 917645686..10134afd5 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -253,7 +253,7 @@ All definitions files include a header with the author and editors, so at some p * [OpenLayers](https://github.com/openlayers/openlayers) (by [Ilya Bolkhovsky](https://github.com/bolhovsky/)) * [Optimist](https://github.com/substack/node-optimist) (by [Carlos Ballesteros Velasco](https://github.com/soywiz)) * [Passport](http://passportjs.org/) (by [Hiroki Horiuchi](https://github.com/horiuchi/)) -* [passport-strategy](http://passportjs.org/) (by [Lior Mualem](https://github.com/liorm)) +* [passport-strategy](https://github.com/jaredhanson/passport-strategy) (by [Lior Mualem](https://github.com/liorm)) * [pathwatcher](http://atom.github.io/node-pathwatcher/) (by [vvakame](https://github.com/vvakame)) * [Parallel.js](https://github.com/adambom/parallel.js) (by [Josh Baldwin](https://github.com/jbaldwin)) * [Parsimmon](https://github.com/jayferd/parsimmon) (by [Bart van der Schoor](https://github.com/Bartvds)) diff --git a/passport-strategy/passport-strategy.d.ts b/passport-strategy/passport-strategy.d.ts index 2e5d0e309..36036f54b 100644 --- a/passport-strategy/passport-strategy.d.ts +++ b/passport-strategy/passport-strategy.d.ts @@ -1,5 +1,5 @@ // Type definitions for Passport Strategy module v0.2.0 -// Project: http://passportjs.org +// Project: https://github.com/jaredhanson/passport-strategy // Definitions by: Lior Mualem // Definitions: https://github.com/borisyankov/DefinitelyTyped From 279ca5b760655ece3bb893c3a608177c8ef7f48a Mon Sep 17 00:00:00 2001 From: KATO Kanryu Date: Thu, 10 Jul 2014 15:17:05 +0900 Subject: [PATCH 098/324] add SpriteSheetExporter, etc.. --- jsfl/jsfl.d.ts | 42 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/jsfl/jsfl.d.ts b/jsfl/jsfl.d.ts index a8c9911d2..5ef860e85 100644 --- a/jsfl/jsfl.d.ts +++ b/jsfl/jsfl.d.ts @@ -466,8 +466,9 @@ interface FlashDocument { id: number; // A unique integer (assigned automatically) that library: FlashLibrary; // Read-only; the library object for a document. livePreview: boolean; // A Boolean value that specifies if Live Preview is - name: number; // Read-only; a string that represents the name of a - path: number; // Read-only; a string that represents the path of the + name: string; // Read-only; a string that represents the name of a + path: string; // Read-only; a string that represents the path of the + pathURI: string; // Read-only property; a string that represents the path of the document, expressed as a file:/// URI. If the document has never been saved, this property is undefined. publishProfiles: string[]; // Read-only; an array of the publish profile names for /** Read-only; the current ScreenOutline object for the */ @@ -1146,6 +1147,8 @@ interface FlashTimeline { /** A string that represents the name of the current */ name: string; + + libraryItem:FlashItem; } interface FlashPath { @@ -1271,9 +1274,42 @@ interface FlashTools { toolObjs; } +declare class SpriteSheetExporter { + addBitmap(item:FlashItem); + addSymbol(item:FlashItem, name?:string, beginFrame?:number, endFrame?:number); + algorithm:string; + allowRotate:boolean; + allowTrimming:boolean; + app:string; + autoSize:boolean; + beginExport(); + borderPadding:number; + canBorderPad:boolean; + canRotate:boolean; + canTrim:boolean; + canShapePad:boolean; + canStackDuplicateFrames:boolean; + changeSymbol(); + exportSpriteSheet(fileURL:string,option:Object,writeMetaData?:boolean):string; + format:string; + image:string; + layoutFormat:string; + maxSheetHeight:number; + maxSheetWidth:number; + overflowed:boolean; + removeBitmap(); + removeSymbol(); + shapePadding:number; + sheetHeight:number; + sheetWidth:number; + stackDuplicateFrames:boolean; + version:string; +} + + interface FlashFL { addEventListener(eventType, callbackFunction); - browseForFileURL(browseType, title?, previewArea?); + browseForFileURL(browseType, title?, previewArea?, fileFilter?); browseForFolderURL(description: string); clearPublishCache(): void; clipCopyString(string: string): void; From 464e0ee49e695da744016fccb8cb4ca3da373a28 Mon Sep 17 00:00:00 2001 From: Saftpresse99 Date: Thu, 10 Jul 2014 11:11:06 +0200 Subject: [PATCH 099/324] Rename ITranslatePartialLoader into ITranslatePartialLoaderService --- angular-translate/angular-translate.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts index 6f5c9ca06..4401b1309 100644 --- a/angular-translate/angular-translate.d.ts +++ b/angular-translate/angular-translate.d.ts @@ -7,7 +7,7 @@ declare module ng.translate { - interface ITranslatePartialLoader{ + interface ITranslatePartialLoaderService { addPart(name: string): ITranslatePartialLoader; deletePart(name: string, removeData?: boolean): ITranslatePartialLoader; isPartAvailable(name: string): boolean; From 3edc940cc11ab098f716d3864975cddd269e4337 Mon Sep 17 00:00:00 2001 From: Saftpresse99 Date: Thu, 10 Jul 2014 11:16:20 +0200 Subject: [PATCH 100/324] Rename addPart and deletePart return value --- angular-translate/angular-translate.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts index 4401b1309..ddb568a15 100644 --- a/angular-translate/angular-translate.d.ts +++ b/angular-translate/angular-translate.d.ts @@ -8,8 +8,8 @@ declare module ng.translate { interface ITranslatePartialLoaderService { - addPart(name: string): ITranslatePartialLoader; - deletePart(name: string, removeData?: boolean): ITranslatePartialLoader; + addPart(name: string): ITranslatePartialLoaderService; + deletePart(name: string, removeData?: boolean): ITranslatePartialLoaderService; isPartAvailable(name: string): boolean; } From 9d7f8f967d5b1a2860b6254333c21cf699517646 Mon Sep 17 00:00:00 2001 From: Ciel Date: Thu, 10 Jul 2014 10:52:50 -0500 Subject: [PATCH 101/324] Updated "then" within interface JQueryXHR Updated "then" within the JQueryXHR interface - details are visible here: https://github.com/borisyankov/DefinitelyTyped/issues/2492 Sorry if this isn't the right way. This is my very first pull request. --- jquery/jquery.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index ad60f9670..59159a188 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -176,7 +176,7 @@ interface JQueryXHR extends XMLHttpRequest, JQueryPromise { /** * Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details. */ - then(doneCallback: (data: any, textStatus: string, jqXHR: JQueryXHR) => void, failCallback: (jqXHR: JQueryXHR, textStatus: string, errorThrown: any) => void): JQueryPromise; + then(doneCallback: (data: any, textStatus: string, jqXHR: JQueryXHR) => void, failCallback?: (jqXHR: JQueryXHR, textStatus: string, errorThrown: any) => void): JQueryPromise; /** * Property containing the parsed response if the response Content-Type is json */ From 54e460e2165670374f3440be4972fd06be9e2b8c Mon Sep 17 00:00:00 2001 From: Bart van der Schoor Date: Fri, 11 Jul 2014 07:37:05 +0200 Subject: [PATCH 102/324] fixed bufferlist --- bl/bl-tests.ts | 56 +++++++++++++++++++++++++------------------------- bl/bl.d.ts | 28 ++++++++++++------------- 2 files changed, 42 insertions(+), 42 deletions(-) diff --git a/bl/bl-tests.ts b/bl/bl-tests.ts index 96bfb8e3b..b8435911d 100644 --- a/bl/bl-tests.ts +++ b/bl/bl-tests.ts @@ -38,31 +38,31 @@ str = bl.toString(); num = bl.length; -buffer = bl.readDoubleBE(offset, noAssert); -buffer = bl.readDoubleBE(offset); -buffer = bl.readDoubleLE(offset, noAssert); -buffer = bl.readDoubleLE(offset); -buffer = bl.readFloatBE(offset, noAssert); -buffer = bl.readFloatBE(offset); -buffer = bl.readFloatLE(offset, noAssert); -buffer = bl.readFloatLE(offset); -buffer = bl.readInt32BE(offset, noAssert); -buffer = bl.readInt32BE(offset); -buffer = bl.readInt32LE(offset, noAssert); -buffer = bl.readInt32LE(offset); -buffer = bl.readUInt32BE(offset, noAssert); -buffer = bl.readUInt32BE(offset); -buffer = bl.readUInt32LE(offset, noAssert); -buffer = bl.readUInt32LE(offset); -buffer = bl.readInt16BE(offset, noAssert); -buffer = bl.readInt16BE(offset); -buffer = bl.readInt16LE(offset, noAssert); -buffer = bl.readInt16LE(offset); -buffer = bl.readUInt16BE(offset, noAssert); -buffer = bl.readUInt16BE(offset); -buffer = bl.readUInt16LE(offset, noAssert); -buffer = bl.readUInt16LE(offset); -buffer = bl.readInt8(offset, noAssert); -buffer = bl.readInt8(offset); -buffer = bl.readUInt8(offset, noAssert); -buffer = bl.readUInt8(offset); +num = bl.readDoubleBE(offset, noAssert); +num = bl.readDoubleBE(offset); +num = bl.readDoubleLE(offset, noAssert); +num = bl.readDoubleLE(offset); +num = bl.readFloatBE(offset, noAssert); +num = bl.readFloatBE(offset); +num = bl.readFloatLE(offset, noAssert); +num = bl.readFloatLE(offset); +num = bl.readInt32BE(offset, noAssert); +num = bl.readInt32BE(offset); +num = bl.readInt32LE(offset, noAssert); +num = bl.readInt32LE(offset); +num = bl.readUInt32BE(offset, noAssert); +num = bl.readUInt32BE(offset); +num = bl.readUInt32LE(offset, noAssert); +num = bl.readUInt32LE(offset); +num = bl.readInt16BE(offset, noAssert); +num = bl.readInt16BE(offset); +num = bl.readInt16LE(offset, noAssert); +num = bl.readInt16LE(offset); +num = bl.readUInt16BE(offset, noAssert); +num = bl.readUInt16BE(offset); +num = bl.readUInt16LE(offset, noAssert); +num = bl.readUInt16LE(offset); +num = bl.readInt8(offset, noAssert); +num = bl.readInt8(offset); +num = bl.readUInt8(offset, noAssert); +num = bl.readUInt8(offset); diff --git a/bl/bl.d.ts b/bl/bl.d.ts index c277ea44b..6e8c3b4a8 100644 --- a/bl/bl.d.ts +++ b/bl/bl.d.ts @@ -20,20 +20,20 @@ declare module 'bl' { toString(encoding?: string, start?: number, end?: number): string; length: number; - readDoubleBE(offset: number, noAssert?: boolean): Buffer; - readDoubleLE(offset: number, noAssert?: boolean): Buffer; - readFloatBE(offset: number, noAssert?: boolean): Buffer; - readFloatLE(offset: number, noAssert?: boolean): Buffer; - readInt32BE(offset: number, noAssert?: boolean): Buffer; - readInt32LE(offset: number, noAssert?: boolean): Buffer; - readUInt32BE(offset: number, noAssert?: boolean): Buffer; - readUInt32LE(offset: number, noAssert?: boolean): Buffer; - readInt16BE(offset: number, noAssert?: boolean): Buffer; - readInt16LE(offset: number, noAssert?: boolean): Buffer; - readUInt16BE(offset: number, noAssert?: boolean): Buffer; - readUInt16LE(offset: number, noAssert?: boolean): Buffer; - readInt8(offset: number, noAssert?: boolean): Buffer; - readUInt8(offset: number, noAssert?: boolean): Buffer; + readDoubleBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; } export = BufferList; From dd9c603823ad97c869197f8ee58e2225fe75c0b1 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Fri, 11 Jul 2014 14:42:06 +0100 Subject: [PATCH 103/324] JSDoc --- angularjs/angular.d.ts | 45 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 40 insertions(+), 5 deletions(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 11763d608..d6b649a33 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -519,16 +519,51 @@ declare module ng { /////////////////////////////////////////////////////////////////////////// interface IRootElementService extends JQuery {} - /////////////////////////////////////////////////////////////////////////// - // QService - // see http://docs.angularjs.org/api/ng.$q - /////////////////////////////////////////////////////////////////////////// + /** + * $q - service in module ng + * A promise/deferred implementation inspired by Kris Kowal's Q. + * See http://docs.angularjs.org/api/ng/service/$q + */ interface IQService { + /** + * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. + * + * Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. + * + * @param promises An array or hash of promises. + */ all(promises: IPromise[]): IPromise; - all(promises: {[id: string]: IPromise;}): IPromise<{[id: string]: any}>; + /** + * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. + * + * Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. + * + * @param promises An array or hash of promises. + */ + all(promises: { [id: string]: IPromise; }): IPromise<{ [id: string]: any }>; + /** + * Creates a Deferred object which represents a task which will finish in the future. + */ defer(): IDeferred; + /** + * Creates a promise that is resolved as rejected with the specified reason. This api should be used to forward rejection in a chain of promises. If you are dealing with the last promise in a promise chain, you don't need to worry about it. + * + * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of reject as the throw keyword in JavaScript. This also means that if you "catch" an error via a promise error callback and you want to forward the error to the promise derived from the current promise, you have to "rethrow" the error by returning a rejection constructed via reject. + * + * @param reason Constant, message, exception or an object representing the rejection reason. + */ reject(reason?: any): IPromise; + /** + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. + * + * @param value Value or a promise + */ when(value: IPromise): IPromise; + /** + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. + * + * @param value Value or a promise + */ when(value: T): IPromise; } From a8fbeb0d2883ccccd90ab68ad3ea218bbc3bfe7a Mon Sep 17 00:00:00 2001 From: Martin Poelstra Date: Mon, 14 Jul 2014 10:57:13 +0200 Subject: [PATCH 104/324] Expand typings for source-map-support. --- .../source-map-support-tests.ts | 36 ++++++++++++++++++ source-map-support/source-map-support.d.ts | 37 ++++++++++++++++++- 2 files changed, 71 insertions(+), 2 deletions(-) diff --git a/source-map-support/source-map-support-tests.ts b/source-map-support/source-map-support-tests.ts index ddd6308cc..09a4fff45 100644 --- a/source-map-support/source-map-support-tests.ts +++ b/source-map-support/source-map-support-tests.ts @@ -3,3 +3,39 @@ import sms = require('source-map-support'); sms.install(); + +function retrieveFile(path: string): string { + return "foo"; +} + +function retrieveSourceMap(source: string): sms.UrlAndMap { + return { + url: "http://foo", + map: "foo" + }; +} + +var options: sms.Options = { + emptyCacheBetweenOperations: false, + handleUncaughtExceptions: false, + retrieveFile: retrieveFile, + retrieveSourceMap: retrieveSourceMap +}; + +sms.install(options); + +var stackFrame: any; // TODO: this should be a StackFrame, but it seems this would need to be defined elsewhere (in e.g. lib.d.ts) +stackFrame = sms.wrapCallSite(stackFrame); + +var s: string; +s = sms.getErrorSource(new Error("foo")); + +var p: sms.Position = { + column: 0, + line: 0, + source: "foo" +}; +p = sms.mapSourcePosition(p); + +var u: sms.UrlAndMap; +u = retrieveSourceMap("foo"); diff --git a/source-map-support/source-map-support.d.ts b/source-map-support/source-map-support.d.ts index 8d4e22579..b0de346a7 100644 --- a/source-map-support/source-map-support.d.ts +++ b/source-map-support/source-map-support.d.ts @@ -1,8 +1,41 @@ -// Type definitions for source-map-support 0.2.5 +// Type definitions for source-map-support 0.2.6 // Project: https://github.com/evanw/source-map-support // Definitions by: Bart van der Schoor // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module 'source-map-support' { - export function install(): any; + /** + * Output of retrieveSourceMap(). + */ + export interface UrlAndMap { + url: string; + map: any; // string or Buffer + } + + /** + * Options to install(). + */ + export interface Options { + handleUncaughtExceptions?: boolean; + emptyCacheBetweenOperations?: boolean; + retrieveFile?: (path: string) => string; + retrieveSourceMap?: (source: string) => UrlAndMap; + } + + export interface Position { + source: string; + line: number; + column: number; + } + + export function wrapCallSite(frame: any /* StackFrame */): any /* StackFrame */; + export function getErrorSource(error: Error): string; + export function mapSourcePosition(position: Position): Position; + export function retrieveSourceMap(source: string): UrlAndMap; + + /** + * Install SourceMap support. + * @param options Can be used to e.g. disable uncaughtException handler. + */ + export function install(options?: Options): void; } From 4e6c9f190bf4237da0da5fb0804c888f28ff85f0 Mon Sep 17 00:00:00 2001 From: Georgie Date: Mon, 14 Jul 2014 14:05:30 -0700 Subject: [PATCH 105/324] ChartArea allows missing members --- google.visualization/google.visualization.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/google.visualization/google.visualization.d.ts b/google.visualization/google.visualization.d.ts index 11a1f780c..f45f3f6a3 100644 --- a/google.visualization/google.visualization.d.ts +++ b/google.visualization/google.visualization.d.ts @@ -244,10 +244,10 @@ declare module google { } export interface ChartArea { - top: any; - left: any; - width: any; - height: any; + top?: any; + left?: any; + width?: any; + height?: any; } export interface ChartLegend { From 56a71f88b0db9a2cd63759e10ba3155a2fde2613 Mon Sep 17 00:00:00 2001 From: Jason Zhao Date: Mon, 14 Jul 2014 14:11:51 -0700 Subject: [PATCH 106/324] added contributos --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index ae430f57d..d40176b54 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -13,6 +13,7 @@ All definitions files include a header with the author and editors, so at some p * [AngularJS](http://angularjs.org) (by [Diego Vilar](https://github.com/diegovilar)) ([wiki](https://github.com/borisyankov/DefinitelyTyped/wiki/AngularJS-Definitions-Usage-Notes)) * [angularLocalStorage](https://github.com/agrublev/angularLocalStorage) (by [Hiroki Horiuchi](https://github.com/horiuchi/)) * [AngularUI](http://angular-ui.github.io/) (by [Michel Salib](https://github.com/michelsalib)) +* [Angular Hotkeys](https://github.com/chieffancypants/angular-hotkeys/) (by [Jason Zhao](https://github.com/jlz27)) * [Angular Protractor](https://github.com/angular/protractor) (by [Bill Armstrong](https://github.com/BillArmstrong)) * [Angular Translate](http://pascalprecht.github.io/angular-translate/) (by [Michel Salib](https://github.com/michelsalib)) * [Angular UI Bootstrap](http://angular-ui.github.io/bootstrap) (by [Brian Surowiec](https://github.com/xt0rted)) From e43fb420097712a9f3af2758da56e2dbaeab177b Mon Sep 17 00:00:00 2001 From: Jason Zhao Date: Mon, 14 Jul 2014 16:28:09 -0700 Subject: [PATCH 107/324] bumped version to 1.4.0 --- angular-hotkeys/angular-hotkeys-tests.ts | 3 +++ angular-hotkeys/angular-hotkeys.d.ts | 4 ++++ 2 files changed, 7 insertions(+) diff --git a/angular-hotkeys/angular-hotkeys-tests.ts b/angular-hotkeys/angular-hotkeys-tests.ts index 4e63b32fa..66f9e6072 100644 --- a/angular-hotkeys/angular-hotkeys-tests.ts +++ b/angular-hotkeys/angular-hotkeys-tests.ts @@ -1,10 +1,13 @@ +/// /// +var scope: ng.IScope; var hotkeyProvider: ng.hotkeys.HotkeysProvider; var hotkeyObj: ng.hotkeys.Hotkey; hotkeyProvider.add("mod+s", "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => {} ); hotkeyProvider.add(hotkeyObj); +hotkeyProvider.bindTo(scope); hotkeyProvider.del("mod+s"); hotkeyProvider.get("mod+s"); hotkeyProvider.toggleCheatSheet(); diff --git a/angular-hotkeys/angular-hotkeys.d.ts b/angular-hotkeys/angular-hotkeys.d.ts index 8c2e1ff1c..cc4a3680c 100644 --- a/angular-hotkeys/angular-hotkeys.d.ts +++ b/angular-hotkeys/angular-hotkeys.d.ts @@ -3,6 +3,8 @@ // Definitions by: Jason Zhao // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module ng.hotkeys { interface HotkeysProvider { @@ -15,6 +17,8 @@ declare module ng.hotkeys { add(hotkeyObj: ng.hotkeys.Hotkey): void; + bindTo(scope : ng.IScope): ng.hotkeys.HotkeysProvider; + del(combo: string): void; get(combo: string): ng.hotkeys.Hotkey; From 6e579ac47196258f0fb59ab48f4288d276a8e9ec Mon Sep 17 00:00:00 2001 From: Basarat Ali Syed Date: Tue, 15 Jul 2014 15:10:17 +1000 Subject: [PATCH 108/324] Update kineticjs.d.ts - `Line` has property `dashArray` not dash : http://kineticjs.com/docs/Kinetic.Line.html - there is no `remove` function on `Container` : http://kineticjs.com/docs/Kinetic.Container.html that takes a child - there is however a `remove` function on `Node` that removes an item from its parent. http://kineticjs.com/docs/Kinetic.Node.html This function exists in Container as well http://kineticjs.com/docs/Kinetic.Container.html (since container inherits from Node) --- kineticjs/kineticjs.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/kineticjs/kineticjs.d.ts b/kineticjs/kineticjs.d.ts index ecfbbae1f..dc9219fe2 100644 --- a/kineticjs/kineticjs.d.ts +++ b/kineticjs/kineticjs.d.ts @@ -53,6 +53,7 @@ declare module Kinetic { moveUp(): void; name(): string; name(name: string): void; + remove(): any; rotate(theta: number): void; rotateDeg(deg: number): void; @@ -124,7 +125,6 @@ declare module Kinetic { getChildren(): INode[]; getIntersections(point: any): any; isAncestorOf(node: any): any; - remove(child: any): any; removeChildren(): any; } @@ -136,6 +136,7 @@ declare module Kinetic { add(layer: ILayer): any; clear(): any; getContainer(): HTMLElement; + getContent(): HTMLElement; getDOM(): HTMLElement; getHeight(): number; getIntersection(pos: any): any; @@ -481,7 +482,7 @@ declare module Kinetic { interface LineConfig extends DrawOptionsConfig, ObjectOptionsConfig { points: any; lineCap?: string; - dashArray?: any; + dash?: number[]; } interface PolygonConfig extends DrawOptionsConfig, ObjectOptionsConfig { From 436ecfdb3bdb97ae882c89128c0560e6928a651c Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 15 Jul 2014 08:39:53 -0700 Subject: [PATCH 109/324] Added Rx.Observable.of. --- rx.js/rx-lite.d.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/rx.js/rx-lite.d.ts b/rx.js/rx-lite.d.ts index ad30b6e94..5c20fd39d 100644 --- a/rx.js/rx-lite.d.ts +++ b/rx.js/rx-lite.d.ts @@ -391,6 +391,24 @@ declare module Rx { fromItreable(iterable: {}, scheduler?: IScheduler): Observable; // todo: can't describe ES6 Iterable via TypeScript type system generate(initialState: TState, condition: (state: TState) => boolean, iterate: (state: TState) => TState, resultSelector: (state: TState) => TResult, scheduler?: IScheduler): Observable; never(): Observable; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * + * @example + * var res = Rx.Observable.of(1, 2, 3); + * @returns The observable sequence whose elements are pulled from the given arguments. + */ + of(...values: T[]): Observable; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.ofWithScheduler(Rx.Scheduler.timeout, 1, 2, 3); + * @param [scheduler] A scheduler to use for scheduling the arguments. + * @returns The observable sequence whose elements are pulled from the given arguments. + */ + ofWithScheduler(scheduler?: IScheduler, ...values: T[]): Observable; range(start: number, count: number, scheduler?: IScheduler): Observable; repeat(value: T, repeatCount?: number, scheduler?: IScheduler): Observable; return(value: T, scheduler?: IScheduler): Observable; From b5c9860090ad5898d7e7a6d9473e3b97ff94ab97 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 15 Jul 2014 08:51:27 -0700 Subject: [PATCH 110/324] Added `exclusive` operator. --- rx.js/rx-lite.d.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/rx.js/rx-lite.d.ts b/rx.js/rx-lite.d.ts index 5c20fd39d..3e5fa2b78 100644 --- a/rx.js/rx-lite.d.ts +++ b/rx.js/rx-lite.d.ts @@ -352,6 +352,16 @@ declare module Rx { * @returns An ES6 compatible promise with the last value from the observable sequence. */ toPromise(promiseCtor?: { new (resolver: (resolvePromise: (value: T) => void, rejectPromise: (reason: any) => void) => void): IPromise; }): IPromise; + + // Experimental Flattening + + /** + * Performs a exclusive waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * Can be applied on `Observable>` or `Observable>`. + * @returns A exclusive observable with only the results that happen when subscribed. + */ + exclusive(): Observable; } interface ObservableStatic { From f3ed4c501ecca2304f98a58da7af321308598e7b Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 15 Jul 2014 09:04:49 -0700 Subject: [PATCH 111/324] Added `exclusiveMap` operator. --- rx.js/rx-lite.d.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/rx.js/rx-lite.d.ts b/rx.js/rx-lite.d.ts index 3e5fa2b78..2e81da920 100644 --- a/rx.js/rx-lite.d.ts +++ b/rx.js/rx-lite.d.ts @@ -361,7 +361,17 @@ declare module Rx { * Can be applied on `Observable>` or `Observable>`. * @returns A exclusive observable with only the results that happen when subscribed. */ - exclusive(): Observable; + exclusive(): Observable; + + /** + * Performs a exclusive map waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * Can be applied on `Observable>` or `Observable>`. + * @param selector Selector to invoke for every item in the current subscription. + * @param [thisArg] An optional context to invoke with the selector parameter. + * @returns {An exclusive observable with only the results that happen when subscribed. + */ + exclusiveMap(selector: (value: I, index: number, source: Observable) => R, thisArg?: any): Observable; } interface ObservableStatic { From 3399c7e738d4121fbe034514daf2d6ec09f99e92 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 15 Jul 2014 09:11:16 -0700 Subject: [PATCH 112/324] `shareReplay` moved to `rx.binding-lite.d.ts`. Removed `replayWhileObserved` from `rx.binding.d.ts` (replaced by `shareReplay`). --- rx.js/rx.binding-lite.d.ts | 1 + rx.js/rx.binding.d.ts | 6 ------ rx.js/rx.lite.d.ts | 4 ---- 3 files changed, 1 insertion(+), 10 deletions(-) diff --git a/rx.js/rx.binding-lite.d.ts b/rx.js/rx.binding-lite.d.ts index e1120e109..f896e260d 100644 --- a/rx.js/rx.binding-lite.d.ts +++ b/rx.js/rx.binding-lite.d.ts @@ -67,5 +67,6 @@ declare module Rx { shareValue(initialValue: T): Observable; replay(selector?: boolean, bufferSize?: number, window?: number, scheduler?: IScheduler): ConnectableObservable; // hack to catch first omitted parameter replay(selector: (source: ConnectableObservable) => Observable, bufferSize?: number, window?: number, scheduler?: IScheduler): Observable; + shareReplay(bufferSize?: number, window?: number, scheduler?: IScheduler): Observable; } } diff --git a/rx.js/rx.binding.d.ts b/rx.js/rx.binding.d.ts index cf089e43f..3adbcbe2b 100644 --- a/rx.js/rx.binding.d.ts +++ b/rx.js/rx.binding.d.ts @@ -6,12 +6,6 @@ /// /// -declare module Rx { - export interface Observable { - replayWhileObserved(bufferSize?: number, window?: number, scheduler?: IScheduler): Observable; - } -} - declare module "rx.binding" { export = Rx; } \ No newline at end of file diff --git a/rx.js/rx.lite.d.ts b/rx.js/rx.lite.d.ts index ddffc4a16..da2ddde3b 100644 --- a/rx.js/rx.lite.d.ts +++ b/rx.js/rx.lite.d.ts @@ -43,10 +43,6 @@ declare module Rx { schedulePeriodic(period: number, action: () => void): IDisposable; schedulePeriodicWithState(state: TState, period: number, action: (state: TState) => TState): IDisposable; } - - export interface Observable { - shareReplay(bufferSize?: number, window?: number, scheduler?: IScheduler): Observable; // same as replayWhileObserved in rx.binding.d.ts - } } declare module "rx.lite" { From cfbd50bddb1ff9c65c7c966e9fbbba13fed6efc7 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 15 Jul 2014 09:13:26 -0700 Subject: [PATCH 113/324] Added @since jsdoc attributes for new methods. --- rx.js/rx-lite.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/rx.js/rx-lite.d.ts b/rx.js/rx-lite.d.ts index 2e81da920..db4642372 100644 --- a/rx.js/rx-lite.d.ts +++ b/rx.js/rx-lite.d.ts @@ -359,6 +359,7 @@ declare module Rx { * Performs a exclusive waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * Can be applied on `Observable>` or `Observable>`. + * @since 2.2.28 * @returns A exclusive observable with only the results that happen when subscribed. */ exclusive(): Observable; @@ -367,6 +368,7 @@ declare module Rx { * Performs a exclusive map waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * Can be applied on `Observable>` or `Observable>`. + * @since 2.2.28 * @param selector Selector to invoke for every item in the current subscription. * @param [thisArg] An optional context to invoke with the selector parameter. * @returns {An exclusive observable with only the results that happen when subscribed. @@ -417,6 +419,7 @@ declare module Rx { * * @example * var res = Rx.Observable.of(1, 2, 3); + * @since 2.2.28 * @returns The observable sequence whose elements are pulled from the given arguments. */ of(...values: T[]): Observable; @@ -425,6 +428,7 @@ declare module Rx { * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.ofWithScheduler(Rx.Scheduler.timeout, 1, 2, 3); + * @since 2.2.28 * @param [scheduler] A scheduler to use for scheduling the arguments. * @returns The observable sequence whose elements are pulled from the given arguments. */ From aa37a6d4be12e148386df01bdd7f1873f6fd8320 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 15 Jul 2014 09:17:13 -0700 Subject: [PATCH 114/324] Added alias `just` for `return`. --- rx.js/rx-lite.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/rx.js/rx-lite.d.ts b/rx.js/rx-lite.d.ts index db4642372..2c65d950a 100644 --- a/rx.js/rx-lite.d.ts +++ b/rx.js/rx-lite.d.ts @@ -436,6 +436,7 @@ declare module Rx { range(start: number, count: number, scheduler?: IScheduler): Observable; repeat(value: T, repeatCount?: number, scheduler?: IScheduler): Observable; return(value: T, scheduler?: IScheduler): Observable; + just(value: T, scheduler?: IScheduler): Observable; // alias for return returnValue(value: T, scheduler?: IScheduler): Observable; // alias for return throw(exception: Error, scheduler?: IScheduler): Observable; throw(exception: any, scheduler?: IScheduler): Observable; From a1fe5ce51b15f76b90ab0bf671efa930f82a3a56 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 15 Jul 2014 09:29:06 -0700 Subject: [PATCH 115/324] Added `switchMap` alias for `selectSwitch`. --- rx.js/rx-lite.d.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/rx.js/rx-lite.d.ts b/rx.js/rx-lite.d.ts index 2c65d950a..c7a148137 100644 --- a/rx.js/rx-lite.d.ts +++ b/rx.js/rx-lite.d.ts @@ -324,6 +324,16 @@ declare module Rx { * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ flatMapLatest(selector: (value: T, index: number, source: Observable) => TResult, thisArg?: any): Observable; // alias for selectSwitch + /** + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @param selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param [thisArg] Object to use as this when executing callback. + * @since 2.2.28 + * @returns An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + switchMap(selector: (value: T, index: number, source: Observable) => TResult, thisArg?: any): Observable; // alias for selectSwitch skip(count: number): Observable; skipWhile(predicate: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; @@ -436,6 +446,9 @@ declare module Rx { range(start: number, count: number, scheduler?: IScheduler): Observable; repeat(value: T, repeatCount?: number, scheduler?: IScheduler): Observable; return(value: T, scheduler?: IScheduler): Observable; + /** + * @since 2.2.28 + */ just(value: T, scheduler?: IScheduler): Observable; // alias for return returnValue(value: T, scheduler?: IScheduler): Observable; // alias for return throw(exception: Error, scheduler?: IScheduler): Observable; From 2f5fb6d9e458763c0b096c2378166e4189ca23f5 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 15 Jul 2014 09:33:03 -0700 Subject: [PATCH 116/324] Version bump to 2.2.28 --- rx.js/rx.aggregates.d.ts | 2 +- rx.js/rx.all.ts | 2 +- rx.js/rx.async.d.ts | 2 +- rx.js/rx.backpressure.d.ts | 2 +- rx.js/rx.binding.d.ts | 2 +- rx.js/rx.coincidence.d.ts | 2 +- rx.js/rx.d.ts | 2 +- rx.js/rx.experimental.d.ts | 2 +- rx.js/rx.joinpatterns.d.ts | 2 +- rx.js/rx.lite.d.ts | 2 +- rx.js/rx.testing.d.ts | 2 +- rx.js/rx.time.d.ts | 2 +- rx.js/rx.virtualtime.d.ts | 2 +- 13 files changed, 13 insertions(+), 13 deletions(-) diff --git a/rx.js/rx.aggregates.d.ts b/rx.js/rx.aggregates.d.ts index 4ab7355ed..001d1b993 100644 --- a/rx.js/rx.aggregates.d.ts +++ b/rx.js/rx.aggregates.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-Aggregates v2.2.25 +// Type definitions for RxJS-Aggregates v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: Carl de Billy , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.all.ts b/rx.js/rx.all.ts index 608605fae..c546477b8 100644 --- a/rx.js/rx.all.ts +++ b/rx.js/rx.all.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-All v2.2.25 +// Type definitions for RxJS-All v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: Carl de Billy , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.async.d.ts b/rx.js/rx.async.d.ts index 14823b948..9370c828b 100644 --- a/rx.js/rx.async.d.ts +++ b/rx.js/rx.async.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-Async v2.2.25 +// Type definitions for RxJS-Async v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: zoetrope , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.backpressure.d.ts b/rx.js/rx.backpressure.d.ts index 5f5013fe1..9c5e8abd5 100644 --- a/rx.js/rx.backpressure.d.ts +++ b/rx.js/rx.backpressure.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-BackPressure v2.2.25 +// Type definitions for RxJS-BackPressure v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.binding.d.ts b/rx.js/rx.binding.d.ts index 3adbcbe2b..b93411a52 100644 --- a/rx.js/rx.binding.d.ts +++ b/rx.js/rx.binding.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-Binding v2.2.25 +// Type definitions for RxJS-Binding v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: Carl de Billy , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.coincidence.d.ts b/rx.js/rx.coincidence.d.ts index af7acd4de..87fa6a55b 100644 --- a/rx.js/rx.coincidence.d.ts +++ b/rx.js/rx.coincidence.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-Coincidence v2.2.25 +// Type definitions for RxJS-Coincidence v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: Carl de Billy , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.d.ts b/rx.js/rx.d.ts index 967b5aefa..1f26a94a9 100644 --- a/rx.js/rx.d.ts +++ b/rx.js/rx.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS v2.2.25 +// Type definitions for RxJS v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: gsino , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.experimental.d.ts b/rx.js/rx.experimental.d.ts index 885630be2..60aec86e1 100644 --- a/rx.js/rx.experimental.d.ts +++ b/rx.js/rx.experimental.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-Experimental v2.2.25 +// Type definitions for RxJS-Experimental v2.2.28 // Project: https://github.com/Reactive-Extensions/RxJS/ // Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.joinpatterns.d.ts b/rx.js/rx.joinpatterns.d.ts index 9d0d7244f..929c66a6f 100644 --- a/rx.js/rx.joinpatterns.d.ts +++ b/rx.js/rx.joinpatterns.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-Join v2.2.25 +// Type definitions for RxJS-Join v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.lite.d.ts b/rx.js/rx.lite.d.ts index da2ddde3b..046ef527d 100644 --- a/rx.js/rx.lite.d.ts +++ b/rx.js/rx.lite.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-Lite v2.2.25 +// Type definitions for RxJS-Lite v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: gsino , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.testing.d.ts b/rx.js/rx.testing.d.ts index 393061625..0adc83e50 100644 --- a/rx.js/rx.testing.d.ts +++ b/rx.js/rx.testing.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-Testing v2.2.25 +// Type definitions for RxJS-Testing v2.2.28 // Project: https://github.com/Reactive-Extensions/RxJS/ // Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.time.d.ts b/rx.js/rx.time.d.ts index ae2408e85..6efd7d9cf 100644 --- a/rx.js/rx.time.d.ts +++ b/rx.js/rx.time.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-Time v2.2.25 +// Type definitions for RxJS-Time v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: Carl de Billy , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.virtualtime.d.ts b/rx.js/rx.virtualtime.d.ts index 04de75e94..50a1bb39b 100644 --- a/rx.js/rx.virtualtime.d.ts +++ b/rx.js/rx.virtualtime.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-VirtualTime v2.2.25 +// Type definitions for RxJS-VirtualTime v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: gsino , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped From 72ab7b498ae39b2cece7d0365f7011f2b380dc03 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 15 Jul 2014 12:41:50 -0700 Subject: [PATCH 117/324] Added AMD named module export definition for `rx.jquery`. --- rx.js/rx.jquery.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/rx.js/rx.jquery.d.ts b/rx.js/rx.jquery.d.ts index 75202142e..ace0c5071 100644 --- a/rx.js/rx.jquery.d.ts +++ b/rx.js/rx.jquery.d.ts @@ -60,3 +60,7 @@ interface JQuery { slideToggleAsObservable(duration: number): Rx.Observable; toggleAsObservable(duration: number): Rx.Observable; } + +declare module "rx.jquery" { + export = Rx; +} \ No newline at end of file From 68dfa3453b17b5138ee57a39f341408c83ec0a63 Mon Sep 17 00:00:00 2001 From: Ian Sibner Date: Tue, 15 Jul 2014 20:02:31 -0400 Subject: [PATCH 118/324] Add definitions for angular-protractor 1.0.0-rc4 --- .../angular-protractor-tests.ts | 91 +- angular-protractor/angular-protractor.d.ts | 786 +++++++++------ .../legacy/angular-protractor-0.17.0-tests.ts | 244 +++++ .../legacy/angular-protractor-0.17.0.d.ts | 906 ++++++++++++++++++ 4 files changed, 1724 insertions(+), 303 deletions(-) create mode 100644 angular-protractor/legacy/angular-protractor-0.17.0-tests.ts create mode 100644 angular-protractor/legacy/angular-protractor-0.17.0.d.ts diff --git a/angular-protractor/angular-protractor-tests.ts b/angular-protractor/angular-protractor-tests.ts index 37c9e49bc..62ed46177 100644 --- a/angular-protractor/angular-protractor-tests.ts +++ b/angular-protractor/angular-protractor-tests.ts @@ -153,21 +153,36 @@ function TestProtractor() { ptor.debugger(); + var webElement: protractor.WebElement = ptor.findElement(by.css('.class')); + var promise: webdriver.promise.Promise; + promise = ptor.findElements(by.css('.class')); + promise = ptor.isElementPresent(by.css('.class')); + promise = ptor.isElementPresent(webElement); + ptor.clearMockModules(); ptor.addMockModule('name', 'script'); ptor.addMockModule('name', function() {}); + ptor.removeMockModule('name'); ptor.waitForAngular(); var elementFinder: protractor.ElementFinder; + var elementArrayFinder: protractor.ElementArrayFinder; elementFinder = ptor.element(by.id('ABC')); elementFinder = ptor.$('.class'); - var elementArrayFinder: protractor.ElementArrayFinder = ptor.$$('.class'); - - var webElement: webdriver.WebElement = ptor.wrapWebElement(new webdriver.WebElement(driver, 'id')); + elementArrayFinder = ptor.$$('.class'); var locationAbsUrl: webdriver.promise.Promise = ptor.getLocationAbsUrl(); + ptor.setLocation('webaddress.com'); + + promise = ptor.get('webaddress.com'); + promise = ptor.get('webdaddress.com', 45); + ptor.refresh(); + ptor.refresh(45); + var navigation: webdriver.WebDriverNavigation = ptor.navigate(); + ptor.pause(); + ptor.pause(8080); } function TestElement() { @@ -180,6 +195,7 @@ function TestElementFinder() { var promise: webdriver.promise.Promise; promise = elementFinder.click(); + promise = elementFinder.allowAnimations('string'); promise = elementFinder.sendKeys(protractor.Key.UP, protractor.Key.DOWN); promise = elementFinder.getTagName(); promise = elementFinder.getCssValue('display'); @@ -196,18 +212,45 @@ function TestElementFinder() { promise = elementFinder.getInnerHtml(); promise = elementFinder.isElementPresent(by.id('id')); promise = elementFinder.isElementPresent(by.js('function(a, b, c) {}'), 1, 2, 3); - promise = elementFinder.findElements(by.className('class')); - promise = elementFinder.findElements(by.js('function(a, b, c) {}'), 1, 2, 3); + promise = elementFinder.$('.class'); promise = elementFinder.$$('.class'); promise = elementFinder.evaluate('expression'); promise = elementFinder.isPresent(); var webElement: webdriver.WebElement; +} - webElement = elementFinder.$('.class'); - webElement = elementFinder.findElement(by.id('id')); - webElement = elementFinder.findElement(by.js('function(a, b, c) {}'), 1, 2, 3); - webElement = elementFinder.find(); +function TestElementArrayFinder() { + var elementArrayFinder: protractor.ElementArrayFinder = element.all(by.id('id')); + var promise: webdriver.promise.Promise; + var elementFinder: protractor.ElementFinder; + + var driverElementArray: webdriver.WebElement[] = elementArrayFinder.getWebElements(); + elementFinder = elementArrayFinder.get(42); + elementFinder = elementArrayFinder.first(); + elementFinder = elementArrayFinder.last(); + promise = elementArrayFinder.count(); + elementArrayFinder.each(function(element: protractor.ElementFinder){ + // nothing + }); + elementArrayFinder.map(function(element: protractor.ElementFinder, index: number){ + // nothing + }); + elementArrayFinder.filter(function(element: protractor.ElementFinder, index: number){ + return element.getText().then((text: string) => { + return text === "foo"; + }); + }); + elementArrayFinder.reduce(function(accumulator: string, element: protractor.ElementFinder){ + return element.getText().then((text: string) => { + return accumulator + ',' + text; + }); + }, ''); + elementArrayFinder.reduce(function(accumulator: string, element: protractor.ElementFinder, index: number, array: protractor.ElementFinder[]){ + return element.getText().then((text: string) => { + return accumulator + ',' + text; + }); + }, ''); } // This function tests the angular specific locator strategies. @@ -216,29 +259,19 @@ function TestLocatorStrategies() { var webElement: webdriver.WebElement; // Protractor Specific Locators + protractor.By.addLocator('customLocator', 'script'); + protractor.By.addLocator('customLocator2', function(){ + // nothing + }); webElement = ptor.findElement(protractor.By.binding('binding')); - webElement = ptor.findElement(protractor.By.select('select')); - webElement = ptor.findElement(protractor.By.selectedOption('selectedOptions')); - webElement = ptor.findElement(protractor.By.input('input')); + webElement = ptor.findElement(protractor.By.exactBinding('exactBinding')); webElement = ptor.findElement(protractor.By.model('model')); - webElement = ptor.findElement(protractor.By.textarea('textarea')); webElement = ptor.findElement(protractor.By.repeater('repeater')); + webElement = ptor.findElement(protractor.By.repeater('repeater').column(0)); + webElement = ptor.findElement(protractor.By.repeater('repeater').row(0)); + webElement = ptor.findElement(protractor.By.repeater('repeater').row(0).column(0)); webElement = ptor.findElement(protractor.By.buttonText('buttonText')); webElement = ptor.findElement(protractor.By.partialButtonText('partialButtonText')); -} - -// This function tests the methods that were added to the base WebElement class -function TestWebElements() { - var ptor: protractor.Protractor = protractor.getInstance(); - - var webElement: protractor.WebElement; - var promise: webdriver.promise.Promise; - - webElement = ptor.findElement(by.id('id')).$('.class'); - promise = ptor.findElement(by.id('id')).$$('.class'); - promise = ptor.findElement(by.id('id')).evaluate('something'); - - webElement = webElement.findElement(by.id('id')).$('.class'); - promise = webElement.findElement(by.id('id')).$$('.class'); - promise = webElement.findElement(by.id('id')).evaluate('something'); + webElement = ptor.findElement(protractor.By.cssContainingText('cssSelector', 'search text')); + webElement = ptor.findElement(protractor.By.options('options')); } diff --git a/angular-protractor/angular-protractor.d.ts b/angular-protractor/angular-protractor.d.ts index 3c3c0981f..81eca975e 100644 --- a/angular-protractor/angular-protractor.d.ts +++ b/angular-protractor/angular-protractor.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular Protractor 0.17.0 +// Type definitions for Angular Protractor 1.0.0-rc4 // Project: https://github.com/angular/protractor // Definitions by: Bill Armstrong // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -25,71 +25,7 @@ declare module protractor { class CommandName extends webdriver.CommandName {} class Key extends webdriver.Key {} class UnhandledAlertError extends webdriver.UnhandledAlertError {} - - class WebElement extends webdriver.WebElement { - /** - * Shortcut for querying the document directly with css. - * - * @param {string} selector a css selector - * @see webdriver.WebElement.findElement - * @return {!protractor.WebElement} - */ - $(selector: string): protractor.WebElement; - - /** - * Shortcut for querying the document directly with css. - * - * @param {string} selector a css selector - * @see webdriver.WebElement.findElements - * @return {!webdriver.promise.Promise} A promise that will be resolved to an - * array of the located {@link webdriver.WebElement}s. - */ - $$(selector: string): webdriver.promise.Promise; - - /** - * Evalates the input as if it were on the scope of the current element. - * @param {string} expression - * - * @return {!webdriver.promise.Promise} A promise that will resolve to the - * evaluated expression. The result will be resolved as in - * {@link webdriver.WebDriver.executeScript}. In summary - primitives will - * be resolved as is, functions will be converted to string, and elements - * will be returned as a WebElement. - */ - evaluate(expression: string): webdriver.promise.Promise; - - /** - * Schedule a command to find a descendant of this element. If the element - * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will - * be returned by the driver. Unlike other commands, this error cannot be - * suppressed. In other words, scheduling a command to find an element doubles - * as an assert that the element is present on the page. To test whether an - * element is present on the page, use {@code #isElementPresent} instead. - *

- * The search criteria for find an element may either be a - * {@code webdriver.Locator} object, or a simple JSON object whose sole key - * is one of the accepted locator strategies, as defined by - * {@code webdriver.Locator.Strategy}. For example, the following two - * statements are equivalent: - *

-         * var e1 = element.findElement(By.id('foo'));
-         * var e2 = element.findElement({id:'foo'});
-         * 
- *

- * Note that JS locator searches cannot be restricted to a subtree. All such - * searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the element. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {protractor.WebElement} A WebElement that can be used to issue - * commands against the located element. If the element is not found, the - * element will be invalidated and all scheduled commands aborted. - */ - findElement(locator: webdriver.Locator, ...var_args: any[]): protractor.WebElement; - findElement(locator: any, ...var_args: any[]): protractor.WebElement; - } + class WebElement extends webdriver.WebElement {} module command { class Command extends webdriver.Command {} @@ -273,13 +209,160 @@ declare module protractor { } //endregion - + /** + * Use as: element(locator) + * + * The ElementFinder can be treated as a WebElement for most purposes, in + * particular, you may perform actions (i.e. click, getText) on them as you + * would a WebElement. ElementFinders extend Promise, and once an action + * is performed on an ElementFinder, the latest result from the chain can be + * accessed using then. Unlike a WebElement, an ElementFinder will wait for + * angular to settle before performing finds or actions. + * + * ElementFinder can be used to build a chain of locators that is used to find + * an element. An ElementFinder does not actually attempt to find the element + * until an action is called, which means they can be set up in helper files + * before the page is available. + * + * @param {webdriver.Locator} locator An element locator. + * @param {ElementFinder=} opt_parentElementFinder The element finder previous + * to this. (i.e. opt_parentElementFinder.element(locator) => this) + * @param {webdriver.promise.Promise} opt_actionResult The promise which + * will be retrieved with then. Resolves to the latest action result, + * or null if no action has been called. + * @param {number=} opt_index The index of the element to retrieve. null means + * retrieve the only element, while -1 means retrieve the last element + * @return {ElementFinder} + */ interface Element { - (locator: webdriver.Locator): ElementFinder; - all(locator: webdriver.Locator): ElementArrayFinder; + (locator: webdriver.Locator, + opt_parentElementFinder?: protractor.ElementFinder, + opt_actionResult?: webdriver.promise.Promise, + opt_index?: number): ElementFinder; + + /** + * ElementArrayFinder is used for operations on an array of elements (as opposed + * to a single element). + * + * @param {webdriver.Locator} locator An element locator. + * @param {ElementFinder=} opt_parentElementFinder The element finder previous to + * this. (i.e. opt_parentElementFinder.all(locator) => this) + * @return {ElementArrayFinder} + */ + all(locator: webdriver.Locator, opt_parentElementFinder?: protractor.ElementFinder): ElementArrayFinder; } interface ElementFinder { + /** + * Use as: element(locator).element(locator) + * Calls to element may be chained to find elements within a parent. + * + * @param {webdriver.Locator} locator The locator that will be used to find descendents. + * + * @return {protractor.ElementFinder} The descendent element found by the locator + */ + element(locator: webdriver.Locator): protractor.ElementFinder; + + /** + * Use as: element(locator).all(locator) + * Calls to element may be chained to find an array of elements within a parent. + * + * @param {webdriver.Locator} locator The locator that will be used to find descendents. + * + * @return {protractor.ElementArrayFinder} The descendent elements found by the locator + */ + all(locator: webdriver.Locator): protractor.ElementArrayFinder; + + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElement + * @return {!protractor.WebElement} + */ + $(selector: string): protractor.WebElement; + + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElements + * @return {!webdriver.promise.Promise} A promise that will be resolved to an + * array of the located {@link webdriver.WebElement}s. + */ + $$(selector: string): webdriver.promise.Promise; + + /** + * Use as: element(locator).isPresent() + * Determine whether the element is present on the page. + * + * @return {protractor.ElementFinder} Which resolves to whether the element is present on the page. + */ + isPresent(): webdriver.promise.Promise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + *

Note that JS locator searches cannot be restricted to a subtree of the + * DOM. All such searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the element. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether an element could be located on the page. + */ + isElementPresent(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; + isElementPresent(locator: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Return this ElementFinder's locator. + * + * @return {webdriver.Locator} + */ + locator(): webdriver.Locator; + + /** + * Use as: element(locator).getWebElement() + * Returns the WebElement represented by this ElementFinder. + * Throws the WebDriver error if the element doesn't exist. + * If index is null, it makes sure that there is only one underlying WebElement + * described by the chain of locators and issues a warning otherwise. + * If index is not null, it retrieves the WebElement specified by the index.. + * @return {webdriver.WebElement} The WebElement represented by the ElementFinder. + */ + getWebElement(): webdriver.WebElement; + + /** + * Evalates the input as if it were on the scope of the current element. + * @param {string} expression + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * evaluated expression. The result will be resolved as in + * {@link webdriver.WebDriver.executeScript}. In summary - primitives will + * be resolved as is, functions will be converted to string, and elements + * will be returned as a WebElement. + */ + evaluate(expression: string): webdriver.promise.Promise; + + /** + * Determine if animation is allowed on the current element. + * @param {string} value + * + * @return {ElementFinder} which resolves to whether animation is allowed. + */ + allowAnimations(value: string): webdriver.promise.Promise; + + /** + * Access the underlying actionResult of ElementFinder. Implementation allows ElementFinder to be used as a webdriver.promise.Promise. + * @param {function(webdriver.promise.Promise)} fn Function which takes the value of the underlying actionResult. + * + * @return {webdriver.promise.Promise} Promise which contains the results of evaluating fn. + */ + then(fn: IThenFunction): webdriver.promise.Promise; + /** * Schedules a command to click on this element. * @return {!webdriver.promise.Promise} A promise that will be resolved when @@ -460,113 +543,128 @@ declare module protractor { getInnerHtml(): webdriver.promise.Promise; /** - * Schedules a command to test if there is at least one descendant of this - * element that matches the given search criteria. - * - *

Note that JS locator searches cannot be restricted to a subtree of the - * DOM. All such searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the element. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * whether an element could be located on the page. + * @return {!webdriver.promise.Promise.} A promise + * that resolves to this element's JSON representation as defined by the + * WebDriver wire protocol. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol */ - isElementPresent(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; - isElementPresent(locator: any, ...var_args: any[]): webdriver.promise.Promise; - - /** - * Schedules a command to find all of the descendants of this element that match - * the given search criteria. - *

- * Note that JS locator searches cannot be restricted to a subtree. All such - * searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the elements. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {!webdriver.promise.Promise} A promise that will be resolved with an - * array of located {@link webdriver.WebElement}s. - */ - findElements(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; - findElements(locator: any, ...var_args: any[]): webdriver.promise.Promise; - - /** - * Shortcut for querying the document directly with css. - * - * @param {string} selector a css selector - * @see webdriver.WebElement.findElement - * @return {!protractor.WebElement} - */ - $(selector: string): protractor.WebElement; - - /** - * Shortcut for querying the document directly with css. - * - * @param {string} selector a css selector - * @see webdriver.WebElement.findElements - * @return {!webdriver.promise.Promise} A promise that will be resolved to an - * array of the located {@link webdriver.WebElement}s. - */ - $$(selector: string): webdriver.promise.Promise; - - /** - * Schedule a command to find a descendant of this element. If the element - * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will - * be returned by the driver. Unlike other commands, this error cannot be - * suppressed. In other words, scheduling a command to find an element doubles - * as an assert that the element is present on the page. To test whether an - * element is present on the page, use {@code #isElementPresent} instead. - *

- * The search criteria for find an element may either be a - * {@code webdriver.Locator} object, or a simple JSON object whose sole key - * is one of the accepted locator strategies, as defined by - * {@code webdriver.Locator.Strategy}. For example, the following two - * statements are equivalent: - *

-         * var e1 = element.findElement(By.id('foo'));
-         * var e2 = element.findElement({id:'foo'});
-         * 
- *

- * Note that JS locator searches cannot be restricted to a subtree. All such - * searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the element. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {protractor.WebElement} A WebElement that can be used to issue - * commands against the located element. If the element is not found, the - * element will be invalidated and all scheduled commands aborted. - */ - findElement(locator: webdriver.Locator, ...var_args: any[]): protractor.WebElement; - findElement(locator: any, ...var_args: any[]): protractor.WebElement; - - /** - * Evalates the input as if it were on the scope of the current element. - * @param {string} expression - * - * @return {!webdriver.promise.Promise} A promise that will resolve to the - * evaluated expression. The result will be resolved as in - * {@link webdriver.WebDriver.executeScript}. In summary - primitives will - * be resolved as is, functions will be converted to string, and elements - * will be returned as a WebElement. - */ - evaluate(expression: string): webdriver.promise.Promise; - - find(): protractor.WebElement; - - isPresent(): webdriver.promise.Promise; + toWireValue(): webdriver.promise.Promise; } - interface ElementArrayFinder{ + interface IThenFunction { + (promise: webdriver.promise.Promise): any; + } + + + interface ElementArrayFinder { + /** + * Use as: element.all(locator).getWebElements() + * Returns the array of WebElements represented by this ElementArrayFinder. + * + * @return {Array.} Array of WebElements represented by this ElementArrayFinder + */ + getWebElements(): webdriver.WebElement[]; + + /** + * Use as: element.all(locator).get(index) + * Get an element found by the locator by index. The index starts at 0. This does not actually retrieve the underlying element. + * + * @param {number} index Element index. + * + * @return {protractor.ElementFinder} Finder representing element at the given index + */ + get(index: number): protractor.ElementFinder; + + + /** + * Use as: element.all(locator).first() + * Get the first matching element for the locator. This does not actually retrieve the underlying element. + * + * @return {Protractor.ElementFinder} Finder representing the first matching element + */ + first(): protractor.ElementFinder; + + /** + * Use as: element.all(locator).last() + * Get the last matching element for the locator. This does not actually retrieve the underlying element. + * + * @return {Protractor.ElementFinder} Finder representing the last matching element + */ + last(): protractor.ElementFinder; + + /** + * Use as: element.all(locator).getWebElements() + * Returns the array of WebElements represented by this ElementArrayFinder. + * + * @return {!webdriver.promise.Promise} The array of WebElements represented by this ElementArrayFinder + */ count(): webdriver.promise.Promise; - get(index: number): protractor.WebElement; - first(): protractor.WebElement; - last(): protractor.WebElement; - then(fn: (value: any) => any): webdriver.promise.Promise; + + /** + * Use as: element.all(locator).each(eachFunction) + * Calls the input function on each ElementFinder found by the locator. + * + * @param {function(ElementFinder)} fn Input function. + */ + each(fn: IEachFunction): void; + + /** + * Use as: element.all(locator).map(mapFunction) + * Apply a map function to each element found using the locator. The callback receives the ElementFinder as the first argument and the index as a second arg. + * + * @param {function(ElementFinder, number)} mapFn Map function that will be applied to each element. + * + * @return {!webdriver.promise.Promise} A promise that resolves to an array of values returned by the map function. + */ + map(mapFn: IMapFunction): webdriver.promise.Promise; + + /** + * Use as: element.all(locator).filter(filterFn) + * Apply a filter function to each element found using the locator. Returns promise of a new array with all elements that pass the filter function. The filter function receives the ElementFinder as the first argument and the index as a second arg. + * + * @param {function(ElementFinder, number): webdriver.promise.Promise} filterFn Filter function that will test if an element should be returned. filterFn should return a promise that resolves to a boolean. + * + * @return {!webdriver.promise.Promise} A promise that resolves to an array of ElementFinders that satisfy the filter function. + */ + filter(func: IFilterFunction): webdriver.promise.Promise; + + /** + * Use as: element.all(locator).reduce(reduceFn) + * Apply a reduce function against an accumulator and every element found using the locator (from left-to-right). + * The reduce function has to reduce every element into a single value (the accumulator). + * Returns promise of the accumulator. + * The reduce function receives the accumulator, current ElementFinder, the index, and the entire array of ElementFinders, respectively. + * + * @param {function(number, ElementFinder, number, Array.): webdriver.promise.Promise} reduceFn Reduce function that reduces every element into a single value. + * @param {*} initialValue Initial value of the accumulator. + * + * @return {!webdriver.promise.Promise} A promise that resolves to the final value of the accumulator. + */ + reduce(func: IReductionFunction, initialValue: any): webdriver.promise.Promise; + } + + interface IEachFunction { + (element: protractor.ElementFinder): void; + } + + interface IMapFunction { + (element: ElementFinder, index: number): any; + } + + interface IFilterFunction { + (element: ElementFinder, index: number): webdriver.promise.Promise; + } + + interface IReductionFunction { + (accumulator: any, element: protractor.ElementFinder, index?: number, array?: protractor.ElementFinder[]): webdriver.promise.Promise; + } + + class LocatorWithColumn extends webdriver.Locator { + column(index: number): webdriver.Locator; + } + + class RepeaterLocator extends LocatorWithColumn { + row(index: number): LocatorWithColumn; } interface IProtractorLocatorStrategy extends webdriver.ILocatorStrategy { @@ -587,69 +685,160 @@ declare module protractor { * Usage: * {{status}} * var status = element(by.binding('{{status}}')); + * + * @param {string} bindingDescriptor + * @return {webdriver.Locator} */ binding(bindingDescriptor: string): webdriver.Locator; /** - * Usage: - * - * element(by.select("user")); + * Find an element by exact binding. + * + * {{ person.name }} + * + * {{person_phone|uppercase}} + * + * expect(element(by.exactBinding('person.name')).isPresent()).toBe(true); + * expect(element(by.exactBinding('person-email')).isPresent()).toBe(true); + * expect(element(by.exactBinding('person')).isPresent()).toBe(false); + * expect(element(by.exactBinding('person_phone')).isPresent()).toBe(true); + * expect(element(by.exactBinding('person_phone|uppercase')).isPresent()).toBe(true); + * expect(element(by.exactBinding('phone')).isPresent()).toBe(false); + * + * @param {string} bindingDescriptor + * @return {webdriver.Locator} */ - select(model: string): webdriver.Locator; + exactBinding(bindingDescriptor: string): webdriver.Locator; /** + * + * Find an element by ng-model expression. + * * Usage: - * - * element(by.selectedOption("user")); - */ - selectedOption(model: string): webdriver.Locator; - - /** - * @DEPRECATED - use 'model' instead. - * Usage: - * - * element(by.input('user')); - */ - input(model: string): webdriver.Locator; - - /** - * Usage: - * - * element(by.model('user')); + * + * var input = element(by.model('person.name')); + * input.sendKeys('123'); + * expect(input.getAttribute('value')).toBe('Foo123'); + * + * @param {string} model ng-model expression. + * @return {webdriver.Locator} */ model(model: string): webdriver.Locator; /** - * Usage: - * - * element(by.textarea("user")); - */ - textarea(model: string): webdriver.Locator; - - /** - * Usage: - *

- * {{cat.name}} - * {{cat.age}} - *
+ * Find a button by text. * - * // Returns the DIV for the second cat. - * var secondCat = element(by.repeater("cat in pets").row(2)); - * // Returns the SPAN for the first cat's name. - * var firstCatName = element( - * by.repeater("cat in pets").row(1).column("{{cat.name}}")); - * // Returns a promise that resolves to an array of WebElements from a column - * var ages = element( - * by.repeater("cat in pets").column("{{cat.age}}")); - * // Returns a promise that resolves to an array of WebElements containing - * // all rows of the repeater. - * var rows = element(by.repeater("cat in pets")); + * Usage: + * + * element(by.buttonText('Save')); + * + * @param {string} searchText + * @return {webdriver.Locator} */ - repeater(repeatDescriptor: string): webdriver.Locator; - buttonText(searchText: string): webdriver.Locator; + + /** + * Find a button by partial text. + * + * Usage: + * + * element(by.partialButtonText('Save')); + * + * @param {string} searchText + * @return {webdriver.Locator} + */ partialButtonText(searchText: string): webdriver.Locator; + + /** + * Find elements inside an ng-repeat. + * + * Usage: + *
+ * {{cat.name}} + * {{cat.age}} + *
+ * + *
+ * {{$index}} + *
+ *
+ *

{{book.name}}

+ *

{{book.blurb}}

+ *
+ * + * // Returns the DIV for the second cat. + * var secondCat = element(by.repeater('cat in pets').row(1)); + * + * // Returns the SPAN for the first cat's name. + * var firstCatName = element(by.repeater('cat in pets'). + * row(0).column('{{cat.name}}')); + * + * // Returns a promise that resolves to an array of WebElements from a column + * var ages = element.all( + * by.repeater('cat in pets').column('{{cat.age}}')); + * + * // Returns a promise that resolves to an array of WebElements containing + * // all top level elements repeated by the repeater. For 2 pets rows resolves + * // to an array of 2 elements. + * var rows = element.all(by.repeater('cat in pets')); + * + * // Returns a promise that resolves to an array of WebElements containing all + * // the elements with a binding to the book's name. + * var divs = element.all(by.repeater('book in library').column('book.name')); + * + * // Returns a promise that resolves to an array of WebElements containing + * // the DIVs for the second book. + * var bookInfo = element.all(by.repeater('book in library').row(1)); + * + * // Returns the H4 for the first book's name. + * var firstBookName = element(by.repeater('book in library'). + * row(0).column('{{book.name}}')); + * + * // Returns a promise that resolves to an array of WebElements containing + * // all top level elements repeated by the repeater. For 2 books divs + * // resolves to an array of 4 elements. + * var divs = element.all(by.repeater('book in library')); + */ + repeater(repeatDescriptor: string): RepeaterLocator; + + /** + * Find elements by CSS which contain a certain string. + * + * @view + *
    + *
  • Dog
  • + *
  • Cat
  • + *
+ * + * @example + * // Returns the DIV for the dog, but not cat. + * var dog = element(by.cssContainingText('.pet', 'Dog')); + * + * @param cssSelector {string} + * @param searchText {string} + * @return {webdriver.Locator} + */ + cssContainingText(cssSelector: string, searchText: string): webdriver.Locator; + + /** + * Find an element by ng-options expression. + * + * Usage: + * + * + * var allOptions = element.all(by.options('c for c in colors')); + * expect(allOptions.count()).toEqual(2); + * var firstOption = allOptions.first(); + * expect(firstOption.getText()).toEqual('red'); + * + * @param {string} optionsDescriptor ng-options expression. + * @return {webdriver.Locator} + */ + options(optionsDescriptor: string): webdriver.Locator; } var By: IProtractorLocatorStrategy; @@ -718,6 +907,43 @@ declare module protractor { //region Methods + /** + * Instruct webdriver to wait until Angular has finished rendering and has + * no outstanding $http calls before continuing. + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * scripts return value. + */ + waitForAngular(): webdriver.promise.Promise; + + /** + * Waits for Angular to finish rendering before searching for elements. + * @see webdriver.WebDriver.findElement + * + * @param {webdriver.Locator} locator The locator used to find the element. + * @return {!webdriver.WebElement} + */ + findElement(locator: webdriver.Locator): protractor.WebElement; + + /** + * Waits for Angular to finish rendering before searching for elements. + * @see webdriver.WebDriver.findElements + * + * @param {webdriver.Locator} locator The locator used to find the elements. + * @return {!webdriver.promise.Promise} A promise that will be resolved to an + * array of the located {@link webdriver.WebElement}s. + */ + findElements(locator: webdriver.Locator): webdriver.promise.Promise; + + /** + * Tests if an element is present on the page. + * @see webdriver.WebDriver.isElementPresent + * @return {!webdriver.promise.Promise} A promise that will resolve to whether + * the element is present on the page. + */ + isElementPresent(locatorOrElement: webdriver.Locator): webdriver.promise.Promise; + isElementPresent(locatorOrElement: any): webdriver.promise.Promise; + /** * Helper function for finding elements. * @@ -739,40 +965,71 @@ declare module protractor { */ $$(cssLocator: string): ElementArrayFinder; - /** - * Instruct webdriver to wait until Angular has finished rendering and has - * no outstanding $http calls before continuing. - * - * @return {!webdriver.promise.Promise} A promise that will resolve to the - * scripts return value. - */ - waitForAngular(): webdriver.promise.Promise; - - /** - * Wrap a webdriver.WebElement with protractor specific functionality. - * - * @param {webdriver.WebElement} element - * @return {protractor.WebElement} the wrapped web element. - */ - wrapWebElement(element: webdriver.WebElement): protractor.WebElement; - /** * Add a module to load before Angular whenever Protractor.get is called. * Modules will be registered after existing modules already on the page, * so any module registered here will override preexisting modules with the same * name. * - * @param {!string} name The name of the module to load or override. - * @param {!string|Function} script The JavaScript to load the module. + * @param {string} name The name of the module to load or override. + * @param {string|Function} script The JavaScript to load the module. + * @param {...*} varArgs Any additional arguments will be provided to + * the script and may be referenced using the `arguments` object. */ - addMockModule(name: string, script: string): void; - addMockModule(name: string, script: any): void; + addMockModule(name: string, script: string, ...varArgs: any[]): void; + addMockModule(name: string, script: any, ...varArgs: any[]): void; /** * Clear the list of registered mock modules. */ clearMockModules(): void; + /** + * Remove a registered mock module. + * @param {!string} name The name of the module to remove. + */ + removeMockModule(name: string): void; + + /** + * See webdriver.WebDriver.get + * + * Navigate to the given destination and loads mock modules before + * Angular. Assumes that the page being loaded uses Angular. + * If you need to access a page which does not have Angular on load, use + * the wrapped webdriver directly. + * + * @param {string} destination Destination URL. + * @param {number=} opt_timeout Number of seconds to wait for Angular to start. + */ + get(destination: string, opt_timeout?: number): webdriver.promise.Promise; + + /** + * See webdriver.WebDriver.refresh + * + * Makes a full reload of the current page and loads mock modules before + * Angular. Assumes that the page being loaded uses Angular. + * If you need to access a page which does not have Angular on load, use + * the wrapped webdriver directly. + * + * @param {number=} opt_timeout Number of seconds to wait for Angular to start. + */ + refresh(opt_timeout?: number): void; + + /** + * Mixin navigation methods back into the navigation object so that + * they are invoked as before, i.e. driver.navigate().refresh() + */ + navigate(): webdriver.WebDriverNavigation; + + /** + * Browse to another page using in-page navigation. + * + * @param {string} url In page URL using the same syntax as $location.url() + * @returns {!webdriver.promise.Promise} A promise that will resolve once + * page has been changed. + */ + setLocation(url: string): webdriver.promise.Promise; + /** * Returns the current absolute url from AngularJS. */ @@ -799,43 +1056,14 @@ declare module protractor { debugger(): void; /** - * Schedule a command to find an element on the page. If the element cannot be - * found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned - * by the driver. Unlike other commands, this error cannot be suppressed. In - * other words, scheduling a command to find an element doubles as an assert - * that the element is present on the page. To test whether an element is - * present on the page, use {@code #isElementPresent} instead. + * Beta (unstable) pause function for debugging webdriver tests. Use + * browser.pause() in your test to enter the protractor debugger from that + * point in the control flow. + * Does not require changes to the command line (no need to add 'debug'). * - *

The search criteria for find an element may either be a - * {@code webdriver.Locator} object, or a simple JSON object whose sole key - * is one of the accepted locator strategies, as defined by - * {@code webdriver.Locator.Strategy}. For example, the following two statements - * are equivalent: - *

-         * var e1 = driver.findElement(By.id('foo'));
-         * var e2 = driver.findElement({id:'foo'});
-         * 
- * - *

When running in the browser, a WebDriver cannot manipulate DOM elements - * directly; it may do so only through a {@link webdriver.WebElement} reference. - * This function may be used to generate a WebElement from a DOM element. A - * reference to the DOM element will be stored in a known location and this - * driver will attempt to retrieve it through {@link #executeScript}. If the - * element cannot be found (eg, it belongs to a different document than the - * one this instance is currently focused on), a - * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. - * - * @param {!(webdriver.Locator|Object.|Element)} locatorOrElement The - * locator strategy to use when searching for the element, or the actual - * DOM element to be located by the server. - * @param {...} var_args Arguments to pass to {@code #executeScript} if using a - * JavaScript locator. Otherwise ignored. - * @return {!protractor.WebElement} A WebElement that can be used to issue - * commands against the located element. If the element is not found, the - * element will be invalidated and all scheduled commands aborted. + * @param {=number} opt_debugPort Optional port to use for the debugging process */ - findElement(locatorOrElement: webdriver.Locator, ...var_args: any[]): protractor.WebElement; - findElement(locatorOrElement: any, ...var_args: any[]): protractor.WebElement; + pause(opt_debugPort?: number): void; //endregion } @@ -863,9 +1091,19 @@ declare module protractor { } +interface cssSelectorHelper { + (cssLocator: string): protractor.ElementFinder; +} + +interface cssArraySelectorHelper { + (cssLocator: string): protractor.ElementArrayFinder; +} + declare var browser: protractor.Protractor; declare var by: protractor.IProtractorLocatorStrategy; declare var element: protractor.Element; +declare var $: cssSelectorHelper; +declare var $$: cssArraySelectorHelper; declare module 'protractor' { export = protractor; diff --git a/angular-protractor/legacy/angular-protractor-0.17.0-tests.ts b/angular-protractor/legacy/angular-protractor-0.17.0-tests.ts new file mode 100644 index 000000000..dfd413d0e --- /dev/null +++ b/angular-protractor/legacy/angular-protractor-0.17.0-tests.ts @@ -0,0 +1,244 @@ +/// + +function TestWebDriverExports() { + var abstractBuilder: protractor.AbstractBuilder = new protractor.AbstractBuilder(); + var baseAbstractBuilder: webdriver.AbstractBuilder = abstractBuilder; + + var button: protractor.Button = new protractor.Button(); + var baseButton: webdriver.Button = button; + + var key: string = protractor.Key.ADD; + var chord: string = protractor.Key.chord(protractor.Key.NUMPAD0, protractor.Key.NUMPAD1); + + var driver: protractor.WebDriver = new protractor.Builder(). + withCapabilities(protractor.Capabilities.chrome()). + build(); + var baseDriver: webdriver.WebDriver = driver; + + var action: protractor.ActionSequence = new protractor.ActionSequence(driver); + var baseAction: webdriver.ActionSequence = action; + + var alert: protractor.Alert = new protractor.Alert(driver, 'Message'); + var baseAlert: webdriver.Alert = alert; + + var unhandledAlertError: protractor.UnhandledAlertError = new protractor.UnhandledAlertError('Message', alert); + var baseUnhandledAlertError: webdriver.UnhandledAlertError = unhandledAlertError; + + var browser: string = protractor.Browser.ANDROID; + + var builder: protractor.Builder = new protractor.Builder(); + var baseBuilder: webdriver.Builder = builder; + + var capability: string = protractor.Capability.BROWSER_NAME; + + var capabilities: protractor.Capabilities = protractor.Capabilities.chrome(); + var baseCapabilities: webdriver.Capabilities = capabilities; + + var commandName: string = protractor.CommandName.CLICK_ELEMENT; + + var command: protractor.Command = new protractor.Command(protractor.CommandName.CLICK); + var baseCommand: webdriver.Command = command; + + var eventEmitter: protractor.EventEmitter = new protractor.EventEmitter(); + var baseEventEmitter: webdriver.EventEmitter = eventEmitter; + + var firefoxDomExecutor: protractor.FirefoxDomExecutor = new protractor.FirefoxDomExecutor(); + var baseFirefoxDomExecutor: webdriver.FirefoxDomExecutor = firefoxDomExecutor; + + var webElement: protractor.WebElement = new protractor.WebElement(driver, new protractor.promise.Promise()); + var baseWebElement: webdriver.WebElement = webElement; + + var locator: protractor.Locator = new protractor.Locator('id', 'ABC'); + var baseLocator: webdriver.Locator = locator; + + var session: protractor.Session = new protractor.Session('ABC', webdriver.Capabilities.android()); + var baseSession: webdriver.Session = session; + + locator = protractor.By.name('name'); + + // logging module + + var levelName: string = protractor.logging.LevelName.ALL; + var loggingType: string = protractor.logging.Type.CLIENT; + + var level: webdriver.logging.Level = protractor.logging.Level.ALL; + + var entry: protractor.logging.Entry = new protractor.logging.Entry(protractor.logging.Level.ALL, 'Message'); + var baseEntry: webdriver.logging.Entry = entry; + + level = protractor.logging.getLevel('DEBUG'); + + protractor.logging.Preferences = { a: 123 }; + + // promise module + + var promise: protractor.promise.Promise = new protractor.promise.Promise(); + var basePromise: webdriver.promise.Promise = promise; + + var deferred: protractor.promise.Deferred = new protractor.promise.Deferred(); + var baseDeferred: webdriver.promise.Deferred = deferred; + + var flow: protractor.promise.ControlFlow = new protractor.promise.ControlFlow(); + var baseFlow: webdriver.promise.ControlFlow = flow; + + protractor.promise.asap(promise, function(value: any){ return true; }); + protractor.promise.asap(promise, function(value: any){}, function(err: any) { return 'ABC'; }); + + promise = protractor.promise.checkedNodeCall(function(err: any, value: any) { return 123; }); + + flow = protractor.promise.controlFlow(); + + promise = protractor.promise.createFlow(function(newFlow: webdriver.promise.ControlFlow) { }); + + deferred = protractor.promise.defer(function() {}); + deferred = protractor.promise.defer(function(reason?: any) {}); + + promise = protractor.promise.delayed(123); + + promise = protractor.promise.fulfilled(); + promise = protractor.promise.fulfilled({a: 123}); + + promise = protractor.promise.fullyResolved({a: 123}); + + var isPromise: boolean = protractor.promise.isPromise('ABC'); + + promise = protractor.promise.rejected({a: 123}); + + protractor.promise.setDefaultFlow(new webdriver.promise.ControlFlow()); + + promise = protractor.promise.when(promise, function(value: any) { return 123; }, function(err: Error) { return 123; }); + + // error module + + var errorCode: number = protractor.error.ErrorCode.ELEMENT_NOT_VISIBLE; + var error: protractor.error.Error = new protractor.error.Error(protractor.error.ErrorCode.ELEMENT_NOT_VISIBLE); + var baseError: webdriver.error.Error = error; + + // process module + + var isNative: boolean = protractor.process.isNative(); + var value: string; + + value = protractor.process.getEnv('name'); + value = protractor.process.getEnv('name', 'default'); + + protractor.process.setEnv('name', 'value'); + protractor.process.setEnv('name', 123); + +} + +function TestProtractor() { + var ptor: protractor.Protractor; + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + ptor = new protractor.Protractor(driver); + ptor = new protractor.Protractor(driver, 'baseUrl'); + ptor = new protractor.Protractor(driver, 'baseUrl', 'rootElement'); + ptor = protractor.getInstance(); + protractor.setInstance(ptor); + + ptor = protractor.wrapDriver(driver); + ptor = protractor.wrapDriver(driver, 'baseUrl'); + ptor = protractor.wrapDriver(driver, 'baseUrl', 'rootElement'); + + ptor = browser; + + driver = ptor.driver; + var baseUrl: string = ptor.baseUrl; + var rootEl: string = ptor.rootEl; + var ignoreSynchronization: boolean = ptor.ignoreSynchronization; + var params: any = ptor.params; + + ptor.debugger(); + + ptor.clearMockModules(); + ptor.addMockModule('name', 'script'); + ptor.addMockModule('name', function() {}); + ptor.waitForAngular(); + + var elementFinder: protractor.ElementFinder; + + elementFinder = ptor.element(by.id('ABC')); + elementFinder = ptor.$('.class'); + + var elementArrayFinder: protractor.ElementArrayFinder = ptor.$$('.class'); + + var webElement: webdriver.WebElement = ptor.wrapWebElement(new webdriver.WebElement(driver, 'id')); + + var locationAbsUrl: webdriver.promise.Promise = ptor.getLocationAbsUrl(); +} + +function TestElement() { + var elementFinder: protractor.ElementFinder = element(by.id('id')); + var elementArrayFinder: protractor.ElementArrayFinder = element.all(by.className('class')); +} + +function TestElementFinder() { + var elementFinder: protractor.ElementFinder = element(by.id('id')); + var promise: webdriver.promise.Promise; + + promise = elementFinder.click(); + promise = elementFinder.sendKeys(protractor.Key.UP, protractor.Key.DOWN); + promise = elementFinder.getTagName(); + promise = elementFinder.getCssValue('display'); + promise = elementFinder.getAttribute('atribute'); + promise = elementFinder.getText(); + promise = elementFinder.getSize(); + promise = elementFinder.getLocation(); + promise = elementFinder.isEnabled(); + promise = elementFinder.isSelected(); + promise = elementFinder.submit(); + promise = elementFinder.clear(); + promise = elementFinder.isDisplayed(); + promise = elementFinder.getOuterHtml(); + promise = elementFinder.getInnerHtml(); + promise = elementFinder.isElementPresent(by.id('id')); + promise = elementFinder.isElementPresent(by.js('function(a, b, c) {}'), 1, 2, 3); + promise = elementFinder.findElements(by.className('class')); + promise = elementFinder.findElements(by.js('function(a, b, c) {}'), 1, 2, 3); + promise = elementFinder.$$('.class'); + promise = elementFinder.evaluate('expression'); + promise = elementFinder.isPresent(); + + var webElement: webdriver.WebElement; + + webElement = elementFinder.$('.class'); + webElement = elementFinder.findElement(by.id('id')); + webElement = elementFinder.findElement(by.js('function(a, b, c) {}'), 1, 2, 3); + webElement = elementFinder.find(); +} + +// This function tests the angular specific locator strategies. +function TestLocatorStrategies() { + var ptor: protractor.Protractor = protractor.getInstance(); + var webElement: webdriver.WebElement; + + // Protractor Specific Locators + webElement = ptor.findElement(protractor.By.binding('binding')); + webElement = ptor.findElement(protractor.By.select('select')); + webElement = ptor.findElement(protractor.By.selectedOption('selectedOptions')); + webElement = ptor.findElement(protractor.By.input('input')); + webElement = ptor.findElement(protractor.By.model('model')); + webElement = ptor.findElement(protractor.By.textarea('textarea')); + webElement = ptor.findElement(protractor.By.repeater('repeater')); + webElement = ptor.findElement(protractor.By.buttonText('buttonText')); + webElement = ptor.findElement(protractor.By.partialButtonText('partialButtonText')); +} + +// This function tests the methods that were added to the base WebElement class +function TestWebElements() { + var ptor: protractor.Protractor = protractor.getInstance(); + + var webElement: protractor.WebElement; + var promise: webdriver.promise.Promise; + + webElement = ptor.findElement(by.id('id')).$('.class'); + promise = ptor.findElement(by.id('id')).$$('.class'); + promise = ptor.findElement(by.id('id')).evaluate('something'); + + webElement = webElement.findElement(by.id('id')).$('.class'); + promise = webElement.findElement(by.id('id')).$$('.class'); + promise = webElement.findElement(by.id('id')).evaluate('something'); +} diff --git a/angular-protractor/legacy/angular-protractor-0.17.0.d.ts b/angular-protractor/legacy/angular-protractor-0.17.0.d.ts new file mode 100644 index 000000000..38458b493 --- /dev/null +++ b/angular-protractor/legacy/angular-protractor-0.17.0.d.ts @@ -0,0 +1,906 @@ +// Type definitions for Angular Protractor 0.17.0 +// Project: https://github.com/angular/protractor +// Definitions by: Bill Armstrong +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module protractor { + //region Wrapped webdriver Items + + class AbstractBuilder extends webdriver.AbstractBuilder {} + class ActionSequence extends webdriver.ActionSequence {} + class Alert extends webdriver.Alert {} + class Builder extends webdriver.Builder {} + class Button extends webdriver.Button {} + class Capabilities extends webdriver.Capabilities {} + class Command extends webdriver.Command {} + class EventEmitter extends webdriver.EventEmitter {} + class FirefoxDomExecutor extends webdriver.FirefoxDomExecutor {} + class Locator extends webdriver.Locator {} + class Session extends webdriver.Session {} + class WebDriver extends webdriver.WebDriver {} + class Browser extends webdriver.Browser {} + class Capability extends webdriver.Capability {} + class CommandName extends webdriver.CommandName {} + class Key extends webdriver.Key {} + class UnhandledAlertError extends webdriver.UnhandledAlertError {} + + class WebElement extends webdriver.WebElement { + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElement + * @return {!protractor.WebElement} + */ + $(selector: string): protractor.WebElement; + + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElements + * @return {!webdriver.promise.Promise} A promise that will be resolved to an + * array of the located {@link webdriver.WebElement}s. + */ + $$(selector: string): webdriver.promise.Promise; + + /** + * Evalates the input as if it were on the scope of the current element. + * @param {string} expression + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * evaluated expression. The result will be resolved as in + * {@link webdriver.WebDriver.executeScript}. In summary - primitives will + * be resolved as is, functions will be converted to string, and elements + * will be returned as a WebElement. + */ + evaluate(expression: string): webdriver.promise.Promise; + + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@code #isElementPresent} instead. + *

+ * The search criteria for find an element may either be a + * {@code webdriver.Locator} object, or a simple JSON object whose sole key + * is one of the accepted locator strategies, as defined by + * {@code webdriver.Locator.Strategy}. For example, the following two + * statements are equivalent: + *

+         * var e1 = element.findElement(By.id('foo'));
+         * var e2 = element.findElement({id:'foo'});
+         * 
+ *

+ * Note that JS locator searches cannot be restricted to a subtree. All such + * searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the element. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {protractor.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: webdriver.Locator, ...var_args: any[]): protractor.WebElement; + findElement(locator: any, ...var_args: any[]): protractor.WebElement; + } + + module command { + class Command extends webdriver.Command {} + class CommandName extends webdriver.CommandName {} + } + + module error { + class Error extends webdriver.error.Error {} + class ErrorCode extends webdriver.error.ErrorCode {} + } + + module events { + class EventEmitter extends webdriver.EventEmitter {} + } + + module logging { + var Preferences: any; + + class LevelName extends webdriver.logging.LevelName {} + class Type extends webdriver.logging.Type {} + class Level extends webdriver.logging.Level {} + class Entry extends webdriver.logging.Entry {} + + function getLevel(nameOrValue: string): webdriver.logging.Level; + function getLevel(nameOrValue: number): webdriver.logging.Level; + } + + module promise { + class Promise extends webdriver.promise.Promise {} + class Deferred extends webdriver.promise.Deferred {} + class ControlFlow extends webdriver.promise.ControlFlow {} + + /** + * @return {!webdriver.promise.ControlFlow} The currently active control flow. + */ + function controlFlow(): webdriver.promise.ControlFlow; + + /** + * Creates a new control flow. The provided callback will be invoked as the + * first task within the new flow, with the flow as its sole argument. Returns + * a promise that resolves to the callback result. + * @param {function(!webdriver.promise.ControlFlow)} callback The entry point + * to the newly created flow. + * @return {!webdriver.promise.Promise} A promise that resolves to the callback + * result. + */ + function createFlow(callback: (flow: webdriver.promise.ControlFlow) => any): webdriver.promise.Promise; + + /** + * Determines whether a {@code value} should be treated as a promise. + * Any object whose "then" property is a function will be considered a promise. + * + * @param {*} value The value to test. + * @return {boolean} Whether the value is a promise. + */ + function isPromise(value: any): boolean; + + /** + * Creates a promise that will be resolved at a set time in the future. + * @param {number} ms The amount of time, in milliseconds, to wait before + * resolving the promise. + * @return {!webdriver.promise.Promise} The promise. + */ + function delayed(ms: number): webdriver.promise.Promise; + + /** + * Creates a new deferred object. + * @param {Function=} opt_canceller Function to call when cancelling the + * computation of this instance's value. + * @return {!webdriver.promise.Deferred} The new deferred object. + */ + function defer(opt_canceller?: any): webdriver.promise.Deferred; + + /** + * Creates a promise that has been resolved with the given value. + * @param {*=} opt_value The resolved value. + * @return {!webdriver.promise.Promise} The resolved promise. + */ + function fulfilled(opt_value?: any): webdriver.promise.Promise; + + /** + * Creates a promise that has been rejected with the given reason. + * @param {*=} opt_reason The rejection reason; may be any value, but is + * usually an Error or a string. + * @return {!webdriver.promise.Promise} The rejected promise. + */ + function rejected(opt_reason?: any): webdriver.promise.Promise; + + /** + * Wraps a function that is assumed to be a node-style callback as its final + * argument. This callback takes two arguments: an error value (which will be + * null if the call succeeded), and the success value as the second argument. + * If the call fails, the returned promise will be rejected, otherwise it will + * be resolved with the result. + * @param {!Function} fn The function to wrap. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * result of the provided function's callback. + */ + function checkedNodeCall(fn: (error: any, value: any) => any): webdriver.promise.Promise; + + /** + * Registers an observer on a promised {@code value}, returning a new promise + * that will be resolved when the value is. If {@code value} is not a promise, + * then the return promise will be immediately resolved. + * @param {*} value The value to observe. + * @param {Function=} opt_callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + * @return {!webdriver.promise.Promise} A new promise. + */ + function when(value: any, opt_callback?: (value: any) => any, opt_errback?: (error: any) => any): webdriver.promise.Promise; + + /** + * Invokes the appropriate callback function as soon as a promised + * {@code value} is resolved. This function is similar to + * {@code webdriver.promise.when}, except it does not return a new promise. + * @param {*} value The value to observe. + * @param {Function} callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + */ + function asap(value: any, callback: (value: any) => any, opt_errback?: (error: any) => any): void; + + /** + * Returns a promise that will be resolved with the input value in a + * fully-resolved state. If the value is an array, each element will be fully + * resolved. Likewise, if the value is an object, all keys will be fully + * resolved. In both cases, all nested arrays and objects will also be + * fully resolved. All fields are resolved in place; the returned promise will + * resolve on {@code value} and not a copy. + * + * Warning: This function makes no checks against objects that contain + * cyclical references: + * + * var value = {}; + * value['self'] = value; + * webdriver.promise.fullyResolved(value); // Stack overflow. + * + * @param {*} value The value to fully resolve. + * @return {!webdriver.promise.Promise} A promise for a fully resolved version + * of the input value. + */ + function fullyResolved(value: any): webdriver.promise.Promise; + + /** + * Changes the default flow to use when no others are active. + * @param {!webdriver.promise.ControlFlow} flow The new default flow. + * @throws {Error} If the default flow is not currently active. + */ + function setDefaultFlow(flow: webdriver.promise.ControlFlow): void; + + } + + module process { + + /** + * Queries for a named environment variable. + * @param {string} name The name of the environment variable to look up. + * @param {string=} opt_default The default value if the named variable is not + * defined. + * @return {string} The queried environment variable. + */ + function getEnv(name: string, opt_default?: string): string; + + /** + * @return {boolean} Whether the current process is Node's native process + * object. + */ + function isNative(): boolean; + + /** + * Sets an environment value. If the new value is either null or undefined, the + * environment variable will be cleared. + * @param {string} name The value to set. + * @param {*} value The new value; will be coerced to a string. + */ + function setEnv(name: string, value: any): void; + + } + + //endregion + + interface Element { + (locator: webdriver.Locator): ElementFinder; + all(locator: webdriver.Locator): ElementArrayFinder; + } + + interface ElementFinder { + /** + * Schedules a command to click on this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the click command has completed. + */ + click(): webdriver.promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by this + * instance. + *

+ * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the keysequence, that key state is toggled until one of the + * following occurs: + *

    + *
  • The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + *
  • + *
  • The {@code webdriver.Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys("text was", + * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, + * "now text is"); + * // Alternatively: + * element.sendKeys("text was", + * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), + * "now text is"); + *
  • + *
  • The end of the keysequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying keyup + * events). + *
  • + *
+ * Note: On browsers where native keyboard events are not yet + * supported (e.g. Firefox on OS X), key events will be synthesized. Special + * punctionation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...string} var_args The sequence of keys to + * type. All arguments will be joined into a single sequence (var_args is + * permitted for convenience). + * @return {!webdriver.promise.Promise} A promise that will be resolved when all + * keys have been typed. + */ + sendKeys(...var_args: string[]): webdriver.promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's tag name. + */ + getTagName(): webdriver.promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + *

+ * Warning: the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * requested CSS value. + */ + getCssValue(cssStyleProperty: string): webdriver.promise.Promise; + + /** + * Schedules a command to query for the value of the given attribute of the + * element. Will return the current value even if it has been modified after the + * page has been loaded. More exactly, this method will return the value of the + * given attribute, unless that attribute is not present, in which case the + * value of the property with the same name is returned. If neither value is + * set, null is returned. The "style" attribute is converted as best can be to a + * text representation with a trailing semi-colon. The following are deemed to + * be "boolean" attributes and will be returned as thus: + * + *

async, autofocus, autoplay, checked, compact, complete, controls, declare, + * defaultchecked, defaultselected, defer, disabled, draggable, ended, + * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, + * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, + * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, + * selected, spellcheck, truespeed, willvalidate + * + *

Finally, the following commonly mis-capitalized attribute/property names + * are evaluated as expected: + *

    + *
  • "class" + *
  • "readonly" + *
+ * @param {string} attributeName The name of the attribute to query. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * attribute's value. + */ + getAttribute(attributeName: string): webdriver.promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's visible text. + */ + getText(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's size as a {@code {width:number, height:number}} object. + */ + getSize(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!webdriver.promise.Promise} A promise that will be resolved to the + * element's location as a {@code {x:number, y:number}} object. + */ + getLocation(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently enabled. + */ + isEnabled(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently selected. + */ + isSelected(): webdriver.promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the form has been submitted. + */ + submit(): webdriver.promise.Promise; + + /** + * Schedules a command to clear the {@code value} of this element. This command + * has no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the element has been cleared. + */ + clear(): webdriver.promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently visible on the page. + */ + isDisplayed(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the element's outer HTML. + */ + getOuterHtml(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): webdriver.promise.Promise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + *

Note that JS locator searches cannot be restricted to a subtree of the + * DOM. All such searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the element. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether an element could be located on the page. + */ + isElementPresent(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; + isElementPresent(locator: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that match + * the given search criteria. + *

+ * Note that JS locator searches cannot be restricted to a subtree. All such + * searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the elements. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {!webdriver.promise.Promise} A promise that will be resolved with an + * array of located {@link webdriver.WebElement}s. + */ + findElements(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; + findElements(locator: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElement + * @return {!protractor.WebElement} + */ + $(selector: string): protractor.WebElement; + + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElements + * @return {!webdriver.promise.Promise} A promise that will be resolved to an + * array of the located {@link webdriver.WebElement}s. + */ + $$(selector: string): webdriver.promise.Promise; + + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@code #isElementPresent} instead. + *

+ * The search criteria for find an element may either be a + * {@code webdriver.Locator} object, or a simple JSON object whose sole key + * is one of the accepted locator strategies, as defined by + * {@code webdriver.Locator.Strategy}. For example, the following two + * statements are equivalent: + *

+         * var e1 = element.findElement(By.id('foo'));
+         * var e2 = element.findElement({id:'foo'});
+         * 
+ *

+ * Note that JS locator searches cannot be restricted to a subtree. All such + * searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the element. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {protractor.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: webdriver.Locator, ...var_args: any[]): protractor.WebElement; + findElement(locator: any, ...var_args: any[]): protractor.WebElement; + + /** + * Evalates the input as if it were on the scope of the current element. + * @param {string} expression + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * evaluated expression. The result will be resolved as in + * {@link webdriver.WebDriver.executeScript}. In summary - primitives will + * be resolved as is, functions will be converted to string, and elements + * will be returned as a WebElement. + */ + evaluate(expression: string): webdriver.promise.Promise; + + /** + * Use as: element(locator).element(locator) + * Calls to element may be chained to find elements within a parent. + * + * @param {webdriver.Locator} The locator that will be used to find descendents. + * + * @return {protractor.ElementFinder} the descendent element found by the locator + */ + element(locator: webdriver.Locator): protractor.ElementFinder; + + /** + * Use as: element(locator).all(locator) + * Calls to element may be chained to find an array of elements within a parent. + * + * @param {webdriver.Locator} The locator that will be used to find descendents. + * + * @return {protractor.ElementArrayFinder} the descendent elements found by the locator + */ + all(locator: webdriver.Locator): protractor.ElementArrayFinder; + + find(): protractor.WebElement; + + isPresent(): webdriver.promise.Promise; + } + + interface ElementArrayFinder{ + count(): webdriver.promise.Promise; + get(index: number): protractor.WebElement; + first(): protractor.WebElement; + last(): protractor.WebElement; + then(fn: (value: any) => any): webdriver.promise.Promise; + } + + class LocatorWithColumn extends webdriver.Locator { + column(index: number): webdriver.Locator; + } + + class RepeaterLocator extends LocatorWithColumn { + row(index: number): LocatorWithColumn; + } + + interface IProtractorLocatorStrategy extends webdriver.ILocatorStrategy { + /** + * Add a locator to this instance of ProtractorBy. This locator can then be + * used with element(by.()). + * + * @param {string} name + * @param {function|string} script A script to be run in the context of + * the browser. This script will be passed an array of arguments + * that begins with the element scoping the search, and then + * contains any args passed into the locator. It should return + * an array of elements. + */ + addLocator(name: string, script: any): void; + + /** + * Usage: + * {{status}} + * var status = element(by.binding('{{status}}')); + */ + binding(bindingDescriptor: string): webdriver.Locator; + + /** + * Usage: + * + * element(by.select("user")); + */ + select(model: string): webdriver.Locator; + + /** + * Usage: + * + * element(by.selectedOption("user")); + */ + selectedOption(model: string): webdriver.Locator; + + /** + * @DEPRECATED - use 'model' instead. + * Usage: + * + * element(by.input('user')); + */ + input(model: string): webdriver.Locator; + + /** + * Usage: + * + * element(by.model('user')); + */ + model(model: string): webdriver.Locator; + + /** + * Usage: + * + * element(by.textarea("user")); + */ + textarea(model: string): webdriver.Locator; + + /** + * Usage: + *

+ * {{cat.name}} + * {{cat.age}} + *
+ * + * // Returns the DIV for the second cat. + * var secondCat = element(by.repeater("cat in pets").row(2)); + * // Returns the SPAN for the first cat's name. + * var firstCatName = element( + * by.repeater("cat in pets").row(1).column("{{cat.name}}")); + * // Returns a promise that resolves to an array of WebElements from a column + * var ages = element( + * by.repeater("cat in pets").column("{{cat.age}}")); + * // Returns a promise that resolves to an array of WebElements containing + * // all rows of the repeater. + * var rows = element(by.repeater("cat in pets")); + */ + repeater(repeatDescriptor: string): RepeaterLocator; + + buttonText(searchText: string): webdriver.Locator; + + partialButtonText(searchText: string): webdriver.Locator; + } + + var By: IProtractorLocatorStrategy; + + class Protractor extends webdriver.WebDriver { + + //region Constructors + + /** + * @param {webdriver.WebDriver} webdriver + * @param {string=} opt_baseUrl A base URL to run get requests against. + * @param {string=body} opt_rootElement Selector element that has an ng-app in + * scope. + * @constructor + */ + constructor(webdriver: webdriver.WebDriver, opt_baseUrl?: string, opt_rootElement?: string); + + //endregion + + //region Properties + + /** + * The wrapped webdriver instance. Use this to interact with pages that do + * not contain Angular (such as a log-in screen). + * + * @type {webdriver.WebDriver} + */ + driver: webdriver.WebDriver; + + /** + * All get methods will be resolved against this base URL. Relative URLs are = + * resolved the way anchor tags resolve. + * + * @type {string} + */ + baseUrl: string; + + /** + * The css selector for an element on which to find Angular. This is usually + * 'body' but if your ng-app is on a subsection of the page it may be + * a subelement. + * + * @type {string} + */ + rootEl: string; + + /** + * If true, Protractor will not attempt to synchronize with the page before + * performing actions. This can be harmful because Protractor will not wait + * until $timeouts and $http calls have been processed, which can cause + * tests to become flaky. This should be used only when necessary, such as + * when a page continuously polls an API using $timeout. + * + * @type {boolean} + */ + ignoreSynchronization: boolean; + + /** + * An object that holds custom test parameters. + * + * @type {Object} + */ + params: any; + + //endregion + + //region Methods + + /** + * Helper function for finding elements. + * + * @type {function(webdriver.Locator): ElementFinder} + */ + element(locator: webdriver.Locator): ElementFinder; + + /** + * Helper function for finding elements by css. + * + * @type {function(string): ElementFinder} + */ + $(cssLocator: string): ElementFinder; + + /** + * Helper function for finding arrays of elements by css. + * + * @type {function(string): ElementArrayFinder} + */ + $$(cssLocator: string): ElementArrayFinder; + + /** + * Instruct webdriver to wait until Angular has finished rendering and has + * no outstanding $http calls before continuing. + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * scripts return value. + */ + waitForAngular(): webdriver.promise.Promise; + + /** + * Wrap a webdriver.WebElement with protractor specific functionality. + * + * @param {webdriver.WebElement} element + * @return {protractor.WebElement} the wrapped web element. + */ + wrapWebElement(element: webdriver.WebElement): protractor.WebElement; + + /** + * Add a module to load before Angular whenever Protractor.get is called. + * Modules will be registered after existing modules already on the page, + * so any module registered here will override preexisting modules with the same + * name. + * + * @param {!string} name The name of the module to load or override. + * @param {!string|Function} script The JavaScript to load the module. + */ + addMockModule(name: string, script: string): void; + addMockModule(name: string, script: any): void; + + /** + * Clear the list of registered mock modules. + */ + clearMockModules(): void; + + /** + * Returns the current absolute url from AngularJS. + */ + getLocationAbsUrl(): webdriver.promise.Promise; + + /** + * Pauses the test and injects some helper functions into the browser, so that + * debugging may be done in the browser console. + * + * This should be used under node in debug mode, i.e. with + * protractor debug + * + * While in the debugger, commands can be scheduled through webdriver by + * entering the repl: + * debug> repl + * Press Ctrl + C to leave rdebug repl + * > ptor.findElement(protractor.By.input('user').sendKeys('Laura')); + * > ptor.debugger(); + * debug> c + * + * This will run the sendKeys command as the next task, then re-enter the + * debugger. + */ + debugger(): void; + + /** + * Schedule a command to find an element on the page. If the element cannot be + * found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned + * by the driver. Unlike other commands, this error cannot be suppressed. In + * other words, scheduling a command to find an element doubles as an assert + * that the element is present on the page. To test whether an element is + * present on the page, use {@code #isElementPresent} instead. + * + *

The search criteria for find an element may either be a + * {@code webdriver.Locator} object, or a simple JSON object whose sole key + * is one of the accepted locator strategies, as defined by + * {@code webdriver.Locator.Strategy}. For example, the following two statements + * are equivalent: + *

+         * var e1 = driver.findElement(By.id('foo'));
+         * var e2 = driver.findElement({id:'foo'});
+         * 
+ * + *

When running in the browser, a WebDriver cannot manipulate DOM elements + * directly; it may do so only through a {@link webdriver.WebElement} reference. + * This function may be used to generate a WebElement from a DOM element. A + * reference to the DOM element will be stored in a known location and this + * driver will attempt to retrieve it through {@link #executeScript}. If the + * element cannot be found (eg, it belongs to a different document than the + * one this instance is currently focused on), a + * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. + * + * @param {!(webdriver.Locator|Object.|Element)} locatorOrElement The + * locator strategy to use when searching for the element, or the actual + * DOM element to be located by the server. + * @param {...} var_args Arguments to pass to {@code #executeScript} if using a + * JavaScript locator. Otherwise ignored. + * @return {!protractor.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locatorOrElement: webdriver.Locator, ...var_args: any[]): protractor.WebElement; + findElement(locatorOrElement: any, ...var_args: any[]): protractor.WebElement; + + //endregion + } + + /** + * Create a new instance of Protractor by wrapping a webdriver instance. + * + * @param {webdriver.WebDriver} webdriver The configured webdriver instance. + * @param {string=} opt_baseUrl A URL to prepend to relative gets. + * @return {Protractor} + */ + function wrapDriver(webdriver: webdriver.WebDriver, opt_baseUrl?: string, opt_rootElement?: string): Protractor; + + /** + * Set a singleton instance of protractor. + * @param {Protractor} ptor + */ + function setInstance(ptor: Protractor): void; + + /** + * Get the singleton instance. + * @return {Protractor} + */ + function getInstance(): Protractor; + +} + +interface cssSelectorHelper { + (cssLocator: string): protractor.ElementFinder; +} + +declare var browser: protractor.Protractor; +declare var by: protractor.IProtractorLocatorStrategy; +declare var element: protractor.Element; +declare var $: cssSelectorHelper; +declare var $$: cssSelectorHelper; + +declare module 'protractor' { + export = protractor; +} From a5c374e96a57b59df69a78de61df0f4eac6c95f3 Mon Sep 17 00:00:00 2001 From: Douglas Eichelberger Date: Tue, 15 Jul 2014 17:09:59 -0700 Subject: [PATCH 119/324] Fix JQueryUI Slider definitions --- jqueryui/jqueryui.d.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index 26492bf20..26e2d6cdc 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -609,11 +609,14 @@ declare module JQueryUI { orientation?: string; range?: any; // boolean or string step?: number; - // value?: number; - // values?: number[]; + value?: number; + values?: number[]; } interface SliderUIParams { + handle?: JQuery; + value?: number; + values?: number[]; } interface SliderEvent { From b41dc8fe9c5bb19d8bf0c1a7d5f187dccbd60c4e Mon Sep 17 00:00:00 2001 From: NewNotMoon Date: Wed, 16 Jul 2014 09:13:55 +0900 Subject: [PATCH 120/324] add jquery.pjax.falsandtru --- CONTRIBUTORS.md | 1 + jquery.pjax.falsandtru/jquery.pjax-tests.ts | 96 ++++++++++ jquery.pjax.falsandtru/jquery.pjax.d.ts | 189 ++++++++++++++++++++ 3 files changed, 286 insertions(+) create mode 100644 jquery.pjax.falsandtru/jquery.pjax-tests.ts create mode 100644 jquery.pjax.falsandtru/jquery.pjax.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 0fa132294..ef4467f22 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -164,6 +164,7 @@ All definitions files include a header with the author and editors, so at some p * [jQuery.payment](http://needim.github.io/noty/) (by [Eric J. Smith](https://github.com/ejsmith/)) * [jQuery.pickadate](https://github.com/amsul/pickadate.js) (by [Theodore Brown](https://github.com/theodorejb)) * [jQuery.pjax](https://github.com/defunkt/jquery-pjax) (by [Junle Li](https://github.com/lijunle)) +* [jQuery.pjax.falsandtru](https://github.com/falsandtru/jquery.pjax.js/) (by [NewNotMoon](https://new.not-moon.net/)) * [jQuery.pnotify](http://sciactive.github.io/pnotify/) (by [David Sichau](https://github.com/DavidSichau/)) * [jQuery.postMessage](http://benalman.com/projects/jquery-postmessage-plugin/) (by [Junle Li](https://github.com/lijunle)) * [jQuery.prettyphoto](https://github.com/scaron/prettyphoto) (by [Paul Gaske](https://github.com/pgaske)) diff --git a/jquery.pjax.falsandtru/jquery.pjax-tests.ts b/jquery.pjax.falsandtru/jquery.pjax-tests.ts new file mode 100644 index 000000000..fd8cbaecd --- /dev/null +++ b/jquery.pjax.falsandtru/jquery.pjax-tests.ts @@ -0,0 +1,96 @@ +/// +/// + +function test_pjax() { + $.pjax(); +} + +function test_pjax_selector() { + $('a').pjax(); +} + +function test_pjax_option() { + $.pjax({ + area: 'body', + load: { + head: 'base, meta, link', + css: true, + script: true + }, + cache: { click: true, submit: false, popstate: true }, + server: { query: null } + }); +} + +function test_pjax_event() { + $.pjax({ + wait: 1000 + }); + $(document).bind('pjax.request', function () { + $('div.loading').fadeIn(100); + }); + $(document).bind('pjax.render', function () { + $('div.loading').fadeOut(500); + }); +} + +function test_pjax_progressbar() { + $('body').append('

'); + $.pjax({ + area: 'div.pjax', + callbacks: { + before: function () { + $('div.loading').children().width(''); + $('div.loading').fadeIn(0); + }, + ajax: { + xhr: function () { + var xhr = jQuery.ajaxSettings.xhr(); + + $('div.loading').children().width('5%'); + if (xhr instanceof Object && 'onprogress' in xhr) { + xhr.addEventListener('progress', function (event) { + var percentage = event.total ? event.loaded / event.total : 0.4; + percentage = percentage * 90 + 5; + $('div.loading').children().width(percentage + '%'); + }, false); + xhr.addEventListener('load', function (event) { + $('div.loading').children().width('95%'); + }, false); + xhr.addEventListener('error', function (event) { + $('div.loading').children().css('background-color', '#00f'); + }, false); + } + return xhr; + } + }, + update: { + content: { + after: function () { + $('div.loading').children().width('96.25%'); + } + }, + css: { + after: function () { + $('div.loading').children().width('97.5%'); + } + }, + script: { + after: function () { + $('div.loading').children().width('98.75%'); + } + }, + render: { + after: function () { + $('div.loading').children().width('100%'); + $('div.loading').fadeOut(50); + } + } + } + }, + ajax: { timeout: 3000 }, + wait: 1000 + }); +} \ No newline at end of file diff --git a/jquery.pjax.falsandtru/jquery.pjax.d.ts b/jquery.pjax.falsandtru/jquery.pjax.d.ts new file mode 100644 index 000000000..07bc153df --- /dev/null +++ b/jquery.pjax.falsandtru/jquery.pjax.d.ts @@ -0,0 +1,189 @@ +// Type definitions for jquery.pjax.ts by falsandtru +// Project: https://github.com/falsandtru/jquery.pjax.js/ +// Definitions by: 新ゝ月 NewNotMoon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface PjaxSetting { + gns?: string; + ns?: string; + area?: any; // string, array, function( event, param, origUrl, destUrl ) + link?: string; + filter?: any; // string, function() + form?: string; + scope?: Object; + state?: any; // any, function(event, param, origUrl, destUrl ) + scrollTop?: any; // number, function( event, param, origUrl, destUrl ), null, false + scrollLeft?: any; // number, function( event, param, origUrl, destUrl ), null, false + scroll?: { + delay?: number; + record?: boolean //internal + queue?: number[] //internal + }; + ajax?: JQueryAjaxSettings; + contentType?: string; + load?: { + head?: string; + css?: boolean; + script?: boolean; + execute?: boolean; + reload?: string; + ignore?: string; + sync?: boolean; + ajax?: JQueryAjaxSettings; + rewrite?: (element: any) => any; + redirect?: boolean; + }; + interval?: number; + cache?: { + click?: boolean; + submit?: boolean; + popstate?: boolean; + get?: boolean; + post?: boolean; + page?: boolean; + size?: number; + mix?: number; + expires?: { + min?: number; + max?: number; + }; + }; + wait?: any; // number, function( event, param, origUrl, destUrl ): number + fallback?: any; // boolean, function( event, param, origUrl, destUrl ): boolean + fix?: { + location?: boolean; + history?: boolean; + scroll?: boolean; + reset?: boolean; + }; + database?: boolean; + server?: { + query?: any; // string, object + header?: { + area?: boolean; + head?: boolean; + css?: boolean; + script?: boolean; + }; + }; + callback?: (event: JQueryEventObject, param: any) => any; + callbacks?: { + before?: (event: JQueryEventObject, param: any) => any; + after?: (event: JQueryEventObject, param: any) => any; + ajax?: { + xhr?: (event: JQueryEventObject, param: any) => any; + beforeSend?: (event: JQueryEventObject, param: any, data: any, ajaxSettings: any) => any; + dataFilter?: (event: JQueryEventObject, param: any, data: any, dataType: any) => any; + success?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + error?: (event: JQueryEventObject, param: any, XMLHttpRequest: XMLHttpRequest, textStatus: string, errorThrown: any) => any; + complete?: (event: JQueryEventObject, param: any, XMLHttpRequest: XMLHttpRequest, textStatus: string) => any; + done?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + fail?: (event: JQueryEventObject, param: any, XMLHttpRequest: XMLHttpRequest, textStatus: string, errorThrown: any) => any; + always?: (event: JQueryEventObject, param: any, XMLHttpRequest: XMLHttpRequest, textStatus: string) => any; + }; + update?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + cache?: { + before?: (event: JQueryEventObject, param: any, cache: any) => any; + after?: (event: JQueryEventObject, param: any, cache: any) => any; + }; + redirect?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + url?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + title?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + head?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + content?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + scroll?: { + before?: (event: JQueryEventObject, param: any) => any; + after?: (event: JQueryEventObject, param: any) => any; + }; + css?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + script?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + render?: { + before?: (event: JQueryEventObject, param: any) => any; + after?: (event: JQueryEventObject, param: any) => any; + }; + verify?: { + before?: (event: JQueryEventObject, param: any) => any; + after?: (event: JQueryEventObject, param: any) => any; + }; + success?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + error?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + complete?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + param?: any; + + // internal + uuid?: string; + nss?: { + name?: string; + event?: string[]; + click?: string; + submit?: string; + popstate?: string; + scroll?: string; + data?: string; + class4html?: string; + requestHeader?: string; + }; + origLocation?: HTMLAnchorElement; + destLocation?: HTMLAnchorElement; + retry?: boolean; + speedcheck?: boolean; + disable?: boolean; + option?: any; + }; +} + +interface JQueryStatic { + pjax: { + (setting?: PjaxSetting): any; + enable(): any; + disable(): any; + click(url: string, attr: { href?: string; }): any; + click(url: HTMLAnchorElement, attr: { href?: string; }): any; + click(url: JQuery, attr: { href?: string; }): any; + click(url: any, attr: { href?: string; }): any; + submit(url: string, attr: { action?: string; method?: string; }, data: any): any; + submit(url: HTMLFormElement, attr?: { action?: string; method?: string; }, data?: any): any; + submit(url: JQuery, attr?: { action?: string; method?: string; }, data?: any): any; + submit(url: any, attr?: { action?: string; method?: string; }, data?: any): any; + follow(event: JQueryEventObject, ajax: JQueryXHR, timeStamp?: number): boolean; + setCache(): any; + setCache(url: string): any; + setCache(url: string, data: string): any; + setCache(url: string, data: string, textStatus: string, XMLHttpRequest: XMLHttpRequest): any; + getCache(): any; + getCache(url: string): any; + removeCache(url: string): any; + removeCache(): any; + clearCache(): any; + }; +} + +interface JQuery { + pjax(setting?: PjaxSetting): any; +} \ No newline at end of file From e65feae2035aa410b1462a51f5bb8fd54a57d9cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=96=B0=E3=82=9D=E6=9C=88?= Date: Wed, 16 Jul 2014 10:08:56 +0900 Subject: [PATCH 121/324] Update jquery.pjax-tests.ts --- jquery.pjax.falsandtru/jquery.pjax-tests.ts | 61 --------------------- 1 file changed, 61 deletions(-) diff --git a/jquery.pjax.falsandtru/jquery.pjax-tests.ts b/jquery.pjax.falsandtru/jquery.pjax-tests.ts index fd8cbaecd..18eae623c 100644 --- a/jquery.pjax.falsandtru/jquery.pjax-tests.ts +++ b/jquery.pjax.falsandtru/jquery.pjax-tests.ts @@ -33,64 +33,3 @@ function test_pjax_event() { $('div.loading').fadeOut(500); }); } - -function test_pjax_progressbar() { - $('body').append(''); - $.pjax({ - area: 'div.pjax', - callbacks: { - before: function () { - $('div.loading').children().width(''); - $('div.loading').fadeIn(0); - }, - ajax: { - xhr: function () { - var xhr = jQuery.ajaxSettings.xhr(); - - $('div.loading').children().width('5%'); - if (xhr instanceof Object && 'onprogress' in xhr) { - xhr.addEventListener('progress', function (event) { - var percentage = event.total ? event.loaded / event.total : 0.4; - percentage = percentage * 90 + 5; - $('div.loading').children().width(percentage + '%'); - }, false); - xhr.addEventListener('load', function (event) { - $('div.loading').children().width('95%'); - }, false); - xhr.addEventListener('error', function (event) { - $('div.loading').children().css('background-color', '#00f'); - }, false); - } - return xhr; - } - }, - update: { - content: { - after: function () { - $('div.loading').children().width('96.25%'); - } - }, - css: { - after: function () { - $('div.loading').children().width('97.5%'); - } - }, - script: { - after: function () { - $('div.loading').children().width('98.75%'); - } - }, - render: { - after: function () { - $('div.loading').children().width('100%'); - $('div.loading').fadeOut(50); - } - } - } - }, - ajax: { timeout: 3000 }, - wait: 1000 - }); -} \ No newline at end of file From 98077b3ab84ddfbb7be526bd7adb3a116ef58db0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=96=B0=E3=82=9D=E6=9C=88?= Date: Wed, 16 Jul 2014 22:11:18 +0900 Subject: [PATCH 122/324] Update CONTRIBUTORS.md Sorry, I was writing the wrong URL. --- CONTRIBUTORS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index ef4467f22..c01d01147 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -164,7 +164,7 @@ All definitions files include a header with the author and editors, so at some p * [jQuery.payment](http://needim.github.io/noty/) (by [Eric J. Smith](https://github.com/ejsmith/)) * [jQuery.pickadate](https://github.com/amsul/pickadate.js) (by [Theodore Brown](https://github.com/theodorejb)) * [jQuery.pjax](https://github.com/defunkt/jquery-pjax) (by [Junle Li](https://github.com/lijunle)) -* [jQuery.pjax.falsandtru](https://github.com/falsandtru/jquery.pjax.js/) (by [NewNotMoon](https://new.not-moon.net/)) +* [jQuery.pjax.falsandtru](https://github.com/falsandtru/jquery.pjax.js/) (by [NewNotMoon](http://new.not-moon.net/)) * [jQuery.pnotify](http://sciactive.github.io/pnotify/) (by [David Sichau](https://github.com/DavidSichau/)) * [jQuery.postMessage](http://benalman.com/projects/jquery-postmessage-plugin/) (by [Junle Li](https://github.com/lijunle)) * [jQuery.prettyphoto](https://github.com/scaron/prettyphoto) (by [Paul Gaske](https://github.com/pgaske)) From ad8d43a73b3f5c2302abba8cb5666c8a3f7370fc Mon Sep 17 00:00:00 2001 From: Zalim Bashorov Date: Wed, 16 Jul 2014 23:39:39 +0400 Subject: [PATCH 123/324] Remove extra declaration of Em.Handlebars.compile in ember.d.ts --- ember/ember.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/ember/ember.d.ts b/ember/ember.d.ts index bbb555e8a..2a0b35e42 100644 --- a/ember/ember.d.ts +++ b/ember/ember.d.ts @@ -2235,7 +2235,6 @@ declare module Em { var print: typeof Ember.Handlebars.print; var logger: typeof Ember.Handlebars.logger; var log: typeof Ember.Handlebars.log; - var compile: typeof Ember.Handlebars.compile; } class HashLocation extends Ember.HashLocation { } class HistoryLocation extends Ember.HistoryLocation { } From 84f63e9cc3917650186dc88c996bad5436311405 Mon Sep 17 00:00:00 2001 From: Ryan Date: Wed, 16 Jul 2014 13:27:04 -0700 Subject: [PATCH 124/324] Added signal function to CodeMirror module --- codemirror/codemirror.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index affee3458..316284a78 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -86,6 +86,11 @@ declare module CodeMirror { or the line the widget is on require the widget to be redrawn. */ function on(line: LineWidget, eventName: 'redraw', handler: () => void ): void; function off(line: LineWidget, eventName: 'redraw', handler: () => void ): void; + + /** Various CodeMirror-related objects emit events, which allow client code to react to various situations. + Handlers for such events can be registered with the on and off methods on the objects that the event fires on. + To fire your own events, use CodeMirror.signal(target, name, args...), where target is a non-DOM-node object. */ + function signal(target: any, name: string, ...args: any[]): void; interface Editor { From 213d8c7da7b69e6507659f96305ded3af66ffd28 Mon Sep 17 00:00:00 2001 From: "Omid K. Rad" Date: Wed, 16 Jul 2014 15:31:44 -0700 Subject: [PATCH 125/324] Adding back Backbone.$ MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit http://backbonejs.org/#Utility-Backbone-$ Also removed `setDomLibrary` Backbone change log 0.9.9 — Dec. 13, 2012: To set what library Backbone uses for DOM manipulation and Ajax calls, use `Backbone.$ = ...` instead of `setDomLibrary`. --- backbone/backbone.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index db104f480..f23a4995a 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -359,7 +359,7 @@ declare module Backbone { // Utility function noConflict(): typeof Backbone; - function setDomLibrary(jQueryNew: any): any; + var $: JQueryStatic; } declare module "backbone" { From c743233ab0ae2955158f47f41fc231ec63dd69d0 Mon Sep 17 00:00:00 2001 From: "Omid K. Rad" Date: Wed, 16 Jul 2014 16:08:00 -0700 Subject: [PATCH 126/324] Overloads for Collection.get method --- backbone/backbone.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index f23a4995a..6b390e83e 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -170,7 +170,12 @@ declare module Backbone { add(model: TModel, options?: AddOptions): Collection; add(models: TModel[], options?: AddOptions): Collection; at(index: number): TModel; + /** + * Get a model from a collection, specified by an id, a cid, or by passing in a model. + **/ + get(id: number): TModel; get(id: string): TModel; + get(id: Model): TModel; create(attributes: any, options?: ModelSaveOptions): TModel; pluck(attribute: string): any[]; push(model: TModel, options?: AddOptions): TModel; From 06392eab9487e17a43bc251e5e2688d76e258a9a Mon Sep 17 00:00:00 2001 From: "Omid K. Rad" Date: Wed, 16 Jul 2014 16:12:00 -0700 Subject: [PATCH 127/324] How to access attributes in a strongly-typed manner Only added comments and examples --- backbone/backbone.d.ts | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index 6b390e83e..d8bdc71c9 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -113,8 +113,23 @@ declare module Backbone { fetch(options?: ModelFetchOptions): JQueryXHR; - get(attributeName: string): any; - set(attributeName: string, value: any, options?: ModelSetOptions): Model; + /** + * For strongly-typed access to attributes, use the `get` method only privately in public getter properties. + * @example + * get name(): string { + * return super.get("name"); + * } + **/ + /*private*/ get(attributeName: string): any; + + /** + * For strongly-typed assignment of attributes, use the `set` method only privately in public setter properties. + * @example + * set name(value: string) { + * super.set("name", value); + * } + **/ + /*private*/ set(attributeName: string, value: any, options?: ModelSetOptions): Model; set(obj: any, options?: ModelSetOptions): Model; change(): any; From d205eb87269a1266e867b4e95bd85a66524e6cc0 Mon Sep 17 00:00:00 2001 From: "Omid K. Rad" Date: Wed, 16 Jul 2014 18:32:07 -0700 Subject: [PATCH 128/324] Updated collection tests and added comments --- backbone/backbone-tests.ts | 38 ++++++++++++++++++-------------------- 1 file changed, 18 insertions(+), 20 deletions(-) diff --git a/backbone/backbone-tests.ts b/backbone/backbone-tests.ts index 6b40bb509..e3fbd6ab8 100644 --- a/backbone/backbone-tests.ts +++ b/backbone/backbone-tests.ts @@ -113,9 +113,12 @@ class EmployeeCollection extends Backbone.Collection { class Book extends Backbone.Model { title: string; author: string; + published: boolean; } class Library extends Backbone.Collection { + // This model definition is here only to test type compatibility of the model, but it + // is not necessary in working code as it is automatically inferred through generics. model: typeof Book; } @@ -123,31 +126,26 @@ class Books extends Backbone.Collection { } function test_collection() { - var books = new Library(); + var books = new Books(); - books.each(book => { - book.get("title"); - }); + var book1: Book = new Book({ title: "Title 1", author: "Mike" }); + books.add(book1); - var titles = books.map(book => { - return book.get("title"); - }); - - var publishedBooks = books.filter(book => { - return book.get("published") === true; - }); - - var alphabetical = books.sortBy((book: Book): number => { - return null; - }); - - var model: Book = new Book({title: "Test", author: "Mike"}); - books.add(model); - var model2: Book = model.collection.first(); - if (model !== model2) { + var model: Book = book1.collection.first(); + if (model !== book1) { throw new Error("Error"); } + books.each(book => + book.get("title")); + + var titles = books.map(book => + book.get("title")); + + var publishedBooks = books.filter(book => + book.get("published") === true); + + var alphabetical = books.sortBy((book: Book): number => null); } ////////// From c18eb2ad641d2bb611416eaa75b4f922f0c13c42 Mon Sep 17 00:00:00 2001 From: "Omid K. Rad" Date: Wed, 16 Jul 2014 19:42:09 -0700 Subject: [PATCH 129/324] Added test for adding object literals as models --- backbone/backbone-tests.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/backbone/backbone-tests.ts b/backbone/backbone-tests.ts index e3fbd6ab8..506fd7bb6 100644 --- a/backbone/backbone-tests.ts +++ b/backbone/backbone-tests.ts @@ -131,6 +131,11 @@ function test_collection() { var book1: Book = new Book({ title: "Title 1", author: "Mike" }); books.add(book1); + // Objects can be added to collection by casting to model type. + // Compiler will check if object properties are valid for the cast. + // This gives better type checking than declaring an `any` overload. + books.add({ title: "Title 2", author: "Mikey" }); + var model: Book = book1.collection.first(); if (model !== book1) { throw new Error("Error"); From 14fdf0edc6c4ea52d1096b4f508a24a93871c09f Mon Sep 17 00:00:00 2001 From: Santi Albo Date: Thu, 17 Jul 2014 13:12:44 +0100 Subject: [PATCH 130/324] Remove express 3 type definitions --- express/express-3.1.0-tests.ts | 1498 ------------------ express/express-3.1.0-tests.ts.tscparams | 1 - express/express-3.1.0.d.ts | 1832 ---------------------- 3 files changed, 3331 deletions(-) delete mode 100644 express/express-3.1.0-tests.ts delete mode 100644 express/express-3.1.0-tests.ts.tscparams delete mode 100644 express/express-3.1.0.d.ts diff --git a/express/express-3.1.0-tests.ts b/express/express-3.1.0-tests.ts deleted file mode 100644 index 904f64511..000000000 --- a/express/express-3.1.0-tests.ts +++ /dev/null @@ -1,1498 +0,0 @@ -/// - -import express = require('express'); -var app = express(); - -////////////////////////// - -var hash: any; - -// config - -app.set('view engine', 'ejs'); -app.set('views', __dirname + '/views'); - -// middleware - -app.use(express.bodyParser()); -app.use(express.cookieParser('shhhh, very secret')); -app.use(express.session()); - -// Session-persisted message middleware - -app.use((req: express.Request, res: express.Response, next) => { - var err = req.session.error - , msg = req.session.success; - delete req.session.error; - delete req.session.success; - res.locals.message = ''; - if (err) res.locals.message = '

' + err + '

'; - if (msg) res.locals.message = '

' + msg + '

'; - next(); -}); - -// dummy database - -var users = { - tj: { name: 'tj' } -}; - -// when you create a user, generate a salt -// and hash the password ('foobar' is the pass here) - -hash('foobar', (err, salt, hash) => { - if (err) throw err; - // store the salt & hash in the "db" - users.tj.salt = salt; - users.tj.hash = hash; -}); - - -// Authenticate using our plain-object database of doom! - -function authenticate(name, pass, fn) { - if (!module.parent) console.log('authenticating %s:%s', name, pass); - var user = users[name]; - // query the db for the given username - if (!user) return fn(new Error('cannot find user')); - // apply the same algorithm to the POSTed password, applying - // the hash against the pass / salt, if there is a match we - // found the user - hash(pass, user.salt, (err, hash) => { - if (err) return fn(err); - if (hash == user.hash) return fn(null, user); - fn(new Error('invalid password')); - }); -} - -function restrict(req: express.Request, res: express.Response, next?: Function) { - if (req.session.user) { - next(); - } else { - req.session.error = 'Access denied!'; - res.redirect('/login'); - } -} - -app.get('/', (req: express.Request, res: express.Response) => { - res.redirect('login'); -}); - -app.get('/restricted', restrict, (req: express.Request, res: express.Response) => { - res.send('Wahoo! restricted area, click to logout'); -}); - -app.get('/logout', (req: express.Request, res: express.Response) => { - // destroy the user's session to log them out - // will be re-created next request - req.session.destroy(() => { - res.redirect('/'); - }); -}); - -app.get('/login', (req: express.Request, res: express.Response) => { - res.render('login'); -}); - -app.post('/login', (req: express.Request, res: express.Response) => { - authenticate(req.body.username, req.body.password, (err, user) => { - if (user) { - // Regenerate session when signing in - // to prevent fixation - req.session.regenerate(() => { - // Store the user's primary key - // in the session store to be retrieved, - // or in this case the entire user object - req.session.user = user; - req.session.success = 'Authenticated as ' + user.name - + ' click to logout. ' - + ' You may now access /restricted.'; - res.redirect('back'); - }); - } else { - req.session.error = 'Authentication failed, please check your ' - + ' username and password.' - + ' (use "tj" and "foobar")'; - res.redirect('login'); - } - }); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -////////////// - -app.set('views', __dirname); -app.set('view engine', 'jade'); - -var pets = []; - -var n = 1000; -while (n--) { - pets.push({ name: 'Tobi', age: 2, species: 'ferret' }); - pets.push({ name: 'Loki', age: 1, species: 'ferret' }); - pets.push({ name: 'Jane', age: 6, species: 'ferret' }); -} - -app.use(express.logger('dev')); - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('pets', { pets: pets }); -}); - -app.listen(3000); -console.log('Express listening on port 3000'); - -///////////// - -app.get('/', (req: express.Request, res: express.Response) => { - res.format({ - html: () => { - res.send('
    ' + users.map(user => { - return '
  • ' + user.name + '
  • '; - }).join('') + '
'); - }, - - text: () => { - res.send(users.map(user => { - return ' - ' + user.name + '\n'; - }).join('')); - }, - - json: () => { - res.json(users); - } - }); -}); - -// or you could write a tiny middleware like -// this to abstract make things a bit more declarative: - -function format(mod) { - var obj = require(mod); - return (req: express.Request, res: express.Response) => { - res.format(obj); - }; -} - -app.get('/users', format('./users')); - -if (!module.parent) { - app.listen(3000); - console.log('listening on port 3000'); -} - -///////////////////////// - -// add favicon() before logger() so -// GET /favicon.ico requests are not -// logged, because this middleware -// reponds to /favicon.ico and does not -// call next() -app.use(express.favicon()); - -// custom log format -if ('test' != process.env.NODE_ENV) - app.use(express.logger(':method :url')); - -// parses request cookies, populating -// req.cookies and req.signedCookies -// when the secret is passed, used -// for signing the cookies. -app.use(express.cookieParser('my secret here')); - -// parses json, x-www-form-urlencoded, and multipart/form-data -app.use(express.bodyParser()); - -app.get('/', (req: express.Request, res: express.Response) => { - if (req.cookies.remember) { - res.send('Remembered :). Click to forget!.'); - } else { - res.send('

Check to ' - + '.

'); - } -}); - -app.get('/forget', (req: express.Request, res: express.Response) => { - res.clearCookie('remember'); - res.redirect('back'); -}); - -app.post('/', (req: express.Request, res: express.Response) => { - var minute = 60000; - if (req.body.remember) res.cookie('remember', 1, { maxAge: minute }); - res.redirect('back'); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -/////////////////// - -// ignore GET /favicon.ico -app.use(express.favicon()); - -// pass a secret to cookieParser() for signed cookies -app.use(express.cookieParser('manny is cool')); - -// add req.session cookie support -app.use(express.cookieSession()); - -// do something with the session -app.use(count); - -// custom middleware -function count(req: express.Request, res: express.Response) { - req.session.count = req.session.count || 0; - var n = req.session.count++; - res.send('viewed ' + n + ' times\n'); -} - -if (!module.parent) { - app.listen(3000); - console.log('Express server listening on port 3000'); -} - -/////////////// - -var api = app; - -app.use(express.static(__dirname + '/public')); - -// api middleware - -api.use(express.logger('dev')); -api.use(express.bodyParser()); - -/** - * CORS support. - */ - -api.all('*', (req: express.Request, res: express.Response, next) => { - if (!req.get('Origin')) return next(); - // use "*" here to accept any origin - res.set('Access-Control-Allow-Origin', 'http://localhost:3000'); - res.set('Access-Control-Allow-Methods', 'GET, POST'); - res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type'); - // res.set('Access-Control-Allow-Max-Age', 3600); - if ('OPTIONS' == req.method) return res.send(200); - next(); -}); - -/** - * POST a user. - */ - -api.post('/user', (req: express.Request, res: express.Response) => { - console.log(req.body); - res.send(201); -}); - -app.listen(3000); -api.listen(3001); - -console.log('app listening on 3000'); -console.log('api listening on 3001'); - -//////////////////// - -app.get('/', (req: express.Request, res: express.Response) => { - res.send(''); -}); - -// /files/* is accessed via req.params[0] -// but here we name it :file -app.get('/files/:file(*)', (req: express.Request, res: express.Response) => { - var file = req.params.file - , path = __dirname + '/files/' + file; - - res.download(path); -}); - -// error handling middleware. Because it's -// below our routes, you will be able to -// "intercept" errors, otherwise Connect -// will respond with 500 "Internal Server Error". -app.use((err, req, res: express.Response, next) => { - // special-case 404s, - // remember you could - // render a 404 template here - if (404 == err.status) { - res.statusCode = 404; - res.send('Cant find that file, sorry!'); - } else { - next(err); - } -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -/////////////////// - -// Register ejs as .html. If we did -// not call this, we would need to -// name our views foo.ejs instead -// of foo.html. The __express method -// is simply a function that engines -// use to hook into the Express view -// system by default, so if we want -// to change "foo.ejs" to "foo.html" -// we simply pass _any_ function, in this -// case `ejs.__express`. - -app.engine('.html', require('ejs').__express); - -// Optional since express defaults to CWD/views - -app.set('views', __dirname + '/views'); - -// Without this you would need to -// supply the extension to res.render() -// ex: res.render('users.html'). -app.set('view engine', 'html'); - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('users', { - users: users, - title: "EJS example", - header: "Some users" - }); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express app started on port 3000'); -} - -//////////////////// - -var test: any; - -if (!test) app.use(express.logger('dev')); -app.use(app.router); - -// the error handler is strategically -// placed *below* the app.router; if it -// were above it would not receive errors -// from app.get() etc -app.use(error); - -// error handling middleware have an arity of 4 -// instead of the typical (req: express.Request, res: express.Response, next), -// otherwise they behave exactly like regular -// middleware, you may have several of them, -// in different orders etc. - -function error(err, req, res: express.Response, next) { - // log it - if (!test) console.error(err.stack); - - // respond with 500 "Internal Server Error". - res.send(500); -} - -app.get('/', () => { - // Caught and passed down to the errorHandler middleware - throw new Error('something broke!'); -}); - -app.get('/next', (req: express.Request, res: express.Response, next) => { - // We can also pass exceptions to next() - process.nextTick(() => { - next(new Error('oh no!')); - }); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -///////////////////// - -var silent: any; - -// general config -app.set('views', __dirname + '/views'); -app.set('view engine', 'jade'); - -// our custom "verbose errors" setting -// which we can use in the templates -// via settings['verbose errors'] -app.enable('verbose errors'); - -// disable them in production -// use $ NODE_ENV=production node examples/error-pages -if ('production' == app.settings.env) { - app.disable('verbose errors'); -} - -app.use(express.favicon()); - -silent || app.use(express.logger('dev')); - -// "app.router" positions our routes -// above the middleware defined below, -// this means that Express will attempt -// to match & call routes _before_ continuing -// on, at which point we assume it's a 404 because -// no route has handled the request. - -app.use(app.router); - -// Since this is the last non-error-handling -// middleware use()d, we assume 404, as nothing else -// responded. - -// $ curl http://localhost:3000/notfound -// $ curl http://localhost:3000/notfound -H "Accept: application/json" -// $ curl http://localhost:3000/notfound -H "Accept: text/plain" - -app.use((req: express.Request, res: express.Response) => { - res.status(404); - - // respond with html page - if (req.accepts('html')) { - res.render('404', { url: req.url }); - return; - } - - // respond with json - if (req.accepts('json')) { - res.send({ error: 'Not found' }); - return; - } - - // default to plain-text. send() - res.type('txt').send('Not found'); -}); - -// error-handling middleware, take the same form -// as regular middleware, however they require an -// arity of 4, aka the signature (err, req, res: express.Response, next). -// when connect has an error, it will invoke ONLY error-handling -// middleware. - -// If we were to next() here any remaining non-error-handling -// middleware would then be executed, or if we next(err) to -// continue passing the error, only error-handling middleware -// would remain being executed, however here -// we simply respond with an error page. - -app.use((err, req, res: express.Response) => { - // we may use properties of the error object - // here and next(err) appropriately, or if - // we possibly recovered from the error, simply next(). - res.status(err.status || 500); - res.render('500', { error: err }); -}); - -// Routes - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('index.jade'); -}); - -app.get('/404', (req: express.Request, res: express.Response, next) => { - // trigger a 404 since no other middleware - // will match /404 after this one, and we're not - // responding here - next(); -}); - -app.get('/403', (req: express.Request, res: express.Response, next) => { - // trigger a 403 error - var err = new Error('not allowed!'); - err.status = 403; - next(err); -}); - -app.get('/500', (req: express.Request, res: express.Response, next) => { - // trigger a generic (500) error - next(new Error('keyboard cat!')); -}); - -if (!module.parent) { - app.listen(3000); - //silent ||  console.log('Express started on port 3000'); -} - -/////////////// - -var fs: any; -var md: any; - -app.set('view engine', 'jade'); -app.set('views', __dirname + '/views'); - -function User(name) { - this.private = 'heyyyy'; - this.secret = 'something'; - this.name = name; - this.id = 123; -} - -// You'll probably want to do -// something like this so you -// dont expose "secret" data. - -User.prototype.toJSON = function () { - return { - id: this.id, - name: this.name - }; -}; - -app.use(express.logger('dev')); - -// earlier on expose an object -// that we can tack properties on. -// all res.locals props are exposed -// to the templates, so "expose" will -// be present. - -app.use((req: express.Request, res: express.Response, next) => { - res.locals.expose = {}; - // you could alias this as req or res.expose - // to make it shorter and less annoying - next(); -}); - -// pretend we loaded a user - -app.use((req: express.Request, res: express.Response, next) => { - req.user = new User('Tobi'); - next(); -}); - -app.get('/', (req: express.Request, res: express.Response) => { - res.redirect('/user'); -}); - -app.get('/user', (req: express.Request, res: express.Response) => { - // we only want to expose the user - // to the client for this route: - res.locals.expose.user = req.user; - res.render('page'); -}); - -app.listen(3000); -console.log('app listening on port 3000'); - -/////////////////////// - -app.get('/', (req: express.Request, res: express.Response) => { - res.send('Hello World'); -}); - -app.listen(3000); -console.log('Express started on port 3000'); - -//////////////////// - -// register .md as an engine in express view system - -app.engine('md', (path, options, fn) => { - fs.readFile(path, 'utf8', (err, str) => { - if (err) return fn(err); - try { - var html = md(str); - html = html.replace(/\{([^}]+)\}/g, (_, name) => { - return options[name] || ''; - }); - fn(null, html); - } catch (err) { - fn(err); - } - }); -}); - -app.set('views', __dirname + '/views'); - -// make it the default so we dont need .md -app.set('view engine', 'md'); - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('index', { title: 'Markdown Example' }); -}); - -app.get('/fail', (req: express.Request, res: express.Response) => { - res.render('missing', { title: 'Markdown Example' }); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -/////////////////////// - -var mformat: any; - -// bodyParser in connect 2.x uses node-formidable to parse -// the multipart form data. -app.use(express.bodyParser()); - -app.get('/', (req: express.Request, res: express.Response) => { - res.send('
' - + '

Title:

' - + '

Image:

' - + '

' - + '
'); -}); - -app.post('/', (req: express.Request, res: express.Response) => { - // the uploaded file can be found as `req.files.image` and the - // title field as `req.body.title` - res.send(mformat('\nuploaded %s (%d Kb) to %s as %s' - , req.files.image.name - , req.files.image.size / 1024 | 0 - , req.files.image.path - , req.body.title)); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -////////////////// - - -// first: -// $ npm install redis online -// $ redis-server - -/** - * Module dependencies. - */ - -var online: any; -var db: any; - -// online - -online = online(db); - -// activity tracking, in this case using -// the UA string, you would use req.user.id etc - -app.use((req: express.Request, res: express.Response, next) => { - // fire-and-forget - online.add(req.headers['user-agent']); - next(); -}); - -/** - * List helper. - */ - -function list(ids) { - return '
    ' + ids.map(id => { - return '
  • ' + id + '
  • '; - }).join('') + '
'; -} - -/** - * GET users online. - */ - -app.get('/', (req: express.Request, res: express.Response, next) => { - online.last(5, (err, ids) => { - if (err) return next(err); - res.send('

Users online: ' + ids.length + '

' + list(ids)); - }); -}); - -app.listen(3000); -console.log('listening on port 3000'); - -/////////////////// - -// Convert :to and :from to integers - -app.param(['to', 'from'], (req: express.Request, res: express.Response, next, num, name) => { - req.params[name] = num = parseInt(num, 10); - if (isNaN(num)) { - next(new Error('failed to parseInt ' + num)); - } else { - next(); - } -}); - -// Load user by id - -app.param('user', (req: express.Request, res: express.Response, next, id) => { - if (req.user = users[id]) { - next(); - } else { - next(new Error('failed to find user')); - } -}); - -/** - * GET index. - */ - -app.get('/', (req: express.Request, res: express.Response) => { - res.send('Visit /user/0 or /users/0-2'); -}); - -/** - * GET :user. - */ - -app.get('/user/:user', (req: express.Request, res: express.Response) => { - res.send('user ' + req.user.name); -}); - -/** - * GET users :from - :to. - */ - -app.get('/users/:from-:to', (req: express.Request, res: express.Response) => { - var from = req.params.from - , to = req.params.to - , names = users.map(user => { return user.name; }); - res.send('users ' + names.slice(from, to).join(', ')); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -////////////////// - -// Ad-hoc example resource method - -app.resource = function (path, obj) { - this.get(path, obj.index); - this.get(path + '/:a..:b.:format?', (req: express.Request, res: express.Response) => { - var a = parseInt(req.params.a, 10) - , b = parseInt(req.params.b, 10) - , format = req.params.format; - obj.range(req, res, a, b, format); - }); - this.get(path + '/:id', obj.show); - this.del(path + '/:id', obj.destroy); -}; - -// Fake controller. - -var FUser = { - index: (req: express.Request, res: express.Response) => { - res.send(users); - }, - show: (req: express.Request, res: express.Response) => { - res.send(users[req.params.id] || { error: 'Cannot find user' }); - }, - destroy: (req: express.Request, res: express.Response) => { - var id = req.params.id; - var destroyed = id in users; - delete users[id]; - res.send(destroyed ? 'destroyed' : 'Cannot find user'); - }, - range: (req: express.Request, res: express.Response, a, b, format) => { - var range = users.slice(a, b + 1); - switch (format) { - case 'json': - res.send(range); - break; - case 'html': - default: - var html = '
    ' + range.map(user => { - return '
  • ' + user.name + '
  • '; - }).join('\n') + '
'; - res.send(html); - break; - } - } -}; - -// curl http://localhost:3000/users -- responds with all users -// curl http://localhost:3000/users/1 -- responds with user 1 -// curl http://localhost:3000/users/4 -- responds with error -// curl http://localhost:3000/users/1..3 -- responds with several users -// curl -X DELETE http://localhost:3000/users/1 -- deletes the user - -app.resource('/users', FUser); - -app.get('/', (req: express.Request, res: express.Response) => { - res.send([ - '

Examples:

    ' - , '
  • GET /users
  • ' - , '
  • GET /users/1
  • ' - , '
  • GET /users/3
  • ' - , '
  • GET /users/1..3
  • ' - , '
  • GET /users/1..3.json
  • ' - , '
  • DELETE /users/4
  • ' - , '
' - ].join('\n')); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -///////////////////// - - -var verbose: any; - -app.map = (a, route) => { - route = route || ''; - for (var key in a) { - switch (typeof a[key]) { - // { '/path': { ... }} - case 'object': - app.map(a[key], route + key); - break; - // get: function(){ ... } - case 'function': - if (verbose) console.log('%s %s', key, route); - app[key](route, a[key]); - break; - } - } -}; - -var users2 = { - list: (req: express.Request, res: express.Response) => { - res.send('user list'); - }, - - get: (req: express.Request, res: express.Response) => { - res.send('user ' + req.params.uid); - }, - - del: (req: express.Request, res: express.Response) => { - res.send('delete users'); - } -}; - -var pets2 = { - list: (req: express.Request, res: express.Response) => { - res.send('user ' + req.params.uid + '\'s pets'); - }, - - del: (req: express.Request, res: express.Response) => { - res.send('delete ' + req.params.uid + '\'s pet ' + req.params.pid); - } -}; - -app.map({ - '/users': { - get: users2.list, - del: users2.del, - '/:uid': { - get: users.get , - '/pets': { - get: pets2.list, - '/:pid': { - del: pets2.del - } - } - } - } -}); - -app.listen(3000); - -/////////////////////////// - -// Example requests: -// curl http://localhost:3000/user/0 -// curl http://localhost:3000/user/0/edit -// curl http://localhost:3000/user/1 -// curl http://localhost:3000/user/1/edit (unauthorized since this is not you) -// curl -X DELETE http://localhost:3000/user/0 (unauthorized since you are not an admin) - -function loadUser(req: express.Request, res: express.Response, next) { - // You would fetch your user from the db - var user = users[req.params.id]; - if (user) { - req.user = user; - next(); - } else { - next(new Error('Failed to load user ' + req.params.id)); - } -} - -function andRestrictToSelf(req: express.Request, res: express.Response, next) { - // If our authenticated user is the user we are viewing - // then everything is fine :) - if (req.authenticatedUser.id == req.user.id) { - next(); - } else { - // You may want to implement specific exceptions - // such as UnauthorizedError or similar so that you - // can handle these can be special-cased in an error handler - // (view ./examples/pages for this) - next(new Error('Unauthorized')); - } -} - -function andRestrictTo(role) { - return (req: express.Request, res: express.Response, next) => { - if (req.authenticatedUser.role == role) { - next(); - } else { - next(new Error('Unauthorized')); - } - }; -} - -// Middleware for faux authentication -// you would of course implement something real, -// but this illustrates how an authenticated user -// may interact with middleware - -app.use((req: express.Request, res: express.Response, next) => { - req.authenticatedUser = users[0]; - next(); -}); - -app.get('/', (req: express.Request, res: express.Response) => { - res.redirect('/user/0'); -}); - -app.get('/user/:id', loadUser, (req: express.Request, res: express.Response) => { - res.send('Viewing user ' + req.user.name); -}); - -app.get('/user/:id/edit', loadUser, andRestrictToSelf, (req: express.Request, res: express.Response) => { - res.send('Editing user ' + req.user.name); -}); - -app.del('/user/:id', loadUser, andRestrictTo('admin'), (req: express.Request, res: express.Response) => { - res.send('Deleted user ' + req.user.name); -}); - -app.listen(3000); -console.log('Express app started on port 3000'); - -///////////////////////// - -app.set('view engine', 'jade'); -app.set('views', __dirname); - -// populate search - -db.sadd('ferret', 'tobi'); -db.sadd('ferret', 'loki'); -db.sadd('ferret', 'jane'); -db.sadd('cat', 'manny'); -db.sadd('cat', 'luna'); - -/** - * GET the search page. - */ - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('search'); -}); - -/** - * GET search for :query. - */ - -app.get('/search/:query?', (req: express.Request, res: express.Response) => { - var query = req.params.query; - db.smembers(query, (err, vals) => { - if (err) return res.send(500); - res.send(vals); - }); -}); - -/** - * GET client javascript. Here we use sendfile() - * because serving __dirname with the static() middleware - * would also mean serving our server "index.js" and the "search.jade" - * template. - */ - -app.get('/client.js', (req: express.Request, res: express.Response) => { - res.sendfile(__dirname + '/client.js'); -}); - -app.listen(3000); -console.log('app listening on port 3000'); - -/////////////////// - -app.use(express.logger('dev')); - -// Required by session() middleware -// pass the secret for signed cookies -// (required by session()) -app.use(express.cookieParser('keyboard cat')); - -// Populates req.session -app.use(express.session()); - -app.get('/', (req: express.Request, res: express.Response) => { - var body = ''; - if (req.session.views) { - ++req.session.views; - } else { - req.session.views = 1; - body += '

First time visiting? view this page in several browsers :)

'; - } - res.send(body + '

viewed ' + req.session.views + ' times.

'); -}); - -app.listen(3000); -console.log('Express app started on port 3000'); - -//////////////////////// - -// log requests -app.use(express.logger('dev')); - -// express on its own has no notion -// of a "file". The express.static() -// middleware checks for a file matching -// the `req.path` within the directory -// that you pass it. In this case "GET /js/app.js" -// will look for "./public/js/app.js". - -app.use(express.static(__dirname + '/public')); - -// if you wanted to "prefix" you may use -// the mounting feature of Connect, for example -// "GET /static/js/app.js" instead of "GET /js/app.js". -// The mount-path "/static" is simply removed before -// passing control to the express.static() middleware, -// thus it serves the file correctly by ignoring "/static" -app.use('/static', express.static(__dirname + '/public')); - -// if for some reason you want to serve files from -// several directories, you can use express.static() -// multiple times! Here we're passing "./public/css", -// this will allow "GET /style.css" instead of "GET /css/style.css": -app.use(express.static(__dirname + '/public/css')); - -// this examples does not have any routes, however -// you may `app.use(app.router)` before or after these -// static() middleware. If placed before them your routes -// will be matched BEFORE file serving takes place. If placed -// after as shown here then file serving is performed BEFORE -// any routes are hit: -app.use(app.router); - -app.listen(3000); -console.log('listening on port 3000'); -console.log('try:'); -console.log(' GET /hello.txt'); -console.log(' GET /js/app.js'); -console.log(' GET /css/style.css'); - -////////////////// - -/* -edit /etc/vhosts: - -127.0.0.1 foo.example.com -127.0.0.1 bar.example.com -127.0.0.1 example.com -*/ - -// Main app - -var main = express(); - -main.use(express.logger('dev')); - -main.get('/', (req: express.Request, res: express.Response) => { - res.send('Hello from main app!'); -}); - -main.get('/:sub', (req: express.Request, res: express.Response) => { - res.send('requsted ' + req.params.sub); -}); - -// Redirect app - -var redirect = express(); - -redirect.all('*', (req: express.Request, res: express.Response) => { - console.log(req.subdomains); - res.redirect('http://example.com:3000/' + req.subdomains[0]); -}); - -app.use(express.vhost('*.example.com', redirect)); -app.use(express.vhost('example.com', main)); - -app.listen(3000); -console.log('Express app started on port 3000'); - -//////////////////// - -// create an error with .status. we -// can then use the property in our -// custom error handler (Connect repects this prop as well) - -function merror(status, msg) { - var err = new Error(msg); - err.status = status; - return err; -} - -// if we wanted to supply more than JSON, we could -// use something similar to the content-negotiation -// example. - -// here we validate the API key, -// by mounting this middleware to /api -// meaning only paths prefixed with "/api" -// will cause this middleware to be invoked - -app.use('/api', (req, res: express.Response, next) => { - var key = req.query['api-key']; - - // key isnt present - if (!key) return next(merror(400, 'api key required')); - - // key is invalid - if (!~apiKeys.indexOf(key)) return next(merror(401, 'invalid api key')); - - // all good, store req.key for route access - req.key = key; - next(); -}); - -// position our routes above the error handling middleware, -// and below our API middleware, since we want the API validation -// to take place BEFORE our routes -app.use(app.router); - -// middleware with an arity of 4 are considered -// error handling middleware. When you next(err) -// it will be passed through the defined middleware -// in order, but ONLY those with an arity of 4, ignoring -// regular middleware. -app.use((err, req, res: express.Response) => { - // whatever you want here, feel free to populate - // properties on `err` to treat it differently in here. - res.send(err.status || 500, { error: err.message }); -}); - -// our custom JSON 404 middleware. Since it's placed last -// it will be the last middleware called, if all others -// invoke next() and do not respond. -app.use((req: express.Request, res: express.Response) => { - res.send(404, { error: "Lame, can't find that" }); -}); - -// map of valid api keys, typically mapped to -// account info with some sort of database like redis. -// api keys do _not_ serve as authentication, merely to -// track API usage or help prevent malicious behavior etc. - -var apiKeys = ['foo', 'bar', 'baz']; - -// these two objects will serve as our faux database - -var repos = [ - { name: 'express', url: 'http://github.com/visionmedia/express' } - , { name: 'stylus', url: 'http://github.com/learnboost/stylus' } - , { name: 'cluster', url: 'http://github.com/learnboost/cluster' } -]; - -var userRepos = { - tobi: [repos[0], repos[1]] - , loki: [repos[1]] - , jane: [repos[2]] -}; - -// we now can assume the api key is valid, -// and simply expose the data - -app.get('/api/users', (req: express.Request, res: express.Response) => { - res.send(users); -}); - -app.get('/api/repos', (req: express.Request, res: express.Response) => { - res.send(repos); -}); - -app.get('/api/user/:name/repos', (req: express.Request, res: express.Response, next) => { - var name = req.params.name - , user = userRepos[name]; - - if (user) res.send(user); - else next(); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express server listening on port 3000'); -} - -////// - -var router = new express.Router(); - -router.get('/', function (req, resp, next?) { - resp.send('response from router'); - resp.end(); - if (next) { - next(); - } -}); - -function test_general() { - - app.use((err, req, res: express.Response) => { - console.error(err.stack); - res.send(500, 'Something broke!'); - }); - app.use(express.bodyParser()); - app.use(express.methodOverride()); - app.use(app.router); - app.use(() => {}); - app.use(express.bodyParser()); - app.use(express.methodOverride()); - app.use(app.router); - - app.get('/', (req: express.Request, res: express.Response) => { - res.send('hello world'); - }); - - app.listen(3000); - - app.set('title', 'My Site'); - app.get('title'); - - app.enable('trust proxy'); - app.get('trust proxy'); - - app.disable('trust proxy'); - app.get('trust proxy'); - - app.enabled('trust proxy'); - - app.configure(() => { - app.set('title', 'My Application'); - }); - - app.configure('development', () => { - app.set('db uri', 'localhost/dev'); - }); - - app.configure('stage', 'production', () => {}); - - app.configure('1', '2', '3', () => {}); - - app.use((req: express.Request, res: express.Response) => { - res.send('Hello World'); - }); - - app.engine('jade', require('jade').__express); - - var User; - app.param('user', (req: express.Request, res: express.Response, next, id) => { - User.find(id, (err, user) =>{ - if (err) { - next(err); - } else if (user) { - req.user = user; - next(); - } else { - next(new Error('failed to load user')); - } - }); - }); - - app.get(/^\/commits\/(\d+)(?:\.\.(\d+))?$/, (req: express.Request, res: express.Response) => { - var from = req.params[0]; - var to = req.params[1] || 'HEAD'; - res.send('commit range ' + from + '..' + to); - }); - - app.locals.title = 'My App'; - app.locals.strftime = require('strftime'); - - var requireAuthentication; - var loadUser = () => {}; - app.all('*', requireAuthentication, loadUser); - app.all('*', loadUser); - app.all('*', loadUser, loadUser, loadUser); - - app.locals.title = 'My App'; - app.locals.strftime = require('strftime'); - app.locals({ - title: 'My App', - phone: '1-250-858-9990', - email: 'me@myapp.com' - }); - app.render('email', () => {}); - - app.render('email', { name: 'Tobi' }, () => {}); -} - -function test_request() { - var req: express.Request; - req.params.name; - req.params[0]; - req.query.q; - req.body.user.name; - app.use(express.bodyParser({ keepExtensions: true, uploadDir: '/my/files' })); - req.param('name'); - req.route; - req.cookies.name; - req.signedCookies; - req.get('Content-Type'); - req.accepts('html'); - req.accepts(['html', 'json']); - req.is('html'); - req.ip; - req.path; - req.host; - req.fresh; - req.stale; - req.xhr; - req.protocol; - req.subdomains; - req.originalUrl; - req.acceptedLanguages; - req.acceptedCharsets; - var charset; - req.acceptsCharset(charset); - var lang; - req.acceptsLanguage(lang); - req.session = null; -} - -function test_response() { - var res: express.Response; - res.status(404).sendfile('path/to/404.png'); - res.set('Content-Type', 'text/plain'); - res.set({ - 'Content-Type': 'text/plain', - 'Content-Length': '123', - 'ETag': '12345' - }); - res.get('Content-Type'); - res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true }); - res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); - res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }); - res.cookie('cart', { items: [1, 2, 3] }); - res.cookie('cart', { items: [1, 2, 3] }, { maxAge: 900000 });; - res.cookie('name', 'tobi', { signed: true }); - res.cookie('name', 'tobi', { path: '/admin' }); - res.clearCookie('name', { path: '/admin' }); - res.redirect('/foo/bar'); - res.redirect('http://example.com'); - res.redirect(301, 'http://example.com'); - res.charset = 'value'; - res.send('some html'); - res.send(new Buffer('whoop')); - res.send({ some: 'json' }); - res.send('some html'); - res.send(404, 'Sorry, we cannot find that!'); - res.send(500, { error: 'something blew up' }); - res.send(200); - res.set('Content-Type', 'text/html'); - res.send(new Buffer('some html')); - res.send('some html'); - res.send({ user: 'tobi' }); - res.send([1, 2, 3]); - res.json(null); - res.json({ user: 'tobi' }); - res.json(500, { error: 'message' }); - res.jsonp(null); - res.jsonp({ user: 'tobi' }); - res.jsonp(500, { error: 'message' }); - res.jsonp({ user: 'tobi' }); - res.type('application/json'); - - res.format({ - 'text/plain': () => { - res.send('hey'); - }, - 'text/html': () => { - res.send('hey'); - }, - 'application/json': () => { - res.send({ message: 'hey' }); - } - }); - - res.attachment(); - res.attachment('path/to/logo.png'); - app.get('/user/:uid/photos/:file', (req: express.Request, res: express.Response) => { - var uid = req.params.uid - , file = req.params.file; - - req.user.mayViewFilesFrom(uid, yes => { - if (yes) { - res.sendfile('/uploads/' + uid + '/' + file); - } else { - res.send(403, 'Sorry! you cant see that.'); - } - }); - }); - - res.download('/report-12345.pdf'); - res.download('/report-12345.pdf', 'report.pdf'); - res.download('/report-12345.pdf', 'report.pdf', err => { - if (err) { } else { } - }); - - res.links({ - next: 'http://api.example.com/users?page=2', - last: 'http://api.example.com/users?page=5' - }); - - app.use((req: express.Request, res: express.Response, next) => { - res.locals.user = req.user; - res.locals.authenticated = !req.user.anonymous; - next(); - }); - res.render('index', () => {}); - res.render('user', { name: 'Tobi' }, () => {}); - -} - -function test_middleware() { - app.use(express.basicAuth('username', 'password')); - app.use(express.basicAuth((user, pass) => { - return 'tj' == user && 'wahoo' == pass; - })); - app.use(express.bodyParser()); - app.use(express.json()); - app.use(express.urlencoded()); - app.use(express.multipart()); - app.use(express.logger()); - app.use(express.compress()); - app.use(express.methodOverride()); - app.use(express.bodyParser()); - app.use(express.cookieParser()); - app.use(express.cookieParser('some secret')); - app.use(express.cookieSession()); - app.use(express.directory('public')); - app.use(express.static('public')); - app.use(router.middleware); -} - -//////////////////// - -// make sure server can be shut down -var testShutdownServer = app.listen(0); -console.log('listening on port ' + testShutdownServer.address().port); -testShutdownServer.close(); diff --git a/express/express-3.1.0-tests.ts.tscparams b/express/express-3.1.0-tests.ts.tscparams deleted file mode 100644 index e16c76dff..000000000 --- a/express/express-3.1.0-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/express/express-3.1.0.d.ts b/express/express-3.1.0.d.ts deleted file mode 100644 index d5865f418..000000000 --- a/express/express-3.1.0.d.ts +++ /dev/null @@ -1,1832 +0,0 @@ -// Type definitions for Express 3.1 -// Project: http://expressjs.com -// Definitions by: Boris Yankov -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped - -/* =================== USAGE =================== - - import express = require('express'); - var app = express(); - - =============================================== */ - -/// - - -declare module Express { - - // These open interfaces may be extended in an application-specific manner via declaration merging. - // See for example passport.d.ts (https://github.com/borisyankov/DefinitelyTyped/blob/master/passport/passport.d.ts) - export interface Request { } - export interface Response { } - export interface Application { } -} - - -declare module "express" { - import http = require('http'); - - // Merged declaration, e is both a callable function and a namespace - function e(): e.Express; - - module e { - interface IRoute { - path: string; - - method: string; - - callbacks: Function[]; - - regexp: any; - - /** - * Check if this route matches `path`, if so - * populate `.params`. - */ - match(path: string): boolean; - } - - class Route implements IRoute { - path: string; - - method: string; - - callbacks: Function[]; - - regexp: any; - match(path: string): boolean; - - /** - * Initialize `Route` with the given HTTP `method`, `path`, - * and an array of `callbacks` and `options`. - * - * Options: - * - * - `sensitive` enable case-sensitive routes - * - `strict` enable strict matching for trailing slashes - * - * @param method - * @param path - * @param callbacks - * @param options - */ - new (method: string, path: string, callbacks: Function[], options: any): Route; - } - - interface IRouter { - /** - * Map the given param placeholder `name`(s) to the given callback(s). - * - * Parameter mapping is used to provide pre-conditions to routes - * which use normalized placeholders. For example a _:user_id_ parameter - * could automatically load a user's information from the database without - * any additional code, - * - * The callback uses the samesignature as middleware, the only differencing - * being that the value of the placeholder is passed, in this case the _id_ - * of the user. Once the `next()` function is invoked, just like middleware - * it will continue on to execute the route, or subsequent parameter functions. - * - * app.param('user_id', function(req, res, next, id){ - * User.find(id, function(err, user){ - * if (err) { - * next(err); - * } else if (user) { - * req.user = user; - * next(); - * } else { - * next(new Error('failed to load user')); - * } - * }); - * }); - * - * @param name - * @param fn - */ - param(name: string, fn: Function): T; - - param(name: string[], fn: Function): T; - - /** - * Special-cased "all" method, applying the given route `path`, - * middleware, and callback to _every_ HTTP method. - * - * @param path - * @param fn - */ - all(path: string, fn?: (req: Request, res: Response, next: Function) => any): T; - - all(path: string, ...callbacks: Function[]): void; - - get(name: string, ...handlers: RequestFunction[]): T; - - get(name: RegExp, ...handlers: RequestFunction[]): T; - - post(name: string, ...handlers: RequestFunction[]): T; - - post(name: RegExp, ...handlers: RequestFunction[]): T; - - put(name: string, ...handlers: RequestFunction[]): T; - - put(name: RegExp, ...handlers: RequestFunction[]): T; - - del(name: string, ...handlers: RequestFunction[]): T; - - del(name: RegExp, ...handlers: RequestFunction[]): T; - - patch(name: string, ...handlers: RequestFunction[]): T; - - patch(name: RegExp, ...handlers: RequestFunction[]): T; - } - - export class Router implements IRouter { - new (options?: any): Router; - - middleware (): any; - - param(name: string, fn: Function): Router; - - param(name: any[], fn: Function): Router; - - all(path: string, fn?: (req: Request, res: Response, next: Function) => any): Router; - - all(path: string, ...callbacks: Function[]): void; - - get(name: string, ...handlers: RequestFunction[]): Router; - - get(name: RegExp, ...handlers: RequestFunction[]): Router; - - post(name: string, ...handlers: RequestFunction[]): Router; - - post(name: RegExp, ...handlers: RequestFunction[]): Router; - - put(name: string, ...handlers: RequestFunction[]): Router; - - put(name: RegExp, ...handlers: RequestFunction[]): Router; - - del(name: string, ...handlers: RequestFunction[]): Router; - - del(name: RegExp, ...handlers: RequestFunction[]): Router; - - patch(name: string, ...handlers: RequestFunction[]): Router; - - patch(name: RegExp, ...handlers: RequestFunction[]): Router; - } - - interface Handler { - (req: Request, res: Response, next?: Function): void; - } - - interface CookieOptions { - maxAge?: number; - signed?: boolean; - expires?: Date; - httpOnly?: boolean; - path?: string; - domain?: string; - secure?: boolean; - } - - interface Errback { (err: Error): void; } - - interface Session { - /** - * Update reset `.cookie.maxAge` to prevent - * the cookie from expiring when the - * session is still active. - * - * @return {Session} for chaining - * @api public - */ - touch(): Session; - - /** - * Reset `.maxAge` to `.originalMaxAge`. - */ - resetMaxAge(): Session; - - /** - * Save the session data with optional callback `fn(err)`. - */ - save(fn: Function): Session; - - /** - * Re-loads the session data _without_ altering - * the maxAge properties. Invokes the callback `fn(err)`, - * after which time if no exception has occurred the - * `req.session` property will be a new `Session` object, - * although representing the same session. - */ - reload(fn: Function): Session; - - /** - * Destroy `this` session. - */ - destroy(fn: Function): Session; - - /** - * Regenerate this request's session. - */ - regenerate(fn: Function): Session; - - user: any; - - error: string; - - success: string; - - views: any; - - count: number; - } - - interface Request extends http.ServerRequest, Express.Request { - - session: Session; - - /** - * Return request header. - * - * The `Referrer` header field is special-cased, - * both `Referrer` and `Referer` are interchangeable. - * - * Examples: - * - * req.get('Content-Type'); - * // => "text/plain" - * - * req.get('content-type'); - * // => "text/plain" - * - * req.get('Something'); - * // => undefined - * - * Aliased as `req.header()`. - * - * @param name - */ - get (name: string): string; - - header(name: string): string; - - headers: { [key: string]: string; }; - - /** - * Check if the given `type(s)` is acceptable, returning - * the best match when true, otherwise `undefined`, in which - * case you should respond with 406 "Not Acceptable". - * - * The `type` value may be a single mime type string - * such as "application/json", the extension name - * such as "json", a comma-delimted list such as "json, html, text/plain", - * or an array `["json", "html", "text/plain"]`. When a list - * or array is given the _best_ match, if any is returned. - * - * Examples: - * - * // Accept: text/html - * req.accepts('html'); - * // => "html" - * - * // Accept: text/*, application/json - * req.accepts('html'); - * // => "html" - * req.accepts('text/html'); - * // => "text/html" - * req.accepts('json, text'); - * // => "json" - * req.accepts('application/json'); - * // => "application/json" - * - * // Accept: text/*, application/json - * req.accepts('image/png'); - * req.accepts('png'); - * // => undefined - * - * // Accept: text/*;q=.5, application/json - * req.accepts(['html', 'json']); - * req.accepts('html, json'); - * // => "json" - */ - accepts(type: string): string; - - accepts(type: string[]): string; - - /** - * Check if the given `charset` is acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param charset - */ - acceptsCharset(charset: string): boolean; - - /** - * Check if the given `lang` is acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param lang - */ - acceptsLanguage(lang: string): boolean; - - /** - * Parse Range header field, - * capping to the given `size`. - * - * Unspecified ranges such as "0-" require - * knowledge of your resource length. In - * the case of a byte range this is of course - * the total number of bytes. If the Range - * header field is not given `null` is returned, - * `-1` when unsatisfiable, `-2` when syntactically invalid. - * - * NOTE: remember that ranges are inclusive, so - * for example "Range: users=0-3" should respond - * with 4 users when available, not 3. - * - * @param size - */ - range(size: number): any[]; - - /** - * Return an array of Accepted media types - * ordered from highest quality to lowest. - */ - accepted: MediaType[]; - - /** - * Return an array of Accepted languages - * ordered from highest quality to lowest. - * - * Examples: - * - * Accept-Language: en;q=.5, en-us - * ['en-us', 'en'] - */ - acceptedLanguages: any[]; - - /** - * Return an array of Accepted charsets - * ordered from highest quality to lowest. - * - * Examples: - * - * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8 - * ['unicode-1-1', 'iso-8859-5'] - */ - acceptedCharsets: any[]; - - /** - * Return the value of param `name` when present or `defaultValue`. - * - * - Checks route placeholders, ex: _/user/:id_ - * - Checks body params, ex: id=12, {"id":12} - * - Checks query string params, ex: ?id=12 - * - * To utilize request bodies, `req.body` - * should be an object. This can be done by using - * the `connect.bodyParser()` middleware. - * - * @param name - * @param defaultValue - */ - param(name: string, defaultValue?: any): string; - - /** - * Check if the incoming request contains the "Content-Type" - * header field, and it contains the give mime `type`. - * - * Examples: - * - * // With Content-Type: text/html; charset=utf-8 - * req.is('html'); - * req.is('text/html'); - * req.is('text/*'); - * // => true - * - * // When Content-Type is application/json - * req.is('json'); - * req.is('application/json'); - * req.is('application/*'); - * // => true - * - * req.is('html'); - * // => false - * - * @param type - */ - is(type: string): boolean; - - /** - * Return the protocol string "http" or "https" - * when requested with TLS. When the "trust proxy" - * setting is enabled the "X-Forwarded-Proto" header - * field will be trusted. If you're running behind - * a reverse proxy that supplies https for you this - * may be enabled. - */ - protocol: string; - - /** - * Short-hand for: - * - * req.protocol == 'https' - */ - secure: boolean; - - /** - * Return the remote address, or when - * "trust proxy" is `true` return - * the upstream addr. - */ - ip: string; - - /** - * When "trust proxy" is `true`, parse - * the "X-Forwarded-For" ip address list. - * - * For example if the value were "client, proxy1, proxy2" - * you would receive the array `["client", "proxy1", "proxy2"]` - * where "proxy2" is the furthest down-stream. - */ - ips: string[]; - - /** - * Return basic auth credentials. - * - * Examples: - * - * // http://tobi:hello@example.com - * req.auth - * // => { username: 'tobi', password: 'hello' } - */ - auth: any; - - /** - * Return subdomains as an array. - * - * Subdomains are the dot-separated parts of the host before the main domain of - * the app. By default, the domain of the app is assumed to be the last two - * parts of the host. This can be changed by setting "subdomain offset". - * - * For example, if the domain is "tobi.ferrets.example.com": - * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. - * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. - */ - subdomains: string[]; - - /** - * Short-hand for `url.parse(req.url).pathname`. - */ - path: string; - - /** - * Parse the "Host" header field hostname. - */ - host: string; - - /** - * Check if the request is fresh, aka - * Last-Modified and/or the ETag - * still match. - */ - fresh: boolean; - - /** - * Check if the request is stale, aka - * "Last-Modified" and / or the "ETag" for the - * resource has changed. - */ - stale: boolean; - - /** - * Check if the request was an _XMLHttpRequest_. - */ - xhr: boolean; - - //body: { username: string; password: string; remember: boolean; title: string; }; - body: any; - - //cookies: { string; remember: boolean; }; - cookies: any; - - /** - * Used to generate an anti-CSRF token. - * Placed by the CSRF protection middleware. - */ - csrfToken(): string; - - method: string; - - params: any; - - user: any; - - authenticatedUser: any; - - files: any; - - /** - * Clear cookie `name`. - * - * @param name - * @param options - */ - clearCookie(name: string, options?: any): Response; - - query: any; - - route: any; - - signedCookies: any; - - originalUrl: string; - - url: string; - } - - interface MediaType { - value: string; - quality: number; - type: string; - subtype: string; - } - - interface Send { - (status: number, body?: any): Response; - (body: any): Response; - } - - interface Response extends http.ServerResponse, Express.Response { - /** - * Set status `code`. - * - * @param code - */ - status(code: number): Response; - - /** - * Set Link header field with the given `links`. - * - * Examples: - * - * res.links({ - * next: 'http://api.example.com/users?page=2', - * last: 'http://api.example.com/users?page=5' - * }); - * - * @param links - */ - links(links: any): Response; - - /** - * Send a response. - * - * Examples: - * - * res.send(new Buffer('wahoo')); - * res.send({ some: 'json' }); - * res.send('

some html

'); - * res.send(404, 'Sorry, cant find that'); - * res.send(404); - */ - send: Send; - - /** - * Send JSON response. - * - * Examples: - * - * res.json(null); - * res.json({ user: 'tj' }); - * res.json(500, 'oh noes!'); - * res.json(404, 'I dont have that'); - */ - json: Send; - - /** - * Send JSON response with JSONP callback support. - * - * Examples: - * - * res.jsonp(null); - * res.jsonp({ user: 'tj' }); - * res.jsonp(500, 'oh noes!'); - * res.jsonp(404, 'I dont have that'); - */ - jsonp: Send; - - /** - * Transfer the file at the given `path`. - * - * Automatically sets the _Content-Type_ response header field. - * The callback `fn(err)` is invoked when the transfer is complete - * or when an error occurs. Be sure to check `res.sentHeader` - * if you wish to attempt responding, as the header and some data - * may have already been transferred. - * - * Options: - * - * - `maxAge` defaulting to 0 - * - `root` root directory for relative filenames - * - * Examples: - * - * The following example illustrates how `res.sendfile()` may - * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendfile()` is actually - * the same code, so HTTP cache support etc is identical. - * - * app.get('/user/:uid/photos/:file', function(req, res){ - * var uid = req.params.uid - * , file = req.params.file; - * - * req.user.mayViewFilesFrom(uid, function(yes){ - * if (yes) { - * res.sendfile('/uploads/' + uid + '/' + file); - * } else { - * res.send(403, 'Sorry! you cant see that.'); - * } - * }); - * }); - */ - sendfile(path: string): void; - - sendfile(path: string, options: any): void; - - sendfile(path: string, fn: Errback): void; - - sendfile(path: string, options: any, fn: Errback): void; - - /** - * Transfer the file at the given `path` as an attachment. - * - * Optionally providing an alternate attachment `filename`, - * and optional callback `fn(err)`. The callback is invoked - * when the data transfer is complete, or when an error has - * ocurred. Be sure to check `res.headerSent` if you plan to respond. - * - * This method uses `res.sendfile()`. - */ - download(path: string): void; - - download(path: string, filename: string): void; - - download(path: string, fn: Errback): void; - - download(path: string, filename: string, fn: Errback): void; - - /** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. - * - * Examples: - * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); - * - * @param type - */ - contentType(type: string): Response; - - /** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. - * - * Examples: - * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); - * - * @param type - */ - type(type: string): Response; - - /** - * Respond to the Acceptable formats using an `obj` - * of mime-type callbacks. - * - * This method uses `req.accepted`, an array of - * acceptable types ordered by their quality values. - * When "Accept" is not present the _first_ callback - * is invoked, otherwise the first match is used. When - * no match is performed the server responds with - * 406 "Not Acceptable". - * - * Content-Type is set for you, however if you choose - * you may alter this within the callback using `res.type()` - * or `res.set('Content-Type', ...)`. - * - * res.format({ - * 'text/plain': function(){ - * res.send('hey'); - * }, - * - * 'text/html': function(){ - * res.send('

hey

'); - * }, - * - * 'appliation/json': function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * In addition to canonicalized MIME types you may - * also use extnames mapped to these types: - * - * res.format({ - * text: function(){ - * res.send('hey'); - * }, - * - * html: function(){ - * res.send('

hey

'); - * }, - * - * json: function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * By default Express passes an `Error` - * with a `.status` of 406 to `next(err)` - * if a match is not made. If you provide - * a `.default` callback it will be invoked - * instead. - * - * @param obj - */ - format(obj: any): Response; - - /** - * Set _Content-Disposition_ header to _attachment_ with optional `filename`. - * - * @param filename - */ - attachment(filename?: string): Response; - - /** - * Set header `field` to `val`, or pass - * an object of header fields. - * - * Examples: - * - * res.set('Foo', ['bar', 'baz']); - * res.set('Accept', 'application/json'); - * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); - * - * Aliased as `res.header()`. - */ - set (field: any): Response; - - set (field: string, value?: string): Response; - - header(field: any): Response; - - header(field: string, value?: string): Response; - - /** - * Get value for header `field`. - * - * @param field - */ - get (field: string): string; - - /** - * Clear cookie `name`. - * - * @param name - * @param options - */ - clearCookie(name: string, options?: any): Response; - - /** - * Set cookie `name` to `val`, with the given `options`. - * - * Options: - * - * - `maxAge` max-age in milliseconds, converted to `expires` - * - `signed` sign the cookie - * - `path` defaults to "/" - * - * Examples: - * - * // "Remember Me" for 15 minutes - * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); - * - * // save as above - * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) - */ - cookie(name: string, val: string, options: CookieOptions): Response; - - cookie(name: string, val: any, options: CookieOptions): Response; - - cookie(name: string, val: any): Response; - - /** - * Set the location header to `url`. - * - * The given `url` can also be the name of a mapped url, for - * example by default express supports "back" which redirects - * to the _Referrer_ or _Referer_ headers or "/". - * - * Examples: - * - * res.location('/foo/bar').; - * res.location('http://example.com'); - * res.location('../login'); // /blog/post/1 -> /blog/login - * - * Mounting: - * - * When an application is mounted and `res.location()` - * is given a path that does _not_ lead with "/" it becomes - * relative to the mount-point. For example if the application - * is mounted at "/blog", the following would become "/blog/login". - * - * res.location('login'); - * - * While the leading slash would result in a location of "/login": - * - * res.location('/login'); - * - * @param url - */ - location(url: string): Response; - - /** - * Redirect to the given `url` with optional response `status` - * defaulting to 302. - * - * The resulting `url` is determined by `res.location()`, so - * it will play nicely with mounted apps, relative paths, - * `"back"` etc. - * - * Examples: - * - * res.redirect('/foo/bar'); - * res.redirect('http://example.com'); - * res.redirect(301, 'http://example.com'); - * res.redirect('http://example.com', 301); - * res.redirect('../login'); // /blog/post/1 -> /blog/login - */ - redirect(url: string): void; - - redirect(status: number, url: string): void; - - redirect(url: string, status: number): void; - - /** - * Render `view` with the given `options` and optional callback `fn`. - * When a callback function is given a response will _not_ be made - * automatically, otherwise a response of _200_ and _text/html_ is given. - * - * Options: - * - * - `cache` boolean hinting to the engine it should cache - * - `filename` filename of the view being rendered - */ - - render(view: string, options?: Object, callback?: (err: Error, html: string) => void ): void; - - render(view: string, callback?: (err: Error, html: string) => void ): void; - - locals: any; - - charset: string; - } - - interface RequestFunction { - (req: Request, res: Response, next: Function): any; - } - - interface Application extends IRouter, Express.Application { - /** - * Initialize the server. - * - * - setup default configuration - * - setup default middleware - * - setup route reflection methods - */ - init(): void; - - /** - * Initialize application configuration. - */ - defaultConfiguration(): void; - - /** - * Proxy `connect#use()` to apply settings to - * mounted applications. - **/ - use(route: string, callback?: Function): Application; - - use(route: string, server: Application): Application; - - use(callback: Function): Application; - - use(server: Application): Application; - - /** - * Register the given template engine callback `fn` - * as `ext`. - * - * By default will `require()` the engine based on the - * file extension. For example if you try to render - * a "foo.jade" file Express will invoke the following internally: - * - * app.engine('jade', require('jade').__express); - * - * For engines that do not provide `.__express` out of the box, - * or if you wish to "map" a different extension to the template engine - * you may use this method. For example mapping the EJS template engine to - * ".html" files: - * - * app.engine('html', require('ejs').renderFile); - * - * In this case EJS provides a `.renderFile()` method with - * the same signature that Express expects: `(path, options, callback)`, - * though note that it aliases this method as `ejs.__express` internally - * so if you're using ".ejs" extensions you dont need to do anything. - * - * Some template engines do not follow this convention, the - * [Consolidate.js](https://github.com/visionmedia/consolidate.js) - * library was created to map all of node's popular template - * engines to follow this convention, thus allowing them to - * work seamlessly within Express. - */ - engine(ext: string, fn: Function): Application; - - param(name: string, fn: Function): Application; - - param(name: string[], fn: Function): Application; - - /** - * Assign `setting` to `val`, or return `setting`'s value. - * - * app.set('foo', 'bar'); - * app.get('foo'); - * // => "bar" - * - * Mounted servers inherit their parent server's settings. - * - * @param setting - * @param val - */ - set (setting: string, val: string): Application; - - get(name: string): string; - - get(name: string, ...handlers: RequestFunction[]): Application; - - get(name: RegExp, ...handlers: RequestFunction[]): Application; - - /** - * Return the app's absolute pathname - * based on the parent(s) that have - * mounted it. - * - * For example if the application was - * mounted as "/admin", which itself - * was mounted as "/blog" then the - * return value would be "/blog/admin". - */ - path(): string; - - /** - * Check if `setting` is enabled (truthy). - * - * app.enabled('foo') - * // => false - * - * app.enable('foo') - * app.enabled('foo') - * // => true - */ - enabled(setting: string): boolean; - - /** - * Check if `setting` is disabled. - * - * app.disabled('foo') - * // => true - * - * app.enable('foo') - * app.disabled('foo') - * // => false - * - * @param setting - */ - disabled(setting: string): boolean; - - /** - * Enable `setting`. - * - * @param setting - */ - enable(setting: string): Application; - - /** - * Disable `setting`. - * - * @param setting - */ - disable(setting: string): Application; - - /** - * Configure callback for zero or more envs, - * when no `env` is specified that callback will - * be invoked for all environments. Any combination - * can be used multiple times, in any order desired. - * - * Examples: - * - * app.configure(function(){ - * // executed for all envs - * }); - * - * app.configure('stage', function(){ - * // executed staging env - * }); - * - * app.configure('stage', 'production', function(){ - * // executed for stage and production - * }); - * - * Note: - * - * These callbacks are invoked immediately, and - * are effectively sugar for the following: - * - * var env = process.env.NODE_ENV || 'development'; - * - * switch (env) { - * case 'development': - * ... - * break; - * case 'stage': - * ... - * break; - * case 'production': - * ... - * break; - * } - * - * @param env - * @param fn - */ - configure(env: string, fn: Function): Application; - - configure(env0: string, env1: string, fn: Function): Application; - - configure(env0: string, env1: string, env2: string, fn: Function): Application; - - configure(env0: string, env1: string, env2: string, env3: string, fn: Function): Application; - - configure(env0: string, env1: string, env2: string, env3: string, env4: string, fn: Function): Application; - - configure(fn: Function): Application; - - - /** - * Render the given view `name` name with `options` - * and a callback accepting an error and the - * rendered template string. - * - * Example: - * - * app.render('email', { name: 'Tobi' }, function(err, html){ - * // ... - * }) - * - * @param name - * @param options or fn - * @param fn - */ - render(name: string, options?: Object, callback?: (err: Error, html: string) => void): void; - - render(name: string, callback: (err: Error, html: string) => void): void; - - - /** - * Listen for connections. - * - * A node `http.Server` is returned, with this - * application (which is a `Function`) as its - * callback. If you wish to create both an HTTP - * and HTTPS server you may do so with the "http" - * and "https" modules as shown here: - * - * var http = require('http') - * , https = require('https') - * , express = require('express') - * , app = express(); - * - * http.createServer(app).listen(80); - * https.createServer({ ... }, app).listen(443); - */ - listen(port: number, hostname: string, backlog: number, callback?: Function): http.Server; - - listen(port: number, hostname: string, callback?: Function): http.Server; - - listen(port: number, callback?: Function): http.Server; - - listen(path: string, callback?: Function): http.Server; - - listen(handle: any, listeningListener?: Function): http.Server; - - route: IRoute; - - router: string; - - settings: any; - - resource: any; - - map: any; - - locals: any; - - /** - * The app.routes object houses all of the routes defined mapped by the - * associated HTTP verb. This object may be used for introspection - * capabilities, for example Express uses this internally not only for - * routing but to provide default OPTIONS behaviour unless app.options() - * is used. Your application or framework may also remove routes by - * simply by removing them from this object. - */ - routes: any; - } - - interface Express extends Application { - /** - * Framework version. - */ - version: string; - - /** - * Expose mime. - */ - mime: string; - - (): Application; - - /** - * Create an express application. - */ - createApplication(): Application; - - createServer(): Application; - - application: any; - - request: Request; - - response: Response; - } - - /** - * Body parser: - * - * Parse request bodies, supports _application/json_, - * _application/x-www-form-urlencoded_, and _multipart/form-data_. - * - * This is equivalent to: - * - * app.use(connect.json()); - * app.use(connect.urlencoded()); - * app.use(connect.multipart()); - * - * Examples: - * - * connect() - * .use(connect.bodyParser()) - * .use(function(req, res) { - * res.end('viewing user ' + req.body.user.name); - * }); - * - * $ curl -d 'user[name]=tj' http://local/ - * $ curl -d '{"user":{"name":"tj"}}' -H "Content-Type: application/json" http://local/ - * - * View [json](json.html), [urlencoded](urlencoded.html), and [multipart](multipart.html) for more info. - * - * @param options - */ - function bodyParser(options?: any): Handler; - - /** - * Error handler: - * - * Development error handler, providing stack traces - * and error message responses for requests accepting text, html, - * or json. - * - * Text: - * - * By default, and when _text/plain_ is accepted a simple stack trace - * or error message will be returned. - * - * JSON: - * - * When _application/json_ is accepted, connect will respond with - * an object in the form of `{ "error": error }`. - * - * HTML: - * - * When accepted connect will output a nice html stack trace. - */ - function errorHandler(opts?: any): Handler; - - /** - * Method Override: - * - * Provides faux HTTP method support. - * - * Pass an optional `key` to use when checking for - * a method override, othewise defaults to _\_method_. - * The original method is available via `req.originalMethod`. - * - * @param key - */ - function methodOverride(key?: string): Handler; - - /** - * Cookie parser: - * - * Parse _Cookie_ header and populate `req.cookies` - * with an object keyed by the cookie names. Optionally - * you may enabled signed cookie support by passing - * a `secret` string, which assigns `req.secret` so - * it may be used by other middleware. - * - * Examples: - * - * connect() - * .use(connect.cookieParser('optional secret string')) - * .use(function(req, res, next){ - * res.end(JSON.stringify(req.cookies)); - * }) - * - * @param secret - */ - function cookieParser(secret?: string): Handler; - - /** - * Session: - * - * Setup session store with the given `options`. - * - * Session data is _not_ saved in the cookie itself, however - * cookies are used, so we must use the [cookieParser()](cookieParser.html) - * middleware _before_ `session()`. - * - * Examples: - * - * connect() - * .use(connect.cookieParser()) - * .use(connect.session({ secret: 'keyboard cat', key: 'sid', cookie: { secure: true }})) - * - * Options: - * - * - `key` cookie name defaulting to `connect.sid` - * - `store` session store instance - * - `secret` session cookie is signed with this secret to prevent tampering - * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` - * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") - * - * Cookie option: - * - * By default `cookie.maxAge` is `null`, meaning no "expires" parameter is set - * so the cookie becomes a browser-session cookie. When the user closes the - * browser the cookie (and session) will be removed. - * - * ## req.session - * - * To store or access session data, simply use the request property `req.session`, - * which is (generally) serialized as JSON by the store, so nested objects - * are typically fine. For example below is a user-specific view counter: - * - * connect() - * .use(connect.favicon()) - * .use(connect.cookieParser()) - * .use(connect.session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }})) - * .use(function(req, res, next){ - * var sess = req.session; - * if (sess.views) { - * res.setHeader('Content-Type', 'text/html'); - * res.write('

views: ' + sess.views + '

'); - * res.write('

expires in: ' + (sess.cookie.maxAge / 1000) + 's

'); - * res.end(); - * sess.views++; - * } else { - * sess.views = 1; - * res.end('welcome to the session demo. refresh!'); - * } - * } - * )).listen(3000); - * - * ## Session#regenerate() - * - * To regenerate the session simply invoke the method, once complete - * a new SID and `Session` instance will be initialized at `req.session`. - * - * req.session.regenerate(function(err){ - * // will have a new session here - * }); - * - * ## Session#destroy() - * - * Destroys the session, removing `req.session`, will be re-generated next request. - * - * req.session.destroy(function(err){ - * // cannot access session here - * }); - * - * ## Session#reload() - * - * Reloads the session data. - * - * req.session.reload(function(err){ - * // session updated - * }); - * - * ## Session#save() - * - * Save the session. - * - * req.session.save(function(err){ - * // session saved - * }); - * - * ## Session#touch() - * - * Updates the `.maxAge` property. Typically this is - * not necessary to call, as the session middleware does this for you. - * - * ## Session#cookie - * - * Each session has a unique cookie object accompany it. This allows - * you to alter the session cookie per visitor. For example we can - * set `req.session.cookie.expires` to `false` to enable the cookie - * to remain for only the duration of the user-agent. - * - * ## Session#maxAge - * - * Alternatively `req.session.cookie.maxAge` will return the time - * remaining in milliseconds, which we may also re-assign a new value - * to adjust the `.expires` property appropriately. The following - * are essentially equivalent - * - * var hour = 3600000; - * req.session.cookie.expires = new Date(Date.now() + hour); - * req.session.cookie.maxAge = hour; - * - * For example when `maxAge` is set to `60000` (one minute), and 30 seconds - * has elapsed it will return `30000` until the current request has completed, - * at which time `req.session.touch()` is called to reset `req.session.maxAge` - * to its original value. - * - * req.session.cookie.maxAge; - * // => 30000 - * - * Session Store Implementation: - * - * Every session store _must_ implement the following methods - * - * - `.get(sid, callback)` - * - `.set(sid, session, callback)` - * - `.destroy(sid, callback)` - * - * Recommended methods include, but are not limited to: - * - * - `.length(callback)` - * - `.clear(callback)` - * - * For an example implementation view the [connect-redis](http://github.com/visionmedia/connect-redis) repo. - * - * @param options - */ - function session(options?: any): Handler; - - /** - * Hash the given `sess` object omitting changes - * to `.cookie`. - * - * @param sess - */ - function hash(sess: string): string; - - /** - * Static: - * - * Static file server with the given `root` path. - * - * Examples: - * - * var oneDay = 86400000; - * - * connect() - * .use(connect.static(__dirname + '/public')) - * - * connect() - * .use(connect.static(__dirname + '/public', { maxAge: oneDay })) - * - * Options: - * - * - `maxAge` Browser cache maxAge in milliseconds. defaults to 0 - * - `hidden` Allow transfer of hidden files. defaults to false - * - `redirect` Redirect to trailing "/" when the pathname is a dir. defaults to true - * - * @param root - * @param options - */ - function static(root: string, options?: any): Handler; - - /** - * Basic Auth: - * - * Enfore basic authentication by providing a `callback(user, pass)`, - * which must return `true` in order to gain access. Alternatively an async - * method is provided as well, invoking `callback(user, pass, callback)`. Populates - * `req.user`. The final alternative is simply passing username / password - * strings. - * - * Simple username and password - * - * connect(connect.basicAuth('username', 'password')); - * - * Callback verification - * - * connect() - * .use(connect.basicAuth(function(user, pass){ - * return 'tj' == user & 'wahoo' == pass; - * })) - * - * Async callback verification, accepting `fn(err, user)`. - * - * connect() - * .use(connect.basicAuth(function(user, pass, fn){ - * User.authenticate({ user: user, pass: pass }, fn); - * })) - * - * @param callback or username - * @param realm - */ - export function basicAuth(callback: (user: string, pass: string, fn : Function) => void, realm?: string): Handler; - - export function basicAuth(callback: (user: string, pass: string) => boolean, realm?: string): Handler; - - export function basicAuth(user: string, pass: string, realm?: string): Handler; - - /** - * Compress: - * - * Compress response data with gzip/deflate. - * - * Filter: - * - * A `filter` callback function may be passed to - * replace the default logic of: - * - * exports.filter = function(req, res){ - * return /json|text|javascript/.test(res.getHeader('Content-Type')); - * }; - * - * Options: - * - * All remaining options are passed to the gzip/deflate - * creation functions. Consult node's docs for additional details. - * - * - `chunkSize` (default: 16*1024) - * - `windowBits` - * - `level`: 0-9 where 0 is no compression, and 9 is slow but best compression - * - `memLevel`: 1-9 low is slower but uses less memory, high is fast but uses more - * - `strategy`: compression strategy - * - * @param options - */ - function compress(options?: any): Handler; - - /** - * Cookie Session: - * - * Cookie session middleware. - * - * var app = connect(); - * app.use(connect.cookieParser()); - * app.use(connect.cookieSession({ secret: 'tobo!', cookie: { maxAge: 60 * 60 * 1000 }})); - * - * Options: - * - * - `key` cookie name defaulting to `connect.sess` - * - `secret` prevents cookie tampering - * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` - * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") - * - * Clearing sessions: - * - * To clear the session simply set its value to `null`, - * `cookieSession()` will then respond with a 1970 Set-Cookie. - * - * req.session = null; - * - * @param options - */ - function cookieSession(options?: any): Handler; - - /** - * Anti CSRF: - * - * CSRF protection middleware. - * - * This middleware adds a `req.csrfToken()` function to make a token - * which should be added to requests which mutate - * state, within a hidden form field, query-string etc. This - * token is validated against the visitor's session. - * - * The default `value` function checks `req.body` generated - * by the `bodyParser()` middleware, `req.query` generated - * by `query()`, and the "X-CSRF-Token" header field. - * - * This middleware requires session support, thus should be added - * somewhere _below_ `session()` and `cookieParser()`. - * - * Options: - * - * - `value` a function accepting the request, returning the token - * - * @param options - */ - export function csrf(options?: {value?: Function}): Handler; - - /** - * Directory: - * - * Serve directory listings with the given `root` path. - * - * Options: - * - * - `hidden` display hidden (dot) files. Defaults to false. - * - `icons` display icons. Defaults to false. - * - `filter` Apply this filter function to files. Defaults to false. - * - * @param root - * @param options - */ - function directory(root: string, options?: any): Handler; - - /** - * Favicon: - * - * By default serves the connect favicon, or the favicon - * located by the given `path`. - * - * Options: - * - * - `maxAge` cache-control max-age directive, defaulting to 1 day - * - * Examples: - * - * Serve default favicon: - * - * connect() - * .use(connect.favicon()) - * - * Serve favicon before logging for brevity: - * - * connect() - * .use(connect.favicon()) - * .use(connect.logger('dev')) - * - * Serve custom favicon: - * - * connect() - * .use(connect.favicon('public/favicon.ico)) - * - * @param path - * @param options - */ - export function favicon(path?: string, options?: any): Handler; - - /** - * JSON: - * - * Parse JSON request bodies, providing the - * parsed object as `req.body`. - * - * Options: - * - * - `strict` when `false` anything `JSON.parse()` accepts will be parsed - * - `reviver` used as the second "reviver" argument for JSON.parse - * - `limit` byte limit disabled by default - * - * @param options - */ - function json(options?: any): Handler; - - /** - * Limit: - * - * Limit request bodies to the given size in `bytes`. - * - * A string representation of the bytesize may also be passed, - * for example "5mb", "200kb", "1gb", etc. - * - * connect() - * .use(connect.limit('5.5mb')) - * .use(handleImageUpload) - */ - function limit(bytes: number): Handler; - - function limit(bytes: string): Handler; - - /** - * Logger: - * - * Log requests with the given `options` or a `format` string. - * - * Options: - * - * - `format` Format string, see below for tokens - * - `stream` Output stream, defaults to _stdout_ - * - `buffer` Buffer duration, defaults to 1000ms when _true_ - * - `immediate` Write log line on request instead of response (for response times) - * - * Tokens: - * - * - `:req[header]` ex: `:req[Accept]` - * - `:res[header]` ex: `:res[Content-Length]` - * - `:http-version` - * - `:response-time` - * - `:remote-addr` - * - `:date` - * - `:method` - * - `:url` - * - `:referrer` - * - `:user-agent` - * - `:status` - * - * Formats: - * - * Pre-defined formats that ship with connect: - * - * - `default` ':remote-addr - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"' - * - `short` ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms' - * - `tiny` ':method :url :status :res[content-length] - :response-time ms' - * - `dev` concise output colored by response status for development use - * - * Examples: - * - * connect.logger() // default - * connect.logger('short') - * connect.logger('tiny') - * connect.logger({ immediate: true, format: 'dev' }) - * connect.logger(':method :url - :referrer') - * connect.logger(':req[content-type] -> :res[content-type]') - * connect.logger(function(tokens, req, res){ return 'some format string' }) - * - * Defining Tokens: - * - * To define a token, simply invoke `connect.logger.token()` with the - * name and a callback function. The value returned is then available - * as ":type" in this case. - * - * connect.logger.token('type', function(req, res){ return req.headers['content-type']; }) - * - * Defining Formats: - * - * All default formats are defined this way, however it's public API as well: - * - * connect.logger.format('name', 'string or function') - */ - function logger(options: string): Handler; - - function logger(options: Function): Handler; - - function logger(options?: any): Handler; - - /** - * Compile `fmt` into a function. - * - * @param fmt - */ - function compile(fmt: string): Handler; - - /** - * Define a token function with the given `name`, - * and callback `fn(req, res)`. - * - * @param name - * @param fn - */ - function token(name: string, fn: Function): any; - - /** - * Define a `fmt` with the given `name`. - */ - function format(name: string, str: string): any; - - function format(name: string, str: Function): any; - - /** - * Query: - * - * Automatically parse the query-string when available, - * populating the `req.query` object. - * - * Examples: - * - * connect() - * .use(connect.query()) - * .use(function(req, res){ - * res.end(JSON.stringify(req.query)); - * }); - * - * The `options` passed are provided to qs.parse function. - */ - function query(options: any): Handler; - - /** - * Reponse time: - * - * Adds the `X-Response-Time` header displaying the response - * duration in milliseconds. - */ - function responseTime(): Handler; - - /** - * Static cache: - * - * Enables a memory cache layer on top of - * the `static()` middleware, serving popular - * static files. - * - * By default a maximum of 128 objects are - * held in cache, with a max of 256k each, - * totalling ~32mb. - * - * A Least-Recently-Used (LRU) cache algo - * is implemented through the `Cache` object, - * simply rotating cache objects as they are - * hit. This means that increasingly popular - * objects maintain their positions while - * others get shoved out of the stack and - * garbage collected. - * - * Benchmarks: - * - * static(): 2700 rps - * node-static: 5300 rps - * static() + staticCache(): 7500 rps - * - * Options: - * - * - `maxObjects` max cache objects [128] - * - `maxLength` max cache object length 256kb - */ - function staticCache(options: any): Handler; - - /** - * Timeout: - * - * Times out the request in `ms`, defaulting to `5000`. The - * method `req.clearTimeout()` is added to revert this behaviour - * programmatically within your application's middleware, routes, etc. - * - * The timeout error is passed to `next()` so that you may customize - * the response behaviour. This error has the `.timeout` property as - * well as `.status == 408`. - */ - function timeout(ms: number): Handler; - - /** - * Vhost: - * - * Setup vhost for the given `hostname` and `server`. - * - * connect() - * .use(connect.vhost('foo.com', fooApp)) - * .use(connect.vhost('bar.com', barApp)) - * .use(connect.vhost('*.com', mainApp)) - * - * The `server` may be a Connect server or - * a regular Node `http.Server`. - * - * @param hostname - * @param server - */ - function vhost(hostname: string, server: any): Handler; - - function urlencoded(): any; - - function multipart(): any; - - } - - export = e; -} - From 8b07ce8811369dfe80a465e292ba1d1f43281288 Mon Sep 17 00:00:00 2001 From: Santi Albo Date: Thu, 17 Jul 2014 13:18:27 +0100 Subject: [PATCH 131/324] A Router is also a RequestHandler --- express/express.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/express/express.d.ts b/express/express.d.ts index 052173c83..2dc36199c 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -38,7 +38,7 @@ declare module "express" { (name: RegExp, ...handlers: RequestHandler[]): T; } - interface IRouter { + interface IRouter extends RequestHandler { /** * Map the given param placeholder `name`(s) to the given callback(s). * From b09ee215ec421b7ed51ba44b90c8d0f5f25b3cf3 Mon Sep 17 00:00:00 2001 From: zaneli Date: Thu, 17 Jul 2014 21:21:02 +0900 Subject: [PATCH 132/324] Add definitions for ProgressJs --- CONTRIBUTORS.md | 1 + progressjs/progress-tests.ts | 36 ++++++++++++ progressjs/progress.d.ts | 103 +++++++++++++++++++++++++++++++++++ 3 files changed, 140 insertions(+) create mode 100644 progressjs/progress-tests.ts create mode 100644 progressjs/progress.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index c01d01147..456dbc9ce 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -271,6 +271,7 @@ All definitions files include a header with the author and editors, so at some p * [Platform](https://github.com/bestiejs/platform.js) (by [Jake Hickman](https://github.com/JakeH)) * [PouchDB](http://pouchdb.com) (by [Bill Sears](https://github.com/MrBigDog2U/)) * [PreloadJS](http://www.createjs.com/#!/PreloadJS) (by [Pedro Ferreira](https://bitbucket.org/drk4)) +* [ProgressJs](http://usablica.github.io/progress.js/) (by [Shunsuke Ohtani](https://github.com/zaneli)) * [Q](https://github.com/kriskowal/q) (by Barrie Nemetchek, Andrew Gaspar) * [Q-io](https://github.com/kriskowal/q-io) (by [Bart van der Schoor](https://github.com/Bartvds)) * [QUnit](http://qunitjs.com/) (by [Diullei Gomes](https://github.com/Diullei)) diff --git a/progressjs/progress-tests.ts b/progressjs/progress-tests.ts new file mode 100644 index 000000000..e2ab62f9a --- /dev/null +++ b/progressjs/progress-tests.ts @@ -0,0 +1,36 @@ +/// + +progressJs(); //without selector, set progress-bar for whole page +progressJs("#targetElement"); //start progress-bar for element id='targetElement' + +progressJs().start(); + +progressJs().set(20); //set progress to 20% + +progressJs().start().autoIncrease(4, 500); //every 500 milliseconds, percentage + 4 + +progressJs().increase(); //increase one percent +progressJs().increase(2); //increase two percent + +progressJs().start().set(20).end(); + +progressJs().setOption("theme", "black"); +progressJs().setOption("overlayMode", true); +progressJs().setOption("considerTransition", false); + +progressJs().setOptions({ 'theme': 'black', 'overlayMode': true }); +progressJs().setOptions({ 'theme': 'black', 'overlayMode': true }); +progressJs().setOptions({ 'theme': 'black', 'overlayMode': true, 'considerTransition': false }); +progressJs().setOptions({ 'overlayMode': true }); + +progressJs().onbeforeend(function() { + alert("before end"); +}); + +progressJs().onbeforestart(function() { + alert("before start"); +}); + +progressJs().onprogress(function(targetElm, percent) { + alert("progress changed to:" + percent); +}); diff --git a/progressjs/progress.d.ts b/progressjs/progress.d.ts new file mode 100644 index 000000000..a7f9923c3 --- /dev/null +++ b/progressjs/progress.d.ts @@ -0,0 +1,103 @@ +// Type definitions for ProgressJs v0.1.0 +// Project: http://usablica.github.io/progress.js/ +// Definitions by: Shunsuke Ohtani +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface ProgressJsStatic { + + /** + * Creating an ProgressJS object. + * + * @param targetElm String (optional) Should be defined to start progress-bar for specific element. + */ + (targetElm?: string): ProgressJs; +} + +interface ProgressJs { + + /** + * Start the progress-bar for defined element(s). + */ + start(): ProgressJs; + + /** + * Set specific percentage to progress-bar. + * + * @param percent Set to specific percentage. + */ + set(percent: number): ProgressJs; + + /** + * Set an auto-increase timer for the progress-bar. + * + * @param size The size of increment when timer elapsed. + * @param millisecond Timer in milliseconds. + */ + autoIncrease(size: number, millisecond: number): ProgressJs; + + /** + * Increase the progress-bar bar specified size. Default size is 1. + * + * @param size The size of increment. + */ + increase(size?: number): ProgressJs; + + /** + * End the progress-bar and remove the elements from page. + */ + end(): ProgressJs; + + /** + * Set a single option to progressJs object. + * + * @param option Option key name. + * @param value Value of the option. + */ + setOption(option: string, value: string): ProgressJs; + setOption(option: string, value: boolean): ProgressJs; + + /** + * Set a group of options to the progressJs object. + * + * @param options Object that contains option keys with values. + */ + setOptions(options: ProgressJsOptions): ProgressJs; + + /** + * Set a callback function for before end of the progress-bar. + * + * @param providedCallback Callback function. + */ + onbeforeend(providedCallback: () => any): ProgressJs; + + /** + * Set a callback function to call before start the progress-bar. + * + * @param providedCallback Callback function. + */ + onbeforestart(providedCallback: () => any): ProgressJs; + + /** + * Set callback function to call for each change of progress-bar. + * + * @param providedCallback Callback function. + */ + onprogress(providedCallback: (targetElement: string, percent: number) => any): ProgressJs; +} + +interface ProgressJsOptions { + /** + * progress bar theme + */ + theme?: string; + /** + * overlay mode makes an overlay layer in the target element + */ + overlayMode?: boolean; + /** + * to consider CSS3 transitions in events + */ + considerTransition?: boolean; +} + +declare var progressJs: ProgressJsStatic From 43f1770f23c542e5b07b102f6f2b7fbf58eb82d8 Mon Sep 17 00:00:00 2001 From: Santi Albo Date: Thu, 17 Jul 2014 13:22:10 +0100 Subject: [PATCH 133/324] use takes multiple request handlers now --- express/express.d.ts | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/express/express.d.ts b/express/express.d.ts index 2dc36199c..3eb3649d9 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -89,12 +89,10 @@ declare module "express" { route(path: string): IRoute; - use(server: Application): Application; - use(handler: RequestHandler): Application; - use(handler: ErrorRequestHandler): Application; - use(path: string, server: Application): Application; - use(path: string, handler: RequestHandler): Application; - use(path: string, handler: ErrorRequestHandler): Application; + use(...handler: RequestHandler[]): T; + use(handler: ErrorRequestHandler): T; + use(path: string, ...handler: RequestHandler[]): T; + use(path: string, handler: ErrorRequestHandler): T; } export function Router(options?: any): Router; From e039638763ea9c7e581a32fcfac3b4559ac47506 Mon Sep 17 00:00:00 2001 From: Santi Albo Date: Thu, 17 Jul 2014 13:22:19 +0100 Subject: [PATCH 134/324] Add more tests --- express/express-tests.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/express/express-tests.ts b/express/express-tests.ts index cda1e3e2e..76fa4da0d 100644 --- a/express/express-tests.ts +++ b/express/express-tests.ts @@ -18,4 +18,19 @@ app.get('/', function(req, res){ res.send('hello world'); }); +var router = express.Router(); + +router.use((req, res, next) => { next(); }) +router.route('/users') + .get((req, res, next) => { + res.send(req.query['token']); + }); + +app.use((req, res, next) => { + // hacky trick, router is just a handler + router(req, res, next); +}); + +app.use(router); + app.listen(3000); From bc8bc17374d87764fb6338f67ac12940f0ffc0c4 Mon Sep 17 00:00:00 2001 From: Ian Sibner Date: Thu, 17 Jul 2014 11:30:43 -0400 Subject: [PATCH 135/324] Changes based on @BillArmstrong's feedback * Remove optional parameters from Element interface * Remove additional parameters from ElementFinder.isElementPresent * Add "asElementFinders_" and "then" methods to ElementArrayFinder interface --- .../angular-protractor-tests.ts | 5 +- angular-protractor/angular-protractor.d.ts | 71 +++++++++++-------- 2 files changed, 47 insertions(+), 29 deletions(-) diff --git a/angular-protractor/angular-protractor-tests.ts b/angular-protractor/angular-protractor-tests.ts index 62ed46177..5ca9ecde4 100644 --- a/angular-protractor/angular-protractor-tests.ts +++ b/angular-protractor/angular-protractor-tests.ts @@ -211,7 +211,6 @@ function TestElementFinder() { promise = elementFinder.getOuterHtml(); promise = elementFinder.getInnerHtml(); promise = elementFinder.isElementPresent(by.id('id')); - promise = elementFinder.isElementPresent(by.js('function(a, b, c) {}'), 1, 2, 3); promise = elementFinder.$('.class'); promise = elementFinder.$$('.class'); promise = elementFinder.evaluate('expression'); @@ -230,6 +229,7 @@ function TestElementArrayFinder() { elementFinder = elementArrayFinder.first(); elementFinder = elementArrayFinder.last(); promise = elementArrayFinder.count(); + promise = elementArrayFinder.asElementFinders_(); elementArrayFinder.each(function(element: protractor.ElementFinder){ // nothing }); @@ -251,6 +251,9 @@ function TestElementArrayFinder() { return accumulator + ',' + text; }); }, ''); + elementArrayFinder.then(function(underlyingElementFinders: protractor.ElementFinder[]){ + //nothing + }); } // This function tests the angular specific locator strategies. diff --git a/angular-protractor/angular-protractor.d.ts b/angular-protractor/angular-protractor.d.ts index 81eca975e..2de49a0a4 100644 --- a/angular-protractor/angular-protractor.d.ts +++ b/angular-protractor/angular-protractor.d.ts @@ -225,31 +225,19 @@ declare module protractor { * before the page is available. * * @param {webdriver.Locator} locator An element locator. - * @param {ElementFinder=} opt_parentElementFinder The element finder previous - * to this. (i.e. opt_parentElementFinder.element(locator) => this) - * @param {webdriver.promise.Promise} opt_actionResult The promise which - * will be retrieved with then. Resolves to the latest action result, - * or null if no action has been called. - * @param {number=} opt_index The index of the element to retrieve. null means - * retrieve the only element, while -1 means retrieve the last element * @return {ElementFinder} */ interface Element { - (locator: webdriver.Locator, - opt_parentElementFinder?: protractor.ElementFinder, - opt_actionResult?: webdriver.promise.Promise, - opt_index?: number): ElementFinder; + (locator: webdriver.Locator): ElementFinder; /** * ElementArrayFinder is used for operations on an array of elements (as opposed * to a single element). * * @param {webdriver.Locator} locator An element locator. - * @param {ElementFinder=} opt_parentElementFinder The element finder previous to - * this. (i.e. opt_parentElementFinder.all(locator) => this) * @return {ElementArrayFinder} */ - all(locator: webdriver.Locator, opt_parentElementFinder?: protractor.ElementFinder): ElementArrayFinder; + all(locator: webdriver.Locator): ElementArrayFinder; } interface ElementFinder { @@ -301,21 +289,13 @@ declare module protractor { isPresent(): webdriver.promise.Promise; /** - * Schedules a command to test if there is at least one descendant of this - * element that matches the given search criteria. + * Override for WebElement.prototype.isElementPresent so that protractor waits + * for Angular to settle before making the check. * - *

Note that JS locator searches cannot be restricted to a subtree of the - * DOM. All such searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the element. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * whether an element could be located on the page. + * @see ElementFinder.isPresent + * @return {!webdriver.promise.Promise} which resolves to whether the element is present on the page. */ - isElementPresent(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; - isElementPresent(locator: any, ...var_args: any[]): webdriver.promise.Promise; + isElementPresent(locator: webdriver.Locator): webdriver.promise.Promise; /** * Return this ElementFinder's locator. @@ -552,7 +532,7 @@ declare module protractor { } interface IThenFunction { - (promise: webdriver.promise.Promise): any; + (promiseResult: any): any; } @@ -641,6 +621,37 @@ declare module protractor { * @return {!webdriver.promise.Promise} A promise that resolves to the final value of the accumulator. */ reduce(func: IReductionFunction, initialValue: any): webdriver.promise.Promise; + + /** + * Represents the ElementArrayFinder as an array of ElementFinders. + * + * @return {!webdriver.promise.Promise} Return a promise, which resolves to a list (array) + * of ElementFinders specified by the locator. + */ + asElementFinders_(): webdriver.promise.Promise; + + + /** + * Find the elements specified by the locator. The input function is passed + * to the resulting promise, which resolves to an array of ElementFinders. + * + * Use as: element.all(locator).then(thenFunction) + *

    + *
  • First
  • + *
  • Second
  • + *
  • Third
  • + *
+ * + * element.all(by.css('.items li')).then(function(arr) { + * expect(arr.length).toEqual(3); + * }); + * + * @param {function(Array.)} fn + * + * @type {webdriver.promise.Promise} a promise which will resolve to + * an array of ElementFinders matching the locator. + */ + then(fn: IElementArrayFinderThenFunction): webdriver.promise.Promise; } interface IEachFunction { @@ -659,6 +670,10 @@ declare module protractor { (accumulator: any, element: protractor.ElementFinder, index?: number, array?: protractor.ElementFinder[]): webdriver.promise.Promise; } + interface IElementArrayFinderThenFunction { + (promiseResult: ElementFinder[]): any; + } + class LocatorWithColumn extends webdriver.Locator { column(index: number): webdriver.Locator; } From c7cb7f5ceaa6eba0e18f4b4c8d67af833cd34ee5 Mon Sep 17 00:00:00 2001 From: Santi Albo Date: Thu, 17 Jul 2014 19:17:47 +0100 Subject: [PATCH 136/324] Fix errorhandler test --- errorhandler/errorhandler-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/errorhandler/errorhandler-tests.ts b/errorhandler/errorhandler-tests.ts index 02f788790..1d02ed14c 100644 --- a/errorhandler/errorhandler-tests.ts +++ b/errorhandler/errorhandler-tests.ts @@ -1,4 +1,4 @@ -/// +/// import express = require('express'); import errorhandler = require('errorhandler'); From 9dbba87a0de04697b26391557f48acfff113b7ce Mon Sep 17 00:00:00 2001 From: Santi Albo Date: Thu, 17 Jul 2014 19:20:44 +0100 Subject: [PATCH 137/324] Fix headers --- body-parser/body-parser.d.ts | 2 +- compression/compression.d.ts | 2 +- cookie-parser/cookie-parser.d.ts | 2 +- errorhandler/errorhandler.d.ts | 2 +- express/express.d.ts | 2 +- method-override/method-override.d.ts | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/body-parser/body-parser.d.ts b/body-parser/body-parser.d.ts index f16b2eefb..0cd67332a 100644 --- a/body-parser/body-parser.d.ts +++ b/body-parser/body-parser.d.ts @@ -1,7 +1,7 @@ // Type definitions for body-parser // Project: http://expressjs.com // Definitions by: Santi Albo -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/compression/compression.d.ts b/compression/compression.d.ts index 9ef3a8cb7..00b2e0459 100644 --- a/compression/compression.d.ts +++ b/compression/compression.d.ts @@ -1,7 +1,7 @@ // Type definitions for compression // Project: https://github.com/expressjs/compression // Definitions by: Santi Albo -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/cookie-parser/cookie-parser.d.ts b/cookie-parser/cookie-parser.d.ts index f43553b7c..a4897c5e7 100644 --- a/cookie-parser/cookie-parser.d.ts +++ b/cookie-parser/cookie-parser.d.ts @@ -1,7 +1,7 @@ // Type definitions for cookie-parser // Project: https://github.com/expressjs/cookie-parser // Definitions by: Santi Albo -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/errorhandler/errorhandler.d.ts b/errorhandler/errorhandler.d.ts index e6c3011a5..31bf44ce1 100644 --- a/errorhandler/errorhandler.d.ts +++ b/errorhandler/errorhandler.d.ts @@ -1,7 +1,7 @@ // Type definitions for errorhandler // Project: https://github.com/expressjs/errorhandler // Definitions by: Santi Albo -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/express/express.d.ts b/express/express.d.ts index 3eb3649d9..18d6f993a 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -1,7 +1,7 @@ // Type definitions for Express 4.x // Project: http://expressjs.com // Definitions by: Boris Yankov -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/method-override/method-override.d.ts b/method-override/method-override.d.ts index 51b62f521..099b5eeb9 100644 --- a/method-override/method-override.d.ts +++ b/method-override/method-override.d.ts @@ -1,7 +1,7 @@ // Type definitions for method-override // Project: https://github.com/expressjs/method-override // Definitions by: Santi Albo -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// From 6db771a25952f260a8cbc412fcd158cb9b04e360 Mon Sep 17 00:00:00 2001 From: Santi Albo Date: Thu, 17 Jul 2014 19:23:22 +0100 Subject: [PATCH 138/324] Add Handler interface for backwards compatibility on Passport type definitions --- express/express.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/express/express.d.ts b/express/express.d.ts index 18d6f993a..984007192 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -746,6 +746,8 @@ declare module "express" { (req: Request, res: Response, next: Function): any; } + interface Handler extends RequestHandler {} + interface RequestParamHandler { (req: Request, res: Response, next: Function, param: any): any; } From dc8ac9a4789408c9232bd41d42cbc32180455bf6 Mon Sep 17 00:00:00 2001 From: Santi Albo Date: Thu, 17 Jul 2014 19:43:47 +0100 Subject: [PATCH 139/324] Fix passport tests --- passport/passport.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/passport/passport.d.ts b/passport/passport.d.ts index 37d4035a0..fc3dd786f 100644 --- a/passport/passport.d.ts +++ b/passport/passport.d.ts @@ -5,6 +5,12 @@ /// +declare module Express { + export interface Request { + session?: any; + } +} + declare module 'passport' { import express = require('express'); From 44ace5c6602c18d5301b23c66d197bb97a086d68 Mon Sep 17 00:00:00 2001 From: Tom Hasner Date: Thu, 17 Jul 2014 18:04:10 -0400 Subject: [PATCH 140/324] added second argument "element" to $.filter --- jquery/jquery.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index 59159a188..eb6ec2e56 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -3655,7 +3655,7 @@ interface JQuery { * * @param func A function used as a test for each element in the set. this is the current DOM element. */ - filter(func: (index: number) => any): JQuery; + filter(func: (index: number, element: Element) => any): JQuery; /** * Reduce the set of matched elements to those that match the selector or pass the function's test. * From c9370c43268664be14a67f139137c8cc7affa71a Mon Sep 17 00:00:00 2001 From: Kensuke Matsuzaki Date: Fri, 18 Jul 2014 14:45:24 +0900 Subject: [PATCH 141/324] Fix jQuery BlockUI Plugin --- jquery.blockUI/jquery.blockUI-tests.ts | 14 ++++++++++++++ jquery.blockUI/jquery.blockUI.d.ts | 10 +++++----- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/jquery.blockUI/jquery.blockUI-tests.ts b/jquery.blockUI/jquery.blockUI-tests.ts index 19372976f..234340b93 100644 --- a/jquery.blockUI/jquery.blockUI-tests.ts +++ b/jquery.blockUI/jquery.blockUI-tests.ts @@ -9,3 +9,17 @@ $.blockUI(opt); $.unblockUI(); $("#test").block().unblock(); $("#test").block(opt); + +$.blockUI.defaults.css.border = '5px solid red'; +$.blockUI.defaults.fadeOut = 200; + +$.blockUI({ message: $('#domMessage') }); +$.unblockUI({ fadeOut: 200 }); + +$.blockUI({ + fadeIn: 1000, + timeout: 2000, + onBlock: function() { + alert('Page is now blocked; fadeIn complete'); + } +}); diff --git a/jquery.blockUI/jquery.blockUI.d.ts b/jquery.blockUI/jquery.blockUI.d.ts index 5b1df3f7b..259044eaf 100644 --- a/jquery.blockUI/jquery.blockUI.d.ts +++ b/jquery.blockUI/jquery.blockUI.d.ts @@ -7,7 +7,7 @@ interface JQBlockUIOptions { /** message displayed when blocking (use null for no message) */ - message?: string; + message?: any; /** title string; only used when theme == true */ title?: string; /** only used when theme == true (requires jquery-ui.js to be loaded) */ @@ -76,7 +76,7 @@ interface JQBlockUIOptions { focusInput?: boolean; /** callback method invoked when fadeIn has completed and blocking message is visible */ - onBlock?: boolean; + onBlock?: () => void; /** * callback method invoked when unblocking has completed; the callback is @@ -99,7 +99,7 @@ interface JQBlockUIOptions { interface JQBlockUIStatic { /** default options */ - default?: JQBlockUIOptions; + defaults?: JQBlockUIOptions; /** block user activity for the page */ (): void; /** @@ -113,7 +113,7 @@ interface JQueryStatic { /** block user activity for the page */ blockUI?: JQBlockUIStatic; /** unblock the page */ - unblockUI?: () => void; + unblockUI?: JQBlockUIStatic; } interface JQuery { @@ -125,5 +125,5 @@ interface JQuery { /** * unblock the element(s) */ - unblock(): JQuery; + unblock(option?: JQBlockUIOptions): JQuery; } \ No newline at end of file From dfab9f569d2233725c375fd17841ff4b649685b0 Mon Sep 17 00:00:00 2001 From: Bart van der Schoor Date: Sat, 19 Jul 2014 05:11:42 +0200 Subject: [PATCH 142/324] moved chai-assert into main chai definition renamed chai-fuzzy-assert to chai-fuzzy --- chai-datetime/chai-datetime-tests.ts | 4 +- ...chai-fuzzy-assert.d.ts => chai-fuzzy.d.ts} | 4 +- ...ts.tscparams => chai-fuzzy.d.ts.tscparams} | 0 chai/chai-assert-tests.ts | 655 ------------------ chai/chai-assert.d.ts | 131 ---- chai/chai-tests.ts | 621 +++++++++++++++++ chai/chai.d.ts | 117 +++- 7 files changed, 741 insertions(+), 791 deletions(-) rename chai-fuzzy/{chai-fuzzy-assert.d.ts => chai-fuzzy.d.ts} (91%) rename chai-fuzzy/{chai-fuzzy-assert.d.ts.tscparams => chai-fuzzy.d.ts.tscparams} (100%) delete mode 100644 chai/chai-assert-tests.ts delete mode 100644 chai/chai-assert.d.ts diff --git a/chai-datetime/chai-datetime-tests.ts b/chai-datetime/chai-datetime-tests.ts index 0b7ff729f..8f8238b4e 100644 --- a/chai-datetime/chai-datetime-tests.ts +++ b/chai-datetime/chai-datetime-tests.ts @@ -1,8 +1,8 @@ /// -/// /// var expect = chai.expect; +var assert = chai.assert; function test_equalTime(){ var date: Date = new Date(2014, 1, 1); @@ -44,4 +44,4 @@ function test_afterDate(){ expect(date).to.afterDate(date); date.should.afterDate(date); assert.afterDate(date, date); -} \ No newline at end of file +} diff --git a/chai-fuzzy/chai-fuzzy-assert.d.ts b/chai-fuzzy/chai-fuzzy.d.ts similarity index 91% rename from chai-fuzzy/chai-fuzzy-assert.d.ts rename to chai-fuzzy/chai-fuzzy.d.ts index f75f99d55..0cbb1741b 100644 --- a/chai-fuzzy/chai-fuzzy-assert.d.ts +++ b/chai-fuzzy/chai-fuzzy.d.ts @@ -3,7 +3,7 @@ // Definitions by: Bart van der Schoor // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// declare module chai { interface Assert { @@ -14,4 +14,4 @@ declare module chai { jsonOf(act:any, exp:any, msg?:string); notJsonOf(act:any, exp:any, msg?:string); } -} \ No newline at end of file +} diff --git a/chai-fuzzy/chai-fuzzy-assert.d.ts.tscparams b/chai-fuzzy/chai-fuzzy.d.ts.tscparams similarity index 100% rename from chai-fuzzy/chai-fuzzy-assert.d.ts.tscparams rename to chai-fuzzy/chai-fuzzy.d.ts.tscparams diff --git a/chai/chai-assert-tests.ts b/chai/chai-assert-tests.ts deleted file mode 100644 index 4dc430f0c..000000000 --- a/chai/chai-assert-tests.ts +++ /dev/null @@ -1,655 +0,0 @@ -/* - ---------- - test extracted from original test suite - chai original licence follows ---------- - -## License - -(The MIT License) - -Copyright (c) 2011-2013 Jake Luer - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -/// - -//stubs - -//tdd -declare function suite(description: string, action: Function):void; -declare function test(description: string, action: Function):void; -declare function err(action: any, msg?: string):void; -interface FieldObj { - field: any; -} -class Foo { - constructor() { - - } -} - -class CrashyObject { - inspect (): void { - throw new Error("Arg's inspect() called even though the test passed"); - } -} - -suite('assert', function () { - - test('assert', function () { - var foo = 'bar'; - assert(foo == 'bar', "expected foo to equal `bar`"); - - err(function () { - assert(foo == 'baz', "expected foo to equal `bar`"); - }, "expected foo to equal `bar`"); - }); - - test('isTrue', function () { - assert.isTrue(true); - - err(function () { - assert.isTrue(false); - }, "expected false to be true"); - - err(function () { - assert.isTrue(1); - }, "expected 1 to be true"); - - err(function () { - assert.isTrue('test'); - }, "expected 'test' to be true"); - }); - - test('ok', function () { - assert.ok(true); - assert.ok(1); - assert.ok('test'); - - err(function () { - assert.ok(false); - }, "expected false to be truthy"); - - err(function () { - assert.ok(0); - }, "expected 0 to be truthy"); - - err(function () { - assert.ok(''); - }, "expected '' to be truthy"); - }); - - test('isFalse', function () { - assert.isFalse(false); - - err(function () { - assert.isFalse(true); - }, "expected true to be false"); - - err(function () { - assert.isFalse(0); - }, "expected 0 to be false"); - }); - - test('equal', function () { - var foo: any; - assert.equal(foo, undefined); - }); - - test('typeof / notTypeOf', function () { - assert.typeOf('test', 'string'); - assert.typeOf(true, 'boolean'); - assert.typeOf(5, 'number'); - - err(function () { - assert.typeOf(5, 'string'); - }, "expected 5 to be a string"); - - }); - - test('notTypeOf', function () { - assert.notTypeOf('test', 'number'); - - err(function () { - assert.notTypeOf(5, 'number'); - }, "expected 5 not to be a number"); - }); - - test('instanceOf', function () { - assert.instanceOf(new Foo(), Foo); - - err(function () { - assert.instanceOf(5, Foo); - }, "expected 5 to be an instance of Foo"); - assert.instanceOf(new CrashyObject(), CrashyObject); - }); - - test('notInstanceOf', function () { - assert.notInstanceOf(new Foo(), String); - - err(function () { - assert.notInstanceOf(new Foo(), Foo); - }, "expected {} to not be an instance of Foo"); - }); - - test('isObject', function () { - assert.isObject({}); - assert.isObject(new Foo()); - - err(function () { - assert.isObject(true); - }, "expected true to be an object"); - - err(function () { - assert.isObject(Foo); - }, "expected [Function: Foo] to be an object"); - - err(function () { - assert.isObject('foo'); - }, "expected 'foo' to be an object"); - }); - - test('isNotObject', function () { - assert.isNotObject(5); - - err(function () { - assert.isNotObject({}); - }, "expected {} not to be an object"); - }); - - test('notEqual', function () { - assert.notEqual(3, 4); - - err(function () { - assert.notEqual(5, 5); - }, "expected 5 to not equal 5"); - }); - - test('strictEqual', function () { - assert.strictEqual('foo', 'foo'); - - err(function () { - assert.strictEqual('5', 5); - }, "expected \'5\' to equal 5"); - }); - - test('notStrictEqual', function () { - assert.notStrictEqual(5, '5'); - - err(function () { - assert.notStrictEqual(5, 5); - }, "expected 5 to not equal 5"); - }); - - test('deepEqual', function () { - assert.deepEqual({tea: 'chai'}, {tea: 'chai'}); - - err(function () { - assert.deepEqual({tea: 'chai'}, {tea: 'black'}); - }, "expected { tea: \'chai\' } to deeply equal { tea: \'black\' }"); - - var obja = Object.create({ tea: 'chai' }) - , objb = Object.create({ tea: 'chai' }); - - assert.deepEqual(obja, objb); - - var obj1 = Object.create({tea: 'chai'}) - , obj2 = Object.create({tea: 'black'}); - - err(function () { - assert.deepEqual(obj1, obj2); - }, "expected { tea: \'chai\' } to deeply equal { tea: \'black\' }"); - }); - - test('deepEqual (ordering)', function () { - var a = { a: 'b', c: 'd' } - , b = { c: 'd', a: 'b' }; - assert.deepEqual(a, b); - }); - - test('deepEqual (circular)', function () { - var circularObject:any = {} - , secondCircularObject:any = {}; - circularObject.field = circularObject; - secondCircularObject.field = secondCircularObject; - - assert.deepEqual(circularObject, secondCircularObject); - - err(function () { - secondCircularObject.field2 = secondCircularObject; - assert.deepEqual(circularObject, secondCircularObject); - }, "expected { field: [Circular] } to deeply equal { Object (field, field2) }"); - }); - - test('notDeepEqual', function () { - assert.notDeepEqual({tea: 'jasmine'}, {tea: 'chai'}); - err(function () { - assert.notDeepEqual({tea: 'chai'}, {tea: 'chai'}); - }, "expected { tea: \'chai\' } to not deeply equal { tea: \'chai\' }"); - }); - - test('notDeepEqual (circular)', function () { - var circularObject:any = {} - , secondCircularObject:any = { tea: 'jasmine' }; - circularObject.field = circularObject; - secondCircularObject.field = secondCircularObject; - - assert.notDeepEqual(circularObject, secondCircularObject); - - err(function () { - delete secondCircularObject.tea; - assert.notDeepEqual(circularObject, secondCircularObject); - }, "expected { field: [Circular] } to not deeply equal { field: [Circular] }"); - }); - - test('isNull', function () { - assert.isNull(null); - - err(function () { - assert.isNull(undefined); - }, "expected undefined to equal null"); - }); - - test('isNotNull', function () { - assert.isNotNull(undefined); - - err(function () { - assert.isNotNull(null); - }, "expected null to not equal null"); - }); - - test('isUndefined', function () { - assert.isUndefined(undefined); - - err(function () { - assert.isUndefined(null); - }, "expected null to equal undefined"); - }); - - test('isDefined', function () { - assert.isDefined(null); - - err(function () { - assert.isDefined(undefined); - }, "expected undefined to not equal undefined"); - }); - - test('isFunction', function () { - var func = function () { - }; - assert.isFunction(func); - - err(function () { - assert.isFunction({}); - }, "expected {} to be a function"); - }); - - test('isNotFunction', function () { - assert.isNotFunction(5); - - err(function () { - assert.isNotFunction(function () { - }); - }, "expected [Function] not to be a function"); - }); - - test('isArray', function () { - assert.isArray([]); - assert.isArray(new Array()); - - err(function () { - assert.isArray({}); - }, "expected {} to be an array"); - }); - - test('isNotArray', function () { - assert.isNotArray(3); - - err(function () { - assert.isNotArray([]); - }, "expected [] not to be an array"); - - err(function () { - assert.isNotArray(new Array()); - }, "expected [] not to be an array"); - }); - - test('isString', function () { - assert.isString('Foo'); - assert.isString(new String('foo')); - - err(function () { - assert.isString(1); - }, "expected 1 to be a string"); - }); - - test('isNotString', function () { - assert.isNotString(3); - assert.isNotString([ 'hello' ]); - - err(function () { - assert.isNotString('hello'); - }, "expected 'hello' not to be a string"); - }); - - test('isNumber', function () { - assert.isNumber(1); - assert.isNumber(Number('3')); - - err(function () { - assert.isNumber('1'); - }, "expected \'1\' to be a number"); - }); - - test('isNotNumber', function () { - assert.isNotNumber('hello'); - assert.isNotNumber([ 5 ]); - - err(function () { - assert.isNotNumber(4); - }, "expected 4 not to be a number"); - }); - - test('isBoolean', function () { - assert.isBoolean(true); - assert.isBoolean(false); - - err(function () { - assert.isBoolean('1'); - }, "expected \'1\' to be a boolean"); - }); - - test('isNotBoolean', function () { - assert.isNotBoolean('true'); - - err(function () { - assert.isNotBoolean(true); - }, "expected true not to be a boolean"); - - err(function () { - assert.isNotBoolean(false); - }, "expected false not to be a boolean"); - }); - - test('include', function () { - assert.include('foobar', 'bar'); - assert.include([ 1, 2, 3], 3); - - err(function () { - assert.include('foobar', 'baz'); - }, "expected \'foobar\' to contain \'baz\'"); - - err(function () { - assert.include(undefined, 'bar'); - }, "expected an array or string"); - }); - - test('notInclude', function () { - assert.notInclude('foobar', 'baz'); - assert.notInclude([ 1, 2, 3 ], 4); - - err(function () { - assert.notInclude('foobar', 'bar'); - }, "expected \'foobar\' to not contain \'bar\'"); - - err(function () { - assert.notInclude(undefined, 'bar'); - }, "expected an array or string"); - }); - - test('lengthOf', function () { - assert.lengthOf([1, 2, 3], 3); - assert.lengthOf('foobar', 6); - - err(function () { - assert.lengthOf('foobar', 5); - }, "expected 'foobar' to have a length of 5 but got 6"); - - err(function () { - assert.lengthOf(1, 5); - }, "expected 1 to have a property \'length\'"); - }); - - test('match', function () { - assert.match('foobar', /^foo/); - assert.notMatch('foobar', /^bar/); - - err(function () { - assert.match('foobar', /^bar/i); - }, "expected 'foobar' to match /^bar/i"); - - err(function () { - assert.notMatch('foobar', /^foo/i); - }, "expected 'foobar' not to match /^foo/i"); - }); - - test('property', function () { - var obj = { foo: { bar: 'baz' } }; - var simpleObj = { foo: 'bar' }; - assert.property(obj, 'foo'); - assert.deepProperty(obj, 'foo.bar'); - assert.notProperty(obj, 'baz'); - assert.notProperty(obj, 'foo.bar'); - assert.notDeepProperty(obj, 'foo.baz'); - assert.deepPropertyVal(obj, 'foo.bar', 'baz'); - assert.deepPropertyNotVal(obj, 'foo.bar', 'flow'); - - err(function () { - assert.property(obj, 'baz'); - }, "expected { foo: { bar: 'baz' } } to have a property 'baz'"); - - err(function () { - assert.deepProperty(obj, 'foo.baz'); - }, "expected { foo: { bar: 'baz' } } to have a deep property 'foo.baz'"); - - err(function () { - assert.notProperty(obj, 'foo'); - }, "expected { foo: { bar: 'baz' } } to not have property 'foo'"); - - err(function () { - assert.notDeepProperty(obj, 'foo.bar'); - }, "expected { foo: { bar: 'baz' } } to not have deep property 'foo.bar'"); - - err(function () { - assert.propertyVal(simpleObj, 'foo', 'ball'); - }, "expected { foo: 'bar' } to have a property 'foo' of 'ball', but got 'bar'"); - - err(function () { - assert.deepPropertyVal(obj, 'foo.bar', 'ball'); - }, "expected { foo: { bar: 'baz' } } to have a deep property 'foo.bar' of 'ball', but got 'baz'"); - - err(function () { - assert.propertyNotVal(simpleObj, 'foo', 'bar'); - }, "expected { foo: 'bar' } to not have a property 'foo' of 'bar'"); - - err(function () { - assert.deepPropertyNotVal(obj, 'foo.bar', 'baz'); - }, "expected { foo: { bar: 'baz' } } to not have a deep property 'foo.bar' of 'baz'"); - }); - - test('throws', function () { - assert.throws(function () { - throw new Error('foo'); - }); - assert.throws(function () { - throw new Error('bar'); - }, 'bar'); - assert.throws(function () { - throw new Error('bar'); - }, /bar/); - assert.throws(function () { - throw new Error('bar'); - }, Error); - assert.throws(function () { - throw new Error('bar'); - }, Error, 'bar'); - - err(function () { - assert.throws(function () { - throw new Error('foo') - }, TypeError); - }, "expected [Function] to throw 'TypeError' but [Error: foo] was thrown") - - err(function () { - assert.throws(function () { - throw new Error('foo') - }, 'bar'); - }, "expected [Function] to throw error including 'bar' but got 'foo'") - - err(function () { - assert.throws(function () { - throw new Error('foo') - }, Error, 'bar'); - }, "expected [Function] to throw error including 'bar' but got 'foo'") - - err(function () { - assert.throws(function () { - throw new Error('foo') - }, TypeError, 'bar'); - }, "expected [Function] to throw 'TypeError' but [Error: foo] was thrown") - - err(function () { - assert.throws(function () { - }); - }, "expected [Function] to throw an error"); - - err(function () { - assert.throws(function () { - throw new Error('') - }, 'bar'); - }, "expected [Function] to throw error including 'bar' but got ''"); - - err(function () { - assert.throws(function () { - throw new Error('') - }, /bar/); - }, "expected [Function] to throw error matching /bar/ but got ''"); - }); - - test('doesNotThrow', function () { - assert.doesNotThrow(function () { - }); - assert.doesNotThrow(function () { - }, 'foo'); - - err(function () { - assert.doesNotThrow(function () { - throw new Error('foo'); - }); - }, 'expected [Function] to not throw an error but [Error: foo] was thrown'); - }); - - test('ifError', function () { - assert.ifError(false); - assert.ifError(null); - assert.ifError(undefined); - - err(function () { - assert.ifError('foo'); - }, "expected \'foo\' to be falsy"); - }); - - test('operator', function () { - assert.operator(1, '<', 2); - assert.operator(2, '>', 1); - assert.operator(1, '==', 1); - assert.operator(1, '<=', 1); - assert.operator(1, '>=', 1); - assert.operator(1, '!=', 2); - assert.operator(1, '!==', 2); - - err(function () { - assert.operator(1, '=', 2); - }, 'Invalid operator "="'); - - err(function () { - assert.operator(2, '<', 1); - }, "expected 2 to be < 1"); - - err(function () { - assert.operator(1, '>', 2); - }, "expected 1 to be > 2"); - - err(function () { - assert.operator(1, '==', 2); - }, "expected 1 to be == 2"); - - err(function () { - assert.operator(2, '<=', 1); - }, "expected 2 to be <= 1"); - - err(function () { - assert.operator(1, '>=', 2); - }, "expected 1 to be >= 2"); - - err(function () { - assert.operator(1, '!=', 1); - }, "expected 1 to be != 1"); - - err(function () { - assert.operator(1, '!==', '1'); - }, "expected 1 to be !== \'1\'"); - }); - - test('closeTo', function () { - assert.closeTo(1.5, 1.0, 0.5); - assert.closeTo(10, 20, 20); - assert.closeTo(-10, 20, 30); - - err(function () { - assert.closeTo(2, 1.0, 0.5); - }, "expected 2 to be close to 1 +/- 0.5"); - - err(function () { - assert.closeTo(-10, 20, 29); - }, "expected -10 to be close to 20 +/- 29"); - }); - - test('members', function () { - assert.includeMembers([1, 2, 3], [2, 3]); - assert.includeMembers([1, 2, 3], []); - assert.includeMembers([1, 2, 3], [3]); - - err(function () { - assert.includeMembers([5, 6], [7, 8]); - }, 'expected [ 5, 6 ] to be a superset of [ 7, 8 ]'); - - err(function () { - assert.includeMembers([5, 6], [5, 6, 0]); - }, 'expected [ 5, 6 ] to be a superset of [ 5, 6, 0 ]'); - }); - - test('memberEquals', function () { - assert.sameMembers([], []); - assert.sameMembers([1, 2, 3], [3, 2, 1]); - assert.sameMembers([4, 2], [4, 2]); - - err(function () { - assert.sameMembers([], [1, 2]); - }, 'expected [] to have the same members as [ 1, 2 ]'); - - err(function () { - assert.sameMembers([1, 54], [6, 1, 54]); - }, 'expected [ 1, 54 ] to have the same members as [ 6, 1, 54 ]'); - }); - -}); diff --git a/chai/chai-assert.d.ts b/chai/chai-assert.d.ts deleted file mode 100644 index 30ae2deb7..000000000 --- a/chai/chai-assert.d.ts +++ /dev/null @@ -1,131 +0,0 @@ -// Type definitions for chai v1.9.0 assert style -// Project: http://chaijs.com/ -// Definitions by: Bart van der Schoor -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module chai { - export class AssertionError { - constructor(message: string, _props?: any, ssf?: Function); - name: string; - message: string; - showDiff: boolean; - stack: string; - } - export function use(plugin: any): void; - - export var Assertion: ChaiAssertion; - export var assert: Assert; - export var config: ChaiConfig; - - export interface ChaiConfig { - includeStack: boolean; - } - - export interface ChaiAssertion { - // what? - } - - export interface Assert { - (express: any, msg?: string):void; - - fail(actual?: any, expected?: any, msg?: string, operator?: string):void; - - ok(val: any, msg?: string):void; - notOk(val: any, msg?: string):void; - - equal(act: any, exp: any, msg?: string):void; - notEqual(act: any, exp: any, msg?: string):void; - - strictEqual(act: any, exp: any, msg?: string):void; - notStrictEqual(act: any, exp: any, msg?: string):void; - - deepEqual(act: any, exp: any, msg?: string):void; - notDeepEqual(act: any, exp: any, msg?: string):void; - - isTrue(val: any, msg?: string):void; - isFalse(val: any, msg?: string):void; - - isNull(val: any, msg?: string):void; - isNotNull(val: any, msg?: string):void; - - isUndefined(val: any, msg?: string):void; - isDefined(val: any, msg?: string):void; - - isFunction(val: any, msg?: string):void; - isNotFunction(val: any, msg?: string):void; - - isObject(val: any, msg?: string):void; - isNotObject(val: any, msg?: string):void; - - isArray(val: any, msg?: string):void; - isNotArray(val: any, msg?: string):void; - - isString(val: any, msg?: string):void; - isNotString(val: any, msg?: string):void; - - isNumber(val: any, msg?: string):void; - isNotNumber(val: any, msg?: string):void; - - isBoolean(val: any, msg?: string):void; - isNotBoolean(val: any, msg?: string):void; - - typeOf(val: any, type: string, msg?: string):void; - notTypeOf(val: any, type: string, msg?: string):void; - - instanceOf(val: any, type: Function, msg?: string):void; - notInstanceOf(val: any, type: Function, msg?: string):void; - - include(exp: string, inc: any, msg?: string):void; - include(exp: any[], inc: any, msg?: string):void; - - notInclude(exp: string, inc: any, msg?: string):void; - notInclude(exp: any[], inc: any, msg?: string):void; - - match(exp: any, re: RegExp, msg?: string):void; - notMatch(exp: any, re: RegExp, msg?: string):void; - - property(obj: Object, prop: string, msg?: string):void; - notProperty(obj: Object, prop: string, msg?: string):void; - deepProperty(obj: Object, prop: string, msg?: string):void; - notDeepProperty(obj: Object, prop: string, msg?: string):void; - - propertyVal(obj: Object, prop: string, val: any, msg?: string):void; - propertyNotVal(obj: Object, prop: string, val: any, msg?: string):void; - - deepPropertyVal(obj: Object, prop: string, val: any, msg?: string):void; - deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string):void; - - lengthOf(exp: any, len: number, msg?: string):void; - //alias frenzy - throw(fn: Function, msg?: string):void; - throw(fn: Function, regExp: RegExp):void; - throw(fn: Function, errType: Function, msg?: string):void; - throw(fn: Function, errType: Function, regExp: RegExp):void; - - throws(fn: Function, msg?: string):void; - throws(fn: Function, regExp: RegExp):void; - throws(fn: Function, errType: Function, msg?: string):void; - throws(fn: Function, errType: Function, regExp: RegExp):void; - - Throw(fn: Function, msg?: string):void; - Throw(fn: Function, regExp: RegExp):void; - Throw(fn: Function, errType: Function, msg?: string):void; - Throw(fn: Function, errType: Function, regExp: RegExp):void; - - doesNotThrow(fn: Function, msg?: string):void; - doesNotThrow(fn: Function, regExp: RegExp):void; - doesNotThrow(fn: Function, errType: Function, msg?: string):void; - doesNotThrow(fn: Function, errType: Function, regExp: RegExp):void; - - operator(val: any, operator: string, val2: any, msg?: string):void; - closeTo(act: number, exp: number, delta: number, msg?: string):void; - - sameMembers(set1: any[], set2: any[], msg?: string):void; - includeMembers(set1: any[], set2: any[], msg?: string):void; - - ifError(val: any, msg?: string):void; - } -} - -//browser global -declare var assert:chai.Assert; diff --git a/chai/chai-tests.ts b/chai/chai-tests.ts index b559c515d..398ebd069 100644 --- a/chai/chai-tests.ts +++ b/chai/chai-tests.ts @@ -1,6 +1,7 @@ /// var expect = chai.expect; +var assert = chai.assert; declare var err: Function; function chaiVersion() { @@ -767,3 +768,623 @@ function members() { expect([5, 4]).not.members([6, 3]); expect([5, 4]).not.members([5, 4, 2]); } + +//tdd +declare function suite(description: string, action: Function):void; +declare function test(description: string, action: Function):void; +declare function err(action: any, msg?: string):void; +interface FieldObj { + field: any; +} +class Foo { + constructor() { + + } +} + +class CrashyObject { + inspect (): void { + throw new Error("Arg's inspect() called even though the test passed"); + } +} + +suite('assert', function () { + + test('assert', function () { + var foo = 'bar'; + assert(foo == 'bar', "expected foo to equal `bar`"); + + err(function () { + assert(foo == 'baz', "expected foo to equal `bar`"); + }, "expected foo to equal `bar`"); + }); + + test('isTrue', function () { + assert.isTrue(true); + + err(function () { + assert.isTrue(false); + }, "expected false to be true"); + + err(function () { + assert.isTrue(1); + }, "expected 1 to be true"); + + err(function () { + assert.isTrue('test'); + }, "expected 'test' to be true"); + }); + + test('ok', function () { + assert.ok(true); + assert.ok(1); + assert.ok('test'); + + err(function () { + assert.ok(false); + }, "expected false to be truthy"); + + err(function () { + assert.ok(0); + }, "expected 0 to be truthy"); + + err(function () { + assert.ok(''); + }, "expected '' to be truthy"); + }); + + test('isFalse', function () { + assert.isFalse(false); + + err(function () { + assert.isFalse(true); + }, "expected true to be false"); + + err(function () { + assert.isFalse(0); + }, "expected 0 to be false"); + }); + + test('equal', function () { + var foo: any; + assert.equal(foo, undefined); + }); + + test('typeof / notTypeOf', function () { + assert.typeOf('test', 'string'); + assert.typeOf(true, 'boolean'); + assert.typeOf(5, 'number'); + + err(function () { + assert.typeOf(5, 'string'); + }, "expected 5 to be a string"); + + }); + + test('notTypeOf', function () { + assert.notTypeOf('test', 'number'); + + err(function () { + assert.notTypeOf(5, 'number'); + }, "expected 5 not to be a number"); + }); + + test('instanceOf', function () { + assert.instanceOf(new Foo(), Foo); + + err(function () { + assert.instanceOf(5, Foo); + }, "expected 5 to be an instance of Foo"); + assert.instanceOf(new CrashyObject(), CrashyObject); + }); + + test('notInstanceOf', function () { + assert.notInstanceOf(new Foo(), String); + + err(function () { + assert.notInstanceOf(new Foo(), Foo); + }, "expected {} to not be an instance of Foo"); + }); + + test('isObject', function () { + assert.isObject({}); + assert.isObject(new Foo()); + + err(function () { + assert.isObject(true); + }, "expected true to be an object"); + + err(function () { + assert.isObject(Foo); + }, "expected [Function: Foo] to be an object"); + + err(function () { + assert.isObject('foo'); + }, "expected 'foo' to be an object"); + }); + + test('isNotObject', function () { + assert.isNotObject(5); + + err(function () { + assert.isNotObject({}); + }, "expected {} not to be an object"); + }); + + test('notEqual', function () { + assert.notEqual(3, 4); + + err(function () { + assert.notEqual(5, 5); + }, "expected 5 to not equal 5"); + }); + + test('strictEqual', function () { + assert.strictEqual('foo', 'foo'); + + err(function () { + assert.strictEqual('5', 5); + }, "expected \'5\' to equal 5"); + }); + + test('notStrictEqual', function () { + assert.notStrictEqual(5, '5'); + + err(function () { + assert.notStrictEqual(5, 5); + }, "expected 5 to not equal 5"); + }); + + test('deepEqual', function () { + assert.deepEqual({tea: 'chai'}, {tea: 'chai'}); + + err(function () { + assert.deepEqual({tea: 'chai'}, {tea: 'black'}); + }, "expected { tea: \'chai\' } to deeply equal { tea: \'black\' }"); + + var obja = Object.create({ tea: 'chai' }) + , objb = Object.create({ tea: 'chai' }); + + assert.deepEqual(obja, objb); + + var obj1 = Object.create({tea: 'chai'}) + , obj2 = Object.create({tea: 'black'}); + + err(function () { + assert.deepEqual(obj1, obj2); + }, "expected { tea: \'chai\' } to deeply equal { tea: \'black\' }"); + }); + + test('deepEqual (ordering)', function () { + var a = { a: 'b', c: 'd' } + , b = { c: 'd', a: 'b' }; + assert.deepEqual(a, b); + }); + + test('deepEqual (circular)', function () { + var circularObject:any = {} + , secondCircularObject:any = {}; + circularObject.field = circularObject; + secondCircularObject.field = secondCircularObject; + + assert.deepEqual(circularObject, secondCircularObject); + + err(function () { + secondCircularObject.field2 = secondCircularObject; + assert.deepEqual(circularObject, secondCircularObject); + }, "expected { field: [Circular] } to deeply equal { Object (field, field2) }"); + }); + + test('notDeepEqual', function () { + assert.notDeepEqual({tea: 'jasmine'}, {tea: 'chai'}); + err(function () { + assert.notDeepEqual({tea: 'chai'}, {tea: 'chai'}); + }, "expected { tea: \'chai\' } to not deeply equal { tea: \'chai\' }"); + }); + + test('notDeepEqual (circular)', function () { + var circularObject:any = {} + , secondCircularObject:any = { tea: 'jasmine' }; + circularObject.field = circularObject; + secondCircularObject.field = secondCircularObject; + + assert.notDeepEqual(circularObject, secondCircularObject); + + err(function () { + delete secondCircularObject.tea; + assert.notDeepEqual(circularObject, secondCircularObject); + }, "expected { field: [Circular] } to not deeply equal { field: [Circular] }"); + }); + + test('isNull', function () { + assert.isNull(null); + + err(function () { + assert.isNull(undefined); + }, "expected undefined to equal null"); + }); + + test('isNotNull', function () { + assert.isNotNull(undefined); + + err(function () { + assert.isNotNull(null); + }, "expected null to not equal null"); + }); + + test('isUndefined', function () { + assert.isUndefined(undefined); + + err(function () { + assert.isUndefined(null); + }, "expected null to equal undefined"); + }); + + test('isDefined', function () { + assert.isDefined(null); + + err(function () { + assert.isDefined(undefined); + }, "expected undefined to not equal undefined"); + }); + + test('isFunction', function () { + var func = function () { + }; + assert.isFunction(func); + + err(function () { + assert.isFunction({}); + }, "expected {} to be a function"); + }); + + test('isNotFunction', function () { + assert.isNotFunction(5); + + err(function () { + assert.isNotFunction(function () { + }); + }, "expected [Function] not to be a function"); + }); + + test('isArray', function () { + assert.isArray([]); + assert.isArray(new Array()); + + err(function () { + assert.isArray({}); + }, "expected {} to be an array"); + }); + + test('isNotArray', function () { + assert.isNotArray(3); + + err(function () { + assert.isNotArray([]); + }, "expected [] not to be an array"); + + err(function () { + assert.isNotArray(new Array()); + }, "expected [] not to be an array"); + }); + + test('isString', function () { + assert.isString('Foo'); + assert.isString(new String('foo')); + + err(function () { + assert.isString(1); + }, "expected 1 to be a string"); + }); + + test('isNotString', function () { + assert.isNotString(3); + assert.isNotString([ 'hello' ]); + + err(function () { + assert.isNotString('hello'); + }, "expected 'hello' not to be a string"); + }); + + test('isNumber', function () { + assert.isNumber(1); + assert.isNumber(Number('3')); + + err(function () { + assert.isNumber('1'); + }, "expected \'1\' to be a number"); + }); + + test('isNotNumber', function () { + assert.isNotNumber('hello'); + assert.isNotNumber([ 5 ]); + + err(function () { + assert.isNotNumber(4); + }, "expected 4 not to be a number"); + }); + + test('isBoolean', function () { + assert.isBoolean(true); + assert.isBoolean(false); + + err(function () { + assert.isBoolean('1'); + }, "expected \'1\' to be a boolean"); + }); + + test('isNotBoolean', function () { + assert.isNotBoolean('true'); + + err(function () { + assert.isNotBoolean(true); + }, "expected true not to be a boolean"); + + err(function () { + assert.isNotBoolean(false); + }, "expected false not to be a boolean"); + }); + + test('include', function () { + assert.include('foobar', 'bar'); + assert.include([ 1, 2, 3], 3); + + err(function () { + assert.include('foobar', 'baz'); + }, "expected \'foobar\' to contain \'baz\'"); + + err(function () { + assert.include(undefined, 'bar'); + }, "expected an array or string"); + }); + + test('notInclude', function () { + assert.notInclude('foobar', 'baz'); + assert.notInclude([ 1, 2, 3 ], 4); + + err(function () { + assert.notInclude('foobar', 'bar'); + }, "expected \'foobar\' to not contain \'bar\'"); + + err(function () { + assert.notInclude(undefined, 'bar'); + }, "expected an array or string"); + }); + + test('lengthOf', function () { + assert.lengthOf([1, 2, 3], 3); + assert.lengthOf('foobar', 6); + + err(function () { + assert.lengthOf('foobar', 5); + }, "expected 'foobar' to have a length of 5 but got 6"); + + err(function () { + assert.lengthOf(1, 5); + }, "expected 1 to have a property \'length\'"); + }); + + test('match', function () { + assert.match('foobar', /^foo/); + assert.notMatch('foobar', /^bar/); + + err(function () { + assert.match('foobar', /^bar/i); + }, "expected 'foobar' to match /^bar/i"); + + err(function () { + assert.notMatch('foobar', /^foo/i); + }, "expected 'foobar' not to match /^foo/i"); + }); + + test('property', function () { + var obj = { foo: { bar: 'baz' } }; + var simpleObj = { foo: 'bar' }; + assert.property(obj, 'foo'); + assert.deepProperty(obj, 'foo.bar'); + assert.notProperty(obj, 'baz'); + assert.notProperty(obj, 'foo.bar'); + assert.notDeepProperty(obj, 'foo.baz'); + assert.deepPropertyVal(obj, 'foo.bar', 'baz'); + assert.deepPropertyNotVal(obj, 'foo.bar', 'flow'); + + err(function () { + assert.property(obj, 'baz'); + }, "expected { foo: { bar: 'baz' } } to have a property 'baz'"); + + err(function () { + assert.deepProperty(obj, 'foo.baz'); + }, "expected { foo: { bar: 'baz' } } to have a deep property 'foo.baz'"); + + err(function () { + assert.notProperty(obj, 'foo'); + }, "expected { foo: { bar: 'baz' } } to not have property 'foo'"); + + err(function () { + assert.notDeepProperty(obj, 'foo.bar'); + }, "expected { foo: { bar: 'baz' } } to not have deep property 'foo.bar'"); + + err(function () { + assert.propertyVal(simpleObj, 'foo', 'ball'); + }, "expected { foo: 'bar' } to have a property 'foo' of 'ball', but got 'bar'"); + + err(function () { + assert.deepPropertyVal(obj, 'foo.bar', 'ball'); + }, "expected { foo: { bar: 'baz' } } to have a deep property 'foo.bar' of 'ball', but got 'baz'"); + + err(function () { + assert.propertyNotVal(simpleObj, 'foo', 'bar'); + }, "expected { foo: 'bar' } to not have a property 'foo' of 'bar'"); + + err(function () { + assert.deepPropertyNotVal(obj, 'foo.bar', 'baz'); + }, "expected { foo: { bar: 'baz' } } to not have a deep property 'foo.bar' of 'baz'"); + }); + + test('throws', function () { + assert.throws(function () { + throw new Error('foo'); + }); + assert.throws(function () { + throw new Error('bar'); + }, 'bar'); + assert.throws(function () { + throw new Error('bar'); + }, /bar/); + assert.throws(function () { + throw new Error('bar'); + }, Error); + assert.throws(function () { + throw new Error('bar'); + }, Error, 'bar'); + + err(function () { + assert.throws(function () { + throw new Error('foo') + }, TypeError); + }, "expected [Function] to throw 'TypeError' but [Error: foo] was thrown") + + err(function () { + assert.throws(function () { + throw new Error('foo') + }, 'bar'); + }, "expected [Function] to throw error including 'bar' but got 'foo'") + + err(function () { + assert.throws(function () { + throw new Error('foo') + }, Error, 'bar'); + }, "expected [Function] to throw error including 'bar' but got 'foo'") + + err(function () { + assert.throws(function () { + throw new Error('foo') + }, TypeError, 'bar'); + }, "expected [Function] to throw 'TypeError' but [Error: foo] was thrown") + + err(function () { + assert.throws(function () { + }); + }, "expected [Function] to throw an error"); + + err(function () { + assert.throws(function () { + throw new Error('') + }, 'bar'); + }, "expected [Function] to throw error including 'bar' but got ''"); + + err(function () { + assert.throws(function () { + throw new Error('') + }, /bar/); + }, "expected [Function] to throw error matching /bar/ but got ''"); + }); + + test('doesNotThrow', function () { + assert.doesNotThrow(function () { + }); + assert.doesNotThrow(function () { + }, 'foo'); + + err(function () { + assert.doesNotThrow(function () { + throw new Error('foo'); + }); + }, 'expected [Function] to not throw an error but [Error: foo] was thrown'); + }); + + test('ifError', function () { + assert.ifError(false); + assert.ifError(null); + assert.ifError(undefined); + + err(function () { + assert.ifError('foo'); + }, "expected \'foo\' to be falsy"); + }); + + test('operator', function () { + assert.operator(1, '<', 2); + assert.operator(2, '>', 1); + assert.operator(1, '==', 1); + assert.operator(1, '<=', 1); + assert.operator(1, '>=', 1); + assert.operator(1, '!=', 2); + assert.operator(1, '!==', 2); + + err(function () { + assert.operator(1, '=', 2); + }, 'Invalid operator "="'); + + err(function () { + assert.operator(2, '<', 1); + }, "expected 2 to be < 1"); + + err(function () { + assert.operator(1, '>', 2); + }, "expected 1 to be > 2"); + + err(function () { + assert.operator(1, '==', 2); + }, "expected 1 to be == 2"); + + err(function () { + assert.operator(2, '<=', 1); + }, "expected 2 to be <= 1"); + + err(function () { + assert.operator(1, '>=', 2); + }, "expected 1 to be >= 2"); + + err(function () { + assert.operator(1, '!=', 1); + }, "expected 1 to be != 1"); + + err(function () { + assert.operator(1, '!==', '1'); + }, "expected 1 to be !== \'1\'"); + }); + + test('closeTo', function () { + assert.closeTo(1.5, 1.0, 0.5); + assert.closeTo(10, 20, 20); + assert.closeTo(-10, 20, 30); + + err(function () { + assert.closeTo(2, 1.0, 0.5); + }, "expected 2 to be close to 1 +/- 0.5"); + + err(function () { + assert.closeTo(-10, 20, 29); + }, "expected -10 to be close to 20 +/- 29"); + }); + + test('members', function () { + assert.includeMembers([1, 2, 3], [2, 3]); + assert.includeMembers([1, 2, 3], []); + assert.includeMembers([1, 2, 3], [3]); + + err(function () { + assert.includeMembers([5, 6], [7, 8]); + }, 'expected [ 5, 6 ] to be a superset of [ 7, 8 ]'); + + err(function () { + assert.includeMembers([5, 6], [5, 6, 0]); + }, 'expected [ 5, 6 ] to be a superset of [ 5, 6, 0 ]'); + }); + + test('memberEquals', function () { + assert.sameMembers([], []); + assert.sameMembers([1, 2, 3], [3, 2, 1]); + assert.sameMembers([4, 2], [4, 2]); + + err(function () { + assert.sameMembers([], [1, 2]); + }, 'expected [] to have the same members as [ 1, 2 ]'); + + err(function () { + assert.sameMembers([1, 54], [6, 1, 54]); + }, 'expected [ 1, 54 ] to have the same members as [ 6, 1, 54 ]'); + }); + +}); diff --git a/chai/chai.d.ts b/chai/chai.d.ts index 058d55196..fc767c639 100644 --- a/chai/chai.d.ts +++ b/chai/chai.d.ts @@ -1,11 +1,25 @@ // Type definitions for chai 1.7.2 // Project: http://chaijs.com/ -// Definitions by: Jed Hunsaker +// Definitions by: Jed Hunsaker , Bart van der Schoor // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module chai { + export class AssertionError { + constructor(message: string, _props?: any, ssf?: Function); + name: string; + message: string; + showDiff: boolean; + stack: string; + } function expect(target: any, message?: string): Expect; + + export var assert: Assert; + export var config: Config; + + export interface Config { + includeStack: boolean; + } // Provides a way to extend the internals of Chai function use(fn: (chai: any, utils: any) => void): any; @@ -161,6 +175,107 @@ declare module chai { (constructor: Function, expected?: string, message?: string): Expect; (constructor: Function, expected?: RegExp, message?: string): Expect; } + + export interface Assert { + (express: any, msg?: string):void; + + fail(actual?: any, expected?: any, msg?: string, operator?: string):void; + + ok(val: any, msg?: string):void; + notOk(val: any, msg?: string):void; + + equal(act: any, exp: any, msg?: string):void; + notEqual(act: any, exp: any, msg?: string):void; + + strictEqual(act: any, exp: any, msg?: string):void; + notStrictEqual(act: any, exp: any, msg?: string):void; + + deepEqual(act: any, exp: any, msg?: string):void; + notDeepEqual(act: any, exp: any, msg?: string):void; + + isTrue(val: any, msg?: string):void; + isFalse(val: any, msg?: string):void; + + isNull(val: any, msg?: string):void; + isNotNull(val: any, msg?: string):void; + + isUndefined(val: any, msg?: string):void; + isDefined(val: any, msg?: string):void; + + isFunction(val: any, msg?: string):void; + isNotFunction(val: any, msg?: string):void; + + isObject(val: any, msg?: string):void; + isNotObject(val: any, msg?: string):void; + + isArray(val: any, msg?: string):void; + isNotArray(val: any, msg?: string):void; + + isString(val: any, msg?: string):void; + isNotString(val: any, msg?: string):void; + + isNumber(val: any, msg?: string):void; + isNotNumber(val: any, msg?: string):void; + + isBoolean(val: any, msg?: string):void; + isNotBoolean(val: any, msg?: string):void; + + typeOf(val: any, type: string, msg?: string):void; + notTypeOf(val: any, type: string, msg?: string):void; + + instanceOf(val: any, type: Function, msg?: string):void; + notInstanceOf(val: any, type: Function, msg?: string):void; + + include(exp: string, inc: any, msg?: string):void; + include(exp: any[], inc: any, msg?: string):void; + + notInclude(exp: string, inc: any, msg?: string):void; + notInclude(exp: any[], inc: any, msg?: string):void; + + match(exp: any, re: RegExp, msg?: string):void; + notMatch(exp: any, re: RegExp, msg?: string):void; + + property(obj: Object, prop: string, msg?: string):void; + notProperty(obj: Object, prop: string, msg?: string):void; + deepProperty(obj: Object, prop: string, msg?: string):void; + notDeepProperty(obj: Object, prop: string, msg?: string):void; + + propertyVal(obj: Object, prop: string, val: any, msg?: string):void; + propertyNotVal(obj: Object, prop: string, val: any, msg?: string):void; + + deepPropertyVal(obj: Object, prop: string, val: any, msg?: string):void; + deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string):void; + + lengthOf(exp: any, len: number, msg?: string):void; + //alias frenzy + throw(fn: Function, msg?: string):void; + throw(fn: Function, regExp: RegExp):void; + throw(fn: Function, errType: Function, msg?: string):void; + throw(fn: Function, errType: Function, regExp: RegExp):void; + + throws(fn: Function, msg?: string):void; + throws(fn: Function, regExp: RegExp):void; + throws(fn: Function, errType: Function, msg?: string):void; + throws(fn: Function, errType: Function, regExp: RegExp):void; + + Throw(fn: Function, msg?: string):void; + Throw(fn: Function, regExp: RegExp):void; + Throw(fn: Function, errType: Function, msg?: string):void; + Throw(fn: Function, errType: Function, regExp: RegExp):void; + + doesNotThrow(fn: Function, msg?: string):void; + doesNotThrow(fn: Function, regExp: RegExp):void; + doesNotThrow(fn: Function, errType: Function, msg?: string):void; + doesNotThrow(fn: Function, errType: Function, regExp: RegExp):void; + + operator(val: any, operator: string, val2: any, msg?: string):void; + closeTo(act: number, exp: number, delta: number, msg?: string):void; + + sameMembers(set1: any[], set2: any[], msg?: string):void; + includeMembers(set1: any[], set2: any[], msg?: string):void; + + ifError(val: any, msg?: string):void; + } } declare module "chai" { From d1f9d3fef52d491cbdfd0ab11a564672a5dff4a3 Mon Sep 17 00:00:00 2001 From: Bart van der Schoor Date: Sat, 19 Jul 2014 05:35:05 +0200 Subject: [PATCH 143/324] fixed chai test --- chai/chai-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chai/chai-tests.ts b/chai/chai-tests.ts index 398ebd069..98d75e8ae 100644 --- a/chai/chai-tests.ts +++ b/chai/chai-tests.ts @@ -772,7 +772,7 @@ function members() { //tdd declare function suite(description: string, action: Function):void; declare function test(description: string, action: Function):void; -declare function err(action: any, msg?: string):void; + interface FieldObj { field: any; } From e827d60b1a4f0278d5bb0022e7e5d416c642a8ae Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Sat, 19 Jul 2014 11:44:50 +0200 Subject: [PATCH 144/324] jasmine: add missing variable DEFAULT_TIMEOUT_INTERVAL --- jasmine/jasmine.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/jasmine/jasmine.d.ts b/jasmine/jasmine.d.ts index f64a59d39..34e30cdd1 100644 --- a/jasmine/jasmine.d.ts +++ b/jasmine/jasmine.d.ts @@ -429,4 +429,5 @@ declare module jasmine { export var HtmlReporter: HtmlReporter; export var HtmlSpecFilter: HtmlSpecFilter; + export var DEFAULT_TIMEOUT_INTERVAL: number; } From 3c4d380a0fb61defc9f11ac57eb44881f5fba58a Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Sat, 19 Jul 2014 11:48:42 +0200 Subject: [PATCH 145/324] add example to jasmine-tests.ts --- jasmine/jasmine-tests.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/jasmine/jasmine-tests.ts b/jasmine/jasmine-tests.ts index 3ce5dbc5f..8a4a00e22 100644 --- a/jasmine/jasmine-tests.ts +++ b/jasmine/jasmine-tests.ts @@ -698,3 +698,5 @@ describe("Asynchronous specs", function () { }; })(); + +jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000; From 730cb88fb0ac988945ff4376506678eb7c0d2fb9 Mon Sep 17 00:00:00 2001 From: Sebastian Lenz Date: Sun, 20 Jul 2014 12:13:28 +0200 Subject: [PATCH 146/324] Added lunr.js definitions --- lunr/lunr-tests.ts | 44 +++ lunr/lunr.d.ts | 839 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 883 insertions(+) create mode 100644 lunr/lunr-tests.ts create mode 100644 lunr/lunr.d.ts diff --git a/lunr/lunr-tests.ts b/lunr/lunr-tests.ts new file mode 100644 index 000000000..949a53e87 --- /dev/null +++ b/lunr/lunr-tests.ts @@ -0,0 +1,44 @@ +/// + +/** + * Basic test, from http://lunrjs.com/ + */ +function basic_test() { + var index = lunr(function () { + this.field('title', {boost: 10}); + this.field('body'); + this.ref('id'); + }); + + index.add({ + id: 1, + title: 'Foo', + body: 'Foo foo foo!' + }); + + index.add({ + id: 2, + title: 'Bar', + body: 'Bar bar bar!' + }); + + index.search('foo'); +} + + +/** + * Pipeline test, from http://lunrjs.com/ + */ +function pipeline_test() { + var index = lunr(function () { + this.pipeline.add(function (token:string, tokenIndex:number, tokens:string[]):string { + // text processing in here + return token; + }); + + this.pipeline.after(lunr.stopWordFilter, function (token:string, tokenIndex:number, tokens:string[]):string { + // text processing in here + return token; + }); + }) +} \ No newline at end of file diff --git a/lunr/lunr.d.ts b/lunr/lunr.d.ts new file mode 100644 index 000000000..709e5864d --- /dev/null +++ b/lunr/lunr.d.ts @@ -0,0 +1,839 @@ +// Type definitions for lunr.js 0.5.4 +// Project: https://github.com/olivernn/lunr.js +// Definitions by: Sebastian Lenz +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/** + * lunr - http://lunrjs.com - A bit like Solr, but much smaller and not as bright - 0.5.4 + * Copyright (C) 2014 Oliver Nightingale + * MIT Licensed + * @license + */ +declare module lunr +{ + var version:string; + + + /** + * A function for splitting a string into tokens ready to be inserted into the search index. + * + * @param token The token to pass through the filter + */ + function tokenizer(token:string):string; + + + /** + * lunr.stemmer is an english language stemmer, this is a JavaScript implementation of + * the PorterStemmer taken from http://tartaurs.org/~martin + * + * @param token The string to stem + */ + function stemmer(token:string):string; + + + /** + * lunr.stopWordFilter is an English language stop word list filter, any words contained + * in the list will not be passed through the filter. + * + * This is intended to be used in the Pipeline. If the token does not pass the filter then + * undefined will be returned. + * + * @param token The token to pass through the filter + */ + function stopWordFilter(token:string):string; + + module stopWordFilter { + var stopWords:SortedSet; + } + + + /** + * lunr.trimmer is a pipeline function for trimming non word characters from the beginning + * and end of tokens before they enter the index. + * + * This implementation may not work correctly for non latin characters and should either + * be removed or adapted for use with languages with non-latin characters. + * @param token The token to pass through the filter + */ + function trimmer(token:string):string; + + + /** + * lunr.EventEmitter is an event emitter for lunr. It manages adding and removing event handlers + * and triggering events and their handlers. + */ + class EventEmitter + { + /** + * Can bind a single function to many different events in one call. + * + * @param eventName The name(s) of events to bind this function to. + * @param handler The function to call when an event is fired. Binds a handler + * function to a specific event(s). + */ + addListener(eventName:string, handler:Function):void; + addListener(eventName:string, eventName2:string, handler:Function):void; + addListener(eventName:string, eventName2:string, eventName3:string, handler:Function):void; + addListener(eventName:string, eventName2:string, eventName3:string, eventName4:string, handler:Function):void; + addListener(eventName:string, eventName2:string, eventName3:string, eventName4:string, eventName5:string, handler:Function):void; + + + /** + * Removes a handler function from a specific event. + * + * @param eventName The name of the event to remove this function from. + * @param handler The function to remove from an event. + */ + removeListener(eventName:string, handler:Function):void; + + + /** + * Calls all functions bound to the given event. + * + * Additional data can be passed to the event handler as arguments to emit after the event name. + * + * @param eventName The name of the event to emit. + * @param args + */ + emit(eventName:string, ...args:any[]):void; + + + /** + * Checks whether a handler has ever been stored against an event. + * + * @param eventName The name of the event to check. + */ + hasHandler(eventName:string):boolean; + } + + + interface IPipelineFunction { + (token:string):string; + (token:string, tokenIndex:number):string; + (token:string, tokenIndex:number, tokens:string[]):string; + } + + + /** + * lunr.Pipelines maintain an ordered list of functions to be applied to all tokens in documents + * entering the search index and queries being ran against the index. + * + * An instance of lunr.Index created with the lunr shortcut will contain a pipeline with a stop + * word filter and an English language stemmer. Extra functions can be added before or after either + * of these functions or these default functions can be removed. + * + * When run the pipeline will call each function in turn, passing a token, the index of that token + * in the original list of all tokens and finally a list of all the original tokens. + * + * The output of functions in the pipeline will be passed to the next function in the pipeline. + * To exclude a token from entering the index the function should return undefined, the rest of + * the pipeline will not be called with this token. + * + * For serialisation of pipelines to work, all functions used in an instance of a pipeline should + * be registered with lunr.Pipeline. Registered functions can then be loaded. If trying to load a + * serialised pipeline that uses functions that are not registered an error will be thrown. + * + * If not planning on serialising the pipeline then registering pipeline functions is not necessary. + */ + class Pipeline + { + registeredFunctions:{[label:string]:Function}; + + + /** + * Register a function with the pipeline. + * + * Functions that are used in the pipeline should be registered if the pipeline needs to be + * serialised, or a serialised pipeline needs to be loaded. + * + * Registering a function does not add it to a pipeline, functions must still be added to instances + * of the pipeline for them to be used when running a pipeline. + * + * @param fn The function to check for. + * @param label The label to register this function with + */ + registerFunction(fn:IPipelineFunction, label:string):void; + + + /** + * Warns if the function is not registered as a Pipeline function. + * + * @param fn The function to check for. + */ + warnIfFunctionNotRegistered(fn:IPipelineFunction):void; + + + /** + * Adds new functions to the end of the pipeline. + * + * Logs a warning if the function has not been registered. + * + * @param functions Any number of functions to add to the pipeline. + */ + add(...functions:IPipelineFunction[]):void; + + + /** + * Adds a single function after a function that already exists in the pipeline. + * + * Logs a warning if the function has not been registered. + * + * @param existingFn A function that already exists in the pipeline. + * @param newFn The new function to add to the pipeline. + */ + after(existingFn:IPipelineFunction, newFn:IPipelineFunction):void; + + + /** + * Adds a single function before a function that already exists in the pipeline. + * + * Logs a warning if the function has not been registered. + * + * @param existingFn A function that already exists in the pipeline. + * @param newFn The new function to add to the pipeline. + */ + before(existingFn:IPipelineFunction, newFn:IPipelineFunction):void; + + + /** + * Removes a function from the pipeline. + * + * @param fn The function to remove from the pipeline. + */ + remove(fn:IPipelineFunction):void; + + + /** + * Runs the current list of functions that make up the pipeline against + * the passed tokens. + * + * @param tokens The tokens to run through the pipeline. + */ + run(tokens:string[]):string[]; + + + /** + * Resets the pipeline by removing any existing processors. + */ + reset():void; + + + /** + * Returns a representation of the pipeline ready for serialisation. + */ + toJSON():any; + + + /** + * Loads a previously serialised pipeline. + * + * All functions to be loaded must already be registered with lunr.Pipeline. If any function from + * the serialised data has not been registered then an error will be thrown. + * + * @param serialised The serialised pipeline to load. + */ + static load(serialised:any):Pipeline; + } + + + /** + * lunr.Vectors implement vector related operations for a series of elements. + */ + class Vector + { + list:Node; + + + /** + * Calculates the magnitude of this vector. + */ + magnitude():number; + + + /** + * Calculates the dot product of this vector and another vector. + * @param otherVector The vector to compute the dot product with. + */ + dot(otherVector:Vector):number; + + + /** + * Calculates the cosine similarity between this vector and another vector. + * + * @param otherVector The other vector to calculate the + */ + similarity(otherVector:Vector):number; + } + + + /** + * lunr.Vector.Node is a simple struct for each node in a lunr.Vector. + */ + class Node + { + /** + * The index of the node in the vector. + */ + idx:number; + + /** + * The data at this node in the vector. + */ + val:number; + + /** + * The node directly after this node in the vector. + */ + next:Node; + + + /** + * @param idx The index of the node in the vector. + * @param val The data at this node in the vector. + * @param next The node directly after this node in the vector. + */ + constructor(idx:number, val:number, next:Node); + } + + + /** + * lunr.SortedSets are used to maintain an array of unique values in a sorted order. + */ + class SortedSet + { + elements:T[]; + + length:number; + + + /** + * Inserts new items into the set in the correct position to maintain the order. + * + * @param values The objects to add to this set. + */ + add(...values:T[]):void; + + + /** + * Converts this sorted set into an array. + */ + toArray():T[]; + + + /** + * Creates a new array with the results of calling a provided function on + * every element in this sorted set. + * + * Delegates to Array.prototype.map and has the same signature. + * + * @param fn The function that is called on each element of the + * @param ctx An optional object that can be used as the context + */ + map(fn:Function, ctx:any):T[]; + + + /** + * Executes a provided function once per sorted set element. + * + * Delegates to Array.prototype.forEach and has the same signature. + * + * @param fn The function that is called on each element of the + * @param ctx An optional object that can be used as the context + */ + forEach(fn:Function, ctx:any):any; + + + /** + * Returns the index at which a given element can be found in the sorted + * set, or -1 if it is not present. + * + * @param elem The object to locate in the sorted set. + * @param start An optional index at which to start searching from + * @param end An optional index at which to stop search from within + */ + indexOf(elem:T, start?:number, end?:number):number; + + + /** + * Returns the position within the sorted set that an element should be + * inserted at to maintain the current order of the set. + * + * This function assumes that the element to search for does not already exist + * in the sorted set. + * + * @param elem - The elem to find the position for in the set + * @param start - An optional index at which to start searching from + * @param end - An optional index at which to stop search from within + */ + locationFor(elem:T, start?:number, end?:number):number; + + + /** + * Creates a new lunr.SortedSet that contains the elements in the + * intersection of this set and the passed set. + * + * @param otherSet The set to intersect with this set. + */ + intersect(otherSet:SortedSet):SortedSet; + + + /** + * Creates a new lunr.SortedSet that contains the elements in the union of this + * set and the passed set. + * + * @param otherSet The set to union with this set. + */ + union(otherSet:SortedSet):SortedSet; + + + /** + * Makes a copy of this set + */ + clone():SortedSet; + + + /** + * Returns a representation of the sorted set ready for serialisation. + */ + toJSON():any; + + + /** + * Loads a previously serialised sorted set. + * + * @param serialisedData The serialised set to load. + */ + static load(serialisedData:T[]):SortedSet; + } + + + interface IIndexField + { + /** + * The name of the field within the document that + */ + name:string; + + /** + * An optional boost that can be applied to terms in this field. + */ + boost:number; + } + + + interface IIndexSearchResult + { + ref:any; + + score:number; + } + + + /** + * lunr.Index is object that manages a search index. It contains the indexes and stores + * all the tokens and document lookups. It also provides the main user facing API for + * the library. + */ + class Index + { + eventEmitter:EventEmitter; + + documentStore:Store; + + tokenStore:TokenStore; + + corpusTokens:SortedSet; + + pipeline:Pipeline; + + _fields:IIndexField[]; + + _ref:string; + + _idfCache:{[key:string]:string}; + + + /** + * Bind a handler to events being emitted by the index. + * + * The handler can be bound to many events at the same time. + * + * @param eventName The name(s) of events to bind the function to. + * @param handler The function to call when an event is fired. Binds a handler + * function to a specific event(s). + */ + on(eventName:string, handler:Function):void; + on(eventName:string, eventName2:string, handler:Function):void; + on(eventName:string, eventName2:string, eventName3:string, handler:Function):void; + on(eventName:string, eventName2:string, eventName3:string, eventName4:string, handler:Function):void; + on(eventName:string, eventName2:string, eventName3:string, eventName4:string, eventName5:string, handler:Function):void; + + + /** + * Removes a handler from an event being emitted by the index. + * + * @param eventName The name of events to remove the function from. + * @param handler The serialised set to load. + */ + off(eventName:string, handler:Function):void; + + + /** + * Adds a field to the list of fields that will be searchable within documents in the index. + * + * An optional boost param can be passed to affect how much tokens in this field rank in + * search results, by default the boost value is 1. + * + * Fields should be added before any documents are added to the index, fields that are added + * after documents are added to the index will only apply to new documents added to the index. + * + * @param fieldName The name of the field within the document that + * @param options An optional boost that can be applied to terms in this field. + */ + field(fieldName:string, options?:{boost?:number}):Index; + + + /** + * Sets the property used to uniquely identify documents added to the index, by default this + * property is 'id'. + * + * This should only be changed before adding documents to the index, changing the ref property + * without resetting the index can lead to unexpected results. + * + * @refName The property to use to uniquely identify the + */ + ref(refName:string):Index; + + + /** + * Add a document to the index. + * + * This is the way new documents enter the index, this function will run the fields from the + * document through the index's pipeline and then add it to the index, it will then show up + * in search results. + * + * An 'add' event is emitted with the document that has been added and the index the document + * has been added to. This event can be silenced by passing false as the second argument to add. + * + * @param doc The document to add to the index. + * @param emitEvent Whether or not to emit events, default true. + */ + add(doc:any, emitEvent?:boolean):void; + + + /** + * Removes a document from the index. + * + * To make sure documents no longer show up in search results they can be removed from the + * index using this method. + * + * The document passed only needs to have the same ref property value as the document that was + * added to the index, they could be completely different objects. + * + * A 'remove' event is emitted with the document that has been removed and the index the + * document has been removed from. This event can be silenced by passing false as the second + * argument to remove. + * + * @param doc The document to remove from the index. + * @param emitEvent Whether to emit remove events, defaults to true + */ + remove(doc:any, emitEvent?:boolean):void; + + + /** + * Updates a document in the index. + * + * When a document contained within the index gets updated, fields changed, added or removed, + * to make sure it correctly matched against search queries, it should be updated in the index. + * + * This method is just a wrapper around [[remove]] and [[add]]. + * + * An 'update' event is emitted with the document that has been updated and the index. + * This event can be silenced by passing false as the second argument to update. Only an + * update event will be fired, the 'add' and 'remove' events of the underlying calls are + * silenced. + * + * @param doc The document to update in the index. + * @param emitEvent Whether to emit update events, defaults to true + */ + update(doc:any, emitEvent?:boolean):void; + + + /** + * Calculates the inverse document frequency for a token within the index. + * + * @param token The token to calculate the idf of. + */ + idf(token:string):string; + + + /** + * Searches the index using the passed query. + * + * Queries should be a string, multiple words are allowed and will lead to an AND based + * query, e.g. idx.search('foo bar') will run a search for documents containing both + * 'foo' and 'bar'. + * + * All query tokens are passed through the same pipeline that document tokens are passed + * through, so any language processing involved will be run on every query term. + * + * Each query term is expanded, so that the term 'he' might be expanded to 'hello' + * and 'help' if those terms were already included in the index. + * + * Matching documents are returned as an array of objects, each object contains the + * matching document ref, as set for this index, and the similarity score for this + * document against the query. + * + * @param query The query to search the index with. + */ + search(query:string):IIndexSearchResult[]; + + + /** + * Generates a vector containing all the tokens in the document matching the + * passed documentRef. + * + * The vector contains the tf-idf score for each token contained in the document with + * the passed documentRef. The vector will contain an element for every token in the + * indexes corpus, if the document does not contain that token the element will be 0. + * + * @param documentRef The ref to find the document with. + */ + documentVector(documentRef:string):Vector; + + + /** + * Returns a representation of the index ready for serialisation. + */ + toJSON():any; + + + /** + * Applies a plugin to the current index. + * + * A plugin is a function that is called with the index as its context. Plugins can be + * used to customise or extend the behaviour the index in some way. A plugin is just a + * function, that encapsulated the custom behaviour that should be applied to the index. + * + * The plugin function will be called with the index as its argument, additional arguments + * can also be passed when calling use. The function will be called with the index as + * its context. + * + * Example: + * + * ```javascript + * var myPlugin = function(idx, arg1, arg2) { + * // `this` is the index to be extended + * // apply any extensions etc here. + * }; + * + * var idx = lunr(function() { + * this.use(myPlugin, 'arg1', 'arg2'); + * }); + * ``` + * + * @param plugin The plugin to apply. + * @param args + */ + use(plugin:Function, ...args:any[]):void; + + + /** + * Loads a previously serialised index. + * + * Issues a warning if the index being imported was serialised by a different version + * of lunr. + * + * @param serialisedData The serialised set to load. + */ + static load(serialisedData:any):Index; + } + + + /** + * lunr.Store is a simple key-value store used for storing sets of tokens for documents + * stored in index. + */ + class Store + { + store:{[id:string]:SortedSet}; + + length:number; + + + /** + * Stores the given tokens in the store against the given id. + * + * @param id The key used to store the tokens against. + * @param tokens The tokens to store against the key. + */ + set(id:string, tokens:SortedSet):void; + + + /** + * Retrieves the tokens from the store for a given key. + * + * @param id The key to lookup and retrieve from the store. + */ + get(id:string):SortedSet; + + + /** + * Checks whether the store contains a key. + * + * @param id The id to look up in the store. + */ + has(id:string):boolean; + + + /** + * Removes the value for a key in the store. + * + * @param id The id to remove from the store. + */ + remove(id:string):void; + + + /** + * Returns a representation of the store ready for serialisation. + */ + toJSON():any; + + + /** + * Loads a previously serialised store. + * + * @param serialisedData The serialised store to load. + */ + static load(serialisedData:any):Store; + } + + + interface ITokenDocument + { + ref:number; + + tf:number; + } + + + /** + * lunr.TokenStore is used for efficient storing and lookup of the reverse index of token + * to document ref. + */ + class TokenStore + { + root:{[token:string]:TokenStore}; + + docs:{[ref:string]:ITokenDocument}; + + length:number; + + + /** + * Adds a new token doc pair to the store. + * + * By default this function starts at the root of the current store, however it can + * start at any node of any token store if required. + * + * @param token The token to store the doc under + * @param doc The doc to store against the token + * @param root An optional node at which to start looking for the + */ + add(token:string, doc:ITokenDocument, root?:TokenStore):void; + + + /** + * Checks whether this key is contained within this lunr.TokenStore. + * + * @param token The token to check for + */ + has(token:string):boolean; + + + /** + * Retrieve a node from the token store for a given token. + * + * @param token The token to get the node for. + */ + getNode(token:string):TokenStore; + + + /** + * Retrieve the documents for a node for the given token. + * + * By default this function starts at the root of the current store, however it can + * start at any node of any token store if required. + * + * @param token The token to get the documents for. + * @param root An optional node at which to start. + */ + get(token:string, root:TokenStore):{[ref:string]:ITokenDocument}; + + + count(token:string, root:TokenStore):number; + + + /** + * Remove the document identified by ref from the token in the store. + * + * @param token The token to get the documents for. + * @param ref The ref of the document to remove from this token. + */ + remove(token:string, ref:string):void; + + + /** + * Find all the possible suffixes of the passed token using tokens currently in + * the store. + * + * @param token The token to expand. + * @param memo + */ + expand(token:string, memo?:string[]):string[]; + + + /** + * Returns a representation of the token store ready for serialisation. + */ + toJSON():any; + + + /** + * Loads a previously serialised token store. + * + * @param serialisedData The serialised token store to load. + */ + static load(serialisedData:any):TokenStore; + } +} + + +/** + * Convenience function for instantiating a new lunr index and configuring it with the default + * pipeline functions and the passed config function. + * + * When using this convenience function a new index will be created with the following functions + * already in the pipeline: + * + * * lunr.StopWordFilter - filters out any stop words before they enter the index + * + * * lunr.stemmer - stems the tokens before entering the index. + * + * Example: + * + * ```javascript + * var idx = lunr(function () { + * this.field('title', 10); + * this.field('tags', 100); + * this.field('body'); + * + * this.ref('cid'); + * + * this.pipeline.add(function () { + * // some custom pipeline function + * }); + * }); + * ``` + */ +declare function lunr(config:Function):lunr.Index; \ No newline at end of file From 4227be18c1bf006da4af4f435fcdab2349f125db Mon Sep 17 00:00:00 2001 From: Steve Ognibene Date: Sun, 20 Jul 2014 09:10:21 -0400 Subject: [PATCH 147/324] Added typing for big.js library --- big.js/big.js-tests.ts | 233 +++++++++++++++++++++++++++++++++++++++++ big.js/big.js.d.ts | 200 +++++++++++++++++++++++++++++++++++ 2 files changed, 433 insertions(+) create mode 100644 big.js/big.js-tests.ts create mode 100644 big.js/big.js.d.ts diff --git a/big.js/big.js-tests.ts b/big.js/big.js-tests.ts new file mode 100644 index 000000000..6de9ee7cc --- /dev/null +++ b/big.js/big.js-tests.ts @@ -0,0 +1,233 @@ +// Type definitions for big.js +// Project: https://github.com/MikeMcl/big.js/ +// Definitions by: Steve Ognibene +// Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + +/* + + Tests include code from http://mikemcl.github.io/big.js/ + + Minor changes have been made such as adding variable definitions where required. + +*/ + +function constructorTests() { + var x = new Big(9) // '9' + var y = new Big(x) // '9' + var d = Big(435.345) // 'new' is optional + var e = Big('435.345') // 'new' is optional + var a = new Big('5032485723458348569331745.33434346346912144534543') + var b = new Big('4.321e+4') // '43210' + var c = new Big('-735.0918e-430') // '-7.350918e-428' +} + +function staticPropertiesTests() { + Big.DP = 40; + Big.RM = 3; + Big.RM = BigJsLibrary.RoundingMode.RoundAwayFromZero; +} + +function absTests() { + var x = new Big(-0.8); + x.abs(); // '0.8' +} + +function cmpTests() { + var x = new Big(6); + var y = new Big(5); + x.cmp(y); // 1 + y.cmp(x.minus(1)); // 0 +} + +function divTests() { + var x = new Big(355); + var y = new Big(113); + x.div(y); // '3.14159292035398230088' + Big.DP = 2; + x.div(y); // '3.14' + x.div(5); // '71' +} + +function eqTests() { + 0 === 1e-324; // true + var x = new Big(0); + x.eq('1e-324'); // false + Big(-0).eq(x); // true ( -0 === 0 ) +} + +function gtTests() { + 0.1 > 0.3 - 0.2; // true + var x = new Big(0.1); + x.gt(Big(0.3).minus(0.2)); // false + Big(0).gt(x); // false +} + +function gteTests() { + 0.3 - 0.2 >= 0.1; // false + var x = new Big(0.3).minus(0.2); + x.gte(0.1); // true + Big(1).gte(x); // true +} + +function ltTests() { + 0.3 - 0.2 < 0.1; // true + var x = new Big(0.3).minus(0.2); + x.lt(0.1); // false + Big(0).lt(x); // true +} + +function lteTests() { + 0.1 <= 0.3 - 0.2; // false + var x = new Big(0.1); + x.lte(Big(0.3).minus(0.2)); // true + Big(-1).lte(x); // true +} + +function minusTests() { + 0.3 - 0.1; // 0.19999999999999998 + var x = new Big(0.3); + x.minus(0.1); // '0.2' +} + +function modTests() { + 1 % 0.9 // 0.09999999999999998 + var x = Big(1); + x.mod(0.9) // '0.1' +} + +function plusTests() { + 0.1 + 0.2 // 0.30000000000000004 + var x = new Big(0.1) + var y = x.plus(0.2) // '0.3' + Big(0.7).plus(x).plus(y) // '1' +} + +function powTests() { + Math.pow(0.7, 2) // 0.48999999999999994 + var x = new Big(0.7) + x.pow(2) // '0.49' + Big.DP = 20 + Big(3).pow(-2) // '0.11111111111111111111' + + new Big(123.456).pow(1000).toString().length // 5099 + new Big(2).pow(1e+6) // Time taken (Node.js): 9 minutes 34 secs. +} + +function roundTests() { + var x = 123.45 + Math.round(x) // 123 + var y = new Big(x) + y.round() // '123' + y.round(2) // '123.45' + y.round(10) // '123.45' + y.round(1, 0) // '123.4' + y.round(1, 1) // '123.5' + y.round(1, 2) // '123.4' + y.round(1, 3) // '123.5' + y // '123.45' +} + +function sqrtTests() { + var x = new Big(16) + x.sqrt() // '4' + var y = new Big(3) + y.sqrt() // '1.73205080756887729353' +} + +function timesTests() { + 0.6 * 3 // 1.7999999999999998 + var x = new Big(0.6) + var y = x.times(3) // '1.8' + Big('7e+500').times(y) // '1.26e+501' +} + +function toExponentialTests() { + var x = 45.6 + var y = new Big(x) + x.toExponential() // '4.56e+1' + y.toExponential() // '4.56e+1' + x.toExponential(0) // '5e+1' + y.toExponential(0) // '5e+1' + x.toExponential(1) // '4.6e+1' + y.toExponential(1) // '4.6e+1' + x.toExponential(3) // '4.560e+1' + y.toExponential(3) // '4.560e+1' +} + +function toFixedTests() { + var x = 45.6 + var y = new Big(x) + x.toFixed() // '46' + y.toFixed() // '45.6' + y.toFixed(0) // '46' + x.toFixed(3) // '45.600' + y.toFixed(3) // '45.600' +} + +function toPrecisionTests() { + var x = 45.6 + var y = new Big(x) + x.toPrecision() // '45.6' + y.toPrecision() // '45.6' + x.toPrecision(1) // '5e+1' + y.toPrecision(1) // '5e+1' + x.toPrecision(5) // '45.600' + y.toPrecision(5) // '45.600' +} + +function toStringTests() { + var x = new Big('9.99e+20') + x.toString() // '999000000000000000000' + var y = new Big('1E21') + x.toString() // '1e+21' +} + +function valueOfTests() { + var x = new Big('177.7e+457') + x.valueOf() // '1.777e+459' +} + +function toJSONTests() { + var x = new Big('177.7e+457') + var y = new Big(235.4325) + var z = new Big('0.0098074') + var str = JSON.stringify([x, y, z]) + + var a = new Big('123').toJSON(); + + JSON.parse(str, function (k, v) { return k === '' ? v : new Big(v) }) // Returns an array of three Big numbers. +} + +function propertiesTest1() { + var x = new Big(0.123) // '0.123' + x.toExponential() // '1.23e-1' + x.c // '1,2,3' + x.e // -1 + x.s // 1 + + var y = new Number(-123.4567000e+2) // '-12345.67' + y.toExponential() // '-1.234567e+4' + var z = new Big('-123.4567000e+2') // '-12345.67' + z.toExponential() // '-1.234567e+4' + z.c // '1,2,3,4,5,6,7' + z.e // 4 + z.s // -1 +} + +function propertiesTest2() { + var x = new Big('1234.000') // '1234' + x.toExponential() // '1.234e+3' + x.c // '1,2,3,4' + x.e // 3 + + x.e = -5 + x // '0.00001234' +} + +function propertiesTest3() { + var y = new Big(-0) // '0' + y.c // '0' [0].toString() + y.e // 0 + y.s // -1 +} \ No newline at end of file diff --git a/big.js/big.js.d.ts b/big.js/big.js.d.ts new file mode 100644 index 000000000..4f6278a80 --- /dev/null +++ b/big.js/big.js.d.ts @@ -0,0 +1,200 @@ +// Type definitions for big.js +// Project: https://github.com/MikeMcl/big.js/ +// Definitions by: Steve Ognibene +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +declare module BigJsLibrary { + + export enum RoundingMode { + RoundTowardsZero = 0, + RoundTowardsNearestAwayFromZero = 1, + RoundTowardsNearestTowardsEven = 2, + RoundAwayFromZero = 3 + } + + interface BigJS extends BigJS_Constructors { + /** The maximum number of decimal places of the results of operations involving division. + It is relevant only to the div and sqrt methods, and the pow method when the exponent is negative. + @default 40 */ + DP: number; + + /** The rounding mode used in the above operations and by round, toExponential, toFixed and toPrecision. + Default is RoundTowardsNearestAwayFromZero + @default 1 */ + RM: RoundingMode; + } + + interface BigJS_Constructors { + /** A decimal value. */ + new (value: number): BigJS; + /** A decimal value. + String values may be in exponential, as well as normal (non-exponential) notation. There is no limit to the number of digits of a string value (other than that of Javascript's maximum array size), but the largest recommended exponent magnitude is 1e+6. Infinity, NaN and hexadecimal literal strings, e.g. '0xff', are not valid. + String values in octal literal form will be interpreted as decimals, e.g. '011' is 11, not 9. */ + new (value: string): BigJS; + /** A decimal value. */ + new (value: BigJS): BigJS; + /** A decimal value. */ + (value: number): BigJS; + /** A decimal value. + String values may be in exponential, as well as normal (non-exponential) notation. There is no limit to the number of digits of a string value (other than that of Javascript's maximum array size), but the largest recommended exponent magnitude is 1e+6. Infinity, NaN and hexadecimal literal strings, e.g. '0xff', are not valid. + String values in octal literal form will be interpreted as decimals, e.g. '011' is 11, not 9. */ + (value: string): BigJS; + /** A decimal value. */ + (value: BigJS): BigJS; + } + + /** BigJS instance methods */ + interface BigJS extends BigJS_Constructors { + /** Returns a Big number whose value is the absolute value, i.e. the magnitude, of this Big number. */ + abs(): BigJS; + + /** Compare + @returns {Number} + 1 = If the value of this Big number is greater than the value of n + -1 = If the value of this Big number is less than the value of n + 0 = If this Big number and n have the same value */ + cmp(n: number): number; + /** Compare + @returns {Number} + 1 = If the value of this Big number is greater than the value of n + -1 = If the value of this Big number is less than the value of n + 0 = If this Big number and n have the same value */ + cmp(n: string): number; + /** Compare + @returns {Number} + 1 = If the value of this Big number is greater than the value of n + -1 = If the value of this Big number is less than the value of n + 0 = If this Big number and n have the same value */ + cmp(n: BigJS): number; + + /** Returns a Big number whose value is the value of this Big number divided by n. */ + div(n: number): BigJS; + /** Returns a Big number whose value is the value of this Big number divided by n. */ + div(n: string): BigJS; + /** Returns a Big number whose value is the value of this Big number divided by n. */ + div(n: BigJS): BigJS; + + /** Returns true if the value of this Big equals the value of n, otherwise returns false. */ + eq(n: number): boolean; + /** Returns true if the value of this Big equals the value of n, otherwise returns false. */ + eq(n: string): boolean; + /** Returns true if the value of this Big equals the value of n, otherwise returns false. */ + eq(n: BigJS): boolean; + + /** Returns true if the value of this Big is greater than the value of n, otherwise returns false. */ + gt(n: number): boolean; + /** Returns true if the value of this Big is greater than the value of n, otherwise returns false. */ + gt(n: string): boolean; + /** Returns true if the value of this Big is greater than the value of n, otherwise returns false. */ + gt(n: BigJS): boolean; + + /** Returns true if the value of this Big is greater than or equal to the value of n, otherwise returns false. */ + gte(n: number): boolean; + /** Returns true if the value of this Big is greater than or equal to the value of n, otherwise returns false. */ + gte(n: string): boolean; + /** Returns true if the value of this Big is greater than or equal to the value of n, otherwise returns false. */ + gte(n: BigJS): boolean; + + /** Returns true if the value of this Big is less than the value of n, otherwise returns false. */ + lt(n: number): boolean; + /** Returns true if the value of this Big is less than the value of n, otherwise returns false. */ + lt(n: string): boolean; + /** Returns true if the value of this Big is less than the value of n, otherwise returns false. */ + lt(n: BigJS): boolean; + + /** Returns true if the value of this Big is less than or equal to the value of n, otherwise returns false. */ + lte(n: number): boolean; + /** Returns true if the value of this Big is less than or equal to the value of n, otherwise returns false. */ + lte(n: string): boolean; + /** Returns true if the value of this Big is less than or equal to the value of n, otherwise returns false. */ + lte(n: BigJS): boolean; + + /** Returns a Big number whose value is the value of this Big number minus n. */ + minus(n: number): BigJS; + /** Returns a Big number whose value is the value of this Big number minus n. */ + minus(n: string): BigJS; + /** Returns a Big number whose value is the value of this Big number minus n. */ + minus(n: BigJS): BigJS; + + /** Returns a Big number whose value is the value of this Big number modulo n, i.e. the integer remainder of dividing this Big number by n. + The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */ + mod(n: number): BigJS; + /** Returns a Big number whose value is the value of this Big number modulo n, i.e. the integer remainder of dividing this Big number by n. + The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */ + mod(n: string): BigJS; + /** Returns a Big number whose value is the value of this Big number modulo n, i.e. the integer remainder of dividing this Big number by n. + The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */ + mod(n: BigJS): BigJS; + + /** Returns a Big number whose value is the value of this Big number plus n. */ + plus(n: number): BigJS; + /** Returns a Big number whose value is the value of this Big number plus n. */ + plus(n: string): BigJS; + /** Returns a Big number whose value is the value of this Big number plus n. */ + plus(n: BigJS): BigJS; + + /** Returns a Big number whose value is the value of this Big number raised to the power exp. + If exp is negative and the result has more fraction digits than is specified by Big.DP, it will be rounded to Big.DP decimal places using rounding mode Big.RM. + @param exp integer, -1e+6 to 1e+6 inclusive */ + pow(exp: number): BigJS; + + /** Returns a Big number whose value is the value of this Big number rounded to a whole number. */ + round(): BigJS; + /** Returns a Big number whose value is the value of this Big number rounded using rounding mode rm to a maximum of dp decimal places. + @param dp Number of decimal places (0 to 1e+6 inclusive). If dp is omitted or is null or undefined, the return value is n rounded to a whole number. */ + round(dp: number): BigJS; + /** Returns a Big number whose value is the value of this Big number rounded using rounding mode rm to a maximum of dp decimal places. + @param dp Number of decimal places (0 to 1e+6 inclusive). If dp is omitted or is null or undefined, the return value is n rounded to a whole number. + @param rm Rounding mode. If rm is omitted or is null or undefined, the current Big.RM setting is used. */ + round(dp: number, rm: RoundingMode): BigJS; + + /** Returns a Big number whose value is the square root of this Big number. */ + sqrt(): BigJS; + + /** Returns a Big number whose value is the value of this Big number times n. */ + times(n: number): BigJS; + /** Returns a Big number whose value is the value of this Big number times n. */ + times(n: string): BigJS; + /** Returns a Big number whose value is the value of this Big number times n. */ + times(n: BigJS): BigJS; + + /** Returns a string representing the value of this Big number in exponential notation to a fixed number of decimal places dp. */ + toExponential(): string; + /** Returns a string representing the value of this Big number in exponential notation to a fixed number of decimal places dp. + @param dp Number of decimal places (0 to 1e+6 inclusive). If dp is omitted, or is null or undefined, the number of digits after the decimal point defaults to the minimum number of digits necessary to represent the value exactly. */ + toExponential(dp: number): string; + + /** Returns a string representing the value of this Big number in normal notation to a fixed number of decimal places dp. */ + toFixed(): string; + /** Returns a string representing the value of this Big number in normal notation to a fixed number of decimal places dp. + @param dp Number of decimal places (0 to 1e+6 inclusive). If dp is omitted, or is null or undefined, then the return value is simply the value in normal notation. This is also unlike Number.prototype.toFixed, which returns the value to zero decimal places. */ + toFixed(dp: number): string; + + /** Returns a string representing the value of this Big number to the specified number of significant digits sd. */ + toPrecision(): string; + /** Returns a string representing the value of this Big number to the specified number of significant digits sd. + @param sd significant digits. If sd is omitted, or is null or undefined, then the return value is the same as .toString(). */ + toPrecision(sd: number /** number of significant digits (0 to 1e+6 inclusive) */): string; + + /** Returns a string representing the value of this Big number. */ + toString(): string; + + /** As toString. */ + valueOf(): string; + + /** As toString. */ + toJSON(): string; + + /** coefficient (significand) */ + c: number[]; + + /** exponent (Integer, -1e+6 to 1e+6 inclusive) */ + e: number; + + /** sign (-1 or 1) */ + s: number; + } +} + +declare var Big: BigJsLibrary.BigJS; \ No newline at end of file From 433b0cf2df9a92cc00ab22901da4f13a74a1c9dc Mon Sep 17 00:00:00 2001 From: Steve Ognibene Date: Sun, 20 Jul 2014 09:14:58 -0400 Subject: [PATCH 148/324] Added line to contributors file. --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index c01d01147..4955fcbdb 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -28,6 +28,7 @@ All definitions files include a header with the author and editors, so at some p * [aws-sdk-js](https://github.com/aws/aws-sdk-js) (by [midknight41](https://github.com/midknight41)) * [Backbone.js](http://backbonejs.org/) (by [Boris Yankov](https://github.com/borisyankov)) * [Backbone Relational](http://backbonerelational.org/) (by [Eirik Hoem](https://github.com/eirikhm)) +* [big.js](https://github.com/MikeMcl/big.js) (by [Steve Ognibene](https://github.com/nycdotnet)) * [BigInteger](https://github.com/peterolson/BigInteger.js) (by [Ingo Bürk](https://github.com/Airblader)) * [BigScreen](http://brad.is/coding/BigScreen/) (by [Douglas Eichelberger](https://github.com/dduugg)) * [Bluebird](https://github.com/petkaantonov/bluebird) (by [Bart van der Schoor](https://github.com/Bartvds)) From dc4d81a6bda11013ce1e1752a53a8cf00606adfd Mon Sep 17 00:00:00 2001 From: Carl de Billy Date: Sun, 20 Jul 2014 12:59:27 -0400 Subject: [PATCH 149/324] Remove useless reference to RxJS This reference is not needed and is now causing problem because the definitelyTyped for RxJS is now part of the RxJS package directly. The Nuget package will needed to be changed also. --- knockout.rx/knockout.rx.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/knockout.rx/knockout.rx.d.ts b/knockout.rx/knockout.rx.d.ts index 71d95d758..601ef5af4 100644 --- a/knockout.rx/knockout.rx.d.ts +++ b/knockout.rx/knockout.rx.d.ts @@ -4,7 +4,6 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped /// -/// interface KnockoutSubscribableFunctions { toObservable(event?: string): Rx.Observable; From 0692edd2381159aa004995cfd973f4d6995170f8 Mon Sep 17 00:00:00 2001 From: Carl de Billy Date: Sun, 20 Jul 2014 16:25:49 -0400 Subject: [PATCH 150/324] Revert "Remove useless reference to RxJS" This reverts commit dc4d81a6bda11013ce1e1752a53a8cf00606adfd. --- knockout.rx/knockout.rx.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/knockout.rx/knockout.rx.d.ts b/knockout.rx/knockout.rx.d.ts index 601ef5af4..71d95d758 100644 --- a/knockout.rx/knockout.rx.d.ts +++ b/knockout.rx/knockout.rx.d.ts @@ -4,6 +4,7 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped /// +/// interface KnockoutSubscribableFunctions { toObservable(event?: string): Rx.Observable; From a2cb953ad174cbd4431b9dc78c97251413bbe76f Mon Sep 17 00:00:00 2001 From: Carl de Billy Date: Sun, 20 Jul 2014 16:30:34 -0400 Subject: [PATCH 151/324] Removed useless reference to RxJS typing Since the typing is now part of RxJS, referencing it (which is causing a nuget package dependency) will cause a problem by having twice the save references in the samme app. --- knockout.rx/knockout.rx.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/knockout.rx/knockout.rx.d.ts b/knockout.rx/knockout.rx.d.ts index 71d95d758..4a27f3fed 100644 --- a/knockout.rx/knockout.rx.d.ts +++ b/knockout.rx/knockout.rx.d.ts @@ -4,7 +4,6 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped /// -/// interface KnockoutSubscribableFunctions { toObservable(event?: string): Rx.Observable; @@ -21,6 +20,8 @@ interface KnockoutComputedFunctions { } declare module Rx { + interface ISubject { } + interface Observable { toKoSubscribable(): KnockoutSubscribable; toKoObservable(initialValue?: T): KnockoutObservable; From 735c0f1d5d58cff9399035d4f70d6d30a12256c7 Mon Sep 17 00:00:00 2001 From: Basarat Syed Date: Mon, 21 Jul 2014 11:48:03 +1000 Subject: [PATCH 152/324] Added val methods - ref https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md#api --- typeahead/typeahead-tests.ts | 5 +++++ typeahead/typeahead.d.ts | 11 +++++++++++ 2 files changed, 16 insertions(+) diff --git a/typeahead/typeahead-tests.ts b/typeahead/typeahead-tests.ts index 67fc8d31a..1044fe3bf 100644 --- a/typeahead/typeahead-tests.ts +++ b/typeahead/typeahead-tests.ts @@ -85,3 +85,8 @@ $('.example-countries .typeahead').typeahead({ prefetch: '../data/countries.json', limit: 10 }); + +module valueTest { + var value: string = $('foo').typeahead('val'); + $('foo').typeahead('val', value); +} \ No newline at end of file diff --git a/typeahead/typeahead.d.ts b/typeahead/typeahead.d.ts index f6f387986..bb8aaf31d 100644 --- a/typeahead/typeahead.d.ts +++ b/typeahead/typeahead.d.ts @@ -60,6 +60,17 @@ interface JQuery { * @param dataset Array of datasets */ typeahead(options: Twitter.Typeahead.Options, dataset: Twitter.Typeahead.Dataset): JQuery; + + /** + * Returns the current value of the typeahead. The value is the text the user has entered into the input element. + */ + typeahead(methodName: 'val'): string; + typeahead(methodName: string): string; + + /** + * Sets the value of the typeahead. This should be used in place of jQuery#val. + */ + typeahead(methodName: 'val', value: string): JQuery; } declare module Twitter.Typeahead { From fe47b495c8aa7ee551fb3239fb08c93f15a05f92 Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Mon, 21 Jul 2014 11:09:13 +0200 Subject: [PATCH 153/324] angularjs: allow $q.when to be called w/o args The current definition does not cover the case that the input type is void. --- angularjs/angular-tests.ts | 6 ++++++ angularjs/angular.d.ts | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 37dae22f4..d7534bc36 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -139,6 +139,12 @@ module HttpAndRegularPromiseTests { dPromise.then((snack: string) => { $scope.snack = snack; }); + + // $q.when may be called without arguments + var ePromise: ng.IPromise = $q.when(); + ePromise.then(() => { + $scope.nothing = "really nothing"; + }); } // Test that we can pass around a type-checked success/error Promise Callback diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index d6b649a33..3880a8c05 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -565,6 +565,12 @@ declare module ng { * @param value Value or a promise */ when(value: T): IPromise; + /** + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. + * + * @param value Value or a promise + */ + when(): IPromise; } interface IPromise { From 93116a95bb19d90999519cf863170d905c91ebfd Mon Sep 17 00:00:00 2001 From: Taylan Date: Mon, 21 Jul 2014 10:24:55 +0100 Subject: [PATCH 154/324] Update kineticjs.d.ts Updated arguments for Node.move() to match library: http://kineticjs.com/docs/Kinetic.Node.html --- kineticjs/kineticjs.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kineticjs/kineticjs.d.ts b/kineticjs/kineticjs.d.ts index dc9219fe2..b5d56e846 100644 --- a/kineticjs/kineticjs.d.ts +++ b/kineticjs/kineticjs.d.ts @@ -45,7 +45,7 @@ declare module Kinetic { isDraggable(): boolean; isDragging(): boolean; isListening(): boolean; - move(x: number, y: number): void; + move(change:{x: number; y: number}): void; moveDown(): void; moveTo(newContainer: IContainer): void; moveToBottom(): void; From 625b9f2523e465181c9b3793269a2755e4fddca7 Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Mon, 21 Jul 2014 15:33:31 +0200 Subject: [PATCH 155/324] Fixup --- angularjs/angular-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index d7534bc36..647287215 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -141,7 +141,7 @@ module HttpAndRegularPromiseTests { }); // $q.when may be called without arguments - var ePromise: ng.IPromise = $q.when(); + var ePromise: ng.IPromise = $q.when(); ePromise.then(() => { $scope.nothing = "really nothing"; }); From a7c4e5074328c50acf03ef0bf5bd44c31c80fed1 Mon Sep 17 00:00:00 2001 From: Frederik Wordenskjold Date: Mon, 21 Jul 2014 15:35:58 +0200 Subject: [PATCH 156/324] Added channel support to Marionette.d.ts Marionette.d.ts includes definitions for Backbone.Wreqr, but does not support the recommended way of using the Wreqr object as seen here: https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.application.md#accessing-the-global-channel I've added the Channel object, and a definition to the Radio class as well. This is only a means of getting a specific channel through the channel() method, so while it is possible to create an instance of Radio, I've chosen only to include channel() method, and make it static. This makes it possible to access the instance of a channel with the name 'global' like this (created if not found), as recommended in the above documentation: var channel = Backbone.Wreqr.radio.channel('global'); // channel.vent; Finally, I've made the parameter context of the setHandler method in the Backbone.Wreqr.Handlers class optional, as this adheres to the actual implementation. --- marionette/marionette.d.ts | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/marionette/marionette.d.ts b/marionette/marionette.d.ts index 96672ca3f..9ff239dc5 100644 --- a/marionette/marionette.d.ts +++ b/marionette/marionette.d.ts @@ -57,13 +57,35 @@ declare module Backbone { // Backbone.Wreqr module Wreqr { + class radio { + + static channel(channelName: string): Channel; + + } + + class Channel { + + constructor(channelName: string); + + vent: Backbone.Wreqr.EventAggregator; + reqres: Backbone.Wreqr.RequestResponse; + commands: Backbone.Wreqr.Commands; + channelName: string; + + reset(): Channel; + connectEvents(hash: string, context: any): Channel; + connectCommands(hash: string, context: any): Channel; + connectRequests(hash: string, context: any): Channel; + + } + class Handlers extends Backbone.Events { constructor(options?: any); options: any; - setHandler(name: string, handler: any, context: any): void; + setHandler(name: string, handler: any, context?: any): void; hasHandler(name: string): boolean; getHandler(name: string): Function; removeHandler(name: string); From 48a3150ca5fa6b7a4a48b8d79709ae1e03961b8c Mon Sep 17 00:00:00 2001 From: "Omid K. Rad" Date: Mon, 21 Jul 2014 16:04:35 -0700 Subject: [PATCH 157/324] Backbone.emulateJSON http://backbonejs.org/#Sync-emulateJSON --- backbone/backbone.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index d8bdc71c9..3aeeb7d90 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -375,7 +375,7 @@ declare module Backbone { function sync(method: string, model: Model, options?: JQueryAjaxSettings): any; function ajax(options?: JQueryAjaxSettings): JQueryXHR; var emulateHTTP: boolean; - var emulateJSONBackbone: boolean; + var emulateJSON: boolean; // Utility function noConflict(): typeof Backbone; From c0df8aa594852cec97d841e28488d9b39b1c62ee Mon Sep 17 00:00:00 2001 From: Brian Malehorn Date: Mon, 21 Jul 2014 17:56:42 -0700 Subject: [PATCH 158/324] fix a number of bugs in d3.d.ts Most are a result of setter = foo.bar(x), getter = foo.bar() only reflecting the setter signature. --- d3/d3.d.ts | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 598cd9f34..8da827f4e 100755 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -243,7 +243,7 @@ declare module D3 { * * @param map Array of objects to get the values from */ - values(map: any[]): any[]; + values(map: any): any[]; /** * List the key-value entries of an associative array. * @@ -1720,10 +1720,21 @@ declare module D3 { (): any[]; (values: any[]): Axis; }; - tickSubdivide(count: number): Axis; - tickSize(major?: number, minor?: number, end?: number): Axis; + tickSize: { + (): number; + (inner: number, outer?: number): Axis; + } + innerTickSize: { + (): number; + (value: number): Axis; + } + outerTickSize: { + (): number; + (value: number): Axis; + } tickFormat(formatter: (value: any) => string): Axis; + nice(count?: number): Axis; } export interface Arc { @@ -2569,7 +2580,10 @@ declare module D3 { * * @param clamp Enable or disable */ - clamp(clamp: boolean): QuantitiveScale; + clamp: { + (): boolean; + (clamp: boolean): QuantitiveScale; + } /** * extend the scale domain to nice round numbers. * @@ -2587,7 +2601,7 @@ declare module D3 { * * @param count Aproximate representative values to return */ - tickFormat(count: number): (n: number) => string; + tickFormat(count: number, format?: string): (n: number) => string; /** * create a new scale from an existing scale.. */ @@ -2768,6 +2782,7 @@ declare module D3 { }; tickFormat(count: number): (n: number) => string; copy(): TimeScale; + nice(count?: number): TimeScale; } } From 70b0bfebde611eeb97ddc8286fa9ae1f8d19d226 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Mon, 21 Jul 2014 18:10:22 -0700 Subject: [PATCH 159/324] rx.jquery.d.ts moved to separated folder 'rx-jquery'. --- {rx.js => rx-jquery}/rx.jquery.d.ts | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {rx.js => rx-jquery}/rx.jquery.d.ts (100%) diff --git a/rx.js/rx.jquery.d.ts b/rx-jquery/rx.jquery.d.ts similarity index 100% rename from rx.js/rx.jquery.d.ts rename to rx-jquery/rx.jquery.d.ts From 3a92e771933d2dd8fc184294d4077b0ef86f47a5 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Mon, 21 Jul 2014 18:11:26 -0700 Subject: [PATCH 160/324] rx.js renamed to rx. --- {rx.js => rx}/rx-lite.d.ts | 0 {rx.js => rx}/rx.aggregates.d.ts | 0 {rx.js => rx}/rx.all.ts | 0 {rx.js => rx}/rx.async-lite.d.ts | 0 {rx.js => rx}/rx.async-tests.ts | 0 {rx.js => rx}/rx.async.d.ts | 0 {rx.js => rx}/rx.backpressure-lite.d.ts | 0 {rx.js => rx}/rx.backpressure-tests.ts | 0 {rx.js => rx}/rx.backpressure.d.ts | 0 {rx.js => rx}/rx.binding-lite.d.ts | 0 {rx.js => rx}/rx.binding.d.ts | 0 {rx.js => rx}/rx.coincidence-lite.d.ts | 0 {rx.js => rx}/rx.coincidence.d.ts | 0 {rx.js => rx}/rx.d.ts | 0 {rx.js => rx}/rx.experimental.d.ts | 0 {rx.js => rx}/rx.joinpatterns.d.ts | 0 {rx.js => rx}/rx.lite.d.ts | 0 {rx.js => rx}/rx.testing.d.ts | 0 {rx.js => rx}/rx.time-lite.d.ts | 0 {rx.js => rx}/rx.time.d.ts | 0 {rx.js => rx}/rx.virtualtime.d.ts | 0 21 files changed, 0 insertions(+), 0 deletions(-) rename {rx.js => rx}/rx-lite.d.ts (100%) rename {rx.js => rx}/rx.aggregates.d.ts (100%) rename {rx.js => rx}/rx.all.ts (100%) rename {rx.js => rx}/rx.async-lite.d.ts (100%) rename {rx.js => rx}/rx.async-tests.ts (100%) rename {rx.js => rx}/rx.async.d.ts (100%) rename {rx.js => rx}/rx.backpressure-lite.d.ts (100%) rename {rx.js => rx}/rx.backpressure-tests.ts (100%) rename {rx.js => rx}/rx.backpressure.d.ts (100%) rename {rx.js => rx}/rx.binding-lite.d.ts (100%) rename {rx.js => rx}/rx.binding.d.ts (100%) rename {rx.js => rx}/rx.coincidence-lite.d.ts (100%) rename {rx.js => rx}/rx.coincidence.d.ts (100%) rename {rx.js => rx}/rx.d.ts (100%) rename {rx.js => rx}/rx.experimental.d.ts (100%) rename {rx.js => rx}/rx.joinpatterns.d.ts (100%) rename {rx.js => rx}/rx.lite.d.ts (100%) rename {rx.js => rx}/rx.testing.d.ts (100%) rename {rx.js => rx}/rx.time-lite.d.ts (100%) rename {rx.js => rx}/rx.time.d.ts (100%) rename {rx.js => rx}/rx.virtualtime.d.ts (100%) diff --git a/rx.js/rx-lite.d.ts b/rx/rx-lite.d.ts similarity index 100% rename from rx.js/rx-lite.d.ts rename to rx/rx-lite.d.ts diff --git a/rx.js/rx.aggregates.d.ts b/rx/rx.aggregates.d.ts similarity index 100% rename from rx.js/rx.aggregates.d.ts rename to rx/rx.aggregates.d.ts diff --git a/rx.js/rx.all.ts b/rx/rx.all.ts similarity index 100% rename from rx.js/rx.all.ts rename to rx/rx.all.ts diff --git a/rx.js/rx.async-lite.d.ts b/rx/rx.async-lite.d.ts similarity index 100% rename from rx.js/rx.async-lite.d.ts rename to rx/rx.async-lite.d.ts diff --git a/rx.js/rx.async-tests.ts b/rx/rx.async-tests.ts similarity index 100% rename from rx.js/rx.async-tests.ts rename to rx/rx.async-tests.ts diff --git a/rx.js/rx.async.d.ts b/rx/rx.async.d.ts similarity index 100% rename from rx.js/rx.async.d.ts rename to rx/rx.async.d.ts diff --git a/rx.js/rx.backpressure-lite.d.ts b/rx/rx.backpressure-lite.d.ts similarity index 100% rename from rx.js/rx.backpressure-lite.d.ts rename to rx/rx.backpressure-lite.d.ts diff --git a/rx.js/rx.backpressure-tests.ts b/rx/rx.backpressure-tests.ts similarity index 100% rename from rx.js/rx.backpressure-tests.ts rename to rx/rx.backpressure-tests.ts diff --git a/rx.js/rx.backpressure.d.ts b/rx/rx.backpressure.d.ts similarity index 100% rename from rx.js/rx.backpressure.d.ts rename to rx/rx.backpressure.d.ts diff --git a/rx.js/rx.binding-lite.d.ts b/rx/rx.binding-lite.d.ts similarity index 100% rename from rx.js/rx.binding-lite.d.ts rename to rx/rx.binding-lite.d.ts diff --git a/rx.js/rx.binding.d.ts b/rx/rx.binding.d.ts similarity index 100% rename from rx.js/rx.binding.d.ts rename to rx/rx.binding.d.ts diff --git a/rx.js/rx.coincidence-lite.d.ts b/rx/rx.coincidence-lite.d.ts similarity index 100% rename from rx.js/rx.coincidence-lite.d.ts rename to rx/rx.coincidence-lite.d.ts diff --git a/rx.js/rx.coincidence.d.ts b/rx/rx.coincidence.d.ts similarity index 100% rename from rx.js/rx.coincidence.d.ts rename to rx/rx.coincidence.d.ts diff --git a/rx.js/rx.d.ts b/rx/rx.d.ts similarity index 100% rename from rx.js/rx.d.ts rename to rx/rx.d.ts diff --git a/rx.js/rx.experimental.d.ts b/rx/rx.experimental.d.ts similarity index 100% rename from rx.js/rx.experimental.d.ts rename to rx/rx.experimental.d.ts diff --git a/rx.js/rx.joinpatterns.d.ts b/rx/rx.joinpatterns.d.ts similarity index 100% rename from rx.js/rx.joinpatterns.d.ts rename to rx/rx.joinpatterns.d.ts diff --git a/rx.js/rx.lite.d.ts b/rx/rx.lite.d.ts similarity index 100% rename from rx.js/rx.lite.d.ts rename to rx/rx.lite.d.ts diff --git a/rx.js/rx.testing.d.ts b/rx/rx.testing.d.ts similarity index 100% rename from rx.js/rx.testing.d.ts rename to rx/rx.testing.d.ts diff --git a/rx.js/rx.time-lite.d.ts b/rx/rx.time-lite.d.ts similarity index 100% rename from rx.js/rx.time-lite.d.ts rename to rx/rx.time-lite.d.ts diff --git a/rx.js/rx.time.d.ts b/rx/rx.time.d.ts similarity index 100% rename from rx.js/rx.time.d.ts rename to rx/rx.time.d.ts diff --git a/rx.js/rx.virtualtime.d.ts b/rx/rx.virtualtime.d.ts similarity index 100% rename from rx.js/rx.virtualtime.d.ts rename to rx/rx.virtualtime.d.ts From aef69df8b45cae140cf3696a84f4ecc98c05eda1 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Mon, 21 Jul 2014 18:13:36 -0700 Subject: [PATCH 161/324] Fixed reference path in rx.jquery.d.ts --- rx-jquery/rx.jquery.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rx-jquery/rx.jquery.d.ts b/rx-jquery/rx.jquery.d.ts index ace0c5071..d3d405451 100644 --- a/rx-jquery/rx.jquery.d.ts +++ b/rx-jquery/rx.jquery.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped /// -/// +/// interface RxJQueryAjaxResult { data: T; From 3394ad045ed7febf7b6d05bccbc590c0e0a028e3 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Mon, 21 Jul 2014 18:15:18 -0700 Subject: [PATCH 162/324] Fixed reference path to RxJS in knockout.rx.d.ts --- knockout.rx/knockout.rx.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/knockout.rx/knockout.rx.d.ts b/knockout.rx/knockout.rx.d.ts index 71d95d758..7b98e25c2 100644 --- a/knockout.rx/knockout.rx.d.ts +++ b/knockout.rx/knockout.rx.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped /// -/// +/// interface KnockoutSubscribableFunctions { toObservable(event?: string): Rx.Observable; From fb839ffeb94cc8b94a5f93825fd7bce209a40b1a Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Mon, 21 Jul 2014 18:36:03 -0700 Subject: [PATCH 163/324] Fixed reference of rx in promises-a-plus-tests.ts --- promises-a-plus/promises-a-plus-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/promises-a-plus/promises-a-plus-tests.ts b/promises-a-plus/promises-a-plus-tests.ts index 042c4f066..bba258649 100644 --- a/promises-a-plus/promises-a-plus-tests.ts +++ b/promises-a-plus/promises-a-plus-tests.ts @@ -1,5 +1,5 @@ /// -/// +/// /// /// import When = require("../when/when"); From e917a9c81ea00b39281e75c69dd827ed3c0153c6 Mon Sep 17 00:00:00 2001 From: basarat Date: Tue, 22 Jul 2014 21:00:50 +1000 Subject: [PATCH 164/324] JQuery `originalEvent` should be of type `Event` closes #2545 --- jquery/jquery-tests.ts | 3 +++ jquery/jquery.d.ts | 7 ++----- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/jquery/jquery-tests.ts b/jquery/jquery-tests.ts index 920b95846..2f647c4d1 100644 --- a/jquery/jquery-tests.ts +++ b/jquery/jquery-tests.ts @@ -1494,6 +1494,9 @@ function test_eventParams() { $('#whichkey').bind('mousedown', function (e) { $('#log').html(e.type + ': ' + e.which); }); + $(window).on('mousewheel', (e) => { + var delta = (e.originalEvent).deltaY; + }); } function test_extend() { diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index eb6ec2e56..e40110c16 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -548,6 +548,7 @@ interface BaseJQueryEventObject extends Event { isImmediatePropagationStopped(): boolean; isPropagationStopped(): boolean; namespace: string; + originalEvent: Event; preventDefault(): any; relatedTarget: Element; result: any; @@ -585,11 +586,7 @@ interface JQueryKeyEventObject extends JQueryInputEventObject { keyCode: number; } -interface JQueryPopStateEventObject extends BaseJQueryEventObject { - originalEvent: PopStateEvent; -} - -interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject, JQueryPopStateEventObject { +interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject{ } /* From fde9a8e787f472f252b163ba83ed4e86867e1834 Mon Sep 17 00:00:00 2001 From: StefanSchoof Date: Tue, 22 Jul 2014 20:58:26 +0200 Subject: [PATCH 165/324] Added calendar Property to GlobalizeCulture The calendar Property is used to get and set the default calendar. See https://github.com/jquery/globalize/tree/79ae658b842f75f58199d6e9074e01f7ce207468#defining-culture-information and https://github.com/jquery/globalize/blob/79ae658b842f75f58199d6e9074e01f7ce207468/lib/globalize.js#L263 --- globalize/globalize.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/globalize/globalize.d.ts b/globalize/globalize.d.ts index 0bdaeb4bf..4510e38cb 100644 --- a/globalize/globalize.d.ts +++ b/globalize/globalize.d.ts @@ -91,6 +91,7 @@ interface GlobalizeCulture { isRTL: boolean; language: string; numberFormat: GlobalizeNumberFormat; + calendar: GlobalizeCalendar; calendars: GlobalizeCalendars; messages: any; } From 1d60391f76fc07dc7ba42d3f811c13306d2cd22f Mon Sep 17 00:00:00 2001 From: Bart van der Schoor Date: Tue, 22 Jul 2014 21:27:20 +0200 Subject: [PATCH 166/324] node.d.ts : pass Uint8Array to Buffer constructor closes #2499 --- node/node.d.ts | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index d7c06203b..282120dc6 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -50,6 +50,7 @@ declare var exports: any; declare var SlowBuffer: { new (str: string, encoding?: string): Buffer; new (size: number): Buffer; + new (size: Uint8Array): Buffer; new (array: any[]): Buffer; prototype: Buffer; isBuffer(obj: any): boolean; @@ -63,6 +64,7 @@ interface Buffer extends NodeBuffer {} declare var Buffer: { new (str: string, encoding?: string): Buffer; new (size: number): Buffer; + new (size: Uint8Array): Buffer; new (array: any[]): Buffer; prototype: Buffer; isBuffer(obj: any): boolean; @@ -760,18 +762,18 @@ declare module "net" { declare module "dgram" { import events = require("events"); - interface RemoteInfo { - address: string; - port: number; - size: number; - } - - interface AddressInfo { - address: string; - family: string; - port: number; - } - + interface RemoteInfo { + address: string; + port: number; + size: number; + } + + interface AddressInfo { + address: string; + family: string; + port: number; + } + export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; interface Socket extends events.EventEmitter { From c0e29234f7681f88ada9aa4ce09a32f655cb3388 Mon Sep 17 00:00:00 2001 From: brentj73 Date: Wed, 23 Jul 2014 12:19:26 +0100 Subject: [PATCH 167/324] Added typing for recaptcha.js --- recaptcha/recaptcha-tests.ts | 52 ++++++++++++++++++++++++++++++++++++ recaptcha/recaptcha.d.ts | 39 +++++++++++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 recaptcha/recaptcha-tests.ts create mode 100644 recaptcha/recaptcha.d.ts diff --git a/recaptcha/recaptcha-tests.ts b/recaptcha/recaptcha-tests.ts new file mode 100644 index 000000000..61ef51d9f --- /dev/null +++ b/recaptcha/recaptcha-tests.ts @@ -0,0 +1,52 @@ +/// + +var recaptchaOptions: RecaptchaOptions = { + theme : 'custom', + custom_theme_widget: 'recaptcha_widget' + }; + +var recaptchaOptions: RecaptchaOptions = { + custom_translations: { instructions_visual: "This is my text:" } +}; + +var recaptchaOptions: RecaptchaOptions = { + custom_translations: { + instructions_visual: "Scrivi le due parole:", + instructions_audio: "Trascrivi ci\u00f2 che senti:", + play_again: "Riascolta la traccia audio", + cant_hear_this: "Scarica la traccia in formato MP3", + visual_challenge: "Modalit\u00e0 visiva", + audio_challenge: "Modalit\u00e0 auditiva", + refresh_btn: "Chiedi due nuove parole", + help_btn: "Aiuto", + incorrect_try_again: "Scorretto. Riprova.", + }, + lang: 'it', + theme: 'red' +}; + +var recaptchaOptions: RecaptchaOptions = { + theme : 'white', + tabindex : 2 +}; + +Recaptcha.create("public_key_a", + "element_id_a", + { + theme: "red", + callback: Recaptcha.focus_response_field + } +); + +Recaptcha.create("public_key_b", + "element_id_b", + recaptchaOptions +); + +Recaptcha.switch_type("audio"); +Recaptcha.get_challenge(); +Recaptcha.get_response(); +Recaptcha.reload(); +Recaptcha.showhelp(); +Recaptcha.focus_response_field(); +Recaptcha.destroy(); diff --git a/recaptcha/recaptcha.d.ts b/recaptcha/recaptcha.d.ts new file mode 100644 index 000000000..410db7651 --- /dev/null +++ b/recaptcha/recaptcha.d.ts @@ -0,0 +1,39 @@ +// Type definitions for Google Recaptcha +// Project: https://www.google.com/recaptcha +// Definitions by: Brent Jenkins +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare class Recaptcha { + constructor(); + static reload(): void; + static switch_type(newtype: any); + static showhelp(): void; + static get_challenge(): string; + static get_response(): string; + static focus_response_field(): void; + static create(public_key: string, element: string, options: RecaptchaOptions): void; + static destroy(): void; +} + +interface RecaptchaOptions { + tabindex?: number; + theme?: string; + callback?: Function; + lang?: string; + custom_theme_widget?: string; + custom_translations?: CustomTranslations; +} + +interface CustomTranslations { + visual_challenge?: string; + audio_challenge?: string; + refresh_btn?: string; + instructions_visual?: string; + instructions_audio?: string; + help_btn?: string; + play_again?: string; + cant_hear_this?: string; + incorrect_try_again?: string; + image_alt_text?: string; + privacy_and_terms?: string; +} \ No newline at end of file From 4c3b64221298a22ea834fbb7c27e5c92a67f1615 Mon Sep 17 00:00:00 2001 From: brentj73 Date: Wed, 23 Jul 2014 13:01:36 +0100 Subject: [PATCH 168/324] Updated switch_type method with correct types --- recaptcha/recaptcha.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/recaptcha/recaptcha.d.ts b/recaptcha/recaptcha.d.ts index 410db7651..db2096275 100644 --- a/recaptcha/recaptcha.d.ts +++ b/recaptcha/recaptcha.d.ts @@ -6,7 +6,7 @@ declare class Recaptcha { constructor(); static reload(): void; - static switch_type(newtype: any); + static switch_type(newtype: string): void; static showhelp(): void; static get_challenge(): string; static get_response(): string; @@ -36,4 +36,4 @@ interface CustomTranslations { incorrect_try_again?: string; image_alt_text?: string; privacy_and_terms?: string; -} \ No newline at end of file +} From ba1b3d7d609b1cde8d828cd67b91003e6aa3a60a Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Wed, 23 Jul 2014 14:08:31 +0200 Subject: [PATCH 169/324] Fixup --- angularjs/angular-tests.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 647287215..788545156 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -95,6 +95,7 @@ module HttpAndRegularPromiseTests { theAnswer: number; letters: string[]; snack: string; + nothing?: string; } var someController: Function = ($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) => { From 1e9a25470164976c069ecc4c7dce1941f60e85d8 Mon Sep 17 00:00:00 2001 From: Nickolas Westman Date: Wed, 23 Jul 2014 11:24:32 -0700 Subject: [PATCH 170/324] Update Anon Function Parameters in asyncTest Encountered compiler errors on using asyncTest ... fixed by making sure that the assert is a function of the anon function --- qunit/qunit.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/qunit/qunit.d.ts b/qunit/qunit.d.ts index 5628feaa6..c6fe34f0f 100644 --- a/qunit/qunit.d.ts +++ b/qunit/qunit.d.ts @@ -381,7 +381,7 @@ interface QUnitStatic extends QUnitAssert{ * @param expected Number of assertions in this test * @param test Function to close over assertions */ - asyncTest(name: string, expected: number, test: () => any): any; + asyncTest(name: string, expected: number, test: (assert: QUnitAssert) => any): any; /** * Add an asynchronous test to run. The test must include a call to start(). @@ -392,7 +392,7 @@ interface QUnitStatic extends QUnitAssert{ * @param name Title of unit being tested * @param test Function to close over assertions */ - asyncTest(name: string, test: () => any): any; + asyncTest(name: string, test: (assert: QUnitAssert) => any): any; /** * Specify how many assertions are expected to run within a test. @@ -662,7 +662,7 @@ declare function testStart(callback: (details: TestStartCallbackObject) => any): * @param expected Number of assertions in this test * @param test Function to close over assertions */ -declare function asyncTest(name: string, expected?: any, test?: () => any): any; +declare function asyncTest(name: string, expected?: any, test?: (assert: QUnitAssert) => any): any; /** * Add an asynchronous test to run. The test must include a call to start(). @@ -673,7 +673,7 @@ declare function asyncTest(name: string, expected?: any, test?: () => any): any; * @param name Title of unit being tested * @param test Function to close over assertions */ -declare function asyncTest(name: string, test: () => any): any; +declare function asyncTest(name: string, test: (assert: QUnitAssert) => any): any; /** * Specify how many assertions are expected to run within a test. From b1776d0257335d62d9f7d5a475d3a26cf1b34a74 Mon Sep 17 00:00:00 2001 From: Steve Fenton Date: Wed, 23 Jul 2014 23:00:11 +0100 Subject: [PATCH 171/324] Dropbox-JS Definition. The dropbox-js project is a wrapped for the Dropbox API. --- dropboxjs/dropboxjs-tests.ts | 54 +++++++++++++++++++ dropboxjs/dropboxjs.d.ts | 101 +++++++++++++++++++++++++++++++++++ 2 files changed, 155 insertions(+) create mode 100644 dropboxjs/dropboxjs-tests.ts create mode 100644 dropboxjs/dropboxjs.d.ts diff --git a/dropboxjs/dropboxjs-tests.ts b/dropboxjs/dropboxjs-tests.ts new file mode 100644 index 000000000..cf5fd3827 --- /dev/null +++ b/dropboxjs/dropboxjs-tests.ts @@ -0,0 +1,54 @@ +/// + +var browserClient = new Dropbox.Client({ key: "your-key-here" }); + +browserClient.authenticate(function (error, client) { + if (error) { + alert(error); + } + + client.onError.addListener(function (error) { + if (window.console) { // Skip the "if" in node.js code. + console.error(error); + } + }); + + client.getAccountInfo(function (error, accountInfo) { + if (error) { + alert(error); // Something went wrong. + } + + alert("Hello, " + accountInfo.name + "!"); + }); + + client.writeFile("hello_world.txt", "Hello, world!\n", function (error, stat) { + if (error) { + alert(error); // Something went wrong. + } + + alert("File saved as revision " + stat.versionTag); + }); + + client.readFile("hello_world.txt", function (error, data) { + if (error) { + alert(error); // Something went wrong. + } + + alert(data); // data has the file's contents + }); + + client.readdir("/", function (error, entries) { + if (error) { + alert(error); // Something went wrong. + } + + alert("Your Dropbox contains " + entries.join(", ")); + }); +}); + +var serverClient = new Dropbox.Client({ + key: "your-key-here", + secret: "your-secret-here" +}); + +serverClient.authDriver(new Dropbox.AuthDriver.NodeServer(8191)); \ No newline at end of file diff --git a/dropboxjs/dropboxjs.d.ts b/dropboxjs/dropboxjs.d.ts new file mode 100644 index 000000000..a718fabaf --- /dev/null +++ b/dropboxjs/dropboxjs.d.ts @@ -0,0 +1,101 @@ +// Type definitions for dropbox-js +// Project: https://github.com/dropbox/dropbox-js +// Definitions by: Steve Fenton +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Dropbox { + export interface DropboxConfig { + key: string; + secret?: string; + } + + export interface AccountInfoData { + name: string; + email: string; + countryCode: string; + uid: string; + referralUrl: string; + publicAppUrl: string; + quota: number; + usedQuota: number; + privateBytes: number; + sharedBytes: number; + } + + export interface AccountInfo extends AccountInfoData { + parse(accountInfo: string): AccountInfo; + json(): AccountInfoData; + } + + export interface ApiError { + INVALID_TOKEN: number; + NOT_FOUND: number; + OVER_QUOTA: number; + RATE_LIMITED: number; + NETWORK_ERROR: number; + INVALID_PARAM: number; + OAUTH_ERROR: number; + INVALID_METHOD: number; + } + + export interface FileStatisticsData { + path: string; + name: string; + inAppFolder: boolean; + isFolder: boolean; + isFile: boolean; + isRemoved: boolean; + typeIcon: string; + versionTag: string; + contentHash: string; + mimeType: string; + size: number; + humanSize: string; + hasThumbnail: boolean; + modifiedAt: Date; + clientModifiedAt: Date; + } + + export interface FileStatistics extends FileStatisticsData { + parse(stats: string): FileStatistics; + json(): FileStatisticsData; + } + + export interface ClientOnError { + addListener(callback: (error: number) => any): void; + } + + export interface Client { + new (config: DropboxConfig): Client; + authDriver(authDriver: any): Client; + authenticate(callback: (error: number, client: Client) => any): Client; + credentials(): string; + dropboxUid(): string; + isAuthenticated(): boolean; + onError: ClientOnError; + getAccountInfo(callback: (error: number, accountInfo: AccountInfo) => any): XMLHttpRequest; + getUserInfo(callback: (error: number, accountInfo: AccountInfo) => any): XMLHttpRequest; + signOut(options: {}, callback: (error: number) => any): XMLHttpRequest; + signOff(options: {}, callback: (error: number) => any): XMLHttpRequest; + writeFile(fileName: string, contents: string, options: {}, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest; + writeFile(fileName: string, contents: string, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest; + readFile(fileName: string, options: {}, callback: (error: number, contents: string, stats: FileStatistics) => any): XMLHttpRequest; + readFile(fileName: string, callback: (error: number, contents: string, stats: FileStatistics) => any): XMLHttpRequest; + stat(path: string, options: {}, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest; + stat(path: string, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest; + metadata(path: string, options: {}, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest; + metadata(path: string, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest; + readdir(path: string, options: {}, callback: (error: number, entries: any[]) => any): XMLHttpRequest; + readdir(path: string, callback: (error: number, entries: any[]) => any): XMLHttpRequest; + } + + export module AuthDriver { + export interface NodeServer { + new (port: number): any; + } + + export var NodeServer: NodeServer; + } + + export var Client: Client; +} From 00fdeb909473de02d9f6634c47ece4bc87127a61 Mon Sep 17 00:00:00 2001 From: zaneli Date: Thu, 24 Jul 2014 11:32:35 +0900 Subject: [PATCH 172/324] Add definitions for bucks.js --- bucksjs/bucks-test.ts | 222 ++++++++++++++++++++++++++++++++++++++++++ bucksjs/bucks.d.ts | 55 +++++++++++ 2 files changed, 277 insertions(+) create mode 100644 bucksjs/bucks-test.ts create mode 100644 bucksjs/bucks.d.ts diff --git a/bucksjs/bucks-test.ts b/bucksjs/bucks-test.ts new file mode 100644 index 000000000..5ebbd882c --- /dev/null +++ b/bucksjs/bucks-test.ts @@ -0,0 +1,222 @@ +/// + +function add_and_end() { + // + // new Bucks object + // + var b = new Bucks(); + + // + // Add and add several tasks. + // + b.add(function f1(err, res) { + + return 'a'; + + }).add(function f2(err, res, next) { + + // res => 'a' + return next(null, 3); + + }).add(function f3(err, res, next) { + + // res => 3 + return next(new Error('error after 3')); + + }).add(function f4(err, res, next) { + + // err => 'error after 3' + return next(null, "recover 4"); + + }).add(function f5(err, res) { + + // res => 'recover 4' + throw new Error('error in f5'); + + }).add(function f6(err, res) { + + // err => 'error in f5' + throw err; + + }).add(function f7(err, res) { + + // err => 'error in f5' + // ignore and return + return "recover 7"; + + }).add(function f8(err, res, next) { + + // res => 'recover 7'; + throw new Error('error in f8'); + + }).add(function f9(err, res, next) { + + // err => 'Error in f8' + // ignore error + return next(null, 'result of 9'); + + }).end(function last(err, results) { + + // all of results + // are obtained in #end + + // err => null + + // results => [ + // 'a', + // null, + // null, + // 'recover 4', + // null, + // null, + // 'recover 7', + // null, + // 'result of 9' + // ]; + }); +} + +function then() { + var b = new Bucks(); + b.then(function start() { + return 'start'; + }).then(function second(res, next) { + // res => 'start' + return next(null, 'second') + }).end(); +} + +function delay() { + var b = new Bucks(); + b.add(function (){ /** program */ }) + .delay(1 * 1000) // 1ms + .add(function() { /** program */}) + .end(); +} + +function error() { + var b = new Bucks(); + b.then(function start() { + throw new Error('error in start'); + return 'start'; + }).error(function onError(e, next) { + // e => 'error in start' + return next(); + }).end(); +} + +function final_errorback_in_end() { + // + // last error back + // + var b = new Bucks(); + b.empty( + // add empty task (#end with no task cause error) + ).end(function last(err, res) { + // error in last callback + throw new Error('error in end'); + }, function finalErrorback(err) { + // catch uncaught error in last callback + // err => 'error in end' + }); +} + +function uncaught_error() { + try { + var b = new Bucks(); + b.then(function () { + throw new Error('error'); + }).end(); + } catch(e) { + // e => 'error' + } +} + +function waterfall() { + var t1: Bucks.Task = function t1(err, res) { + return 't1'; + }; + var t2: Bucks.Task = function t2(err, res) { + return 't2'; + }; + + new Bucks().waterfall([t1, t2]).end(function finish(err, ress) { + // ress => ['t1', 't2'] + }); + + // same as + new Bucks().add(t1).add(t2).end(function finish(err, ress) { + // ress => ['t1', 't2'] + }); +} + +function parallel() { + var b = new Bucks(); + + b.parallel([ + function task1(err, res) { + return "task1"; + }, + function task2(err, res, next) { + return next(null, "task2"); + }, + function task3(err, res, next) { + return next(new Error('passed error in task3')); + }, + function task4(err, res, next) { + throw new Error('thrown error in task4'); + } + ]).add(function getResults(err, res, next) { + // res => { + // err: [ + // null, + // null, + // [Error: passed error in task3], + // [Error: thrown error in task4] + // ], + // res: [ + // 'task1', + // 'task2', + // null, + // null + // ] + // } + next(); + }).end(); +} + +function onError() { + var onError = function (e: Error, bucks: Bucks.Bucks) { + console.log("Custom onError"); + }; + + // Bucks.onError!! + Bucks.onError(onError); + var b0 = new Bucks(); + b0 + .add(function(err, next) { + throw new Error('b0'); + }) + .end() + ; +} + +function dispose() { + var b0 = new Bucks(); + + b0.dispose = function dispose () { + // delete b0.dummy; + } + + b0 + .add(function(err, next) { + // b0.dummy = "dummy"; + next(); + }) + .end(null, null) + ; +} + +function debug() { + Bucks.DEBUG = true; +} diff --git a/bucksjs/bucks.d.ts b/bucksjs/bucks.d.ts new file mode 100644 index 000000000..111665744 --- /dev/null +++ b/bucksjs/bucks.d.ts @@ -0,0 +1,55 @@ +// Type definitions for bucks.js 0.8.3 +// Project: https://github.com/CyberAgent/bucks.js +// Definitions by: Shunsuke Ohtani +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Bucks { + + interface BucksStatic { + + VERSION: string; + + DEBUG: boolean; + + running: Bucks[]; + + living: Bucks[]; + + new (): Bucks; + + onError(onError:(err:Error, bucks:Bucks)=>any): void; + } + + interface Bucks { + + add(task: Task): Bucks; + + then(onSuccess: (res:any, next?:Next)=>any): Bucks; + + empty(): Bucks; + + error(onError: (err:Error, res:any, next?:Next)=>any): Bucks; + + parallel(tasks: Task[]): Bucks; + + waterfall(tasks: Task[]): Bucks; + + delay(ms: number): Bucks; + + dispose(): void; + + destroy(err: Error): Bucks; + + end(callback?: (err?:Error, res?:any)=>any, errback?: (err:Error)=>any): void; + } + + interface Task { + (err?: Error, res?: any, next?: Next): any; + } + + interface Next { + (err?: Error, res?: any): any; + } +} + +declare var Bucks: Bucks.BucksStatic; From c711aaae5cde8691b1d33b6d4d9dae876a0ebfde Mon Sep 17 00:00:00 2001 From: zaneli Date: Thu, 24 Jul 2014 12:17:15 +0900 Subject: [PATCH 173/324] Add comments for bucks.js --- CONTRIBUTORS.md | 1 + bucksjs/bucks.d.ts | 84 +++++++++++++++++++++++++++++++++++++++------- 2 files changed, 72 insertions(+), 13 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index e51d544d5..4a2d5d0ea 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -39,6 +39,7 @@ All definitions files include a header with the author and editors, so at some p * [Box2DWeb](http://code.google.com/p/box2dweb/) (by [Josh Baldwin](https://github.com/jbaldwin/)) * [Breeze](http://www.breezejs.com/) (by [Boris Yankov](https://github.com/borisyankov)) * [Browser Harness](https://github.com/scriby/browser-harness) (by [Chris Scribner](https://github.com/scriby)) +* [bucks.js](https://github.com/CyberAgent/bucks.js) (by [Shunsuke Ohtani](https://github.com/zaneli)) * [CasperJS](http://casperjs.org) (by [Jed Hunsaker](https://github.com/jedhunsaker)) * [Cheerio](https://github.com/MatthewMueller/cheerio) (by [Bret Little](https://github.com/blittle)) * [Chosen](http://harvesthq.github.com/chosen/) (by [Boris Yankov](https://github.com/borisyankov)) diff --git a/bucksjs/bucks.d.ts b/bucksjs/bucks.d.ts index 111665744..cac3c7121 100644 --- a/bucksjs/bucks.d.ts +++ b/bucksjs/bucks.d.ts @@ -7,47 +7,105 @@ declare module Bucks { interface BucksStatic { + /** + * bucks.js version. + */ VERSION: string; + /** + * If set `true`, uncaught errors are logged. + */ DEBUG: boolean; + /** + * Running bucks objects. + */ running: Bucks[]; + /** + * Not yet called `end` bucks object. + */ living: Bucks[]; - new (): Bucks; + /** + * Create bucks object. + */ + new(): Bucks; - onError(onError:(err:Error, bucks:Bucks)=>any): void; + /** + * Catch all errors. + * @param onError Function called after catching error + */ + onError(onError: (err:Error, bucks:Bucks)=>any): void; } interface Bucks { - add(task: Task): Bucks; + /** + * Add a task. + * @param task Function added async chain + */ + add(task: TaskWithNext): Bucks; - then(onSuccess: (res:any, next?:Next)=>any): Bucks; + /** + * Add a task called only in case of success. + * @param onSuccess Function called only in case of success + */ + then(onSuccess: (res:any, next?:Task)=>any): Bucks; + /** + * Add a empty task. + */ empty(): Bucks; - error(onError: (err:Error, res:any, next?:Next)=>any): Bucks; + /** + * Add a task called only in case of error. + * @param onError Function called only in case of error + */ + error(onError: (err:Error, next?:Task)=>any): Bucks; - parallel(tasks: Task[]): Bucks; + /** + * Add tasks in asynchronous way and join their results. + * @param tasks Functions called in asynchronous way and join their results + */ + parallel(tasks: TaskWithNext[]): Bucks; - waterfall(tasks: Task[]): Bucks; + /** + * Add tasks in asynchronous way and join their results. + * @param tasks Functions added async chain + */ + waterfall(tasks: TaskWithNext[]): Bucks; + /** + * Add delay execution. + * @param ms number millisecond for delaying + */ delay(ms: number): Bucks; + /** + * Called when destroy async chain. + */ dispose(): void; - destroy(err: Error): Bucks; + /** + * Destroy this object and call last callback function. + * @param err If specify err and no callback, throw to execute failure callback + */ + destroy(err?: Error): Bucks; - end(callback?: (err?:Error, res?:any)=>any, errback?: (err:Error)=>any): void; + /** + * Complete creating async chain and start executing. + * @param callback Last callback function + * @param errback Handler for occurring error in last callback function + */ + end(callback?: Task, errback?: (err:Error)=>any): void; + } + + interface TaskWithNext { + (err?: Error, res?: any, next?: Task): any; } interface Task { - (err?: Error, res?: any, next?: Next): any; - } - - interface Next { (err?: Error, res?: any): any; } } From cd24246cad4b8ccd0cf5c5755cf53dd158bcb060 Mon Sep 17 00:00:00 2001 From: jonathantyates Date: Thu, 24 Jul 2014 00:30:20 -0400 Subject: [PATCH 174/324] Add support for plugin --- browserify/browserify.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/browserify/browserify.d.ts b/browserify/browserify.d.ts index 5326abaeb..02ac29bf2 100644 --- a/browserify/browserify.d.ts +++ b/browserify/browserify.d.ts @@ -22,6 +22,8 @@ interface BrowserifyObject extends NodeJS.EventEmitter { ignore(file: string): BrowserifyObject; transform(tr: string): BrowserifyObject; transform(tr: Function): BrowserifyObject; + plugin(plugin: string, opts?: any): BrowserifyObject; + plugin(plugin: Function, opts?: any): BrowserifyObject; } declare module "browserify" { @@ -33,4 +35,4 @@ declare module "browserify" { }): BrowserifyObject; export = browserify; -} \ No newline at end of file +} From 10f80b4b2080b3c5ede5f44cdf97f2f60b508644 Mon Sep 17 00:00:00 2001 From: zaneli Date: Thu, 24 Jul 2014 15:47:39 +0900 Subject: [PATCH 175/324] rename folder --- CONTRIBUTORS.md | 2 +- {bucksjs => bucks}/bucks-test.ts | 0 {bucksjs => bucks}/bucks.d.ts | 0 3 files changed, 1 insertion(+), 1 deletion(-) rename {bucksjs => bucks}/bucks-test.ts (100%) rename {bucksjs => bucks}/bucks.d.ts (100%) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 4a2d5d0ea..57e5eeb6f 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -39,7 +39,7 @@ All definitions files include a header with the author and editors, so at some p * [Box2DWeb](http://code.google.com/p/box2dweb/) (by [Josh Baldwin](https://github.com/jbaldwin/)) * [Breeze](http://www.breezejs.com/) (by [Boris Yankov](https://github.com/borisyankov)) * [Browser Harness](https://github.com/scriby/browser-harness) (by [Chris Scribner](https://github.com/scriby)) -* [bucks.js](https://github.com/CyberAgent/bucks.js) (by [Shunsuke Ohtani](https://github.com/zaneli)) +* [bucks](https://github.com/CyberAgent/bucks.js) (by [Shunsuke Ohtani](https://github.com/zaneli)) * [CasperJS](http://casperjs.org) (by [Jed Hunsaker](https://github.com/jedhunsaker)) * [Cheerio](https://github.com/MatthewMueller/cheerio) (by [Bret Little](https://github.com/blittle)) * [Chosen](http://harvesthq.github.com/chosen/) (by [Boris Yankov](https://github.com/borisyankov)) diff --git a/bucksjs/bucks-test.ts b/bucks/bucks-test.ts similarity index 100% rename from bucksjs/bucks-test.ts rename to bucks/bucks-test.ts diff --git a/bucksjs/bucks.d.ts b/bucks/bucks.d.ts similarity index 100% rename from bucksjs/bucks.d.ts rename to bucks/bucks.d.ts From 2ca13ee457f59caea2c8e49fb44aca1c4cbcd617 Mon Sep 17 00:00:00 2001 From: brentj73 Date: Thu, 24 Jul 2014 13:08:45 +0100 Subject: [PATCH 176/324] Updated contributors.md for recaptcha.js details --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index e51d544d5..ed2927d99 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -277,6 +277,7 @@ All definitions files include a header with the author and editors, so at some p * [Q-io](https://github.com/kriskowal/q-io) (by [Bart van der Schoor](https://github.com/Bartvds)) * [QUnit](http://qunitjs.com/) (by [Diullei Gomes](https://github.com/Diullei)) * [Raven.js](https://github.com/getsentry/raven-js) (by [Santi Albo](https://github.com/santialbo)) +* [Recaptcha.js](https://www.google.com/recaptcha) (by [Brent Jenkins](https://github.com/brentj73)) * [Rickshaw](http://code.shutterstock.com/rickshaw/) (by [Blake Niemyjski](https://github.com/niemyjski)) * [Riot.js](https://github.com/moot/riotjs) (by [vvakame](https://github.com/vvakame)) * [Restify](https://github.com/mcavage/node-restify) (by [Bret Little](https://github.com/blittle)) From c322a99ff490720d05718d3d0eb6bb0fbf3c70c7 Mon Sep 17 00:00:00 2001 From: vvakame Date: Thu, 24 Jul 2014 23:07:06 +0900 Subject: [PATCH 177/324] add test for angular.d.ts --- angularjs/angular-tests.ts | 250 +++++++++++++++++++++++++++++++++++++ angularjs/angular.d.ts | 6 +- 2 files changed, 253 insertions(+), 3 deletions(-) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 8d86949d2..7f1e6edf9 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -271,3 +271,253 @@ test_IAttributes({ }, $attr: {} }); + +// test from https://docs.angularjs.org/guide/directive +angular.module('docsSimpleDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + template: 'Name: {{customer.name}} Address: {{customer.address}}' + }; + }); + +angular.module('docsTemplateUrlDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + templateUrl: 'my-customer.html' + }; + }); + +angular.module('docsRestrictDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + templateUrl: 'my-customer.html' + }; + }); + +angular.module('docsScopeProblemExample', []) + .controller('NaomiController', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .controller('IgorController', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Igor', + address: '123 Somewhere' + }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + templateUrl: 'my-customer.html' + }; + }); + +angular.module('docsIsolateScopeDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; + $scope.igor = { name: 'Igor', address: '123 Somewhere' }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + scope: { + customerInfo: '=info' + }, + templateUrl: 'my-customer-iso.html' + }; + }); + +angular.module('docsIsolationExample', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; + $scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + scope: { + customerInfo: '=info' + }, + templateUrl: 'my-customer-plus-vojta.html' + }; + }); + +angular.module('docsTimeDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.format = 'M/d/yy h:mm:ss a'; + }]) + .directive('myCurrentTime', ['$interval', 'dateFilter', function($interval: any, dateFilter: any): ng.IDirective { + + return { + link: function(scope: any, element: any, attrs: any) { + var format: any, + timeoutId: any; + + function updateTime() { + element.text(dateFilter(new Date(), format)); + } + + scope.$watch(attrs.myCurrentTime, function (value: any) { + format = value; + updateTime(); + }); + + element.on('$destroy', function () { + $interval.cancel(timeoutId); + }); + + // start the UI update process; save the timeoutId for canceling + timeoutId = $interval(function () { + updateTime(); // update DOM + }, 1000); + } + }; + }]); + +angular.module('docsTransclusionDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.name = 'Tobias'; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + templateUrl: 'my-dialog.html' + }; + }); + +angular.module('docsTransclusionExample', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.name = 'Tobias'; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + scope: {}, + templateUrl: 'my-dialog.html', + link: function (scope: any, element: any) { + scope.name = 'Jeff'; + } + }; + }); + +angular.module('docsIsoFnBindExample', []) + .controller('Controller', ['$scope', '$timeout', function($scope: any, $timeout: any) { + $scope.name = 'Tobias'; + $scope.hideDialog = function () { + $scope.dialogIsHidden = true; + $timeout(function () { + $scope.dialogIsHidden = false; + }, 2000); + }; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + scope: { + 'close': '&onClose' + }, + templateUrl: 'my-dialog-close.html' + }; + }); + +angular.module('dragModule', []) + .directive('myDraggable', ['$document', function($document: any) { + return function(scope: any, element: any, attr: any) { + var startX = 0, startY = 0, x = 0, y = 0; + + element.css({ + position: 'relative', + border: '1px solid red', + backgroundColor: 'lightgrey', + cursor: 'pointer' + }); + + element.on('mousedown', function(event: any) { + // Prevent default dragging of selected content + event.preventDefault(); + startX = event.pageX - x; + startY = event.pageY - y; + $document.on('mousemove', mousemove); + $document.on('mouseup', mouseup); + }); + + function mousemove(event: any) { + y = event.pageY - startY; + x = event.pageX - startX; + element.css({ + top: y + 'px', + left: x + 'px' + }); + } + + function mouseup() { + $document.off('mousemove', mousemove); + $document.off('mouseup', mouseup); + } + }; + }]); + +angular.module('docsTabsExample', []) + .directive('myTabs', function() { + return { + restrict: 'E', + transclude: true, + scope: {}, + controller: function($scope: any) { + var panes: any = $scope.panes = []; + + $scope.select = function(pane: any) { + angular.forEach(panes, function(pane: any) { + pane.selected = false; + }); + pane.selected = true; + }; + + this.addPane = function(pane: any) { + if (panes.length === 0) { + $scope.select(pane); + } + panes.push(pane); + }; + }, + templateUrl: 'my-tabs.html' + }; + }) + .directive('myPane', function() { + return { + require: '^myTabs', + restrict: 'E', + transclude: true, + scope: { + title: '@' + }, + link: function(scope, element, attrs, tabsCtrl) { + tabsCtrl.addPane(scope); + }, + templateUrl: 'my-pane.html' + }; + }); diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index ca8751b8e..42d94ee8a 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1001,9 +1001,9 @@ declare module ng { link?: (scope: IScope, instanceElement: IAugmentedJQuery, - instanceAttributes: IAttributes, - controller: any, - transclude: ITranscludeFunction + instanceAttributes?: IAttributes, + controller?: any, + transclude?: ITranscludeFunction ) => void; name?: string; priority?: number; From e911b3c06170ac7c68391f03f7ac884152f5fbc7 Mon Sep 17 00:00:00 2001 From: Steve Fenton Date: Fri, 25 Jul 2014 08:15:51 +0100 Subject: [PATCH 178/324] Added extensibility point for templates. This allows named templates to be added, for example: interface HandlebarsTemplates { specialListOfThings: HandlebarsTemplateDelegate; } So the strongly typed version can be used. var template = Handlebars.templates.specialListOfThings; --- handlebars/handlebars.d.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/handlebars/handlebars.d.ts b/handlebars/handlebars.d.ts index ee3098ec4..56cce331f 100644 --- a/handlebars/handlebars.d.ts +++ b/handlebars/handlebars.d.ts @@ -37,9 +37,13 @@ interface HandlebarsStatic extends HandlebarsCommon { compile(input: any, options?: any): HandlebarsTemplateDelegate; } -interface HandlebarsRuntimeStatic extends HandlebarsCommon { +interface HandlebarsTemplates { + [index: string]: HandlebarsTemplateDelegate; +} + +interface HandlebarsRuntimeStatic extends HandlebarsCommon { // Handlebars.templates is the default template namespace in precompiler. - templates: { (s: string): HandlebarsTemplateDelegate }[]; + templates: HandlebarsTemplates; } declare class SafeString { From ba945bd8667d300638a01812e17a1622f4c5e967 Mon Sep 17 00:00:00 2001 From: Antoine Pultier Date: Fri, 25 Jul 2014 14:23:17 +0200 Subject: [PATCH 179/324] Angular-hotkeys : Chaining when hotkeys is bound to a $scope object --- angular-hotkeys/angular-hotkeys-tests.ts | 9 +++++++++ angular-hotkeys/angular-hotkeys.d.ts | 8 +++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/angular-hotkeys/angular-hotkeys-tests.ts b/angular-hotkeys/angular-hotkeys-tests.ts index 66f9e6072..a065d4b21 100644 --- a/angular-hotkeys/angular-hotkeys-tests.ts +++ b/angular-hotkeys/angular-hotkeys-tests.ts @@ -14,3 +14,12 @@ hotkeyProvider.toggleCheatSheet(); hotkeyProvider.add(hotkeyObj.combo, hotkeyObj.description ,hotkeyObj.callback); +hotkeyProvider.bindTo(scope) + .add(hotkeyObj) + .add(hotkeyObj) + .add({ + combo: 'w', + description: 'blah blah', + callback: function() {} + }); + diff --git a/angular-hotkeys/angular-hotkeys.d.ts b/angular-hotkeys/angular-hotkeys.d.ts index cc4a3680c..f209fbe08 100644 --- a/angular-hotkeys/angular-hotkeys.d.ts +++ b/angular-hotkeys/angular-hotkeys.d.ts @@ -17,7 +17,7 @@ declare module ng.hotkeys { add(hotkeyObj: ng.hotkeys.Hotkey): void; - bindTo(scope : ng.IScope): ng.hotkeys.HotkeysProvider; + bindTo(scope : ng.IScope): ng.hotkeys.HotkeysProviderChained; del(combo: string): void; @@ -26,6 +26,12 @@ declare module ng.hotkeys { toggleCheatSheet(): void; } + interface HotkeysProviderChained { + add(combo: string, description: string, callback: (event: Event, hotkeys: ng.hotkeys.Hotkey) => void): HotkeysProviderChained; + + add(hotkeyObj: ng.hotkeys.Hotkey): HotkeysProviderChained; + } + interface Hotkey { combo: string; description?: string; From 1f96102ae331de0984cae539f321feb560965d8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafa=C5=82=20Wrzeszcz?= Date: Fri, 25 Jul 2014 14:24:05 +0200 Subject: [PATCH 180/324] Added HashMap definition. --- CONTRIBUTORS.md | 1 + hashmap/hashmap-tests.ts | 24 ++++++++++++++ hashmap/hashmap.d.ts | 71 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 96 insertions(+) create mode 100644 hashmap/hashmap-tests.ts create mode 100644 hashmap/hashmap.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index ad46a5f5f..4cf7ab60d 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -113,6 +113,7 @@ All definitions files include a header with the author and editors, so at some p * [Google Url Shortener](https://developers.google.com/url-shortener/) (by [Frank M](https://github.com/sgtfrankieboy)) * [Hammer.js](http://eightmedia.github.com/hammer.js/) (by [Boris Yankov](https://github.com/borisyankov)) * [Handlebars](http://handlebarsjs.com/) (by [Boris Yankov](https://github.com/borisyankov)) +* [HashMap](https://github.com/flesler/hashmap) (by [Rafał Wrzeszcz](https://wrzasq.pl)) * [HashSet](http://www.timdown.co.uk/jshashtable/jshashset.html) (by [Sergey Gerasimov](https://github.com/gerich-home)) * [Hashtable](http://www.timdown.co.uk/jshashtable/) (by [Sergey Gerasimov](https://github.com/gerich-home)) * [HelloJS](http://adodson.com/hello.js) (by [Pavel Zika](https://github.com/PavelPZ)) diff --git a/hashmap/hashmap-tests.ts b/hashmap/hashmap-tests.ts new file mode 100644 index 000000000..4c3d74ee0 --- /dev/null +++ b/hashmap/hashmap-tests.ts @@ -0,0 +1,24 @@ +/// + +var map : HashMap = new HashMap(); + +map.set("foo", 123); + +var value : number = map.get("foo"); + +map.has("foo"); + +map.remove("foo"); + +var keys : string[] = map.keys(); + +var values : number[] = map.values(); + +var count : number = map.count(); + +map.forEach(function(value : number, key : string) : void { + console.log(key); + console.log(value); +}); + +map.clear(); diff --git a/hashmap/hashmap.d.ts b/hashmap/hashmap.d.ts new file mode 100644 index 000000000..c9f858174 --- /dev/null +++ b/hashmap/hashmap.d.ts @@ -0,0 +1,71 @@ +// Type definitions for HashMap 1.1.0 +// Project: https://github.com/flesler/hashmap +// Definitions by: Rafał Wrzeszcz +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare class HashMap { + /** + * Return value from hashmap. + * + * @param key Key. + * @return Value stored under given key. + */ + get(key : KeyType) : ValueType; + + /** + * Store value in hashmap. + * + * @param key Key. + * @param value Value. + */ + set(key : KeyType, value : ValueType) : void; + + /** + * Checks if given key exists in hashmap. + * + * @param key Key. + * @return Whether given key exists in hashmap. + */ + has(key : KeyType) : boolean; + + /** + * Removes given key from hashmap. + * + * @param key Key. + */ + remove(key : KeyType) : void; + + /** + * Returns all contained keys. + * + * @return List of keys. + */ + keys() : KeyType[]; + + /** + * Returns all container values. + * + * @return List of values. + */ + values() : ValueType[]; + + /** + * Returns size of hashmap (number of entries). + * + * @return Number of entries in hashmap. + */ + count() : number; + + /** + * Clears hashmap. + */ + clear() : void; + + /** + * Iterates over hashmap. + * + * @param callback Function to be invoked for every hashmap entry. + */ + forEach(callback : (value : ValueType, key : KeyType) => void) : void; +} + From 74d8b10775d49c73275dd72296f51fd9ba7067b9 Mon Sep 17 00:00:00 2001 From: Xiaohan Zhang Date: Fri, 25 Jul 2014 17:38:54 -0700 Subject: [PATCH 181/324] Add definitions for fromTextArea methods --- codemirror/codemirror.d.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index 316284a78..af4b32046 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -9,7 +9,7 @@ declare function CodeMirror(callback: (host: HTMLElement) => void , options?: Co declare module CodeMirror { export var Pass: any; - function fromTextArea(host: HTMLTextAreaElement, options?: EditorConfiguration): CodeMirror.Editor; + function fromTextArea(host: HTMLTextAreaElement, options?: EditorConfiguration): CodeMirror.EditorFromTextArea; var version: string; @@ -374,6 +374,18 @@ declare module CodeMirror { on(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: number, element: HTMLElement) => void ): void; off(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: number, element: HTMLElement) => void ): void; } + + interface EditorFromTextArea extends Editor { + + /** Copy the content of the editor into the textarea. */ + save(): void; + + /** Remove the editor, and restore the original textarea (with the editor's current content). */ + toTextArea(): void; + + /** Returns the textarea that the instance was based on. */ + getTextArea(): HTMLTextAreaElement; + } class Doc { constructor (text: string, mode?: any, firstLineNumber?: number); From bfeb4664189633ede61cc28768fc388a84fca90c Mon Sep 17 00:00:00 2001 From: Basarat Ali Syed Date: Sat, 26 Jul 2014 11:35:54 +1000 Subject: [PATCH 182/324] Update angular-mocks.d.ts allow ```ts angular.mock.module("myApp", function($provide) { $provide.value("myService", { ... }); }) ``` Also signature is consistent with the global in the same file: ```ts declare var module: (...modules: any[]) => any; ``` --- angularjs/angular-mocks.d.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/angularjs/angular-mocks.d.ts b/angularjs/angular-mocks.d.ts index 6db753e1f..2591c006e 100644 --- a/angularjs/angular-mocks.d.ts +++ b/angularjs/angular-mocks.d.ts @@ -33,9 +33,7 @@ declare module ng { inject(...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works // see http://docs.angularjs.org/api/angular.mock.module - module(...modules: string[]): any; - module(...modules: Function[]): any; - module(modules: Object): any; + module(...modules: any[]): any; // see http://docs.angularjs.org/api/angular.mock.TzDate TzDate(offset: number, timestamp: number): Date; From abfde2a3003f1a2687f67d6bb0266553b672cf66 Mon Sep 17 00:00:00 2001 From: Basarat Ali Syed Date: Sat, 26 Jul 2014 11:51:54 +1000 Subject: [PATCH 183/324] Update angular.d.ts remove unnecessary restriction on directive's `link` callback to accept optional parameters --- angularjs/angular.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 42d94ee8a..ca8751b8e 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1001,9 +1001,9 @@ declare module ng { link?: (scope: IScope, instanceElement: IAugmentedJQuery, - instanceAttributes?: IAttributes, - controller?: any, - transclude?: ITranscludeFunction + instanceAttributes: IAttributes, + controller: any, + transclude: ITranscludeFunction ) => void; name?: string; priority?: number; From f8cfab178847551b2a023f133ad10f2b9fca8c71 Mon Sep 17 00:00:00 2001 From: damianog Date: Sat, 26 Jul 2014 14:33:29 +0200 Subject: [PATCH 184/324] Update swig.d.ts Added function renderFile --- swig/swig.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/swig/swig.d.ts b/swig/swig.d.ts index c8317ac5c..db2353375 100644 --- a/swig/swig.d.ts +++ b/swig/swig.d.ts @@ -9,6 +9,7 @@ declare module "swig" { export function init(options: Options): void; export function compileFile(filepath: string): any; export function compile(source: string, options?: Options): any; + export function renderFile(pathName: string, locals: any, cb: (err: any, output: string) => void): string; export interface Options { allowErrors?: boolean; From 1cdae538ab7919cbe3392f37a6d4876491d5d8b7 Mon Sep 17 00:00:00 2001 From: Douglas Eichelberger Date: Fri, 25 Jul 2014 11:40:02 -0700 Subject: [PATCH 185/324] Create ion.rangeSlider.d.ts --- CONTRIBUTORS.md | 1 + ion.rangeSlider/ion.rangeSlider-tests.ts | 38 ++++++++++++++++++ ion.rangeSlider/ion.rangeSlider.d.ts | 51 ++++++++++++++++++++++++ 3 files changed, 90 insertions(+) create mode 100644 ion.rangeSlider/ion.rangeSlider-tests.ts create mode 100644 ion.rangeSlider/ion.rangeSlider.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 4cf7ab60d..1eb31acbb 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -128,6 +128,7 @@ All definitions files include a header with the author and editors, so at some p * [Impress.js](https://github.com/bartaz/impress.js) (by [Boris Yankov](https://github.com/borisyankov)) * [Imagemagick](http://github.com/rsms/node-imagemagick) (by [Carlos Ballesteros Velasco](https://github.com/soywiz)) * [interact.js](http://github.com/taye/interact.js) (by [Douglas Eichelberger](https://github.com/dduugg)) +* [Ion.RangeSlider](https://github.com/IonDen/ion.rangeSlider) (by [Douglas Eichelberger](https://github.com/dduugg)) * [Ionic-Cordova](https://github.com/driftyco/) (by [Hendrik Maus](https://github.com/hendrikmaus)) * [iScroll](http://cubiq.org/iscroll-4) (by [Boris Yankov](https://github.com/borisyankov) and [Christiaan Rakowski](https://github.com/csrakowski)) * [IxJS (Interactive extensions)](https://github.com/Reactive-Extensions/IxJS) (by [Igor Oleinikov](https://github.com/Igorbek)) diff --git a/ion.rangeSlider/ion.rangeSlider-tests.ts b/ion.rangeSlider/ion.rangeSlider-tests.ts new file mode 100644 index 000000000..6f1d25f0d --- /dev/null +++ b/ion.rangeSlider/ion.rangeSlider-tests.ts @@ -0,0 +1,38 @@ +/// +/// + +var sliderInputElement = $(''); +sliderInputElement.ionRangeSlider({ + min: 10, + max: 100, + from: 30, + to: 80, + type: "single", + step: 10, + prefix: "$", + postfix: ".00", + maxPostfix: "+", + hasGrid: true, + hideMinMax: true, + hideFromTo: true, + prettify: true, + disable: false, + values: ["a", "b", "c"], + onLoad: function (obj) { + console.log(obj); + }, + onChange: function (obj) { + console.log(obj); + }, + onFinish: function (obj) { + console.log(obj); + } +}); +sliderInputElement.ionRangeSlider("update", { + min: 20, + max: 90, + from: 40, + to: 70, + step: 5 +}); +sliderInputElement.ionRangeSlider("remove"); diff --git a/ion.rangeSlider/ion.rangeSlider.d.ts b/ion.rangeSlider/ion.rangeSlider.d.ts new file mode 100644 index 000000000..b60954b3b --- /dev/null +++ b/ion.rangeSlider/ion.rangeSlider.d.ts @@ -0,0 +1,51 @@ +// Type definitions for for Ion.RangeSlider 1.9.1 +// Project: https://github.com/IonDen/ion.rangeSlider/ +// Definitions by: Douglas Eichelberger +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// API documentation: http://ionden.com/a/plugins/ion.rangeSlider/en.html + +interface JQuery { + ionRangeSlider(): JQuery; + ionRangeSlider(options: IonRangeSliderOptions): JQuery; + ionRangeSlider(method: string): JQuery; + ionRangeSlider(method: string, options: IonRangeSliderOptions): JQuery; +} + +interface IonRangeSliderOptions { + disable?: boolean; + from?: number; + hasGrid?: boolean; + hideFromTo?: boolean; + hideMinMax?: boolean; + max?: number; + maxPostfix?: string; + min?: number; + onChange?: (obj: IonRangeSliderEvent) => void; + onFinish?: (obj: IonRangeSliderEvent) => void; + onLoad?: (obj: IonRangeSliderEvent) => void; + postfix?: string; + prefix?: string; + prettify?: boolean; + step?: number; + to?: number; + type?: string; + values?: any[]; +} + +interface IonRangeSliderEvent { + fromNumber: number; + fromPers: number; + fromValue?: any; + fromX: number; + fromX_pure?: number; + input: JQuery; + max: number; + min: number; + slider: JQuery; + toNumber: number; + toPers: number; + toValue?: number; + toX: number; + toX_pure?: number; +} From a9960f762090ba1aa7e59ff8f8f78e1ed04aa51b Mon Sep 17 00:00:00 2001 From: Basarat Ali Syed Date: Sun, 27 Jul 2014 11:19:19 +1000 Subject: [PATCH 186/324] add api doc link --- swig/swig.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/swig/swig.d.ts b/swig/swig.d.ts index c8317ac5c..6255815bd 100644 --- a/swig/swig.d.ts +++ b/swig/swig.d.ts @@ -5,6 +5,8 @@ // Imported from: https://github.com/soywiz/typescript-node-definitions/swig.d.ts +// API Documentation : http://paularmstrong.github.io/swig/docs/api/ + declare module "swig" { export function init(options: Options): void; export function compileFile(filepath: string): any; From 312632f1a4af24b7ae6ceacc0ad2cbab098d28d9 Mon Sep 17 00:00:00 2001 From: damianog Date: Sun, 27 Jul 2014 08:58:58 +0200 Subject: [PATCH 187/324] Update swig.d.ts --- swig/swig.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swig/swig.d.ts b/swig/swig.d.ts index db2353375..3d4e07df1 100644 --- a/swig/swig.d.ts +++ b/swig/swig.d.ts @@ -9,7 +9,7 @@ declare module "swig" { export function init(options: Options): void; export function compileFile(filepath: string): any; export function compile(source: string, options?: Options): any; - export function renderFile(pathName: string, locals: any, cb: (err: any, output: string) => void): string; + export function renderFile(pathName: string, locals?: any, cb?: (err: any, output: string) => void): string; export interface Options { allowErrors?: boolean; From c51cfd5670e04deb30d2e7866293dc210fb15b2f Mon Sep 17 00:00:00 2001 From: rsamec Date: Sun, 27 Jul 2014 09:05:21 +0200 Subject: [PATCH 188/324] node-form typescript definition file added --- CONTRIBUTORS.md | 1 + node-form/node-form-tests.ts | 31 ++ node-form/node-form.d.ts | 681 +++++++++++++++++++++++++++++++++++ 3 files changed, 713 insertions(+) create mode 100644 node-form/node-form-tests.ts create mode 100644 node-form/node-form.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 1eb31acbb..35e2980f7 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -251,6 +251,7 @@ All definitions files include a header with the author and editors, so at some p * [Node.js](http://nodejs.org/) (from TypeScript samples) * [node_redis](https://github.com/mranney/node_redis) (by [Boris Yankov](https://github.com/borisyankov)) * [node-ffi](https://github.com/rbranson/node-ffi) (by [Paul Loyd](https://github.com/loyd)) +* [node-form] (https://github.com/rsamec/form) (by [Roman Samec] (https://github.com/rsamec)) * [node-git](https://github.com/christkv/node-git) (by [vvakame](https://github.com/vvakame)) * [nodeunit](https://github.com/caolan/nodeunit) (by [Jeff Goddard](https://github.com/jedigo)) * [node_zeromq](https://github.com/JustinTulloss/zeromq.node) (by [Dave McKeown](https://github.com/davemckeown)) diff --git a/node-form/node-form-tests.ts b/node-form/node-form-tests.ts new file mode 100644 index 000000000..776014b68 --- /dev/null +++ b/node-form/node-form-tests.ts @@ -0,0 +1,31 @@ +/// +/// +/// +/// + + +export interface IPerson{ + Checked:boolean; + FirstName:string; + LastName:string; + Email:string; +} + +//create custom composite validator +var personValidator = new Validation.AbstractValidator(); + +//create field validators +var required = new Validation.RequiredValidator(); +var email = new Validation.EmailValidator(); +var maxLength = new Validation.MaxLengthValidator(); +maxLength.MaxLength = 15; + + +personValidator.RuleFor("FirstName", required); +personValidator.RuleFor("FirstName", maxLength); + +personValidator.RuleFor("LastName", required); +personValidator.RuleFor("LastName", maxLength); + +personValidator.RuleFor("Email", required); +personValidator.RuleFor("Email", email); diff --git a/node-form/node-form.d.ts b/node-form/node-form.d.ts new file mode 100644 index 000000000..b84236896 --- /dev/null +++ b/node-form/node-form.d.ts @@ -0,0 +1,681 @@ +// Type definitions for node-form v1.0.0 +// Project: https://github.com/rsamec/form +// Definitions by: Roman Samec +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// +/// +declare module Validation { + /** + * It represents a propert y validator for atomic object. + */ + interface IPropertyValidator { + isAcceptable(s: any): boolean; + customMessage? (config: any, args: any): string; + tagName?: string; + } + /** + * It represents a property validator for simple string value. + */ + interface IStringValidator extends IPropertyValidator { + isAcceptable(s: string): boolean; + } + /** + * It represents an async property validator for atomic object. + */ + interface IAsyncPropertyValidator { + isAcceptable(s: any): Q.Promise; + customMessage? (config: any, args: any): string; + isAsync: boolean; + tagName?: string; + } + /** + * It represents an async property validator for simple string value. + */ + interface IAsyncStringPropertyValidator extends IAsyncPropertyValidator { + isAcceptable(s: string): Q.Promise; + } + /** + * It defines compare operators. + */ + enum CompareOperator { + LessThan = 0, + LessThanEqual = 1, + Equal = 2, + NotEqual = 3, + GreaterThanEqual = 4, + GreaterThan = 5, + } + class StringFce { + static format(s: string, args: any): string; + } + class NumberFce { + static GetNegDigits(value: string): number; + } + class LettersOnlyValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class ZipCodeValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class EmailValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class UrlValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class RequiredValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class DateValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class DateISOValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class NumberValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class DigitValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class SignedDigitValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class MinLengthValidator implements IStringValidator { + public MinLength: number; + constructor(MinLength?: number); + public isAcceptable(s: string): boolean; + public tagName: string; + } + class MaxLengthValidator implements IStringValidator { + public MaxLength: number; + constructor(MaxLength?: number); + public isAcceptable(s: string): boolean; + public tagName: string; + } + class RangeLengthValidator implements IStringValidator { + public RangeLength: number[]; + constructor(RangeLength?: number[]); + public isAcceptable(s: string): boolean; + public MinLength : number; + public MaxLength : number; + public tagName: string; + } + class MinValidator implements IPropertyValidator { + public Min: number; + constructor(Min?: number); + public isAcceptable(s: any): boolean; + public tagName: string; + } + class MaxValidator implements IPropertyValidator { + public Max: number; + constructor(Max?: number); + public isAcceptable(s: any): boolean; + public tagName: string; + } + class RangeValidator implements IPropertyValidator { + public Range: number[]; + constructor(Range?: number[]); + public isAcceptable(s: any): boolean; + public Min : number; + public Max : number; + public tagName: string; + } + class StepValidator implements IPropertyValidator { + public Step: string; + constructor(Step?: string); + public isAcceptable(s: any): boolean; + public tagName: string; + } + class PatternValidator implements IStringValidator { + public Pattern: string; + constructor(Pattern?: string); + public isAcceptable(s: string): boolean; + public tagName: string; + } + class ContainsValidator implements IAsyncPropertyValidator { + public Options: Q.Promise; + constructor(Options: Q.Promise); + public isAcceptable(s: string): Q.Promise; + public isAsync: boolean; + public tagName: string; + } +} +declare module Validation { + /** + * basic error structure + */ + interface IError { + HasError: boolean; + ErrorMessage: string; + TranslateArgs?: IErrorTranslateArgs; + } + /** + * support for localization of error messages + */ + interface IErrorTranslateArgs { + TranslateId: string; + MessageArgs: any; + } + /** + * It defines conditional function. + */ + interface IOptional { + (): boolean; + } + /** + * It represents the validation result. + */ + interface IValidationFailure extends IError { + IsAsync: boolean; + Error: IError; + } + /** + * This class provides unit of information about error. + * Implements composite design pattern to enable nesting of error information. + */ + interface IValidationResult { + /** + * The name of error collection. + */ + Name: string; + /** + * Add error information to child collection of errors. + * @param validationResult - error information to be added. + */ + Add(validationResult: IValidationResult): void; + /** + * Remove error information from child collection of errors. + * @param index - index of error information to be removed. + */ + Remove(index: number): void; + /** + * Return collections of child errors information. + */ + Children: IValidationResult[]; + /** + * Return true if there is any error. + */ + HasErrors: boolean; + /** + * Return true if there is any error and hasw dirty state. + */ + HasErrorsDirty: boolean; + /** + * Return error message, if there is no error, return empty string. + */ + ErrorMessage: string; + /** + * Return number of errors. + */ + ErrorCount: number; + /** + * It enables to have errors optional. + */ + Optional?: IOptional; + /** + * It enables support for localization of error messages. + */ + TranslateArgs?: IErrorTranslateArgs[]; + } + /** + * + * @ngdoc object + * @name Error + * @module Validation + * + * + * @description + * It represents basic error structure. + */ + class Error implements IError { + public HasError: boolean; + public ErrorMessage: string; + constructor(); + } + /** + * + * @ngdoc object + * @name ValidationFailure + * @module Validation + * + * + * @description + * It represents validation failure. + */ + class ValidationFailure implements IError { + public Error: IError; + public IsAsync: boolean; + constructor(Error: IError, IsAsync: boolean); + public HasError : boolean; + public ErrorMessage : string; + public TranslateArgs : IErrorTranslateArgs; + } + /** + * + * @ngdoc object + * @name ValidationResult + * @module Validation + * + * + * @description + * It represents simple abstract error object. + */ + class ValidationResult implements IValidationResult { + public Name: string; + constructor(Name: string); + public IsDirty: boolean; + public Children : IValidationResult[]; + public Add(error: IValidationResult): void; + public Remove(index: number): void; + public Optional: IOptional; + public TranslateArgs: IErrorTranslateArgs[]; + public HasErrorsDirty : boolean; + public HasErrors : boolean; + public ErrorCount : number; + public ErrorMessage : string; + } + /** + * + * @ngdoc object + * @name CompositeValidationResult + * @module Validation + * + * + * @description + * It represents composite error object. + */ + class CompositeValidationResult implements IValidationResult { + public Name: string; + public Children: IValidationResult[]; + constructor(Name: string); + public Optional: IOptional; + public AddFirst(error: IValidationResult): void; + public Add(error: IValidationResult): void; + public Remove(index: number): void; + public HasErrorsDirty : boolean; + public HasErrors : boolean; + public ErrorCount : number; + public ErrorMessage : string; + public TranslateArgs : IErrorTranslateArgs[]; + public LogErrors(headerMessage?: string): void; + public Errors : { + [name: string]: IValidationResult; + }; + private FlattenErros; + public SetDirty(): void; + public SetPristine(): void; + private SetDirtyEx(node, dirty); + private flattenErrors(node, errorCollection); + private traverse(node, indent); + } +} +declare module Validation { + /** + * @ngdoc module + * @name Validation + * + * + * @description + * # Validation (core module) + * The module itself contains the essential components for an validation engine to function. The table below + * lists a high level breakdown of each of the components (object, functions) available within this core module. + * + *
+ */ + /** + * It defines validation function. + */ + interface IValidate { + (args: IError): void; + } + /** + * It represents named validation function. + */ + interface IValidatorFce { + Name: string; + ValidationFce: IValidate; + } + /** + * This class represents custom validator. + */ + interface IValidator { + Validate(context: any): boolean; + Error: IError; + } + /** + * It represents abstract validator for type of . + */ + interface IAbstractValidator { + RuleFor(prop: string, validator: IPropertyValidator): any; + ValidationFor(prop: string, validator: IValidatorFce): any; + ValidatorFor(prop: string, validator: IAbstractValidator): any; + /** + * It creates new concrete validation rule and assigned data context to this rule. + * @param name of the rule + * @constructor + */ + CreateRule(name: string): IAbstractValidationRule; + CreateAbstractRule(name: string): IAbstractValidationRule; + CreateAbstractListRule(name: string): IAbstractValidationRule; + /** + * return true if this validation rule is intended for list of items, otherwise true + */ + ForList: boolean; + } + /** + * It represents concrete validation rule for type of . + */ + interface IAbstractValidationRule { + /** + * Performs validation using a validation context and returns a collection of Validation Failures. + */ + Validate(context: T): IValidationResult; + /** + * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. + */ + ValidateAsync(context: T): Q.Promise; + /** + * Performs validation and async validation using a validation context. + */ + ValidateAll(context: T): void; + /** + * Performs validation and async validation using a validation context for a passed field. + */ + ValidateField(context: T, propName: string): void; + /** + * Return validation results. + */ + ValidationResult: IValidationResult; + Rules: { + [name: string]: IPropertyValidationRule; + }; + Validators: { + [name: string]: IValidator; + }; + Children: { + [name: string]: AbstractValidationRule; + }; + } + /** + * It represents property validation rule for type of . + */ + interface IPropertyValidationRule { + /** + *The validators that are grouped under this rule. + */ + Validators: { + [name: string]: any; + }; + /** + * Performs validation using a validation context and returns a collection of Validation Failures. + */ + Validate(context: IValidationContext): IValidationFailure[]; + /** + * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. + */ + ValidateAsync(context: IValidationContext): Q.Promise; + } + /** + * It represents a data context for validation rule. + */ + interface IValidationContext { + /** + * Return current value. + */ + Value: string; + /** + * Return property name for current data context. + */ + Key: string; + /** + * Data context for validation rule. + */ + Data: T; + } + /** + * + * @ngdoc object + * @name AbstractValidator + * @module Validation + * + * + * @description + * It enables to create custom validator for your own abstract object (class) and to assign validation rules to its properties. + * You can assigned these rules + * + * + property validation rules - use _RuleFor_ property + * + property async validation rules - use _RuleFor_ property + * + shared validation rules - use _ValidationFor_ property + * + custom object validator - use _ValidatorFor_ property - enables composition of child custom validators + */ + class AbstractValidator implements IAbstractValidator { + public Validators: { + [name: string]: IPropertyValidator[]; + }; + public AbstractValidators: { + [name: string]: IAbstractValidator; + }; + public ValidationFunctions: { + [name: string]: IValidatorFce[]; + }; + public RuleFor(prop: string, validator: IPropertyValidator): void; + public ValidationFor(prop: string, fce: IValidatorFce): void; + public ValidatorFor(prop: string, validator: IAbstractValidator, forList?: boolean): void; + public CreateAbstractRule(name: string): AbstractValidationRule; + public CreateAbstractListRule(name: string): AbstractListValidationRule; + public CreateRule(name: string): AbstractValidationRule; + /** + * Return true if this validation rule is intended for list of items, otherwise true. + */ + public ForList: boolean; + } + /** + * + * @ngdoc object + * @name AbstractValidationRule + * @module Validation + * + * + * @description + * It represents concreate validator for custom object. It enables to assign validation rules to custom object properties. + */ + class AbstractValidationRule implements IAbstractValidationRule { + public Name: string; + public validator: AbstractValidator; + public ValidationResult: IValidationResult; + public Rules: { + [name: string]: IPropertyValidationRule; + }; + public Validators: { + [name: string]: IValidator; + }; + public Children: { + [name: string]: AbstractValidationRule; + }; + /** + * Return true if this validation rule is intended for list of items, otherwise true. + */ + public ForList: boolean; + constructor(Name: string, validator: AbstractValidator, forList?: boolean); + public addChildren(): void; + public SetOptional(fce: IOptional): void; + private createRuleFor(prop); + /** + * Performs validation using a validation context and returns a collection of Validation Failures. + */ + public Validate(context: T): IValidationResult; + /** + * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. + */ + public ValidateAsync(context: T): Q.Promise; + public ValidateAll(context: T): void; + public ValidateField(context: T, propName: string): void; + } + /** + * + * @ngdoc object + * @name AbstractListValidationRule + * @module Validation + * + * + * @description + * It represents an validator for custom object. It enables to assign rules to custom object properties. + */ + class AbstractListValidationRule extends AbstractValidationRule { + public Name: string; + public validator: AbstractValidator; + constructor(Name: string, validator: AbstractValidator); + /** + * Performs validation using a validation context and returns a collection of Validation Failures. + */ + public Validate(context: any): IValidationResult; + /** + * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. + */ + public ValidateAsync(context: any): Q.Promise; + private getValidationRule(i); + private getIndexedKey(i); + public NotifyListChanged(list: any[]): void; + } + /** + * + * @ngdoc object + * @name ValidationContext + * @module Validation + * + * + * @description + * It represents a data context for validation rule. + */ + class ValidationContext implements IValidationContext { + public Key: string; + public Data: T; + constructor(Key: string, Data: T); + public Value : any; + } + class MessageLocalization { + static customMsg: string; + static defaultMessages: { + "required": string; + "remote": string; + "email": string; + "url": string; + "date": string; + "dateISO": string; + "number": string; + "digits": string; + "signedDigits": string; + "creditcard": string; + "equalTo": string; + "maxlength": string; + "minlength": string; + "rangelength": string; + "range": string; + "max": string; + "min": string; + "step": string; + "contains": string; + "mask": string; + "custom": string; + }; + static ValidationMessages: { + "required": string; + "remote": string; + "email": string; + "url": string; + "date": string; + "dateISO": string; + "number": string; + "digits": string; + "signedDigits": string; + "creditcard": string; + "equalTo": string; + "maxlength": string; + "minlength": string; + "rangelength": string; + "range": string; + "max": string; + "min": string; + "step": string; + "contains": string; + "mask": string; + "custom": string; + }; + static GetValidationMessage(validator: any): string; + } + /** + * + * @ngdoc object + * @name PropertyValidationRule + * @module Validation + * + * + * @description + * It represents a property validation rule. The property has assigned collection of property validators. + */ + class PropertyValidationRule extends ValidationResult implements IPropertyValidationRule { + public Name: string; + public Validators: { + [name: string]: any; + }; + public ValidationFailures: { + [name: string]: IValidationFailure; + }; + constructor(Name: string, validatorsToAdd?: IPropertyValidator[]); + public AddValidator(validator: any): void; + public Errors : IError[]; + public HasErrors : boolean; + public ErrorCount : number; + public ErrorMessage : string; + public TranslateArgs : IErrorTranslateArgs[]; + /** + * Performs validation using a validation context and returns a collection of Validation Failures. + */ + public Validate(context: IValidationContext): IValidationFailure[]; + public ValidateEx(value: any): IValidationFailure[]; + /** + * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. + */ + public ValidateAsync(context: IValidationContext): Q.Promise; + /** + * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. + */ + public ValidateAsyncEx(value: string): Q.Promise; + } + /** + * + * @ngdoc object + * @name Validator + * @module Validation + * + * + * @description + * It represents a custom validator. It enables to define your own shared validation rules + */ + class Validator extends ValidationResult implements IValidator { + public Name: string; + private ValidateFce; + public Error: IError; + constructor(Name: string, ValidateFce: IValidate); + public Optional: IOptional; + public Validate(context: any): boolean; + public HasError : boolean; + public HasErrors : boolean; + public ErrorCount : number; + public ErrorMessage : string; + public TranslateArgs : IErrorTranslateArgs[]; + } +} From 45f3f63865b75968ce1aade8d771aad94b849170 Mon Sep 17 00:00:00 2001 From: MIZUNE Pine Date: Mon, 28 Jul 2014 04:10:48 +0900 Subject: [PATCH 189/324] Add chrome.sockets.* --- chrome/chrome-app.d.ts | 188 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 187 insertions(+), 1 deletion(-) diff --git a/chrome/chrome-app.d.ts b/chrome/chrome-app.d.ts index ad319394f..e82de28b2 100644 --- a/chrome/chrome-app.d.ts +++ b/chrome/chrome-app.d.ts @@ -1,6 +1,6 @@ // Type definitions for Chrome packaged application development // Project: http://developer.chrome.com/apps/ -// Definitions by: Adam Lay +// Definitions by: Adam Lay , MIZUNE Pine // Definitions: https://github.com/borisyankov/DefinitelyTyped //////////////////// @@ -93,3 +93,189 @@ declare module chrome.app.window { var onMinimized: WindowEvent; var onRestored: WindowEvent; } + + +//////////////////// +// Sockets +//////////////////// +declare module chrome.sockets.tcp { + interface CreateInfo { + socketId: number; + } + + interface SendInfo { + resultCode: number; + bytesSent?: number; + } + + interface Event { + addListener(callback: (info: T) => void): void; + } + + interface ReceiveEventArgs { + socketId: number; + data: ArrayBuffer; + } + + interface ReceiveErrorEventArgs { + socketId: number; + resultCode: number; + } + + interface SocketProperties { + persistent?: boolean; + name?: string; + bufferSize?: number; + } + + interface SocketInfo { + socketId: number; + persistent: boolean; + name?: string; + bufferSize?: number; + paused: boolean; + connected: boolean; + localAddress?: string; + localPort?: number; + peerAddress?: string; + peerPort?: number; + } + + export function create(callback: (createInfo: CreateInfo) => void): void; + export function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; + + export function update(socketId: number, properties: SocketProperties, callback?: () => void): void; + export function setPaused(socketId: number, paused: boolean, callback: () => void): void; + + export function setKeepAlive(socketId: number, + enable: boolean, callback: (result: number) => void): void; + export function setKeepAlive(socketId: number, + enable: boolean, delay: number, callback: (result: number) => void): void; + + export function setNoDelay(socketId: number, + peerAddress: string, peerPort: number, callback: (result: number) => void): void; + export function disconnect(socketId: number, callback?: () => void): void; + export function send(socketId: number, data: ArrayBuffer, callback: (sendInfo: SendInfo) => void): void; + export function close(socketId: number, callback?: () => void): void; + export function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; + export function getSockets(socketId: number, callback: (socketInfos: SocketInfo[]) => void): void; + + var onReceive: Event; + var onReceiveError: Event; +} + +declare module chrome.sockets.udp { + interface CreateInfo { + socketId: number; + } + + interface SendInfo { + resultCode: number; + bytesSent?: number; + } + + interface Event { + addListener(callback: (info: T) => void): void; + } + + interface ReceiveEventArgs { + socketId: number; + data: ArrayBuffer; + remoteAddress: string; + remotePort: number; + } + + interface ReceiveErrorEventArgs { + socketId: number; + resultCode: number; + } + + interface SocketProperties { + persistent?: boolean; + name?: string; + bufferSize?: number; + } + + interface SocketInfo { + socketId: number; + persistent: boolean; + name?: string; + bufferSize?: number; + paused: boolean; + connected: boolean; + localAddress?: string; + localPort?: number; + } + + export function create(callback: (createInfo: CreateInfo) => void): void; + export function create(properties: SocketProperties, + callback: (createInfo: CreateInfo) => void): void; + + export function update(socketId: number, properties: SocketProperties, callback?: () => void): void; + export function setPaused(socketId: number, paused: boolean, callback?: () => void): void; + export function bind(socketId: number, address: string, port: number, callback: (result: number) => void): void; + export function send(socketId: number, data: ArrayBuffer, address: string, port: number, callback: (sendInfo: SendInfo) => void): void; + export function close(socketId: number, callback?: () => void): void; + export function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; + export function getSockets(callback: (socketInfos: SocketInfo[]) => void): void; + export function joinGroup(socketId: number, address: string, callback: (result: number) => void): void; + export function leaveGroup(socketId: number, address: string, callback: (result: number) => void): void; + export function setMulticastTimeToLive(socketId: number, ttl: number, callback: (result: number) => void): void; + export function setMulticastLoopbackMode(socketId: number, enabled: boolean, callback: (result: number) => void): void; + export function getJoinedGroups(socketId: number, callback: (groups: string[]) => void): void; + + var onReceive: Event; + var onReceiveError: Event; +} + +declare module chrome.sockets.tcpServer { + interface CreateInfo { + socketId: number; + } + + interface Event { + addListener(callback: (info: T) => void): void; + } + + interface AcceptEventArgs { + socketId: number; + clientSocketId: number; + } + + interface AcceptErrorEventArgs { + socketId: number; + resultCode: number; + } + + interface SocketProperties { + persistent?: boolean; + name?: string; + } + + interface SocketInfo { + socketId: number; + persistent: boolean; + name?: string; + paused: boolean; + localAddress?: string; + localPort?: number; + } + + export function create(callback: (createInfo: CreateInfo) => void): void; + export function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; + + export function update(socketId: number, properties: SocketProperties, callback?: () => void): void; + export function setPaused(socketId: number, paused: boolean, callback: () => void): void; + + export function listen(socketId: number, address: string, + port: number, backlog: number, callback: (result: number) => void): void; + export function listen(socketId: number, address: string, + port: number, callback: (result: number) => void): void; + + export function disconnect(socketId: number, callback?: () => void): void; + export function close(socketId: number, callback?: () => void): void; + export function getInfo(socketId: number, callback: (socketInfos: SocketInfo[]) => void): void; + + var onAccept: Event; + var onAcceptError: Event; +} \ No newline at end of file From 9084225d447d22acdee8b0102274e92b8f4bbebf Mon Sep 17 00:00:00 2001 From: rsamec Date: Mon, 28 Jul 2014 08:36:08 +0200 Subject: [PATCH 190/324] explicitly define node-form module with export = Validation --- node-form/node-form.d.ts | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/node-form/node-form.d.ts b/node-form/node-form.d.ts index b84236896..8c9bc73a8 100644 --- a/node-form/node-form.d.ts +++ b/node-form/node-form.d.ts @@ -1,14 +1,9 @@ -// Type definitions for node-form v1.0.0 -// Project: https://github.com/rsamec/form -// Definitions by: Roman Samec -// Definitions: https://github.com/borisyankov/DefinitelyTyped - /// /// /// declare module Validation { /** - * It represents a propert y validator for atomic object. + * It represents a property validator for atomic object. */ interface IPropertyValidator { isAcceptable(s: any): boolean; @@ -163,11 +158,18 @@ declare module Validation { TranslateArgs?: IErrorTranslateArgs; } /** + * Custom message functions. + */ + interface IErrorCustomMessage { + (config: any, args: any): string; + } + /** * support for localization of error messages */ interface IErrorTranslateArgs { TranslateId: string; MessageArgs: any; + CustomMessage?: IErrorCustomMessage; } /** * It defines conditional function. @@ -636,7 +638,9 @@ declare module Validation { }; constructor(Name: string, validatorsToAdd?: IPropertyValidator[]); public AddValidator(validator: any): void; - public Errors : IError[]; + public Errors : { + [name: string]: IValidationFailure; + }; public HasErrors : boolean; public ErrorCount : number; public ErrorMessage : string; @@ -669,13 +673,22 @@ declare module Validation { public Name: string; private ValidateFce; public Error: IError; + public ValidationFailures: { + [name: string]: IValidationFailure; + }; constructor(Name: string, ValidateFce: IValidate); public Optional: IOptional; public Validate(context: any): boolean; public HasError : boolean; + public Errors : { + [name: string]: IValidationFailure; + }; public HasErrors : boolean; public ErrorCount : number; public ErrorMessage : string; public TranslateArgs : IErrorTranslateArgs[]; } } +declare module "node-form" { + export = Validation ; +} \ No newline at end of file From 76781c4c859386006983e34c1046c43f143cb901 Mon Sep 17 00:00:00 2001 From: rsamec Date: Mon, 28 Jul 2014 08:47:12 +0200 Subject: [PATCH 191/324] explicitly define node-form module with export = Validation --- node-form/node-form.d.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/node-form/node-form.d.ts b/node-form/node-form.d.ts index 8c9bc73a8..96fab7001 100644 --- a/node-form/node-form.d.ts +++ b/node-form/node-form.d.ts @@ -2,12 +2,18 @@ /// /// declare module Validation { + /** + * Custom message functions. + */ + interface IErrorCustomMessage { + (config: any, args: any): string; + } /** * It represents a property validator for atomic object. */ interface IPropertyValidator { isAcceptable(s: any): boolean; - customMessage? (config: any, args: any): string; + customMessage?: IErrorCustomMessage; tagName?: string; } /** @@ -21,7 +27,7 @@ declare module Validation { */ interface IAsyncPropertyValidator { isAcceptable(s: any): Q.Promise; - customMessage? (config: any, args: any): string; + customMessage?: IErrorCustomMessage; isAsync: boolean; tagName?: string; } @@ -158,12 +164,6 @@ declare module Validation { TranslateArgs?: IErrorTranslateArgs; } /** - * Custom message functions. - */ - interface IErrorCustomMessage { - (config: any, args: any): string; - } - /** * support for localization of error messages */ interface IErrorTranslateArgs { @@ -690,5 +690,5 @@ declare module Validation { } } declare module "node-form" { - export = Validation ; +export = Validation ; } \ No newline at end of file From c320d0fac2fad31e762ff9931cd292928307a010 Mon Sep 17 00:00:00 2001 From: rsamec Date: Mon, 28 Jul 2014 09:25:35 +0200 Subject: [PATCH 192/324] explicitly define node-form module with export = Validation --- node-form/node-form.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/node-form/node-form.d.ts b/node-form/node-form.d.ts index 96fab7001..d75e313cd 100644 --- a/node-form/node-form.d.ts +++ b/node-form/node-form.d.ts @@ -1,3 +1,8 @@ +// Type definitions for node-form v1.0.6 +// Project: https://github.com/rsamec/form +// Definitions by: Roman Samec +// Definitions: https://github.com/borisyankov/DefinitelyTyped + /// /// /// From 4bd26e0a11d78732670f081984dfe2ebcc0f9b35 Mon Sep 17 00:00:00 2001 From: MIZUNE Pine Date: Mon, 28 Jul 2014 23:17:35 +0900 Subject: [PATCH 193/324] Fix bug --- chrome/chrome-app.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/chrome/chrome-app.d.ts b/chrome/chrome-app.d.ts index e82de28b2..830b26e4f 100644 --- a/chrome/chrome-app.d.ts +++ b/chrome/chrome-app.d.ts @@ -145,14 +145,15 @@ declare module chrome.sockets.tcp { export function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; export function update(socketId: number, properties: SocketProperties, callback?: () => void): void; - export function setPaused(socketId: number, paused: boolean, callback: () => void): void; + export function setPaused(socketId: number, paused: boolean, callback?: () => void): void; export function setKeepAlive(socketId: number, enable: boolean, callback: (result: number) => void): void; export function setKeepAlive(socketId: number, enable: boolean, delay: number, callback: (result: number) => void): void; - export function setNoDelay(socketId: number, + export function setNoDelay(socketId: number, noDelay: boolean, callback: (result: number) => void): void; + export function connect(socketId: number, peerAddress: string, peerPort: number, callback: (result: number) => void): void; export function disconnect(socketId: number, callback?: () => void): void; export function send(socketId: number, data: ArrayBuffer, callback: (sendInfo: SendInfo) => void): void; @@ -202,7 +203,6 @@ declare module chrome.sockets.udp { name?: string; bufferSize?: number; paused: boolean; - connected: boolean; localAddress?: string; localPort?: number; } @@ -265,7 +265,7 @@ declare module chrome.sockets.tcpServer { export function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; export function update(socketId: number, properties: SocketProperties, callback?: () => void): void; - export function setPaused(socketId: number, paused: boolean, callback: () => void): void; + export function setPaused(socketId: number, paused: boolean, callback?: () => void): void; export function listen(socketId: number, address: string, port: number, backlog: number, callback: (result: number) => void): void; From f4dbe8f1e780cd583c038879b18ae9dcb442573c Mon Sep 17 00:00:00 2001 From: MIZUNE Pine Date: Mon, 28 Jul 2014 23:17:55 +0900 Subject: [PATCH 194/324] Add tests --- chrome/chrome-app-tests.ts | 251 ++++++++++++++++++++++++++++++++++++- 1 file changed, 250 insertions(+), 1 deletion(-) diff --git a/chrome/chrome-app-tests.ts b/chrome/chrome-app-tests.ts index 0ae0ae2af..12dc7b97d 100644 --- a/chrome/chrome-app-tests.ts +++ b/chrome/chrome-app-tests.ts @@ -24,4 +24,253 @@ chrome.app.runtime.onLaunched.addListener(function (launchData: runtime.LaunchDa chrome.app.runtime.onRestarted.addListener(function () { return; }); // Get Current Window -var currentWindow: cwindow.AppWindow = chrome.app.window.current(); \ No newline at end of file +var currentWindow: cwindow.AppWindow = chrome.app.window.current(); + +// Sockets +// https://developer.chrome.com/apps/sockets_tcp +function test_socketsTcp(): void { + var socketId: number; + var properties: chrome.sockets.tcp.SocketProperties = {}; + var buffer: ArrayBuffer = new ArrayBuffer(256); + + // create + chrome.sockets.tcp.create((info) => { + socketId = info.socketId; + }); + + chrome.sockets.tcp.create(properties, (info) => { + socketId = info.socketId; + }); + + // update + chrome.sockets.tcp.update(socketId, properties); + chrome.sockets.tcp.update(socketId, properties, () => { }); + + // setPaused + chrome.sockets.tcp.setPaused(socketId, true); + chrome.sockets.tcp.setPaused(socketId, true, () => { }); + + // setKeepAlive + chrome.sockets.tcp.setKeepAlive(socketId, true, (result: number) => { }); + chrome.sockets.tcp.setKeepAlive(socketId, true, 0, (result: number) => { }); + + // setNoDelay + chrome.sockets.tcp.setNoDelay(socketId, true, (result: number) => { }); + + // connect + chrome.sockets.tcp.connect(socketId, "192.168.0.1", 8080, (result: number) => { }); + + // disconnect + chrome.sockets.tcp.disconnect(socketId); + chrome.sockets.tcp.disconnect(socketId, () => { }); + + // send + chrome.sockets.tcp.send(socketId, buffer, (info: chrome.sockets.tcp.SendInfo) => { }); + + // close + chrome.sockets.tcp.close(socketId); + chrome.sockets.tcp.close(socketId, () => { }); + + // getInfo + chrome.sockets.tcp.getInfo(socketId, (info: chrome.sockets.tcp.SocketInfo) => { }); + + // getSockets + chrome.sockets.tcp.getSockets(socketId, (infos: chrome.sockets.tcp.SocketInfo[]) => { }); +} + +function test_socketsTcpEvents(): void { + chrome.sockets.tcp.onReceive.addListener((info: chrome.sockets.tcp.ReceiveEventArgs) => { }); + chrome.sockets.tcp.onReceiveError.addListener((info: chrome.sockets.tcp.ReceiveErrorEventArgs) => { }); +} + +function testSocketsTcpTypes(): void { + // SocketProperties + var properties: chrome.sockets.tcp.SocketProperties; + + properties = { + }; + + properties = { + persistent: true, + name: "test", + bufferSize: 1024 + }; + + // SocketInfo + var socketInfo: chrome.sockets.tcp.SocketInfo; + + socketInfo = { + socketId: 1, + persistent: true, + paused: true, + connected: false + }; + + socketInfo.name = "test"; + socketInfo.bufferSize = 1024; + socketInfo.localAddress = "192.168.0.2"; + socketInfo.localPort = 8000; + socketInfo.peerAddress = "192.168.0.3"; + socketInfo.peerPort = 1000; +} + +// https://developer.chrome.com/apps/sockets_udp +function test_socketsUdp(): void { + var socketId: number; + var properties: chrome.sockets.udp.SocketProperties = {}; + var buffer: ArrayBuffer = new ArrayBuffer(256); + + // create + chrome.sockets.udp.create((info) => { + socketId = info.socketId; + }); + + chrome.sockets.udp.create(properties, (info) => { + socketId = info.socketId; + }); + + // update + chrome.sockets.udp.update(socketId, properties); + chrome.sockets.udp.update(socketId, properties, () => { }); + + // setPaused + chrome.sockets.udp.setPaused(socketId, true); + chrome.sockets.udp.setPaused(socketId, true, () => { }); + + // bind + chrome.sockets.udp.bind(socketId, "0.0.0.0", 8080, (result: number) => { }); + + // send + chrome.sockets.udp.send(socketId, buffer, "172.21.0.1", 10080, (info: chrome.sockets.udp.SendInfo) => { }); + + // close + chrome.sockets.udp.close(socketId); + chrome.sockets.udp.close(socketId, () => { }); + + // getInfo + chrome.sockets.udp.getInfo(socketId, (info: chrome.sockets.udp.SocketInfo) => { }); + + // getSockets + chrome.sockets.udp.getSockets((infos: chrome.sockets.udp.SocketInfo[]) => { }); + + // joinGroup + chrome.sockets.udp.joinGroup(socketId, "224.0.0.1", (result: number) => { }); + + // leaveGroup + chrome.sockets.udp.leaveGroup(socketId, "224.0.0.1", (result: number) => { }); + + // setMulticastTimeToLive + chrome.sockets.udp.setMulticastTimeToLive(socketId, 100, (result: number) => { }); + + // setMulticastLoopbackMode + chrome.sockets.udp.setMulticastLoopbackMode(socketId, true, (result: number) => { }); + + // getJoinedGroups + chrome.sockets.udp.getJoinedGroups(socketId, (groups: string[]) => { }); +} + +function test_socketsUdpEvents(): void { + chrome.sockets.udp.onReceive.addListener((info: chrome.sockets.udp.ReceiveEventArgs) => { }); + chrome.sockets.udp.onReceiveError.addListener((info: chrome.sockets.udp.ReceiveErrorEventArgs) => { }); +} + +function testSocketsUdpTypes(): void { + // SocketProperties + var properties: chrome.sockets.udp.SocketProperties; + + properties = { + }; + + properties = { + persistent: true, + name: "test", + bufferSize: 1024 + }; + + // SocketInfo + var socketInfo: chrome.sockets.udp.SocketInfo; + + socketInfo = { + socketId: 1, + persistent: true, + paused: true + }; + + socketInfo.name = "test"; + socketInfo.bufferSize = 1024; + socketInfo.localAddress = "192.168.0.2"; + socketInfo.localPort = 8000; +} + +// https://developer.chrome.com/apps/sockets_tcpServer +function test_socketsTcpServer(): void { + var socketId: number; + var properties: chrome.sockets.tcpServer.SocketProperties = {}; + var buffer: ArrayBuffer = new ArrayBuffer(256); + + // create + chrome.sockets.tcpServer.create((info) => { + socketId = info.socketId; + }); + + chrome.sockets.tcpServer.create(properties, (info) => { + socketId = info.socketId; + }); + + // update + chrome.sockets.tcpServer.update(socketId, properties); + chrome.sockets.tcpServer.update(socketId, properties, () => { }); + + // setPaused + chrome.sockets.tcpServer.setPaused(socketId, true); + chrome.sockets.tcpServer.setPaused(socketId, true, () => { }); + + // listen + chrome.sockets.tcpServer.listen(socketId, "0.0.0.0", 80, (result: number) => { }); + chrome.sockets.tcpServer.listen(socketId, "0.0.0.0", 80, 128, (result: number) => { }); + + // disconnect + chrome.sockets.tcp.disconnect(socketId); + chrome.sockets.tcp.disconnect(socketId, () => { }); + + // close + chrome.sockets.udp.close(socketId); + chrome.sockets.udp.close(socketId, () => { }); + + // getInfo + chrome.sockets.udp.getInfo(socketId, (info: chrome.sockets.udp.SocketInfo) => { }); + + // getSockets + chrome.sockets.tcp.getSockets(socketId, (infos: chrome.sockets.tcp.SocketInfo[]) => { }); +} + +function test_socketsTcpServerEvents(): void { + chrome.sockets.tcpServer.onAccept.addListener((info: chrome.sockets.tcpServer.AcceptEventArgs) => { }); + chrome.sockets.tcpServer.onAcceptError.addListener((info: chrome.sockets.tcpServer.AcceptErrorEventArgs) => { }); +} + +function testSocketsTcpServerTypes(): void { + // SocketProperties + var properties: chrome.sockets.tcpServer.SocketProperties; + + properties = { + }; + + properties = { + persistent: true, + name: "test" + }; + + // SocketInfo + var socketInfo: chrome.sockets.tcpServer.SocketInfo; + + socketInfo = { + socketId: 1, + persistent: true, + paused: true + }; + + socketInfo.name = "test"; + socketInfo.localAddress = "192.168.0.2"; + socketInfo.localPort = 8000; +} From 61144d85fd840981dee0221ac875008ee9eb5633 Mon Sep 17 00:00:00 2001 From: Daniel Mane Date: Mon, 28 Jul 2014 13:41:43 -0700 Subject: [PATCH 195/324] Rename "QuantitiveScale" to "QuantitativeScale" for consistency with d3's API docs and common usage of the english language. Close #2573 --- d3/d3.d.ts | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 598cd9f34..0354bc264 100755 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -749,7 +749,7 @@ declare module D3 { insert: (name: string, before: string) => Selection; remove: () => Selection; empty: () => boolean; - + data: { (values: (data: any, index?: number) => any[], key?: (data: any, index?: number) => any): UpdateSelection; (values: any[], key?: (data: any, index?: number) => any): UpdateSelection; @@ -2508,7 +2508,7 @@ declare module D3 { copy(): Scale; } - export interface QuantitiveScale extends Scale { + export interface QuantitativeScale extends Scale { /** * Get the range value corresponding to a given domain value. * @@ -2530,7 +2530,7 @@ declare module D3 { * * @param value The input domain */ - (values: any[]): QuantitiveScale; + (values: any[]): QuantitativeScale; /** * Get the scale's input domain. */ @@ -2545,7 +2545,7 @@ declare module D3 { * * @param value The output range. */ - (values: any[]): QuantitiveScale; + (values: any[]): QuantitativeScale; /** * Get the scale's output range. */ @@ -2556,26 +2556,26 @@ declare module D3 { * * @param value The output range. */ - rangeRound: (values: any[]) => QuantitiveScale; + rangeRound: (values: any[]) => QuantitativeScale; /** * get or set the scale's output interpolator. */ interpolate: { (): D3.Transition.Interpolate; - (factory: D3.Transition.Interpolate): QuantitiveScale; + (factory: D3.Transition.Interpolate): QuantitativeScale; }; /** * enable or disable clamping of the output range. * * @param clamp Enable or disable */ - clamp(clamp: boolean): QuantitiveScale; + clamp(clamp: boolean): QuantitativeScale; /** * extend the scale domain to nice round numbers. - * + * * @param count Optional number of ticks to exactly fit the domain */ - nice(count?: number): QuantitiveScale; + nice(count?: number): QuantitativeScale; /** * get representative values from the input domain. * @@ -2591,10 +2591,10 @@ declare module D3 { /** * create a new scale from an existing scale.. */ - copy(): QuantitiveScale; + copy(): QuantitativeScale; } - export interface LinearScale extends QuantitiveScale { + export interface LinearScale extends QuantitativeScale { /** * Get the range value corresponding to a given domain value. * @@ -2630,7 +2630,7 @@ declare module D3 { tickFormat(count: number): (n: number) => string; } - export interface SqrtScale extends QuantitiveScale { + export interface SqrtScale extends QuantitativeScale { /** * Get the range value corresponding to a given domain value. * @@ -2639,7 +2639,7 @@ declare module D3 { (value: number): number; } - export interface PowScale extends QuantitiveScale { + export interface PowScale extends QuantitativeScale { /** * Get the range value corresponding to a given domain value. * @@ -2648,7 +2648,7 @@ declare module D3 { (value: number): number; } - export interface LogScale extends QuantitiveScale { + export interface LogScale extends QuantitativeScale { /** * Get the range value corresponding to a given domain value. * @@ -3417,7 +3417,7 @@ declare module D3 { * * @param constant The new constant value. */ - (constant: number): Voronoi; + (constant: number): Voronoi; } clipExtent: { /** From 2d73f7313823d22ad7434872110c207eb58bda6c Mon Sep 17 00:00:00 2001 From: Niklas Mollenhauer Date: Mon, 28 Jul 2014 23:22:10 +0200 Subject: [PATCH 196/324] Add getVideoData() + interfaces --- youtube/youtube.d.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/youtube/youtube.d.ts b/youtube/youtube.d.ts index 3f21dcb86..44e98dd84 100644 --- a/youtube/youtube.d.ts +++ b/youtube/youtube.d.ts @@ -71,6 +71,13 @@ declare module YT { suggestedQuality?: string; } + export interface VideoData + { + video_id: string; + author: string; + title: string; + } + export class Player { // Constructor constructor(id: string, playerOptions: PlayerOptions); @@ -132,6 +139,7 @@ declare module YT { getDuration(): number; getVideoUrl(): string; getVideoEmbedCode(): string; + getVideoData(): VideoData; // Playlist getPlaylist(): any[]; From 7f47a884ea46c73ca44078e960aefc8b3f4fe9a1 Mon Sep 17 00:00:00 2001 From: Niklas Mollenhauer Date: Mon, 28 Jul 2014 23:22:29 +0200 Subject: [PATCH 197/324] Remove trailing spaces from empty lines --- youtube/youtube.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/youtube/youtube.d.ts b/youtube/youtube.d.ts index 44e98dd84..cfdba0efb 100644 --- a/youtube/youtube.d.ts +++ b/youtube/youtube.d.ts @@ -95,7 +95,7 @@ declare module YT { // Properties size; - + // Playing playVideo(): void; pauseVideo(): void; @@ -122,7 +122,7 @@ declare module YT { getPlaybackRate(): number; setPlaybackRate(suggestedRate:number): void; getAvailablePlaybackRates(): number[]; - + // Behavior setLoop(loopPlaylists: boolean): void; setShuffle(shufflePlaylist: boolean): void; @@ -144,7 +144,7 @@ declare module YT { // Playlist getPlaylist(): any[]; getPlaylistIndex(): number; - + // Event Listener addEventListener(event: string, listener: string): void; } From 22894235a23f59f738278398144d9fc57c002cd9 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Tue, 29 Jul 2014 11:08:28 +0100 Subject: [PATCH 198/324] Add genericised forEach and indexer for FormController --- angularjs/angular-tests.ts | 9 ++++++++ angularjs/angular.d.ts | 45 ++++++++++++++++++++++++++++++++++---- 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 7f1e6edf9..1502ac963 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -251,6 +251,15 @@ httpFoo.then((x) => { }); +function test_angular_forEach() { + var values: { [key: string]: string } = { name: 'misko', gender: 'male' }; + var log = []; + angular.forEach(values, function (value, key) { + this.push(key + ': ' + value); + }, log); + //expect(log).toEqual(['name: misko', 'gender: male']); +} + // angular.element() tests var element = angular.element("div.myApp"); var scope: ng.IScope = element.scope(); diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index ca8751b8e..c515b096f 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -46,7 +46,38 @@ declare module ng { element: IAugmentedJQueryStatic; equals(value1: any, value2: any): boolean; extend(destination: any, ...sources: any[]): any; + + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ + forEach(obj: T[], iterator: (value: T, key: number) => any, context?: any): any; + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ + forEach(obj: { [index: string]: T; }, iterator: (value: T, key: string) => any, context?: any): any; + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ forEach(obj: any, iterator: (value: any, key: any) => any, context?: any): any; + fromJson(json: string): any; identity(arg?: any): any; injector(modules?: any[]): auto.IInjectorService; @@ -221,11 +252,17 @@ declare module ng { $attr: Object; } - /////////////////////////////////////////////////////////////////////////// - // FormController - // see http://docs.angularjs.org/api/ng.directive:form.FormController - /////////////////////////////////////////////////////////////////////////// + /** + * form.FormController - type in module ng + * see https://docs.angularjs.org/api/ng/type/form.FormController + */ interface IFormController { + + /** + * Indexer which should return ng.INgModelController for most properties but cannot because of "All named properties must be assignable to string indexer type" constraint - see https://github.com/Microsoft/TypeScript/issues/272 + */ + [name: string]: any; + $pristine: boolean; $dirty: boolean; $valid: boolean; From 68a3cb28753ddce6c9d9b1ea0f3dc5c5a9d3e42f Mon Sep 17 00:00:00 2001 From: John Reilly Date: Tue, 29 Jul 2014 11:21:28 +0100 Subject: [PATCH 199/324] Fix test --- angularjs/angular-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 1502ac963..d7f2a5bd5 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -254,7 +254,7 @@ httpFoo.then((x) => { function test_angular_forEach() { var values: { [key: string]: string } = { name: 'misko', gender: 'male' }; var log = []; - angular.forEach(values, function (value, key) { + angular.forEach(values, function (value: string, key: string) { this.push(key + ': ' + value); }, log); //expect(log).toEqual(['name: misko', 'gender: male']); From 86d681f2890170baae4a47016fb3bf01dcdc41d0 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Tue, 29 Jul 2014 11:26:06 +0100 Subject: [PATCH 200/324] Fix test --- angularjs/angular-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index d7f2a5bd5..a1577856e 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -253,8 +253,8 @@ httpFoo.then((x) => { function test_angular_forEach() { var values: { [key: string]: string } = { name: 'misko', gender: 'male' }; - var log = []; - angular.forEach(values, function (value: string, key: string) { + var log: string[] = []; + angular.forEach(values, function (value, key) { this.push(key + ': ' + value); }, log); //expect(log).toEqual(['name: misko', 'gender: male']); From 4394dc65a298c715dc6bbf3111dfae2aa8e4f840 Mon Sep 17 00:00:00 2001 From: Antoine Pultier Date: Tue, 29 Jul 2014 15:43:41 +0200 Subject: [PATCH 201/324] API update (version 0.7.3) --- leaflet/leaflet.d.ts | 145 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 141 insertions(+), 4 deletions(-) diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 54f0fe4f0..ff5a42d05 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Leaflet.js 0.6.4 +// Type definitions for Leaflet.js 0.7.3 // Project: https://github.com/Leaflet/Leaflet // Definitions by: Vladimir Zotov // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -870,6 +870,13 @@ declare module L { * Default value: [0, 0]. */ padding?: Point; + + /** + * The maximum possible zoom to use. + * + * Default value: null + */ + maxZoom?: number; } } @@ -1128,6 +1135,11 @@ declare module L { * Mercator-based CRS. */ scale(zoom: number): number; + + /** + * Returns the size of the world in pixels for a particular zoom. + */ + getSize(zoom: number): Point; } } @@ -1277,6 +1289,11 @@ declare module L { * Sets the opacity of the overlay. */ setOpacity(opacity: number): ImageOverlay; + + /** + * Changes the URL of the image. + */ + setUrl(imageUrl: string): ImageOverlay; /** * Brings the layer to the top of all overlays. @@ -1802,6 +1819,17 @@ declare module L { popup: Popup; } } + +declare module L { + + export interface LeafletDragEndEvent extends LeafletEvent { + + /** + * The distance in pixels the draggable element was moved by. + */ + distance: number; + } +} declare module L { @@ -1960,7 +1988,7 @@ declare module L { * Sets the view of the map (geographical center and zoom) with the given * animation options. */ - setView(center: LatLng, zoom: number, options?: ZoomPanOptions): Map; + setView(center: LatLng, zoom?: number, options?: ZoomPanOptions): Map; /** * Sets the zoom of the map. @@ -2370,17 +2398,24 @@ declare module L { /** * Whether the map can be zoomed by using the mouse wheel. + * If passed 'center', it will zoom to the center of the view regardless of + * where the mouse was. * * Default value: true. */ scrollWheelZoom?: boolean; + scrollWheelZoom?: string; /** - * Whether the map can be zoomed in by double clicking on it. + * Whether the map can be zoomed in by double clicking on it and zoomed out + * by double clicking while holding shift. + * If passed 'center', double-click zoom will zoom to the center of the view + * regardless of where the mouse was. * * Default value: true. */ doubleClickZoom?: boolean; + doubleClickZoom?: string; /** * Whether the map can be zoomed to a rectangular area specified by dragging @@ -2529,6 +2564,14 @@ declare module L { * in all browsers that support CSS3 Transitions except Android. */ markerZoomAnimation?: boolean; + + /** + * Set it to false if you don't want the map to zoom beyond min/max zoom + * and then bounce back when pinch-zooming. + * + * Default value: true. + */ + bounceAtZoomLimits?: boolean; } } @@ -2652,6 +2695,11 @@ declare module L { * Opens the popup previously bound by the bindPopup method. */ openPopup(): Marker; + + /** + * Returns the popup previously bound by the bindPopup method. + */ + getPopup(): Popup; /** * Closes the bound popup of the marker if it's opened. @@ -2752,6 +2800,13 @@ declare module L { * Default value: ''. */ title?: string; + + /** + * Text for the alt attribute of the icon image (useful for accessibility). + * + * Default value: ''. + */ + alt?: string; /** * By default, marker images zIndex is set automatically based on its latitude. @@ -2814,6 +2869,11 @@ declare module L { */ getLatLngs(): LatLng[][]; + /** + * Opens the popup previously bound by bindPopup. + */ + openPopup(): MultiPolygon; + /** * Returns a GeoJSON representation of the multipolygon (GeoJSON MultiPolygon Feature). */ @@ -2848,6 +2908,11 @@ declare module L { */ getLatLngs(): LatLng[][]; + /** + * Opens the popup previously bound by bindPopup. + */ + openPopup(): MultiPolyline; + /** * Returns a GeoJSON representation of the multipolyline (GeoJSON MultiLineString Feature). */ @@ -3076,6 +3141,20 @@ declare module L { * layers (e.g. Android 2). */ dashArray?: string; + + /** + * A string that defines shape to be used at the end of the stroke. + * + * Default: null. + */ + lineCap?: string; + + /** + * A string that defines shape to be used at the corners of the stroke. + * + * Default: null. + */ + lineJoin?: string; /** * If false, the vector will not emit mouse events and will act as a part of the @@ -3089,6 +3168,13 @@ declare module L { * Sets the pointer-events attribute on the path if SVG backend is used. */ pointerEvents?: boolean; + + /** + * Custom class name set on an element. + * + * Default value: ''. + */ + className?: string; } } @@ -3308,7 +3394,12 @@ declare module L { * Sets the geographical point where the popup will open. */ setLatLng(latlng: LatLng): Popup; - + + /** + * Returns the geographical point of popup. + */ + getLatLng(): LatLng; + /** * Sets the HTML content of the popup. */ @@ -3319,6 +3410,16 @@ declare module L { */ setContent(el: HTMLElement): Popup; + /** + * Returns the content of the popup. + */ + getContent(): string; + + /** + * Returns the content of the popup. + */ + getContent(): HTMLElement; + //////////// //////////// /** @@ -3333,6 +3434,12 @@ declare module L { * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). */ onRemove(map: Map): void; + + /** + * Updates the popup content, layout and position. Useful for updating the popup after + * something inside changed, e.g. image loaded. + */ + update(): Popup; } } @@ -3382,6 +3489,22 @@ declare module L { * Default value: new Point(0, 6). */ offset?: Point; + + /** + * The margin between the popup and the top left corner of the map view after + * autopanning was performed. + * + * Default value: null. + */ + autoPanPaddingTopLeft?: Point; + + /** + * The margin between the popup and the bottom right corner of the map view after + * autopanning was performed. + * + * Default value: null. + */ + autoPanPaddingBottomRight?: Point; /** * The margin between the popup and the edges of the map view after autopanning @@ -3695,6 +3818,15 @@ declare module L { * Default value: 18. */ maxZoom?: number; + + /** + * Maximum zoom number the tiles source has available. If it is specified, + * the tiles on all zoom levels higher than maxNativeZoom will be loaded from + * maxZoom level and auto-scaled. + * + * Default value: null. + */ + maxNativeZoom?: number; /** * Tile size (width and height in pixels, assuming tiles are square). @@ -3997,6 +4129,11 @@ declare module L { * An equivalent of passing animate to both zoom and pan options (see below). */ animate?: boolean; + + /** + * If true, it will delay moveend event so that it doesn't happen many times in a row. + */ + debounceMoveend?: boolean; } } From c11810a1cc5cbf7f8008b930bb2abef2d332fe7e Mon Sep 17 00:00:00 2001 From: Antoine Pultier Date: Tue, 29 Jul 2014 15:55:02 +0200 Subject: [PATCH 202/324] L.Handler object --- leaflet/leaflet.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index ff5a42d05..42a7d4d82 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -1243,6 +1243,10 @@ declare module L { */ enabled(): boolean; } + + export class Handler extends Class implements IHandler { + initialize(map: Map): void; + } } declare module L { From 4d014a48600d27b4626bab48816977cb7c850aa5 Mon Sep 17 00:00:00 2001 From: Antoine Pultier Date: Tue, 29 Jul 2014 16:17:55 +0200 Subject: [PATCH 203/324] Leaflet: L.Mixin.Events --- leaflet/leaflet.d.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 42a7d4d82..7f7b8dc9a 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -1267,6 +1267,17 @@ declare module L { onRemove(map: Map): void; } } + +declare module L { + export var Mixin: any; + + module Mixin { + export interface LeafletMixinEvents implements IEventPowered { + } + + export var Events: LeafletMixinEvents; + } +} declare module L { From 133ace301b80361b41695133d883bcbaa2b6574e Mon Sep 17 00:00:00 2001 From: Frederik Wordenskjold Date: Tue, 29 Jul 2014 20:36:17 +0200 Subject: [PATCH 204/324] Made Wreqr.radio a module --- marionette/marionette.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/marionette/marionette.d.ts b/marionette/marionette.d.ts index 9ff239dc5..cee7b1845 100644 --- a/marionette/marionette.d.ts +++ b/marionette/marionette.d.ts @@ -57,9 +57,9 @@ declare module Backbone { // Backbone.Wreqr module Wreqr { - class radio { + module radio { - static channel(channelName: string): Channel; + function channel(channelName: string): Channel; } From 2bb123d25009b368292613891e62b1c1599105d8 Mon Sep 17 00:00:00 2001 From: Paulo Cesar Date: Tue, 29 Jul 2014 20:58:09 -0300 Subject: [PATCH 205/324] add object path --- object-path/object-path-tests.ts | 68 +++++++++ object-path/object-path.d.ts | 238 +++++++++++++++++++++++++++++++ 2 files changed, 306 insertions(+) create mode 100644 object-path/object-path-tests.ts create mode 100644 object-path/object-path.d.ts diff --git a/object-path/object-path-tests.ts b/object-path/object-path-tests.ts new file mode 100644 index 000000000..5984c78a8 --- /dev/null +++ b/object-path/object-path-tests.ts @@ -0,0 +1,68 @@ +/// + +var + object = { + one: 1, + two: { + three: 3, + four: ['4'] + } + }, + array: any[] = [], + Null:any = null; + +objectPath.del(array) === ['12']; +objectPath.del(object) === object; +objectPath.del(object) === object; + +objectPath.del() === void 0; +objectPath.del(object, ['1','2','3']); +objectPath.del(object, [1,2,3]); +objectPath.del(object, 1); +objectPath.del(object, 'one').one === 1; + +objectPath.coalesce(object, ['1','2']) === void 0; +objectPath.coalesce(object, ['1',['2','1']]) === void 0; +objectPath.coalesce(object, ['1',['2','1']], 1) === 1; +objectPath.coalesce(object, [1,1], 1) === 1; +objectPath.coalesce(object, >[1,[1,1]], 1) === 1; + +objectPath.ensureExists(object, '1.2', 2); +objectPath.ensureExists(object, 1, 2); +objectPath.ensureExists(object, [1,2], 2); +objectPath.ensureExists(object, ['1','2'], 2); +objectPath.ensureExists(object, ['1','2'], 2) === 3; +objectPath.ensureExists(object, ['1','2'], 2) === [[]]; + +objectPath.push(object, 1, 1,2,3,4); +objectPath.push(object, 1, 1,'2', 3, false); +objectPath.push(object, 'one.four', 1,'2', 3, false); +objectPath.push(object, ['one','two'], [1,'2', 3, false]); + +objectPath.get(array) === array; +objectPath.get(Null) === Null; +objectPath.get() === void 0; +objectPath.get(object, 'one') === 1; +objectPath.get(object, ['two','three']) === 3; +objectPath.get(object, ['three'], 3) === 3; +objectPath.get(object, 'three', 3) === 3; +objectPath.get(object, 0, 3) === 3; +objectPath.get(object, 0, '3') === '3'; +objectPath.get(object, 0, ['1','2']) === ['1','2']; +objectPath.get(object, 0) === 10; + +objectPath.set(object, '1.2', true); +objectPath.set(object, ['1','2'], true); +objectPath.set(object, [1, 2], true); +objectPath.set(object, '1.2', true, true); +objectPath.set(object, '1.2', true, false); +objectPath.set(object, '1.2', true, false) === ['string']; +objectPath.set(object, '1.2', true, false) === object; + +objectPath.insert(object, '1.2', 1); +objectPath.insert(object, ['1','2'], 1); +objectPath.insert(object, 1, 1); +objectPath.insert(object, [1,2], 1); +objectPath.insert(object, '1.2', 1, 2); +objectPath.insert(object, ['1.2'], 1, 6); + diff --git a/object-path/object-path.d.ts b/object-path/object-path.d.ts new file mode 100644 index 000000000..fe38f8702 --- /dev/null +++ b/object-path/object-path.d.ts @@ -0,0 +1,238 @@ +// Type definitions for objectPath v0.6.0 +// Project: https://github.com/mariocasciaro/object-path +// Definitions by: Paulo Cesar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare var objectPath: objectPath.IObjectPathStatic; + +declare module objectPath { + + interface IStringArray { + [index: number]: string; + } + + interface INumberArray { + [index: number]: number; + } + + interface IObjectPathStatic { + /*======== Del =========*/ + + /** + * Deletes a member from object or array + * @param {object} object + * @param {string[]|string} path + * @return object + */ + del(object: T, path: IStringArray): T; + /** + * @see objectPath.del + */ + del(object: T, path: INumberArray): T; + /** + * @see objectPath.del + */ + del(object: T, path: number): T; + /** + * @see objectPath.del + */ + del(object: T, path: string): T; + /** + * @see objectPath.del + */ + del(object: T): T; + /** + * @see objectPath.del + */ + del():void; + + /*======== Get =========*/ + /** + * Get a path from an object + * @param {object} object + * @param {string|string[]|number|number[]} path + * @param {*} [defaultValue=undefined] + */ + get(object: T, path: string, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(object: T, path: IStringArray, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(object: T, path: number, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(object: T, path: INumberArray, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(object: T): T; + /** + * @see objectPath.get + */ + get():void; + + /*======== Set =========*/ + /** + * Set a path to a value + * @param {object} object + * @param {string|string[]|number|number[]} path + * @param {*} value + * @param {boolean} [doNotReplace=false] + * @return Any existing value on the path if any + */ + set(object: T, path: string, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(object: T, path: number, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(object: T, path: IStringArray, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(object: T, path: INumberArray, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(object: T): T; + /** + * @see objectPath.set + */ + set():void; + + /*======== Push =========*/ + /** + * Create (if path isn't an array) and push the value to it. Can push unlimited number of values + * @param {object} object + */ + push(object: T, path: INumberArray, ...args:any[]):void; + /** + * @see objectPath.push + */ + push(object: T, path: IStringArray, ...args:any[]):void; + /** + * @see objectPath.push + */ + push(object: T, path: number, ...args:any[]):void; + /** + * @see objectPath.push + */ + push(object: T, path: string, ...args:any[]):void; + /** + * @see objectPath.push + */ + push():void; + + /*======== Coalesce =========*/ + /** + * Get the first non undefined property + * @param {object} object + * @param {string[]|string[][]|number[]|number[][]} paths + * @param {*} defaultValue + * @return {*} + */ + coalesce(object: T, paths: IStringArray, defaultValue?: any):TResult; + /** + * @see objectPath.coalesce + */ + coalesce(object: T, paths: INumberArray, defaultValue?: any):TResult; + /** + * @see objectPath.coalesce + */ + coalesce(object: T, paths: IStringArray[], defaultValue?: any):TResult; + /** + * @see objectPath.coalesce + */ + coalesce(object: T, paths: INumberArray[], defaultValue?: any):TResult; + + /*======== Empty =========*/ + /** + * Empty a path. Arrays are set to length 0, objects have all elements deleted, strings + * are set to empty, numbers to 0, everything else is set to null + * @param {object} object + * @param {string|string[]|number[]} path + */ + empty(object: T, path: string):TResult; + /** + * @see objectPath.empty + */ + empty(object: T, path: INumberArray):TResult; + /** + * @see objectPath.empty + */ + empty(object: T, path: IStringArray):TResult; + /** + * @see objectPath.empty + */ + empty(object: T, path: number):TResult; + /** + * @see objectPath.empty + */ + empty(object: T):T; + /** + * @see objectPath.empty + */ + empty():void; + + /*======== EnsureExists =========*/ + /** + * Set a value if it doesn't exist, do nothing if it does + * @param {object} object + * @param {string|string[]|number|number[]} path + */ + ensureExists(object: T, path: string, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(object: T, path: number, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(object: T, path: INumberArray, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(object: T, path: IStringArray, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(object: T): T; + /** + * @see objectPath.ensureExists + */ + ensureExists():void; + + /*======== Insert =========*/ + /** + * Insert an item in an array path + * @param {object} object + * @param {string|string[]|number|number[]} path + * @param {*} value + * @param {number} [at=0] + */ + insert(object: T, path: string, value: any, at?: number):void; + /** + * @see objectPath.insert + */ + insert(object: T, path: INumberArray, value: any, at?: number):void; + /** + * @see objectPath.insert + */ + insert(object: T, path: IStringArray, value: any, at?: number):void; + /** + * @see objectPath.insert + */ + insert(object: T, path: number, value: any, at?: number):void; + } + +} + +declare module 'objectPath' { + export = objectPath; +} \ No newline at end of file From 70ff4da3eee5250de662c8faa3d5eb6399a48a09 Mon Sep 17 00:00:00 2001 From: Bo Miller Date: Tue, 29 Jul 2014 23:49:35 -0400 Subject: [PATCH 206/324] Underscore.js: Updated chained calls to first() so that they return a _ChainSingle instead of _Chain. This causes a future call to value() to return a single T rather than an array of T which matches underscore's behavior. --- underscore/underscore-tests.ts | 4 ++++ underscore/underscore.d.ts | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/underscore/underscore-tests.ts b/underscore/underscore-tests.ts index 11624abeb..8b638ee50 100644 --- a/underscore/underscore-tests.ts +++ b/underscore/underscore-tests.ts @@ -328,4 +328,8 @@ function chain_tests() { .flatten() .find(num => num % 2 == 0) .value(); + + var firstVal: number = _.chain([1, 2, 3]) + .first() + .value(); } diff --git a/underscore/underscore.d.ts b/underscore/underscore.d.ts index 5b64aceb1..7d9c84f82 100644 --- a/underscore/underscore.d.ts +++ b/underscore/underscore.d.ts @@ -2620,7 +2620,7 @@ interface _Chain { * Wrapped type `any[]`. * @see _.first **/ - first(): _Chain; + first(): _ChainSingle; /** * Wrapped type `any[]`. From 49664879ddf34d597e8a032dba22cb6feae5e10b Mon Sep 17 00:00:00 2001 From: zaneli Date: Wed, 30 Jul 2014 12:12:40 +0900 Subject: [PATCH 207/324] Add definitions for fingerprintjs --- CONTRIBUTORS.md | 1 + fingerprintjs/fingerprint-tests.ts | 53 ++++++++++++++++ fingerprintjs/fingerprint.d.ts | 99 ++++++++++++++++++++++++++++++ 3 files changed, 153 insertions(+) create mode 100644 fingerprintjs/fingerprint-tests.ts create mode 100644 fingerprintjs/fingerprint.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 35e2980f7..38519a81a 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -82,6 +82,7 @@ All definitions files include a header with the author and editors, so at some p * [File API: Directories and System](http://www.w3.org/TR/file-system-api/) (by [Kon](http://phyzkit.net/)) * [File API: Writer](http://www.w3.org/TR/file-writer-api/) (by [Kon](http://phyzkit.net/)) * [Finch](https://github.com/stoodder/finchjs) (by [David Sichau](https://github.com/DavidSichau/)) +* [fingerprintjs](https://github.com/Valve/fingerprintjs) (by [Shunsuke Ohtani](https://github.com/zaneli)) * [Finite State Machine](https://github.com/jakesgordon/javascript-state-machine) (by [Boris Yankov](https://github.com/borisyankov)) * [Firebase](https://www.firebase.com/docs/javascript/firebase) (by [Vincent Bortone](https://github.com/vbortone)) * [Firefox](https://developer.mozilla.org/en-US/docs/Web/API) (by [vvakame](https://github.com/vvakame)) diff --git a/fingerprintjs/fingerprint-tests.ts b/fingerprintjs/fingerprint-tests.ts new file mode 100644 index 000000000..8b0789870 --- /dev/null +++ b/fingerprintjs/fingerprint-tests.ts @@ -0,0 +1,53 @@ +/// + +function test_no_option() { + var fingerprint = new Fingerprint().get(); +} + +function test_set_canvas_enabled() { + var fingerprint = new Fingerprint({canvas: true}).get(); +} + +function test_set_screen_resolution_enabled() { + var fingerprint = new Fingerprint({screen_resolution: true}).get(); +} + +function test_set_ie_activex_enabled() { + var fingerprint = new Fingerprint({ie_activex: true}).get(); +} + +function test_set_hasher_in_option() { + var my_hasher = (value: string, seed: number) => { return value.length % seed; }; + var fingerprint = new Fingerprint({hasher: my_hasher}).get(); + + var fingerprint = new Fingerprint({hasher: (value, seed) => { return value.length % seed; }}).get(); +} + +function test_set_hasher_in_constructor() { + var my_hasher = (value: string, seed: number) => { return value.length % seed; }; + var fingerprint = new Fingerprint(my_hasher).get(); + + var fingerprint = new Fingerprint((value, seed) => { return value.length % seed; }).get(); +} + +function test_call_methods() { + var f = new Fingerprint(); + f.murmurhash3_32_gc("abcde", 123); + if (f.hasLocalStorage()) { + alert("LocalStorage"); + } + if (f.hasSessionStorage()) { + alert("SessionStorage"); + } + if (f.isCanvasSupported()) { + alert("CanvasSupported"); + } + if (f.isIE()) { + alert("IE"); + } + f.getPluginsString(); + f.getRegularPluginsString(); + f.getIEPluginsString(); + f.getScreenResolution(); + f.getCanvasFingerprint(); +} diff --git a/fingerprintjs/fingerprint.d.ts b/fingerprintjs/fingerprint.d.ts new file mode 100644 index 000000000..f472b0489 --- /dev/null +++ b/fingerprintjs/fingerprint.d.ts @@ -0,0 +1,99 @@ +// Type definitions for fingerprintjs 0.5.4 +// Project: https://github.com/Valve/fingerprintjs +// Definitions by: Shunsuke Ohtani +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module FingerprintJs { + + interface FingerprintStatic { + /** + * Create Fingerprint object. + */ + new(hasher: (key: string, seed: number) => number): Fingerprint; + new(option: FingerprintOption): Fingerprint; + new(): Fingerprint; + } + + interface Fingerprint { + /** + * Generate fingerprint number. + */ + get(): number; + + /** + * Generate fingerprint number using Murmur hashing. + * @param key ASCII only + * @param seed Positive integer only + */ + murmurhash3_32_gc(key: string, seed: number): number; + + /** + * Check whether or not the browser has local storage. + */ + hasLocalStorage(): boolean; + + /** + * Check whether or not the browser has session storage. + */ + hasSessionStorage(): boolean; + + /** + * Check whether or not the browser supports canvas. + */ + isCanvasSupported(): boolean; + + /** + * Check whether or not the browser is IE. + */ + isIE(): boolean; + + /** + * Get plugins string. + */ + getPluginsString(): string; + + /** + * Get plugins string from navigator plugins. + */ + getRegularPluginsString(): string; + + /** + * Get plugins string from ActiveXObject. + */ + getIEPluginsString(): string; + + /** + * Get screen height and width. + */ + getScreenResolution(): number[]; + + /** + * Get canvas data url string. + */ + getCanvasFingerprint(): string; + } + + interface FingerprintOption { + /** + * If you want to use canvas fingerprinting, set true. + */ + canvas?: boolean; + + /** + * If you want to use the screen resolution in calculating the fingerprint, set true. + */ + screen_resolution?: boolean; + + /** + * If you want to query the IE plugins info to further diversify the fingerprinting process, set true. + */ + ie_activex?: boolean; + + /** + * If you want to use custom hashing function, set function. + */ + hasher?: (key: string, seed: number) => number; + } +} + +declare var Fingerprint: FingerprintJs.FingerprintStatic; From 8cc523f0fa559172971834b74254688c95dd1d9f Mon Sep 17 00:00:00 2001 From: Paulo Cesar Date: Wed, 30 Jul 2014 09:44:38 -0300 Subject: [PATCH 208/324] Update CONTRIBUTORS.md --- CONTRIBUTORS.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 35e2980f7..b3acae253 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -251,7 +251,7 @@ All definitions files include a header with the author and editors, so at some p * [Node.js](http://nodejs.org/) (from TypeScript samples) * [node_redis](https://github.com/mranney/node_redis) (by [Boris Yankov](https://github.com/borisyankov)) * [node-ffi](https://github.com/rbranson/node-ffi) (by [Paul Loyd](https://github.com/loyd)) -* [node-form] (https://github.com/rsamec/form) (by [Roman Samec] (https://github.com/rsamec)) +* [node-form](https://github.com/rsamec/form) (by [Roman Samec](https://github.com/rsamec)) * [node-git](https://github.com/christkv/node-git) (by [vvakame](https://github.com/vvakame)) * [nodeunit](https://github.com/caolan/nodeunit) (by [Jeff Goddard](https://github.com/jedigo)) * [node_zeromq](https://github.com/JustinTulloss/zeromq.node) (by [Dave McKeown](https://github.com/davemckeown)) @@ -260,6 +260,7 @@ All definitions files include a header with the author and editors, so at some p * [notify.js](https://github.com/alexgibson/notify.js) (by [soundTricker](https://github.com/soundTricker)) * [NProgress](https://github.com/rstacruz/nprogress) (by [Judah Gabriel Himango](https://github.com/judahgabriel)) * [Numeral.js](https://github.com/adamwdraper/Numeral-js) (by [Vincent Bortone](https://github.com/vbortone/)) +* [object-path](https://github.com/mariocasciaro/object-path) (by [Paulo Cesar](https://github.com/pocesar/)) * [ocLazyLoad](https://github.com/ocombe/ocLazyLoad) (by [Roland Zwaga](https://github.com/rolandzwaga/)) * [OpenLayers](https://github.com/openlayers/openlayers) (by [Ilya Bolkhovsky](https://github.com/bolhovsky/)) * [Optimist](https://github.com/substack/node-optimist) (by [Carlos Ballesteros Velasco](https://github.com/soywiz)) @@ -293,7 +294,7 @@ All definitions files include a header with the author and editors, so at some p * [Raphael](http://raphaeljs.com/) (by [CheCoxshall](https://github.com/CheCoxshall)) * [Restangular](https://github.com/mgonto/restangular/) (by [Boris Yankov](https://github.com/borisyankov)) * [require.js](http://requirejs.org/) (by [Josh Baldwin](https://github.com/jbaldwin/)) -* [rtree.js] (https://github.com/leaflet-extras/RTree) (by [Omede Firouz](https://github.com/oefirouz)) +* [rtree.js](https://github.com/leaflet-extras/RTree) (by [Omede Firouz](https://github.com/oefirouz)) * [Sammy.js](http://sammyjs.org/) (by [Boris Yankov](https://github.com/borisyankov)) * [Select2](http://ivaynberg.github.com/select2/) (by [Boris Yankov](https://github.com/borisyankov)) * [Selenium WebDriverJS](https://code.google.com/p/selenium/) (by [Bill Armstrong](https://github.com/BillArmstrong)) From adec6babb59ef08a52e7ec69e995d63169137c33 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Wed, 30 Jul 2014 17:22:20 +0100 Subject: [PATCH 209/324] Added title to --- angularjs/angular.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index c515b096f..878f4f3cc 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -961,7 +961,9 @@ declare module ng { // RootScopeService // see http://docs.angularjs.org/api/ng.$rootScope /////////////////////////////////////////////////////////////////////////// - interface IRootScopeService extends IScope {} + interface IRootScopeService extends IScope { + title: string; + } /////////////////////////////////////////////////////////////////////////// // SCEService From a664ce369bc2afb45a27206931843e8295a5ef57 Mon Sep 17 00:00:00 2001 From: Wayne Maurer Date: Wed, 30 Jul 2014 21:17:53 +0200 Subject: [PATCH 210/324] added static html() methods to cheerio --- cheerio/cheerio.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/cheerio/cheerio.d.ts b/cheerio/cheerio.d.ts index df5058f20..af5f0172e 100644 --- a/cheerio/cheerio.d.ts +++ b/cheerio/cheerio.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/cheeriojs/cheerio // Definitions by: Bret Little // Definitions by: VILIC VANE +// Definitions by: Wayne Maurer // Definitions: https://github.com/borisyankov/DefinitelyTyped interface Cheerio { @@ -190,6 +191,11 @@ interface CheerioStatic { root(): Cheerio; contains(container: CheerioElement, contained: CheerioElement): boolean; parseHTML(data: string, context?: Document, keepScripts?: boolean): Document[]; + + html(options?: CheerioOptionsInterface): string; + html(selector: string, options?: CheerioOptionsInterface): string; + html(element: Cheerio, options?: CheerioOptionsInterface): string; + html(element: CheerioElement, options?: CheerioOptionsInterface): string; } interface CheerioElement { From 1b831404eebc5f7ab6f741aac08b9bd3f74b04c3 Mon Sep 17 00:00:00 2001 From: vvakame Date: Thu, 31 Jul 2014 11:06:46 +0900 Subject: [PATCH 211/324] fix .travis.yml from https://github.com/travis-ci/travis-ci/issues/2591 --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index d138403cc..acfc5176f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: node_js node_js: - - 0.10 + - "0.10" notifications: email: false From 500fc1022b92c5c856eb11d07054ebf9cc5c44bb Mon Sep 17 00:00:00 2001 From: allentc Date: Thu, 31 Jul 2014 01:12:24 -0600 Subject: [PATCH 212/324] Correct parameter optionality The last three parameters of ticker.addEventListener are optional. See: http://api.greensock.com/js/com/greensock/TweenMax.html#ticker --- greensock/greensock.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/greensock/greensock.d.ts b/greensock/greensock.d.ts index 4cf521e15..42fa6aa85 100644 --- a/greensock/greensock.d.ts +++ b/greensock/greensock.d.ts @@ -7,7 +7,7 @@ // Version 1.1 (TypeScript 0.9) interface IDispatcher { - addEventListener(type:string, callback:Function, scope:Object, useParam:boolean, priority:number):void; + addEventListener(type:string, callback:Function, scope?:Object, useParam?:boolean, priority?:number):void; removeEventListener(type:string, callback:Function):void; } From a4661ce23c4241f822f56acc5b4a7bbf56871a68 Mon Sep 17 00:00:00 2001 From: Roland Zwaga Date: Thu, 31 Jul 2014 09:20:10 +0200 Subject: [PATCH 213/324] Added definition and tests for angular-bootstrap-lightbox. (https://github.com/compact/angular-bootstrap-lightbox) --- .../angular-bootstrap-lightbox-tests.ts | 35 +++++++++++++ .../angular-bootstrap-lightbox.d.ts | 49 +++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 angular-bootstrap-lightbox/angular-bootstrap-lightbox-tests.ts create mode 100644 angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts diff --git a/angular-bootstrap-lightbox/angular-bootstrap-lightbox-tests.ts b/angular-bootstrap-lightbox/angular-bootstrap-lightbox-tests.ts new file mode 100644 index 000000000..21e9b2ce9 --- /dev/null +++ b/angular-bootstrap-lightbox/angular-bootstrap-lightbox-tests.ts @@ -0,0 +1,35 @@ +/// + +var imageList:angular.bootstrap.lightbox.ILightboxImageInfo[] = []; +imageList.push({ + url: 'url1', + width: 100, + height: 100 +}); +imageList.push({ + url: 'url2', + width: 100, + height: 100, + thumbUrl: 'thumbUrl', + caption: 'caption' +}); + +var lightBox:angular.bootstrap.lightbox.ILightbox = {}; +lightBox.openModal(imageList, 0); + +var provider:angular.bootstrap.lightbox.ILightBoxProvider = {}; +provider.templateUrl = 'templateUrl'; +provider.calculateImageDimensionLimits = (dimensions:angular.bootstrap.lightbox.IImageDimensionParameter):angular.bootstrap.lightbox.IImageDimensionLimits=> { + return { + minWidth: 100, + minHeight: 100, + maxWidth: dimensions.windowWidth - 102, + maxHeight: dimensions.windowHeight - 136 + }; +}; +provider.calculateModalDimensions = (dimensions:angular.bootstrap.lightbox.IModalDimensionsParameter):angular.bootstrap.lightbox.IModalDimensions=> { + return { + width: Math.max(500, dimensions.imageDisplayWidth + 42), + height: Math.max(500, dimensions.imageDisplayHeight + 76) + }; + }; \ No newline at end of file diff --git a/angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts b/angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts new file mode 100644 index 000000000..d8c831249 --- /dev/null +++ b/angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts @@ -0,0 +1,49 @@ +/** + * Created by Roland on 7/31/2014. + */ +declare module angular.bootstrap.lightbox { + + export interface ILightboxImageInfo { + url: string; + width: number; + height: number; + thumbUrl?: string; + caption?: string; + } + + export interface IImageDimensionLimits { + minWidth?: number; + minHeight?: number; + maxWidth?: number; + maxHeight?: number; + } + + export interface IImageDimensionParameter { + windowWidth:number; + windowHeight:number; + imageWidth:number; + imageHeight:number; + } + + export interface IModalDimensionsParameter { + windowWidth:number; + windowHeight:number; + imageDisplayWidth:number; + imageDisplayHeight:number; + } + + export interface IModalDimensions { + width:number; + height:number; + } + + export interface ILightbox { + openModal(images:ILightboxImageInfo[], index:number):void; + } + + export interface ILightBoxProvider { + templateUrl:string; + calculateImageDimensionLimits:(dimensions:IImageDimensionParameter)=>IImageDimensionLimits; + calculateModalDimensions:(dimensions:IModalDimensionsParameter)=>IModalDimensions; + } +} \ No newline at end of file From cf1a372e77c46cc40c21c73276decc64bbbff3fe Mon Sep 17 00:00:00 2001 From: Roland Zwaga Date: Thu, 31 Jul 2014 09:27:05 +0200 Subject: [PATCH 214/324] Update CONTRIBUTORS.md --- CONTRIBUTORS.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 83d78bfd6..088a423eb 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -8,7 +8,8 @@ All definitions files include a header with the author and editors, so at some p * [Ace Cloud9 Editor](http://ace.ajax.org/) (by [Diullei Gomes](https://github.com/Diullei)) * [Add To Home Screen](http://cubiq.org/add-to-home-screen) (by [James Wilkins](http://www.codeplex.com/site/users/view/jamesnw)) * [AmCharts](http://www.amcharts.com/) (by [Covobonomo](https://github.com/covobonomo/)) -* [AngularAgility](https://github.com/AngularAgility/AngularAgility) (by [Roland Zwaga](https://github.com/rolandzwaga) +* [AngularAgility](https://github.com/AngularAgility/AngularAgility) (by [Roland Zwaga](https://github.com/rolandzwaga)) +* [AngularBootstrapLightbox](https://github.com/compact/angular-bootstrap-lightbox) (by [Roland Zwaga](https://github.com/rolandzwaga)) * [AngularFire](https://www.firebase.com/docs/angular/reference.html) (by [Dénes Harmath](https://github.com/thSoft)) * [AngularJS](http://angularjs.org) (by [Diego Vilar](https://github.com/diegovilar)) ([wiki](https://github.com/borisyankov/DefinitelyTyped/wiki/AngularJS-Definitions-Usage-Notes)) * [angularLocalStorage](https://github.com/agrublev/angularLocalStorage) (by [Hiroki Horiuchi](https://github.com/horiuchi/)) From 3ae57ef657a2006e409b8dc4931908e0e8f84859 Mon Sep 17 00:00:00 2001 From: vvakame Date: Thu, 31 Jul 2014 18:45:02 +0900 Subject: [PATCH 215/324] fix SlickGrid declaration --- slickgrid/SlickGrid-tests.ts | 14 ++++++++++++-- slickgrid/SlickGrid-tests.ts.tscparams | 1 - slickgrid/SlickGrid.d.ts | 4 ++-- 3 files changed, 14 insertions(+), 5 deletions(-) delete mode 100644 slickgrid/SlickGrid-tests.ts.tscparams diff --git a/slickgrid/SlickGrid-tests.ts b/slickgrid/SlickGrid-tests.ts index 50db88b52..e267a8594 100644 --- a/slickgrid/SlickGrid-tests.ts +++ b/slickgrid/SlickGrid-tests.ts @@ -47,7 +47,7 @@ grid.getDataItem(14).title; grid.setData([{ title: "task", duration: "5 days", percentComplete: 5, start: "01/01/2013", finish: "12/12/2013", effortDriven: false }], true); -var ids = []; +var ids: string[] = []; for (i = 0; i < grid.getDataLength(); i++) { ids.push(grid.getDataItem(i).title); } @@ -82,7 +82,7 @@ class SingleCellSelectionModel extends Slick.SelectionModel(); var gridWithDataView = new Slick.Grid('#grid2', dataView, columns, options); dataView.getIdxById('foo') + 5; + +columns.forEach(column => { + if (column.editor !== Slick.Editors.Integer) { + return; + } +}); + +grid.onSort.subscribe((e, args) => { + var sortCol:string = args.sortCols[0].sortCol.field; +}); diff --git a/slickgrid/SlickGrid-tests.ts.tscparams b/slickgrid/SlickGrid-tests.ts.tscparams deleted file mode 100644 index e16c76dff..000000000 --- a/slickgrid/SlickGrid-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/slickgrid/SlickGrid.d.ts b/slickgrid/SlickGrid.d.ts index 90aa9cf13..d8a365d94 100644 --- a/slickgrid/SlickGrid.d.ts +++ b/slickgrid/SlickGrid.d.ts @@ -424,7 +424,7 @@ declare module Slick { /** * The editor for cell edits {TextEditor, IntegerEditor, DateEditor...} See slick.editors.js **/ - editor?: Editors.Editor; + editor?: any; // typeof Editors.Editor; /** * The property name in the data object to pull content from. (This is assumed to be on the root of the data object.) @@ -1333,7 +1333,7 @@ declare module Slick { // todo: merge with existing column definition export interface Column { - sortCol?: string; + sortCol?: Column; sortAsc?: boolean; } From f6f588b101906b5ac539bcbb7b3cd3ea07fc4432 Mon Sep 17 00:00:00 2001 From: Peter Kooijmans Date: Thu, 31 Jul 2014 12:29:26 +0200 Subject: [PATCH 216/324] Add loadZoneDataFromObject function. --- timezone-js/timezone-js.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/timezone-js/timezone-js.d.ts b/timezone-js/timezone-js.d.ts index ecf7d9e48..9aca2738e 100644 --- a/timezone-js/timezone-js.d.ts +++ b/timezone-js/timezone-js.d.ts @@ -75,6 +75,7 @@ declare module "timezone-js" { transport(opts: TimezoneJsOptions): any; init(opts?: TimezoneJsOptions): any; getAllZones(): string[]; + loadZoneDataFromObject(obj: Object): void; } export interface TimezoneJsOptions { From 761209a551bad41077686a39b03d77104f1248b3 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Thu, 31 Jul 2014 13:26:15 +0100 Subject: [PATCH 217/324] Pull title back off --- angularjs/angular.d.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 878f4f3cc..c515b096f 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -961,9 +961,7 @@ declare module ng { // RootScopeService // see http://docs.angularjs.org/api/ng.$rootScope /////////////////////////////////////////////////////////////////////////// - interface IRootScopeService extends IScope { - title: string; - } + interface IRootScopeService extends IScope {} /////////////////////////////////////////////////////////////////////////// // SCEService From 9c8cef88118832b21b10add82ba566896c428b6c Mon Sep 17 00:00:00 2001 From: Roland Zwaga Date: Thu, 31 Jul 2014 16:50:05 +0200 Subject: [PATCH 218/324] Added correct headers --- .../angular-bootstrap-lightbox.d.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts b/angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts index d8c831249..299967bdd 100644 --- a/angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts +++ b/angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts @@ -1,6 +1,8 @@ -/** - * Created by Roland on 7/31/2014. - */ +// Type definitions for angular-bootstrap-lightbox +// Project: https://github.com/compact/angular-bootstrap-lightbox +// Definitions by: Roland Zwaga +// Definitions: https://github.com/borisyankov/DefinitelyTyped + declare module angular.bootstrap.lightbox { export interface ILightboxImageInfo { From 7961ac184b54a1dfd28457121dbdcfc2531e832b Mon Sep 17 00:00:00 2001 From: Wayne Maurer Date: Thu, 31 Jul 2014 17:29:48 +0200 Subject: [PATCH 219/324] cheerio: fixed format of header as suggested by Bartvds - https://github.com/borisyankov/DefinitelyTyped/pull/2588 --- cheerio/cheerio.d.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/cheerio/cheerio.d.ts b/cheerio/cheerio.d.ts index af5f0172e..cd0be3593 100644 --- a/cheerio/cheerio.d.ts +++ b/cheerio/cheerio.d.ts @@ -1,8 +1,6 @@ // Type definitions for Cheerio v0.17.0 // Project: https://github.com/cheeriojs/cheerio -// Definitions by: Bret Little -// Definitions by: VILIC VANE -// Definitions by: Wayne Maurer +// Definitions by: Bret Little , VILIC VANE , Wayne Maurer // Definitions: https://github.com/borisyankov/DefinitelyTyped interface Cheerio { From d564ddbb2c4f6642331f615eaa41d0ef46e14d5d Mon Sep 17 00:00:00 2001 From: MIZUNE Pine Date: Fri, 1 Aug 2014 11:29:04 +0900 Subject: [PATCH 220/324] Add LastError interface --- chrome/chrome.d.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts index 796635c27..23ee0d916 100755 --- a/chrome/chrome.d.ts +++ b/chrome/chrome.d.ts @@ -843,8 +843,12 @@ declare module chrome.extension { type?: string; } + interface LastError { + message?: string; + } + var inIncognitoContext: boolean; - var lastError: Object; + var lastError: LastError; export function getBackgroundPage(): Window; export function getURL(path: string): string; @@ -1487,9 +1491,13 @@ declare module chrome.proxy { // Runtime //////////////////// declare module chrome.runtime { - var lastError: Object; + var lastError: LastError; var id: string; + interface LastError { + message?: string; + } + interface ConnectInfo { name?: string; } From 88e093242ad84927f986a92aa287020566ebbdb2 Mon Sep 17 00:00:00 2001 From: rsamec Date: Fri, 1 Aug 2014 06:49:29 +0200 Subject: [PATCH 221/324] IValidator - async support --- node-form/node-form.d.ts | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/node-form/node-form.d.ts b/node-form/node-form.d.ts index d75e313cd..3e56ddc4a 100644 --- a/node-form/node-form.d.ts +++ b/node-form/node-form.d.ts @@ -1,4 +1,4 @@ -// Type definitions for node-form v1.0.6 +// Type definitions for node-form v1.0.13 // Project: https://github.com/rsamec/form // Definitions by: Roman Samec // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -349,17 +349,25 @@ declare module Validation { (args: IError): void; } /** + * It defines async validation function. + */ + interface IAsyncValidate { + (args: IError): Q.Promise; + } + /** * It represents named validation function. */ interface IValidatorFce { Name: string; - ValidationFce: IValidate; + ValidationFce?: IValidate; + AsyncValidationFce?: IAsyncValidate; } /** * This class represents custom validator. */ interface IValidator { - Validate(context: any): boolean; + Validate(context: any): IValidationFailure; + ValidateAsync(context: any): Q.Promise; Error: IError; } /** @@ -677,13 +685,15 @@ declare module Validation { class Validator extends ValidationResult implements IValidator { public Name: string; private ValidateFce; + private AsyncValidationFce; public Error: IError; public ValidationFailures: { [name: string]: IValidationFailure; }; - constructor(Name: string, ValidateFce: IValidate); + constructor(Name: string, ValidateFce?: IValidate, AsyncValidationFce?: IAsyncValidate); public Optional: IOptional; - public Validate(context: any): boolean; + public Validate(context: any): IValidationFailure; + public ValidateAsync(context: any): Q.Promise; public HasError : boolean; public Errors : { [name: string]: IValidationFailure; @@ -694,6 +704,7 @@ declare module Validation { public TranslateArgs : IErrorTranslateArgs[]; } } -declare module "node-form" { -export = Validation ; + +declare module "node-form"{ + export = Validation; } \ No newline at end of file From 52318243888c4aa02b3c0b5e68631577728ffcf8 Mon Sep 17 00:00:00 2001 From: vvakame Date: Fri, 1 Aug 2014 17:26:03 +0900 Subject: [PATCH 222/324] js-yaml support on browser --- js-yaml/js-yaml.d.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/js-yaml/js-yaml.d.ts b/js-yaml/js-yaml.d.ts index 0607b4891..0de5a8f6b 100644 --- a/js-yaml/js-yaml.d.ts +++ b/js-yaml/js-yaml.d.ts @@ -3,7 +3,7 @@ // Definitions by: Bart van der Schoor // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module 'js-yaml' { +declare module jsyaml { export function safeLoad(str: string, opts?: LoadOptions): any; export function load(str: string, opts?: LoadOptions): any; @@ -46,3 +46,7 @@ declare module 'js-yaml' { // all supported YAML types. export var DEFAULT_FULL_SCHEMA: any; } + +declare module 'js-yaml' { + export = jsyaml; +} From 4c104285874869143ce48c05f00605310a296f0a Mon Sep 17 00:00:00 2001 From: Zalim Bashorov Date: Fri, 1 Aug 2014 16:26:37 +0400 Subject: [PATCH 223/324] Fix return type of PullDecl.isRootDecl: void -> boolean --- typescript-services/typescriptServices.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/typescript-services/typescriptServices.d.ts b/typescript-services/typescriptServices.d.ts index 18bef7b3d..25f174b43 100644 --- a/typescript-services/typescriptServices.d.ts +++ b/typescript-services/typescriptServices.d.ts @@ -5640,7 +5640,7 @@ declare module TypeScript { public hasBeenBound(): boolean; public isSynthesized(): boolean; public ast(): AST; - public isRootDecl(): void; + public isRootDecl(): boolean; } class RootPullDecl extends PullDecl { private _isExternalModule; @@ -9317,4 +9317,4 @@ declare module TypeScript.Services { declare module 'typescript-services' { export = TypeScript; -} \ No newline at end of file +} From f7c9354f94582093578d6911bb128eed15ca3c1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonathan=20H=C3=A4berle?= Date: Fri, 1 Aug 2014 15:40:16 +0200 Subject: [PATCH 224/324] body-parser definitions added --- body-parser/body-parser.d.ts | 63 +++++++++++++++++++++++++++++++++--- 1 file changed, 58 insertions(+), 5 deletions(-) diff --git a/body-parser/body-parser.d.ts b/body-parser/body-parser.d.ts index 0cd67332a..3f2f90057 100644 --- a/body-parser/body-parser.d.ts +++ b/body-parser/body-parser.d.ts @@ -1,12 +1,65 @@ // Type definitions for body-parser // Project: http://expressjs.com -// Definitions by: Santi Albo + +// Definition by: Jonathan Häberle // Definitions: https://github.com/borisyankov/DefinitelyTyped /// declare module "body-parser" { - import express = require('express'); - function e(options?: any): express.RequestHandler; - export = e; -} \ No newline at end of file + import express = require('express'); + + module e { + + // JSON Options + interface JsonOptions { + strict? : boolean; // only parse objects and arrays. (default: true) + inflate? : boolean; // if deflated bodies will be inflated. (default: true) + limit? : number; // maximum request body size. (default: <100kb>) + reviver? : (k :any, v:any) => any // passed to JSON.parse() + type? : string; // request content-type to parse (default: json) + verify? : (req : express.Request, res : express.Response, streamBuf : any, encoding : string) => void; // function to verify body content + } + + // Raw Options + interface RawOptions { + inflate? : boolean; // if deflated bodies will be inflated. (default: true) + limit? :number; // maximum request body size. (default: <100kb>) + type? : string; // request content-type to parse (default: application/octet-stream) + verify? : (req : express.Request, res : express.Response, streamBuf : any, encoding : string) => void; // function to verify body content + } + + // Text Options + interface TextOptions { + defaultCharset? : string; // the default charset to parse as, if not specified in content-type. (default: utf-8) + inflate? : boolean; // if deflated bodies will be inflated. (default: true) + limit? : number; // maximum request body size. (default: <100kb>) + type? : string; // request content-type to parse (default: text/plain) + verify? : (req : express.Request, res : express.Response, streamBuf : any, encoding : string) => void; // function to verify body content + } + + // UrlEncoded Options + interface UrlEncodedOptions { + extended? : boolean; // parse extended syntax with the qs module. (default: true) + inflate? : boolean; // if deflated bodies will be inflated. (default: true) + limit: number; // maximum request body size. (default: <100kb>) + type: string; // request content-type to parse (default: urlencoded) + verify? : (req : express.Request, res : express.Response, streamBuf : any, encoding : string) => void; // function to verify body content + } + + + // Returns middleware that only parses json + function json(options? : JsonOptions) : express.RequestHandler; + + // Returns middleware that parses all bodies as a Buffer + function raw(options? : RawOptions) : express.RequestHandler; + + // Returns middleware that parses all bodies as a string + function text(options? : TextOptions) : express.RequestHandler; + + // Returns middleware that only parses urlencoded bodies + function urlencoded(options? : UrlEncodedOptions) : express.RequestHandler; + } + + export = e; +} From 72943b80ba4c330379a4f2dcd05765a5bbb64fc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonathan=20H=C3=A4berle?= Date: Fri, 1 Aug 2014 16:03:41 +0200 Subject: [PATCH 225/324] Fixed: expected '// Definitions by: ' at line 3 --- body-parser/body-parser.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/body-parser/body-parser.d.ts b/body-parser/body-parser.d.ts index 3f2f90057..9271144dc 100644 --- a/body-parser/body-parser.d.ts +++ b/body-parser/body-parser.d.ts @@ -1,6 +1,5 @@ // Type definitions for body-parser // Project: http://expressjs.com - // Definition by: Jonathan Häberle // Definitions: https://github.com/borisyankov/DefinitelyTyped From 6165fcf3c2b20a34fcfd7b221543bc0e4cbf4117 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonathan=20H=C3=A4berle?= Date: Fri, 1 Aug 2014 16:11:38 +0200 Subject: [PATCH 226/324] Fixed: expected url at line 3 --- body-parser/body-parser.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/body-parser/body-parser.d.ts b/body-parser/body-parser.d.ts index 9271144dc..a1932dae0 100644 --- a/body-parser/body-parser.d.ts +++ b/body-parser/body-parser.d.ts @@ -1,6 +1,6 @@ // Type definitions for body-parser // Project: http://expressjs.com -// Definition by: Jonathan Häberle +// Definition by: Jonathan Haeberle // Definitions: https://github.com/borisyankov/DefinitelyTyped /// From 21ec790831327a8116ac55e3dfe5a52019d147df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonathan=20H=C3=A4berle?= Date: Fri, 1 Aug 2014 16:24:03 +0200 Subject: [PATCH 227/324] Fixed Header --- body-parser/body-parser.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/body-parser/body-parser.d.ts b/body-parser/body-parser.d.ts index a1932dae0..614a63555 100644 --- a/body-parser/body-parser.d.ts +++ b/body-parser/body-parser.d.ts @@ -1,6 +1,6 @@ // Type definitions for body-parser // Project: http://expressjs.com -// Definition by: Jonathan Haeberle +// Definition by: Santi Albo , Jonathan Häberle // Definitions: https://github.com/borisyankov/DefinitelyTyped /// From 2e08343a0d65f2cacf393cf85be57f11e609366f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonathan=20H=C3=A4berle?= Date: Fri, 1 Aug 2014 16:40:46 +0200 Subject: [PATCH 228/324] typing header format fixed --- body-parser/body-parser.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/body-parser/body-parser.d.ts b/body-parser/body-parser.d.ts index 614a63555..a46b5e336 100644 --- a/body-parser/body-parser.d.ts +++ b/body-parser/body-parser.d.ts @@ -1,6 +1,6 @@ // Type definitions for body-parser // Project: http://expressjs.com -// Definition by: Santi Albo , Jonathan Häberle +// Definitions by: Jonathan Häberle // Definitions: https://github.com/borisyankov/DefinitelyTyped /// From 83717637aef10852c667b559853fa57bae0edabf Mon Sep 17 00:00:00 2001 From: Maxime Fabre Date: Fri, 1 Aug 2014 18:24:47 +0200 Subject: [PATCH 229/324] Add new accessToken property to Mapbox --- mapbox/mapbox.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/mapbox/mapbox.d.ts b/mapbox/mapbox.d.ts index cf2da20b5..d15598cfd 100644 --- a/mapbox/mapbox.d.ts +++ b/mapbox/mapbox.d.ts @@ -13,6 +13,7 @@ ////////////////////////////////////////////////////////////////////// declare module L.mapbox { + var accessToken: string; /** * Create and automatically configure a map with layers, markers, and interactivity. From 2d77b19dfab6cc00e8d9423ffa71f621709151f8 Mon Sep 17 00:00:00 2001 From: VILIC VANE Date: Fri, 1 Aug 2014 23:24:54 +0800 Subject: [PATCH 230/324] merged conflict --- body-parser/body-parser.d.ts | 180 ++++++++++++++++++++++++----------- 1 file changed, 127 insertions(+), 53 deletions(-) diff --git a/body-parser/body-parser.d.ts b/body-parser/body-parser.d.ts index a46b5e336..994aa4e1b 100644 --- a/body-parser/body-parser.d.ts +++ b/body-parser/body-parser.d.ts @@ -1,64 +1,138 @@ // Type definitions for body-parser // Project: http://expressjs.com -// Definitions by: Jonathan Häberle +// Definitions by: Santi Albo , VILIC VANE , Jonathan Häberle // Definitions: https://github.com/borisyankov/DefinitelyTyped /// declare module "body-parser" { - import express = require('express'); + import express = require('express'); - module e { + /** + * bodyParser: use individual json/urlencoded middlewares + * @deprecated + */ - // JSON Options - interface JsonOptions { - strict? : boolean; // only parse objects and arrays. (default: true) - inflate? : boolean; // if deflated bodies will be inflated. (default: true) - limit? : number; // maximum request body size. (default: <100kb>) - reviver? : (k :any, v:any) => any // passed to JSON.parse() - type? : string; // request content-type to parse (default: json) - verify? : (req : express.Request, res : express.Response, streamBuf : any, encoding : string) => void; // function to verify body content + function bodyParser(options?: { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + /** + * only parse objects and arrays. (default: true) + */ + strict?: boolean; + /** + * passed to JSON.parse(). + */ + receiver?: (key: string, value: any) => any; + /** + * parse extended syntax with the qs module. (default: true) + */ + extended?: boolean; + }): express.RequestHandler; + + module bodyParser { + export function json(options?: { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * request content-type to parse, passed directly to the type-is library. (default: 'json') + */ + type?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + /** + * only parse objects and arrays. (default: true) + */ + strict?: boolean; + /** + * passed to JSON.parse(). + */ + receiver?: (key: string, value: any) => any; + }): express.RequestHandler; + + export function raw(options?: { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * request content-type to parse, passed directly to the type-is library. (default: 'application/octet-stream') + */ + type?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + }): express.RequestHandler; + + export function text(options?: { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * request content-type to parse, passed directly to the type-is library. (default: 'text/plain') + */ + type?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + /** + * the default charset to parse as, if not specified in content-type. (default: 'utf-8') + */ + defaultCharset?: string; + }): express.RequestHandler; + + export function urlencoded(options?: { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * request content-type to parse, passed directly to the type-is library. (default: 'urlencoded') + */ + type?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + /** + * parse extended syntax with the qs module. (default: true) + */ + extended?: boolean; + }): express.RequestHandler; } - // Raw Options - interface RawOptions { - inflate? : boolean; // if deflated bodies will be inflated. (default: true) - limit? :number; // maximum request body size. (default: <100kb>) - type? : string; // request content-type to parse (default: application/octet-stream) - verify? : (req : express.Request, res : express.Response, streamBuf : any, encoding : string) => void; // function to verify body content - } - - // Text Options - interface TextOptions { - defaultCharset? : string; // the default charset to parse as, if not specified in content-type. (default: utf-8) - inflate? : boolean; // if deflated bodies will be inflated. (default: true) - limit? : number; // maximum request body size. (default: <100kb>) - type? : string; // request content-type to parse (default: text/plain) - verify? : (req : express.Request, res : express.Response, streamBuf : any, encoding : string) => void; // function to verify body content - } - - // UrlEncoded Options - interface UrlEncodedOptions { - extended? : boolean; // parse extended syntax with the qs module. (default: true) - inflate? : boolean; // if deflated bodies will be inflated. (default: true) - limit: number; // maximum request body size. (default: <100kb>) - type: string; // request content-type to parse (default: urlencoded) - verify? : (req : express.Request, res : express.Response, streamBuf : any, encoding : string) => void; // function to verify body content - } - - - // Returns middleware that only parses json - function json(options? : JsonOptions) : express.RequestHandler; - - // Returns middleware that parses all bodies as a Buffer - function raw(options? : RawOptions) : express.RequestHandler; - - // Returns middleware that parses all bodies as a string - function text(options? : TextOptions) : express.RequestHandler; - - // Returns middleware that only parses urlencoded bodies - function urlencoded(options? : UrlEncodedOptions) : express.RequestHandler; - } - - export = e; -} + export = bodyParser; +} \ No newline at end of file From 8e33cf7b841fc1bc072824d990ce970781294572 Mon Sep 17 00:00:00 2001 From: MIZUNE Pine Date: Sat, 2 Aug 2014 08:31:04 +0900 Subject: [PATCH 231/324] Add text-encoding library --- CONTRIBUTORS.md | 1 + text-encoding/text-encoding-tests.ts | 60 ++++++++++++++++++++++++++++ text-encoding/text-encoding.d.ts | 45 +++++++++++++++++++++ 3 files changed, 106 insertions(+) create mode 100644 text-encoding/text-encoding-tests.ts create mode 100644 text-encoding/text-encoding.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 088a423eb..af326634b 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -326,6 +326,7 @@ All definitions files include a header with the author and editors, so at some p * [Tags Manager](http://welldonethings.com/tags/manager) (by [Vincent Bortone](https://github.com/vbortone)) * [Teechart](http://www.steema.com) (by [Steema](http://www.steema.com)) * [text-buffer](https://github.com/atom/text-buffer) (by [vvakame](https://github.com/vvakame)) +* [text-encoding](https://github.com/inexorabletash/text-encoding) (by [MIZUNE Pine](https://github.com/pine613)) * [three.js](http://mrdoob.github.com/three.js/) (by [Kon](http://phyzkit.net/)) * [TimelineJS](https://github.com/NUKnightLab/TimelineJS) (by [Roland Zwaga](https://github.com/rolandzwaga)) * [timezonecomplete](https://github.com/SpiritIT/timezonecomplete) (by [Rogier Schouten](https://github.com/rogierschouten)) diff --git a/text-encoding/text-encoding-tests.ts b/text-encoding/text-encoding-tests.ts new file mode 100644 index 000000000..e0274a04c --- /dev/null +++ b/text-encoding/text-encoding-tests.ts @@ -0,0 +1,60 @@ +/// + +function test_encoder() { + var text = "plain text"; + var uint8array: Uint8Array; + + // constructor + uint8array = new TextEncoder().encode(text); + uint8array = new TextEncoder('utf-8').encode(text); + uint8array = new TextEncoder('windows-1252', { NONSTANDARD_allowLegacyEncoding: true }).encode(text); + + uint8array = TextEncoder().encode(text); + uint8array = TextEncoder('utf-8').encode(text); + uint8array = TextEncoder('windows-1252', { NONSTANDARD_allowLegacyEncoding: true }).encode(text); + + // attributes + var encoder = new TextEncoder(); + encoder.encoding = 'utf-8'; + var encoding: string = encoder.encoding; + + // methods + encoder.encode(); + encoder.encode(text); + encoder.encode(text, { stream: true }); +} + +function test_decoder() { + var text = "plain text"; + var uint8array: Uint8Array = TextEncoder().encode(text); + + // constructor + text = new TextDecoder().decode(uint8array); + text = new TextDecoder('utf-8').decode(uint8array); + text = new TextDecoder('windows-1252', {}).decode(uint8array); + text = new TextDecoder('windows-1252', { fatal: true }).decode(uint8array); + text = new TextDecoder('windows-1252', { ignoreBOM: true }).decode(uint8array); + + text = TextDecoder().decode(uint8array); + text = TextDecoder('utf-8').decode(uint8array); + text = TextDecoder('windows-1252', {}).decode(uint8array); + text = TextDecoder('windows-1252', { fatal: true }).decode(uint8array); + text = TextDecoder('windows-1252', { ignoreBOM: true }).decode(uint8array); + + // attributes + var decoder = new TextDecoder(); + + decoder.encoding = 'utf-8'; + var encoding: string = decoder.encoding; + + decoder.fatal = true; + var fatal: boolean = decoder.fatal; + + decoder.ignoreBOM = true; + var ignoreBOM: boolean = decoder.ignoreBOM; + + // methods + decoder.decode(); + decoder.decode(uint8array); + decoder.decode(uint8array, { stream: true }); +} \ No newline at end of file diff --git a/text-encoding/text-encoding.d.ts b/text-encoding/text-encoding.d.ts new file mode 100644 index 000000000..422597b41 --- /dev/null +++ b/text-encoding/text-encoding.d.ts @@ -0,0 +1,45 @@ +// Type definitions for text-encoding +// Project: https://github.com/inexorabletash/text-encoding +// Definitions by: MIZUNE Pine +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module TextEncodingStatic { + interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; + } + + interface TextDecodeOptions { + stream?: boolean; + } + + interface TextEncoderOptions { + NONSTANDARD_allowLegacyEncoding?: boolean; + } + + interface TextDecoder { + encoding: string; + fatal: boolean; + ignoreBOM: boolean; + decode(input?: ArrayBufferView, options?: TextDecodeOptions): string; + } + + interface TextEncoder { + encoding: string; + encode(input?: string, options?: TextEncodeOptions): Uint8Array; + } + + interface TextEncodeOptions { + stream?: boolean; + } +} + +declare var TextDecoder: { + (label?: string, options?: TextEncodingStatic.TextDecoderOptions): TextEncodingStatic.TextDecoder; + new (label?: string, options?: TextEncodingStatic.TextDecoderOptions): TextEncodingStatic.TextDecoder; +}; + +declare var TextEncoder: { + (utfLabel?: string, options?: TextEncodingStatic.TextEncoderOptions): TextEncodingStatic.TextEncoder; + new (utfLabel?: string, options?: TextEncodingStatic.TextEncoderOptions): TextEncodingStatic.TextEncoder; +}; \ No newline at end of file From a417b07f5b2ebc8610c24d8f35a5fc3d66384b91 Mon Sep 17 00:00:00 2001 From: Atsushi Kanehara Date: Sat, 2 Aug 2014 08:57:23 +0900 Subject: [PATCH 232/324] Fixed signature of `verifyClient`. --- ws/ws.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ws/ws.d.ts b/ws/ws.d.ts index ef7acc3ba..d12e2913f 100644 --- a/ws/ws.d.ts +++ b/ws/ws.d.ts @@ -91,8 +91,8 @@ declare module "ws" { port?: number; server?: http.Server; verifyClient?: { - (info: {origin: string; secure: boolean; req: http.ClientRequest}): boolean; - (info: {origin: string; secure: boolean; req: http.ClientRequest}, + (info: {origin: string; secure: boolean; req: http.ServerRequest}): boolean; + (info: {origin: string; secure: boolean; req: http.ServerRequest}, callback: (res: boolean) => void): void; }; handleProtocols?: any; From c874738f2eee50077d77659a114ad05e449f5f77 Mon Sep 17 00:00:00 2001 From: Paulo Cesar Date: Sat, 2 Aug 2014 01:23:38 -0300 Subject: [PATCH 233/324] add angular $viewChangeListeners to ngModelController --- angularjs/angular.d.ts | 93 ++++++++++++++++++++++-------------------- 1 file changed, 49 insertions(+), 44 deletions(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index c515b096f..e447985fb 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -22,7 +22,7 @@ declare module ng { interface IServiceProviderClass { new(...args: any[]): IServiceProvider; } - + interface IServiceProviderFactory { (...args: any[]): IServiceProvider; } @@ -49,9 +49,9 @@ declare module ng { /** * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. - * + * * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. - * + * * @param obj Object to iterate over. * @param iterator Iterator function. * @param context Object to become context (this) for the iterator function. @@ -59,9 +59,9 @@ declare module ng { forEach(obj: T[], iterator: (value: T, key: number) => any, context?: any): any; /** * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. - * + * * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. - * + * * @param obj Object to iterate over. * @param iterator Iterator function. * @param context Object to become context (this) for the iterator function. @@ -69,9 +69,9 @@ declare module ng { forEach(obj: { [index: string]: T; }, iterator: (value: T, key: string) => any, context?: any): any; /** * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. - * + * * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. - * + * * @param obj Object to iterate over. * @param iterator Iterator function. * @param context Object to become context (this) for the iterator function. @@ -96,7 +96,7 @@ declare module ng { * The angular.module is a global place for creating, registering and retrieving Angular modules. All modules (angular core or 3rd party) that should be available to an application must be registered using this mechanism. * * When passed two or more arguments, a new module is created. If passed only one argument, an existing module (the name passed as the first argument to module) is retrieved. - * + * * @param name The name of the module to create or retrieve. * @param requires The names of modules this module depends on. If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. * @param configFn Optional configuration function for the module. @@ -128,19 +128,19 @@ declare module ng { animation(object: Object): IModule; /** * Use this method to register work which needs to be performed on module loading. - * + * * @param configFn Execute this function on module load. Useful for service configuration. */ config(configFn: Function): IModule; /** * Use this method to register work which needs to be performed on module loading. - * + * * @param inlineAnnotatedFunction Execute this function on module load. Useful for service configuration. */ config(inlineAnnotatedFunction: any[]): IModule; /** * Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator. - * + * * @param name The name of the constant. * @param value The constant value. */ @@ -148,18 +148,18 @@ declare module ng { constant(object: Object): IModule; /** * The $controller service is used by Angular to create new controllers. - * + * * This provider allows controller registration via the register method. - * + * * @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors. * @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation). */ controller(name: string, controllerConstructor: Function): IModule; /** * The $controller service is used by Angular to create new controllers. - * + * * This provider allows controller registration via the register method. - * + * * @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors. * @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation). */ @@ -170,14 +170,14 @@ declare module ng { directive(object: Object): IModule; /** * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider. - * + * * @param name The name of the instance. * @param $getFn The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}). */ factory(name: string, $getFn: Function): IModule; /** * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider. - * + * * @param name The name of the instance. * @param inlineAnnotatedFunction The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}). */ @@ -291,6 +291,7 @@ declare module ng { $parsers: IModelParser[]; $formatters: IModelFormatter[]; + $viewChangeListeners: IModelViewChangeListener[]; $error: any; $pristine: boolean; $dirty: boolean; @@ -306,6 +307,10 @@ declare module ng { (value: any): any; } + interface IModelViewChangeListener { + (): void; + } + /////////////////////////////////////////////////////////////////////////// // Scope // see http://docs.angularjs.org/api/ng.$rootScope.Scope @@ -574,17 +579,17 @@ declare module ng { interface IQService { /** * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. - * + * * Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. - * + * * @param promises An array or hash of promises. */ all(promises: IPromise[]): IPromise; /** * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. - * + * * Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. - * + * * @param promises An array or hash of promises. */ all(promises: { [id: string]: IPromise; }): IPromise<{ [id: string]: any }>; @@ -594,27 +599,27 @@ declare module ng { defer(): IDeferred; /** * Creates a promise that is resolved as rejected with the specified reason. This api should be used to forward rejection in a chain of promises. If you are dealing with the last promise in a promise chain, you don't need to worry about it. - * + * * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of reject as the throw keyword in JavaScript. This also means that if you "catch" an error via a promise error callback and you want to forward the error to the promise derived from the current promise, you have to "rethrow" the error by returning a rejection constructed via reject. - * + * * @param reason Constant, message, exception or an object representing the rejection reason. */ reject(reason?: any): IPromise; /** * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. - * + * * @param value Value or a promise */ when(value: IPromise): IPromise; /** * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. - * + * * @param value Value or a promise */ when(value: T): IPromise; /** * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. - * + * * @param value Value or a promise */ when(): IPromise; @@ -702,7 +707,7 @@ declare module ng { aHrefSanitizationWhitelist(): RegExp; aHrefSanitizationWhitelist(regexp: RegExp): ICompileProvider; - + imgSrcSanitizationWhitelist(): RegExp; imgSrcSanitizationWhitelist(regexp: RegExp): ICompileProvider; } @@ -742,7 +747,7 @@ declare module ng { } /** - * HttpService + * HttpService * see http://docs.angularjs.org/api/ng/service/$http */ interface IHttpService { @@ -753,7 +758,7 @@ declare module ng { /** * Shortcut method to perform GET request. - * + * * @param url Relative or absolute URL specifying the destination of the request * @param config Optional configuration object */ @@ -761,7 +766,7 @@ declare module ng { /** * Shortcut method to perform DELETE request. - * + * * @param url Relative or absolute URL specifying the destination of the request * @param config Optional configuration object */ @@ -769,7 +774,7 @@ declare module ng { /** * Shortcut method to perform HEAD request. - * + * * @param url Relative or absolute URL specifying the destination of the request * @param config Optional configuration object */ @@ -777,7 +782,7 @@ declare module ng { /** * Shortcut method to perform JSONP request. - * + * * @param url Relative or absolute URL specifying the destination of the request * @param config Optional configuration object */ @@ -785,7 +790,7 @@ declare module ng { /** * Shortcut method to perform POST request. - * + * * @param url Relative or absolute URL specifying the destination of the request * @param data Request content * @param config Optional configuration object @@ -794,7 +799,7 @@ declare module ng { /** * Shortcut method to perform PUT request. - * + * * @param url Relative or absolute URL specifying the destination of the request * @param data Request content * @param config Optional configuration object @@ -814,12 +819,12 @@ declare module ng { /** * Object describing the request to be made and how it should be processed. - * see http://docs.angularjs.org/api/ng/service/$http#usage + * see http://docs.angularjs.org/api/ng/service/$http#usage */ interface IRequestShortcutConfig { /** * {Object.} - * Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified. + * Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified. */ params?: any; @@ -850,7 +855,7 @@ declare module ng { withCredentials?: boolean; /** - * {string|Object} + * {string|Object} * Data to be sent as the request message data. */ data?: any; @@ -881,7 +886,7 @@ declare module ng { /** * Object describing the request to be made and how it should be processed. - * see http://docs.angularjs.org/api/ng/service/$http#usage + * see http://docs.angularjs.org/api/ng/service/$http#usage */ interface IRequestConfig extends IRequestShortcutConfig { /** @@ -1114,7 +1119,7 @@ declare module ng { annotate(fn: Function): string[]; annotate(inlineAnnotatedFunction: any[]): string[]; get(name: string): any; - has(name: string): boolean; + has(name: string): boolean; instantiate(typeConstructor: Function, locals?: any): any; invoke(inlineAnnotatedFunction: any[]): any; invoke(func: Function, context?: any, locals?: any): any; @@ -1130,7 +1135,7 @@ declare module ng { // constant(name: string, value: any): any; /** * Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator. - * + * * @param name The name of the constant. * @param value The constant value. */ @@ -1138,19 +1143,19 @@ declare module ng { /** * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. - * + * * @param name The name of the service to decorate. * @param decorator This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: - * + * * $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to. */ decorator(name: string, decorator: Function): void; /** * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. - * + * * @param name The name of the service to decorate. * @param inlineAnnotatedFunction This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: - * + * * $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to. */ decorator(name: string, inlineAnnotatedFunction: any[]): void; From 281db74a55053efb4084f96021be65eafd96029f Mon Sep 17 00:00:00 2001 From: MIZUNE Pine Date: Sat, 2 Aug 2014 21:59:16 +0900 Subject: [PATCH 234/324] Change module name --- text-encoding/text-encoding.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/text-encoding/text-encoding.d.ts b/text-encoding/text-encoding.d.ts index 422597b41..574b25d71 100644 --- a/text-encoding/text-encoding.d.ts +++ b/text-encoding/text-encoding.d.ts @@ -3,7 +3,7 @@ // Definitions by: MIZUNE Pine // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module TextEncodingStatic { +declare module TextEncoding { interface TextDecoderOptions { fatal?: boolean; ignoreBOM?: boolean; @@ -35,11 +35,11 @@ declare module TextEncodingStatic { } declare var TextDecoder: { - (label?: string, options?: TextEncodingStatic.TextDecoderOptions): TextEncodingStatic.TextDecoder; - new (label?: string, options?: TextEncodingStatic.TextDecoderOptions): TextEncodingStatic.TextDecoder; + (label?: string, options?: TextEncoding.TextDecoderOptions): TextEncoding.TextDecoder; + new (label?: string, options?: TextEncoding.TextDecoderOptions): TextEncoding.TextDecoder; }; declare var TextEncoder: { - (utfLabel?: string, options?: TextEncodingStatic.TextEncoderOptions): TextEncodingStatic.TextEncoder; - new (utfLabel?: string, options?: TextEncodingStatic.TextEncoderOptions): TextEncodingStatic.TextEncoder; + (utfLabel?: string, options?: TextEncoding.TextEncoderOptions): TextEncoding.TextEncoder; + new (utfLabel?: string, options?: TextEncoding.TextEncoderOptions): TextEncoding.TextEncoder; }; \ No newline at end of file From b7dda17cc1b21040560192daeccead6114fdce8f Mon Sep 17 00:00:00 2001 From: Paulo Cesar Date: Sat, 2 Aug 2014 13:59:17 -0300 Subject: [PATCH 235/324] angular directive changes, still missing #2605 --- angularjs/angular-tests.ts | 461 ++++++++++++++++++++----------------- angularjs/angular.d.ts | 38 +-- 2 files changed, 269 insertions(+), 230 deletions(-) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index a1577856e..2507d7f8c 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -231,11 +231,11 @@ foo.then((x) => { }).then((x) => { // Object is inferred here x.a = 123; - //Try a promise + //Try a promise var y: ng.IPromise; - return y; + return y; }).then((x) => { - // x is infered to be a number, which is the resolved value of a promise + // x is infered to be a number, which is the resolved value of a promise x.toFixed(); }); @@ -281,252 +281,279 @@ test_IAttributes({ $attr: {} }); +class SampleDirective implements ng.IDirective { + public restrict = 'A'; + name = 'doh'; + + compile(templateElement: any) { + return this.link; + } + + link(scope: any) { + + } +} + +class SampleDirective2 implements ng.IDirective { + public restrict = 'EAC'; + + compile(templateElement: any) { + return { + pre: this.link + }; + } + + link(scope: any) { + + } +} + // test from https://docs.angularjs.org/guide/directive angular.module('docsSimpleDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.customer = { - name: 'Naomi', - address: '1600 Amphitheatre' - }; - }]) - .directive('myCustomer', function() { - return { - template: 'Name: {{customer.name}} Address: {{customer.address}}' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + template: 'Name: {{customer.name}} Address: {{customer.address}}' + }; + }); angular.module('docsTemplateUrlDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.customer = { - name: 'Naomi', - address: '1600 Amphitheatre' - }; - }]) - .directive('myCustomer', function() { - return { - templateUrl: 'my-customer.html' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + templateUrl: 'my-customer.html' + }; + }); angular.module('docsRestrictDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.customer = { - name: 'Naomi', - address: '1600 Amphitheatre' - }; - }]) - .directive('myCustomer', function() { - return { - restrict: 'E', - templateUrl: 'my-customer.html' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + templateUrl: 'my-customer.html' + }; + }); angular.module('docsScopeProblemExample', []) - .controller('NaomiController', ['$scope', function($scope: any) { - $scope.customer = { - name: 'Naomi', - address: '1600 Amphitheatre' - }; - }]) - .controller('IgorController', ['$scope', function($scope: any) { - $scope.customer = { - name: 'Igor', - address: '123 Somewhere' - }; - }]) - .directive('myCustomer', function() { - return { - restrict: 'E', - templateUrl: 'my-customer.html' - }; - }); + .controller('NaomiController', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .controller('IgorController', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Igor', + address: '123 Somewhere' + }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + templateUrl: 'my-customer.html' + }; + }); angular.module('docsIsolateScopeDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; - $scope.igor = { name: 'Igor', address: '123 Somewhere' }; - }]) - .directive('myCustomer', function() { - return { - restrict: 'E', - scope: { - customerInfo: '=info' - }, - templateUrl: 'my-customer-iso.html' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; + $scope.igor = { name: 'Igor', address: '123 Somewhere' }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + scope: { + customerInfo: '=info' + }, + templateUrl: 'my-customer-iso.html' + }; + }); angular.module('docsIsolationExample', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; - $scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' }; - }]) - .directive('myCustomer', function() { - return { - restrict: 'E', - scope: { - customerInfo: '=info' - }, - templateUrl: 'my-customer-plus-vojta.html' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; + $scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + scope: { + customerInfo: '=info' + }, + templateUrl: 'my-customer-plus-vojta.html' + }; + }); angular.module('docsTimeDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.format = 'M/d/yy h:mm:ss a'; - }]) - .directive('myCurrentTime', ['$interval', 'dateFilter', function($interval: any, dateFilter: any): ng.IDirective { + .controller('Controller', ['$scope', function($scope: any) { + $scope.format = 'M/d/yy h:mm:ss a'; + }]) + .directive('myCurrentTime', ['$interval', 'dateFilter', function($interval: any, dateFilter: any): ng.IDirective { - return { - link: function(scope: any, element: any, attrs: any) { - var format: any, - timeoutId: any; + return { + link: function(scope: any, element: any, attrs: any) { + var format: any, + timeoutId: any; - function updateTime() { - element.text(dateFilter(new Date(), format)); - } + function updateTime() { + element.text(dateFilter(new Date(), format)); + } - scope.$watch(attrs.myCurrentTime, function (value: any) { - format = value; - updateTime(); - }); + scope.$watch(attrs.myCurrentTime, function (value: any) { + format = value; + updateTime(); + }); - element.on('$destroy', function () { - $interval.cancel(timeoutId); - }); + element.on('$destroy', function () { + $interval.cancel(timeoutId); + }); - // start the UI update process; save the timeoutId for canceling - timeoutId = $interval(function () { - updateTime(); // update DOM - }, 1000); - } - }; - }]); + // start the UI update process; save the timeoutId for canceling + timeoutId = $interval(function () { + updateTime(); // update DOM + }, 1000); + } + }; + }]); angular.module('docsTransclusionDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.name = 'Tobias'; - }]) - .directive('myDialog', function() { - return { - restrict: 'E', - transclude: true, - templateUrl: 'my-dialog.html' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.name = 'Tobias'; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + templateUrl: 'my-dialog.html' + }; + }); angular.module('docsTransclusionExample', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.name = 'Tobias'; - }]) - .directive('myDialog', function() { - return { - restrict: 'E', - transclude: true, - scope: {}, - templateUrl: 'my-dialog.html', - link: function (scope: any, element: any) { - scope.name = 'Jeff'; - } - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.name = 'Tobias'; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + scope: {}, + templateUrl: 'my-dialog.html', + link: function (scope: any, element: any) { + scope.name = 'Jeff'; + } + }; + }); angular.module('docsIsoFnBindExample', []) - .controller('Controller', ['$scope', '$timeout', function($scope: any, $timeout: any) { - $scope.name = 'Tobias'; - $scope.hideDialog = function () { - $scope.dialogIsHidden = true; - $timeout(function () { - $scope.dialogIsHidden = false; - }, 2000); - }; - }]) - .directive('myDialog', function() { - return { - restrict: 'E', - transclude: true, - scope: { - 'close': '&onClose' - }, - templateUrl: 'my-dialog-close.html' - }; - }); + .controller('Controller', ['$scope', '$timeout', function($scope: any, $timeout: any) { + $scope.name = 'Tobias'; + $scope.hideDialog = function () { + $scope.dialogIsHidden = true; + $timeout(function () { + $scope.dialogIsHidden = false; + }, 2000); + }; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + scope: { + 'close': '&onClose' + }, + templateUrl: 'my-dialog-close.html' + }; + }); angular.module('dragModule', []) - .directive('myDraggable', ['$document', function($document: any) { - return function(scope: any, element: any, attr: any) { - var startX = 0, startY = 0, x = 0, y = 0; + .directive('myDraggable', ['$document', function($document: any) { + return function(scope: any, element: any, attr: any) { + var startX = 0, startY = 0, x = 0, y = 0; - element.css({ - position: 'relative', - border: '1px solid red', - backgroundColor: 'lightgrey', - cursor: 'pointer' - }); + element.css({ + position: 'relative', + border: '1px solid red', + backgroundColor: 'lightgrey', + cursor: 'pointer' + }); - element.on('mousedown', function(event: any) { - // Prevent default dragging of selected content - event.preventDefault(); - startX = event.pageX - x; - startY = event.pageY - y; - $document.on('mousemove', mousemove); - $document.on('mouseup', mouseup); - }); + element.on('mousedown', function(event: any) { + // Prevent default dragging of selected content + event.preventDefault(); + startX = event.pageX - x; + startY = event.pageY - y; + $document.on('mousemove', mousemove); + $document.on('mouseup', mouseup); + }); - function mousemove(event: any) { - y = event.pageY - startY; - x = event.pageX - startX; - element.css({ - top: y + 'px', - left: x + 'px' - }); - } + function mousemove(event: any) { + y = event.pageY - startY; + x = event.pageX - startX; + element.css({ + top: y + 'px', + left: x + 'px' + }); + } - function mouseup() { - $document.off('mousemove', mousemove); - $document.off('mouseup', mouseup); - } - }; - }]); + function mouseup() { + $document.off('mousemove', mousemove); + $document.off('mouseup', mouseup); + } + }; + }]); angular.module('docsTabsExample', []) - .directive('myTabs', function() { - return { - restrict: 'E', - transclude: true, - scope: {}, - controller: function($scope: any) { - var panes: any = $scope.panes = []; + .directive('myTabs', function() { + return { + restrict: 'E', + transclude: true, + scope: {}, + controller: function($scope: any) { + var panes: any = $scope.panes = []; - $scope.select = function(pane: any) { - angular.forEach(panes, function(pane: any) { - pane.selected = false; - }); - pane.selected = true; - }; + $scope.select = function(pane: any) { + angular.forEach(panes, function(pane: any) { + pane.selected = false; + }); + pane.selected = true; + }; - this.addPane = function(pane: any) { - if (panes.length === 0) { - $scope.select(pane); - } - panes.push(pane); - }; - }, - templateUrl: 'my-tabs.html' - }; - }) - .directive('myPane', function() { - return { - require: '^myTabs', - restrict: 'E', - transclude: true, - scope: { - title: '@' - }, - link: function(scope, element, attrs, tabsCtrl) { - tabsCtrl.addPane(scope); - }, - templateUrl: 'my-pane.html' - }; - }); + this.addPane = function(pane: any) { + if (panes.length === 0) { + $scope.select(pane); + } + panes.push(pane); + }; + }, + templateUrl: 'my-tabs.html' + }; + }) + .directive('myPane', function() { + return { + require: '^myTabs', + restrict: 'E', + transclude: true, + scope: { + title: '@' + }, + link: function(scope: any, element: any, attrs: any, tabsCtrl: any) { + tabsCtrl.addPane(scope); + }, + templateUrl: 'my-pane.html' + }; + }); diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index e447985fb..b1b5e358f 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1031,22 +1031,34 @@ declare module ng { (...args: any[]): IDirective; } + interface IDirectiveLinkFn { + ( + scope?: IScope, + instanceElement?: IAugmentedJQuery, + instanceAttributes?: IAttributes, + controller?: any, + transclude?: ITranscludeFunction + ): void; + } - interface IDirective{ - compile?: - (templateElement: IAugmentedJQuery, - templateAttributes: IAttributes, - transclude: ITranscludeFunction - ) => any; + interface IDirectivePrePost { + pre?: IDirectiveLinkFn; + post?: IDirectiveLinkFn; + } + + interface IDirectiveCompileFn { + ( + templateElement?: IAugmentedJQuery, + templateAttributes?: IAttributes, + transclude?: ITranscludeFunction + ): IDirectivePrePost; + } + + interface IDirective { + compile?: IDirectiveCompileFn; controller?: any; controllerAs?: string; - link?: - (scope: IScope, - instanceElement: IAugmentedJQuery, - instanceAttributes: IAttributes, - controller: any, - transclude: ITranscludeFunction - ) => void; + link?: IDirectivePrePost; name?: string; priority?: number; replace?: boolean; From 12fba7b62683f4ed7a78247756b69bdb06675ada Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonathan=20H=C3=A4berle?= Date: Sat, 2 Aug 2014 20:29:45 +0200 Subject: [PATCH 236/324] missing npost() function added --- q/Q.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/q/Q.d.ts b/q/Q.d.ts index 8e9696be5..617bf0140 100644 --- a/q/Q.d.ts +++ b/q/Q.d.ts @@ -214,6 +214,7 @@ declare module Q { export function nfapply(nodeFunction: Function, args: any[]): Promise; export function ninvoke(nodeModule: any, functionName: string, ...args: any[]): Promise; + export function npost(nodeModule: any, functionName: string, args: any[]): Promise; export function nsend(nodeModule: any, functionName: string, ...args: any[]): Promise; export function nmcall(nodeModule: any, functionName: string, ...args: any[]): Promise; From 64795f2f0f0b96d7bf95d1d485e11dbc6d6703d1 Mon Sep 17 00:00:00 2001 From: James Roland Cabresos Date: Sun, 3 Aug 2014 04:47:28 +0800 Subject: [PATCH 237/324] Added morgan definitions --- morgan/morgan-tests.ts | 29 +++++++++++++ morgan/morgan.d.ts | 93 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 122 insertions(+) create mode 100644 morgan/morgan-tests.ts create mode 100644 morgan/morgan.d.ts diff --git a/morgan/morgan-tests.ts b/morgan/morgan-tests.ts new file mode 100644 index 000000000..00e67f875 --- /dev/null +++ b/morgan/morgan-tests.ts @@ -0,0 +1,29 @@ +/// +/** + * Created by staticfunction on 8/3/14. + */ + +import morgan = require('morgan'); + +// a pre-defined name +morgan('combined') +morgan('common') +morgan('short') +morgan('tiny') + +// a format string +morgan(':remote-addr :method :url') + +// a custom function +morgan(function (req, res) { + return req.method + ' ' + req.url +}) + +morgan('combined', { + buffer: true, + immediate: true, + skip: function (req, res) { return res.statusCode < 400 }, + stream: (str: string) => { + console.log(str); + } +}); diff --git a/morgan/morgan.d.ts b/morgan/morgan.d.ts new file mode 100644 index 000000000..b889bc7be --- /dev/null +++ b/morgan/morgan.d.ts @@ -0,0 +1,93 @@ +// Type definitions for morgan 1.2.2 +// Project: https://github.com/expressjs/morgan +// Definitions by: James Roland Cabresos +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +declare module "morgan" { + + import express = require('express'); + + module morgan { + + export function token(name: string, callback: (req: express.Request, res: express.Response) => T): express.RequestHandler; + + /*** + * Morgan accepts these properties in the options object. + */ + export interface Options { + + /*** + * Buffer duration before writing logs to the stream, defaults to false. When set to true, defaults to 1000 ms. + */ + buffer?: boolean; + + /*** + * Write log line on request instead of response. This means that a requests will be logged even if the server crashes, but data from the response cannot be logged (like the response code). + */ + immediate?: boolean; + + /*** + * Function to determine if logging is skipped, defaults to false. This function will be called as skip(req, res). + */ + skip?: (req: express.Request, res: express.Response) => boolean; + + /*** + * Output stream for writing log lines, defaults to process.stdout. + * @param str + */ + stream?: (str: string) => void; + } + } + + /*** + * Create a new morgan logger middleware function using the given format and options. The format argument may be a string of a predefined name (see below for the names), a string of a format string, or a function that will produce a log entry. + * @param format + * @param options + */ + function morgan(format: string, options?: morgan.Options): express.RequestHandler; + + /*** + * Standard Apache combined log output. + * :remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" + * @param format + * @param options + */ + function morgan(format: 'combined', options?: morgan.Options): express.RequestHandler; + + /*** + * Standard Apache common log output. + * :remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length] + * @param format + * @param options + */ + function morgan(format: 'common', options?: morgan.Options): express.RequestHandler; + + /*** + * Concise output colored by response status for development use. The :status token will be colored red for server error codes, yellow for client error codes, cyan for redirection codes, and uncolored for all other codes. + * :method :url :status :response-time ms - :res[content-length] + * @param format + * @param options + */ + function morgan(format: 'dev', options?: morgan.Options): express.RequestHandler; + + /*** + * Shorter than default, also including response time. + * :remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms + * @param format + * @param options + */ + function morgan(format: 'short', options?: morgan.Options): express.RequestHandler; + + /*** + * The minimal output. + * :method :url :status :res[content-length] - :response-time ms + * @param format + * @param options + */ + function morgan(format: 'tiny', options?: morgan.Options): express.RequestHandler; + + function morgan(custom: (req: express.Request, res: express.Response) => string): express.RequestHandler + + export = morgan; +} \ No newline at end of file From d9ada3076f601e05a8fb85eee418ced6ba545e26 Mon Sep 17 00:00:00 2001 From: satoru kimura Date: Sun, 3 Aug 2014 13:13:23 +0900 Subject: [PATCH 238/324] update to three.js r68. --- threejs/tests/canvas/canvas_geometry_cube.ts | 2 +- .../canvas/canvas_interactive_cubes_tween.ts | 1 + .../tests/canvas/canvas_lights_pointlights.ts | 43 +- threejs/tests/canvas/canvas_materials.ts | 19 +- threejs/tests/css3d/css3d_sprites.ts | 20 +- threejs/tests/math/test_unit_math.ts | 640 ++++++++++++---- .../webgl/webgl_animation_skinning_morph.ts | 297 ++++++++ threejs/tests/webgl/webgl_buffergeometry.ts | 18 +- threejs/tests/webgl/webgl_camera.ts | 2 +- ...webgl_interactive_raycasting_pointcloud.ts | 335 +++++++++ threejs/tests/webgl/webgl_lensflares.ts | 2 +- threejs/tests/webgl/webgl_materials.ts | 10 +- .../tests/webgl/webgl_particles_billboards.ts | 4 +- threejs/tests/webgl/webgl_postprocessing.ts | 2 - threejs/three-tests.ts | 3 + threejs/three.d.ts | 710 ++++++++++++------ 16 files changed, 1653 insertions(+), 455 deletions(-) create mode 100644 threejs/tests/webgl/webgl_animation_skinning_morph.ts create mode 100644 threejs/tests/webgl/webgl_interactive_raycasting_pointcloud.ts diff --git a/threejs/tests/canvas/canvas_geometry_cube.ts b/threejs/tests/canvas/canvas_geometry_cube.ts index 00c3b0426..bf5f9ae99 100644 --- a/threejs/tests/canvas/canvas_geometry_cube.ts +++ b/threejs/tests/canvas/canvas_geometry_cube.ts @@ -43,7 +43,7 @@ // Cube - var geometry = new THREE.CubeGeometry(200, 200, 200); + var geometry = new THREE.BoxGeometry(200, 200, 200); for (var i = 0; i < geometry.faces.length; i += 2) { diff --git a/threejs/tests/canvas/canvas_interactive_cubes_tween.ts b/threejs/tests/canvas/canvas_interactive_cubes_tween.ts index 8fbd7c2cf..865e07023 100644 --- a/threejs/tests/canvas/canvas_interactive_cubes_tween.ts +++ b/threejs/tests/canvas/canvas_interactive_cubes_tween.ts @@ -1,5 +1,6 @@ /// /// +/// // https://github.com/mrdoob/three.js/blob/master/examples/canvas_interactive_cubes_tween.html diff --git a/threejs/tests/canvas/canvas_lights_pointlights.ts b/threejs/tests/canvas/canvas_lights_pointlights.ts index 1b6a6663f..ad1a103d5 100644 --- a/threejs/tests/canvas/canvas_lights_pointlights.ts +++ b/threejs/tests/canvas/canvas_lights_pointlights.ts @@ -7,7 +7,6 @@ // ------- variable definitions that does not exist in the original code. These are for typescript. // ------- var camera, scene, renderer, - particle1, particle2, particle3, light1, light2, light3, loader, mesh; @@ -43,14 +42,14 @@ } - particle1 = new THREE.Sprite(new THREE.SpriteCanvasMaterial({ color: 0xff0040, program: program })); - scene.add(particle1); + var sprite = new THREE.Sprite( new THREE.SpriteCanvasMaterial( { color: 0xff0040, program: program } ) ); + light1.add( sprite ); - particle2 = new THREE.Sprite(new THREE.SpriteCanvasMaterial({ color: 0x0040ff, program: program })); - scene.add(particle2); + var sprite = new THREE.Sprite( new THREE.SpriteCanvasMaterial( { color: 0x0040ff, program: program } ) ); + light2.add( sprite ); - particle3 = new THREE.Sprite(new THREE.SpriteCanvasMaterial({ color: 0x80ff80, program: program })); - scene.add(particle3); + var sprite = new THREE.Sprite( new THREE.SpriteCanvasMaterial( { color: 0x80ff80, program: program } ) ); + light3.add( sprite ); loader = new THREE.JSONLoader(); loader.load('obj/WaltHeadLo.js', function (geometry) { @@ -94,29 +93,17 @@ if (mesh) mesh.rotation.y -= 0.01; - particle1.position.x = Math.sin(time * 0.7) * 30; - particle1.position.y = Math.cos(time * 0.5) * 40; - particle1.position.z = Math.cos(time * 0.3) * 30; + light1.position.x = Math.sin( time * 0.7 ) * 30; + light1.position.y = Math.cos( time * 0.5 ) * 40; + light1.position.z = Math.cos( time * 0.3 ) * 30; - light1.position.x = particle1.position.x; - light1.position.y = particle1.position.y; - light1.position.z = particle1.position.z; + light2.position.x = Math.cos( time * 0.3 ) * 30; + light2.position.y = Math.sin( time * 0.5 ) * 40; + light2.position.z = Math.sin( time * 0.7 ) * 30; - particle2.position.x = Math.cos(time * 0.3) * 30; - particle2.position.y = Math.sin(time * 0.5) * 40; - particle2.position.z = Math.sin(time * 0.7) * 30; - - light2.position.x = particle2.position.x; - light2.position.y = particle2.position.y; - light2.position.z = particle2.position.z; - - particle3.position.x = Math.sin(time * 0.7) * 30; - particle3.position.y = Math.cos(time * 0.3) * 40; - particle3.position.z = Math.sin(time * 0.5) * 30; - - light3.position.x = particle3.position.x; - light3.position.y = particle3.position.y; - light3.position.z = particle3.position.z; + light3.position.x = Math.sin( time * 0.7 ) * 30; + light3.position.y = Math.cos( time * 0.3 ) * 40; + light3.position.z = Math.sin( time * 0.5 ) * 30; renderer.render(scene, camera); diff --git a/threejs/tests/canvas/canvas_materials.ts b/threejs/tests/canvas/canvas_materials.ts index 23524098a..a39a780ca 100644 --- a/threejs/tests/canvas/canvas_materials.ts +++ b/threejs/tests/canvas/canvas_materials.ts @@ -11,7 +11,7 @@ var container, stats; var camera, scene, renderer, objects; - var particleLight, pointLight; + var pointLight; init(); animate(); @@ -103,10 +103,6 @@ } - particleLight = new THREE.Sprite(new THREE.SpriteCanvasMaterial({ color: 0xffffff, program: program })); - particleLight.scale.x = particleLight.scale.y = 8; - scene.add(particleLight); - // Lights scene.add(new THREE.AmbientLight(Math.random() * 0x202020)); @@ -121,6 +117,10 @@ pointLight = new THREE.PointLight(0xffffff, 1); scene.add(pointLight); + var sprite = new THREE.Sprite( new THREE.SpriteCanvasMaterial( { color: 0xffffff, program: program } ) ); + sprite.scale.set( 8, 8, 8 ); + pointLight.add( sprite ); + renderer = new THREE.CanvasRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); container.appendChild(renderer.domElement); @@ -198,13 +198,10 @@ } - particleLight.position.x = Math.sin(timer * 7) * 300; - particleLight.position.y = Math.cos(timer * 5) * 400; - particleLight.position.z = Math.cos(timer * 3) * 300; + pointLight.position.x = Math.sin( timer * 7 ) * 300; + pointLight.position.y = Math.cos( timer * 5 ) * 400; + pointLight.position.z = Math.cos( timer * 3 ) * 300; - pointLight.position.x = particleLight.position.x; - pointLight.position.y = particleLight.position.y; - pointLight.position.z = particleLight.position.z; renderer.render(scene, camera); diff --git a/threejs/tests/css3d/css3d_sprites.ts b/threejs/tests/css3d/css3d_sprites.ts index 20760735a..0b69a85bf 100644 --- a/threejs/tests/css3d/css3d_sprites.ts +++ b/threejs/tests/css3d/css3d_sprites.ts @@ -1,5 +1,6 @@ /// /// +/// // https://github.com/mrdoob/three.js/blob/master/examples/css3d_sprites.html @@ -26,23 +27,16 @@ scene = new THREE.Scene(); - var sprite = document.createElement('img'); - sprite.addEventListener('load', function (event) { + var image = document.createElement( 'img' ); + image.addEventListener( 'load', function ( event ) { - for (var i = 0, j = 0; i < particlesTotal; i++, j += 3) { + for ( var i = 0; i < particlesTotal; i ++ ) { - var canvas = document.createElement('canvas'); - canvas.width = sprite.width; - canvas.height = sprite.height; - - var context = canvas.getContext('2d'); - context.drawImage(sprite, 0, 0); - - var object = new THREE.CSS3DSprite(canvas); + var object = new THREE.CSS3DSprite( image.cloneNode() ); object.position.x = Math.random() * 4000 - 2000, object.position.y = Math.random() * 4000 - 2000, object.position.z = Math.random() * 4000 - 2000 - scene.add(object); + scene.add(object); objects.push(object); @@ -51,7 +45,7 @@ transition(); }, false); - sprite.src = 'textures/sprite.png'; + image.src = 'textures/sprite.png'; // Plane diff --git a/threejs/tests/math/test_unit_math.ts b/threejs/tests/math/test_unit_math.ts index f1c3818cc..a30e60dcd 100644 --- a/threejs/tests/math/test_unit_math.ts +++ b/threejs/tests/math/test_unit_math.ts @@ -6,6 +6,7 @@ // https://github.com/mrdoob/three.js/tree/master/test/unit/math ()=>{ + // -------------------------------------------- Constants var x = 2; var y = 3; var z = 4; @@ -25,8 +26,7 @@ var one3 = new THREE.Vector3( 1, 1, 1 ); var two3 = new THREE.Vector3( 2, 2, 2 ); - (QUnit.module)( "Box2" ); - + // -------------------------------------------- Box2 test( "constructor", function() { var a = new THREE.Box2(); ok( a.min.equals( posInf2 ), "Passed!" ); @@ -62,6 +62,21 @@ ok( a.max.equals( one2 ), "Passed!" ); }); + test( "setFromPoints", function() { + var a = new THREE.Box2(); + + a.setFromPoints( [ zero2, one2, two2 ] ); + ok( a.min.equals( zero2 ), "Passed!" ); + ok( a.max.equals( two2 ), "Passed!" ); + + a.setFromPoints( [ one2 ] ); + ok( a.min.equals( one2 ), "Passed!" ); + ok( a.max.equals( one2 ), "Passed!" ); + + a.setFromPoints( [] ); + ok( a.empty(), "Passed!" ); + }); + test( "empty/makeEmpty", function() { var a = new THREE.Box2(); @@ -197,21 +212,6 @@ ok( b.distanceToPoint( new THREE.Vector2( -2, -2 ) ) == Math.sqrt( 2 ), "Passed!" ); }); - test( "distanceToPoint", function() { - var a = new THREE.Box2( zero2.clone(), zero2.clone() ); - var b = new THREE.Box2( one2.clone().negate(), one2.clone() ); - - ok( a.distanceToPoint( new THREE.Vector2( 0, 0 ) ) == 0, "Passed!" ); - ok( a.distanceToPoint( new THREE.Vector2( 1, 1 ) ) == Math.sqrt( 2 ), "Passed!" ); - ok( a.distanceToPoint( new THREE.Vector2( -1, -1 ) ) == Math.sqrt( 2 ), "Passed!" ); - - ok( b.distanceToPoint( new THREE.Vector2( 2, 2 ) ) == Math.sqrt( 2 ), "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector2( 1, 1 ) ) == 0, "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector2( 0, 0 ) ) == 0, "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector2( -1, -1 ) ) == 0, "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector2( -2, -2 ) ) == Math.sqrt( 2 ), "Passed!" ); - }); - test( "isIntersectionBox", function() { var a = new THREE.Box2( zero2.clone(), zero2.clone() ); var b = new THREE.Box2( zero2.clone(), one2.clone() ); @@ -267,6 +267,7 @@ ok( b.clone().translate( one2.clone().negate() ).equals( d ), "Passed!" ); }); + // -------------------------------------------- Box3 test( "constructor", function() { var a = new THREE.Box3(); ok( a.min.equals( posInf3 ), "Passed!" ); @@ -302,6 +303,21 @@ ok( a.max.equals( one3 ), "Passed!" ); }); + test( "setFromPoints", function() { + var a = new THREE.Box3(); + + a.setFromPoints( [ zero3, one3, two3 ] ); + ok( a.min.equals( zero3 ), "Passed!" ); + ok( a.max.equals( two3 ), "Passed!" ); + + a.setFromPoints( [ one3 ] ); + ok( a.min.equals( one3 ), "Passed!" ); + ok( a.max.equals( one3 ), "Passed!" ); + + a.setFromPoints( [] ); + ok( a.empty(), "Passed!" ); + }); + test( "empty/makeEmpty", function() { var a = new THREE.Box3(); @@ -508,7 +524,7 @@ var compareBox = function ( a, b, threshold? ) { threshold = threshold || 0.0001; return ( a.min.distanceTo( b.min ) < threshold && - a.max.distanceTo( b.max ) < threshold ); + a.max.distanceTo( b.max ) < threshold ); }; test( "applyMatrix4", function() { @@ -538,11 +554,19 @@ ok( b.clone().translate( one3.clone().negate() ).equals( d ), "Passed!" ); }); + // -------------------------------------------- Color test( "constructor", function(){ var c = new THREE.Color(); ok( c.r, "Red: " + c.r ); ok( c.g, "Green: " + c.g ); - ok( c.b, "Blue: " + c.g ); + ok( c.b, "Blue: " + c.b ); + }); + + test( "rgb constructor", function(){ + var c = new THREE.Color( 1, 1, 1 ); + ok( c.r == 1, "Passed" ); + ok( c.g == 1, "Passed" ); + ok( c.b == 1, "Passed" ); }); test( "copyHex", function(){ @@ -560,48 +584,48 @@ }); test( "setRGB", function(){ - var c = new THREE.Color() - c.setRGB(255, 2, 1); - ok( c.r == 255, "Red: " + c.r ); - ok( c.g == 2, "Green: " + c.g ); - ok( c.b == 1, "Blue: " + c.b ); + var c = new THREE.Color(); + c.setRGB(1, 0.2, 0.1); + ok( c.r == 1, "Red: " + c.r ); + ok( c.g == 0.2, "Green: " + c.g ); + ok( c.b == 0.1, "Blue: " + c.b ); }); test( "copyGammaToLinear", function(){ var c = new THREE.Color(); var c2 = new THREE.Color(); - c2.setRGB(2, 4, 8) - c.copyGammaToLinear(c2) - ok( c.r == 4, "Red c: " + c.r + " Red c2: " + c2.r); - ok( c.g == 16, "Green c: " + c.g + " Green c2: " + c2.g); - ok( c.b == 64, "Blue c: " + c.b + " Blue c2: " + c2.b); + c2.setRGB(0.3, 0.5, 0.9); + c.copyGammaToLinear(c2); + ok( c.r == 0.09, "Red c: " + c.r + " Red c2: " + c2.r); + ok( c.g == 0.25, "Green c: " + c.g + " Green c2: " + c2.g); + ok( c.b == 0.81, "Blue c: " + c.b + " Blue c2: " + c2.b); }); test( "copyLinearToGamma", function(){ var c = new THREE.Color(); var c2 = new THREE.Color(); - c2.setRGB(4, 9, 16) - c.copyLinearToGamma(c2) - ok( c.r == 2, "Red c: " + c.r + " Red c2: " + c2.r); - ok( c.g == 3, "Green c: " + c.g + " Green c2: " + c2.g); - ok( c.b == 4, "Blue c: " + c.b + " Blue c2: " + c2.b); + c2.setRGB(0.09, 0.25, 0.81); + c.copyLinearToGamma(c2); + ok( c.r == 0.3, "Red c: " + c.r + " Red c2: " + c2.r); + ok( c.g == 0.5, "Green c: " + c.g + " Green c2: " + c2.g); + ok( c.b == 0.9, "Blue c: " + c.b + " Blue c2: " + c2.b); }); test( "convertGammaToLinear", function(){ var c = new THREE.Color(); - c.setRGB(2, 4, 8) - c.convertGammaToLinear() - ok( c.r == 4, "Red: " + c.r ); - ok( c.g == 16, "Green: " + c.g ); - ok( c.b == 64, "Blue: " + c.b ); + c.setRGB(0.3, 0.5, 0.9); + c.convertGammaToLinear(); + ok( c.r == 0.09, "Red: " + c.r ); + ok( c.g == 0.25, "Green: " + c.g ); + ok( c.b == 0.81, "Blue: " + c.b ); }); test( "convertLinearToGamma", function(){ var c = new THREE.Color(); - c.setRGB(4, 9, 16) - c.convertLinearToGamma() + c.setRGB(4, 9, 16); + c.convertLinearToGamma(); ok( c.r == 2, "Red: " + c.r ); ok( c.g == 3, "Green: " + c.g ); ok( c.b == 4, "Blue: " + c.b ); @@ -611,8 +635,8 @@ var c = new THREE.Color(); c.set(0xFF0000); ok( c.r == 1, "Red: " + c.r ); - ok( c.g == 0, "Green: " + c.g ); - ok( c.b == 0, "Blue: " + c.b ); + ok( c.g === 0, "Green: " + c.g ); + ok( c.b === 0, "Blue: " + c.b ); }); @@ -633,11 +657,11 @@ var c = new THREE.Color(); var c2 = new THREE.Color(); c.setRGB(0, 0, 0); - c.lerp(c2, 2); - ok( c.r == 2, "Red: " + c.r ); - ok( c.g == 2, "Green: " + c.g ); - ok( c.b == 2, "Blue: " + c.b ); - + c.lerp(c2, 0.2); + ok( c.r == 0.2, "Red: " + c.r ); + ok( c.g == 0.2, "Green: " + c.g ); + ok( c.b == 0.2, "Blue: " + c.b ); + }); @@ -645,8 +669,16 @@ var c = new THREE.Color(); c.setStyle('rgb(255,0,0)'); ok( c.r == 1, "Red: " + c.r ); - ok( c.g == 0, "Green: " + c.g ); - ok( c.b == 0, "Blue: " + c.b ); + ok( c.g === 0, "Green: " + c.g ); + ok( c.b === 0, "Blue: " + c.b ); + }); + + test( "setStyleRGBRedWithSpaces", function(){ + var c = new THREE.Color(); + c.setStyle('rgb(255, 0, 0)'); + ok( c.r == 1, "Red: " + c.r ); + ok( c.g === 0, "Green: " + c.g ); + ok( c.b === 0, "Blue: " + c.b ); }); test( "setStyleRGBPercent", function(){ @@ -657,6 +689,14 @@ ok( c.b == 0.1, "Blue: " + c.b ); }); + test( "setStyleRGBPercentWithSpaces", function(){ + var c = new THREE.Color(); + c.setStyle('rgb(100%,50%,10%)'); + ok( c.r == 1, "Red: " + c.r ); + ok( c.g == 0.5, "Green: " + c.g ); + ok( c.b == 0.1, "Blue: " + c.b ); + }); + test( "setStyleHexSkyBlue", function(){ var c = new THREE.Color(); c.setStyle('#87CEEB'); @@ -706,10 +746,7 @@ ok( hsl.h == 0.5, "hue: " + hsl.h ); ok( hsl.s == 1.0, "saturation: " + hsl.s ); - - - //ok( (Math.round(parseFloat(hsl.l)*100)/100) == 0.75, "lightness: " + hsl.l ); - ok( (Math.round(hsl.l*100)/100) == 0.75, "lightness: " + hsl.l ); + ok( (Math.round(parseFloat(hsl.l.toString())*100)/100) == 0.75, "lightness: " + hsl.l ); }); test( "setHSL", function () { @@ -722,6 +759,98 @@ ok( hsl.l == 0.25, "lightness: " + hsl.l ); }); + // -------------------------------------------- Euler + + var eulerZero = new THREE.Euler( 0, 0, 0, "XYZ" ); + var eulerAxyz = new THREE.Euler( 1, 0, 0, "XYZ" ); + var eulerAzyx = new THREE.Euler( 0, 1, 0, "ZYX" ); + + var matrixEquals4 = function( a, b ) { + var tolerance = 0.0001; + if( a.elements.length != b.elements.length ) { + return false; + } + for( var i = 0, il = a.elements.length; i < il; i ++ ) { + var delta = a.elements[i] - b.elements[i]; + if( delta > tolerance ) { + return false; + } + } + return true; + }; + + test( "constructor/equals", function() { + var a = new THREE.Euler(); + ok( a.equals( eulerZero ), "Passed!" ); + ok( ! a.equals( eulerAxyz ), "Passed!" ); + ok( ! a.equals( eulerAzyx ), "Passed!" ); + }); + + test( "clone/copy/equals", function() { + var a = eulerAxyz.clone(); + ok( a.equals( eulerAxyz ), "Passed!" ); + ok( ! a.equals( eulerZero ), "Passed!" ); + ok( ! a.equals( eulerAzyx ), "Passed!" ); + + a.copy( eulerAzyx ); + ok( a.equals( eulerAzyx ), "Passed!" ); + ok( ! a.equals( eulerAxyz ), "Passed!" ); + ok( ! a.equals( eulerZero ), "Passed!" ); + + }); + + test( "set", function() { + var a = new THREE.Euler(); + + a.set( 0, 1, 0, "ZYX" ); + ok( a.equals( eulerAzyx ), "Passed!" ); + ok( ! a.equals( eulerAxyz ), "Passed!" ); + ok( ! a.equals( eulerZero ), "Passed!" ); + }); + + test( "Quaternion.setFromEuler/Euler.fromQuaternion", function() { + var testValues = [ eulerZero, eulerAxyz, eulerAzyx ]; + for( var i = 0; i < testValues.length; i ++ ) { + var v = testValues[i]; + var q = new THREE.Quaternion().setFromEuler( v ); + + var v2 = new THREE.Euler().setFromQuaternion( q, v.order ); + var q2 = new THREE.Quaternion().setFromEuler( v2 ); + ok( q.equals( q2 ), "Passed!" ); + } + }); + + + test( "Matrix4.setFromEuler/Euler.fromRotationMatrix", function() { + var testValues = [ eulerZero, eulerAxyz, eulerAzyx ]; + for( var i = 0; i < testValues.length; i ++ ) { + var v = testValues[i]; + var m = new THREE.Matrix4().makeRotationFromEuler( v ); + + var v2 = new THREE.Euler().setFromRotationMatrix( m, v.order ); + var m2 = new THREE.Matrix4().makeRotationFromEuler( v2 ); + ok( matrixEquals4( m, m2 ), "Passed!" ); + } + }); + + test( "reorder", function() { + var testValues = [ eulerZero, eulerAxyz, eulerAzyx ]; + for( var i = 0; i < testValues.length; i ++ ) { + var v = testValues[i]; + var q = new THREE.Quaternion().setFromEuler( v ); + + v.reorder( 'YZX' ); + var q2 = new THREE.Quaternion().setFromEuler( v ); + ok( q.equals( q2 ), "Passed!" ); + + v.reorder( 'ZXY' ); + var q3 = new THREE.Quaternion().setFromEuler( v ); + ok( q.equals( q3 ), "Passed!" ); + } + }); + + // -------------------------------------------- Frustum + var unit3 = new THREE.Vector3( 1, 0, 0 ); var planeEquals = function ( a, b, tolerance ) { @@ -873,6 +1002,7 @@ ok( b.planes[0].equals( p0 ), "Passed!" ); }); + // -------------------------------------------- Line3 test( "constructor/equals", function() { var a = new THREE.Line3(); @@ -925,7 +1055,6 @@ // nearby the ray ok( a.closestPointToPointParameter( zero3.clone(), false ) == -1, "Passed!" ); var b2 = a.closestPointToPoint( zero3.clone(), false ); - console.log( b2 ); ok( b2.distanceTo( new THREE.Vector3( 1, 1, 0 ) ) < 0.0001, "Passed!" ); // nearby the ray @@ -939,7 +1068,7 @@ ok( c.distanceTo( one3.clone() ) < 0.0001, "Passed!" ); }); - + // -------------------------------------------- Matrix3 var matrixEquals3 = function( a, b, tolerance? ) { tolerance = tolerance || 0.0001; @@ -1081,15 +1210,13 @@ var identity = new THREE.Matrix4(); var a = new THREE.Matrix4(); var b = new THREE.Matrix3( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); - - //var c = new THREE.Matrix4( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); - var c = new THREE.Matrix4( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + var c = new THREE.Matrix4( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); ok( ! matrixEquals3( a, b ), "Passed!" ); b.getInverse( a, false ); ok( matrixEquals3( b, new THREE.Matrix3() ), "Passed!" ); - try { + try { b.getInverse( c, true ); ok( false, "Passed!" ); // should never get here. } @@ -1106,7 +1233,7 @@ new THREE.Matrix4().makeRotationZ( -0.3 ), new THREE.Matrix4().makeScale( 1, 2, 3 ), new THREE.Matrix4().makeScale( 1/8, 1/2, 1/3 ) - ]; + ]; for( var i = 0, il = testMatrices.length; i < il; i ++ ) { var m = testMatrices[i]; @@ -1131,9 +1258,9 @@ b = new THREE.Matrix3( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); var c = b.clone().transpose(); - ok( ! matrixEquals3( b, c ), "Passed!" ); + ok( ! matrixEquals3( b, c ), "Passed!" ); c.transpose(); - ok( matrixEquals3( b, c ), "Passed!" ); + ok( matrixEquals3( b, c ), "Passed!" ); }); test( "clone", function() { @@ -1147,8 +1274,10 @@ ok( ! matrixEquals3( a, b ), "Passed!" ); }); - var matrixEquals4 = function( a, b, tolerance? ) { - tolerance = tolerance || 0.0001; + // -------------------------------------------- Matrix4 + + var matrixEquals4 = function (a, b) { + var tolerance = 0.0001; if( a.elements.length != b.elements.length ) { return false; } @@ -1310,7 +1439,7 @@ b.getInverse( a, false ); ok( matrixEquals4( b, new THREE.Matrix4() ), "Passed!" ); - try { + try { b.getInverse( c, true ); ok( false, "Passed!" ); // should never get here. } @@ -1330,15 +1459,21 @@ new THREE.Matrix4().makeFrustum( -1, 1, -1, 1, 1, 1000 ), new THREE.Matrix4().makeFrustum( -16, 16, -9, 9, 0.1, 10000 ), new THREE.Matrix4().makeTranslation( 1, 2, 3 ) - ]; + ]; for( var i = 0, il = testMatrices.length; i < il; i ++ ) { var m = testMatrices[i]; var mInverse = new THREE.Matrix4().getInverse( m ); + var mSelfInverse = m.clone(); + mSelfInverse.getInverse( mSelfInverse ); + + + // self-inverse should the same as inverse + ok( matrixEquals4( mSelfInverse, mInverse ), "Passed!" ); // the determinant of the inverse should be the reciprocal - ok( Math.abs( m.determinant() * mInverse.determinant() - 1 ) < 0.0001, "Passed!" ); + ok( Math.abs( m.determinant() * mInverse.determinant() - 1 ) < 0.0001, "Passed!" ); var mProduct = new THREE.Matrix4().multiplyMatrices( m, mInverse ); @@ -1355,9 +1490,9 @@ b = new THREE.Matrix4( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ); var c = b.clone().transpose(); - ok( ! matrixEquals4( b, c ), "Passed!" ); + ok( ! matrixEquals4( b, c ), "Passed!" ); c.transpose(); - ok( matrixEquals4( b, c ), "Passed!" ); + ok( matrixEquals4( b, c ), "Passed!" ); }); test( "clone", function() { @@ -1372,10 +1507,75 @@ }); + test( "compose/decompose", function() { + var tValues = [ + new THREE.Vector3(), + new THREE.Vector3( 3, 0, 0 ), + new THREE.Vector3( 0, 4, 0 ), + new THREE.Vector3( 0, 0, 5 ), + new THREE.Vector3( -6, 0, 0 ), + new THREE.Vector3( 0, -7, 0 ), + new THREE.Vector3( 0, 0, -8 ), + new THREE.Vector3( -2, 5, -9 ), + new THREE.Vector3( -2, -5, -9 ) + ]; + + var sValues = [ + new THREE.Vector3( 1, 1, 1 ), + new THREE.Vector3( 2, 2, 2 ), + new THREE.Vector3( 1, -1, 1 ), + new THREE.Vector3( -1, 1, 1 ), + new THREE.Vector3( 1, 1, -1 ), + new THREE.Vector3( 2, -2, 1 ), + new THREE.Vector3( -1, 2, -2 ), + new THREE.Vector3( -1, -1, -1 ), + new THREE.Vector3( -2, -2, -2 ) + ]; + + var rValues = [ + new THREE.Quaternion(), + new THREE.Quaternion().setFromEuler( new THREE.Euler( 1, 1, 0 ) ), + new THREE.Quaternion().setFromEuler( new THREE.Euler( 1, -1, 1 ) ), + new THREE.Quaternion( 0, 0.9238795292366128, 0, 0.38268342717215614 ) + ]; + + + for( var ti = 0; ti < tValues.length; ti ++ ) { + for( var si = 0; si < sValues.length; si ++ ) { + for( var ri = 0; ri < rValues.length; ri ++ ) { + var t = tValues[ti]; + var s = sValues[si]; + var r = rValues[ri]; + + var m = new THREE.Matrix4().compose( t, r, s ); + var t2 = new THREE.Vector3(); + var r2 = new THREE.Quaternion(); + var s2 = new THREE.Vector3(); + + m.decompose( t2, r2, s2 ); + + var m2 = new THREE.Matrix4().compose( t2, r2, s2 ); + + var matrixIsSame = matrixEquals4( m, m2 ); + /* debug code + if( ! matrixIsSame ) { + console.log( t, s, r ); + console.log( t2, s2, r2 ); + console.log( m, m2 ); + }*/ + ok( matrixEquals4( m, m2 ), "Passed!" ); + + } + } + } + }); + + // -------------------------------------------- Plane + var comparePlane = function ( a, b, threshold? ) { threshold = threshold || 0.0001; return ( a.normal.distanceTo( b.normal ) < threshold && - Math.abs( a.constant - b.constant ) < threshold ); + Math.abs( a.constant - b.constant ) < threshold ); }; @@ -1564,6 +1764,8 @@ ok( comparePlane( a.clone().applyMatrix4( m ), a.clone().translate( new THREE.Vector3( 1, 1, 1 ) ) ), "Passed!" ); }); + // -------------------------------------------- Quaternion + var orders = [ 'XYZ', 'YXZ', 'ZXY', 'ZYX', 'YZX', 'XZY' ]; var eulerAngles = new THREE.Euler( 0.1, -0.3, 0.25 ); @@ -1658,12 +1860,9 @@ // ensure euler conversion to/from Quaternion matches. for( var i = 0; i < orders.length; i ++ ) { for( var j = 0; j < angles.length; j ++ ) { - var eulers2 = new THREE.Euler().setFromQuaternion( - new THREE.Quaternion().setFromEuler(new THREE.Euler(angles[j].x, angles[j].y, angles[j].z, orders[i])), - orders[i] - ); - var v = new THREE.Vector3().applyEuler(eulers2); - ok( v.distanceTo( angles[j] ) < 0.001, "Passed!" ); + var eulers2 = new THREE.Euler().setFromQuaternion( new THREE.Quaternion().setFromEuler( new THREE.Euler( angles[j].x, angles[j].y, angles[j].z, orders[i] ) ), orders[i] ); + var newAngle = new THREE.Vector3( eulers2.x, eulers2.y, eulers2.z ); + ok( newAngle.distanceTo( angles[j] ) < 0.001, "Passed!" ); } } @@ -1673,7 +1872,7 @@ // ensure euler conversion for Quaternion matches that of Matrix4 for( var i = 0; i < orders.length; i ++ ) { - var q = new THREE.Quaternion().setFromEuler( eulerAngles ); + var q = new THREE.Quaternion().setFromEuler( eulerAngles, false ); var m = new THREE.Matrix4().makeRotationFromEuler( eulerAngles ); var q2 = new THREE.Quaternion().setFromRotationMatrix( m ); @@ -1716,17 +1915,17 @@ test( "multiplyQuaternions/multiply", function() { - var angles = [ new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ) ]; + var angles = [ new THREE.Euler( 1, 0, 0 ), new THREE.Euler( 0, 1, 0 ), new THREE.Euler( 0, 0, 1 ) ]; - var q1 = new THREE.Quaternion().setFromEuler( new THREE.Euler(angles[0].x, angles[0].y, angles[0].z) ); - var q2 = new THREE.Quaternion().setFromEuler( new THREE.Euler(angles[1].x, angles[1].y, angles[1].z) ); - var q3 = new THREE.Quaternion().setFromEuler( new THREE.Euler(angles[2].x, angles[2].y, angles[2].z) ); + var q1 = new THREE.Quaternion().setFromEuler( angles[0], false ); + var q2 = new THREE.Quaternion().setFromEuler( angles[1], false ); + var q3 = new THREE.Quaternion().setFromEuler( angles[2], false ); var q = new THREE.Quaternion().multiplyQuaternions( q1, q2 ).multiply( q3 ); - var m1 = new THREE.Matrix4().makeRotationFromEuler( new THREE.Euler(angles[0].x, angles[0].y, angles[0].z) ); - var m2 = new THREE.Matrix4().makeRotationFromEuler( new THREE.Euler(angles[1].x, angles[1].y, angles[1].z) ); - var m3 = new THREE.Matrix4().makeRotationFromEuler( new THREE.Euler(angles[2].x, angles[2].y, angles[2].z) ); + var m1 = new THREE.Matrix4().makeRotationFromEuler( angles[0] ); + var m2 = new THREE.Matrix4().makeRotationFromEuler( angles[1] ); + var m3 = new THREE.Matrix4().makeRotationFromEuler( angles[2] ); var m = new THREE.Matrix4().multiplyMatrices( m1, m2 ).multiply( m3 ); @@ -1737,13 +1936,13 @@ test( "multiplyVector3", function() { - var angles = [ new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ) ]; + var angles = [ new THREE.Euler( 1, 0, 0 ), new THREE.Euler( 0, 1, 0 ), new THREE.Euler( 0, 0, 1 ) ]; // ensure euler conversion for Quaternion matches that of Matrix4 for( var i = 0; i < orders.length; i ++ ) { for( var j = 0; j < angles.length; j ++ ) { - var q = new THREE.Quaternion().setFromEuler( new THREE.Euler(angles[j].x, angles[j].y, angles[j].z, orders[i]) ); - var m = new THREE.Matrix4().makeRotationFromEuler( new THREE.Euler(angles[j].x, angles[j].y, angles[j].z, orders[i]) ); + var q = new THREE.Quaternion().setFromEuler( angles[j], false ); + var m = new THREE.Matrix4().makeRotationFromEuler( angles[j] ); var v0 = new THREE.Vector3(1, 0, 0); var qv = v0.clone().applyQuaternion( q ); @@ -1773,6 +1972,7 @@ ok( b.equals( a ), "Passed!" ); }); + // -------------------------------------------- Ray test( "constructor/equals", function() { var a = new THREE.Ray(); @@ -1834,25 +2034,33 @@ test( "closestPointToPoint", function() { var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); - // nearby the ray + // behind the ray var b = a.closestPointToPoint( zero3 ); - ok( b.equals( new THREE.Vector3( 1, 1, 0 ) ), "Passed!" ); + ok( b.equals( one3 ), "Passed!" ); + + // front of the ray + var c = a.closestPointToPoint( new THREE.Vector3( 0, 0, 50 ) ); + ok( c.equals( new THREE.Vector3( 1, 1, 50 ) ), "Passed!" ); // exactly on the ray - var c = a.closestPointToPoint( one3 ); - ok( c.equals( one3 ), "Passed!" ); + var d = a.closestPointToPoint( one3 ); + ok( d.equals( one3 ), "Passed!" ); }); test( "distanceToPoint", function() { var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); - // nearby the ray + // behind the ray var b = a.distanceToPoint( zero3 ); - ok( b == Math.sqrt( 2 ), "Passed!" ); + ok( b === Math.sqrt( 3 ), "Passed!" ); + + // front of the ray + var c = a.distanceToPoint( new THREE.Vector3( 0, 0, 50 ) ); + ok( c === Math.sqrt( 2 ), "Passed!" ); // exactly on the ray - var c = a.distanceToPoint( one3 ); - ok( c == 0, "Passed!" ); + var d = a.distanceToPoint( one3 ); + ok( d === 0, "Passed!" ); }); test( "isIntersectionSphere", function() { @@ -1864,16 +2072,75 @@ var f = new THREE.Sphere( two3, 1 ); ok( ! a.isIntersectionSphere( b ), "Passed!" ); - ok( a.isIntersectionSphere( c ), "Passed!" ); + ok( ! a.isIntersectionSphere( c ), "Passed!" ); ok( a.isIntersectionSphere( d ), "Passed!" ); ok( ! a.isIntersectionSphere( e ), "Passed!" ); ok( ! a.isIntersectionSphere( f ), "Passed!" ); }); + test( "intersectSphere", function() { + + var TOL = 0.0001; + + // ray a0 origin located at ( 0, 0, 0 ) and points outward in negative-z direction + var a0 = new THREE.Ray( zero3.clone(), new THREE.Vector3( 0, 0, -1 ) ); + // ray a1 origin located at ( 1, 1, 1 ) and points left in negative-x direction + var a1 = new THREE.Ray( one3.clone(), new THREE.Vector3( -1, 0, 0 ) ); + + // sphere (radius of 2) located behind ray a0, should result in null + var b = new THREE.Sphere( new THREE.Vector3( 0, 0, 3 ), 2 ); + ok( a0.intersectSphere( b ) === null, "Passed!" ); + + // sphere (radius of 2) located in front of, but too far right of ray a0, should result in null + var b = new THREE.Sphere( new THREE.Vector3( 3, 0, -1 ), 2 ); + ok( a0.intersectSphere( b ) === null, "Passed!" ); + + // sphere (radius of 2) located below ray a1, should result in null + var b = new THREE.Sphere( new THREE.Vector3( 1, -2, 1 ), 2 ); + ok( a1.intersectSphere( b ) === null, "Passed!" ); + + // sphere (radius of 1) located to the left of ray a1, should result in intersection at 0, 1, 1 + var b = new THREE.Sphere( new THREE.Vector3( -1, 1, 1 ), 1 ); + ok( a1.intersectSphere( b ).distanceTo( new THREE.Vector3( 0, 1, 1 ) ) < TOL, "Passed!" ); + + // sphere (radius of 1) located in front of ray a0, should result in intersection at 0, 0, -1 + var b = new THREE.Sphere( new THREE.Vector3( 0, 0, -2 ), 1 ); + ok( a0.intersectSphere( b ).distanceTo( new THREE.Vector3( 0, 0, -1 ) ) < TOL, "Passed!" ); + + // sphere (radius of 2) located in front & right of ray a0, should result in intersection at 0, 0, -1, or left-most edge of sphere + var b = new THREE.Sphere( new THREE.Vector3( 2, 0, -1 ), 2 ); + ok( a0.intersectSphere( b ).distanceTo( new THREE.Vector3( 0, 0, -1 ) ) < TOL, "Passed!" ); + + // same situation as above, but move the sphere a fraction more to the right, and ray a0 should now just miss + var b = new THREE.Sphere( new THREE.Vector3( 2.01, 0, -1 ), 2 ); + ok( a0.intersectSphere( b ) === null, "Passed!" ); + + // following tests are for situations where the ray origin is inside the sphere + + // sphere (radius of 1) center located at ray a0 origin / sphere surrounds the ray origin, so the first intersect point 0, 0, 1, + // is behind ray a0. Therefore, second exit point on back of sphere will be returned: 0, 0, -1 + // thus keeping the intersection point always in front of the ray. + var b = new THREE.Sphere( zero3.clone(), 1 ); + ok( a0.intersectSphere( b ).distanceTo( new THREE.Vector3( 0, 0, -1 ) ) < TOL, "Passed!" ); + + // sphere (radius of 4) center located behind ray a0 origin / sphere surrounds the ray origin, so the first intersect point 0, 0, 5, + // is behind ray a0. Therefore, second exit point on back of sphere will be returned: 0, 0, -3 + // thus keeping the intersection point always in front of the ray. + var b = new THREE.Sphere( new THREE.Vector3( 0, 0, 1 ), 4 ); + ok( a0.intersectSphere( b ).distanceTo( new THREE.Vector3( 0, 0, -3 ) ) < TOL, "Passed!" ); + + // sphere (radius of 4) center located in front of ray a0 origin / sphere surrounds the ray origin, so the first intersect point 0, 0, 3, + // is behind ray a0. Therefore, second exit point on back of sphere will be returned: 0, 0, -5 + // thus keeping the intersection point always in front of the ray. + var b = new THREE.Sphere( new THREE.Vector3( 0, 0, -1 ), 4 ); + ok( a0.intersectSphere( b ).distanceTo( new THREE.Vector3( 0, 0, -5 ) ) < TOL, "Passed!" ); + + }); + test( "isIntersectionPlane", function() { var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); - // parallel plane behind + // parallel plane in front of the ray var b = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), one3.clone().sub( new THREE.Vector3( 0, 0, -1 ) ) ); ok( a.isIntersectionPlane( b ), "Passed!" ); @@ -1881,9 +2148,9 @@ var c = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), one3.clone().sub( new THREE.Vector3( 0, 0, 0 ) ) ); ok( a.isIntersectionPlane( c ), "Passed!" ); - // parallel plane infront + // parallel plane behind the ray var d = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), one3.clone().sub( new THREE.Vector3( 0, 0, 1 ) ) ); - ok( a.isIntersectionPlane( d ), "Passed!" ); + ok( ! a.isIntersectionPlane( d ), "Passed!" ); // perpendical ray that overlaps exactly var e = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 1, 0, 0 ), one3 ); @@ -1899,15 +2166,15 @@ // parallel plane behind var b = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 1, 1, -1 ) ); - ok( a.intersectPlane( b ).equals( new THREE.Vector3( 1, 1, -1 ) ), "Passed!" ); + ok( a.intersectPlane( b ) === null, "Passed!" ); // parallel plane coincident with origin var c = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 1, 1, 0 ) ); - ok( a.intersectPlane( c ).equals( new THREE.Vector3( 1, 1, 0 ) ), "Passed!" ); + ok( a.intersectPlane( c ) === null, "Passed!" ); // parallel plane infront var d = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 1, 1, 1 ) ); - ok( a.intersectPlane( d ).equals( new THREE.Vector3( 1, 1, 1 ) ), "Passed!" ); + ok( a.intersectPlane( d ).equals( a.origin ), "Passed!" ); // perpendical ray that overlaps exactly var e = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 1, 0, 0 ), one3 ); @@ -1915,21 +2182,21 @@ // perpendical ray that doesn't overlap var f = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 1, 0, 0 ), zero3 ); - ok( a.intersectPlane( f ) === undefined, "Passed!" ); + ok( a.intersectPlane( f ) === null, "Passed!" ); }); test( "applyMatrix4", function() { var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); - var m = new THREE.Matrix4().identity(); + var m = new THREE.Matrix4(); ok( a.clone().applyMatrix4( m ).equals( a ), "Passed!" ); a = new THREE.Ray( zero3.clone(), new THREE.Vector3( 0, 0, 1 ) ); - m.makeRotationAxis( new THREE.Vector3( 0, 0, 1 ), Math.PI ); + m.makeRotationZ( Math.PI ); ok( a.clone().applyMatrix4( m ).equals( a ), "Passed!" ); - m.identity().makeRotationX( Math.PI ); + m.makeRotationX( Math.PI ); var b = a.clone(); b.direction.negate(); var a2 = a.clone().applyMatrix4( m ); @@ -1944,6 +2211,80 @@ }); + test( "distanceSqToSegment", function() { + var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); + var ptOnLine = new THREE.Vector3(); + var ptOnSegment = new THREE.Vector3(); + + //segment in front of the ray + var v0 = new THREE.Vector3( 3, 5, 50 ); + var v1 = new THREE.Vector3( 50, 50, 50 ); // just a far away point + var distSqr = a.distanceSqToSegment( v0, v1, ptOnLine, ptOnSegment ); + + ok( ptOnSegment.distanceTo( v0 ) < 0.0001, "Passed!" ); + ok( ptOnLine.distanceTo( new THREE.Vector3(1, 1, 50) ) < 0.0001, "Passed!" ); + // ((3-1) * (3-1) + (5-1) * (5-1) = 4 + 16 = 20 + ok( Math.abs( distSqr - 20 ) < 0.0001, "Passed!" ); + + //segment behind the ray + v0 = new THREE.Vector3( -50, -50, -50 ); // just a far away point + v1 = new THREE.Vector3( -3, -5, -4 ); + distSqr = a.distanceSqToSegment( v0, v1, ptOnLine, ptOnSegment ); + + ok( ptOnSegment.distanceTo( v1 ) < 0.0001, "Passed!" ); + ok( ptOnLine.distanceTo( one3 ) < 0.0001, "Passed!" ); + // ((-3-1) * (-3-1) + (-5-1) * (-5-1) + (-4-1) + (-4-1) = 16 + 36 + 25 = 77 + ok( Math.abs( distSqr - 77 ) < 0.0001, "Passed!" ); + + //exact intersection between the ray and the segment + v0 = new THREE.Vector3( -50, -50, -50 ); + v1 = new THREE.Vector3( 50, 50, 50 ); + distSqr = a.distanceSqToSegment( v0, v1, ptOnLine, ptOnSegment ); + + ok( ptOnSegment.distanceTo( one3 ) < 0.0001, "Passed!" ); + ok( ptOnLine.distanceTo( one3 ) < 0.0001, "Passed!" ); + ok( distSqr < 0.0001, "Passed!" ); + }); + + test( "intersectBox", function() { + + var TOL = 0.0001; + + var box = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ); + + var a = new THREE.Ray( new THREE.Vector3( -2, 0, 0 ), new THREE.Vector3( 1, 0, 0) ); + //ray should intersect box at -1,0,0 + ok( a.isIntersectionBox(box) === true, "Passed!" ); + ok( a.intersectBox(box).distanceTo( new THREE.Vector3( -1, 0, 0 ) ) < TOL, "Passed!" ); + + var b = new THREE.Ray( new THREE.Vector3( -2, 0, 0 ), new THREE.Vector3( -1, 0, 0) ); + //ray is point away from box, it should not intersect + ok( b.isIntersectionBox(box) === false, "Passed!" ); + ok( b.intersectBox(box) === null, "Passed!" ); + + var c = new THREE.Ray( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 1, 0, 0) ); + // ray is inside box, should return exit point + ok( c.isIntersectionBox(box) === true, "Passed!" ); + ok( c.intersectBox(box).distanceTo( new THREE.Vector3( 1, 0, 0 ) ) < TOL, "Passed!" ); + + var d = new THREE.Ray( new THREE.Vector3( 0, 2, 1 ), new THREE.Vector3( 0, -1, -1).normalize() ); + //tilted ray should intersect box at 0,1,0 + ok( d.isIntersectionBox(box) === true, "Passed!" ); + ok( d.intersectBox(box).distanceTo( new THREE.Vector3( 0, 1, 0 ) ) < TOL, "Passed!" ); + + var e = new THREE.Ray( new THREE.Vector3( 1, -2, 1 ), new THREE.Vector3( 0, 1, 0).normalize() ); + //handle case where ray is coplanar with one of the boxes side - box in front of ray + ok( e.isIntersectionBox(box) === true, "Passed!" ); + ok( e.intersectBox(box).distanceTo( new THREE.Vector3( 1, -1, 1 ) ) < TOL, "Passed!" ); + + var f = new THREE.Ray( new THREE.Vector3( 1, -2, 0 ), new THREE.Vector3( 0, -1, 0).normalize() ); + //handle case where ray is coplanar with one of the boxes side - box behind ray + ok( f.isIntersectionBox(box) === false, "Passed!" ); + ok( f.intersectBox(box) == null, "Passed!" ); + + }); + + // -------------------------------------------- Sphere test( "constructor", function() { var a = new THREE.Sphere(); ok( a.center.equals( zero3 ), "Passed!" ); @@ -2040,6 +2381,8 @@ ok( a.center.equals( zero3 ), "Passed!" ); }); + // -------------------------------------------- Triangle + test( "constructor", function() { var a = new THREE.Triangle(); ok( a.a.equals( zero3 ), "Passed!" ); @@ -2195,7 +2538,7 @@ ok( ! a.containsPoint( new THREE.Vector3( -1, -1, -1 ) ), "Passed!" ); }); - + // -------------------------------------------- Vector2 test( "constructor", function() { var a = new THREE.Vector2(); ok( a.x == 0, "Passed!" ); @@ -2316,6 +2659,32 @@ c.clamp( b, a ); ok( c.x == -x, "Passed!" ); ok( c.y == y, "Passed!" ); + + c.set(-2*x, 2*x); + c.clampScalar( -x, x ); + equal( c.x, -x, "scalar clamp x" ); + equal( c.y, x, "scalar clamp y" ); + }); + + test( "rounding", function() { + deepEqual( new THREE.Vector2( -0.1, 0.1 ).floor(), new THREE.Vector2( -1, 0 ), "floor .1" ); + deepEqual( new THREE.Vector2( -0.5, 0.5 ).floor(), new THREE.Vector2( -1, 0 ), "floor .5" ); + deepEqual( new THREE.Vector2( -0.9, 0.9 ).floor(), new THREE.Vector2( -1, 0 ), "floor .9" ); + + deepEqual( new THREE.Vector2( -0.1, 0.1 ).ceil(), new THREE.Vector2( 0, 1 ), "ceil .1" ); + deepEqual( new THREE.Vector2( -0.5, 0.5 ).ceil(), new THREE.Vector2( 0, 1 ), "ceil .5" ); + deepEqual( new THREE.Vector2( -0.9, 0.9 ).ceil(), new THREE.Vector2( 0, 1 ), "ceil .9" ); + + deepEqual( new THREE.Vector2( -0.1, 0.1 ).round(), new THREE.Vector2( 0, 0 ), "round .1" ); + deepEqual( new THREE.Vector2( -0.5, 0.5 ).round(), new THREE.Vector2( 0, 1 ), "round .5" ); + deepEqual( new THREE.Vector2( -0.9, 0.9 ).round(), new THREE.Vector2( -1, 1 ), "round .9" ); + + deepEqual( new THREE.Vector2( -0.1, 0.1 ).roundToZero(), new THREE.Vector2( 0, 0 ), "roundToZero .1" ); + deepEqual( new THREE.Vector2( -0.5, 0.5 ).roundToZero(), new THREE.Vector2( 0, 0 ), "roundToZero .5" ); + deepEqual( new THREE.Vector2( -0.9, 0.9 ).roundToZero(), new THREE.Vector2( 0, 0 ), "roundToZero .9" ); + deepEqual( new THREE.Vector2( -1.1, 1.1 ).roundToZero(), new THREE.Vector2( -1, 1 ), "roundToZero 1.1" ); + deepEqual( new THREE.Vector2( -1.5, 1.5 ).roundToZero(), new THREE.Vector2( -1, 1 ), "roundToZero 1.5" ); + deepEqual( new THREE.Vector2( -1.9, 1.9 ).roundToZero(), new THREE.Vector2( -1, 1 ), "roundToZero 1.9" ); }); test( "negate", function() { @@ -2427,7 +2796,7 @@ ok( b.equals( a ), "Passed!" ); }); - + // -------------------------------------------- Vector3 test( "constructor", function() { var a = new THREE.Vector3(); ok( a.x == 0, "Passed!" ); @@ -2700,18 +3069,19 @@ }); test( "reflect", function() { - var a = new THREE.Vector3( 1, 0, 0 ); - var normal = new THREE.Vector3( 1, 0, 0 ); - var b = new THREE.Vector3( 0, 0, 0 ); + var a = new THREE.Vector3(); + var normal = new THREE.Vector3( 0, 1, 0 ); + var b = new THREE.Vector3(); - ok( b.copy( a ).reflect( normal ).equals( new THREE.Vector3( 1, 0, 0 ) ), "Passed!" ); + a.set( 0, -1, 0 ); + ok( b.copy( a ).reflect( normal ).equals( new THREE.Vector3( 0, 1, 0 ) ), "Passed!" ); a.set( 1, -1, 0 ); ok( b.copy( a ).reflect( normal ).equals( new THREE.Vector3( 1, 1, 0 ) ), "Passed!" ); a.set( 1, -1, 0 ); normal.set( 0, -1, 0 ); - ok( b.copy( a ).reflect( normal ).equals( new THREE.Vector3( -1, -1, 0 ) ), "Passed!" ); + ok( b.copy( a ).reflect( normal ).equals( new THREE.Vector3( 1, 1, 0 ) ), "Passed!" ); }); test( "angleTo", function() { @@ -2768,7 +3138,7 @@ ok( b.equals( a ), "Passed!" ); }); - + // -------------------------------------------- Vector4 test( "constructor", function() { var a = new THREE.Vector4(); ok( a.x == 0, "Passed!" ); @@ -2897,9 +3267,9 @@ b.multiplyScalar( -2 ); ok( b.x == 2*x, "Passed!" ); - ok( b.y == 2*y, "Passed!" ); - ok( b.z == 2*z, "Passed!" ); - ok( b.w == 2*w, "Passed!" ); + ok( b.y == 2*y, "Passed!" ); + ok( b.z == 2*z, "Passed!" ); + ok( b.w == 2*w, "Passed!" ); a.divideScalar( -2 ); ok( a.x == x, "Passed!" ); @@ -3008,26 +3378,26 @@ }); /* - test( "distanceTo/distanceToSquared", function() { - var a = new THREE.Vector4( x, 0, 0, 0 ); - var b = new THREE.Vector4( 0, -y, 0, 0 ); - var c = new THREE.Vector4( 0, 0, z, 0 ); - var d = new THREE.Vector4( 0, 0, 0, -w ); - var e = new THREE.Vector4(); - - ok( a.distanceTo( e ) == x, "Passed!" ); - ok( a.distanceToSquared( e ) == x*x, "Passed!" ); + test( "distanceTo/distanceToSquared", function() { + var a = new THREE.Vector4( x, 0, 0, 0 ); + var b = new THREE.Vector4( 0, -y, 0, 0 ); + var c = new THREE.Vector4( 0, 0, z, 0 ); + var d = new THREE.Vector4( 0, 0, 0, -w ); + var e = new THREE.Vector4(); - ok( b.distanceTo( e ) == y, "Passed!" ); - ok( b.distanceToSquared( e ) == y*y, "Passed!" ); + ok( a.distanceTo( e ) == x, "Passed!" ); + ok( a.distanceToSquared( e ) == x*x, "Passed!" ); - ok( c.distanceTo( e ) == z, "Passed!" ); - ok( c.distanceToSquared( e ) == z*z, "Passed!" ); + ok( b.distanceTo( e ) == y, "Passed!" ); + ok( b.distanceToSquared( e ) == y*y, "Passed!" ); - ok( d.distanceTo( e ) == w, "Passed!" ); - ok( d.distanceToSquared( e ) == w*w, "Passed!" ); - }); - */ + ok( c.distanceTo( e ) == z, "Passed!" ); + ok( c.distanceToSquared( e ) == z*z, "Passed!" ); + + ok( d.distanceTo( e ) == w, "Passed!" ); + ok( d.distanceToSquared( e ) == w*w, "Passed!" ); + }); + */ test( "setLength", function() { diff --git a/threejs/tests/webgl/webgl_animation_skinning_morph.ts b/threejs/tests/webgl/webgl_animation_skinning_morph.ts new file mode 100644 index 000000000..ab588fad3 --- /dev/null +++ b/threejs/tests/webgl/webgl_animation_skinning_morph.ts @@ -0,0 +1,297 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_sprites.html + +() => { + // ------- variable definitions that does not exist in the original code. These are for typescript. + var material: THREE.SpriteMaterial; + var geometry: THREE.JSonLoaderResultGeometry; + var dat:any; + // ------- + + var SCREEN_WIDTH = window.innerWidth; + var SCREEN_HEIGHT = window.innerHeight; + var FLOOR = -250; + + var container,stats; + + var camera, scene; + var renderer; + + var mesh, helper; + + var mouseX = 0, mouseY = 0; + + var windowHalfX = window.innerWidth / 2; + var windowHalfY = window.innerHeight / 2; + + var clock = new THREE.Clock(); + + document.addEventListener( 'mousemove', onDocumentMouseMove, false ); + + init(); + animate(); + + function init() { + + container = document.getElementById( 'container' ); + + camera = new THREE.PerspectiveCamera( 30, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000 ); + camera.position.z = 2200; + + scene = new THREE.Scene(); + + scene.fog = new THREE.Fog( 0xffffff, 2000, 10000 ); + + scene.add( camera ); + + // GROUND + + var groundMaterial = new THREE.MeshPhongMaterial( { emissive: 0xbbbbbb } ); + var planeGeometry = new THREE.PlaneGeometry( 16000, 16000 ); + + var ground = new THREE.Mesh( planeGeometry, groundMaterial ); + ground.position.set( 0, FLOOR, 0 ); + ground.rotation.x = -Math.PI/2; + scene.add( ground ); + + ground.receiveShadow = true; + + + // LIGHTS + + var ambient = new THREE.AmbientLight( 0x222222 ); + scene.add( ambient ); + + + var light = new THREE.DirectionalLight( 0xebf3ff, 1.6 ); + light.position.set( 0, 140, 500 ).multiplyScalar( 1.1 ); + scene.add( light ); + + light.castShadow = true; + + light.shadowMapWidth = 2048; + light.shadowMapHeight = 2048; + + var d = 390; + + light.shadowCameraLeft = -d * 2; + light.shadowCameraRight = d * 2; + light.shadowCameraTop = d * 1.5; + light.shadowCameraBottom = -d; + + light.shadowCameraFar = 3500; + //light.shadowCameraVisible = true; + + // + + var light = new THREE.DirectionalLight( 0x497f13, 1 ); + light.position.set( 0, -1, 0 ); + scene.add( light ); + + // RENDERER + + renderer = new THREE.WebGLRenderer( { antialias: true } ); + renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); + renderer.domElement.style.position = "relative"; + + renderer.setClearColor( scene.fog.color, 1 ); + + container.appendChild( renderer.domElement ); + + renderer.gammaInput = true; + renderer.gammaOutput = true; + + renderer.shadowMapEnabled = true; + + + // STATS + + stats = new Stats(); + container.appendChild( stats.domElement ); + + // + + var loader = new THREE.JSONLoader(); + loader.load( "models/skinned/knight.js", function ( geometry, materials ) { + + createScene( geometry, materials, 0, FLOOR, -300, 60 ) + + } ); + + // GUI + + initGUI(); + + // + + window.addEventListener( 'resize', onWindowResize, false ); + + } + + function onWindowResize() { + + windowHalfX = window.innerWidth / 2; + windowHalfY = window.innerHeight / 2; + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize( window.innerWidth, window.innerHeight ); + + } + + function ensureLoop( animation ) { + + for ( var i = 0; i < animation.hierarchy.length; i ++ ) { + + var bone = animation.hierarchy[ i ]; + + var first = bone.keys[ 0 ]; + var last = bone.keys[ bone.keys.length - 1 ]; + + last.pos = first.pos; + last.rot = first.rot; + last.scl = first.scl; + + } + + } + + function createScene( geometry, materials, x, y, z, s ) { + + ensureLoop( geometry.animation ); + + geometry.computeBoundingBox(); + var bb = geometry.boundingBox; + + var path = "textures/cube/Park2/"; + var format = '.jpg'; + var urls = [ + path + 'posx' + format, path + 'negx' + format, + path + 'posy' + format, path + 'negy' + format, + path + 'posz' + format, path + 'negz' + format + ]; + + + //var envMap = THREE.ImageUtils.loadTextureCube( urls ); + + //var map = THREE.ImageUtils.loadTexture( "textures/UV_Grid_Sm.jpg" ); + + //var bumpMap = THREE.ImageUtils.generateDataTexture( 1, 1, new THREE.Color() ); + //var bumpMap = THREE.ImageUtils.loadTexture( "textures/water.jpg" ); + + for ( var i = 0; i < materials.length; i ++ ) { + + var m = materials[ i ]; + m.skinning = true; + m.morphTargets = true; + + m.specular.setHSL( 0, 0, 0.1 ); + + m.color.setHSL( 0.6, 0, 0.6 ); + m.ambient.copy( m.color ); + + //m.map = map; + //m.envMap = envMap; + //m.bumpMap = bumpMap; + //m.bumpScale = 2; + + //m.combine = THREE.MixOperation; + //m.reflectivity = 0.75; + + m.wrapAround = true; + + } + + mesh = new THREE.SkinnedMesh( geometry, new THREE.MeshFaceMaterial( materials ) ); + mesh.position.set( x, y - bb.min.y * s, z ); + mesh.scale.set( s, s, s ); + scene.add( mesh ); + + mesh.castShadow = true; + mesh.receiveShadow = true; + + helper = new THREE.SkeletonHelper( mesh ); + helper.material.linewidth = 3; + helper.visible = false; + scene.add( helper ); + + var animation = new THREE.Animation( mesh, geometry.animation ); + animation.play(); + + } + + function initGUI() { + + var API = { + 'show model' : true, + 'show skeleton' : false + }; + + var gui = new dat.GUI(); + + gui.add( API, 'show model' ).onChange( function() { mesh.visible = API[ 'show model' ]; } ); + + gui.add( API, 'show skeleton' ).onChange( function() { helper.visible = API[ 'show skeleton' ]; } ); + + } + + function onDocumentMouseMove( event ) { + + mouseX = ( event.clientX - windowHalfX ); + mouseY = ( event.clientY - windowHalfY ); + + } + + // + + function animate() { + + requestAnimationFrame( animate ); + + render(); + stats.update(); + + } + + function render() { + + var delta = 0.75 * clock.getDelta(); + + camera.position.x += ( mouseX - camera.position.x ) * .05; + camera.position.y = THREE.Math.clamp( camera.position.y + ( - mouseY - camera.position.y ) * .05, 0, 1000 ); + + camera.lookAt( scene.position ); + + // update skinning + + THREE.AnimationHandler.update( delta ); + + if ( helper !== undefined ) helper.update(); + + // update morphs + + if ( mesh ) { + + var time = Date.now() * 0.001; + + // mouth + + mesh.morphTargetInfluences[ 1 ] = ( 1 + Math.sin( 4 * time ) ) / 2; + + // frown ? + + mesh.morphTargetInfluences[ 2 ] = ( 1 + Math.sin( 2 * time ) ) / 2; + + // eyes + + mesh.morphTargetInfluences[ 3 ] = ( 1 + Math.cos( 4 * time ) ) / 2; + + } + + renderer.render( scene, camera ); + + } +} \ No newline at end of file diff --git a/threejs/tests/webgl/webgl_buffergeometry.ts b/threejs/tests/webgl/webgl_buffergeometry.ts index f8d455932..de4ad2aee 100644 --- a/threejs/tests/webgl/webgl_buffergeometry.ts +++ b/threejs/tests/webgl/webgl_buffergeometry.ts @@ -49,11 +49,6 @@ var geometry = new THREE.BufferGeometry(); - geometry.addAttribute('index', new Uint16Array(triangles * 3), 1); - geometry.addAttribute('position', new Float32Array(triangles * 3 * 3), 3); - geometry.addAttribute('normal', new Float32Array(triangles * 3 * 3), 3); - geometry.addAttribute('color', new Float32Array(triangles * 3 * 3), 3); - // break geometry into // chunks of 21,845 triangles (3 unique vertices per triangle) // for indices to fit into 16 bit integer number @@ -61,7 +56,7 @@ var chunkSize = 21845; - var indices = geometry.getAttribute('index').array; + var indices = new Uint16Array( triangles * 3 ); for (var i = 0; i < indices.length; i++) { @@ -69,9 +64,9 @@ } - var positions = geometry.getAttribute('position').array; - var normals = geometry.getAttribute('normal').array; - var colors = geometry.getAttribute('color').array; + var positions = new Float32Array( triangles * 3 * 3 ); + var normals = new Float32Array( triangles * 3 * 3 ); + var colors = new Float32Array( triangles * 3 * 3 ); var color = new THREE.Color(); @@ -167,6 +162,11 @@ } + geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) ); + geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); + geometry.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) ); + geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) ); + var offsets = triangles / chunkSize; for (var i = 0; i < offsets; i++) { diff --git a/threejs/tests/webgl/webgl_camera.ts b/threejs/tests/webgl/webgl_camera.ts index 4bf35883c..531d97fc4 100644 --- a/threejs/tests/webgl/webgl_camera.ts +++ b/threejs/tests/webgl/webgl_camera.ts @@ -85,7 +85,7 @@ } - var particles = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial({ color: 0x888888 })); + var particles = new THREE.PointCloud( geometry, new THREE.PointCloudMaterial( { color: 0x888888 } ) ); scene.add(particles); // diff --git a/threejs/tests/webgl/webgl_interactive_raycasting_pointcloud.ts b/threejs/tests/webgl/webgl_interactive_raycasting_pointcloud.ts new file mode 100644 index 000000000..330abd001 --- /dev/null +++ b/threejs/tests/webgl/webgl_interactive_raycasting_pointcloud.ts @@ -0,0 +1,335 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_sprites.html + +() => { + // ------- variable definitions that does not exist in the original code. These are for typescript. + var material: THREE.SpriteMaterial; + var intersection: THREE.Intersection; + var container: HTMLElement; + var pcBuffer: THREE.PointCloud; + var v: any; + // ------- + + if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); + + var renderer, scene, camera, stats; + var pointclouds; + var projector, raycaster, intersects; + var mouse = { x: 1, y: 1 }; + var vector = new THREE.Vector3(); + intersection = null; + var spheres = []; + var spheresIndex = 0; + var clock; + + var threshold = 0.1; + var pointSize = 0.01; + var width = 150; + var length = 150; + var rotateY = new THREE.Matrix4().makeRotationY( 0.005 ); + + init(); + animate(); + + function generatePointCloudGeometry( color, width, length ){ + + var geometry = new THREE.BufferGeometry(); + var numPoints = width*length; + + var positions = new Float32Array( numPoints*3 ); + var colors = new Float32Array( numPoints*3 ); + + var k = 0; + + for( var i = 0; i < width; i++ ) { + + for( var j = 0; j < length; j++ ) { + + var u = i / width; + var v = j / length; + var x = u - 0.5; + var y = ( Math.cos( u * Math.PI * 8 ) + Math.sin( v * Math.PI * 8 ) ) / 20; + var z = v - 0.5; + + positions[ 3 * k ] = x; + positions[ 3 * k + 1 ] = y; + positions[ 3 * k + 2 ] = z; + + var intensity = ( y + 0.1 ) * 5; + colors[ 3 * k ] = color.r * intensity; + colors[ 3 * k + 1 ] = color.g * intensity; + colors[ 3 * k + 2 ] = color.b * intensity; + + k++; + + } + + } + + geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); + geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) ); + geometry.computeBoundingBox(); + + return geometry; + + } + + function generatePointcloud( color, width, length ) { + + var geometry = generatePointCloudGeometry( color, width, length ); + + var material = new THREE.PointCloudMaterial( { size: pointSize, vertexColors: THREE.VertexColors } ); + var pointcloud = new THREE.PointCloud( geometry, material ); + + return pointcloud; + + } + + function generateIndexedPointcloud( color, width, length ) { + + var geometry = generatePointCloudGeometry( color, width, length ); + var numPoints = width * length; + var indices = new Uint16Array( numPoints ); + + var k = 0; + + for( var i = 0; i < width; i++ ) { + + for( var j = 0; j < length; j++ ) { + + indices[ k ] = k; + k++; + + } + + } + + geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) ); + + var material = new THREE.PointCloudMaterial( { size: pointSize, vertexColors: THREE.VertexColors } ); + var pointcloud = new THREE.PointCloud( geometry, material ); + + return pointcloud; + + } + + function generateIndexedWithOffsetPointcloud( color, width, length ){ + + var geometry = generatePointCloudGeometry( color, width, length ); + var numPoints = width * length; + var indices = new Uint16Array( numPoints ); + + var k = 0; + + for( var i = 0; i < width; i++ ){ + + for( var j = 0; j < length; j++ ) { + + indices[ k ] = k; + k++; + + } + + } + + geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) ); + + var offset = { start: 0, count: indices.length, index: 0 }; + geometry.offsets.push( offset ); + + var material = new THREE.PointCloudMaterial( { size: pointSize, vertexColors: THREE.VertexColors } ); + var pointcloud = new THREE.PointCloud( geometry, material ); + + return pointcloud; + + } + + function generateRegularPointcloud( color, width, length ) { + + var geometry = new THREE.Geometry(); + var numPoints = width * length; + + var colors = []; + + var k = 0; + + for( var i = 0; i < width; i++ ) { + + for( var j = 0; j < length; j++ ) { + + var u = i / width; + v = j / length; + var x = u - 0.5; + var y = ( Math.cos( u * Math.PI * 8 ) + Math.sin( v * Math.PI * 8) ) / 20; + var z = v - 0.5; + v = new THREE.Vector3( x,y,z ); + + var intensity = ( y + 0.1 ) * 7; + colors[ 3 * k ] = color.r * intensity; + colors[ 3 * k + 1 ] = color.g * intensity; + colors[ 3 * k + 2 ] = color.b * intensity; + + geometry.vertices.push( v ); + colors[ k ] = ( color.clone().multiplyScalar( intensity ) ); + + k++; + + } + + } + + geometry.colors = colors; + geometry.computeBoundingBox(); + + var material = new THREE.PointCloudMaterial( { size: pointSize, vertexColors: THREE.VertexColors } ); + var pointcloud = new THREE.PointCloud( geometry, material ); + + return pointcloud; + + } + + function init() { + + container = document.getElementById( 'container' ); + + scene = new THREE.Scene(); + + clock = new THREE.Clock(); + + camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 ); + camera.applyMatrix( new THREE.Matrix4().makeTranslation( 0,0,20 ) ); + camera.applyMatrix( new THREE.Matrix4().makeRotationX( -0.5 ) ); + + // + + pcBuffer = generatePointcloud( new THREE.Color( 1,0,0 ), width, length ); + pcBuffer.scale.set( 10,10,10 ); + pcBuffer.position.set( -5,0,5 ); + scene.add( pcBuffer ); + + var pcIndexed = generateIndexedPointcloud( new THREE.Color( 0,1,0 ), width, length ); + pcIndexed.scale.set( 10,10,10 ); + pcIndexed.position.set( 5,0,5 ); + scene.add( pcIndexed ); + + var pcIndexedOffset = generateIndexedWithOffsetPointcloud( new THREE.Color( 0,1,1 ), width, length ); + pcIndexedOffset.scale.set( 10,10,10 ); + pcIndexedOffset.position.set( 5,0,-5 ); + scene.add( pcIndexedOffset ); + + var pcRegular = generateRegularPointcloud( new THREE.Color( 1,0,1 ), width, length ); + pcRegular.scale.set( 10,10,10 ); + pcRegular.position.set( -5,0,-5 ); + scene.add( pcRegular ); + + pointclouds = [ pcBuffer, pcIndexed, pcIndexedOffset, pcRegular ]; + + // + + var sphereGeometry = new THREE.SphereGeometry( 0.1, 32, 32 ); + var sphereMaterial = new THREE.MeshBasicMaterial( { color: 0xff0000, shading: THREE.FlatShading } ); + + for ( var i = 0; i < 40; i++ ) { + + var sphere = new THREE.Mesh( sphereGeometry, sphereMaterial ); + scene.add( sphere ); + spheres.push( sphere ); + + } + + // + + renderer = new THREE.WebGLRenderer(); + renderer.setSize( window.innerWidth, window.innerHeight ); + + container.appendChild( renderer.domElement ); + + // + + projector = new THREE.Projector(); + raycaster = new THREE.Raycaster(); + raycaster.params.PointCloud.threshold = threshold; + + // + + stats = new Stats(); + stats.domElement.style.position = 'absolute'; + stats.domElement.style.top = '0px'; + container.appendChild( stats.domElement ); + + // + + window.addEventListener( 'resize', onWindowResize, false ); + document.addEventListener( 'mousemove', onDocumentMouseMove, false ); + + } + + function onDocumentMouseMove( event ) { + + event.preventDefault(); + + mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1; + mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1; + + } + + function onWindowResize() { + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize( window.innerWidth, window.innerHeight ); + + } + + function animate() { + + requestAnimationFrame( animate ); + + render(); + stats.update(); + + } + + var toggle = 0; + + function render() { + + camera.applyMatrix( rotateY ); + camera.updateMatrixWorld( true ); + + vector.set( mouse.x, mouse.y, 0.1 ); + + projector.unprojectVector( vector, camera ); + + raycaster.ray.set( camera.position, vector.sub( camera.position ).normalize() ); + + var intersections = raycaster.intersectObjects( pointclouds ); + intersection = ( intersections.length ) > 0 ? intersections[ 0 ] : null; + + if ( toggle > 0.02 && intersection !== null) { + + spheres[ spheresIndex ].position.copy( intersection.point ); + spheres[ spheresIndex ].scale.set( 1, 1, 1 ); + spheresIndex = ( spheresIndex + 1 ) % spheres.length; + + toggle = 0; + + } + + for ( var i = 0; i < spheres.length; i++ ) { + + var sphere = spheres[ i ]; + sphere.scale.multiplyScalar( 0.98 ); + sphere.scale.clampScalar( 0.01, 1 ); + + } + + toggle += clock.getDelta(); + + renderer.render( scene, camera ); + + } +} \ No newline at end of file diff --git a/threejs/tests/webgl/webgl_lensflares.ts b/threejs/tests/webgl/webgl_lensflares.ts index c8e1bfed4..bb99d701c 100644 --- a/threejs/tests/webgl/webgl_lensflares.ts +++ b/threejs/tests/webgl/webgl_lensflares.ts @@ -116,7 +116,7 @@ lensFlare.add(textureFlare3, 70, 1.0, THREE.AdditiveBlending); lensFlare.customUpdateCallback = lensFlareUpdateCallback; - lensFlare.position = light.position; + lensFlare.position.copy( light.position ); scene.add(lensFlare); diff --git a/threejs/tests/webgl/webgl_materials.ts b/threejs/tests/webgl/webgl_materials.ts index 1f1dab70c..da1c311da 100644 --- a/threejs/tests/webgl/webgl_materials.ts +++ b/threejs/tests/webgl/webgl_materials.ts @@ -12,7 +12,7 @@ var container, stats; var camera, scene, renderer, objects; - var particleLight, pointLight; + var particleLight; var materials = []; @@ -130,8 +130,8 @@ scene.add(directionalLight); - pointLight = new THREE.PointLight(0xffffff, 1); - scene.add(pointLight); + var pointLight = new THREE.PointLight(0xffffff, 1); + particleLight.add(pointLight); // @@ -228,10 +228,6 @@ particleLight.position.y = Math.cos(timer * 5) * 400; particleLight.position.z = Math.cos(timer * 3) * 300; - pointLight.position.x = particleLight.position.x; - pointLight.position.y = particleLight.position.y; - pointLight.position.z = particleLight.position.z; - renderer.render(scene, camera); } diff --git a/threejs/tests/webgl/webgl_particles_billboards.ts b/threejs/tests/webgl/webgl_particles_billboards.ts index 8e786303d..a2f62fc6a 100644 --- a/threejs/tests/webgl/webgl_particles_billboards.ts +++ b/threejs/tests/webgl/webgl_particles_billboards.ts @@ -42,10 +42,10 @@ } - material = new THREE.ParticleSystemMaterial({ size: 35, sizeAttenuation: false, map: sprite, transparent: true }); + material = new THREE.PointCloudMaterial({ size: 35, sizeAttenuation: false, map: sprite, transparent: true }); material.color.setHSL(1.0, 0.3, 0.7); - particles = new THREE.ParticleSystem(geometry, material); + particles = new THREE.PointCloud(geometry, material); particles.sortParticles = true; scene.add(particles); diff --git a/threejs/tests/webgl/webgl_postprocessing.ts b/threejs/tests/webgl/webgl_postprocessing.ts index e3aaff31a..707804c28 100644 --- a/threejs/tests/webgl/webgl_postprocessing.ts +++ b/threejs/tests/webgl/webgl_postprocessing.ts @@ -80,8 +80,6 @@ requestAnimationFrame(animate); - var time = Date.now(); - object.rotation.x += 0.005; object.rotation.y += 0.01; diff --git a/threejs/three-tests.ts b/threejs/three-tests.ts index 4ff78b618..46a563a6d 100644 --- a/threejs/three-tests.ts +++ b/threejs/three-tests.ts @@ -26,12 +26,14 @@ THE SOFTWARE. // webGL renderer test. /// +/// /// /// /// /// /// /// +/// /// /// /// @@ -54,3 +56,4 @@ THE SOFTWARE. /// /// /// + diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 748900166..41a07f32b 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -1,4 +1,4 @@ -// Type definitions for three.js r67 +// Type definitions for three.js r68 // Project: http://mrdoob.github.com/three.js/ // Definitions by: Kon , Satoru Kimura // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -174,6 +174,15 @@ declare module THREE { clone(camera?: Camera): Camera; } + export class CubeCamera extends Object3D { + constructor( near?: number, far?: number, cubeResolution?: number); + + renderTarget: WebGLRenderTargetCube; + + updateCubeMap( renderer: Renderer, scene: Scene ): void; + + } + /** * Camera with orthographic projection * @@ -326,43 +335,64 @@ declare module THREE { // Core /////////////////////////////////////////////////////////////////////////////////////////////// export class BufferAttribute { - constructor(); + constructor(array: any, itemSize: number); - set(value: number): void; - setX(index: number, x: number): void; - setY(index: number, y: number): void; - setZ(index: number, z: number): void; - setXY(index: number, x: number, y: number): void; - setXYZ(index: number, x: number, y: number, z: number): void; - setXYZW(index: number, x: number, y: number, z: number, w: number): void; + array: any; + itemSize: number; + length: number; + + set(value: number): BufferAttribute; + setX(index: number, x: number): BufferAttribute; + setY(index: number, y: number): BufferAttribute; + setZ(index: number, z: number): BufferAttribute; + setXY(index: number, x: number, y: number): BufferAttribute; + setXYZ(index: number, x: number, y: number, z: number): BufferAttribute; + setXYZW(index: number, x: number, y: number, z: number, w: number): BufferAttribute; } + // deprecated export class Int8Attribute extends BufferAttribute{ - constructor(size: number, itemSize: number); + constructor(data: any[], itemSize: number); } + + // deprecated export class Uint8Attribute extends BufferAttribute { - constructor(size: number, itemSize: number); + constructor(data: any[], itemSize: number); } + + // deprecated export class Uint8ClampedAttribute extends BufferAttribute { - constructor(size: number, itemSize: number); + constructor(data: any[], itemSize: number); } + + // deprecated export class Int16Attribute extends BufferAttribute { - constructor(size: number, itemSize: number); + constructor(data: any[], itemSize: number); } + + // deprecated export class Uint16Attribute extends BufferAttribute { - constructor(size: number, itemSize: number); + constructor(data: any[], itemSize: number); } + + // deprecated export class Int32Attribute extends BufferAttribute { - constructor(size: number, itemSize: number); + constructor(data: any[], itemSize: number); } + + // deprecated export class Uint32Attribute extends BufferAttribute { - constructor(size: number, itemSize: number); + constructor(data: any[], itemSize: number); } + + // deprecated export class Float32Attribute extends BufferAttribute { - constructor(size: number, itemSize: number); + constructor(data: any[], itemSize: number); } + + // deprecated export class Float64Attribute extends BufferAttribute { - constructor(size: number, itemSize: number); + constructor(data: any[], itemSize: number); } /** @@ -401,6 +431,8 @@ declare module THREE { */ applyMatrix(matrix: Matrix4): void; + fromGeometry( geometry: Geometry, settings?: any ): BufferGeometry; + /** * Computes bounding box of the geometry, updating Geometry.boundingBox attribute. * Bounding boxes aren't computed by default. They need to be explicitly computed, otherwise they are null. @@ -639,7 +671,7 @@ declare module THREE { export interface MorphColor { name: string; - color: Color[]; + colors: Color[]; } export interface MorphNormals { @@ -758,6 +790,11 @@ declare module THREE { */ skinIndices: number[]; + /** + * + */ + lineDistances: number[]; + /** * Bounding box. */ @@ -823,13 +860,18 @@ declare module THREE { /** * */ - lineDistances: number[]; + groupsNeedUpdate: boolean; /** * Bakes matrix transform directly into vertex coordinates. */ applyMatrix(matrix: Matrix4): void; + /** + * + */ + center(): Vector3; + /** * Computes face normals. */ @@ -899,6 +941,11 @@ declare module THREE { */ id: number; + /** + * + */ + uuid: number; + /** * Optional name of the object (doesn't need to be unique). */ @@ -914,6 +961,11 @@ declare module THREE { */ children: Object3D[]; + /** + * Up direction. + */ + up: Vector3; + /** * Object's local position. */ @@ -925,10 +977,9 @@ declare module THREE { rotation: Euler; /** - * Order of axis for Euler angles. + * Global rotation. */ - eulerOrder: string; - // eulerOrder:EulerOrder; + quaternion: Quaternion; /** * Object's local scale. @@ -936,9 +987,14 @@ declare module THREE { scale: Vector3; /** - * Up direction. + * Override depth-sorting order if non null. */ - up: Vector3; + renderDepth: number; + + /** + * When this is set, then the rotationMatrix gets calculated every frame. + */ + rotationAutoUpdate: boolean; /** * Local transform. @@ -946,19 +1002,19 @@ declare module THREE { matrix: Matrix4; /** - * Global rotation. + * The global transform of the object. If the Object3d has no parent, then it's identical to the local transform. */ - quaternion: Quaternion; + matrixWorld: Matrix4; /** - * Use quaternion instead of Euler angles for specifying local rotation. + * When this is set, it calculates the matrix of position, (rotation or quaternion) and scale every frame and also recalculates the matrixWorld property. */ - useQuaternion: boolean; + matrixAutoUpdate: boolean; /** - * Override depth-sorting order if non null. + * When this is set, it calculates the matrixWorld in that frame and resets this property to false. */ - renderDepth: number; + matrixWorldNeedsUpdate: boolean; /** * Object gets rendered if true. @@ -980,54 +1036,95 @@ declare module THREE { */ frustumCulled: boolean; - /** - * When this is set, it calculates the matrix of position, (rotation or quaternion) and scale every frame and also recalculates the matrixWorld property. - */ - matrixAutoUpdate: boolean; - - /** - * When this is set, it calculates the matrixWorld in that frame and resets this property to false. - */ - matrixWorldNeedsUpdate: boolean; - - /** - * When this is set, then the rotationMatrix gets calculated every frame. - */ - rotationAutoUpdate: boolean; - /** * An object that can be used to store custom data about the Object3d. It should not hold references to functions as these will not be cloned. */ userData: any; /** - * The global transform of the object. If the Object3d has no parent, then it's identical to the local transform. + * */ - matrixWorld: Matrix4; + static DefaultUp: Vector3; + /** + * Order of axis for Euler angles. + */ + eulerOrder: string; + // eulerOrder:EulerOrder; + + /** + * Use quaternion instead of Euler angles for specifying local rotation. + */ + useQuaternion: boolean; + /** * This updates the position, rotation and scale with the matrix. */ applyMatrix(matrix: Matrix4): void; + /** + * + */ + setRotationFromAxisAngle(axis: Vector3, angle: number): void; + + /** + * + */ + setRotationFromEuler(euler: Euler ): void; + + /** + * + */ + setRotationFromMatrix(m: Matrix4): void; + + /** + * + */ + setRotationFromQuaternion( q: Quaternion ): void; + + /** + * + * @param angle + */ + rotateX(angle: number): Object3D; + + /** + * + * @param angle + */ + rotateY(angle: number): Object3D; + + /** + * + * @param angle + */ + rotateZ(angle: number): Object3D; + + /** + * + * @param distance + * @param axis + */ + translate( distance: number, axis: Vector3 ): Object3D; + /** * Translates object along x axis by distance. * @param distance Distance. */ - translateX(distance: number): void; + translateX(distance: number): Object3D; /** * Translates object along y axis by distance. * @param distance Distance. */ - translateY(distance: number): void; + translateY(distance: number): Object3D; /** * Translates object along z axis by distance. * @param distance Distance. */ - translateZ(distance: number): void; + translateZ(distance: number): Object3D; /** * Updates the vector from local space to world space. @@ -1057,6 +1154,11 @@ declare module THREE { */ remove(object: Object3D): void; + /** + * + */ + raycast(raycaster: Raycaster, intersects: any): void; + /** * Translates object along arbitrary axis by distance. * @param distance Distance. @@ -1065,10 +1167,22 @@ declare module THREE { traverse(callback: (object: Object3D) => any): void; /** - * Searches whole subgraph recursively to add all objects in the array. - * @param array optional argument that returns the the array with descendants. + * Searches through the object's children and returns the first with a matching id, optionally recursive. + * @param id Unique number of the object instance + * @param recursive Boolean whether to search through the children's children. Default is false. */ - getDescendants(array?: Object3D[]): Object3D[]; + getObjectById(id: string, recursive: boolean): Object3D; + + + /** + * Searches through the object's children and returns the first with a matching name, optionally recursive. + * @param name String to match to the children's Object3d.name property. + * @param recursive Boolean whether to search through the children's children. Default is false. + */ + getObjectByName(name: string, recursive: boolean): Object3D; + + + getChildByName( name: string, recursive: boolean ): Object3D; /** * Updates local transform. @@ -1080,22 +1194,13 @@ declare module THREE { */ updateMatrixWorld(force: boolean): void; + /** + * + * @param object + * @param recursive + */ clone(object?: Object3D, recursive?: boolean): Object3D; - /** - * Searches through the object's children and returns the first with a matching name, optionally recursive. - * @param name String to match to the children's Object3d.name property. - * @param recursive Boolean whether to search through the children's children. Default is false. - */ - getObjectByName(name: string, recursive: boolean): Object3D; - - /** - * Searches through the object's children and returns the first with a matching id, optionally recursive. - * @param id Unique number of the object instance - * @param recursive Boolean whether to search through the children's children. Default is false. - */ - getObjectById(id: string, recursive: boolean): Object3D; - /** * @param axis A normalized vector in object space. * @param distance The distance to translate. @@ -1148,12 +1253,22 @@ declare module THREE { object: Object3D; } + export interface RaycasterParameters { + Sprite?: any; + Mesh?: any; + PointCloud?: any; + LOD?: any; + Line?: any; + } + export class Raycaster { constructor(origin?: Vector3, direction?: Vector3, near?: number, far?: number); ray: Ray; near: number; far: number; + params: RaycasterParameters; precision: number; + linePrecision: number; set(origin: Vector3, direction: Vector3): void; intersectObject(object: Object3D, recursive?: boolean): Intersection[]; intersectObjects(objects: Object3D[], recursive?: boolean): Intersection[]; @@ -1609,17 +1724,34 @@ declare module THREE { initMaterials(materials: Material[], texturePath: string): Material[]; extractUrlBase(url: string): string; addStatusElement(): HTMLElement; + + static Handlers:LoaderHandler; + } + + export interface LoaderHandler{ + handlers:any[]; + add(regex:string, loader:Loader):void; + get(file: string):Loader; } export class BufferGeometryLoader { constructor(manager?: LoadingManager); - load(url: string, onLoad: (bufferGeometry: BufferGeometry) => void): void; + load(url: string, onLoad: (bufferGeometry: BufferGeometry) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; setCrossOrigin(crossOrigin: string): void; parse(json: any): BufferGeometry; } + export class GeometryLoader { + constructor(manager?: LoadingManager); + + load(url: string, onLoad: (bufferGeometry: BufferGeometry) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; + setCrossOrigin(crossOrigin: string): void; + parse(json: any): Geometry; + + } + export class Cache{ constructor(); @@ -1659,12 +1791,16 @@ declare module THREE { * @param callback. This function will be called with the loaded model as an instance of geometry when the load is completed. * @param texturePath If not specified, textures will be assumed to be in the same folder as the Javascript model file. */ - load(url: string, callback: (geometry: Geometry, materials: Material[]) => void , texturePath?: string): void; + load(url: string, callback: (geometry: JSonLoaderResultGeometry, materials: Material[]) => void , texturePath?: string): void; parse(json:string, texturePath:string): any; loadAjaxJSON(context: JSONLoader, url: string, callback: (geometry: Geometry, materials: Material[]) => void , texturePath?: string, callbackProgress?: (progress: Progress) => void ): void; } + export class JSonLoaderResultGeometry extends Geometry { + animation: AnimationData; + } + /** * Handles and keeps track of loaded and pending data. */ @@ -1713,76 +1849,6 @@ declare module THREE { parseObject(data: any, geometries: any[], materials: Material[]): T; } - interface SceneLoaderResult{ - scene: Scene; - geometries: {[id:string]:Geometry;}; - face_materials: {[id:string]:Material;}; - materials: {[id:string]:Material;}; - textures: {[id:string]:Texture;}; - objects: {[id:string]:Object3D;}; - cameras: {[id:string]:Camera;}; - lights: {[id:string]:Light;}; - fogs: {[id:string]:IFog;}; - empties: {[id:string]:any;}; - groups: {[id:string]:any;}; - } - - interface SceneLoaderProgress{ - totalModels: number; - totalTextures: number; - loadedModels: number; - loadedTextures: number; - } - - /** - * A loader for loading a complete scene out of a JSON file. - */ - export class SceneLoader { - constructor(); - - /** - * Will be called when load starts. - * The default is a function with empty body. - */ - onLoadStart: () => void; - - /** - * Will be called while load progresses. - * The default is a function with empty body. - */ - onLoadProgress: () => void; - - /** - * Will be called when each element in the scene completes loading. - * The default is a function with empty body. - */ - onLoadComplete: () => void; - - /** - * Will be called when load completes. - * The default is a function with empty body. - */ - callbackSync: (result: SceneLoaderResult) => void; - - /** - * Will be called as load progresses. - * The default is a function with empty body. - */ - callbackProgress: (progress: SceneLoaderProgress, result: SceneLoaderResult) => void; - hierarchyHandlers: any; - geometryHandlers: any; - - /** - * @param url - * @param callbackFinished This function will be called with the loaded model as an instance of scene when the load is completed. - */ - load(url: string, onLoad: (result: SceneLoaderResult) => void): void; - setCrossOrigin(crossOrigin: string): void; - addHierarchyHandler(typeID: string, loaderClass: any): void; - parse(json: any, callbackFinished: (result: SceneLoaderResult) => void, url: string): void; - addGeometryHandler(typeID: string, loaderClass: any): void; - } - /** * Class for loading a texture. * Unlike other loaders, this one emits events instead of using predefined callbacks. So if you're interested in getting notified when things happen, you need to add listeners to the object. @@ -1804,9 +1870,11 @@ declare module THREE { cache: Cache; crossOrigin: string; + responseType: string; load(url: string, onLoad?: (responseText: string) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; setCrossOrigin(crossOrigin: string): void; + setResponseType(responseType: string): void; } // Materials ////////////////////////////////////////////////////////////////////////////////// @@ -1977,6 +2045,7 @@ declare module THREE { fog?: boolean; lightMap?: Texture; specularMap?: Texture; + alphaMap?: Texture; envMap?: Texture; skinning?: boolean; morphTargets?: boolean; @@ -1999,6 +2068,7 @@ declare module THREE { fog: boolean; lightMap: Texture; specularMap: Texture; + alphaMap: Texture; envMap: Texture; skinning: boolean; morphTargets: boolean; @@ -2044,6 +2114,7 @@ declare module THREE { map?: Texture; lightMap?: Texture; specularMap?: Texture; + alphaMap?: Texture; envMap?: Texture; reflectivity?: number; refractionRatio?: number; @@ -2070,6 +2141,7 @@ declare module THREE { map: Texture; lightMap: Texture; specularMap: Texture; + alphaMap: Texture; envMap: Texture; reflectivity: number; refractionRatio: number; @@ -2116,6 +2188,7 @@ declare module THREE { map?: Texture; lightMap?: Texture; specularMap?: Texture; + alphaMap?: Texture; envMap?: Texture; reflectivity?: number; refractionRatio?: number; @@ -2150,6 +2223,7 @@ declare module THREE { map: Texture; lightMap: Texture; specularMap: Texture; + alphaMap: Texture; envMap: Texture; reflectivity: number; refractionRatio: number; @@ -2169,17 +2243,17 @@ declare module THREE { clone(): MeshPhongMaterial; } - export interface ParticleSystemMaterialParameters { + export interface PointCloudMaterialParameters { color?: number; map?: Texture; size?: number; sizeAttenuation?: boolean; - vertexColors?: boolean; + vertexColors?: Colors; fog?: boolean; } - export class ParticleSystemMaterial extends Material { - constructor(parameters?: ParticleSystemMaterialParameters); + export class PointCloudMaterial extends Material { + constructor(parameters?: PointCloudMaterialParameters); color: Color; map: Texture; size: number; @@ -2187,7 +2261,17 @@ declare module THREE { vertexColors: boolean; fog: boolean; - clone(): ParticleSystemMaterial; + clone(): PointCloudMaterial; + } + + // deprecated + export class ParticleBasicMaterial extends PointCloudMaterial{ + + } + + // deprecated + export class ParticleSystemMaterial extends PointCloudMaterial{ + } export class RawShaderMaterial extends ShaderMaterial { @@ -2337,6 +2421,7 @@ declare module THREE { distanceToPoint(point: Vector3): number; containsPoint(point: Vector3): boolean; setFromCenterAndSize(center: Vector3, size: number): Box3; + setFromObject(object: Object3D): Box3; } export interface HSL { @@ -2466,6 +2551,157 @@ declare module THREE { clone(): Color; } + export class ColorKeywords { + static test2: string; + static aliceblue: string; + static antiquewhite: string; + static aqua: string; + static aquamarine: string; + static azure: string; + static beige: string; + static bisque: string; + static black: string; + static blanchedalmond: string; + static blue: string; + static blueviolet: string; + static brown: string; + static burlywood: string; + static cadetblue: string; + static chartreuse: string; + static chocolate: string; + static coral: string; + static cornflowerblue: string; + static cornsilk: string; + static crimson: string; + static cyan: string; + static darkblue: string; + static darkcyan: string; + static darkgoldenrod: string; + static darkgray: string; + static darkgreen: string; + static darkgrey: string; + static darkkhaki: string; + static darkmagenta: string; + static darkolivegreen: string; + static darkorange: string; + static darkorchid: string; + static darkred: string; + static darksalmon: string; + static darkseagreen: string; + static darkslateblue: string; + static darkslategray: string; + static darkslategrey: string; + static darkturquoise: string; + static darkviolet: string; + static deeppink: string; + static deepskyblue: string; + static dimgray: string; + static dimgrey: string; + static dodgerblue: string; + static firebrick: string; + static floralwhite: string; + static forestgreen: string; + static fuchsia: string; + static gainsboro: string; + static ghostwhite: string; + static gold: string; + static goldenrod: string; + static gray: string; + static green: string; + static greenyellow: string; + static grey: string; + static honeydew: string; + static hotpink: string; + static indianred: string; + static indigo: string; + static ivory: string; + static khaki: string; + static lavender: string; + static lavenderblush: string; + static lawngreen: string; + static lemonchiffon: string; + static lightblue: string; + static lightcoral: string; + static lightcyan: string; + static lightgoldenrodyellow: string; + static lightgray: string; + static lightgreen: string; + static lightgrey: string; + static lightpink: string; + static lightsalmon: string; + static lightseagreen: string; + static lightskyblue: string; + static lightslategray: string; + static lightslategrey: string; + static lightsteelblue: string; + static lightyellow: string; + static lime: string; + static limegreen: string; + static linen: string; + static magenta: string; + static maroon: string; + static mediumaquamarine: string; + static mediumblue: string; + static mediumorchid: string; + static mediumpurple: string; + static mediumseagreen: string; + static mediumslateblue: string; + static mediumspringgreen: string; + static mediumturquoise: string; + static mediumvioletred: string; + static midnightblue: string; + static mintcream: string; + static mistyrose: string; + static moccasin: string; + static navajowhite: string; + static navy: string; + static oldlace: string; + static olive: string; + static olivedrab: string; + static orange: string; + static orangered: string; + static orchid: string; + static palegoldenrod: string; + static palegreen: string; + static paleturquoise: string; + static palevioletred: string; + static papayawhip: string; + static peachpuff: string; + static peru: string; + static pink: string; + static plum: string; + static powderblue: string; + static purple: string; + static red: string; + static rosybrown: string; + static royalblue: string; + static saddlebrown: string; + static salmon: string; + static sandybrown: string; + static seagreen: string; + static seashell: string; + static sienna: string; + static silver: string; + static skyblue: string; + static slateblue: string; + static slategray: string; + static slategrey: string; + static snow: string; + static springgreen: string; + static steelblue: string; + static tan: string; + static teal: string; + static thistle: string; + static tomato: string; + static turquoise: string; + static violet: string; + static wheat: string; + static white: string; + static whitesmoke: string; + static yellow: string; + static yellowgreen: string; + } + export class Euler { constructor(x?: number, y?: number, z?: number, order?: string); @@ -2701,17 +2937,10 @@ declare module THREE { * m.multiply( m3 ); */ export class Matrix4 implements Matrix { - - /** - * Creates an identity matrix. - */ - constructor(); - - /** * Initialises the matrix with the supplied n11..n44 values. */ - constructor(n11: number, n12: number, n13: number, n14: number, n21: number, n22: number, n23: number, n24: number, n31: number, n32: number, n33: number, n34: number, n41: number, n42: number, n43: number, n44: number); + constructor(n11?: number, n12?: number, n13?: number, n14?: number, n21?: number, n22?: number, n23?: number, n24?: number, n31?: number, n32?: number, n33?: number, n34?: number, n41?: number, n42?: number, n43?: number, n44?: number); /** * Float32Array with matrix values. @@ -2936,11 +3165,11 @@ declare module THREE { * Copies values of q to this quaternion. */ copy(q: Quaternion): Quaternion; - setFromEuler(euler: Euler, update?: boolean): Quaternion; + /** * Sets this quaternion from rotation specified by Euler angles. */ - setFromEuler(v: Vector3, order: string): Quaternion; + setFromEuler(euler: Euler, update?: boolean): Quaternion; /** * Sets this quaternion from rotation specified by axis and angle. @@ -2997,6 +3226,8 @@ declare module THREE { equals(v: Quaternion): boolean; + dot(v: Vector3): number; + lengthSq(): number; fromArray(n: number[]): Quaternion; @@ -3021,10 +3252,12 @@ declare module THREE { equals(ray: Ray): boolean; intersectBox(box: Box3, optionalTarget?: Vector3): Vector3; intersectPlane(plane: Plane, optionalTarget?: Vector3): Vector3; + intersectSphere(sphere: Sphere, optionalTarget?: Vector3): Vector3; intersectTriangle(a: Vector3, b: Vector3, c: Vector3, backfaceCulling: boolean, optionalTarget?: Vector3): Vector3; isIntersectionBox(box: Box3): boolean; isIntersectionPlane(plane: Plane): boolean; isIntersectionSphere(sphere: Sphere): boolean; + recast(t: number): Ray; set(origin: Vector3, direction: Vector3): Ray; } @@ -3296,6 +3529,8 @@ declare module THREE { */ negate(): Vector2; + + /** * Computes dot product of this vector and v. */ @@ -3715,14 +3950,13 @@ declare module THREE { export class Bone extends Object3D { constructor(belongsToSkin: SkinnedMesh); - skinMatrix: Matrix4; skin: SkinnedMesh; accumulatedRotWeight: number; accumulatedPosWeight: number; accumulatedSclWeight: number; - update(parentSkinMatrix?: Matrix4, forceUpdate?: boolean): void; + update(forceUpdate?: boolean): void; } export class Line extends Object3D { @@ -3733,8 +3967,10 @@ declare module THREE { constructor(geometry?: BufferGeometry, material?: LineBasicMaterial, type?: number); constructor(geometry?: BufferGeometry, material?: ShaderMaterial, type?: number); geometry: Geometry; - material: Material; + material: LineBasicMaterial; type: LineType; + + raycast(raycaster: Raycaster, intersects: any): void; clone(object?: Line): Line; } @@ -3748,6 +3984,7 @@ declare module THREE { objects: any[]; addLevel(object: Object3D, distance?: number): void; getObjectForDistance(distance: number): Object3D; + raycast(raycaster: Raycaster, intersects: any): void; update(camera: Camera): void; clone(): LOD; } @@ -3761,6 +3998,7 @@ declare module THREE { getMorphTargetIndexByName(name: string): number; updateMorphTargets(): void; + raycast(raycaster: Raycaster, intersects: any): void; clone(object?: Mesh): Mesh; } @@ -3791,7 +4029,7 @@ declare module THREE { parseAnimations(): void; updateAnimation(delta: number): void; setAnimationLabel(label: string, start: number, end: number): void; - + interpolateTargets( a: number, b: number, t: number ): void; clone(object?: MorphAnimMesh): MorphAnimMesh; } @@ -3800,15 +4038,15 @@ declare module THREE { * * @see src/objects/ParticleSystem.js */ - export class ParticleSystem extends Object3D { + export class PointCloud extends Object3D { /** * @param geometry An instance of Geometry. * @param material An instance of Material (optional). */ - constructor(geometry: Geometry, material?: ParticleSystemMaterial); + constructor(geometry: Geometry, material?: PointCloudMaterial); constructor(geometry: Geometry, material?: ShaderMaterial); - constructor(geometry: BufferGeometry, material?: ParticleSystemMaterial); + constructor(geometry: BufferGeometry, material?: PointCloudMaterial); constructor(geometry: BufferGeometry, material?: ShaderMaterial); /** @@ -3821,24 +4059,21 @@ declare module THREE { */ material: Material; - /** - * Specifies whether the particle system will be culled if it's outside the camera's frustum. By default this is set to false. - */ - frustrumCulled: boolean; - sortParticles: boolean; - clone(object?: ParticleSystem): ParticleSystem; + raycast(raycaster: Raycaster, intersects: any): void; + clone(object?: PointCloud): PointCloud; } export class Skeleton extends Mesh { - constructor(boneList: Bone[], useVertexTexture: boolean); + constructor(bones: Bone[], boneInverses?: Matrix4[], useVertexTexture?: boolean); bones: Bone[]; useVertexTexture: boolean; boneMatrices: Float32Array; - addBone(bone: Bone): Bone; calculateInverses(bone: Bone): void; + pose(): void; + update(): void; } export class SkinnedMesh extends Mesh { @@ -3850,10 +4085,14 @@ declare module THREE { constructor(geometry?: Geometry, material?: MeshPhongMaterial, useVertexTexture?: boolean); constructor(geometry?: Geometry, material?: ShaderMaterial, useVertexTexture?: boolean); - identityMatrix: Matrix4; + bindMode: string; + bindMatrix: Matrix4; + bindMatrixInverse: Matrix4; + bind( skeleton: Skeleton, bindMatrix?: Matrix4 ): void; pose(): void; normalizeSkinWeights(): void; + updateMatrixWorld(force?: boolean): void; clone(object?: SkinnedMesh): SkinnedMesh; } @@ -3863,6 +4102,7 @@ declare module THREE { geometry: BufferGeometry; material: SpriteMaterial; + raycast(raycaster: Raycaster, intersects: any): void; updateMatrix(): void; clone(object?: Sprite): Sprite; } @@ -3899,6 +4139,8 @@ declare module THREE { supportsVertexTextures(): void; setSize(width: number, height: number, updateStyle?: boolean): void; setClearColorHex(hex: number, alpha?: number): void; + getClearColor(): Color; + getClearAlpha(): number; setViewport(x: number, y: number, width: number, height: number): void; } @@ -4319,6 +4561,7 @@ declare module THREE { copy(vertex: RenderableVertex): void; } + // Renderers / Shaders ///////////////////////////////////////////////////////////////////// // Renderers / Shaders ///////////////////////////////////////////////////////////////////// export interface ShaderChunk { [name: string]: string; @@ -4514,6 +4757,24 @@ declare module THREE { clone(): CompressedTexture; } + export class CubeTexture extends Texture { + constructor( + images: any[], // HTMLImageElement or HTMLCanvasElement + mapping?: Mapping, + wrapS?: Wrapping, + wrapT?: Wrapping, + magFilter?: TextureFilter, + minFilter?: TextureFilter, + format?: PixelFormat, + type?: TextureDataType, + anisotropy?: number + ); + + images: any[]; + + clone(texture?: CubeTexture): CubeTexture; + } + export class DataTexture extends Texture { constructor( data: ImageData, @@ -4601,6 +4862,9 @@ declare module THREE { clone(): Texture; dispose(): void; + + DEFAULT_IMAGE: any; + DEFAULT_MAPPING: any; } // Extras ///////////////////////////////////////////////////////////////////// @@ -4634,12 +4898,11 @@ declare module THREE { export var GeometryUtils: { // DEPRECATED merge(geometry1: Geometry, object2: Mesh, materialIndexOffset?: number): void; + // DEPRECATED merge(geometry1: Geometry, object2: Geometry, materialIndexOffset?: number): void; - randomPointInTriangle(vectorA: Vector3, vectorB: Vector3, vectorC: Vector3): Vector3; - randomPointInFace(face: Face3, geometry: Geometry, useCachedAreas: boolean): Vector3; - randomPointsInGeometry(geometry: Geometry, points: number): Vector3; - triangleArea(vectorA: Vector3, vectorB: Vector3, vectorC: Vector3): number; + + // DEPRECATED center(geometry: Geometry): Vector3; }; @@ -4647,12 +4910,9 @@ declare module THREE { crossOrigin: string; generateDataTexture(width: number, height: number, color: Color): DataTexture; - parseDDS(buffer: ArrayBuffer, loadMipmaps: boolean): { mipmaps: { data: Uint8Array; width: number; height: number; }[]; width: number; height: number; format: number; mipmapCount: number; }; - loadCompressedTexture(url: string, mapping?: Mapping, onLoad?: (texture: Texture) => void, onError?: (message: string) => void): Texture; loadTexture(url: string, mapping?: Mapping, onLoad?: (texture: Texture) => void, onError?: (message: string) => void): Texture; - getNormalMap(image: HTMLImageElement, depth?: number): HTMLCanvasElement; - loadCompressedTextureCube(array: string[], mapping?: Mapping, onLoad?: () => void, onError?: (message: string) => void): Texture; loadTextureCube(array: string[], mapping?: Mapping, onLoad?: () => void , onError?: (message: string) => void ): Texture; + getNormalMap(image: HTMLImageElement, depth?: number): HTMLCanvasElement; }; export var SceneUtils: { @@ -4684,7 +4944,7 @@ declare module THREE { } export class Animation { - constructor(root: Mesh, name: string); + constructor(root: Mesh, data: AnimationData); root: Mesh; data: AnimationData; @@ -4692,37 +4952,37 @@ declare module THREE { currentTime: number; timeScale: number; isPlaying: boolean; - isPaused: boolean; loop: boolean; weight: number; - interpolationType: AnimationInterpolation; keyTypes: string[]; play(startTime?: number, weight?: number): void; - pause(): void; stop(): void; reset(): void; update(deltaTimeMS: number): void; - interpolateCatmullRom(points: Vector3[], scale: number): Vector3[]; - interpolate(p0: number, p1: number, p2: number, p3: number, t: number, t2: number, t3: number): number; - getNextKeyWith(type: string, h: number, key: number): KeyFrame; // ???? + getNextKeyWith(type: string, h: number, key: number): KeyFrame; getPrevKeyWith(type: string, h: number, key: number): KeyFrame; } - export class AnimationInterpolation { } - export var AnimationHandler: { - CATMULLROM: AnimationInterpolation; - CATMULLROM_FORWARD: AnimationInterpolation; - LINEAR: AnimationInterpolation; + LINEAR: number; + CATMULLROM: number; + CATMULLROM_FORWARD: number; - remove(name: string): void; - removeFromUpdate(animation: Animation): void; - get(name: string): AnimationData; - update(deltaTimeMS: number): void; + animations: any[]; + + init(data: Animation): void; parse(root: Mesh): Object3D[]; + play(animation: Animation): void; + stop(animation: Animation): void; + update(deltaTimeMS: number): void; + + // deprecated add(data: AnimationData): void; - addToUpdate(animation: Animation): void; + // deprecated + get(name: string): AnimationData; + // deprecated + remove(name: string): void; }; export class MorphAnimation { @@ -4741,7 +5001,7 @@ declare module THREE { } export class KeyFrameAnimation { - constructor(root: Mesh, data: any, JITCompile?: boolean); + constructor(data: any); root: Mesh; data: Object; @@ -4753,55 +5013,13 @@ declare module THREE { loop: number; JITCompile: boolean; - play(loop?: number, startTimeMS?: number): void; - pause(): void; + play(startTime?: number): void; stop(): void; - update(deltaTimeMS: number): void; - interpolateCatmullRom(points: Vector3[], scale: number): Vector3[]; - getNextKeyWith(type: string, h: number, key: number): KeyFrame; // ???? + update(delta: number): void; + getNextKeyWith(type: string, h: number, key: number): KeyFrame; getPrevKeyWith(type: string, h: number, key: number): KeyFrame; } - // Extras / Cameras ///////////////////////////////////////////////////////////////////// - - export class CombinedCamera extends Camera { - constructor(width: number, height: number, fov: number, near: number, far: number, orthoNear: number, orthoFar: number); - - fov: number; - right: number; - bottom: number; - cameraP: PerspectiveCamera; - top: number; - zoom: number; - far: number; - near: number; - inPerspectiveMode: boolean; - cameraO: OrthographicCamera; - inOrthographicMode: boolean; - left: number; - - toBottomView(): void; - setFov(fov: number): void; - toBackView(): void; - setZoom(zoom: number): void; - setLens(focalLength: number, frameHeight?: number): number; - toFrontView(): void; - toLeftView(): void; - updateProjectionMatrix(): void; - toTopView(): void; - toOrthographic(): void; - setSize(width: number, height: number): void; - toPerspective(): void; - toRightView(): void; - } - - export class CubeCamera extends Object3D { - constructor(near: number, far: number, cubeResolution: number); - - renderTarget: WebGLRenderTargetCube; - updateCubeMap(renderer: Renderer, scene: Scene): void; - } - // Extras / Curves ///////////////////////////////////////////////////////////////////// export class ArcCurve extends EllipseCurve { constructor(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean ); @@ -5310,11 +5528,13 @@ declare module THREE { } export class SkeletonHelper extends Line { - constructor(bone: Bone); + constructor(bone: Object3D); - skeleton: Skeleton; + bones: Bone[]; + root: Object3D; + matrixWorld: Matrix4; matrixAutoUpdate: boolean; - + getBoneList(object: Object3D): Bone[]; update(): void; } From 1086c1fac6fcbd8f7455aa78d4e7e66d6c1e9051 Mon Sep 17 00:00:00 2001 From: Evgenus Date: Sun, 3 Aug 2014 15:16:57 +0300 Subject: [PATCH 239/324] definitions for BigInt by Baird Leemon. distribution source: https://github.com/Evgenus/BigInt original source: http://www.leemon.com/crypto/BigInt.html --- CONTRIBUTORS.md | 1 + bigint/bigint-tests.ts | 81 ++++++++++++++ bigint/bigint.d.ts | 245 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 327 insertions(+) create mode 100644 bigint/bigint-tests.ts create mode 100644 bigint/bigint.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index af326634b..eab14f2c5 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -31,6 +31,7 @@ All definitions files include a header with the author and editors, so at some p * [Backbone.js](http://backbonejs.org/) (by [Boris Yankov](https://github.com/borisyankov)) * [Backbone Relational](http://backbonerelational.org/) (by [Eirik Hoem](https://github.com/eirikhm)) * [big.js](https://github.com/MikeMcl/big.js) (by [Steve Ognibene](https://github.com/nycdotnet)) +* [BigInt](https://github.com/Evgenus/BigInt) (by [Eugene Chernyshov](https://github.com/Evgenus)) * [BigInteger](https://github.com/peterolson/BigInteger.js) (by [Ingo Bürk](https://github.com/Airblader)) * [BigScreen](http://brad.is/coding/BigScreen/) (by [Douglas Eichelberger](https://github.com/dduugg)) * [Bluebird](https://github.com/petkaantonov/bluebird) (by [Bart van der Schoor](https://github.com/Bartvds)) diff --git a/bigint/bigint-tests.ts b/bigint/bigint-tests.ts new file mode 100644 index 000000000..8ccf2ba4b --- /dev/null +++ b/bigint/bigint-tests.ts @@ -0,0 +1,81 @@ +/// + +var bi: BigInt.BigInt; +var num: number; +var str: string; +var b: boolean; + +BigInt.setRandom(() => { return 0; }); + +bi = BigInt.add(bi, bi); +bi = BigInt.addInt(bi, num); +str = BigInt.bigInt2str(bi, num); +str = BigInt.bigInt2str(bi, str); +num = BigInt.bitSize(bi); +bi = BigInt.dup(bi); +b = BigInt.equals(bi, bi); +b = BigInt.equalsInt(bi, num); +bi = BigInt.expand(bi, num); +var nums: number[] = BigInt.findPrimes(num); +bi = BigInt.GCD(bi, bi); +b = BigInt.greater(bi, bi); +b = BigInt.greaterShift(bi, bi, num); +bi = BigInt.int2bigInt(0); +bi = BigInt.int2bigInt(0, 0); +bi = BigInt.int2bigInt(0, 0, 0); +bi = BigInt.inverseMod(bi, bi); +bi = BigInt.inverseModInt(num, num); +b = BigInt.isZero(bi); +b = BigInt.millerRabin(bi, bi); +b = BigInt.millerRabinInt(num, num); +bi = BigInt.mod(bi, bi); +num = BigInt.modInt(bi, num); +bi = BigInt.mult(bi, bi); +bi = BigInt.multMod(bi, bi, bi); +b = BigInt.negative(bi); +bi = BigInt.powMod(bi, bi, bi); +bi = BigInt.randBigInt(num, num); +bi = BigInt.randTruePrime(num); +bi = BigInt.randProbPrime(num); +bi = BigInt.str2bigInt(str, num); +bi = BigInt.str2bigInt(str, num, 0); +bi = BigInt.str2bigInt(str, num, 0, 0); +bi = BigInt.str2bigInt(str, str); +bi = BigInt.str2bigInt(str, str, 0); +bi = BigInt.str2bigInt(str, str, 0, 0); +bi = BigInt.sub(bi, bi); +bi = BigInt.trim(bi, num); + +BigInt.addInt_(bi, num); +BigInt.add_(bi, bi); +BigInt.copy_(bi, bi); +num = BigInt.copyInt_(bi, num); +BigInt.GCD_(bi, bi); +b = BigInt.inverseMod_(bi, bi); +BigInt.mod_(bi, bi); +BigInt.mult_(bi, bi); +BigInt.multMod_(bi, bi, bi); +BigInt.powMod_(bi, bi, bi); +BigInt.randBigInt_(bi, num, num); +BigInt.randTruePrime_(bi, num); +BigInt.sub_(bi, bi); +BigInt.addShift_(bi, bi, num); +BigInt.carry_(bi); +BigInt.divide_(bi, bi, bi, bi); +num = BigInt.divInt_(bi, num); +BigInt.eGCD_(bi, bi, bi, bi, bi); +BigInt.halve_(bi); +BigInt.leftShift_(bi, num); +BigInt.linComb_(bi, bi, num, num); +BigInt.linCombShift_(bi, bi, num, num); +BigInt.mont_(bi, bi, bi, num); +BigInt.multInt_(bi, num); +BigInt.rightShift_(bi, num); +BigInt.squareMod_(bi, bi); +BigInt.subShift_(bi, bi, num); + +function someRandomRealCode() { + bi = BigInt.int2bigInt(22, 5); + bi = BigInt.str2bigInt("FFFFFFFFFFFFFFFFC90FDAA2", 16); + str = BigInt.bigInt2str(bi, 16); +} diff --git a/bigint/bigint.d.ts b/bigint/bigint.d.ts new file mode 100644 index 000000000..61543b1c6 --- /dev/null +++ b/bigint/bigint.d.ts @@ -0,0 +1,245 @@ +// Type definitions for BigInt v5.5.1 +// Project: https://github.com/Evgenus/BigInt +// Definitions by: Eugene Chernyshov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module BigInt { + export interface BigInt extends Array { + } + + export interface IRandom { + (): number; + } + + export function setRandom(random: IRandom): void; + + // bigInt add(x,y) + // return (x+y) for bigInts x and y. + export function add(x: BigInt, y: BigInt): BigInt; + + // bigInt addInt(x,n) + // return (x+n) where x is a bigInt and n is an integer. + export function addInt(x: BigInt, n: number): BigInt; + + // string bigInt2str(x,base) + // return a string form of bigInt x in a given base, with 2 <= base <= 95 + export function bigInt2str(x: BigInt, base: number): string; + export function bigInt2str(x: BigInt, base: string): string; + + // int bitSize(x) + // return how many bits long the bigInt x is, not counting leading zeros + export function bitSize(x: BigInt): number; + + // bigInt dup(x) + // return a copy of bigInt x + export function dup(x: BigInt): BigInt; + + // boolean equals(x,y) + // is the bigInt x equal to the bigint y? + export function equals(x: BigInt, y: BigInt): boolean; + + // boolean equalsInt(x,y) + // is bigint x equal to integer y? + export function equalsInt(x: BigInt, y: number): boolean; + + // bigInt expand(x,n) + // return a copy of x with at least n elements, adding leading zeros if needed + export function expand(value: BigInt, n: number): BigInt; + + // Array findPrimes(n) + // return array of all primes less than integer n + export function findPrimes(n: number): number[]; + + // bigInt GCD(x,y) + // return greatest common divisor of bigInts x and y (each with same number of elements). + export function GCD(x: BigInt, y: BigInt): BigInt; + + // boolean greater(x,y) + // is x>y? (x and y are nonnegative bigInts) + export function greater(x: BigInt, y: BigInt): boolean; + + // boolean greaterShift(x,y,shift) + // is (x <<(shift*bpe)) > y? + export function greaterShift(x: BigInt, y: BigInt, shift: number): boolean; + + // bigInt int2bigInt(t,n,m) + // return a bigInt equal to integer t, with at least n bits and m array elements + export function int2bigInt(t: number, n?: number, m?: number): BigInt; + + // bigInt inverseMod(x,n) + // return (x**(-1) mod n) for bigInts x and n. If no inverse exists, it returns null + export function inverseMod(x: BigInt, n: BigInt): BigInt; + + // int inverseModInt(x,n) + // return x**(-1) mod n, for integers x and n. Return 0 if there is no inverse + export function inverseModInt(x: number, n: number): BigInt; + + // boolean isZero(x) + // is the bigInt x equal to zero? + export function isZero(x: BigInt): boolean; + + // boolean millerRabin(x,b) + // does one round of Miller-Rabin base integer b say that bigInt x is possibly prime? (b is bigInt, 1=1). If s=1, then the most significant of those n bits is set to 1. + export function randBigInt(n: number, s: number): BigInt; + + // bigInt randTruePrime(k) + // return a new, random, k-bit, true prime bigInt using Maurer's algorithm. + export function randTruePrime(k: number): BigInt; + + // bigInt randProbPrime(k) + // return a new, random, k-bit, probable prime bigInt (probability it's composite less than 2^-80). + export function randProbPrime(k: number): BigInt; + + // bigInt str2bigInt(s,b,n,m) + // return a bigInt for number represented in string s in base b with at least n bits and m array elements + export function str2bigInt(s: string, b: number, n?: number, m?: number): BigInt; + export function str2bigInt(s: string, b: string, n?: number, m?: number): BigInt; + + // bigInt sub(x,y) + // return (x-y) for bigInts x and y. Negative answers will be 2s complement + export function sub(x: BigInt, y: BigInt): BigInt; + + // bigInt trim(x,k) + // return a copy of x with exactly k leading zero elements + export function trim(x: BigInt, k: number): BigInt; + + // void addInt_(x,n) + // do x=x+n where x is a bigInt and n is an integer + export function addInt_(x: BigInt, n: number): void; + + // void add_(x,y) + // do x=x+y for bigInts x and y + export function add_(x: BigInt, y: BigInt): void; + + // void copy_(x,y) + // do x=y on bigInts x and y + export function copy_(x: BigInt, y: BigInt): void; + + // void copyInt_(x,n) + // do x=n on bigInt x and integer n + export function copyInt_(x: BigInt, n: number): number; + + // void GCD_(x,y) + // set x to the greatest common divisor of bigInts x and y, (y is destroyed). (This never overflows its array). + export function GCD_(x: BigInt, y: BigInt): void; + + // boolean inverseMod_(x,n) + // do x=x**(-1) mod n, for bigInts x and n. Returns 1 (0) if inverse does (doesn't) exist + export function inverseMod_(x: BigInt, n: BigInt): boolean; + + // void mod_(x,n) + // do x=x mod n for bigInts x and n. (This never overflows its array). + export function mod_(x: BigInt, n: BigInt): void; + + // void mult_(x,y) + // do x=x*y for bigInts x and y. + export function mult_(x: BigInt, y: BigInt): void; + + // void multMod_(x,y,n) + // do x=x*y mod n for bigInts x,y,n. + export function multMod_(x: BigInt, y: BigInt, n: BigInt): void; + + // void powMod_(x,y,n) + // do x=x**y mod n, where x,y,n are bigInts (n is odd) and ** is exponentiation. 0**0=1. + export function powMod_(x: BigInt, y: BigInt, n: BigInt): void; + + // void randBigInt_(b,n,s) + // do b = an n-bit random BigInt. if s=1, then nth bit (most significant bit) is set to 1. n>=1. + export function randBigInt_(b: BigInt, n: number, s: number): void; + + // void randTruePrime_(ans,k) + // do ans = a random k-bit true random prime (not just probable prime) with 1 in the msb. + export function randTruePrime_(ans: BigInt, k: number): void; + + // void sub_(x,y) + // do x=x-y for bigInts x and y. Negative answers will be 2s complement. + export function sub_(x: BigInt, y: BigInt): void; + + // void addShift_(x,y,ys) + // do x=x+(y<<(ys*bpe)) + export function addShift_(x: BigInt, y: BigInt, ys: number): void; + + // void carry_(x) + // do carries and borrows so each element of the bigInt x fits in bpe bits. + export function carry_(x: BigInt): void; + + // void divide_(x,y,q,r) + // divide x by y giving quotient q and remainder r + export function divide_(x: BigInt, y: BigInt, q: BigInt, r: BigInt): void; + + // int divInt_(x,n) + // do x=floor(x/n) for bigInt x and integer n, and return the remainder. (This never overflows its array). + export function divInt_(x: BigInt, n: number): number; + + // void eGCD_(x,y,d,a,b) + // sets a,b,d to positive bigInts such that d = GCD_(x,y) = a*x-b*y + export function eGCD_(x: BigInt, y: BigInt, d: BigInt, a: BigInt, b: BigInt): void; + + // void halve_(x) + // do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement. (This never overflows its array). + export function halve_(x: BigInt): void; + + // void leftShift_(x,n) + // left shift bigInt x by n bits. n Date: Sun, 3 Aug 2014 15:43:21 +0300 Subject: [PATCH 240/324] definitions for Stanford Javascript Crypto Library --- CONTRIBUTORS.md | 1 + sjcl/sjcl-tests.ts | 267 ++++++++++++++++++++++ sjcl/sjcl.d.ts | 556 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 824 insertions(+) create mode 100644 sjcl/sjcl-tests.ts create mode 100644 sjcl/sjcl.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index af326634b..bf47e04a9 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -306,6 +306,7 @@ All definitions files include a header with the author and editors, so at some p * [SignalR](http://www.asp.net/signalr) (by [Boris Yankov](https://github.com/borisyankov)) * [simple-cw-node](https://github.com/astronaughts/simple-cw-node) (by [vvakame](https://github.com/vvakame)) * [Sinon](http://sinonjs.org/) (by [William Sears](https://github.com/mrbigdog2u)) +* [sjcl](http://crypto.stanford.edu/sjcl/) (by [Eugene Chernyshov](https://github.com/Evgenus)) * [SlickGrid](https://github.com/mleibman/SlickGrid) (by [Josh Baldwin](https://github.com/jbaldwin)) * [smoothie](https://github.com/joewalnes/smoothie) (by [Mike H. Hawley](https://github.com/mikehhawley) and [Drew Noakes](https://drewnoakes.com)) * [socket.io](http://socket.io) (by [William Orr](https://github.com/worr)) diff --git a/sjcl/sjcl-tests.ts b/sjcl/sjcl-tests.ts new file mode 100644 index 000000000..4ff603203 --- /dev/null +++ b/sjcl/sjcl-tests.ts @@ -0,0 +1,267 @@ +/// + +var b: boolean; +var n: number; +var s: string; +var bn: sjcl.BigNumber; +var ba: sjcl.BitArray; + +function testBigNumber() { + bn = new sjcl.bn(); + bn = new sjcl.bn(0); + bn = new sjcl.bn("0"); + bn = new sjcl.bn(bn); + + bn = bn.initWith(0); + bn = bn.initWith("0"); + bn = bn.initWith(bn); + + bn = bn.addM(0); + bn = bn.addM("0"); + bn = bn.addM(bn); + + bn = bn.subM(0); + bn = bn.subM("0"); + bn = bn.subM(bn); + + bn = bn.mod(0); + bn = bn.mod("0"); + bn = bn.mod(bn); + + bn = bn.inverseMod(0); + bn = bn.inverseMod("0"); + bn = bn.inverseMod(bn); + + bn = bn.add(0); + bn = bn.add("0"); + bn = bn.add(bn); + + bn = bn.sub(0); + bn = bn.sub("0"); + bn = bn.sub(bn); + + bn = bn.mul(0); + bn = bn.mul("0"); + bn = bn.mul(bn); + + bn = bn.mulmod(0, 0); + bn = bn.mulmod(0, "0"); + bn = bn.mulmod(0, bn); + bn = bn.mulmod("0", 0); + bn = bn.mulmod("0", "0"); + bn = bn.mulmod("0", bn); + bn = bn.mulmod(bn, 0); + bn = bn.mulmod(bn, "0"); + bn = bn.mulmod(bn, bn); + + bn = bn.powermod(0, 0); + bn = bn.powermod(0, "0"); + bn = bn.powermod(0, bn); + bn = bn.powermod("0", 0); + bn = bn.powermod("0", "0"); + bn = bn.powermod("0", bn); + bn = bn.powermod(bn, 0); + bn = bn.powermod(bn, "0"); + bn = bn.powermod(bn, bn); + + bn = bn.copy(); + + b = bn.equals(0); + b = bn.equals(bn); + + b = bn.greaterEquals(0); + b = bn.greaterEquals(bn); + + n = bn.getLimb(0); + + s = bn.toString(); + + bn = bn.doubleM(); + + bn = bn.halveM(); + + bn = bn.square(); + + bn = bn.power(1); + bn = bn.power([1, 1]); + bn = bn.power(bn); + + bn = bn.trim(); + + bn = bn.reduce(); + + bn = bn.fullReduce(); + + bn = bn.normalize(); + + bn = bn.cnormalize(); + + ba = bn.toBits(); + ba = bn.toBits(1); + + n = bn.bitLength(); + + bn = sjcl.bn.fromBits(ba); +} + +function testBitArray() { + ba = sjcl.bitArray.bitSlice(ba, 0, 1); + + n = sjcl.bitArray.extract(ba, 0, 1); + + ba = sjcl.bitArray.concat(ba, ba); + + n = sjcl.bitArray.bitLength(ba); + + ba = sjcl.bitArray.clamp(ba, 0); + + n = sjcl.bitArray.partial(1, 1); + n = sjcl.bitArray.partial(1, 1, 0); + + n = sjcl.bitArray.getPartial(0); + + b = sjcl.bitArray.equal(ba, ba); + + ba = sjcl.bitArray._shiftRight(ba, 0); + ba = sjcl.bitArray._shiftRight(ba, 0, 0); + ba = sjcl.bitArray._shiftRight(ba, 0, 0, ba); +} + +function testCodecs() { + s = sjcl.codec.base64.fromBits(ba); + ba = sjcl.codec.base64.toBits(s); + + s = sjcl.codec.base64url.fromBits(ba); + ba = sjcl.codec.base64url.toBits(s); + + s = sjcl.codec.hex.fromBits(ba); + ba = sjcl.codec.hex.toBits(s); + + s = sjcl.codec.utf8String.fromBits(ba); + ba = sjcl.codec.utf8String.toBits(s); + + var bytes: number[] = sjcl.codec.bytes.fromBits(ba); + ba = sjcl.codec.bytes.toBits(bytes); +} + +function testHashes() { + var hash: sjcl.SjclHash; + ba = hash.reset().update("xxx").update(ba).finalize(); + + hash = new sjcl.hash.sha1(); + hash = new sjcl.hash.sha1(hash); + ba = sjcl.hash.sha1.hash(ba); + ba = sjcl.hash.sha1.hash("xxx"); + + hash = new sjcl.hash.sha256(); + hash = new sjcl.hash.sha256(hash); + ba = sjcl.hash.sha256.hash(ba); + ba = sjcl.hash.sha256.hash("xxx"); + + hash = new sjcl.hash.sha512(); + hash = new sjcl.hash.sha512(hash); + ba = sjcl.hash.sha512.hash(ba); + ba = sjcl.hash.sha512.hash("xxx"); +} + +function testSymetric() { + var aes = new sjcl.cipher.aes([0, 0, 0, 0]); + + ba = sjcl.mode.cbc.encrypt(aes, ba, ba); + ba = sjcl.mode.cbc.encrypt(aes, ba, ba, ba); + + ba = sjcl.mode.gcm.encrypt(aes, ba, ba); + ba = sjcl.mode.gcm.encrypt(aes, ba, ba, ba); + ba = sjcl.mode.gcm.encrypt(aes, ba, ba, ba, 128); + + ba = sjcl.mode.ccm.encrypt(aes, ba, ba); + ba = sjcl.mode.ccm.encrypt(aes, ba, ba, ba); + ba = sjcl.mode.ccm.encrypt(aes, ba, ba, ba, 128); + + ba = sjcl.mode.ocb2.encrypt(aes, ba, ba); + ba = sjcl.mode.ocb2.encrypt(aes, ba, ba, ba); + ba = sjcl.mode.ocb2.encrypt(aes, ba, ba, ba, 128); + ba = sjcl.mode.ocb2.encrypt(aes, ba, ba, ba, 128, false); +} + +function testHmacPbdkf2() { + ba = sjcl.misc.pbkdf2("xxx", "xxx"); + ba = sjcl.misc.pbkdf2("xxx", "xxx", 1000); + ba = sjcl.misc.pbkdf2("xxx", "xxx", 1000, 12); + ba = sjcl.misc.pbkdf2("xxx", "xxx", 1000, 12, sjcl.misc.hmac); + + ba = sjcl.misc.pbkdf2("xxx", ba); + ba = sjcl.misc.pbkdf2("xxx", ba, 1000); + ba = sjcl.misc.pbkdf2("xxx", ba, 1000, 12); + ba = sjcl.misc.pbkdf2("xxx", ba, 1000, 12, sjcl.misc.hmac); + + ba = sjcl.misc.pbkdf2(ba, "xxx"); + ba = sjcl.misc.pbkdf2(ba, "xxx", 1000); + ba = sjcl.misc.pbkdf2(ba, "xxx", 1000, 12); + ba = sjcl.misc.pbkdf2(ba, "xxx", 1000, 12, sjcl.misc.hmac); + + ba = sjcl.misc.pbkdf2(ba, ba); + ba = sjcl.misc.pbkdf2(ba, ba, 1000); + ba = sjcl.misc.pbkdf2(ba, ba, 1000, 12); + ba = sjcl.misc.pbkdf2(ba, ba, 1000, 12, sjcl.misc.hmac); + + var hmac: sjcl.SjclHmac; + hmac = new sjcl.misc.hmac(ba); + hmac = new sjcl.misc.hmac(ba, sjcl.hash.sha512); + + ba = hmac.mac("xxx"); + ba = hmac.mac(ba); + + ba = hmac.encrypt("xxx"); + ba = hmac.encrypt(ba); + + hmac.reset(); + + hmac.update("xxx"); + hmac.update(ba); + + ba = hmac.digest(); +} + +function testECC() { + var keys = sjcl.ecc.elGamal.generateKeys(192, 0); + + var ciphertext = sjcl.encrypt(keys.pub, "hello world"); + var plaintext = sjcl.decrypt(keys.sec, ciphertext); + + // TODO: Maybe deeper testing required. Let me know +} + +function testRandom() { + b = sjcl.random.isReady(); + ba = sjcl.random.randomWords(8); + ba = sjcl.random.randomWords(8, 6); + + var rnd = new sjcl.prng(1); + ba = rnd.randomWords(16); + ba = rnd.randomWords(16, 6); +} + +function testSRP() { + var group = sjcl.keyexchange.srp.knownGroup(1024); + ba = sjcl.codec.hex.toBits(s); + ba = sjcl.keyexchange.srp.makeX(s, s, ba); + ba = sjcl.keyexchange.srp.makeVerifier(s, s, ba, group); +} + +function testConvenince() { + var x: sjcl.SjclCipherEncrypted; + x = sjcl.encrypt("xxx", "text"); + s = sjcl.decrypt(ba, x); + + x = sjcl.encrypt("xxx", "text", { iv: ba, salt: ba }); + s = sjcl.decrypt(ba, x, { iv: ba, salt: ba }); + + var y: sjcl.SjclCipherDecrypted; + + sjcl.encrypt("xxx", "text", { iv: ba, salt: ba, mode: "gcm" }, x); + s = sjcl.decrypt(ba, x, { iv: ba, salt: ba, mode: "gcm" }, y); + + sjcl.encrypt("xxx", "text", { iv: ba, salt: ba, mode: "gcm", iter: 200 }, x); + s = sjcl.decrypt(ba, x, { iv: ba, salt: ba, mode: "gcm", iter: 200 }, y); +} \ No newline at end of file diff --git a/sjcl/sjcl.d.ts b/sjcl/sjcl.d.ts new file mode 100644 index 000000000..8413edb2f --- /dev/null +++ b/sjcl/sjcl.d.ts @@ -0,0 +1,556 @@ +// Type definitions for sjcl v1.0.1 +// Project: http://crypto.stanford.edu/sjcl/ +// Definitions by: Eugene Chernyshov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module sjcl { + + export var bn: BigNumberStatic; + export var bitArray: BitArrayStatic; + export var codec: SjclCodecs; + export var hash: SjclHashes; + export var exception: SjclExceptions; + export var cipher: SjclCiphers; + export var mode: SjclModes; + export var misc: SjclMisc; + export var ecc: SjclEllipticCurveCryptography; + export var random: SjclRandom; + export var prng: SjclRandomStatic; + export var keyexchange: SjclKeyExchange; + export var json: SjclJson; + export var encrypt: SjclConveninceEncryptor; + export var decrypt: SjclConveninceDecryptor; + + // ________________________________________________________________________ + + interface BigNumber { + radix: number; + maxMul: number; + + copy(): BigNumber; + + /// Initializes this with it, either as a bn, a number, or a hex string. + initWith: TypeHelpers.BigNumberBinaryOperator; + + /// Returns true if "this" and "that" are equal. Calls fullReduce(). + /// Equality test is in constant time. + equals(that: number): boolean; + equals(that: BigNumber): boolean; + + /// Get the i'th limb of this, zero if i is too large. + getLimb(index: number): number; + + /// Constant time comparison function. + /// Returns 1 if this >= that, or zero otherwise. + greaterEquals(that: number): boolean; + greaterEquals(that: BigNumber): boolean; + + /// Convert to a hex string. + toString(): string; + + /// this += that. Does not normalize. + addM: TypeHelpers.BigNumberBinaryOperator; + + /// this *= 2. Requires normalized; ends up normalized. + doubleM(): BigNumber; + + /// this /= 2, rounded down. Requires normalized; ends up normalized. + halveM(): BigNumber; + + /// this -= that. Does not normalize. + subM: TypeHelpers.BigNumberBinaryOperator; + + mod: TypeHelpers.BigNumberBinaryOperator; + + /// return inverse mod prime p. p must be odd. Binary extended Euclidean algorithm mod p. + inverseMod: TypeHelpers.BigNumberBinaryOperator; + + /// this + that. Does not normalize. + add: TypeHelpers.BigNumberBinaryOperator; + + /// this - that. Does not normalize. + sub: TypeHelpers.BigNumberBinaryOperator; + + /// this * that. Normalizes and reduces. + mul: TypeHelpers.BigNumberBinaryOperator; + + /// this ^ 2. Normalizes and reduces. + square(): BigNumber; + + /// this ^ n. Uses square-and-multiply. Normalizes and reduces. + power(n: number): BigNumber; + power(n: BigNumber): BigNumber; + power(a: number[]): BigNumber; + + /// this * that mod N + mulmod: TypeHelpers.BigNumberTrinaryOperator; + + /// this ^ x mod N + powermod: TypeHelpers.BigNumberTrinaryOperator; + + trim(): BigNumber; + + /// Reduce mod a modulus. Stubbed for subclassing. + reduce(): BigNumber; + + /// Reduce and normalize. + fullReduce(): BigNumber; + + /// Propagate carries. + normalize(): BigNumber; + + /// Constant-time normalize. Does not allocate additional space. + cnormalize(): BigNumber; + + /// Serialize to a bit array + toBits(len?: number): BitArray; + + /// Return the length in bits, rounded up to the nearest byte. + bitLength(): number; + } + + interface BigNumberStatic { + new (): BigNumber; + new (n: string): BigNumber; + new (n: number): BigNumber; + new (n: BigNumber): BigNumber; + + fromBits(bits: BitArray): BigNumber; + random: TypeHelpers.Bind1; + prime: { + p127: PseudoMersennePrimeStatic; + // Bernstein's prime for Curve25519 + p25519: PseudoMersennePrimeStatic; + // Koblitz primes + p192k: PseudoMersennePrimeStatic; + p224k: PseudoMersennePrimeStatic; + p256k: PseudoMersennePrimeStatic; + // NIST primes + p192: PseudoMersennePrimeStatic; + p224: PseudoMersennePrimeStatic; + p256: PseudoMersennePrimeStatic; + p384: PseudoMersennePrimeStatic; + p521: PseudoMersennePrimeStatic; + }; + + pseudoMersennePrime(exponent: number, coeff: number[][]): PseudoMersennePrimeStatic; + } + + interface PseudoMersennePrime extends BigNumber { + reduce(): PseudoMersennePrime; + fullReduce(): PseudoMersennePrime; + inverse(): PseudoMersennePrime; + } + + interface PseudoMersennePrimeStatic extends BigNumberStatic { + new (): PseudoMersennePrime; + new (n: string): PseudoMersennePrime; + new (n: number): PseudoMersennePrime; + new (n: BigNumber): PseudoMersennePrime; + } + + // ________________________________________________________________________ + + interface BitArray extends Array { + } + + interface BitArrayStatic { + /// Array slices in units of bits. + bitSlice(a: BitArray, bstart: number, bend: number): BitArray; + + /// Extract a number packed into a bit array. + extract(a: BitArray, bstart: number, blenth: number): number; + + /// Concatenate two bit arrays. + concat(a1: BitArray, a2: BitArray): BitArray + + /// Find the length of an array of bits. + bitLength(a: BitArray): number; + + /// Truncate an array. + clamp(a: BitArray, len: number): BitArray; + + /// Make a partial word for a bit array. + partial(len: number, x: number, _end?: number): number; + + /// Get the number of bits used by a partial word. + getPartial(x: number): number; + + /// Compare two arrays for equality in a predictable amount of time. + equal(a: BitArray, b: BitArray): boolean; + + /// Shift an array right. + _shiftRight(a: BitArray, shift: number, carry?: number, out?: BitArray): BitArray; + + /// xor a block of 4 words together. + _xor4(x: number[], y: number[]): number[]; + } + + // ________________________________________________________________________ + + interface SjclCodec { + fromBits(bits: BitArray): T; + toBits(value: T): BitArray; + } + + interface SjclCodecs { + utf8String: SjclCodec; + hex: SjclCodec; + bytes: SjclCodec; + base64: SjclCodec; + base64url: SjclCodec; + } + + // ________________________________________________________________________ + + interface SjclHash { + reset(): SjclHash; + update(data: string): SjclHash; + update(data: BitArray): SjclHash; + finalize(): BitArray; + } + + interface SjclHashStatic { + new (hash?: SjclHash): SjclHash; + hash(data: string): BitArray; + hash(data: BitArray): BitArray; + } + + interface SjclHashes { + sha1: SjclHashStatic; + sha256: SjclHashStatic; + sha512: SjclHashStatic; + } + + // ________________________________________________________________________ + + interface SjclExceptions { + corrupt: SjclExceptionFactory; + invalid: SjclExceptionFactory; + bug: SjclExceptionFactory; + notReady: SjclExceptionFactory; + } + + interface SjclExceptionFactory { + new (message: string): Error; + } + + // ________________________________________________________________________ + + interface SjclCiphers { + aes: SjclCipherStatic; + } + + interface SjclCipher { + encrypt(data: number[]): number[]; + decrypt(data: number[]): number[]; + } + + interface SjclCipherStatic { + new (key: number[]): SjclCipher; + } + + // ________________________________________________________________________ + + interface SjclModes { + gcm: SjclGCMMode; + ccm: SjclCCMMode; + ocb2: SjclOCB2Mode; + cbc: SjclCBCMode; + } + + interface SjclGCMMode { + encrypt(prp: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray; + decrypt(prp: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray; + } + + interface SjclCCMMode { + encrypt(prp: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray; + decrypt(prp: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray; + } + + interface SjclOCB2Mode { + encrypt(prp: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number, premac?: boolean): BitArray; + decrypt(prp: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number, premac?: boolean): BitArray; + pmac(prp: SjclCipher, adata: BitArray): number[]; + } + + interface SjclCBCMode { + encrypt(prp: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray): BitArray; + decrypt(prp: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray): BitArray; + } + + // ________________________________________________________________________ + + interface Pbkdf2Params { + iter?: number; + salt?: BitArray; + } + + interface SjclMisc { + pbkdf2(password: string, salt: string, count?: number, length?: number, Prff?: SjclPseudorandomFunctionFamilyStatic): BitArray; + pbkdf2(password: BitArray, salt: string, count?: number, length?: number, Prff?: SjclPseudorandomFunctionFamilyStatic): BitArray; + pbkdf2(password: BitArray, salt: BitArray, count?: number, length?: number, Prff?: SjclPseudorandomFunctionFamilyStatic): BitArray; + pbkdf2(password: string, salt: BitArray, count?: number, length?: number, Prff?: SjclPseudorandomFunctionFamilyStatic): BitArray; + hmac: SjclHmacStatic; + cachedPbkdf2(password: string, obj?: Pbkdf2Params): { + key: BitArray; + salt: BitArray; + }; + } + + class SjclPseudorandomFunctionFamily { + encrypt(data: string): BitArray; + encrypt(data: BitArray): BitArray; + } + + interface SjclHmac extends SjclPseudorandomFunctionFamily { + mac(data: string): BitArray; + mac(data: BitArray): BitArray; + reset(): void; + update(data: string): void; + update(data: BitArray): void; + digest(): BitArray; + } + + interface SjclPseudorandomFunctionFamilyStatic { + new (key: BitArray): SjclPseudorandomFunctionFamily; + } + + interface SjclHmacStatic { + new (key: BitArray, Hash?: SjclHashStatic): SjclHmac; + } + + // ________________________________________________________________________ + + interface SjclEllipticCurveCryptography { + point: SjclEllipticalPointStatic; + pointJac: SjclPointJacobianStatic; + curve: SjclEllipticalCurveStatic; + curves: { + c192: SjclEllipticalCurve; + c224: SjclEllipticalCurve; + c256: SjclEllipticalCurve; + c384: SjclEllipticalCurve; + k192: SjclEllipticalCurve; + k224: SjclEllipticalCurve; + k256: SjclEllipticalCurve; + }; + basicKey: SjclECCBasic; + elGamal: SjclElGamal; + ecdsa: SjclEcdsa; + } + + interface SjclEllipticalPoint { + toJac(): SjclPointJacobian; + mult(k: BigNumber): SjclEllipticalPoint; + mult2(k: BigNumber, k2: BigNumber, affine2: SjclEllipticalPoint): SjclEllipticalPoint; + multiples(): Array; + isValid(): boolean; + toBits(): BitArray; + } + + interface SjclEllipticalPointStatic { + new (curve: SjclEllipticalCurve, x?: BigNumber, y?: BigNumber): SjclEllipticalPoint; + } + + interface SjclPointJacobian { + add(T: SjclEllipticalPoint): SjclPointJacobian; + doubl(): SjclPointJacobian; + toAffine(): SjclEllipticalPoint; + mult(k: BigNumber, affine: SjclEllipticalPoint): SjclPointJacobian; + mult2(k1: BigNumber, affine: SjclEllipticalPoint, k2: BigNumber, affine2: SjclEllipticalPoint): SjclPointJacobian; + isValid(): boolean; + } + + interface SjclPointJacobianStatic { + new (curve: SjclEllipticalCurve, x?: BigNumber, y?: BigNumber, z?: BigNumber):SjclPointJacobian; + } + + interface SjclEllipticalCurve { + fromBits(bits: BitArray): SjclEllipticalPoint; + } + + interface SjclEllipticalCurveStatic { + new (Field: BigNumber, r: BigNumber, a: BigNumber, b: BigNumber, x: BigNumber, y: BigNumber): SjclEllipticalCurve; + } + + interface SjclKeyPair

{ + pub: P; + sec: S; + } + + interface SjclKeysGenerator

{ + (curve: SjclEllipticalCurve, paranoia: number, sec?: BigNumber): SjclKeyPair; + (curve: number, paranoia: number, sec?: BigNumber): SjclKeyPair; + } + + interface SjclECCPublicKeyData { + x: BitArray; + y: BitArray; + } + + class SjclECCPublicKey { + get(): SjclECCPublicKeyData; + } + + class SjclECCSecretKey { + get(): BitArray; + } + + interface SjclECCPublicKeyFactory { + new (curve: SjclEllipticalCurve, point: SjclEllipticalPoint): T; + new (curve: SjclEllipticalCurve, point: BitArray): T; + } + + interface SjclECCSecretKeyFactory { + new (curve: SjclEllipticalCurve, exponent: BigNumber): T; + } + + interface SjclECCBasic { + publicKey: SjclECCPublicKeyFactory; + secretKey: SjclECCSecretKeyFactory; + generateKeys(cn: string): SjclKeysGenerator; + } + + class SjclElGamalPublicKey extends SjclECCPublicKey { + kem(paranoia: number): { + key: BitArray; + tag: BitArray; + }; + } + + class SjclElGamalSecretKey extends SjclECCSecretKey { + unkem(tag: BitArray): BitArray; + dh(pk: SjclECCPublicKey): BitArray; + } + + interface SjclElGamal { + publicKey: SjclECCPublicKeyFactory; + secretKey: SjclECCSecretKeyFactory; + generateKeys: SjclKeysGenerator; + } + + class SjclEcdsaPublicKey extends SjclECCPublicKey { + verify(hash: BitArray, rs: BitArray, fakeLegacyVersion: boolean): boolean; + } + + class SjclEcdsaSecretKey extends SjclECCSecretKey { + sign(hash: BitArray, paranoia: number, fakeLegacyVersion: boolean, fixedKForTesting?: BigNumber): BitArray; + } + + interface SjclEcdsa { + publicKey: SjclECCPublicKeyFactory; + secretKey: SjclECCSecretKeyFactory; + generateKeys: SjclKeysGenerator; + } + + // ________________________________________________________________________ + + interface SjclRandom { + randomWords(nwords: number, paranoia?: number): BitArray; + setDefaultParanoia(paranoia: number, allowZeroParanoia: string): void; + addEntropy(data: number, estimatedEntropy: number, source: string): void; + addEntropy(data: number[], estimatedEntropy: number, source: string): void; + addEntropy(data: string, estimatedEntropy: number, source: string): void; + isReady(paranoia?: number): boolean; + getProgress(paranoia?: number): number; + startCollectors(): void; + stopCollectors(): void; + addEventListener(name: string, cb: Function): void; + removeEventListener(name: string, cb: Function): void; + } + + interface SjclRandomStatic { + new (defaultParanoia: number): SjclRandom; + } + + // ________________________________________________________________________ + + interface SjclKeyExchange { + srp: SecureRemotePassword; + } + + interface SjclSRPGroup { + N: BigNumber; + g: BigNumber; + } + + interface SecureRemotePassword { + makeVerifier(username: string, password: string, salt: BitArray, group: SjclSRPGroup): BitArray; + makeX(username: string, password: string, salt: BitArray): BitArray; + knownGroup(i: string): SjclSRPGroup; + knownGroup(i: number): SjclSRPGroup; + } + + // ________________________________________________________________________ + + interface SjclCipherParams { + v?: number; + iter?: number; + ks?: number; + ts?: number; + mode?: string; + adata?: string; + cipher?: string; + } + + interface SjclCipherEncryptParams extends SjclCipherParams { + salt: BitArray; + iv: BitArray; + } + + interface SjclCipherDecryptParams extends SjclCipherParams { + salt?: BitArray; + iv?: BitArray; + } + + interface SjclCipherEncrypted extends SjclCipherEncryptParams { + kemtag?: BitArray; + ct: BitArray; + } + + interface SjclCipherDecrypted extends SjclCipherEncrypted { + key: BitArray; + } + + interface SjclConveninceEncryptor { + (password: string, plaintext: string, params?: SjclCipherEncryptParams, rp?: SjclCipherEncrypted): SjclCipherEncrypted; + (password: BitArray, plaintext: string, params?: SjclCipherEncryptParams, rp?: SjclCipherEncrypted): SjclCipherEncrypted; + (password: SjclElGamalPublicKey, plaintext: string, params?: SjclCipherEncryptParams, rp?: SjclCipherEncrypted): SjclCipherEncrypted; + } + + interface SjclConveninceDecryptor { + (password: string, ciphertext: SjclCipherEncrypted, params?: SjclCipherDecryptParams, rp?: SjclCipherDecrypted): string; + (password: BitArray, ciphertext: SjclCipherEncrypted, params?: SjclCipherDecryptParams, rp?: SjclCipherDecrypted): string; + (password: SjclElGamalSecretKey, ciphertext: SjclCipherEncrypted, params?: SjclCipherDecryptParams, rp?: SjclCipherDecrypted): string; + } + + interface SjclJson { + encrypt: SjclConveninceEncryptor; + decrypt: SjclConveninceDecryptor; + encode(obj: Object): string; + decode(obj: string): Object; + } + + // ________________________________________________________________________ + + module TypeHelpers { + interface One { + (value: T): BigNumber; + } + + interface BigNumberBinaryOperator extends One, One, One { + } + + interface Two { + (x: T1, N: T2): BigNumber; + } + + interface Bind1 extends Two, Two, Two { + } + + interface BigNumberTrinaryOperator extends Bind1, Bind1, Bind1 { + } + } +} From b8ce2bd4c01526630b8402af303824bf5341a572 Mon Sep 17 00:00:00 2001 From: Will Johnston Date: Sun, 3 Aug 2014 16:41:25 -0500 Subject: [PATCH 241/324] updated mysql definitions and tests --- mysql/mysql-tests.ts | 381 +++++++++++++++++++++++++++++++++ mysql/mysql.d.ts | 488 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 869 insertions(+) create mode 100644 mysql/mysql-tests.ts create mode 100644 mysql/mysql.d.ts diff --git a/mysql/mysql-tests.ts b/mysql/mysql-tests.ts new file mode 100644 index 000000000..81f1e7766 --- /dev/null +++ b/mysql/mysql-tests.ts @@ -0,0 +1,381 @@ +/// + +import mysql = require('mysql'); + +/// Connections +var connection = mysql.createConnection({ + host: 'localhost', + user: 'me', + password: 'secret' +}); + +connection.connect(); + +connection.query('SELECT 1 + 1 AS solution', function (err, rows, fields) { + if (err) throw err; + + console.log('The solution is: ', rows[0].solution); +}); + +connection.end(); + +connection = mysql.createConnection({ + host: 'example.org', + user: 'bob', + password: 'secret' +}); + +connection.connect(function (err) { + if (err) { + console.error('error connecting: ' + err.stack); + return; + } + + console.log('connected as id ' + connection.threadId); +}); + +connection.query('SELECT 1', function (err, rows) { + // connected! (unless `err` is set) +}); + +connection = mysql.createConnection({ + host: 'localhost', + ssl: { + ca: '' + } +}); + +connection = mysql.createConnection({ + host: 'localhost', + ssl: { + // DO NOT DO THIS + // set up your ca correctly to trust the connection + rejectUnauthorized: false + } +}); + +connection.end(function (err) { + // The connection is terminated now +}); + +connection.destroy(); + +connection.changeUser({ user: 'john' }, function (err) { + if (err) throw err; +}); + +var userId = 'some user provided value'; +var sql = 'SELECT * FROM users WHERE id = ' + connection.escape(userId); +connection.query(sql, function (err, results) { + // ... +}); +connection.query('SELECT * FROM users WHERE id = ?', [userId], function (err, results) { + // ... +}); + +var post = { id: 1, title: 'Hello MySQL' }; +var query = connection.query('INSERT INTO posts SET ?', post, function (err, result) { + // Neat! +}); +console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL' + +var queryStr = "SELECT * FROM posts WHERE title=" + mysql.escape("Hello MySQL"); + +console.log(queryStr); // SELECT * FROM posts WHERE title='Hello MySQL' + +var sorter = 'date'; +var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId(sorter); +connection.query(sql, function (err, results) { + // ... +}); + +var sorter = 'date'; +var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId('posts.' + sorter); +connection.query(sql, function (err, results) { + // ... +}); + +var userIdNum = 1; +var columns = ['username', 'email']; +var query = connection.query('SELECT ?? FROM ?? WHERE id = ?', [columns, 'users', userIdNum], function (err, results) { + // ... +}); + +console.log(query.sql); // SELECT `username`, `email` FROM `users` WHERE id = 1 + +var sql = "SELECT * FROM ?? WHERE ?? = ?"; +var inserts = ['users', 'id', userId]; +sql = mysql.format(sql, inserts); + +connection.config.queryFormat = function (query, values) { + if (!values) return query; + return query.replace(/\:(\w+)/g, function (txt, key) { + if (values.hasOwnProperty(key)) { + return this.escape(values[key]); + } + return txt; + }.bind(this)); +}; + +connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" }); + +connection.query('INSERT INTO posts SET ?', { title: 'test' }, function (err, result) { + if (err) throw err; + + console.log(result.insertId); +}); + +connection.query('DELETE FROM posts WHERE title = "wrong"', function (err, result) { + if (err) throw err; + + console.log('deleted ' + result.affectedRows + ' rows'); +}); + +connection.query('UPDATE posts SET ...', function (err, result) { + if (err) throw err; + + console.log('changed ' + result.changedRows + ' rows'); +}); + +connection.connect(function (err) { + if (err) throw err; + console.log('connected as id ' + connection.threadId); +}); + +/// Pools + +var poolConfig = { + connectionLimit: 10, + host: 'example.org', + user: 'bob', + password: 'secret' +}; + +var pool = mysql.createPool(poolConfig); + +pool.query('SELECT 1 + 1 AS solution', function (err, rows, fields) { + if (err) throw err; + + console.log('The solution is: ', rows[0].solution); +}); + +pool = mysql.createPool({ + host: 'example.org', + user: 'bob', + password: 'secret' +}); + +pool.getConnection(function (err, connection) { + // connected! (unless `err` is set) +}); + +pool.on('connection', function (connection) { + connection.query('SET SESSION auto_increment_increment=1') +}); + +pool.getConnection(function (err, connection: mysql.IConnection) { + // Use the connection + connection.query('SELECT something FROM sometable', function (err, rows) { + // And done with the connection. + connection.release(); + + // Don't use the connection here, it has been returned to the pool. + }); +}); + +/// PoolClusters + +// create +var poolCluster = mysql.createPoolCluster(); + +poolCluster.add(poolConfig); // anonymous group +poolCluster.add('MASTER', poolConfig); +poolCluster.add('SLAVE1', poolConfig); +poolCluster.add('SLAVE2', poolConfig); + +// Target Group : ALL(anonymous, MASTER, SLAVE1-2), Selector : round-robin(default) +poolCluster.getConnection(function (err, connection) { }); + +// Target Group : MASTER, Selector : round-robin +poolCluster.getConnection('MASTER', function (err, connection) { }); + +// Target Group : SLAVE1-2, Selector : order +// If can't connect to SLAVE1, return SLAVE2. (remove SLAVE1 in the cluster) +poolCluster.on('remove', function (nodeId) { + console.log('REMOVED NODE : ' + nodeId); // nodeId = SLAVE1 +}); + +poolCluster.getConnection('SLAVE*', 'ORDER', function (err, connection) { }); + +// of namespace : of(pattern, selector) +poolCluster.of('*').getConnection(function (err, connection) { }); + +var pool = poolCluster.of('SLAVE*', 'RANDOM'); +pool.getConnection(function (err, connection) { }); +pool.getConnection(function (err, connection) { }); + +// destroy +poolCluster.end(); + +/// Queries + +var query = connection.query('SELECT * FROM posts'); +query + .on('error', function (err) { + // Handle error, an 'end' event will be emitted after this as well + }) + .on('fields', function (fields) { + // the field packets for the rows to follow + }) + .on('result', function (row) { + // Pausing the connnection is useful if your processing involves I/O + connection.pause(); + + var processRow = (row: any, cb: () => void) => { + cb(); + }; + + processRow(row, function () { + connection.resume(); + }); + }) + .on('end', function () { + // all rows have been received + }); + +connection.query('SELECT * FROM posts') + .stream({ highWaterMark: 5 }) + .pipe(() => { }); + +connection = mysql.createConnection({ multipleStatements: true }); + +connection.query('SELECT 1; SELECT 2', function (err, results) { + if (err) throw err; + + // `results` is an array with one element for every statement in the query: + console.log(results[0]); // [{1: 1}] + console.log(results[1]); // [{2: 2}] +}); + +var query = connection.query('SELECT 1; SELECT 2'); + +query + .on('fields', function (fields, index) { + // the fields for the result rows that follow + }) + .on('result', function (row, index) { + // index refers to the statement this result belongs to (starts at 0) + }); + +var options = { sql: '...', nestTables: true }; + +connection.query(options, function (err, results) { + /* results will be an array like this now: + [{ + table1: { + fieldA: '...', + fieldB: '...', + }, + table2: { + fieldA: '...', + fieldB: '...', + }, + }, ...] + */ +}); + +connection.beginTransaction(function (err) { + var title = 'title'; + + if (err) { throw err; } + connection.query('INSERT INTO posts SET title=?', title, function (err, result) { + if (err) { + connection.rollback(function () { + throw err; + }); + } + + var log = 'Post ' + result.insertId + ' added'; + + connection.query('INSERT INTO log SET data=?', log, function (err, result) { + if (err) { + connection.rollback(function () { + throw err; + }); + } + connection.commit(function (err) { + if (err) { + connection.rollback(function () { + throw err; + }); + } + console.log('success!'); + }); + }); + }); +}); + +// Kill query after 60s +connection.query({ sql: 'SELECT COUNT(*) AS count FROM big_table', timeout: 60000 }, function (err, rows) { + if (err && err.code === 'PROTOCOL_SEQUENCE_TIMEOUT') { + throw new Error('too long to count table rows!'); + } + + if (err) { + throw err; + } + + console.log(rows[0].count + ' rows'); +}); + +connection = mysql.createConnection({ + port: 84943, // WRONG PORT +}); + +connection.connect(function (err) { + console.log(err.code); // 'ECONNREFUSED' + console.log(err.fatal); // true +}); + +connection.query('SELECT 1', function (err) { + console.log(err.code); // 'ECONNREFUSED' + console.log(err.fatal); // true +}); + +connection.query('USE name_of_db_that_does_not_exist', function (err, rows) { + console.log(err.code); // 'ER_BAD_DB_ERROR' +}); + +connection.query('SELECT 1', function (err, rows) { + console.log(err); // null + console.log(rows.length); // 1 +}); + +connection.on('error', function (err) { + console.log(err.code); // 'ER_BAD_DB_ERROR' +}); + +connection.query('USE name_of_db_that_does_not_exist'); + +// I am Chuck Norris: +connection.on('error', function () { }); + +connection = mysql.createConnection({ typeCast: false }); + +var query = connection.query({ sql: '...', typeCast: false }, function (err, results) { + +}); + +connection.query({ + sql: '...', + typeCast: function (field, next) { + if (field.type == 'TINY' && field.length == 1) { + return (field.string() == '1'); // 1 = true, 0 = false + } + return next(); + } +}); + +connection = mysql.createConnection("mysql://localhost/test?flags=-FOUND_ROWS"); +connection = mysql.createConnection({ debug: true }); +connection = mysql.createConnection({ debug: ['ComQueryPacket', 'RowDataPacket'] }); diff --git a/mysql/mysql.d.ts b/mysql/mysql.d.ts new file mode 100644 index 000000000..3df338e47 --- /dev/null +++ b/mysql/mysql.d.ts @@ -0,0 +1,488 @@ +// Type definitions for node-mysql +// Project: https://github.com/felixge/node-mysql +// Definitions by: William Johnston +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module mysql { + export interface IMySql { + createConnection(connectionUri: string): IConnection; + createConnection(config: IConnectionConfig): IConnection; + + createPool(config: IPoolConfig): IPool; + + createPoolCluster(config?: IPoolClusterConfig): IPoolCluster; + + escape(value: any): string; + + format(sql: string): string; + format(sql: string, values: Array): string; + } + + export interface IConnectionStatic { + createQuery(sql: string): IQuery; + createQuery(sql: string, callback: (err: IError, ...args: any[]) => void): IQuery; + createQuery(sql: string, values: Array): IQuery; + createQuery(sql: string, values: Array, callback: (err: IError, ...args: any[]) => void): IQuery; + } + + export interface IConnection { + config: IConnectionConfig; + + threadId: number; + + beginTransaction(callback: (err: IError) => void): void; + + connect(): void; + connect(callback: (err: IError, ...args: any[]) => void): void; + connect(options: any, callback?: (err: IError, ...args: any[]) => void): void; + + commit(callback: (err: IError) => void): void; + + changeUser(options: IConnectionOptions): void; + changeUser(options: IConnectionOptions, callback: (err: IError) => void): void; + + query: IQueryFunction; + + end(): void; + end(options: any): void; + end(callback: (err: IError, ...args: any[]) => void): void; + end(options: any, callback: (err: IError, ...args: any[]) => void): void; + + destroy(): void; + + pause(): void; + + release(): void; + resume(): void; + + escape(value: any): string; + + escapeId(value: string): string; + escapeId(values: Array): string; + + format(sql: string): string; + format(sql: string, values: Array): string; + + on(ev: string, callback: (...args: any[]) => void): IConnection; + on(ev: 'error', callback: (err: IError) => void): IConnection; + + rollback(callback: () => void): void; + } + + export interface IPool { + config: IPoolConfig; + + getConnection(callback: (err: IError, connection: IConnection) => void): void; + + query: IQueryFunction; + + on(ev: string, callback: (...args: any[]) => void): IPool; + on(ev: 'connection', callback: (connection: IConnection) => void): IPool; + on(ev: 'error', callback: (err: IError) => void): IPool; + } + + export interface IPoolCluster { + config: IPoolClusterConfig; + + add(config: IPoolConfig): void; + add(group: string, config: IPoolConfig): void; + + end(): void; + + getConnection(callback: (err: IError, connection: IConnection) => void): void; + getConnection(group: string, callback: (err: IError, connection: IConnection) => void): void; + getConnection(group: string, selector: string, callback: (err: IError, connection: IConnection) => void): void; + + of(pattern: string): IPool; + of(pattern: string, selector: string): IPool; + + on(ev: string, callback: (...args: any[]) => void): IPoolCluster; + on(ev: 'remove', callback: (nodeId: number) => void): IPoolCluster; + on(ev: 'connection', callback: (connection: IConnection) => void): IPoolCluster; + on(ev: 'error', callback: (err: IError) => void): IPoolCluster; + } + + export interface IQuery { + /** + * The SQL for a constructed query + */ + sql: string; + + /** + * Emits a query packet to start the query + */ + start(): void; + + /** + * Determines the packet class to use given the first byte of the packet. + * + * @param firstByte The first byte of the packet + * @param parser The packet parser + */ + determinePacket(firstByte: number, parser: any): any; + + /** + * Creates a Readable stream with the given options + * + * @param options The options for the stream. + */ + stream(options: IStreamOptions): IQuery; + + /** + * Pipes a stream downstream, providing automatic pause/resume based on the + * options sent to the stream. + * + * @param options The options for the stream. + */ + pipe(callback: (...args: any[]) => void): IQuery; + + on(ev: string, callback: (...args: any[]) => void): IQuery; + on(ev: 'error', callback: (err: IError) => void): IQuery; + on(ev: 'fields', callback: (fields: any, index: number) => void): IQuery; + on(ev: 'result', callback: (row: any, index: number) => void): IQuery; + on(ev: 'end', callback: () => void): IQuery; + } + + export interface IQueryFunction { + (sql: string): IQuery; + (sql: string, callback: (err: IError, ...args: any[]) => void): IQuery; + (sql: string, values: Array): IQuery; + (sql: string, values: Array, callback: (err: IError, ...args: any[]) => void): IQuery; + (sql: string, values: any): IQuery; + (sql: string, values: any, callback: (err: IError, ...args: any[]) => void): IQuery; + (options: IQueryOptions): IQuery; + (options: IQueryOptions, callback: (err: IError, ...args: any[]) => void): IQuery; + (options: IQueryOptions, values: Array): IQuery; + (options: IQueryOptions, values: Array, callback: (err: IError, ...args: any[]) => void): IQuery; + (options: IQueryOptions, values: any): IQuery; + (options: IQueryOptions, values: any, callback: (err: IError, ...args: any[]) => void): IQuery; + } + + export interface IQueryOptions { + /** + * The SQL for the query + */ + sql: string; + + /** + * Every operation takes an optional inactivity timeout option. This allows you to specify appropriate timeouts for + * operations. It is important to note that these timeouts are not part of the MySQL protocol, and rather timeout + * operations through the client. This means that when a timeout is reached, the connection it occurred on will be + * destroyed and no further operations can be performed. + */ + timeout?: number; + + /** + * Either a boolean or string. If true, tables will be nested objects. If string (e.g. '_'), tables will be + * nested as tableName_fieldName + */ + nestTables?: any; + + /** + * Determines if column values should be converted to native JavaScript types. It is not recommended (and may go away / change in the future) + * to disable type casting, but you can currently do so on either the connection or query level. (Default: true) + * + * You can also specify a function (field: any, next: () => void) => {} to do the type casting yourself. + * + * WARNING: YOU MUST INVOKE the parser using one of these three field functions in your custom typeCast callback. They can only be called once. + * + * field.string() + * field.buffer() + * field.geometry() + * + * are aliases for + * + * parser.parseLengthCodedString() + * parser.parseLengthCodedBuffer() + * parser.parseGeometryValue() + * + * You can find which field function you need to use by looking at: RowDataPacket.prototype._typeCast + */ + typeCast?: any; + } + + export interface IStreamOptions { + /** + * Sets the max buffer size in objects of a stream + */ + highWaterMark?: number; + + /** + * The object mode of the stream (Default: true) + */ + objectMode?: any; + } + + export interface IConnectionOptions { + /** + * The MySQL user to authenticate as + */ + user?: string; + + /** + * The password of that MySQL user + */ + password?: string; + + /** + * Name of the database to use for this connection + */ + database?: string; + + /** + * The charset for the connection. This is called "collation" in the SQL-level of MySQL (like utf8_general_ci). + * If a SQL-level charset is specified (like utf8mb4) then the default collation for that charset is used. + * (Default: 'UTF8_GENERAL_CI') + */ + charset?: string; + } + + export interface IConnectionConfig extends IConnectionOptions { + /** + * The hostname of the database you are connecting to. (Default: localhost) + */ + host?: string; + + /** + * The port number to connect to. (Default: 3306) + */ + port?: number; + + /** + * The source IP address to use for TCP connection + */ + localAddress?: string; + + /** + * The path to a unix domain socket to connect to. When used host and port are ignored + */ + socketPath?: string; + + /** + * The timezone used to store local dates. (Default: 'local') + */ + timezone?: string; + + /** + * The milliseconds before a timeout occurs during the initial connection to the MySQL server. (Default: 10 seconds) + */ + connectTimeout?: number; + + /** + * Stringify objects instead of converting to values. (Default: 'false') + */ + stringifyObjects?: boolean; + + /** + * Allow connecting to MySQL instances that ask for the old (insecure) authentication method. (Default: false) + */ + insecureAuth?: boolean; + + /** + * Determines if column values should be converted to native JavaScript types. It is not recommended (and may go away / change in the future) + * to disable type casting, but you can currently do so on either the connection or query level. (Default: true) + * + * You can also specify a function (field: any, next: () => void) => {} to do the type casting yourself. + * + * WARNING: YOU MUST INVOKE the parser using one of these three field functions in your custom typeCast callback. They can only be called once. + * + * field.string() + * field.buffer() + * field.geometry() + * + * are aliases for + * + * parser.parseLengthCodedString() + * parser.parseLengthCodedBuffer() + * parser.parseGeometryValue() + * + * You can find which field function you need to use by looking at: RowDataPacket.prototype._typeCast + */ + typeCast?: any; + + /** + * A custom query format function + */ + queryFormat?: (query: string, values: any) => void; + + /** + * When dealing with big numbers (BIGINT and DECIMAL columns) in the database, you should enable this option + * (Default: false) + */ + supportBigNumbers?: boolean; + + /** + * Enabling both supportBigNumbers and bigNumberStrings forces big numbers (BIGINT and DECIMAL columns) to be + * always returned as JavaScript String objects (Default: false). Enabling supportBigNumbers but leaving + * bigNumberStrings disabled will return big numbers as String objects only when they cannot be accurately + * represented with [JavaScript Number objects] (http://ecma262-5.com/ELS5_HTML.htm#Section_8.5) + * (which happens when they exceed the [-2^53, +2^53] range), otherwise they will be returned as Number objects. + * This option is ignored if supportBigNumbers is disabled. + */ + bigNumberStrings?: boolean; + + /** + * Force date types (TIMESTAMP, DATETIME, DATE) to be returned as strings rather then inflated into JavaScript Date + * objects. (Default: false) + */ + dateStrings?: boolean; + + /** + * This will print all incoming and outgoing packets on stdout. + * You can also restrict debugging to packet types by passing an array of types (strings) to debug; + * + * (Default: false) + */ + debug?: any; + + /** + * Generates stack traces on Error to include call site of library entrance ("long stack traces"). Slight + * performance penalty for most calls. (Default: true) + */ + trace?: boolean; + + /** + * Allow multiple mysql statements per query. Be careful with this, it exposes you to SQL injection attacks. (Default: false) + */ + multipleStatements?: boolean; + + /** + * List of connection flags to use other than the default ones. It is also possible to blacklist default ones + */ + flags?: Array; + + /** + * object with ssl parameters or a string containing name of ssl profile + */ + ssl?: any; + } + + export interface IPoolConfig extends IConnectionConfig { + /** + * The milliseconds before a timeout occurs during the connection acquisition. This is slightly different from connectTimeout, + * because acquiring a pool connection does not always involve making a connection. (Default: 10 seconds) + */ + acquireTimeout?: number; + + /** + * Determines the pool's action when no connections are available and the limit has been reached. If true, the pool will queue + * the connection request and call it when one becomes available. If false, the pool will immediately call back with an error. + * (Default: true) + */ + waitForConnections?: boolean; + + /** + * The maximum number of connections to create at once. (Default: 10) + */ + connectionLimit?: number; + + /** + * The maximum number of connection requests the pool will queue before returning an error from getConnection. If set to 0, there + * is no limit to the number of queued connection requests. (Default: 0) + */ + queueLimit?: number; + } + + export interface IPoolClusterConfig { + /** + * If true, PoolCluster will attempt to reconnect when connection fails. (Default: true) + */ + canRetry?: boolean; + + /** + * If connection fails, node's errorCount increases. When errorCount is greater than removeNodeErrorCount, + * remove a node in the PoolCluster. (Default: 5) + */ + removeNodeErrorCount?: number; + + /** + * The default selector. (Default: RR) + * RR: Select one alternately. (Round-Robin) + * RANDOM: Select the node by random function. + * ORDER: Select the first node available unconditionally. + */ + defaultSelector?: string; + } + + export interface ISslCredentials { + /** + * A string or buffer holding the PFX or PKCS12 encoded private key, certificate and CA certificates + */ + pfx?: string; + + /** + * A string holding the PEM encoded private key + */ + key?: string; + + /** + * A string of passphrase for the private key or pfx + */ + passphrase?: string; + + /** + * A string holding the PEM encoded certificate + */ + cert?: string; + + /** + * Either a string or list of strings of PEM encoded CA certificates to trust. + */ + ca?: Array; + + /** + * Either a string or list of strings of PEM encoded CRLs (Certificate Revocation List) + */ + crl?: Array; + + /** + * A string describing the ciphers to use or exclude + */ + ciphers?: string; + } + + export interface IError extends Error { + /** + * Either a MySQL server error (e.g. 'ER_ACCESS_DENIED_ERROR'), + * a node.js error (e.g. 'ECONNREFUSED') or an internal error + * (e.g. 'PROTOCOL_CONNECTION_LOST'). + */ + code: string; + + /** + * The error number for the error code + */ + errno: number; + + /** + * The sql state marker + */ + sqlStateMarker?: string; + + /** + * The sql state + */ + sqlState?: string; + + /** + * The field count + */ + fieldCount?: number; + + /** + * The stack trace for the error + */ + stack?: string; + + /** + * Boolean, indicating if this error is terminal to the connection object. + */ + fatal: boolean; + } +} + +declare module 'mysql' { + var mysql: mysql.IMySql; + + export = mysql; +} From 4f562b1706cfdae66a74df298d0938151390f7a6 Mon Sep 17 00:00:00 2001 From: Will Johnston Date: Sun, 3 Aug 2014 16:44:58 -0500 Subject: [PATCH 242/324] Fixed mysql tests --- mysql/mysql-tests.ts | 6 +++--- mysql/mysql.d.ts | 1 - 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/mysql/mysql-tests.ts b/mysql/mysql-tests.ts index 81f1e7766..83fdeb06a 100644 --- a/mysql/mysql-tests.ts +++ b/mysql/mysql-tests.ts @@ -109,7 +109,7 @@ sql = mysql.format(sql, inserts); connection.config.queryFormat = function (query, values) { if (!values) return query; - return query.replace(/\:(\w+)/g, function (txt, key) { + return query.replace(/\:(\w+)/g, function (txt: string, key: string) { if (values.hasOwnProperty(key)) { return this.escape(values[key]); } @@ -173,7 +173,7 @@ pool.on('connection', function (connection) { connection.query('SET SESSION auto_increment_increment=1') }); -pool.getConnection(function (err, connection: mysql.IConnection) { +pool.getConnection(function (err, connection) { // Use the connection connection.query('SELECT something FROM sometable', function (err, rows) { // And done with the connection. @@ -368,7 +368,7 @@ var query = connection.query({ sql: '...', typeCast: false }, function (err, res connection.query({ sql: '...', - typeCast: function (field, next) { + typeCast: function (field: any, next: Function) { if (field.type == 'TINY' && field.length == 1) { return (field.string() == '1'); // 1 = true, 0 = false } diff --git a/mysql/mysql.d.ts b/mysql/mysql.d.ts index 3df338e47..479b05266 100644 --- a/mysql/mysql.d.ts +++ b/mysql/mysql.d.ts @@ -44,7 +44,6 @@ declare module mysql { query: IQueryFunction; end(): void; - end(options: any): void; end(callback: (err: IError, ...args: any[]) => void): void; end(options: any, callback: (err: IError, ...args: any[]) => void): void; From 11737fa5b1cceb4401f7c7435b0da4bdc1c334c6 Mon Sep 17 00:00:00 2001 From: Martin McWhorter Date: Mon, 10 Feb 2014 17:40:59 +0000 Subject: [PATCH 243/324] Update angular.d.ts The listener may take a single event argument. --- angularjs/angular.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index e447985fb..59a33e715 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -337,6 +337,7 @@ declare module ng { $new(isolate?: boolean): IScope; $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; + $on(name: string, listener: (event: IAngularEvent, eventArg: any) => any): Function; $watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function; $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; From 783404bd8a37e11559f499ce16465d25d5c88f2f Mon Sep 17 00:00:00 2001 From: Martin McWhorter Date: Tue, 25 Feb 2014 17:32:17 +0000 Subject: [PATCH 244/324] Update angular-ui-router.d.ts --- angular-ui/angular-ui-router.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/angular-ui/angular-ui-router.d.ts b/angular-ui/angular-ui-router.d.ts index 081d35723..889325aa4 100644 --- a/angular-ui/angular-ui-router.d.ts +++ b/angular-ui/angular-ui-router.d.ts @@ -85,6 +85,7 @@ declare module ng.ui { get(state: string): IState; get(): IState[]; current: IState; + $current: IState; params: IStateParamsService; reload(): void; } From 18ef03e31dfc89e937de12d43206f288c72d98b2 Mon Sep 17 00:00:00 2001 From: Martin McWhorter Date: Tue, 25 Feb 2014 17:37:58 +0000 Subject: [PATCH 245/324] Revert "Update angular.d.ts" This reverts commit 0690841c6b5d33bfcbf91be3b02f13e63c990ed1. --- angularjs/angular.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 59a33e715..e447985fb 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -337,7 +337,6 @@ declare module ng { $new(isolate?: boolean): IScope; $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; - $on(name: string, listener: (event: IAngularEvent, eventArg: any) => any): Function; $watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function; $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; From 9bdeb5e6c85654a38684cf2a4914d05706da64ce Mon Sep 17 00:00:00 2001 From: martinmcwhorter Date: Mon, 4 Aug 2014 01:01:21 +0100 Subject: [PATCH 246/324] Revert 783404b..18ef03e This rolls back to commit 783404bd8a37e11559f499ce16465d25d5c88f2f. --- angularjs/angular.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index e447985fb..59a33e715 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -337,6 +337,7 @@ declare module ng { $new(isolate?: boolean): IScope; $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; + $on(name: string, listener: (event: IAngularEvent, eventArg: any) => any): Function; $watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function; $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; From 8d1e03ff7791b3f4fc79846ba8995110d917a174 Mon Sep 17 00:00:00 2001 From: martinmcwhorter Date: Mon, 4 Aug 2014 01:01:40 +0100 Subject: [PATCH 247/324] Revert aec2fa9..9bdeb5e This rolls back to commit aec2fa9e392a883dfa4467ba12a6934f24d50a9e. --- angular-ui/angular-ui-router.d.ts | 1 - angularjs/angular.d.ts | 1 - 2 files changed, 2 deletions(-) diff --git a/angular-ui/angular-ui-router.d.ts b/angular-ui/angular-ui-router.d.ts index 889325aa4..081d35723 100644 --- a/angular-ui/angular-ui-router.d.ts +++ b/angular-ui/angular-ui-router.d.ts @@ -85,7 +85,6 @@ declare module ng.ui { get(state: string): IState; get(): IState[]; current: IState; - $current: IState; params: IStateParamsService; reload(): void; } diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 59a33e715..e447985fb 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -337,7 +337,6 @@ declare module ng { $new(isolate?: boolean): IScope; $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; - $on(name: string, listener: (event: IAngularEvent, eventArg: any) => any): Function; $watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function; $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; From d5ddb0544b0455cf20702f4af36d6c62e400f74e Mon Sep 17 00:00:00 2001 From: martinmcwhorter Date: Mon, 4 Aug 2014 01:02:13 +0100 Subject: [PATCH 248/324] Revert "Revert aec2fa9..9bdeb5e" This reverts commit 8d1e03ff7791b3f4fc79846ba8995110d917a174. --- angular-ui/angular-ui-router.d.ts | 1 + angularjs/angular.d.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/angular-ui/angular-ui-router.d.ts b/angular-ui/angular-ui-router.d.ts index 081d35723..889325aa4 100644 --- a/angular-ui/angular-ui-router.d.ts +++ b/angular-ui/angular-ui-router.d.ts @@ -85,6 +85,7 @@ declare module ng.ui { get(state: string): IState; get(): IState[]; current: IState; + $current: IState; params: IStateParamsService; reload(): void; } diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index e447985fb..59a33e715 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -337,6 +337,7 @@ declare module ng { $new(isolate?: boolean): IScope; $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; + $on(name: string, listener: (event: IAngularEvent, eventArg: any) => any): Function; $watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function; $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; From d17f3145a523e76a876e6d864c708f2d8cfb4dff Mon Sep 17 00:00:00 2001 From: martinmcwhorter Date: Mon, 4 Aug 2014 01:03:42 +0100 Subject: [PATCH 249/324] Revert "Revert "Revert aec2fa9..9bdeb5e"" This reverts commit d5ddb0544b0455cf20702f4af36d6c62e400f74e. --- angular-ui/angular-ui-router.d.ts | 1 - angularjs/angular.d.ts | 1 - 2 files changed, 2 deletions(-) diff --git a/angular-ui/angular-ui-router.d.ts b/angular-ui/angular-ui-router.d.ts index 889325aa4..081d35723 100644 --- a/angular-ui/angular-ui-router.d.ts +++ b/angular-ui/angular-ui-router.d.ts @@ -85,7 +85,6 @@ declare module ng.ui { get(state: string): IState; get(): IState[]; current: IState; - $current: IState; params: IStateParamsService; reload(): void; } diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 59a33e715..e447985fb 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -337,7 +337,6 @@ declare module ng { $new(isolate?: boolean): IScope; $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; - $on(name: string, listener: (event: IAngularEvent, eventArg: any) => any): Function; $watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function; $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; From 24df639f25cd60e06b47cef6887b151ee6849749 Mon Sep 17 00:00:00 2001 From: martinmcwhorter Date: Mon, 4 Aug 2014 01:21:54 +0100 Subject: [PATCH 250/324] Add grunt.log.warn method --- gruntjs/gruntjs-tests.ts | 43 ++++++++++++++++++++++++++++++++++++++++ gruntjs/gruntjs.d.ts | 5 +++++ 2 files changed, 48 insertions(+) diff --git a/gruntjs/gruntjs-tests.ts b/gruntjs/gruntjs-tests.ts index 853cac370..fe0f7ace9 100644 --- a/gruntjs/gruntjs-tests.ts +++ b/gruntjs/gruntjs-tests.ts @@ -73,3 +73,46 @@ exports = (grunt: IGrunt) => { fileMaps[0].src.length; fileMaps[0].dest; }; + +// Official grunt task template from +// https://github.com/gruntjs/grunt-init-gruntplugin/blob/master/root/tasks/name.js +exports.exports = function(grunt: IGrunt) { + + // Please see the Grunt documentation for more information regarding task + // creation: http://gruntjs.com/creating-tasks + + grunt.registerMultiTask('taskName', 'task description', function() { + // Merge task-specific and/or target-specific options with these defaults. + var options = this.options({ + punctuation: '.', + separator: ', ' + }); + + // Iterate over all specified file groups. + this.files.forEach(function(f) { + // Concat specified files. + var src = f.src.filter(function(filepath) { + // Warn on and remove invalid source files (if nonull was set). + if (!grunt.file.exists(filepath)) { + grunt.log.warn('Source file "' + filepath + '" not found.'); + return false; + } else { + return true; + } + }).map(function(filepath) { + // Read file source. + return grunt.file.read(filepath); + }).join(grunt.util.normalizelf(options.separator)); + + // Handle options. + src += options.punctuation; + + // Write the destination file. + grunt.file.write(f.dest, src); + + // Print a success message. + grunt.log.writeln('File "' + f.dest + '" created.'); + }); + }); + +}; \ No newline at end of file diff --git a/gruntjs/gruntjs.d.ts b/gruntjs/gruntjs.d.ts index 86923c56e..8efa08ef6 100644 --- a/gruntjs/gruntjs.d.ts +++ b/gruntjs/gruntjs.d.ts @@ -690,6 +690,11 @@ declare module grunt { * Log a list of obj properties (good for debugging flags). */ writeflags(obj: any): T + + /** + * Log an warning with grunt.log.warn + */ + warn(msg: string): T } /** From 10c19f9b75e97ba6706da7aaea938ed411a5dcd9 Mon Sep 17 00:00:00 2001 From: martinmcwhorter Date: Mon, 4 Aug 2014 01:26:17 +0100 Subject: [PATCH 251/324] Revert "Merge branch 'master' of https://github.com/martinmcwhorter/DefinitelyTyped" This reverts commit 00124520f75bdc8151bc2c1427dd8dd5a2404a1b, reversing changes made to d17f3145a523e76a876e6d864c708f2d8cfb4dff. --- angular-ui/angular-ui-router.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/angular-ui/angular-ui-router.d.ts b/angular-ui/angular-ui-router.d.ts index 889325aa4..081d35723 100644 --- a/angular-ui/angular-ui-router.d.ts +++ b/angular-ui/angular-ui-router.d.ts @@ -85,7 +85,6 @@ declare module ng.ui { get(state: string): IState; get(): IState[]; current: IState; - $current: IState; params: IStateParamsService; reload(): void; } From 78289250ff3fdfd485eb11d55d133283797b906e Mon Sep 17 00:00:00 2001 From: martinmcwhorter Date: Mon, 4 Aug 2014 01:28:26 +0100 Subject: [PATCH 252/324] Revert old changes --- gruntjs/gruntjs-tests.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/gruntjs/gruntjs-tests.ts b/gruntjs/gruntjs-tests.ts index fe0f7ace9..6807cd96e 100644 --- a/gruntjs/gruntjs-tests.ts +++ b/gruntjs/gruntjs-tests.ts @@ -75,6 +75,7 @@ exports = (grunt: IGrunt) => { }; // Official grunt task template from +// Official grunt task template from // https://github.com/gruntjs/grunt-init-gruntplugin/blob/master/root/tasks/name.js exports.exports = function(grunt: IGrunt) { From f2d7f68db344ae9b7490523e22caf525f093306c Mon Sep 17 00:00:00 2001 From: martinmcwhorter Date: Mon, 4 Aug 2014 01:29:07 +0100 Subject: [PATCH 253/324] revert bad changes --- gruntjs/gruntjs-tests.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/gruntjs/gruntjs-tests.ts b/gruntjs/gruntjs-tests.ts index 6807cd96e..5fa560d86 100644 --- a/gruntjs/gruntjs-tests.ts +++ b/gruntjs/gruntjs-tests.ts @@ -74,7 +74,6 @@ exports = (grunt: IGrunt) => { fileMaps[0].dest; }; -// Official grunt task template from // Official grunt task template from // https://github.com/gruntjs/grunt-init-gruntplugin/blob/master/root/tasks/name.js exports.exports = function(grunt: IGrunt) { From b32f41a55cbd9a40a0d62c1b6e57fed486df43fa Mon Sep 17 00:00:00 2001 From: Saftpresse99 Date: Mon, 4 Aug 2014 09:58:08 +0200 Subject: [PATCH 254/324] Update angular-translate.d.ts Improvements ITranslateService --- angular-translate/angular-translate.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts index 313ef8635..4b8da8449 100644 --- a/angular-translate/angular-translate.d.ts +++ b/angular-translate/angular-translate.d.ts @@ -33,13 +33,14 @@ declare module ng.translate { } interface ITranslateService { - (key: string, ...params: string[]): ng.IPromise; + (translationId: string, interpolateParams?: any, interpolationId?: string): ng.IPromise; + (translationId: string[], interpolateParams?: any, interpolationId?: string): ng.IPromise<{ [key: string]: string }>; cloakClassName(): string; cloakClassName(name: string): ITranslateProvider; fallbackLanguage(langKey?: string): string; fallbackLanguage(langKey?: string[]): string; instant(translationId: string, interpolateParams?: any, interpolationId?: string): string; - instant(translationId: string[], interpolateParams?: any, interpolationId?: string): string; + instant(translationId: string[], interpolateParams?: any, interpolationId?: string): { [key: string]: string }; isPostCompilingEnabled(): boolean; preferredLanguage(): string; proposedLanguage(): string; From 86ac984bb0e8019a2c0d583a07a5cbb6f0f18886 Mon Sep 17 00:00:00 2001 From: San Chen Date: Mon, 4 Aug 2014 16:16:54 +0800 Subject: [PATCH 255/324] needle definitions added --- CONTRIBUTORS.md | 1 + needle/needle-tests.ts | 14 ++++++++++++++ needle/needle.d.ts | 16 ++++++++++++++++ 3 files changed, 31 insertions(+) create mode 100644 needle/needle-tests.ts create mode 100644 needle/needle.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index aafef048d..2bba0b895 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -249,6 +249,7 @@ All definitions files include a header with the author and editors, so at some p * [msgpack.js](https://github.com/uupaa/msgpack.js) (by [Shinya Mochizuki](https://github.com/enrapt-mochizuki)) * [Mustache.js](https://github.com/janl/mustache.js) (by [Boris Yankov](https://github.com/borisyankov)) * [nconf](https://github.com/flatiron/nconf) (by [Jeff Goddard](https://github.com/jedigo)) +* [needle](https://github.com/tomas/needle) (by [San Chen](https://github.com/bigsan)) * [noble](https://github.com/sandeepmistry/noble) (by [Seon-Wook Park](https://github.com/swook)) * [nock](https://github.com/pgte/nock) (by [bonnici](https://github.com/bonnici)) * [Node.js](http://nodejs.org/) (from TypeScript samples) diff --git a/needle/needle-tests.ts b/needle/needle-tests.ts new file mode 100644 index 000000000..70c88933c --- /dev/null +++ b/needle/needle-tests.ts @@ -0,0 +1,14 @@ +/// + +import needle = require("needle"); + +var url = ""; +var options = {}; +var callback = (err, resp) => {}; + +needle.head(url, options, callback); +needle.get(url, options, callback); +needle.post(url, data, options, callback); +needle.put(url, data, options, callback); +needle.delete(url, data, options, callback); +needle.request(method, url, data, options, callback); diff --git a/needle/needle.d.ts b/needle/needle.d.ts new file mode 100644 index 000000000..732f5a059 --- /dev/null +++ b/needle/needle.d.ts @@ -0,0 +1,16 @@ +// Type definitions for needle 0.7.8 +// Project: https://github.com/tomas/needle +// Definitions by: San Chen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface INeedle { + head(url: string): IReadableStream; + head(url: string, callback?: Function): IReadableStream; + head(url: string, options?: any, callback?: Function): IReadableStream; + +} + +declare module "needle" { + var needle: INeedle; + export = needle; +} From 56bb95a53205c4d38436436109bd12255394c662 Mon Sep 17 00:00:00 2001 From: Dick van den Brink Date: Mon, 4 Aug 2014 10:48:11 +0200 Subject: [PATCH 256/324] MomentJs: Fixed some return values and made parameters optional --- moment/moment.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/moment/moment.d.ts b/moment/moment.d.ts index f14c7d4be..344885f1b 100644 --- a/moment/moment.d.ts +++ b/moment/moment.d.ts @@ -1,6 +1,6 @@ // Type definitions for Moment.js 2.5.0 // Project: https://github.com/timrwood/moment -// Definitions by: Michael Lakerveld , Aaron King , Hiroki Horiuchi +// Definitions by: Michael Lakerveld , Aaron King , Hiroki Horiuchi , Dick van den Brink // Definitions: https://github.com/borisyankov/DefinitelyTyped interface MomentInput { @@ -203,9 +203,9 @@ interface Moment { isSame(b: Date, granularity: string): boolean; isSame(b: number[], granularity: string): boolean; - lang(language: string): void; - lang(reset: boolean): void; - lang(): string; + lang(language: string): Moment; + lang(reset: boolean): Moment; + lang(): MomentLanguage; max(date: Date): Moment; max(date: number): Moment; @@ -313,8 +313,8 @@ interface MomentStatic { isMoment(): boolean; isMoment(m: any): boolean; - lang(language: string): any; - lang(language: string, definition: MomentLanguage): any; + lang(language?: string): string; + lang(language?: string, definition?: MomentLanguage): string; longDateFormat: any; relativeTime: any; meridiem: (hour: number, minute: number, isLowercase: boolean) => string; From 5c2007a539bb4f244b6ce61899c4bedd9b58bde8 Mon Sep 17 00:00:00 2001 From: Antoine Pultier Date: Mon, 4 Aug 2014 11:20:14 +0200 Subject: [PATCH 257/324] TypeScript validity --- leaflet/leaflet.d.ts | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 7f7b8dc9a..bc4e7be90 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -1244,7 +1244,7 @@ declare module L { enabled(): boolean; } - export class Handler extends Class implements IHandler { + export class Handler extends Class { initialize(map: Map): void; } } @@ -1269,10 +1269,8 @@ declare module L { } declare module L { - export var Mixin: any; - - module Mixin { - export interface LeafletMixinEvents implements IEventPowered { + export module Mixin { + export interface LeafletMixinEvents extends IEventPowered { } export var Events: LeafletMixinEvents; @@ -2418,8 +2416,9 @@ declare module L { * * Default value: true. */ - scrollWheelZoom?: boolean; scrollWheelZoom?: string; + //scrollWheelZoom?: boolean; + //scrollWheelZoom?: string; /** * Whether the map can be zoomed in by double clicking on it and zoomed out @@ -2429,8 +2428,9 @@ declare module L { * * Default value: true. */ - doubleClickZoom?: boolean; doubleClickZoom?: string; + //doubleClickZoom?: boolean; + //doubleClickZoom?: string; /** * Whether the map can be zoomed to a rectangular area specified by dragging @@ -3428,12 +3428,9 @@ declare module L { /** * Returns the content of the popup. */ - getContent(): string; - - /** - * Returns the content of the popup. - */ - getContent(): HTMLElement; + getContent(): any; + //getContent(): string; + //getContent(): HTMLElement; //////////// //////////// From bc1961484a80a021716600123785cedfb1376cc9 Mon Sep 17 00:00:00 2001 From: Antoine Pultier Date: Mon, 4 Aug 2014 13:08:49 +0200 Subject: [PATCH 258/324] [leaflet] small adjustments --- leaflet/leaflet.d.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index bc4e7be90..3332f9000 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -2183,7 +2183,7 @@ declare module L { /** * Closes the popup previously opened with openPopup (or the given one). */ - closePopup(): Map; + closePopup(popup?: Popup): Map; /** * Adds the given control to the map. @@ -2416,7 +2416,7 @@ declare module L { * * Default value: true. */ - scrollWheelZoom?: string; + scrollWheelZoom?: any; //scrollWheelZoom?: boolean; //scrollWheelZoom?: string; @@ -2739,7 +2739,12 @@ declare module L { /** * Returns a GeoJSON representation of the marker (GeoJSON Point Feature). */ - toGeoJSON(popup: Popup, options?: PopupOptions): any; + toGeoJSON(): any; + + /** + * Marker dragging handler (by both mouse and touch). + */ + dragging: IHandler; //////////// //////////// @@ -3428,9 +3433,8 @@ declare module L { /** * Returns the content of the popup. */ - getContent(): any; + getContent(): HTMLElement; //getContent(): string; - //getContent(): HTMLElement; //////////// //////////// From 1cbee878f7753f66ee562789bb5acc9a063b86c2 Mon Sep 17 00:00:00 2001 From: Antoine Pultier Date: Mon, 4 Aug 2014 13:09:19 +0200 Subject: [PATCH 259/324] [leaflet] Brand new test file --- leaflet/leaflet-tests.ts | 301 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 301 insertions(+) create mode 100644 leaflet/leaflet-tests.ts diff --git a/leaflet/leaflet-tests.ts b/leaflet/leaflet-tests.ts new file mode 100644 index 000000000..c07a651d8 --- /dev/null +++ b/leaflet/leaflet-tests.ts @@ -0,0 +1,301 @@ +/// + +// initialize the map on the "map" div with a given center and zoom + +var div = document.getElementById('map'); + +var map : L.Map = L.map(div, { + center: L.latLng([51.505, -0.09]), + zoom: 13, + minZoom: 3, + maxZoom: 8, + maxBounds: L.latLngBounds([L.latLng(-60, -60), L.latLng(60, 60)]), + dragging: true, + touchZoom: true, + scrollWheelZoom: true, + boxZoom: true, + tap: true, + + tapTolerance: 30, + trackResize: true, + worldCopyJump: false, + closePopupOnClick: true, + bounceAtZoomLimits: true, + + keyboard: true, + keyboardPanOffset: 80, + keyboardZoomOffset: 1, + + inertia: true, + inertiaDeceleration: 3000, + inertiaMaxSpeed: 1500, + inertiaThreshold: 32, + + zoomControl: true, + attributionControl: true, + + fadeAnimation: true, + zoomAnimation: true, + zoomAnimationThreshold: 4, + markerZoomAnimation: true + +}); + +map.dragging.enable(); +map.touchZoom.enable(); +map.scrollWheelZoom.enable(); +map.doubleClickZoom.enable(); +map.boxZoom.enable(); +map.tap.enable(); + +map.setView(new L.LatLng(42, 51)); +map.setView(L.latLng(42, 51)); + +map.setView(L.latLng(42, 51), 12); +map.setView(L.latLng(42, 51), 12, { + reset: true, + pan: { + animate: true, + duration: 0.25, + easeLinearity: 0.25, + noMoveStart: false + }, + zoom: { + animate: true + } +}); + +map.setZoom(50); +map.setZoom(50, {}); + +map.zoomIn(); +map.zoomOut(); + +map.zoomIn(2); +map.zoomOut(2); + +map.zoomIn(2, { animate: true }); +map.zoomOut(2, { animate: true }); + +map.setZoomAround(L.latLng(42, 51), 8, { animate: false }); + +map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20))); +map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20)), { + paddingTopLeft: L.point(20, 20), + paddingBottomRight: L.point(20, 20), + padding: L.point(0, 0), + maxZoom: null +}); + +map.fitWorld(); + +map.fitWorld({ + animate: false +}); + +map.panTo(L.latLng(42, 42)); +map.panTo(L.latLng(42, 42), { + animate: true +}); + +map.invalidateSize(true); +map.invalidateSize({ reset: true }); + +map.setMaxBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20))); + +map.locate(); +map.locate({ + watch: false, + setView: false, + maxZoom: 18, + timeout: 10000, + maximumAge: 0, + enableHighAccuracy: false +}); + +map.stopLocate(); + +map.remove(); + +var center : L.LatLng = map.getCenter(); +var zoom : number = map.getZoom(); +var minZoom: number = map.getMinZoom(); +var maxZoom: number = map.getMaxZoom(); +var bounds: L.LatLngBounds = map.getBounds(); +var boundsZoom: number = map.getBoundsZoom(bounds, true); +var size: L.Point = map.getSize(); +var pixelBounds: L.Bounds = map.getPixelBounds(); +var pixelOrigin: L.Point = map.getPixelOrigin(); + +var layer = L.tileLayer("http://{s}.example.net/{x}/{y}/{z}.png"); + +map.addLayer(layer); +map.addLayer(layer, false); + +map.removeLayer(layer); +map.hasLayer(layer); + +map.openPopup("canard", L.latLng(42, 51)); + +var popup = L.popup({ + autoPan: true +}); + +map.openPopup(popup); +map.closePopup(popup); +map.closePopup(); + +map.addControl(L.control.attribution({position: 'bottomright'})); +map.removeControl(L.control.attribution({ position: 'bottomright' })); + +map.latLngToLayerPoint(map.layerPointToLatLng(L.point(0, 0))); +map.latLngToContainerPoint(map.containerPointToLatLng(L.point(0, 0))); +map.containerPointToLayerPoint(L.point(0, 0)); +map.layerPointToContainerPoint(L.point(0, 0)); + +map.project(map.unproject(L.point(10, 20))); +map.project(map.unproject(L.point(10, 20), 12), 12); + +var mouseEvent: L.LeafletMouseEvent; +map.mouseEventToContainerPoint(mouseEvent); +map.mouseEventToLayerPoint(mouseEvent); +map.mouseEventToLatLng(mouseEvent); + +map.getContainer().classList.add('roger'); +map.getPanes().mapPane.classList.add('roger'); +map.getPanes().markerPane.classList.add('roger'); +map.getPanes().objectsPane.classList.add('roger'); +map.getPanes().overlayPane.classList.add('roger'); +map.getPanes().popupPane.classList.add('roger'); +map.getPanes().shadowPane.classList.add('roger'); +map.getPanes().tilePane.classList.add('roger'); + +map.whenReady((m: L.Map) => { + m.zoomOut(); +}); + +map.on('click', () => { + map.zoomOut(); +}); + +map.off('dblclick', L.Util.falseFn); + +map.once('contextmenu', (e: L.LeafletMouseEvent) => { + map.openPopup('contextmenu', e.latlng); +}); + +var marker = L.marker(L.latLng(42, 51), { + icon: L.icon({ + iconURl: 'roger.png', + iconRetinaUrl: 'roger-retina.png', + iconSize: L.point(40, 40), + iconAnchor: L.point(20, 0), + shadowUrl: 'roger-shadow.png', + shadowRetinaUrl: 'roger-shadow-retina.png', + shadowSize: L.point(44, 44), + shadowAnchor: L.point(22, 0), + popupAnchor: L.point(0, 0), + className: 'roger-icon' + }), + clickable: true, + draggable: false, + keyboard: true, + title: 'this is an icon', + alt: '', + zIndexOffset: 0, + opacity: 1.0, + riseOnHover: false, + riseOffset: 250 +}); + +marker.addTo(map); + +marker.on('click', (e: L.LeafletMouseEvent) => { + map.setView(e.latlng); +}); + +marker.once('mouseover', () => { + marker.openPopup(); +}) + +marker.setLatLng(marker.getLatLng()); + +marker.setIcon(L.icon({})); + +marker.setZIndexOffset(30); +marker.setOpacity(0.8); + +marker.bindPopup(popup); +marker.unbindPopup(); +marker.bindPopup('hello', { + closeOnClick: true +}); + +marker.openPopup(); +marker.closePopup(); +marker.togglePopup(); +marker.togglePopup(); +marker.setPopupContent('hello 3') +marker.getPopup().setContent('hello 2'); +marker.update(); + +marker.toGeoJSON(); + +marker.dragging.enable(); + +popup = L.popup({ + maxWidth: 300, + minWidth: 50, + maxHeight: null, + autoPan: true, + keepInView: false, + closeButton: true, + offset: L.point(0, 6), + autoPanPaddingTopLeft: null, + autoPanPaddingBottomRight: L.point(20, 20), + autoPanPadding: L.point(5, 5), + zoomAnimation: true, + closeOnClick: null, + className: 'roger' +}); + +popup.setLatLng(L.latLng(12, 54)).setContent('this is nice popup').openOn(map); + +popup.update(); + +var tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}', { + foo: 'bar', + minZoom: 0, + maxZoom: 18, + maxNativeZoom: 17, + tileSize: 256, + subdomains: ['a','b','c'], + errorTileUrl: '', + attribution: '', + tms: false, + continuousWorld: false, + noWrap: false, + zoomOffset: 0, + zoomReverse: false, + opacity: 1.0, + zIndex: null, + unloadInvisibleTiles: false, + updateWhenIdle: false, + detectRetina: true, + reuseTiles: true, + bounds: null +}); + +tileLayer.on('loading', L.Util.falseFn) + .off('loading', L.Util.falseFn) + .once('tileload', L.Util.falseFn); + +tileLayer.addTo(map); + +tileLayer.bringToBack() + .bringToFront() + .setOpacity(0.7) + .setZIndex(9) + .redraw() + .setUrl('http://perdu.com') + .getContainer(); From df1080e63a50158f3a315b9e9d938e27f45e2fb3 Mon Sep 17 00:00:00 2001 From: James Roland Cabresos Date: Mon, 4 Aug 2014 20:54:42 +0800 Subject: [PATCH 260/324] Added htmlparser2 definitions --- htmlparser2/htmlparser2.d.ts | 89 +++++++++++++++++++++++++++++++++ htmlparser2/htmlparser2tests.ts | 24 +++++++++ 2 files changed, 113 insertions(+) create mode 100644 htmlparser2/htmlparser2.d.ts create mode 100644 htmlparser2/htmlparser2tests.ts diff --git a/htmlparser2/htmlparser2.d.ts b/htmlparser2/htmlparser2.d.ts new file mode 100644 index 000000000..77fb0b983 --- /dev/null +++ b/htmlparser2/htmlparser2.d.ts @@ -0,0 +1,89 @@ +// Type definitions for htmlparser2 v3.7.x +// Project: https://github.com/fb55/htmlparser2/ +// Definitions by: James Roland Cabresos +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +declare module "htmlparser2" { + + export interface Handler { + onopentag?:(name:string, attribs:{[type:string]: string}) => void; + onopentagname?:(name:string) => void; + onattribute?:(name:string, value:string) => void; + ontext?:(text:string) => void; + onclosetag?: (text:string) => void; + onprocessinginstruction?:(name:string, data:string) => void; + oncomment?:(data:string) => void; + oncommentend?:() => void; + oncdatastart?:() => void; + oncdataend?:() => void; + onerror?:(error:Error) => void; + onreset?:() => void; + onend?:() => void; + } + + export interface Options { + + /*** + * Indicates whether special tags ("); +parser.end(); \ No newline at end of file From afc1fc3ed4679698884fae628d1b5214af683963 Mon Sep 17 00:00:00 2001 From: James Roland Cabresos Date: Mon, 4 Aug 2014 20:59:50 +0800 Subject: [PATCH 261/324] Added htmlparser2, morgan, and passport-facebook contributor --- CONTRIBUTORS.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index af326634b..216b74568 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -124,6 +124,7 @@ All definitions files include a header with the author and editors, so at some p * [highlight.js](https://github.com/isagalaev/highlight.js) (by [Niklas Mollenhauer](https://github.com/nikeee)) * [History.js](https://github.com/browserstate/history.js) (by [Boris Yankov](https://github.com/borisyankov)) * [Html2Canvas.js](https://github.com/niklasvh/html2canvas/) (by [Richard Hepburn](https://github.com/rwhepburn)) +* [htmlparser2](https://github.com/fb55/htmlparser2/) (by [James Roland Cabresos](https://github.com/staticfunction)) * [Humane.js](http://wavded.github.com/humane-js/) (by [John Vrbanac](https://github.com/jmvrbanac)) * [i18next](http://i18next.com/) (by [Maarten Docter](https://github.com/mdocter)) * [iCheck](http://damirfoy.com/iCheck/) (by [Dániel Tar](https://github.com/qcz)) @@ -244,6 +245,7 @@ All definitions files include a header with the author and editors, so at some p * [Moment.js](https://github.com/timrwood/moment) (by [Michael Lakerveld](https://github.com/Lakerfield)) * [MongoDB](http://mongodb.github.io/node-mongodb-native/) (from TypeScript samples, updated by [Niklas Mollenhauer](https://github.com/nikeee)) * [mongoose](http://mongoosejs.com/) (by [Hiroki Horiuchi](https://github.com/horiuchi/)) +* [morgan](hhttps://github.com/expressjs/morgan) (by [James Roland Cabresos](https://github.com/staticfunction/)) * [Mousetrap](http://craig.is/killing/mice) (by [Dániel Tar](https://github.com/qcz)) * [msgpack.js](https://github.com/uupaa/msgpack.js) (by [Shinya Mochizuki](https://github.com/enrapt-mochizuki)) * [Mustache.js](https://github.com/janl/mustache.js) (by [Boris Yankov](https://github.com/borisyankov)) @@ -267,6 +269,7 @@ All definitions files include a header with the author and editors, so at some p * [OpenLayers](https://github.com/openlayers/openlayers) (by [Ilya Bolkhovsky](https://github.com/bolhovsky/)) * [Optimist](https://github.com/substack/node-optimist) (by [Carlos Ballesteros Velasco](https://github.com/soywiz)) * [Passport](http://passportjs.org/) (by [Hiroki Horiuchi](https://github.com/horiuchi/)) +* [passport-facebook](https://github.com/jaredhanson/passport-facebook) (by [James Roland Cabresos](https://github.com/staticfunction/)) * [passport-strategy](https://github.com/jaredhanson/passport-strategy) (by [Lior Mualem](https://github.com/liorm)) * [pathwatcher](http://atom.github.io/node-pathwatcher/) (by [vvakame](https://github.com/vvakame)) * [Parallel.js](https://github.com/adambom/parallel.js) (by [Josh Baldwin](https://github.com/jbaldwin)) From 9a0a71177653bda672905ba6605aa319877dcf8e Mon Sep 17 00:00:00 2001 From: James Roland Cabresos Date: Mon, 4 Aug 2014 21:02:17 +0800 Subject: [PATCH 262/324] fix a typo --- CONTRIBUTORS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 216b74568..8098540ed 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -245,7 +245,7 @@ All definitions files include a header with the author and editors, so at some p * [Moment.js](https://github.com/timrwood/moment) (by [Michael Lakerveld](https://github.com/Lakerfield)) * [MongoDB](http://mongodb.github.io/node-mongodb-native/) (from TypeScript samples, updated by [Niklas Mollenhauer](https://github.com/nikeee)) * [mongoose](http://mongoosejs.com/) (by [Hiroki Horiuchi](https://github.com/horiuchi/)) -* [morgan](hhttps://github.com/expressjs/morgan) (by [James Roland Cabresos](https://github.com/staticfunction/)) +* [morgan](https://github.com/expressjs/morgan/) (by [James Roland Cabresos](https://github.com/staticfunction/)) * [Mousetrap](http://craig.is/killing/mice) (by [Dániel Tar](https://github.com/qcz)) * [msgpack.js](https://github.com/uupaa/msgpack.js) (by [Shinya Mochizuki](https://github.com/enrapt-mochizuki)) * [Mustache.js](https://github.com/janl/mustache.js) (by [Boris Yankov](https://github.com/borisyankov)) From 913218129823ae1659d5d539f5df61d9d277add0 Mon Sep 17 00:00:00 2001 From: martinmcwhorter Date: Mon, 4 Aug 2014 15:38:01 +0100 Subject: [PATCH 263/324] added missing type hints --- gruntjs/gruntjs-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gruntjs/gruntjs-tests.ts b/gruntjs/gruntjs-tests.ts index 5fa560d86..6b8607329 100644 --- a/gruntjs/gruntjs-tests.ts +++ b/gruntjs/gruntjs-tests.ts @@ -89,9 +89,9 @@ exports.exports = function(grunt: IGrunt) { }); // Iterate over all specified file groups. - this.files.forEach(function(f) { + this.files.forEach(function(f: grunt.file.IFilesConfig) { // Concat specified files. - var src = f.src.filter(function(filepath) { + var src = f.src.filter(function(filepath: string) { // Warn on and remove invalid source files (if nonull was set). if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file "' + filepath + '" not found.'); From e49477e675eee56f171284a75066d58f85b76156 Mon Sep 17 00:00:00 2001 From: Will Johnston Date: Mon, 4 Aug 2014 09:46:50 -0500 Subject: [PATCH 264/324] Updated with mysql contributor --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index af326634b..c5096509b 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -247,6 +247,7 @@ All definitions files include a header with the author and editors, so at some p * [Mousetrap](http://craig.is/killing/mice) (by [Dániel Tar](https://github.com/qcz)) * [msgpack.js](https://github.com/uupaa/msgpack.js) (by [Shinya Mochizuki](https://github.com/enrapt-mochizuki)) * [Mustache.js](https://github.com/janl/mustache.js) (by [Boris Yankov](https://github.com/borisyankov)) +* [mysql](https://github.com/felixge/node-mysql) (by [William Johnston](https://github.com/wjohnsto)) * [nconf](https://github.com/flatiron/nconf) (by [Jeff Goddard](https://github.com/jedigo)) * [noble](https://github.com/sandeepmistry/noble) (by [Seon-Wook Park](https://github.com/swook)) * [nock](https://github.com/pgte/nock) (by [bonnici](https://github.com/bonnici)) From e3a212a892852cd4b8a5dccd6347ae32f4cfc187 Mon Sep 17 00:00:00 2001 From: Holger Stitz Date: Mon, 4 Aug 2014 17:02:03 +0200 Subject: [PATCH 265/324] Added the nodeSize function to TreeLayout Documentation https://github.com/mbostock/d3/wiki/Tree-Layout#nodeSize --- d3/d3.d.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 0354bc264..637afcc0c 100755 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -1159,6 +1159,19 @@ declare module D3 { */ (size: Array): TreeLayout; }; + /** + * Gets or sets the available node size + */ + nodeSize: { + /** + * Gets the available node size + */ + (): Array; + /** + * Sets the available node size + */ + (size: Array): TreeLayout; + }; } export interface PieLayout { From 7a8afe9eccb19ce169bdfddf05666e90e17d1f20 Mon Sep 17 00:00:00 2001 From: Evgenus Date: Mon, 4 Aug 2014 19:40:22 +0300 Subject: [PATCH 266/324] definitions for Big Integer library by Tom Wu --- CONTRIBUTORS.md | 1 + jsbn/jsbn-tests.ts | 93 +++++++++++++++++ jsbn/jsbn.d.ts | 250 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 344 insertions(+) create mode 100644 jsbn/jsbn-tests.ts create mode 100644 jsbn/jsbn.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index af326634b..8d25e840d 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -193,6 +193,7 @@ All definitions files include a header with the author and editors, so at some p * [js-git](https://github.com/creationix/js-git) (by [Bart van der Schoor](https://github.com/Bartvds)) * [js-url](https://github.com/websanova/js-url) (by [MIZUNE Pine](https://github.com/pine613)) * [js-yaml](https://github.com/nodeca/js-yaml) (by [Bart van der Schoor](https://github.com/Bartvds/)) +* [jsbn](http://www-cs-students.stanford.edu/%7Etjw/jsbn/) (by [Eugene Chernyshov](https://github.com/Evgenus)) * [jScrollPane](http://jscrollpane.kelvinluck.com) (by [Dániel Tar](https://github.com/qcz)) * [JSDeferred](http://cho45.stfuawsc.com/jsdeferred/) (by [Daisuke Mino](https://github.com/minodisk)) * [JSONEditorOnline](https://github.com/josdejong/jsoneditoronline) (by [Vincent Bortone](https://github.com/vbortone/)) diff --git a/jsbn/jsbn-tests.ts b/jsbn/jsbn-tests.ts new file mode 100644 index 000000000..667f78553 --- /dev/null +++ b/jsbn/jsbn-tests.ts @@ -0,0 +1,93 @@ +/// +var BigInteger = jsbn.BigInteger; + +// constructor tests +var x = new BigInteger("AABB", 16); +x = new BigInteger("75643564363473453456342378564387956906736546456235345"); + +// method tests +var isBigInteger: jsbn.BigInteger; +var isNumber: number; +var isBoolean: boolean; +var isString: string; +var isDivmod: jsbn.BigInteger[]; +var isByteArray: number[]; + +x.copyTo(x); +x.fromInt(0); +x.fromString("CAFEBABE", 16); +x.clamp(); +isString = x.toString(); +isString = x.toString(16); +isBigInteger = x.negate(); +isBigInteger = x.abs(); +isNumber = x.compareTo(x); +isNumber = x.bitLength(); +x.dlShiftTo(0, isBigInteger); +x.drShiftTo(0, isBigInteger); +x.lShiftTo(0, isBigInteger); +x.rShiftTo(0, isBigInteger); +x.subTo(x, isBigInteger); +x.multiplyTo(x, isBigInteger); +x.squareTo(isBigInteger); +x.divRemTo(x, isBigInteger, isBigInteger); +isBigInteger = x.mod(x); +isNumber = x.invDigit(); +isBoolean = x.isEven(); +isBigInteger = x.exp(0, { + convert: (x) => x, + revert: (x) => x, + reduce: (x) => x, + mulTo: (x) => x, + sqrTo: (x) => x +}); +isBigInteger = x.modPowInt(0, x); +isBigInteger = x.clone(); +isNumber = x.intValue(); +isNumber = x.byteValue(); +isNumber = x.shortValue(); +isNumber = x.chunkSize(0); +isNumber = x.signum(); +isString = x.toRadix(10); +x.fromRadix("123", 10); +x.fromNumber(1); +x.fromNumber(1, 2); +x.fromNumber(1, 2, 3); +isByteArray = x.toByteArray(); +isBoolean = x.equals(x); +isBigInteger = x.min(x); +isBigInteger = x.max(x); +x.bitwiseTo(x, (x, y) => x + y, isBigInteger); +isBigInteger = x.and(x); +isBigInteger = x.or(x); +isBigInteger = x.xor(x); +isBigInteger = x.andNot(x); +isBigInteger = x.not(); +isBigInteger = x.shiftLeft(0); +isBigInteger = x.shiftRight(0); +isNumber = x.getLowestSetBit(); +isNumber = x.bitCount(); +isBoolean = x.testBit(0); +isBigInteger = x.changeBit(0, (x, y) => x * y); +isBigInteger = x.setBit(0); +isBigInteger = x.clearBit(0); +isBigInteger = x.flipBit(0); +x.addTo(x, isBigInteger); +isBigInteger = x.add(x); +isBigInteger = x.subtract(x); +isBigInteger = x.multiply(x); +isBigInteger = x.square(); +isBigInteger = x.divide(x); +isBigInteger = x.remainder(x); +isDivmod = x.divideAndRemainder(x); +x.dMultiply(0); +x.dAddOffset(0, 0); +isBigInteger = x.pow(0); +x.multiplyLowerTo(x, 0, isBigInteger); +x.multiplyUpperTo(x, 0, isBigInteger); +isBigInteger = x.modPow(x, x); +isBigInteger = x.gcd(x); +isNumber = x.modInt(0); +isBigInteger = x.modInverse(x); +isBoolean = x.isProbablePrime(0); +isBoolean = x.millerRabin(0); diff --git a/jsbn/jsbn.d.ts b/jsbn/jsbn.d.ts new file mode 100644 index 000000000..bd75bd876 --- /dev/null +++ b/jsbn/jsbn.d.ts @@ -0,0 +1,250 @@ +// Type definitions for jsbn v1.2 +// Project: http://www-cs-students.stanford.edu/%7Etjw/jsbn/ +// Definitions by: Eugene Chernyshov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module jsbn { + + interface RandomGenerator { + nextBytes(bytes: number[]): void; + } + + export class BigInteger { + constructor(a: number, c: RandomGenerator); + constructor(a: number, b: number, c: RandomGenerator); + constructor(a: string, b?: number); + constructor(a: number[], b?: number); + constructor(a: BigInteger); + + s: number; + t: number; + data: number[]; // forge specific + + DB: number; + DM: number; + DV: number; + + FV: number; + F1: number; + F2: number; + + // am: Compute w_j += (x*this_i), propagate carries, + am(i: number, x: number, w: BigInteger, j: number, c: number, n: number): number; + + // (protected) copy this to r + copyTo(r: BigInteger): void; + + // (protected) set from integer value x, -DV <= x < DV + fromInt(x: number): void; + + // (protected) set from string and radix + fromString(x: string, b: number): void; + + // (protected) clamp off excess high words + clamp(): void; + + // (public) return string representation in given radix + toString(b?: number): string; + + // (public) -this + negate(): BigInteger; + + // (public) |this| + abs(): BigInteger; + + // (public) return + if this > a, - if this < a, 0 if equal + compareTo(a: BigInteger): number; + + // (public) return the number of bits in "this" + bitLength(): number; + + // (protected) r = this << n*DB + dlShiftTo(n: number, r: BigInteger): void; + + // (protected) r = this >> n*DB + drShiftTo(n: number, r: BigInteger): void; + + // (protected) r = this << n + lShiftTo(n: number, r: BigInteger): void; + + // (protected) r = this >> n + rShiftTo(n: number, r: BigInteger): void; + + // (protected) r = this - a + subTo(a: BigInteger, r: BigInteger): void; + + // (protected) r = this * a, r != this,a (HAC 14.12) + multiplyTo(a: BigInteger, r: BigInteger): void; + + // (protected) r = this^2, r != this (HAC 14.16) + squareTo(r: BigInteger): void; + + // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) + // r != q, this != m. q or r may be null. + divRemTo(m: BigInteger, q: BigInteger, r: BigInteger): void; + + // (public) this mod a + mod(a: BigInteger): BigInteger; + + // (protected) return "-1/this % 2^DB"; useful for Mont. reduction + invDigit(): number; + + // (protected) true iff this is even + isEven(): boolean; + + // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) + exp(e: number, z: Reduction): BigInteger; + + // (public) this^e % m, 0 <= e < 2^32 + modPowInt(e: number, m: BigInteger): BigInteger; + + // (public) + clone(): BigInteger; + + // (public) return value as integer + intValue(): number; + + // (public) return value as byte + byteValue(): number; + + // (public) return value as short (assumes DB>=16) + shortValue(): number; + + // (protected) return x s.t. r^x < DV + chunkSize(r: number): number; + + // (public) 0 if this == 0, 1 if this > 0 + signum(): number; + + // (protected) convert to radix string + toRadix(b: number): string; + + // (protected) convert from radix string + fromRadix(s: string, b: number): void; + + // (protected) alternate constructor + fromNumber(a: number, b?: number, c?: number): void; + + // (public) convert to bigendian byte array + toByteArray(): number[]; + + equals(a: BigInteger): boolean; + + min(a: BigInteger): BigInteger; + + max(a: BigInteger): BigInteger; + + // (protected) r = this op a (bitwise) + bitwiseTo(a: BigInteger, op: (x: number, y: number) => number, r: BigInteger): void; + + // (public) this & a + and(a: BigInteger): BigInteger; + + // (public) this | a + or(a: BigInteger): BigInteger; + + // (public) this ^ a + xor(a: BigInteger): BigInteger; + + // (public) this & ~a + andNot(a: BigInteger): BigInteger; + + // (public) ~this + not(): BigInteger; + + // (public) this << n + shiftLeft(n: number): BigInteger; + + // (public) this >> n + shiftRight(n: number): BigInteger; + + // (public) returns index of lowest 1-bit (or -1 if none) + getLowestSetBit(): number; + + // (public) return number of set bits + bitCount(): number; + + // (public) true iff nth bit is set + testBit(n: number): boolean; + + // (protected) this op (1< number): BigInteger; + + // (protected) this op (1<= 0, 1 < n < DV + dMultiply(n: number): void; + + // (protected) this += n << w words, this >= 0 + dAddOffset(n: number, w: number): void; + + // (public) this^e + pow(e: number): BigInteger; + + // (protected) r = lower n words of "this * a", a.t <= n + multiplyLowerTo(a: BigInteger, n: number, r: BigInteger): void; + + // (protected) r = "this * a" without lower n words, n > 0 + multiplyUpperTo(a: BigInteger, n: number, r: BigInteger): void; + + // (public) this^e % m (HAC 14.85) + modPow(e: BigInteger, m: BigInteger): BigInteger; + + // (public) gcd(this,a) (HAC 14.54) + gcd(a: BigInteger): BigInteger; + + // (protected) this % n, n < 2^26 + modInt(n: number): number; + + // (public) 1/this % m (HAC 14.61) + modInverse(m: BigInteger): BigInteger; + + // (public) test primality with certainty >= 1-.5^t + isProbablePrime(t: number): boolean; + + // (protected) true if probably prime (HAC 4.24, Miller-Rabin) + millerRabin(t: number): boolean; + + static ZERO: BigInteger; + static ONE: BigInteger; + } + + interface Reduction { + convert(x: BigInteger): BigInteger; + revert(x: BigInteger): BigInteger; + reduce(x: BigInteger): void; + mulTo(x: BigInteger, y: BigInteger, r: BigInteger): void; + sqrTo(x: BigInteger, r: BigInteger): void; + } +} \ No newline at end of file From 4ea6c8e68519c2f92d4c7fa200bfafb07194d89e Mon Sep 17 00:00:00 2001 From: San Chen Date: Tue, 5 Aug 2014 09:34:14 +0800 Subject: [PATCH 267/324] needle definitions and tests added --- needle/needle-tests.ts | 112 +++++++++++++++++++++++++++++++++++++---- needle/needle.d.ts | 80 +++++++++++++++++++++++++++-- 2 files changed, 178 insertions(+), 14 deletions(-) diff --git a/needle/needle-tests.ts b/needle/needle-tests.ts index 70c88933c..7283aeaa1 100644 --- a/needle/needle-tests.ts +++ b/needle/needle-tests.ts @@ -2,13 +2,107 @@ import needle = require("needle"); -var url = ""; -var options = {}; -var callback = (err, resp) => {}; +function Usage() { + // using callback + needle.get('http://ifconfig.me/all.json', function (error, response) { + if (!error) + console.log(response.body.ip_addr); // JSON decoding magic. :) + }); -needle.head(url, options, callback); -needle.get(url, options, callback); -needle.post(url, data, options, callback); -needle.put(url, data, options, callback); -needle.delete(url, data, options, callback); -needle.request(method, url, data, options, callback); + // using streams + var out; // = fs.createWriteStream('logo.png'); + needle.get('https://google.com/images/logo.png').pipe(out); +} + +function ResponsePipeline() { + needle.get('http://stackoverflow.com/feeds', { compressed: true }, function (err, resp) { + console.log(resp.body); // this little guy won't be a Gzipped binary blob + // but a nice object containing all the latest entries + }); + + var options = { + compressed: true, + follow: true, + rejectUnauthorized: true + }; + + // in this case, we'll ask Needle to follow redirects (disabled by default), + // but also to verify their SSL certificates when connecting. + var stream = needle.get('https://backend.server.com/everything.html', options); + + stream.on('readable', function () { + var data; + while (data = this.read()) { + console.log(data.toString()); + } + }); +} + +function API_head() { + var options = { + timeout: 5000 // if we don't get a response in 5 seconds, boom. + }; + + needle.head('https://my.backend.server.com', function (err, resp) { + if (err) { + console.log('Shoot! Something is wrong: ' + err.message); + } + else { + console.log('Yup, still alive.'); + } + }); +} + +function API_get() { + needle.get('google.com/search?q=syd+barrett', function (err, resp) { + // if no http:// is found, Needle will automagically prepend it. + }); +} + +function API_post() { + var options = { + headers: { 'X-Custom-Header': 'Bumbaway atuna' } + }; + + needle.post('https://my.app.com/endpoint', 'foo=bar', options, function (err, resp) { + // you can pass params as a string or as an object. + }); +} + +function API_put() { + var nested = { + params: { + are: { + also: 'supported' + } + } + }; + + needle.put('https://api.app.com/v2', nested, function (err, resp) { + console.log('Got ' + resp.bytes + ' bytes.') // another nice treat from this handsome fella. + }); +} + +function API_delete() { + var options = { + username: 'fidelio', + password: 'x' + }; + + needle.delete('https://api.app.com/messages/123', null, options, function (err, resp) { + // in this case, data may be null, but you need to explicity pass it. + }); +} + +function API_request() { + var data = { + q: 'a very smart query', + page: 2, + format: 'json' + }; + + needle.request('get', 'forum.com/search', data, function (err, resp) { + if (!err && resp.statusCode == 200) + console.log(resp.body); // here you go, mister. + }); +} diff --git a/needle/needle.d.ts b/needle/needle.d.ts index 732f5a059..f4c20408f 100644 --- a/needle/needle.d.ts +++ b/needle/needle.d.ts @@ -3,14 +3,84 @@ // Definitions by: San Chen // Definitions: https://github.com/borisyankov/DefinitelyTyped -interface INeedle { - head(url: string): IReadableStream; - head(url: string, callback?: Function): IReadableStream; - head(url: string, options?: any, callback?: Function): IReadableStream; +/// +declare module Needle { + + interface Callback { + (error: Error, response: any, body: any): void; + } + + interface RequestOptions { + timeout?: number; + follow?: any; // number | string + multipart?: boolean; + proxy?: string; + agent?: string; + headers?: any; + auth?: string; // auto | digest | basic (default) + json?: boolean; + } + + interface ResponseOptions { + decode?: boolean; + parse?: boolean; + output?: any; + } + + interface HttpHeaderOptions { + compressed?: boolean; + username?: string; + password?: string; + accept?: string; + connection?: string; + user_agent?: string; + } + + interface TLSOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + ciphers?: any; + rejectUnauthorized?: boolean; + secureProtocol?: any; + } + + interface NeedleOptions extends RequestOptions, ResponseOptions, HttpHeaderOptions, TLSOptions { + } + + interface NeedleStatic { + defaults(options?: any): void; + + head(url: string): ReadableStream; + head(url: string, callback?: Callback): ReadableStream; + head(url: string, options?: RequestOptions, callback?: Callback): ReadableStream; + + get(url: string): ReadableStream; + get(url: string, callback?: Callback): ReadableStream; + get(url: string, options?: RequestOptions, callback?: Callback): ReadableStream; + + post(url: string, data: any): ReadableStream; + post(url: string, data: any, callback?: Callback): ReadableStream; + post(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + + put(url: string, data: any): ReadableStream; + put(url: string, data: any, callback?: Callback): ReadableStream; + put(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + + delete(url: string, data: any): ReadableStream; + delete(url: string, data: any, callback?: Callback): ReadableStream; + delete(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + + request(method: string, url: string, data: any): ReadableStream; + request(method: string, url: string, data: any, callback?: Callback): ReadableStream; + request(method: string, url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + } } declare module "needle" { - var needle: INeedle; + var needle: Needle.NeedleStatic; export = needle; } From 53558dd1643bc3a2939a51446c06e5f8c9f2d7a8 Mon Sep 17 00:00:00 2001 From: MIZUNE Pine Date: Tue, 5 Aug 2014 11:15:55 +0900 Subject: [PATCH 268/324] Add http-string-parser --- CONTRIBUTORS.md | 1 + http-string-parser/http-string-parser-test.ts | 42 +++++++++++++++++++ http-string-parser/http-string-parser.d.ts | 38 +++++++++++++++++ 3 files changed, 81 insertions(+) create mode 100644 http-string-parser/http-string-parser-test.ts create mode 100644 http-string-parser/http-string-parser.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index aafef048d..5da07cb74 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -125,6 +125,7 @@ All definitions files include a header with the author and editors, so at some p * [highlight.js](https://github.com/isagalaev/highlight.js) (by [Niklas Mollenhauer](https://github.com/nikeee)) * [History.js](https://github.com/browserstate/history.js) (by [Boris Yankov](https://github.com/borisyankov)) * [Html2Canvas.js](https://github.com/niklasvh/html2canvas/) (by [Richard Hepburn](https://github.com/rwhepburn)) +* [http-string-parser](https://github.com/apiaryio/http-string-parser) (by [MIZUNE Pine](https://github.com/pine613)) * [Humane.js](http://wavded.github.com/humane-js/) (by [John Vrbanac](https://github.com/jmvrbanac)) * [i18next](http://i18next.com/) (by [Maarten Docter](https://github.com/mdocter)) * [iCheck](http://damirfoy.com/iCheck/) (by [Dániel Tar](https://github.com/qcz)) diff --git a/http-string-parser/http-string-parser-test.ts b/http-string-parser/http-string-parser-test.ts new file mode 100644 index 000000000..9c4116e5d --- /dev/null +++ b/http-string-parser/http-string-parser-test.ts @@ -0,0 +1,42 @@ +/// + +import parser = require("http-string-parser"); + +function test_request(): void { + var result = parser.parseRequest("HTTP/1.1 GET /\r\nHost: www.example.com\r\n\r\n"); + + var body: string = result.body; + var headers: { [key: string]: string } = result.headers; + var method: string = result.method; + var uri: string = result.uri; +} + +function test_response(): void { + var response = parser.parseResponse("HTTP/1.1 200 OK\r\n\r\n"); + + var body: string = response.body; + var headers: { [key: string]: string } = response.headers; + var statusCode: string = response.statusCode; + var statusMessage: string = response.statusMessage; +} + +function test_requestLine(): void { + var result = parser.parseRequestLine("HTTP/1.1 GET /"); + + var method: string = result.method; + var protocol: string = result.protocol; + var uri: string = result.uri; +} + +function test_statusLine(): void { + var result = parser.parseStatusLine("HTTP/1.1 200 OK"); + + var protocol: string = result.protocol; + var statusCode: string = result.statusCode; + var statusMessage: string = result.statusMessage; +} + +function test_headers(): void { + var result: { [key: string]: string } = + parser.parseHeaders("Content-Type: text/html; charset=utf-8\r\nContent-Length: 256\r\n"); +} \ No newline at end of file diff --git a/http-string-parser/http-string-parser.d.ts b/http-string-parser/http-string-parser.d.ts new file mode 100644 index 000000000..893457279 --- /dev/null +++ b/http-string-parser/http-string-parser.d.ts @@ -0,0 +1,38 @@ +// Type definitions for Backbone v0.9.10 +// Project: https://github.com/apiaryio/http-string-parser +// Definitions by: MIZUNE Pine +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "http-string-parser" { + interface ParseRequestResult { + method: string; + uri: string; + headers: { [key: string]: string }; + body: string; + } + + interface ParseResponseResult { + statusCode: string; + statusMessage: string; + headers: { [key: string]: string }; + body: string; + } + + interface ParseRequestLineResult { + method: string; + uri: string; + protocol: string; + } + + interface ParseStatusLineResult { + protocol: string; + statusCode: string; + statusMessage: string; + } + + export function parseRequest(requestString: string): ParseRequestResult; + export function parseResponse(responseString: string): ParseResponseResult; + export function parseRequestLine(requestLineString: string): ParseRequestLineResult; + export function parseStatusLine(statusLine: string): ParseStatusLineResult; + export function parseHeaders(headerLines: string): { [key: string]: string }; +} From e0d5a27525df14b9ba0486f326da549491f026c1 Mon Sep 17 00:00:00 2001 From: MIZUNE Pine Date: Tue, 5 Aug 2014 11:20:19 +0900 Subject: [PATCH 269/324] Fix header --- http-string-parser/http-string-parser.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/http-string-parser/http-string-parser.d.ts b/http-string-parser/http-string-parser.d.ts index 893457279..4239cd9df 100644 --- a/http-string-parser/http-string-parser.d.ts +++ b/http-string-parser/http-string-parser.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Backbone v0.9.10 +// Type definitions for http-string-parser // Project: https://github.com/apiaryio/http-string-parser // Definitions by: MIZUNE Pine // Definitions: https://github.com/borisyankov/DefinitelyTyped From a77c6b79f52a74bc0ff1810215d5b32e9d65a06d Mon Sep 17 00:00:00 2001 From: San Chen Date: Tue, 5 Aug 2014 11:06:19 +0800 Subject: [PATCH 270/324] tests passed --- needle/needle-tests.ts | 4 ++-- needle/needle.d.ts | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/needle/needle-tests.ts b/needle/needle-tests.ts index 7283aeaa1..24d9701b5 100644 --- a/needle/needle-tests.ts +++ b/needle/needle-tests.ts @@ -10,7 +10,7 @@ function Usage() { }); // using streams - var out; // = fs.createWriteStream('logo.png'); + var out: any; // = fs.createWriteStream('logo.png'); needle.get('https://google.com/images/logo.png').pipe(out); } @@ -31,7 +31,7 @@ function ResponsePipeline() { var stream = needle.get('https://backend.server.com/everything.html', options); stream.on('readable', function () { - var data; + var data: any; while (data = this.read()) { console.log(data.toString()); } diff --git a/needle/needle.d.ts b/needle/needle.d.ts index f4c20408f..741cf5fe3 100644 --- a/needle/needle.d.ts +++ b/needle/needle.d.ts @@ -6,6 +6,8 @@ /// declare module Needle { + interface ReadableStream extends NodeJS.ReadableStream { + } interface Callback { (error: Error, response: any, body: any): void; From 982f57d1266842ef4554f639b6adf379c320f8e1 Mon Sep 17 00:00:00 2001 From: Dick van den Brink Date: Tue, 5 Aug 2014 13:10:10 +0200 Subject: [PATCH 271/324] Phonegap: Fixed Filesystem api --- phonegap/phonegap.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/phonegap/phonegap.d.ts b/phonegap/phonegap.d.ts index 37585887b..7d744346a 100644 --- a/phonegap/phonegap.d.ts +++ b/phonegap/phonegap.d.ts @@ -367,7 +367,7 @@ interface FileUploadResult { interface Flags { create: boolean; - exclusive: boolean; + exclusive?: boolean; } /* From 1ba83dded25175aa1239dd6ad0d6e0c81a3571ab Mon Sep 17 00:00:00 2001 From: Nickolas Westman Date: Tue, 5 Aug 2014 11:43:05 -0700 Subject: [PATCH 272/324] Update underscore.d.ts Template return values not correctly typed - if data is passed it will return a string (no partial templating in underscore) --- underscore/underscore.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/underscore/underscore.d.ts b/underscore/underscore.d.ts index 7d9c84f82..9736c2879 100644 --- a/underscore/underscore.d.ts +++ b/underscore/underscore.d.ts @@ -1472,8 +1472,9 @@ interface UnderscoreStatic { * @param settings Settings to use while compiling. * @return Returns the compiled Underscore HTML template. **/ - template(templateString: string, data?: any, settings?: _.TemplateSettings): (...data: any[]) => string; - + template(templateString: string): (...data: any[]) => string; + template(templateString: string, data: any, settings?: _.TemplateSettings): string; + /** * By default, Underscore uses ERB-style template delimiters, change the * following template settings to use alternative delimiters. From f1a45e0d4e2d5260408a5f6f6a5f99269ed133de Mon Sep 17 00:00:00 2001 From: Paulo Cesar Date: Sat, 2 Aug 2014 13:59:17 -0300 Subject: [PATCH 273/324] directive accept classes --- angularjs/angular-tests.ts | 471 ++++++++++++++++++++----------------- angularjs/angular.d.ts | 38 ++- 2 files changed, 279 insertions(+), 230 deletions(-) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index a1577856e..9c1cc0ab4 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -231,11 +231,11 @@ foo.then((x) => { }).then((x) => { // Object is inferred here x.a = 123; - //Try a promise + //Try a promise var y: ng.IPromise; - return y; + return y; }).then((x) => { - // x is infered to be a number, which is the resolved value of a promise + // x is infered to be a number, which is the resolved value of a promise x.toFixed(); }); @@ -281,252 +281,289 @@ test_IAttributes({ $attr: {} }); +class SampleDirective implements ng.IDirective { + public restrict = 'A'; + name = 'doh'; + + compile(templateElement: any) { + return this.link; + } + + static instance():ng.IDirective { + return new SampleDirective(); + } + + link(scope: any) { + + } +} + +class SampleDirective2 implements ng.IDirective { + public restrict = 'EAC'; + + compile(templateElement: any) { + return { + pre: this.link + }; + } + + static instance():ng.IDirective { + return new SampleDirective2(); + } + + link(scope: any) { + + } +} + +angular.module('SameplDirective', []).directive('sampleDirective', SampleDirective.instance).directive('sameplDirective2', SampleDirective2.instance); + // test from https://docs.angularjs.org/guide/directive angular.module('docsSimpleDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.customer = { - name: 'Naomi', - address: '1600 Amphitheatre' - }; - }]) - .directive('myCustomer', function() { - return { - template: 'Name: {{customer.name}} Address: {{customer.address}}' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + template: 'Name: {{customer.name}} Address: {{customer.address}}' + }; + }); angular.module('docsTemplateUrlDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.customer = { - name: 'Naomi', - address: '1600 Amphitheatre' - }; - }]) - .directive('myCustomer', function() { - return { - templateUrl: 'my-customer.html' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + templateUrl: 'my-customer.html' + }; + }); angular.module('docsRestrictDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.customer = { - name: 'Naomi', - address: '1600 Amphitheatre' - }; - }]) - .directive('myCustomer', function() { - return { - restrict: 'E', - templateUrl: 'my-customer.html' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + templateUrl: 'my-customer.html' + }; + }); angular.module('docsScopeProblemExample', []) - .controller('NaomiController', ['$scope', function($scope: any) { - $scope.customer = { - name: 'Naomi', - address: '1600 Amphitheatre' - }; - }]) - .controller('IgorController', ['$scope', function($scope: any) { - $scope.customer = { - name: 'Igor', - address: '123 Somewhere' - }; - }]) - .directive('myCustomer', function() { - return { - restrict: 'E', - templateUrl: 'my-customer.html' - }; - }); + .controller('NaomiController', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .controller('IgorController', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Igor', + address: '123 Somewhere' + }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + templateUrl: 'my-customer.html' + }; + }); angular.module('docsIsolateScopeDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; - $scope.igor = { name: 'Igor', address: '123 Somewhere' }; - }]) - .directive('myCustomer', function() { - return { - restrict: 'E', - scope: { - customerInfo: '=info' - }, - templateUrl: 'my-customer-iso.html' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; + $scope.igor = { name: 'Igor', address: '123 Somewhere' }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + scope: { + customerInfo: '=info' + }, + templateUrl: 'my-customer-iso.html' + }; + }); angular.module('docsIsolationExample', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; - $scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' }; - }]) - .directive('myCustomer', function() { - return { - restrict: 'E', - scope: { - customerInfo: '=info' - }, - templateUrl: 'my-customer-plus-vojta.html' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; + $scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + scope: { + customerInfo: '=info' + }, + templateUrl: 'my-customer-plus-vojta.html' + }; + }); angular.module('docsTimeDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.format = 'M/d/yy h:mm:ss a'; - }]) - .directive('myCurrentTime', ['$interval', 'dateFilter', function($interval: any, dateFilter: any): ng.IDirective { + .controller('Controller', ['$scope', function($scope: any) { + $scope.format = 'M/d/yy h:mm:ss a'; + }]) + .directive('myCurrentTime', ['$interval', 'dateFilter', function($interval: any, dateFilter: any): ng.IDirective { - return { - link: function(scope: any, element: any, attrs: any) { - var format: any, - timeoutId: any; + return { + link: function(scope: any, element: any, attrs: any) { + var format: any, + timeoutId: any; - function updateTime() { - element.text(dateFilter(new Date(), format)); - } + function updateTime() { + element.text(dateFilter(new Date(), format)); + } - scope.$watch(attrs.myCurrentTime, function (value: any) { - format = value; - updateTime(); - }); + scope.$watch(attrs.myCurrentTime, function (value: any) { + format = value; + updateTime(); + }); - element.on('$destroy', function () { - $interval.cancel(timeoutId); - }); + element.on('$destroy', function () { + $interval.cancel(timeoutId); + }); - // start the UI update process; save the timeoutId for canceling - timeoutId = $interval(function () { - updateTime(); // update DOM - }, 1000); - } - }; - }]); + // start the UI update process; save the timeoutId for canceling + timeoutId = $interval(function () { + updateTime(); // update DOM + }, 1000); + } + }; + }]); angular.module('docsTransclusionDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.name = 'Tobias'; - }]) - .directive('myDialog', function() { - return { - restrict: 'E', - transclude: true, - templateUrl: 'my-dialog.html' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.name = 'Tobias'; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + templateUrl: 'my-dialog.html' + }; + }); angular.module('docsTransclusionExample', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.name = 'Tobias'; - }]) - .directive('myDialog', function() { - return { - restrict: 'E', - transclude: true, - scope: {}, - templateUrl: 'my-dialog.html', - link: function (scope: any, element: any) { - scope.name = 'Jeff'; - } - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.name = 'Tobias'; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + scope: {}, + templateUrl: 'my-dialog.html', + link: function (scope: any, element: any) { + scope.name = 'Jeff'; + } + }; + }); angular.module('docsIsoFnBindExample', []) - .controller('Controller', ['$scope', '$timeout', function($scope: any, $timeout: any) { - $scope.name = 'Tobias'; - $scope.hideDialog = function () { - $scope.dialogIsHidden = true; - $timeout(function () { - $scope.dialogIsHidden = false; - }, 2000); - }; - }]) - .directive('myDialog', function() { - return { - restrict: 'E', - transclude: true, - scope: { - 'close': '&onClose' - }, - templateUrl: 'my-dialog-close.html' - }; - }); + .controller('Controller', ['$scope', '$timeout', function($scope: any, $timeout: any) { + $scope.name = 'Tobias'; + $scope.hideDialog = function () { + $scope.dialogIsHidden = true; + $timeout(function () { + $scope.dialogIsHidden = false; + }, 2000); + }; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + scope: { + 'close': '&onClose' + }, + templateUrl: 'my-dialog-close.html' + }; + }); angular.module('dragModule', []) - .directive('myDraggable', ['$document', function($document: any) { - return function(scope: any, element: any, attr: any) { - var startX = 0, startY = 0, x = 0, y = 0; + .directive('myDraggable', ['$document', function($document: any) { + return function(scope: any, element: any, attr: any) { + var startX = 0, startY = 0, x = 0, y = 0; - element.css({ - position: 'relative', - border: '1px solid red', - backgroundColor: 'lightgrey', - cursor: 'pointer' - }); + element.css({ + position: 'relative', + border: '1px solid red', + backgroundColor: 'lightgrey', + cursor: 'pointer' + }); - element.on('mousedown', function(event: any) { - // Prevent default dragging of selected content - event.preventDefault(); - startX = event.pageX - x; - startY = event.pageY - y; - $document.on('mousemove', mousemove); - $document.on('mouseup', mouseup); - }); + element.on('mousedown', function(event: any) { + // Prevent default dragging of selected content + event.preventDefault(); + startX = event.pageX - x; + startY = event.pageY - y; + $document.on('mousemove', mousemove); + $document.on('mouseup', mouseup); + }); - function mousemove(event: any) { - y = event.pageY - startY; - x = event.pageX - startX; - element.css({ - top: y + 'px', - left: x + 'px' - }); - } + function mousemove(event: any) { + y = event.pageY - startY; + x = event.pageX - startX; + element.css({ + top: y + 'px', + left: x + 'px' + }); + } - function mouseup() { - $document.off('mousemove', mousemove); - $document.off('mouseup', mouseup); - } - }; - }]); + function mouseup() { + $document.off('mousemove', mousemove); + $document.off('mouseup', mouseup); + } + }; + }]); angular.module('docsTabsExample', []) - .directive('myTabs', function() { - return { - restrict: 'E', - transclude: true, - scope: {}, - controller: function($scope: any) { - var panes: any = $scope.panes = []; + .directive('myTabs', function() { + return { + restrict: 'E', + transclude: true, + scope: {}, + controller: function($scope: any) { + var panes: any = $scope.panes = []; - $scope.select = function(pane: any) { - angular.forEach(panes, function(pane: any) { - pane.selected = false; - }); - pane.selected = true; - }; + $scope.select = function(pane: any) { + angular.forEach(panes, function(pane: any) { + pane.selected = false; + }); + pane.selected = true; + }; - this.addPane = function(pane: any) { - if (panes.length === 0) { - $scope.select(pane); - } - panes.push(pane); - }; - }, - templateUrl: 'my-tabs.html' - }; - }) - .directive('myPane', function() { - return { - require: '^myTabs', - restrict: 'E', - transclude: true, - scope: { - title: '@' - }, - link: function(scope, element, attrs, tabsCtrl) { - tabsCtrl.addPane(scope); - }, - templateUrl: 'my-pane.html' - }; - }); + this.addPane = function(pane: any) { + if (panes.length === 0) { + $scope.select(pane); + } + panes.push(pane); + }; + }, + templateUrl: 'my-tabs.html' + }; + }) + .directive('myPane', function() { + return { + require: '^myTabs', + restrict: 'E', + transclude: true, + scope: { + title: '@' + }, + link: function(scope: any, element: any, attrs: any, tabsCtrl: any) { + tabsCtrl.addPane(scope); + }, + templateUrl: 'my-pane.html' + }; + }); diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index e447985fb..e66a6c973 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1031,22 +1031,34 @@ declare module ng { (...args: any[]): IDirective; } + interface IDirectiveLinkFn { + ( + scope?: IScope, + instanceElement?: IAugmentedJQuery, + instanceAttributes?: IAttributes, + controller?: any, + transclude?: ITranscludeFunction + ): void; + } - interface IDirective{ - compile?: - (templateElement: IAugmentedJQuery, - templateAttributes: IAttributes, - transclude: ITranscludeFunction - ) => any; + interface IDirectivePrePost { + pre?: IDirectiveLinkFn; + post?: IDirectiveLinkFn; + } + + interface IDirectiveCompileFn { + ( + templateElement?: IAugmentedJQuery, + templateAttributes?: IAttributes, + transclude?: ITranscludeFunction + ): IDirectivePrePost; + } + + interface IDirective { + compile?: IDirectiveCompileFn; controller?: any; controllerAs?: string; - link?: - (scope: IScope, - instanceElement: IAugmentedJQuery, - instanceAttributes: IAttributes, - controller: any, - transclude: ITranscludeFunction - ) => void; + link?: IDirectiveLinkFn; name?: string; priority?: number; replace?: boolean; From 0864d50b8c02b79e8a8f247fa671ba6170773fa5 Mon Sep 17 00:00:00 2001 From: Dick van den Brink Date: Wed, 6 Aug 2014 10:35:48 +0200 Subject: [PATCH 274/324] Phonegap: Added StatusBar plugin interface --- phonegap/phonegap.d.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/phonegap/phonegap.d.ts b/phonegap/phonegap.d.ts index 7d744346a..566594c51 100644 --- a/phonegap/phonegap.d.ts +++ b/phonegap/phonegap.d.ts @@ -575,6 +575,21 @@ interface LocalStorage { } */ +interface StatusBar { + isVisible: boolean; + + overlaysWebView(doOverlay: boolean): void; + styleDefault(): void; + styleLightContent(): void; + styleBlackTranslucent(): void; + styleBlackOpaque(): void; + backgroundColorByName(colorname: string): void; + backgroundColorByHexString(hexString: string): void; + hide(): void; + show(): void; +} +declare var StatusBar: StatusBar; + interface /*PhoneGapNavigator extends*/ Navigator { accelerometer: Accelerometer; camera: Camera; From 62aebaa52148114b7c6be270c034bf1166389915 Mon Sep 17 00:00:00 2001 From: Dick van den Brink Date: Wed, 6 Aug 2014 11:06:12 +0200 Subject: [PATCH 275/324] jQuery: Remove JQueryDeferred.state method because it is already defined in JQueryPromise --- jquery/jquery.d.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index e40110c16..1884180fb 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -1,6 +1,6 @@ // Type definitions for jQuery 1.10.x / 2.0.x // Project: http://jquery.com/ -// Definitions by: Boris Yankov , Christian Hoffmeister , Steve Fenton , Diullei Gomes , Tass Iliopoulos , Jason Swearingen , Sean Hill , Guus Goossens , Kelly Summerlin , Basarat Ali Syed , Nicholas Wolverson , Derek Cicerone , Andrew Gaspar , James Harrison Fisher , Seikichi Kondo , Benjamin Jackman , Poul Sorensen , Josh Strobl , John Reilly +// Definitions by: Boris Yankov , Christian Hoffmeister , Steve Fenton , Diullei Gomes , Tass Iliopoulos , Jason Swearingen , Sean Hill , Guus Goossens , Kelly Summerlin , Basarat Ali Syed , Nicholas Wolverson , Derek Cicerone , Andrew Gaspar , James Harrison Fisher , Seikichi Kondo , Benjamin Jackman , Poul Sorensen , Josh Strobl , John Reilly , Dick van den Brink // Definitions: https://github.com/borisyankov/DefinitelyTyped /* ***************************************************************************** @@ -525,10 +525,6 @@ interface JQueryDeferred extends JQueryPromise { * @param args An optional array of arguments that are passed to the doneCallbacks. */ resolveWith(context: any, ...args: any[]): JQueryDeferred; - /** - * Determine the current state of a Deferred object. - */ - state(): string; /** * Return a Deferred's Promise object. From 3583fdd36d63bd95fdf28ca702ed637ad530e0dc Mon Sep 17 00:00:00 2001 From: Dick van den Brink Date: Wed, 6 Aug 2014 11:12:10 +0200 Subject: [PATCH 276/324] Added DickvdBrink as an author --- phonegap/phonegap.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/phonegap/phonegap.d.ts b/phonegap/phonegap.d.ts index 566594c51..17aeb1ff0 100644 --- a/phonegap/phonegap.d.ts +++ b/phonegap/phonegap.d.ts @@ -1,6 +1,6 @@ // Type definitions for PhoneGap 2.3 // Project: http://phonegap.com -// Definitions by: Boris Yankov +// Definitions by: Boris Yankov , Dick van den Brink // Definitions: https://github.com/borisyankov/DefinitelyTyped interface GeolocationError { From 5f30d6961a2e7db0f1045acbcfcb3ca3d98f3171 Mon Sep 17 00:00:00 2001 From: Dick van den Brink Date: Wed, 6 Aug 2014 09:52:35 +0200 Subject: [PATCH 277/324] Phonegap: Added Keyboard plugin --- phonegap/phonegap.d.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/phonegap/phonegap.d.ts b/phonegap/phonegap.d.ts index 17aeb1ff0..23a9babbe 100644 --- a/phonegap/phonegap.d.ts +++ b/phonegap/phonegap.d.ts @@ -590,6 +590,21 @@ interface StatusBar { } declare var StatusBar: StatusBar; +interface Keyboard { + automaticScrollToTopOnHiding: boolean; + isVisible: boolean; + + onshow: Function; + onhide: Function; + onshowing: Function; + onhiding: Function; + + disableScrollingInShrinkView(disable: boolean): void; + hideFormAccessoryBar(hide: boolean): void; + shrinkView(shrink: boolean): void; +} +declare var Keyboard: Keyboard; + interface /*PhoneGapNavigator extends*/ Navigator { accelerometer: Accelerometer; camera: Camera; From a90450655f562a62fc329378ce323321c80ad6f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonathan=20H=C3=A4berle?= Date: Wed, 6 Aug 2014 14:16:51 +0200 Subject: [PATCH 278/324] Added dependency to express --- express-validator/express-validator.d.ts | 318 ++++++++++++----------- 1 file changed, 165 insertions(+), 153 deletions(-) diff --git a/express-validator/express-validator.d.ts b/express-validator/express-validator.d.ts index b18b17e96..5a5df2fa0 100644 --- a/express-validator/express-validator.d.ts +++ b/express-validator/express-validator.d.ts @@ -1,161 +1,173 @@ // Type definitions for express-validator // Project: https://github.com/ctavan/express-validator -// Definitions by: Nathan Ridley +// Definitions by: Nathan Ridley , Jonathan Häberle // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module ExpressValidator { - export interface ValidationError { - msg: string; - param: string; - } +/// - export interface RequestValidation { - check(field: string, message: string): Validator; - assert(field: string, message: string): Validator; - sanitize(field: string): Sanitizer; - onValidationError(func: (msg: string) => void): void; - } - - export interface Validator { - /** - * Alias for regex() - */ - is(): Validator; - /** - * Alias for notRegex() - */ - not(): Validator; - isEmail(): Validator; - /** - * Accepts http, https, ftp - */ - isUrl(): Validator; - /** - * Combines isIPv4 and isIPv6 - */ - isIP(): Validator; - isIPv4(): Validator; - isIPv6(): Validator; - isAlpha(): Validator; - isAlphanumeric(): Validator; - isNumeric(): Validator; - isHexadecimal(): Validator; - /** - * Accepts valid hexcolors with or without # prefix - */ - isHexColor(): Validator; - /** - * isNumeric accepts zero padded numbers, e.g. '001', isInt doesn't - */ - isInt(): Validator; - isLowercase(): Validator; - isUppercase(): Validator; - isDecimal(): Validator; - /** - * Alias for isDecimal - */ - isFloat(): Validator; - /** - * Check if length is 0 - */ - notNull(): Validator; - isNull(): Validator; - /** - * Not just whitespace (input.trim().length !== 0) - */ - notEmpty(): Validator; - equals(equals: any): Validator; - contains(str: string): Validator; - notContains(str: string): Validator; - /** - * Usage: regex(/[a-z]/i) or regex('[a-z]','i') - */ - regex(pattern: string, modifiers: string): Validator; - notRegex(pattern: string, modifiers: string): Validator; - /** - * max is optional - */ - len(min: number, max?: number): Validator; - /** - * Version can be 3, 4 or 5 or empty, see http://en.wikipedia.org/wiki/Universally_unique_identifier - */ - isUUID(version: number): Validator; - /** - * Alias for isUUID(3) - */ - isUUIDv3(): Validator; - /** - * Alias for isUUID(4) - */ - isUUIDv4(): Validator; - /** - * Alias for isUUID(5) - */ - isUUIDv5(): Validator; - /** - * Uses Date.parse() - regex is probably a better choice - */ - isDate(): Validator; - /** - * Argument is optional and defaults to today. Comparison is non-inclusive - */ - isAfter(date: Date): Validator; - /** - * Argument is optional and defaults to today. Comparison is non-inclusive - */ - isBefore(date: Date): Validator; - isIn(options: string): Validator; - isIn(options: string[]): Validator; - notIn(options: string): Validator; - notIn(options: string[]): Validator; - max(val: string): Validator; - min(val: string): Validator; - /** - * Will work against Visa, MasterCard, American Express, Discover, Diners Club, and JCB card numbering formats - */ - isCreditCard(): Validator; - } - - interface Sanitizer { - /** - * Trim optional `chars`, default is to trim whitespace (\r\n\t ) - */ - trim(...chars: string[]): Sanitizer; - ltrim(...chars: string[]): Sanitizer; - rtrim(...chars: string[]): Sanitizer; - ifNull(replace: any): Sanitizer; - toFloat(): Sanitizer; - toInt(): Sanitizer; - /** - * True unless str = '0', 'false', or str.length == 0 - */ - toBoolean(): Sanitizer; - /** - * False unless str = '1' or 'true' - */ - toBooleanStrict(): Sanitizer; - /** - * Decode HTML entities - */ - entityDecode(): Sanitizer; - entityEncode(): Sanitizer; - /** - * Escape &, <, >, and " - */ - escape(): Sanitizer; - /** - * Remove common XSS attack vectors from user-supplied HTML - */ - xss(): Sanitizer; - /** - * Remove common XSS attack vectors from images - */ - xss(fromImages: boolean): Sanitizer; - } -} - -declare function ExpressValidator(): void; declare module "express-validator" { - export = ExpressValidator; + import express = require('express'); + + module ExpressValidator { + + export interface ValidationError { + msg: string; + param: string; + } + + export interface RequestValidation { + check(field:string, message:string): Validator; + assert(field:string, message:string): Validator; + sanitize(field:string): Sanitizer; + onValidationError(func:(msg:string) => void): void; + validationErrors() : any; + } + + export interface Validator { + /** + * Alias for regex() + */ + is(): Validator; + /** + * Alias for notRegex() + */ + not(): Validator; + isEmail(): Validator; + /** + * Accepts http, https, ftp + */ + isUrl(): Validator; + /** + * Combines isIPv4 and isIPv6 + */ + isIP(): Validator; + isIPv4(): Validator; + isIPv6(): Validator; + isAlpha(): Validator; + isAlphanumeric(): Validator; + isNumeric(): Validator; + isHexadecimal(): Validator; + /** + * Accepts valid hexcolors with or without # prefix + */ + isHexColor(): Validator; + /** + * isNumeric accepts zero padded numbers, e.g. '001', isInt doesn't + */ + isInt(): Validator; + isLowercase(): Validator; + isUppercase(): Validator; + isDecimal(): Validator; + /** + * Alias for isDecimal + */ + isFloat(): Validator; + /** + * Check if length is 0 + */ + notNull(): Validator; + isNull(): Validator; + /** + * Not just whitespace (input.trim().length !== 0) + */ + notEmpty(): Validator; + equals(equals:any): Validator; + contains(str:string): Validator; + notContains(str:string): Validator; + /** + * Usage: regex(/[a-z]/i) or regex('[a-z]','i') + */ + regex(pattern:string, modifiers:string): Validator; + notRegex(pattern:string, modifiers:string): Validator; + /** + * max is optional + */ + len(min:number, max?:number): Validator; + /** + * Version can be 3, 4 or 5 or empty, see http://en.wikipedia.org/wiki/Universally_unique_identifier + */ + isUUID(version:number): Validator; + /** + * Alias for isUUID(3) + */ + isUUIDv3(): Validator; + /** + * Alias for isUUID(4) + */ + isUUIDv4(): Validator; + /** + * Alias for isUUID(5) + */ + isUUIDv5(): Validator; + /** + * Uses Date.parse() - regex is probably a better choice + */ + isDate(): Validator; + /** + * Argument is optional and defaults to today. Comparison is non-inclusive + */ + isAfter(date:Date): Validator; + /** + * Argument is optional and defaults to today. Comparison is non-inclusive + */ + isBefore(date:Date): Validator; + isIn(options:string): Validator; + isIn(options:string[]): Validator; + notIn(options:string): Validator; + notIn(options:string[]): Validator; + max(val:string): Validator; + min(val:string): Validator; + /** + * Will work against Visa, MasterCard, American Express, Discover, Diners Club, and JCB card numbering formats + */ + isCreditCard(): Validator; + } + + interface Sanitizer { + /** + * Trim optional `chars`, default is to trim whitespace (\r\n\t ) + */ + trim(...chars:string[]): Sanitizer; + ltrim(...chars:string[]): Sanitizer; + rtrim(...chars:string[]): Sanitizer; + ifNull(replace:any): Sanitizer; + toFloat(): Sanitizer; + toInt(): Sanitizer; + /** + * True unless str = '0', 'false', or str.length == 0 + */ + toBoolean(): Sanitizer; + /** + * False unless str = '1' or 'true' + */ + toBooleanStrict(): Sanitizer; + /** + * Decode HTML entities + */ + entityDecode(): Sanitizer; + entityEncode(): Sanitizer; + /** + * Escape &, <, >, and " + */ + escape(): Sanitizer; + /** + * Remove common XSS attack vectors from user-supplied HTML + */ + xss(): Sanitizer; + /** + * Remove common XSS attack vectors from images + */ + xss(fromImages:boolean): Sanitizer; + } + } + + /** + * + * @middlewareOptions see: https://github.com/ctavan/express-validator#middleware-options + */ + function ExpressValidator(middlewareOptions?:any):express.RequestHandler; + + + export = ExpressValidator; } From 8badcfa1b3483d78cffe8740ddf974677a94b7e4 Mon Sep 17 00:00:00 2001 From: James Roland Cabresos Date: Wed, 6 Aug 2014 21:33:04 +0800 Subject: [PATCH 279/324] merge new contributors --- CONTRIBUTORS.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 330bda381..1b2eda33d 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -125,11 +125,8 @@ All definitions files include a header with the author and editors, so at some p * [highlight.js](https://github.com/isagalaev/highlight.js) (by [Niklas Mollenhauer](https://github.com/nikeee)) * [History.js](https://github.com/browserstate/history.js) (by [Boris Yankov](https://github.com/borisyankov)) * [Html2Canvas.js](https://github.com/niklasvh/html2canvas/) (by [Richard Hepburn](https://github.com/rwhepburn)) -<<<<<<< HEAD * [htmlparser2](https://github.com/fb55/htmlparser2/) (by [James Roland Cabresos](https://github.com/staticfunction)) -======= * [http-string-parser](https://github.com/apiaryio/http-string-parser) (by [MIZUNE Pine](https://github.com/pine613)) ->>>>>>> upstream/master * [Humane.js](http://wavded.github.com/humane-js/) (by [John Vrbanac](https://github.com/jmvrbanac)) * [i18next](http://i18next.com/) (by [Maarten Docter](https://github.com/mdocter)) * [iCheck](http://damirfoy.com/iCheck/) (by [Dániel Tar](https://github.com/qcz)) From 4b232a12142f0b4751f1e2da059a2bfebe9a4f78 Mon Sep 17 00:00:00 2001 From: Joe Herman Date: Wed, 6 Aug 2014 12:47:48 -0400 Subject: [PATCH 280/324] async: Corrected APIs from forEach* to each* --- async/async-tests.ts | 5 +++-- async/async.d.ts | 6 +++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/async/async-tests.ts b/async/async-tests.ts index 9b0c8e7ee..9a563276a 100644 --- a/async/async-tests.ts +++ b/async/async-tests.ts @@ -26,10 +26,11 @@ async.map(data, asyncProcess, function (err, results) { var openFiles = ['file1', 'file2']; var saveFile = function () { } -async.forEach(openFiles, saveFile, function (err) { }); +async.each(openFiles, saveFile, function (err) { }); +async.eachSeries(openFiles, saveFile, function (err) { }); var documents, requestApi; -async.forEachLimit(documents, 20, requestApi, function (err) { }); +async.eachLimit(documents, 20, requestApi, function (err) { }); async.map(['file1', 'file2', 'file3'], fs.stat, function (err, results) { }); diff --git a/async/async.d.ts b/async/async.d.ts index d1d592629..994ed1799 100644 --- a/async/async.d.ts +++ b/async/async.d.ts @@ -34,9 +34,9 @@ interface AsyncQueue { interface Async { // Collections - forEach(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; - forEachSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; - forEachLimit(arr: T[], limit: number, iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; + each(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; + eachSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; + eachLimit(arr: T[], limit: number, iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; map(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; mapSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; filter(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; From 53d09fb8068f66a6625580a793a8a4bfddb82c8e Mon Sep 17 00:00:00 2001 From: Evgenus Date: Wed, 6 Aug 2014 23:11:18 +0300 Subject: [PATCH 281/324] comments enhanced to jsDoc format --- bigint/bigint.d.ts | 364 ++++++++++++++++++++++++++++++--------------- 1 file changed, 245 insertions(+), 119 deletions(-) diff --git a/bigint/bigint.d.ts b/bigint/bigint.d.ts index 61543b1c6..b70f20fa4 100644 --- a/bigint/bigint.d.ts +++ b/bigint/bigint.d.ts @@ -13,233 +13,359 @@ declare module BigInt { export function setRandom(random: IRandom): void; - // bigInt add(x,y) - // return (x+y) for bigInts x and y. + /** + * bigInt add(x,y) + * return (x+y) for bigInts x and y. + */ export function add(x: BigInt, y: BigInt): BigInt; - // bigInt addInt(x,n) - // return (x+n) where x is a bigInt and n is an integer. + /** + * bigInt addInt(x,n) + * return (x+n) where x is a bigInt and n is an integer. + */ export function addInt(x: BigInt, n: number): BigInt; - // string bigInt2str(x,base) - // return a string form of bigInt x in a given base, with 2 <= base <= 95 - export function bigInt2str(x: BigInt, base: number): string; - export function bigInt2str(x: BigInt, base: string): string; + interface bigInt2str_T { + /** + * string bigInt2str(x,base) + * return a string form of bigInt x in a given base, with 2 <= base <= 95 + */ + (x: BigInt, base: T): string; + } - // int bitSize(x) - // return how many bits long the bigInt x is, not counting leading zeros + interface bigInt2strSignature extends bigInt2str_T, bigInt2str_T{ + } + + export var bigInt2str: bigInt2strSignature; + + /** + * int bitSize(x) + * return how many bits long the bigInt x is, not counting leading zeros + */ export function bitSize(x: BigInt): number; - // bigInt dup(x) - // return a copy of bigInt x + /** + * bigInt dup(x) + * return a copy of bigInt x + */ export function dup(x: BigInt): BigInt; - // boolean equals(x,y) - // is the bigInt x equal to the bigint y? + /** + * boolean equals(x,y) + * is the bigInt x equal to the bigint y? + */ export function equals(x: BigInt, y: BigInt): boolean; - // boolean equalsInt(x,y) - // is bigint x equal to integer y? + /** + * boolean equalsInt(x,y) + * is bigint x equal to integer y? + */ export function equalsInt(x: BigInt, y: number): boolean; - // bigInt expand(x,n) - // return a copy of x with at least n elements, adding leading zeros if needed + /** + * bigInt expand(x,n) + * return a copy of x with at least n elements, adding leading zeros if needed + */ export function expand(value: BigInt, n: number): BigInt; - // Array findPrimes(n) - // return array of all primes less than integer n + /** + * Array findPrimes(n) + * return array of all primes less than integer n + */ export function findPrimes(n: number): number[]; - // bigInt GCD(x,y) - // return greatest common divisor of bigInts x and y (each with same number of elements). + /** + * bigInt GCD(x,y) + * return greatest common divisor of bigInts x and y (each with same number of elements). + */ export function GCD(x: BigInt, y: BigInt): BigInt; - // boolean greater(x,y) - // is x>y? (x and y are nonnegative bigInts) + /** + * boolean greater(x,y) + * is x>y? (x and y are nonnegative bigInts) + */ export function greater(x: BigInt, y: BigInt): boolean; - // boolean greaterShift(x,y,shift) - // is (x <<(shift*bpe)) > y? + /** + * boolean greaterShift(x,y,shift) + * is (x <<(shift*bpe)) > y? + */ export function greaterShift(x: BigInt, y: BigInt, shift: number): boolean; - // bigInt int2bigInt(t,n,m) - // return a bigInt equal to integer t, with at least n bits and m array elements + /** + * bigInt int2bigInt(t,n,m) + * return a bigInt equal to integer t, with at least n bits and m array elements + */ export function int2bigInt(t: number, n?: number, m?: number): BigInt; - // bigInt inverseMod(x,n) - // return (x**(-1) mod n) for bigInts x and n. If no inverse exists, it returns null + /** + * bigInt inverseMod(x,n) + * return (x**(-1) mod n) for bigInts x and n. If no inverse exists, it returns null + */ export function inverseMod(x: BigInt, n: BigInt): BigInt; - // int inverseModInt(x,n) - // return x**(-1) mod n, for integers x and n. Return 0 if there is no inverse + /** + * int inverseModInt(x,n) + * return x**(-1) mod n, for integers x and n. Return 0 if there is no inverse + */ export function inverseModInt(x: number, n: number): BigInt; - // boolean isZero(x) - // is the bigInt x equal to zero? + /** + * boolean isZero(x) + * is the bigInt x equal to zero? + */ export function isZero(x: BigInt): boolean; - // boolean millerRabin(x,b) - // does one round of Miller-Rabin base integer b say that bigInt x is possibly prime? (b is bigInt, 1=1). If s=1, then the most significant of those n bits is set to 1. + /** + * bigInt randBigInt(n,s) + * return an n-bit random BigInt (n>=1). If s=1, then the most significant of those n bits is set to 1. + */ export function randBigInt(n: number, s: number): BigInt; - // bigInt randTruePrime(k) - // return a new, random, k-bit, true prime bigInt using Maurer's algorithm. + /** + * bigInt randTruePrime(k) + * return a new, random, k-bit, true prime bigInt using Maurer's algorithm. + */ export function randTruePrime(k: number): BigInt; - // bigInt randProbPrime(k) - // return a new, random, k-bit, probable prime bigInt (probability it's composite less than 2^-80). + /** + * bigInt randProbPrime(k) + * return a new, random, k-bit, probable prime bigInt (probability it's composite less than 2^-80). + */ export function randProbPrime(k: number): BigInt; - // bigInt str2bigInt(s,b,n,m) - // return a bigInt for number represented in string s in base b with at least n bits and m array elements - export function str2bigInt(s: string, b: number, n?: number, m?: number): BigInt; - export function str2bigInt(s: string, b: string, n?: number, m?: number): BigInt; + interface str2bigInt_T { + /** + * bigInt str2bigInt(s,b,n,m) + * return a bigInt for number represented in string s in base b with at least n bits and m array elements + */ + (s: string, b: T, n?: number, m?: number): BigInt; + } - // bigInt sub(x,y) - // return (x-y) for bigInts x and y. Negative answers will be 2s complement + interface str2bigIntSignature extends str2bigInt_T, str2bigInt_T { + } + + export var str2bigInt: str2bigIntSignature; + + /** + * bigInt sub(x,y) + * return (x-y) for bigInts x and y. Negative answers will be 2s complement + */ export function sub(x: BigInt, y: BigInt): BigInt; - // bigInt trim(x,k) - // return a copy of x with exactly k leading zero elements + /** + * bigInt trim(x,k) + * return a copy of x with exactly k leading zero elements + */ export function trim(x: BigInt, k: number): BigInt; - // void addInt_(x,n) - // do x=x+n where x is a bigInt and n is an integer + /** + * void addInt_(x,n) + * do x=x+n where x is a bigInt and n is an integer + */ export function addInt_(x: BigInt, n: number): void; - // void add_(x,y) - // do x=x+y for bigInts x and y + /** + * void add_(x,y) + * do x=x+y for bigInts x and y + */ export function add_(x: BigInt, y: BigInt): void; - // void copy_(x,y) - // do x=y on bigInts x and y + /** + * void copy_(x,y) + * do x=y on bigInts x and y + */ export function copy_(x: BigInt, y: BigInt): void; - // void copyInt_(x,n) - // do x=n on bigInt x and integer n + /** + * void copyInt_(x,n) + * do x=n on bigInt x and integer n + */ export function copyInt_(x: BigInt, n: number): number; - // void GCD_(x,y) - // set x to the greatest common divisor of bigInts x and y, (y is destroyed). (This never overflows its array). + /** + * void GCD_(x,y) + * set x to the greatest common divisor of bigInts x and y, (y is destroyed). (This never overflows its array). + */ export function GCD_(x: BigInt, y: BigInt): void; - // boolean inverseMod_(x,n) - // do x=x**(-1) mod n, for bigInts x and n. Returns 1 (0) if inverse does (doesn't) exist + /** + * boolean inverseMod_(x,n) + * do x=x**(-1) mod n, for bigInts x and n. Returns 1 (0) if inverse does (doesn't) exist + */ export function inverseMod_(x: BigInt, n: BigInt): boolean; - // void mod_(x,n) - // do x=x mod n for bigInts x and n. (This never overflows its array). + /** + * void mod_(x,n) + * do x=x mod n for bigInts x and n. (This never overflows its array). + */ export function mod_(x: BigInt, n: BigInt): void; - // void mult_(x,y) - // do x=x*y for bigInts x and y. + /** + * void mult_(x,y) + * do x=x*y for bigInts x and y. + */ export function mult_(x: BigInt, y: BigInt): void; - // void multMod_(x,y,n) - // do x=x*y mod n for bigInts x,y,n. + /** + * void multMod_(x,y,n) + * do x=x*y mod n for bigInts x,y,n. + */ export function multMod_(x: BigInt, y: BigInt, n: BigInt): void; - // void powMod_(x,y,n) - // do x=x**y mod n, where x,y,n are bigInts (n is odd) and ** is exponentiation. 0**0=1. + /** + * void powMod_(x,y,n) + * do x=x**y mod n, where x,y,n are bigInts (n is odd) and ** is exponentiation. 0**0=1. + */ export function powMod_(x: BigInt, y: BigInt, n: BigInt): void; - // void randBigInt_(b,n,s) - // do b = an n-bit random BigInt. if s=1, then nth bit (most significant bit) is set to 1. n>=1. + /** + * void randBigInt_(b,n,s) + * do b = an n-bit random BigInt. if s=1, then nth bit (most significant bit) is set to 1. n>=1. + */ export function randBigInt_(b: BigInt, n: number, s: number): void; - // void randTruePrime_(ans,k) - // do ans = a random k-bit true random prime (not just probable prime) with 1 in the msb. + /** + * void randTruePrime_(ans,k) + * do ans = a random k-bit true random prime (not just probable prime) with 1 in the msb. + */ export function randTruePrime_(ans: BigInt, k: number): void; - // void sub_(x,y) - // do x=x-y for bigInts x and y. Negative answers will be 2s complement. + /** + * void sub_(x,y) + * do x=x-y for bigInts x and y. Negative answers will be 2s complement. + */ export function sub_(x: BigInt, y: BigInt): void; - // void addShift_(x,y,ys) - // do x=x+(y<<(ys*bpe)) + /** + * void addShift_(x,y,ys) + * do x=x+(y<<(ys*bpe)) + */ export function addShift_(x: BigInt, y: BigInt, ys: number): void; - // void carry_(x) - // do carries and borrows so each element of the bigInt x fits in bpe bits. + /** + * void carry_(x) + * do carries and borrows so each element of the bigInt x fits in bpe bits. + */ export function carry_(x: BigInt): void; - // void divide_(x,y,q,r) - // divide x by y giving quotient q and remainder r + /** + * void divide_(x,y,q,r) + * divide x by y giving quotient q and remainder r + */ export function divide_(x: BigInt, y: BigInt, q: BigInt, r: BigInt): void; - // int divInt_(x,n) - // do x=floor(x/n) for bigInt x and integer n, and return the remainder. (This never overflows its array). + /** + * int divInt_(x,n) + * do x=floor(x/n) for bigInt x and integer n, and return the remainder. (This never overflows its array). + */ export function divInt_(x: BigInt, n: number): number; - // void eGCD_(x,y,d,a,b) - // sets a,b,d to positive bigInts such that d = GCD_(x,y) = a*x-b*y + /** + * void eGCD_(x,y,d,a,b) + * sets a,b,d to positive bigInts such that d = GCD_(x,y) = a*x-b*y + */ export function eGCD_(x: BigInt, y: BigInt, d: BigInt, a: BigInt, b: BigInt): void; - // void halve_(x) - // do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement. (This never overflows its array). + /** + * void halve_(x) + * do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement. (This never overflows its array). + */ export function halve_(x: BigInt): void; - // void leftShift_(x,n) - // left shift bigInt x by n bits. n Date: Wed, 6 Aug 2014 15:33:20 -0700 Subject: [PATCH 282/324] d3: Typed Scale interface to remove duplicate code --- d3/d3.d.ts | 199 ++++++++--------------------------------------------- 1 file changed, 29 insertions(+), 170 deletions(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 8f66f47a6..619d2bb36 100755 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -1648,13 +1648,13 @@ declare module D3 { /** * Gets the x-scale associated with the brush */ - (): D3.Scale.Scale; + (): D3.Scale.UntypedScale; /** * Sets the x-scale associated with the brush * * @param accessor The new Scale */ - (scale: D3.Scale.Scale): Brush; + (scale: D3.Scale.UntypedScale): Brush; }; /** * Gets or sets the x-scale associated with the brush @@ -1663,13 +1663,13 @@ declare module D3 { /** * Gets the x-scale associated with the brush */ - (): D3.Scale.Scale; + (): D3.Scale.UntypedScale; /** * Sets the x-scale associated with the brush * * @param accessor The new Scale */ - (scale: D3.Scale.Scale): Brush; + (scale: D3.Scale.UntypedScale): Brush; }; /** * Gets or sets the current brush extent @@ -2518,21 +2518,23 @@ declare module D3 { threshold(): ThresholdScale; } - export interface Scale { + export interface Scale { (value: any): any; domain: { - (values: any[]): Scale; + (values: any[]): S; (): any[]; }; range: { - (values: any[]): Scale; + (values: any[]): S; (): any[]; }; invertExtent?(y: any): any[]; - copy(): Scale; + copy(): S; } - export interface QuantitativeScale extends Scale { + export interface UntypedScale extends Scale { } + + export interface QuantitativeScale extends Scale { /** * Get the range value corresponding to a given domain value. * @@ -2546,47 +2548,17 @@ declare module D3 { */ invert(value: number): number; /** - * Get or set the scale's input domain. - */ - domain: { - /** - * Set the scale's input domain. - * - * @param value The input domain - */ - (values: any[]): QuantitativeScale; - /** - * Get the scale's input domain. - */ - (): any[]; - }; - /** - * get or set the scale's output range. - */ - range: { - /** - * Set the scale's output range. - * - * @param value The output range. - */ - (values: any[]): QuantitativeScale; - /** - * Get the scale's output range. - */ - (): any[]; - }; - /** * Set the scale's output range, and enable rounding. * * @param value The output range. */ - rangeRound: (values: any[]) => QuantitativeScale; + rangeRound: (values: any[]) => S; /** * get or set the scale's output interpolator. */ interpolate: { (): D3.Transition.Interpolate; - (factory: D3.Transition.Interpolate): QuantitativeScale; + (factory: D3.Transition.Interpolate): S; }; /** * enable or disable clamping of the output range. @@ -2595,14 +2567,14 @@ declare module D3 { */ clamp: { (): boolean; - (clamp: boolean): QuantitativeScale; + (clamp: boolean): S; } /** * extend the scale domain to nice round numbers. * * @param count Optional number of ticks to exactly fit the domain */ - nice(count?: number): QuantitativeScale; + nice(count?: number): S; /** * get representative values from the input domain. * @@ -2615,22 +2587,11 @@ declare module D3 { * @param count Aproximate representative values to return */ tickFormat(count: number, format?: string): (n: number) => string; - /** - * create a new scale from an existing scale.. - */ - copy(): QuantitativeScale; } - export interface LinearScale extends QuantitativeScale { - /** - * Get the range value corresponding to a given domain value. - * - * @param value Domain Value - */ - (value: number): number; - } + export interface LinearScale extends QuantitativeScale { } - export interface IdentityScale extends Scale { + export interface IdentityScale extends Scale { /** * Get the range value corresponding to a given domain value. * @@ -2657,132 +2618,31 @@ declare module D3 { tickFormat(count: number): (n: number) => string; } - export interface SqrtScale extends QuantitativeScale { - /** - * Get the range value corresponding to a given domain value. - * - * @param value Domain Value - */ - (value: number): number; - } + export interface SqrtScale extends QuantitativeScale { } - export interface PowScale extends QuantitativeScale { - /** - * Get the range value corresponding to a given domain value. - * - * @param value Domain Value - */ - (value: number): number; - } + export interface PowScale extends QuantitativeScale { } - export interface LogScale extends QuantitativeScale { - /** - * Get the range value corresponding to a given domain value. - * - * @param value Domain Value - */ - (value: number): number; - } + export interface LogScale extends QuantitativeScale { } - export interface OrdinalScale extends Scale { - /** - * Get the range value corresponding to a given domain value. - * - * @param value Domain Value - */ - (value: any): any; - /** - * Get or set the scale's input domain. - */ - domain: { - /** - * Set the scale's input domain. - * - * @param value The input domain - */ - (values: any[]): OrdinalScale; - /** - * Get the scale's input domain. - */ - (): any[]; - }; - /** - * get or set the scale's output range. - */ - range: { - /** - * Set the scale's output range. - * - * @param value The output range. - */ - (values: any[]): OrdinalScale; - /** - * Get the scale's output range. - */ - (): any[]; - }; + export interface OrdinalScale extends Scale { rangePoints(interval: any[], padding?: number): OrdinalScale; rangeBands(interval: any[], padding?: number, outerPadding?: number): OrdinalScale; rangeRoundBands(interval: any[], padding?: number, outerPadding?: number): OrdinalScale; rangeBand(): number; rangeExtent(): any[]; - /** - * create a new scale from an existing scale.. - */ - copy(): OrdinalScale; } - export interface QuantizeScale extends Scale { - (value: any): any; - domain: { - (values: number[]): QuantizeScale; - (): any[]; - }; - range: { - (values: any[]): QuantizeScale; - (): any[]; - }; - copy(): QuantizeScale; - } + export interface QuantizeScale extends Scale { } - export interface ThresholdScale extends Scale { - (value: any): any; - domain: { - (values: number[]): ThresholdScale; - (): any[]; - }; - range: { - (values: any[]): ThresholdScale; - (): any[]; - }; - copy(): ThresholdScale; - } + export interface ThresholdScale extends Scale { } - export interface QuantileScale extends Scale { - (value: any): any; - domain: { - (values: number[]): QuantileScale; - (): any[]; - }; - range: { - (values: any[]): QuantileScale; - (): any[]; - }; + export interface QuantileScale extends Scale { quantiles(): any[]; - copy(): QuantileScale; } - export interface TimeScale extends Scale { + export interface TimeScale extends Scale { (value: Date): number; invert(value: number): Date; - domain: { - (values: any[]): TimeScale; - (): any[]; - }; - range: { - (values: any[]): TimeScale; - (): any[]; - }; rangeRound: (values: any[]) => TimeScale; interpolate: { (): D3.Transition.Interpolate; @@ -2794,7 +2654,6 @@ declare module D3 { (range: D3.Time.Range, count: number): any[]; }; tickFormat(count: number): (n: number) => string; - copy(): TimeScale; nice(count?: number): TimeScale; } } @@ -2883,13 +2742,13 @@ declare module D3 { /** * Get the X-Scale */ - (): D3.Scale.Scale; + (): D3.Scale.UntypedScale; /** * Set the X-Scale to be adjusted * * @param x The X Scale */ - (x: D3.Scale.Scale): Zoom; + (x: D3.Scale.UntypedScale): Zoom; }; @@ -2900,13 +2759,13 @@ declare module D3 { /** * Get the Y-Scale */ - (): D3.Scale.Scale; + (): D3.Scale.UntypedScale; /** * Set the Y-Scale to be adjusted * * @param y The Y Scale */ - (y: D3.Scale.Scale): Zoom; + (y: D3.Scale.UntypedScale): Zoom; }; } From 435aaa1ddfb734d1a9dd7bf7b1b6e6b018c3bd18 Mon Sep 17 00:00:00 2001 From: Atsushi Kanehara Date: Thu, 7 Aug 2014 15:01:57 +0900 Subject: [PATCH 283/324] Added property upgradeReq --- ws/ws.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/ws/ws.d.ts b/ws/ws.d.ts index d12e2913f..99983df85 100644 --- a/ws/ws.d.ts +++ b/ws/ws.d.ts @@ -21,6 +21,7 @@ declare module "ws" { protocolVersion: string; url: string; supports: any; + upgradeReq: http.ServerRequest; CONNECTING: number; OPEN: number; From 9a4229df7e1d20ae547bd37b92d7e961cfbfe4f9 Mon Sep 17 00:00:00 2001 From: vvakame Date: Thu, 7 Aug 2014 15:50:27 +0900 Subject: [PATCH 284/324] fix -test.ts to -tests.ts --- bucks/{bucks-test.ts => bucks-tests.ts} | 0 .../{http-string-parser-test.ts => http-string-parser-tests.ts} | 0 .../{jquery.notifyBar-test.ts => jquery.notifyBar-tests.ts} | 0 js-git/{js-git-test.ts => js-git-tests.ts} | 0 js-url/{js-url-test.ts => js-url-tests.ts} | 0 .../{passport-facebook-test.ts => passport-facebook-tests.ts} | 0 .../{passport-strategy-test.ts => passport-strategy-tests.ts} | 0 riotjs/{riotjs-test.ts => riotjs-tests.ts} | 0 .../{simple-cw-node-test.ts => simple-cw-node-tests.ts} | 0 tspromise/{tspromise-test.ts => tspromise-tests.ts} | 0 .../{universal-analytics-test.ts => universal-analytics-tests.ts} | 0 11 files changed, 0 insertions(+), 0 deletions(-) rename bucks/{bucks-test.ts => bucks-tests.ts} (100%) rename http-string-parser/{http-string-parser-test.ts => http-string-parser-tests.ts} (100%) rename jquery.notifyBar/{jquery.notifyBar-test.ts => jquery.notifyBar-tests.ts} (100%) rename js-git/{js-git-test.ts => js-git-tests.ts} (100%) rename js-url/{js-url-test.ts => js-url-tests.ts} (100%) rename passport-facebook/{passport-facebook-test.ts => passport-facebook-tests.ts} (100%) rename passport-strategy/{passport-strategy-test.ts => passport-strategy-tests.ts} (100%) rename riotjs/{riotjs-test.ts => riotjs-tests.ts} (100%) rename simple-cw-node/{simple-cw-node-test.ts => simple-cw-node-tests.ts} (100%) rename tspromise/{tspromise-test.ts => tspromise-tests.ts} (100%) rename universal-analytics/{universal-analytics-test.ts => universal-analytics-tests.ts} (100%) diff --git a/bucks/bucks-test.ts b/bucks/bucks-tests.ts similarity index 100% rename from bucks/bucks-test.ts rename to bucks/bucks-tests.ts diff --git a/http-string-parser/http-string-parser-test.ts b/http-string-parser/http-string-parser-tests.ts similarity index 100% rename from http-string-parser/http-string-parser-test.ts rename to http-string-parser/http-string-parser-tests.ts diff --git a/jquery.notifyBar/jquery.notifyBar-test.ts b/jquery.notifyBar/jquery.notifyBar-tests.ts similarity index 100% rename from jquery.notifyBar/jquery.notifyBar-test.ts rename to jquery.notifyBar/jquery.notifyBar-tests.ts diff --git a/js-git/js-git-test.ts b/js-git/js-git-tests.ts similarity index 100% rename from js-git/js-git-test.ts rename to js-git/js-git-tests.ts diff --git a/js-url/js-url-test.ts b/js-url/js-url-tests.ts similarity index 100% rename from js-url/js-url-test.ts rename to js-url/js-url-tests.ts diff --git a/passport-facebook/passport-facebook-test.ts b/passport-facebook/passport-facebook-tests.ts similarity index 100% rename from passport-facebook/passport-facebook-test.ts rename to passport-facebook/passport-facebook-tests.ts diff --git a/passport-strategy/passport-strategy-test.ts b/passport-strategy/passport-strategy-tests.ts similarity index 100% rename from passport-strategy/passport-strategy-test.ts rename to passport-strategy/passport-strategy-tests.ts diff --git a/riotjs/riotjs-test.ts b/riotjs/riotjs-tests.ts similarity index 100% rename from riotjs/riotjs-test.ts rename to riotjs/riotjs-tests.ts diff --git a/simple-cw-node/simple-cw-node-test.ts b/simple-cw-node/simple-cw-node-tests.ts similarity index 100% rename from simple-cw-node/simple-cw-node-test.ts rename to simple-cw-node/simple-cw-node-tests.ts diff --git a/tspromise/tspromise-test.ts b/tspromise/tspromise-tests.ts similarity index 100% rename from tspromise/tspromise-test.ts rename to tspromise/tspromise-tests.ts diff --git a/universal-analytics/universal-analytics-test.ts b/universal-analytics/universal-analytics-tests.ts similarity index 100% rename from universal-analytics/universal-analytics-test.ts rename to universal-analytics/universal-analytics-tests.ts From 54d719d86ed92466b02f3020f0e510145db02f9d Mon Sep 17 00:00:00 2001 From: Antoine Pultier Date: Thu, 7 Aug 2014 10:42:05 +0200 Subject: [PATCH 285/324] [Leaflet] Optional context argument in L.DomEvent.removeListener --- leaflet/leaflet.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 3332f9000..006d16c1e 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -574,7 +574,7 @@ declare module L { /** * Removes an event listener from the element. */ - static removeListener(el: HTMLElement, type: string, fn: (e: Event) => void): DomEvent; + static removeListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; /** * Stop the given event from propagation to parent elements. Used inside the From c1858577da71e678d994179dbe65c81258e7dc85 Mon Sep 17 00:00:00 2001 From: Antoine Pultier Date: Thu, 7 Aug 2014 10:42:43 +0200 Subject: [PATCH 286/324] [Leaflet] on and off alias for L.DomEvent --- leaflet/leaflet.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 006d16c1e..a1276cbe9 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -570,11 +570,13 @@ declare module L { * inside the listener will point to context, or to the element if not specified. */ static addListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; + static on(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; /** * Removes an event listener from the element. */ static removeListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; + static off(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; /** * Stop the given event from propagation to parent elements. Used inside the From 5f62479f18b6b2d80e8e213d5afca562a64d735f Mon Sep 17 00:00:00 2001 From: James Roland Cabresos Date: Thu, 7 Aug 2014 21:10:37 +0800 Subject: [PATCH 287/324] Rename htmlparser2tests.ts to htmlparser2-tests.ts --- htmlparser2/{htmlparser2tests.ts => htmlparser2-tests.ts} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename htmlparser2/{htmlparser2tests.ts => htmlparser2-tests.ts} (97%) diff --git a/htmlparser2/htmlparser2tests.ts b/htmlparser2/htmlparser2-tests.ts similarity index 97% rename from htmlparser2/htmlparser2tests.ts rename to htmlparser2/htmlparser2-tests.ts index 7ff887e65..c002da0e2 100644 --- a/htmlparser2/htmlparser2tests.ts +++ b/htmlparser2/htmlparser2-tests.ts @@ -21,4 +21,4 @@ var parser = new htmlparser.Parser({ }); parser.write("Xyz "); -parser.end(); \ No newline at end of file +parser.end(); From fcfe9fee87ea637598c57fe3ed07bb7b33a70359 Mon Sep 17 00:00:00 2001 From: Steven Date: Thu, 7 Aug 2014 18:24:19 -0700 Subject: [PATCH 288/324] Color.brighter has an optional number parameter --- d3/d3.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 8f66f47a6..4b7f91ad7 100755 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -1492,7 +1492,7 @@ declare module D3 { /** * increase lightness by some exponential factor (gamma) */ - brighter(k: number): Color; + brighter(k?: number): Color; /** * decrease lightness by some exponential factor (gamma) */ From cc05933bbc0b8a7994ff743a33805218226ed5bc Mon Sep 17 00:00:00 2001 From: James Roland Cabresos Date: Fri, 8 Aug 2014 10:22:24 +0800 Subject: [PATCH 289/324] fix htmlparser tests --- htmlparser2/htmlparser2-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htmlparser2/htmlparser2-tests.ts b/htmlparser2/htmlparser2-tests.ts index c002da0e2..53f6ee2aa 100644 --- a/htmlparser2/htmlparser2-tests.ts +++ b/htmlparser2/htmlparser2-tests.ts @@ -6,7 +6,7 @@ import htmlparser = require("htmlparser2"); var parser = new htmlparser.Parser({ onopentag: (name:string, attribs:{[s:string]:string}) => { - if(name === "script" && attribs.type === "text/javascript"){ + if(name === "script" && attribs['type'] === "text/javascript"){ console.log("JS! Hooray!"); } }, From ad0059764af8e64555d9ddecebcbe62c7b1204db Mon Sep 17 00:00:00 2001 From: VILIC VANE Date: Fri, 8 Aug 2014 12:05:20 +0800 Subject: [PATCH 290/324] add Q.delay(ms: number) --- q/Q.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/q/Q.d.ts b/q/Q.d.ts index 617bf0140..90ec8b461 100644 --- a/q/Q.d.ts +++ b/q/Q.d.ts @@ -294,7 +294,10 @@ declare module Q { * Returns a promise that will have the same result as promise, but will only be fulfilled or rejected after at least ms milliseconds have passed. */ export function delay(value: T, ms: number): Promise; - + /** + * Returns a promise that will be fulfilled with undefined after at least ms milliseconds have passed. + */ + export function delay(ms: number): Promise ; /** * Returns whether a given promise is in the fulfilled state. When the static version is used on non-promises, the result is always true. */ From fa83d0d39c561d98454f72ffc0e32a741a2c7994 Mon Sep 17 00:00:00 2001 From: Benjamin Cosman Date: Thu, 7 Aug 2014 21:50:52 -0700 Subject: [PATCH 291/324] d3: Changed Scale names for consistency --- d3/d3.d.ts | 44 +++++++++++++++++++++++--------------------- 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 619d2bb36..07f071647 100755 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -1648,13 +1648,13 @@ declare module D3 { /** * Gets the x-scale associated with the brush */ - (): D3.Scale.UntypedScale; + (): D3.Scale.Scale; /** * Sets the x-scale associated with the brush * * @param accessor The new Scale */ - (scale: D3.Scale.UntypedScale): Brush; + (scale: D3.Scale.Scale): Brush; }; /** * Gets or sets the x-scale associated with the brush @@ -1663,13 +1663,13 @@ declare module D3 { /** * Gets the x-scale associated with the brush */ - (): D3.Scale.UntypedScale; + (): D3.Scale.Scale; /** * Sets the x-scale associated with the brush * * @param accessor The new Scale */ - (scale: D3.Scale.UntypedScale): Brush; + (scale: D3.Scale.Scale): Brush; }; /** * Gets or sets the current brush extent @@ -2518,7 +2518,7 @@ declare module D3 { threshold(): ThresholdScale; } - export interface Scale { + export interface GenericScale { (value: any): any; domain: { (values: any[]): S; @@ -2532,9 +2532,9 @@ declare module D3 { copy(): S; } - export interface UntypedScale extends Scale { } + export interface Scale extends GenericScale { } - export interface QuantitativeScale extends Scale { + export interface GenericQuantitativeScale extends GenericScale { /** * Get the range value corresponding to a given domain value. * @@ -2589,9 +2589,11 @@ declare module D3 { tickFormat(count: number, format?: string): (n: number) => string; } - export interface LinearScale extends QuantitativeScale { } + export interface QuantitativeScale extends GenericQuantitativeScale { } - export interface IdentityScale extends Scale { + export interface LinearScale extends GenericQuantitativeScale { } + + export interface IdentityScale extends GenericScale { /** * Get the range value corresponding to a given domain value. * @@ -2618,13 +2620,13 @@ declare module D3 { tickFormat(count: number): (n: number) => string; } - export interface SqrtScale extends QuantitativeScale { } + export interface SqrtScale extends GenericQuantitativeScale { } - export interface PowScale extends QuantitativeScale { } + export interface PowScale extends GenericQuantitativeScale { } - export interface LogScale extends QuantitativeScale { } + export interface LogScale extends GenericQuantitativeScale { } - export interface OrdinalScale extends Scale { + export interface OrdinalScale extends GenericScale { rangePoints(interval: any[], padding?: number): OrdinalScale; rangeBands(interval: any[], padding?: number, outerPadding?: number): OrdinalScale; rangeRoundBands(interval: any[], padding?: number, outerPadding?: number): OrdinalScale; @@ -2632,15 +2634,15 @@ declare module D3 { rangeExtent(): any[]; } - export interface QuantizeScale extends Scale { } + export interface QuantizeScale extends GenericScale { } - export interface ThresholdScale extends Scale { } + export interface ThresholdScale extends GenericScale { } - export interface QuantileScale extends Scale { + export interface QuantileScale extends GenericScale { quantiles(): any[]; } - export interface TimeScale extends Scale { + export interface TimeScale extends GenericScale { (value: Date): number; invert(value: number): Date; rangeRound: (values: any[]) => TimeScale; @@ -2742,13 +2744,13 @@ declare module D3 { /** * Get the X-Scale */ - (): D3.Scale.UntypedScale; + (): D3.Scale.Scale; /** * Set the X-Scale to be adjusted * * @param x The X Scale */ - (x: D3.Scale.UntypedScale): Zoom; + (x: D3.Scale.Scale): Zoom; }; @@ -2759,13 +2761,13 @@ declare module D3 { /** * Get the Y-Scale */ - (): D3.Scale.UntypedScale; + (): D3.Scale.Scale; /** * Set the Y-Scale to be adjusted * * @param y The Y Scale */ - (y: D3.Scale.UntypedScale): Zoom; + (y: D3.Scale.Scale): Zoom; }; } From 2f1b69b353b7feea498ce886abf059018131ddd3 Mon Sep 17 00:00:00 2001 From: Daniel Mane Date: Thu, 7 Aug 2014 22:36:44 -0700 Subject: [PATCH 292/324] Add missing properties to definitions for D3.set and D3.map. Paramaterize the function type for Set.add --- d3/d3.d.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 8f66f47a6..e6f26cbd5 100755 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -848,14 +848,18 @@ declare module D3 { values(): Array; entries(): Array; forEach(func: (key: string, value: any) => void ): void; + empty(): boolean; + size(): number; } - export interface Set{ + export interface Set { has(value: any): boolean; - add(value: any): any; + add(value: T): T; remove(value: any): boolean; values(): Array; forEach(func: (value: any) => void ): void; + empty(): boolean; + size(): number; } export interface Random { From 3994e6d6a4da8d0b5c13d5f84653c0e28c4c12dd Mon Sep 17 00:00:00 2001 From: Eraknelo Date: Fri, 8 Aug 2014 15:45:39 +0200 Subject: [PATCH 293/324] Capitalization error http://msdn.microsoft.com/en-us/library/office/jj245318(v=office.15).aspx --- sharepoint/SharePoint.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sharepoint/SharePoint.d.ts b/sharepoint/SharePoint.d.ts index 1f7a2feaf..0be396fe6 100644 --- a/sharepoint/SharePoint.d.ts +++ b/sharepoint/SharePoint.d.ts @@ -4573,7 +4573,7 @@ declare module SP { get_id(): number; get_information(): SP.TimeZoneInformation; localTimeToUTC(date: Date): SP.DateTimeResult; - uTCToLocalTime(date: Date): SP.DateTimeResult; + utcToLocalTime(date: Date): SP.DateTimeResult; } export class TimeZoneCollection extends SP.ClientObjectCollection { itemAt(index: number): SP.TimeZone; From 82447ac01078f1f5d9b25ea27712c3317f94adde Mon Sep 17 00:00:00 2001 From: Paulo Cesar Date: Fri, 8 Aug 2014 12:24:43 -0300 Subject: [PATCH 294/324] squash! fix tabs directive interface definition and tests --- angularjs/angular-tests.ts | 32 +++++++++++++++++--------------- angularjs/angular.d.ts | 19 ++++++++++--------- 2 files changed, 27 insertions(+), 24 deletions(-) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 9c1cc0ab4..220a63dec 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -285,15 +285,17 @@ class SampleDirective implements ng.IDirective { public restrict = 'A'; name = 'doh'; - compile(templateElement: any) { - return this.link; + compile(templateElement: ng.IAugmentedJQuery) { + return { + post: this.link + }; } static instance():ng.IDirective { return new SampleDirective(); } - link(scope: any) { + link(scope: ng.IScope) { } } @@ -301,7 +303,7 @@ class SampleDirective implements ng.IDirective { class SampleDirective2 implements ng.IDirective { public restrict = 'EAC'; - compile(templateElement: any) { + compile(templateElement: ng.IAugmentedJQuery) { return { pre: this.link }; @@ -311,7 +313,7 @@ class SampleDirective2 implements ng.IDirective { return new SampleDirective2(); } - link(scope: any) { + link(scope: ng.IScope) { } } @@ -413,10 +415,10 @@ angular.module('docsTimeDirective', []) .controller('Controller', ['$scope', function($scope: any) { $scope.format = 'M/d/yy h:mm:ss a'; }]) - .directive('myCurrentTime', ['$interval', 'dateFilter', function($interval: any, dateFilter: any): ng.IDirective { + .directive('myCurrentTime', ['$interval', 'dateFilter', function($interval: any, dateFilter: any) { return { - link: function(scope: any, element: any, attrs: any) { + link: function(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs:ng.IAttributes) { var format: any, timeoutId: any; @@ -424,7 +426,7 @@ angular.module('docsTimeDirective', []) element.text(dateFilter(new Date(), format)); } - scope.$watch(attrs.myCurrentTime, function (value: any) { + scope.$watch(attrs['myCurrentTime'], function (value: any) { format = value; updateTime(); }); @@ -463,8 +465,8 @@ angular.module('docsTransclusionExample', []) transclude: true, scope: {}, templateUrl: 'my-dialog.html', - link: function (scope: any, element: any) { - scope.name = 'Jeff'; + link: function (scope: ng.IScope, element: ng.IAugmentedJQuery) { + scope['name'] = 'Jeff'; } }; }); @@ -533,10 +535,10 @@ angular.module('docsTabsExample', []) restrict: 'E', transclude: true, scope: {}, - controller: function($scope: any) { - var panes: any = $scope.panes = []; + controller: function($scope: ng.IScope) { + var panes: any = $scope['panes'] = []; - $scope.select = function(pane: any) { + $scope['select'] = function(pane: any) { angular.forEach(panes, function(pane: any) { pane.selected = false; }); @@ -545,7 +547,7 @@ angular.module('docsTabsExample', []) this.addPane = function(pane: any) { if (panes.length === 0) { - $scope.select(pane); + $scope['select'](pane); } panes.push(pane); }; @@ -561,7 +563,7 @@ angular.module('docsTabsExample', []) scope: { title: '@' }, - link: function(scope: any, element: any, attrs: any, tabsCtrl: any) { + link: function(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, tabsCtrl: any) { tabsCtrl.addPane(scope); }, templateUrl: 'my-pane.html' diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 83dcc151f..282463bcb 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -316,6 +316,7 @@ declare module ng { // see http://docs.angularjs.org/api/ng.$rootScope.Scope /////////////////////////////////////////////////////////////////////////// interface IScope { + [index: string]: any; $apply(): any; $apply(exp: string): any; $apply(exp: (scope: IScope) => any): any; @@ -1033,11 +1034,11 @@ declare module ng { interface IDirectiveLinkFn { ( - scope?: IScope, - instanceElement?: IAugmentedJQuery, - instanceAttributes?: IAttributes, - controller?: any, - transclude?: ITranscludeFunction + scope: IScope, + instanceElement: IAugmentedJQuery, + instanceAttributes: IAttributes, + controller: any, + transclude: ITranscludeFunction ): void; } @@ -1048,13 +1049,13 @@ declare module ng { interface IDirectiveCompileFn { ( - templateElement?: IAugmentedJQuery, - templateAttributes?: IAttributes, - transclude?: ITranscludeFunction + templateElement: IAugmentedJQuery, + templateAttributes: IAttributes, + transclude: ITranscludeFunction ): IDirectivePrePost; } - interface IDirective{ + interface IDirective { compile?: IDirectiveCompileFn; controller?: any; controllerAs?: string; From 2736551e5a150dd42818ad5c5c755778802657f1 Mon Sep 17 00:00:00 2001 From: Asger Feldthaus Date: Fri, 8 Aug 2014 17:42:16 +0200 Subject: [PATCH 295/324] Various fixes in three.d.ts --- threejs/three.d.ts | 421 ++++++++++++++++++++------------------------- 1 file changed, 190 insertions(+), 231 deletions(-) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 41a07f32b..55ecde323 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -413,7 +413,7 @@ declare module THREE { */ id: number; - uuid: number; + uuid: string; name: string; attributes: BufferAttribute[]; drawcalls: { start: number; count: number; index: number; }[]; @@ -944,7 +944,7 @@ declare module THREE { /** * */ - uuid: number; + uuid: string; /** * Optional name of the object (doesn't need to be unique). @@ -1053,11 +1053,6 @@ declare module THREE { eulerOrder: string; // eulerOrder:EulerOrder; - /** - * Use quaternion instead of Euler angles for specifying local rotation. - */ - useQuaternion: boolean; - /** * This updates the position, rotation and scale with the matrix. */ @@ -1743,15 +1738,6 @@ declare module THREE { } - export class GeometryLoader { - constructor(manager?: LoadingManager); - - load(url: string, onLoad: (bufferGeometry: BufferGeometry) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; - setCrossOrigin(crossOrigin: string): void; - parse(json: any): Geometry; - - } - export class Cache{ constructor(); @@ -1797,7 +1783,7 @@ declare module THREE { } - export class JSonLoaderResultGeometry extends Geometry { + export interface JSonLoaderResultGeometry extends Geometry { animation: AnimationData; } @@ -1830,7 +1816,7 @@ declare module THREE { } - export class MaterialLoader extends EventDispatcher { + export class MaterialLoader { constructor(manager?: LoadingManager); load(url: string, onLoad: (material: Material) => void): void; @@ -1838,7 +1824,7 @@ declare module THREE { parse(json: any): Material; } - export class ObjectLoader extends EventDispatcher { + export class ObjectLoader { constructor(manager?: LoadingManager); load(url: string, onLoad: (object: Object3D) => void): void; @@ -1853,7 +1839,7 @@ declare module THREE { * Class for loading a texture. * Unlike other loaders, this one emits events instead of using predefined callbacks. So if you're interested in getting notified when things happen, you need to add listeners to the object. */ - export class TextureLoader extends EventDispatcher { + export class TextureLoader { constructor(manager?: LoadingManager); crossOrigin: string; /** @@ -1865,7 +1851,7 @@ declare module THREE { setCrossOrigin(crossOrigin: string): void; } - export class XHRLoader extends EventDispatcher { + export class XHRLoader { constructor(manager?: LoadingManager); cache: Cache; @@ -1958,9 +1944,9 @@ declare module THREE { alphaTest: number; /** - * Enables/disables overdraw. If enabled, polygons are drawn slightly bigger in order to fix antialiasing gaps when using the CanvasRenderer. Default is false. + * Enables/disables overdraw. If greater than zero, polygons are drawn slightly bigger in order to fix antialiasing gaps when using the CanvasRenderer. Default is 0. */ - overdraw: boolean; + overdraw: number; /** * Defines whether this material is visible. Default is true. @@ -2093,7 +2079,7 @@ declare module THREE { clone(): MeshDepthMaterial; } - export class MeshFaceMaterial extends Material { + export class MeshFaceMaterial { constructor(materials?: Material[]); materials: Material[]; @@ -2552,154 +2538,153 @@ declare module THREE { } export class ColorKeywords { - static test2: string; - static aliceblue: string; - static antiquewhite: string; - static aqua: string; - static aquamarine: string; - static azure: string; - static beige: string; - static bisque: string; - static black: string; - static blanchedalmond: string; - static blue: string; - static blueviolet: string; - static brown: string; - static burlywood: string; - static cadetblue: string; - static chartreuse: string; - static chocolate: string; - static coral: string; - static cornflowerblue: string; - static cornsilk: string; - static crimson: string; - static cyan: string; - static darkblue: string; - static darkcyan: string; - static darkgoldenrod: string; - static darkgray: string; - static darkgreen: string; - static darkgrey: string; - static darkkhaki: string; - static darkmagenta: string; - static darkolivegreen: string; - static darkorange: string; - static darkorchid: string; - static darkred: string; - static darksalmon: string; - static darkseagreen: string; - static darkslateblue: string; - static darkslategray: string; - static darkslategrey: string; - static darkturquoise: string; - static darkviolet: string; - static deeppink: string; - static deepskyblue: string; - static dimgray: string; - static dimgrey: string; - static dodgerblue: string; - static firebrick: string; - static floralwhite: string; - static forestgreen: string; - static fuchsia: string; - static gainsboro: string; - static ghostwhite: string; - static gold: string; - static goldenrod: string; - static gray: string; - static green: string; - static greenyellow: string; - static grey: string; - static honeydew: string; - static hotpink: string; - static indianred: string; - static indigo: string; - static ivory: string; - static khaki: string; - static lavender: string; - static lavenderblush: string; - static lawngreen: string; - static lemonchiffon: string; - static lightblue: string; - static lightcoral: string; - static lightcyan: string; - static lightgoldenrodyellow: string; - static lightgray: string; - static lightgreen: string; - static lightgrey: string; - static lightpink: string; - static lightsalmon: string; - static lightseagreen: string; - static lightskyblue: string; - static lightslategray: string; - static lightslategrey: string; - static lightsteelblue: string; - static lightyellow: string; - static lime: string; - static limegreen: string; - static linen: string; - static magenta: string; - static maroon: string; - static mediumaquamarine: string; - static mediumblue: string; - static mediumorchid: string; - static mediumpurple: string; - static mediumseagreen: string; - static mediumslateblue: string; - static mediumspringgreen: string; - static mediumturquoise: string; - static mediumvioletred: string; - static midnightblue: string; - static mintcream: string; - static mistyrose: string; - static moccasin: string; - static navajowhite: string; - static navy: string; - static oldlace: string; - static olive: string; - static olivedrab: string; - static orange: string; - static orangered: string; - static orchid: string; - static palegoldenrod: string; - static palegreen: string; - static paleturquoise: string; - static palevioletred: string; - static papayawhip: string; - static peachpuff: string; - static peru: string; - static pink: string; - static plum: string; - static powderblue: string; - static purple: string; - static red: string; - static rosybrown: string; - static royalblue: string; - static saddlebrown: string; - static salmon: string; - static sandybrown: string; - static seagreen: string; - static seashell: string; - static sienna: string; - static silver: string; - static skyblue: string; - static slateblue: string; - static slategray: string; - static slategrey: string; - static snow: string; - static springgreen: string; - static steelblue: string; - static tan: string; - static teal: string; - static thistle: string; - static tomato: string; - static turquoise: string; - static violet: string; - static wheat: string; - static white: string; - static whitesmoke: string; - static yellow: string; - static yellowgreen: string; + static aliceblue: number; + static antiquewhite: number; + static aqua: number; + static aquamarine: number; + static azure: number; + static beige: number; + static bisque: number; + static black: number; + static blanchedalmond: number; + static blue: number; + static blueviolet: number; + static brown: number; + static burlywood: number; + static cadetblue: number; + static chartreuse: number; + static chocolate: number; + static coral: number; + static cornflowerblue: number; + static cornsilk: number; + static crimson: number; + static cyan: number; + static darkblue: number; + static darkcyan: number; + static darkgoldenrod: number; + static darkgray: number; + static darkgreen: number; + static darkgrey: number; + static darkkhaki: number; + static darkmagenta: number; + static darkolivegreen: number; + static darkorange: number; + static darkorchid: number; + static darkred: number; + static darksalmon: number; + static darkseagreen: number; + static darkslateblue: number; + static darkslategray: number; + static darkslategrey: number; + static darkturquoise: number; + static darkviolet: number; + static deeppink: number; + static deepskyblue: number; + static dimgray: number; + static dimgrey: number; + static dodgerblue: number; + static firebrick: number; + static floralwhite: number; + static forestgreen: number; + static fuchsia: number; + static gainsboro: number; + static ghostwhite: number; + static gold: number; + static goldenrod: number; + static gray: number; + static green: number; + static greenyellow: number; + static grey: number; + static honeydew: number; + static hotpink: number; + static indianred: number; + static indigo: number; + static ivory: number; + static khaki: number; + static lavender: number; + static lavenderblush: number; + static lawngreen: number; + static lemonchiffon: number; + static lightblue: number; + static lightcoral: number; + static lightcyan: number; + static lightgoldenrodyellow: number; + static lightgray: number; + static lightgreen: number; + static lightgrey: number; + static lightpink: number; + static lightsalmon: number; + static lightseagreen: number; + static lightskyblue: number; + static lightslategray: number; + static lightslategrey: number; + static lightsteelblue: number; + static lightyellow: number; + static lime: number; + static limegreen: number; + static linen: number; + static magenta: number; + static maroon: number; + static mediumaquamarine: number; + static mediumblue: number; + static mediumorchid: number; + static mediumpurple: number; + static mediumseagreen: number; + static mediumslateblue: number; + static mediumspringgreen: number; + static mediumturquoise: number; + static mediumvioletred: number; + static midnightblue: number; + static mintcream: number; + static mistyrose: number; + static moccasin: number; + static navajowhite: number; + static navy: number; + static oldlace: number; + static olive: number; + static olivedrab: number; + static orange: number; + static orangered: number; + static orchid: number; + static palegoldenrod: number; + static palegreen: number; + static paleturquoise: number; + static palevioletred: number; + static papayawhip: number; + static peachpuff: number; + static peru: number; + static pink: number; + static plum: number; + static powderblue: number; + static purple: number; + static red: number; + static rosybrown: number; + static royalblue: number; + static saddlebrown: number; + static salmon: number; + static sandybrown: number; + static seagreen: number; + static seashell: number; + static sienna: number; + static silver: number; + static skyblue: number; + static slateblue: number; + static slategray: number; + static slategrey: number; + static snow: number; + static springgreen: number; + static steelblue: number; + static tan: number; + static teal: number; + static thistle: number; + static tomato: number; + static turquoise: number; + static violet: number; + static wheat: number; + static white: number; + static whitesmoke: number; + static yellow: number; + static yellowgreen: number; } export class Euler { @@ -3442,14 +3427,14 @@ declare module THREE { * * distanceTo(v:T):number; */ - distanceTo(v: Vector): number; + distanceTo?(v: Vector): number; /** * NOTE: Vector4 doesn't have the property. * * distanceToSquared(v:T):number; */ - distanceToSquared(v: Vector): number; + distanceToSquared?(v: Vector): number; /** * setLength(l:number):T; @@ -3913,36 +3898,22 @@ declare module THREE { /** * Sets X component of this vector. */ - setX(x: number): Vector2; + setX(x: number): Vector4; /** * Sets Y component of this vector. */ - setY(y: number): Vector2; + setY(y: number): Vector4; /** * Sets Z component of this vector. */ - setZ(z: number): Vector2; + setZ(z: number): Vector4; /** * Sets w component of this vector. */ - setW(w: number): Vector2; - - /** - * NOTE: Vector4 doesn't have the property. - * - * distanceToSquared(v:T):number; - */ - distanceTo(v: Vector): number; - - /** - * NOTE: Vector4 doesn't have the property. - * - * distanceToSquared(v:T):number; - */ - distanceToSquared(v: Vector): number; + setW(w: number): Vector4; } // Objects ////////////////////////////////////////////////////////////////////////////////// @@ -4065,7 +4036,7 @@ declare module THREE { clone(object?: PointCloud): PointCloud; } - export class Skeleton extends Mesh { + export class Skeleton { constructor(bones: Bone[], boneInverses?: Matrix4[], useVertexTexture?: boolean); bones: Bone[]; useVertexTexture: boolean; @@ -4249,11 +4220,6 @@ declare module THREE { */ sortObjects: boolean; - /** - * Defines whether the renderer should auto update objects. Default is true. - */ - autoUpdateObjects: boolean; - /** * Default is false. */ @@ -4433,7 +4399,6 @@ declare module THREE { */ render(scene: Scene, camera: Camera, renderTarget?: RenderTarget, forceClear?: boolean): void; renderImmediateObject(camera: Camera, lights: Light[], fog: Fog, material: Material, object: Object3D): void; - initWebGLObjects(scene: Scene): void; initMaterial(material: Material, lights: Light[], fog: Fog, object: Object3D): void; /** @@ -4510,7 +4475,7 @@ declare module THREE { export class RenderableFace { constructor(); - color: number; + color: Color; material: Material; uvs: Vector2[][]; v1: RenderableVertex; @@ -4863,8 +4828,8 @@ declare module THREE { clone(): Texture; dispose(): void; - DEFAULT_IMAGE: any; - DEFAULT_MAPPING: any; + static DEFAULT_IMAGE: any; + static DEFAULT_MAPPING: any; } // Extras ///////////////////////////////////////////////////////////////////// @@ -4976,13 +4941,6 @@ declare module THREE { play(animation: Animation): void; stop(animation: Animation): void; update(deltaTimeMS: number): void; - - // deprecated - add(data: AnimationData): void; - // deprecated - get(name: string): AnimationData; - // deprecated - remove(name: string): void; }; export class MorphAnimation { @@ -5008,10 +4966,9 @@ declare module THREE { hierarchy: KeyFrames[]; currentTime: number; timeScale: number; - isPlaying: number; - isPaused: number; - loop: number; - JITCompile: boolean; + isPlaying: boolean; + isPaused: boolean; + loop: boolean; play(startTime?: number): void; stop(): void; @@ -5022,7 +4979,7 @@ declare module THREE { // Extras / Curves ///////////////////////////////////////////////////////////////////// export class ArcCurve extends EllipseCurve { - constructor(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean ); + constructor(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean ); } export class ClosedSplineCurve3 extends Curve { constructor( points:Vector3[] ); @@ -5044,18 +5001,18 @@ declare module THREE { export class CubicBezierCurve3 extends Curve { constructor( v0: Vector3, v1: Vector3, v2: Vector3, v3: Vector3 ); - v0: Vector2; - v1: Vector2; - v2: Vector2; - v3: Vector2; + v0: Vector3; + v1: Vector3; + v2: Vector3; + v3: Vector3; getPoint(t: number): Vector3; } export class EllipseCurve extends Curve { constructor( aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean ); - ax: number; - ay: number; + aX: number; + aY: number; xRadius: number; yRadius: number; aStartAngle: number; @@ -5077,8 +5034,8 @@ declare module THREE { export class LineCurve3 extends Curve { constructor( v1: Vector3, v2: Vector3 ); - v1: Vector2; - v2: Vector2; + v1: Vector3; + v2: Vector3; getPoint(t: number): Vector3; } @@ -5095,9 +5052,9 @@ declare module THREE { export class QuadraticBezierCurve3 extends Curve { constructor( v0: Vector3, v1: Vector3, v2: Vector3 ); - v0: Vector2; - v1: Vector2; - v2: Vector2; + v0: Vector3; + v1: Vector3; + v2: Vector3; getPoint(t: number): Vector3; } @@ -5124,8 +5081,6 @@ declare module THREE { * class Curve<T extends Vector> */ export class Curve { - constructor(); - needsUpdate: boolean; /** @@ -5228,10 +5183,10 @@ declare module THREE { scaleWorld: Vector3; translationWorld: Vector3; - rotationWorld: Quaternion; + quaternionWorld: Quaternion; translationObject: Vector3; scaleObject: Vector3; - rotationObject: Quaternion; + quaternionObject: Quaternion; updateMatrixWorld(force?: boolean): void; } @@ -5246,13 +5201,18 @@ declare module THREE { ELLIPSE, } + export interface PathAction { + action: PathActions; + args: any; + } + /** * a 2d path representation, comprising of points, lines, and cubes, similar to the html5 2d canvas api. It extends CurvePath. */ export class Path extends CurvePath { constructor(points?: Vector2); - actions: PathActions[]; + actions: PathAction[]; fromPoints(vectors: Vector2[]): void; moveTo(x: number, y: number): void; @@ -5366,7 +5326,6 @@ declare module THREE { constructor(shape: Shape, options?: any); constructor(shapes: Shape[], options?: any); - shapebb: BoundingBox; addShapeList(shapes: Shape[], options: any): ShapeGeometry; addShape(shape: Shape, options?: any): void; } From 8a1c9ebad9d96bc26856bbd41f337db3347af5c4 Mon Sep 17 00:00:00 2001 From: Pedro Casaubon Date: Fri, 8 Aug 2014 19:09:46 +0200 Subject: [PATCH 296/324] Updated DropboxJS Definitions --- dropboxjs/dropboxjs-tests.ts | 20 +- dropboxjs/dropboxjs.d.ts | 548 ++++++++++++++++++++++++++++++----- 2 files changed, 487 insertions(+), 81 deletions(-) diff --git a/dropboxjs/dropboxjs-tests.ts b/dropboxjs/dropboxjs-tests.ts index cf5fd3827..efc6a3693 100644 --- a/dropboxjs/dropboxjs-tests.ts +++ b/dropboxjs/dropboxjs-tests.ts @@ -2,18 +2,18 @@ var browserClient = new Dropbox.Client({ key: "your-key-here" }); -browserClient.authenticate(function (error, client) { +browserClient.authenticate((error:any, client:Dropbox.Client) => { if (error) { alert(error); } - client.onError.addListener(function (error) { - if (window.console) { // Skip the "if" in node.js code. + client.onError.addListener((error:any) =>{ + if (window['console']) { // Skip the "if" in node.js code. console.error(error); } }); - client.getAccountInfo(function (error, accountInfo) { + client.getAccountInfo( (error:Dropbox.ApiError, accountInfo:Dropbox.AccountInfo) => { if (error) { alert(error); // Something went wrong. } @@ -21,7 +21,7 @@ browserClient.authenticate(function (error, client) { alert("Hello, " + accountInfo.name + "!"); }); - client.writeFile("hello_world.txt", "Hello, world!\n", function (error, stat) { + client.writeFile("hello_world.txt", "Hello, world!\n", (error:Dropbox.ApiError, stat:Dropbox.File.Stat ) => { if (error) { alert(error); // Something went wrong. } @@ -29,7 +29,7 @@ browserClient.authenticate(function (error, client) { alert("File saved as revision " + stat.versionTag); }); - client.readFile("hello_world.txt", function (error, data) { + client.readFile("hello_world.txt", (error:Dropbox.ApiError, data:string) => { if (error) { alert(error); // Something went wrong. } @@ -37,18 +37,18 @@ browserClient.authenticate(function (error, client) { alert(data); // data has the file's contents }); - client.readdir("/", function (error, entries) { + client.readdir("/", (err: Dropbox.ApiError, filenames: string[], stat: Dropbox.File.Stat, folderEntries?: Dropbox.File.Stat[]) => { if (error) { alert(error); // Something went wrong. } - alert("Your Dropbox contains " + entries.join(", ")); + alert("Your Dropbox contains " + filenames.join(", ")); }); }); -var serverClient = new Dropbox.Client({ +var serverClient:Dropbox.Client = new Dropbox.Client({ key: "your-key-here", secret: "your-secret-here" }); -serverClient.authDriver(new Dropbox.AuthDriver.NodeServer(8191)); \ No newline at end of file +serverClient.authDriver(new Dropbox.AuthDriver.NodeServer({port:8191})); \ No newline at end of file diff --git a/dropboxjs/dropboxjs.d.ts b/dropboxjs/dropboxjs.d.ts index a718fabaf..c40a69f4b 100644 --- a/dropboxjs/dropboxjs.d.ts +++ b/dropboxjs/dropboxjs.d.ts @@ -1,15 +1,367 @@ // Type definitions for dropbox-js // Project: https://github.com/dropbox/dropbox-js -// Definitions by: Steve Fenton +// Definitions by: Steve Fenton , Pedro Casaubon // Definitions: https://github.com/borisyankov/DefinitelyTyped + declare module Dropbox { - export interface DropboxConfig { + + + interface QueryParams { + [key: string]: any; + } + interface Credentials { key: string; secret?: string; + token?: string; + uid?: string; } - export interface AccountInfoData { + + /* Callbacks */ + + interface AuthenticateCallback { + (err: ApiError, client: Client): void; + (err: AuthError, client: Client): void; + } + + interface QueryParamsCallback { + (queryParams: QueryParams): void; + } + + interface ClientFileReadCallback { + + (err: ApiError, fileContents: string, stat: File.Stat, rangeInfo: Http.RangeInfo): void; + } + + interface ClientFileWriteCallback { + + (err: ApiError, stat: File.Stat): void; + } + + interface ResumableUploadStepCallback { + (err: ApiError, uploadCursor: Http.UploadCursor): void; + } + + interface ReadThumbnailCallback { + (err: ApiError, imageData: string, stat: File.Stat): void; + (err: ApiError, imageData: Blob, stat: File.Stat): void; + } + + interface FileStatCallback { + (err: ApiError, stat: File.Stat): void; + } + + /* Options */ + + interface AuthenticateOptions { + interactive: boolean; + } + + interface SingOutOptions { + mustInvalidate: boolean; + } + + interface AccountInfoOptions { + httpCache: boolean; + } + + interface ClientFileReadOptions { + + versionTag?: string; + rev?: string; + arrayBuffer?: boolean; + blob?: boolean; + buffer?: boolean; + binary?: boolean; + length?: number; + start?: number; + httpCache?: boolean; + } + + interface ClientFileWriteOptions { + lastVersionTag?: string; + parentRev?: string; + noOverwrite?: boolean; + } + + interface ReadDirOptions { + removed?: boolean; + deleted?: boolean; + limit?: any; + versionTag?: string; + contentHash?: string; + httpCache?: boolean; + } + + interface MakeURLOptions { + download?: boolean; + downloadHack?: boolean; + long?: boolean; + longUrl?: boolean; + } + + interface HistoryOptions { + limit?: number; + httpCache?: boolean; + + } + + interface ThumbnailUrlOptions { + png?: boolean; + format?: string; + size?: string; + } + + interface ReadThumbnailOptions extends ThumbnailUrlOptions { + arrayBuffer?: boolean; + blob?: boolean; + buffer?: boolean; + } + + interface FindByNameOptions { + limit?: number; + removed?: boolean; + deleted?: boolean; + httpCache?: boolean; + + } + + interface RedirectOptions { + redirectUrl?: string; + redirectFile?: string; + scope?: string; + rememberUser?: boolean; + } + + module Util { + + class EventSource { + constructor(options: { cancelable: boolean }); + addListener(listener: (event: any) => void): EventSource; + removeListener(listener: (event: any) => void): EventSource; + dispatch(event: {}): boolean; + } + + class Oauth { + static queryParamsFromUrl(url: string): QueryParams; + static randomAuthStateParam(): string; + checkAuthStateParam(stateParam: string): boolean; + } + + class Xhr { + xhr: XMLHttpRequest; + onError: (error: ApiError, callBack: (error: ApiError) => void) => void; + + constructor(method: string, baseUrl: string); + static urlEncode(obj: {}): string; + static urlEncodeValue(obj: {}): string; + static urlDecode(string: {}): QueryParams; + + + setParams(params: QueryParams): Xhr; + setCallback(callback: (err: ApiError, responseType: string, metadataHeader: {}, headers: {}) => void): Xhr; + signWithOauth(oauth: Oauth, cacheFriendly: boolean): Xhr; + addOauthParams(oauth: Oauth): Xhr; + addOauthHeader(oauth: Oauth): Xhr; + + setBody(body: string): Xhr; + setBody(body: Blob): Xhr; + setBody(body: ArrayBuffer): Xhr; + + setResponseType(responseType: string): Xhr; + setHeader(headerName: string, value: string): Xhr; + reportResponseHeaders(): Xhr; + setFileField(fieldName: string, fileName: string, fileData: string, contentType?: string): void; + setFileField(fieldName: string, fileName: string, fileData: Blob, contentType?: string): void; + setFileField(fieldName: string, fileName: string, fileData: File, contentType?: string): void; + prepare(): Xhr; + send(callback: (err: ApiError, responseType: string, metadataHeader: {}) => void): Xhr; + onReadyStateChange(): void; + onXdrLoad(): void; + onXdrError(): void; + } + } + module Http { + class AppInfo { + static ICON_SMALL: number; + static ICON_LARGE: number; + static parse(appInfo: {}, appKey?: string): AppInfo; + name: string; + key: string; + canUseDatastores: boolean; + canUseFiles: boolean; + hasAppFolder: boolean; + canUseFullDropbox: boolean; + icon(width: number, height?: number): void; + } + + class PollResult { + static parse(response: {}): PollResult; + hasChanges: boolean; + retryAfter: number; + } + + class PulledChanges { + static parse(deltaInfo: {}): PulledChanges; + blankSlate: boolean; + cursorTag: string; + shouldPullAgain: boolean; + shouldBackOff: boolean; + cursor(): string; + } + + class PulledChange { + static parse(entry: {}): PulledChange; + path: string; + wasRemoved: boolean; + stat: File.Stat; + } + + class RangeInfo { + static parse(headerValue: string): RangeInfo; + start: number; + size: number; + end: number; + } + + class UploadCursor { + static parse(cursorData: string): UploadCursor; + static parse(cursorData: {}): UploadCursor; + constructor(cursorData: string); + constructor(cursorData: {}); + tag: string; + offset: number; + expiresAt: Date; + toJSON(): {}; + } + } + module File { + + interface StatOptions { + version: number; + removed: boolean; + deleted: boolean; + readDir: boolean; + versionTag: string; + rev: string; + contentHash: string; + hash: string; + httpCache: boolean; + } + + class ShareUrl { + static parse(urlData: string, isDirect: boolean): ShareUrl; + static parse(urlData: {}, isDirect: boolean): ShareUrl; + url: string; + expiresAt: Date; + isDirect: boolean; + isPreview: boolean; + toJSON(): {}; + } + + class CopyReference { + static parse(refData: string): CopyReference; + static parse(refData: {}): CopyReference; + tag: string; + expiresAt: Date; + toJSON(): {}; + } + + class Stat { + static parse(metadata: {}): Stat; + path: string; + name: string; + inAppFolder: boolean; + isFolder: boolean; + isFile: boolean; + isRemoved: boolean; + typeIcon: string; + versionTag: string; + contentHash: string; + mimeType: string; + size: number; + humanSize: string; + hasThumbnail: boolean; + modifiedAt: Date; + clientModifiedAt: Date; + toJSON(): {}; + } + } + module AuthDriver { + + class IAuthDriver { + doAuthorize(authUrl: string, stateParam: string, client: Client, callback?: QueryParamsCallback): void; + } + + class BrowserBase { + static localStorage(): Storage; + static currentLocation(): string; + static cleanupLocation(): void; + + constructor(options: { scope: string; rememberUser: boolean }); + authType(): string; + onAuthStepChange(client: Client, callback: () => void): void; + locationStateParam(url: string): string; + } + + class Redirect { + constructor(options?: { redirectUrl: string; redirectFile: string; scope: string; rememberUser: boolean }); + url(): string; + doAuthorize(authUrl: string, stateParam: string, client: Client): void; + resumeAuthorize(stateParam: string, client: Client, callback: QueryParamsCallback): void; + + } + + class Popup extends IAuthDriver { + static locationOrigin(location: string): string; + static oauthReceiver(): void; + constructor(options?: RedirectOptions); + url(): string; + + } + + class ChromeApp extends IAuthDriver { + constructor(options?: { scope: string }); + } + + class ChromeExtension extends IAuthDriver { + static oauthReceiver(): void; + constructor(options?: { scope: string; receiverPath: string }); + } + + class Cordova extends IAuthDriver { + static oauthReceiver(): void; + constructor(options?: { scope: string; receiverPath: string }); + url(): string; + } + + class NodeServer extends IAuthDriver { + constructor(options?: { port: number; tls?: {} }); + authType(): string; + url(): string; + openBrowser(url: string): void; + createApp(): void; + closeServer(): void; + + // TODO check request response types + doRequest(request:any, response:any): void; + closeBrowser(response:any): void; + } + } + + + class AuthDriver { + authType(): string; + url(): string; + doAuthorize(authUrl: string, stateParam: string, client: Client, callback: QueryParamsCallback): void; + getStateParam(client: Client, callback: (state: string) => void): void; + resumeAuthorize(stateParam: string, client: Client, callback: QueryParamsCallback): void; + onAuthStepChange(client: Client, callback: () => void): void; + } + + class AccountInfo { + static parse(acountInfo: {}): AccountInfo; name: string; email: string; countryCode: string; @@ -20,82 +372,136 @@ declare module Dropbox { usedQuota: number; privateBytes: number; sharedBytes: number; + json(): {}; } - export interface AccountInfo extends AccountInfoData { - parse(accountInfo: string): AccountInfo; - json(): AccountInfoData; + class ApiError { + status: number; + method: string; + url: string; + responseText: string; + response: {}; + + constructor(xhr: XMLHttpRequest, method: string, url: string); + + static NETWORK_ERROR: number; + static NO_CONTENT: number; + static INVALID_PARAM: number; + static INVALID_TOKEN: number; + static OAUTH_ERROR: number; + static NOT_FOUND: number; + static INVALID_METHOD: number; + static NOT_ACCEPTABLE: number; + static CONFLICT: number; + static RATE_LIMITED: number; + static SERVER_ERROR: number; + static OVER_QUOTA: number; } - export interface ApiError { - INVALID_TOKEN: number; - NOT_FOUND: number; - OVER_QUOTA: number; - RATE_LIMITED: number; - NETWORK_ERROR: number; - INVALID_PARAM: number; - OAUTH_ERROR: number; - INVALID_METHOD: number; + class AuthError { + + code: string; + description: string; + uri: string; + constructor(queryString: QueryParams); + + static ACCESS_DENIED: string; + static INVALID_REQUEST: string; + static UNAUTHORIZED_CLIENT: string; + static INVALID_GRANT: string; + static INVALID_SCOPE: string; + static UNSUPPORTED_GRANT_TYPE: string; + static UNSUPPORTED_RESPONSE_TYPE: string; + static SERVER_ERROR: string; + static TEMPORARILY_UNAVAILABLE: string; } - export interface FileStatisticsData { - path: string; - name: string; - inAppFolder: boolean; - isFolder: boolean; - isFile: boolean; - isRemoved: boolean; - typeIcon: string; - versionTag: string; - contentHash: string; - mimeType: string; - size: number; - humanSize: string; - hasThumbnail: boolean; - modifiedAt: Date; - clientModifiedAt: Date; - } + class Client { + static ERROR: number; + static RESET: number; + static PARAM_SET: number; + static PARAM_LOADED: number; + static AUTHORIZED: number; + static DONE: number; + static SIGNED_OUT: number; - export interface FileStatistics extends FileStatisticsData { - parse(stats: string): FileStatistics; - json(): FileStatisticsData; - } + onXhr: Util.EventSource; + onError: Util.EventSource; + onAuthStepChange: Util.EventSource; + authStep: number; - export interface ClientOnError { - addListener(callback: (error: number) => any): void; - } - - export interface Client { - new (config: DropboxConfig): Client; - authDriver(authDriver: any): Client; - authenticate(callback: (error: number, client: Client) => any): Client; - credentials(): string; + constructor(options: Credentials); + authDriver(driver: AuthDriver.IAuthDriver): Client; dropboxUid(): string; + credentials(): Credentials; + + // TODO check the error interface + authenticate(): Client; + authenticate(callback: AuthenticateCallback): Client; + authenticate(options: AuthenticateOptions): Client; + authenticate(options: AuthenticateOptions, callback: AuthenticateCallback): Client; isAuthenticated(): boolean; - onError: ClientOnError; - getAccountInfo(callback: (error: number, accountInfo: AccountInfo) => any): XMLHttpRequest; - getUserInfo(callback: (error: number, accountInfo: AccountInfo) => any): XMLHttpRequest; - signOut(options: {}, callback: (error: number) => any): XMLHttpRequest; - signOff(options: {}, callback: (error: number) => any): XMLHttpRequest; - writeFile(fileName: string, contents: string, options: {}, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest; - writeFile(fileName: string, contents: string, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest; - readFile(fileName: string, options: {}, callback: (error: number, contents: string, stats: FileStatistics) => any): XMLHttpRequest; - readFile(fileName: string, callback: (error: number, contents: string, stats: FileStatistics) => any): XMLHttpRequest; - stat(path: string, options: {}, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest; - stat(path: string, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest; - metadata(path: string, options: {}, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest; - metadata(path: string, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest; - readdir(path: string, options: {}, callback: (error: number, entries: any[]) => any): XMLHttpRequest; - readdir(path: string, callback: (error: number, entries: any[]) => any): XMLHttpRequest; + signOut(callback: (err: ApiError) => void): XMLHttpRequest; + signOut(options: SingOutOptions, callback: (err: ApiError) => void): XMLHttpRequest; + signOff(callback: (err: ApiError) => void): void; + signOff(options: SingOutOptions, callback: (err: ApiError) => void): void; + getAccountInfo(callback: (err: ApiError, accountInfo: AccountInfo, AccountInfo: AccountInfo) => void): XMLHttpRequest; + getAccountInfo(options: AccountInfoOptions, callback: (err: ApiError, accountInfo: AccountInfo, AccountInfo: AccountInfo) => void): XMLHttpRequest; + readFile(path: string, callback: ClientFileReadCallback): XMLHttpRequest; + readFile(path: string, options: ClientFileReadOptions, callback: ClientFileReadCallback): XMLHttpRequest; + writeFile(path: string, data: any, callback: ClientFileWriteCallback): XMLHttpRequest; + writeFile(path: string, data: any, options: ClientFileWriteOptions, callback: ClientFileWriteCallback): XMLHttpRequest; + resumableUploadStep(data: any, callback: ResumableUploadStepCallback): XMLHttpRequest; + resumableUploadStep(data: any, cursor: Http.UploadCursor, callback: ResumableUploadStepCallback): XMLHttpRequest; + resumableUploadFinish(path: string, cursor: Http.UploadCursor, callback: ClientFileWriteCallback): XMLHttpRequest; + resumableUploadFinish(path: string, cursor: Http.UploadCursor, options: ClientFileWriteOptions, callback: ClientFileWriteCallback): XMLHttpRequest; + stat(path: string, callback: (err: ApiError, stat: File.Stat, folderEntries?: File.Stat[]) => void): XMLHttpRequest; + stat(path: string, options: File.StatOptions, callback: (err: ApiError, stat: File.Stat, folderEntries?: File.Stat[]) => void): XMLHttpRequest; + readdir(path: string, callback: (err: ApiError, filenames: string[], stat: File.Stat, folderEntries?: File.Stat[]) => void): XMLHttpRequest; + readdir(path: string, options: ReadDirOptions, callback: (err: ApiError, filenames: string[], stat: File.Stat, folderEntries?: File.Stat[]) => void): XMLHttpRequest; + metadata(path: string, callback: (err: ApiError, stat: File.Stat, folderEntries?: File.Stat[]) => void): void; + metadata(path: string, options: File.StatOptions, callback: (err: ApiError, stat: File.Stat, folderEntries?: File.Stat[]) => void): void; + makeUrl(path: string, callback: (err: ApiError, shareUrl: File.ShareUrl) => void): XMLHttpRequest; + makeUrl(path: string, options: MakeURLOptions, callback: (err: ApiError, shareUrl: File.ShareUrl) => void): XMLHttpRequest; + history(path: string, callback: (err: ApiError, fileVersions: File.Stat[]) => void): XMLHttpRequest; + history(path: string, options: HistoryOptions, callback: (err: ApiError, fileVersions: File.Stat[]) => void): XMLHttpRequest; + revisions(path: string, options: HistoryOptions, callback: (err: ApiError, fileVersions: File.Stat[]) => void): void; + thumbnailUrl(path: string, options?: ThumbnailUrlOptions): string; + readThumbnail(path: string, callback: ReadThumbnailCallback): XMLHttpRequest; + readThumbnail(path: string, options: ReadThumbnailOptions, callback: ReadThumbnailCallback): XMLHttpRequest; + revertFile(path: string, versionTag: string, callback: FileStatCallback): XMLHttpRequest; + restore(path: string, versionTag: string, callback: FileStatCallback): void; + findByName(path: string, namePattern: string, callback: (err: ApiError, resultStats: File.Stat[]) => void): XMLHttpRequest; + findByName(path: string, namePattern: string, options: FindByNameOptions, callback: (err: ApiError, resultStats: File.Stat[]) => void): XMLHttpRequest; + search(path: string, namePattern: string, options: FindByNameOptions, callback: (err: ApiError, resultStats: File.Stat[]) => void): void; + makeCopyReference(path: string, callback: (err: ApiError, copyReference: File.CopyReference) => void): XMLHttpRequest; + copyRef(path: string, callback: (err: ApiError, copyReference: File.CopyReference) => void): XMLHttpRequest; + pullChanges(callback: (err: ApiError, changes: Http.PulledChanges) => void): XMLHttpRequest; + pullChanges(cursor: string, callback: (err: ApiError, changes: Http.PulledChanges) => void): XMLHttpRequest; + pullChanges(cursor: Http.PulledChanges, callback: (err: ApiError, changes: Http.PulledChanges) => void): XMLHttpRequest; + delta(cursor: string, callback: (err: ApiError, changes: Http.PulledChanges) => void): void; + delta(cursor: Http.PulledChanges, callback: (err: ApiError, changes: Http.PulledChanges) => void): void; + pollForChanges(cursor: string, options: {}, callback: (err: ApiError, changes: Http.PollResult) => void): void; + pollForChanges(cursor: Http.PulledChanges, options: {}, callback: (err: ApiError, changes: Http.PollResult) => void): void; + mkdir(path: string, callback: FileStatCallback): XMLHttpRequest; + remove(path: string, callback: FileStatCallback): XMLHttpRequest; + unlink(path: string, callback: FileStatCallback): void; + delete(path: string, callback: FileStatCallback): void; + copy(from: string, toPath: string, callback: FileStatCallback): XMLHttpRequest; + copy(from: File.CopyReference, toPath: string, callback: FileStatCallback): XMLHttpRequest; + move(fromPath: string, toPath: string, callback: FileStatCallback): XMLHttpRequest; + appInfo(callback: (err: ApiError, changes: Http.AppInfo) => void): XMLHttpRequest; + appInfo(appKey: string, callback: (err: ApiError, changes: Http.AppInfo) => void): XMLHttpRequest; + + // TODO check if this can better be described + isAppDeveloper(userId:any, callbackcallback: (err: ApiError, isAppDeveloper: boolean) => void): XMLHttpRequest; + isAppDeveloper(userId:any, appKey:any, callbackcallback: (err: ApiError, isAppDeveloper: boolean) => void): XMLHttpRequest; + hasOauthRedirectUri(redirectUri: string, callback: (err: ApiError, hasOauthRedirectUri: boolean) => void): XMLHttpRequest; + hasOauthRedirectUri(redirectUri: string, appKey: string, callback: (err: ApiError, hasOauthRedirectUri: boolean) => void): XMLHttpRequest; + hasOauthRedirectUri(redirectUri: string, appKey: Http.AppInfo, callback: (err: ApiError, hasOauthRedirectUri: boolean) => void): XMLHttpRequest; + reset(): Client; + setCredentials(credentials: Credentials): Client; + appHash(): string; + } - - export module AuthDriver { - export interface NodeServer { - new (port: number): any; - } - - export var NodeServer: NodeServer; - } - - export var Client: Client; -} +} \ No newline at end of file From 3878a37dfad2c3ad01d6be3988aa7d5460519b58 Mon Sep 17 00:00:00 2001 From: Pedro Casaubon Date: Fri, 8 Aug 2014 19:10:43 +0200 Subject: [PATCH 297/324] Added node-webkit definitions --- node-webkit/node-webkit-tests.ts | 203 ++++++++++++++++++++++++++++ node-webkit/node-webkit.d.ts | 221 +++++++++++++++++++++++++++++++ 2 files changed, 424 insertions(+) create mode 100644 node-webkit/node-webkit-tests.ts create mode 100644 node-webkit/node-webkit.d.ts diff --git a/node-webkit/node-webkit-tests.ts b/node-webkit/node-webkit-tests.ts new file mode 100644 index 000000000..da10f2901 --- /dev/null +++ b/node-webkit/node-webkit-tests.ts @@ -0,0 +1,203 @@ +/// +/// +// Load native UI library +var gui: typeof nw.gui; + + +/* WINDOW */ + + // Get the current window + var win = gui.Window.get(); + + // Listen to the minimize event + win.on('minimize', function() { + console.log('Window is minimized'); + }); + + // Minimize the window + win.minimize(); + + // Unlisten the minimize event + win.removeAllListeners('minimize'); + + // Create a new window and get it + var new_win = gui.Window.get( + window.open('https://github.com') + ); + + // And listen to new window's focus event + new_win.on('focus', function() { + console.log('New window is focused'); + }); + + + // Get the current window + var win = gui.Window.get(); + + // Create a new window and get it + var new_win = gui.Window.get( + window.open('https://github.com') + ); + + // png as base64string + win.capturePage(function(base64string:string){ + // do something with the base64string + }, { format : 'png', datatype : 'raw'} ); + + // png as node buffer + win.capturePage(function(buffer:Buffer){ + // do something with the buffer + }, { format : 'png', datatype : 'buffer'} ); + + + // Open a new window. + var win = gui.Window.get( + window.open('popup.html') + ); + + // Release the 'win' object here after the new window is closed. + win.on('closed', function() { + win = null; + }); + + // Listen to main window's close event + gui.Window.get().on('close', function() { + // Hide the window to give user the feeling of closing immediately + this.hide(); + + // If the new window is still open then close it. + if (win != null) + win.close(true); + + // After closing the new window, close the main window. + this.close(true); + }); + + +/* MENU */ + + // Create an empty menu + var menu = new gui.Menu(); + + // Add some items + menu.append(new gui.MenuItem({ label: 'Item A' })); + menu.append(new gui.MenuItem({ label: 'Item B' })); + menu.append(new gui.MenuItem({ type: 'separator' })); + menu.append(new gui.MenuItem({ label: 'Item C' })); + + // Remove one item + menu.removeAt(1); + + // Popup as context menu + menu.popup(10, 10); + + // Iterate menu's items + for (var i = 0; i < menu.items.length; ++i) { + console.log(menu.items[i]); + } + + + var win = gui.Window.get(); + var nativeMenuBar = new gui.Menu({ type: "menubar" }); + nativeMenuBar.createMacBuiltin("My App"); + win.menu = nativeMenuBar; + + nativeMenuBar.createMacBuiltin("My App", { + hideEdit: true, + hideWindow: true + }); + +/* MENU ITEM */ + + var itemc:nw.gui.MenuItem; + + // Create a separator + itemc = new gui.MenuItem({ type: 'separator' }); + + // Create a normal item with label and icon + itemc = new gui.MenuItem({ + type: "normal", + label: "I'm a menu item", + icon: "img/icon.png" + }); + + // Or you can omit the 'type' field for normal items + itemc = new gui.MenuItem({ label: 'Simple item' }); + + // Bind a callback to item + itemc = new gui.MenuItem({ + label: "Click me", + click: function() { + console.log("I'm clicked"); + }, + key: "s", + modifiers: "ctrl-alt", + }); + + // You can have submenu! + var submenu = new gui.Menu(); + submenu.append(new gui.MenuItem({ label: 'Item 1' })); + submenu.append(new gui.MenuItem({ label: 'Item 2' })); + submenu.append(new gui.MenuItem({ label: 'Item 3' })); + itemc.submenu = submenu; + + // And everything can be changed at runtime + itemc.label = 'New label'; + itemc.click = function() { console.log('New click callback'); }; + + +/* APP */ + + // Print arguments + console.log(gui.App.argv); + + // Quit current app + gui.App.quit(); + + // Get the name field in manifest + gui.App.manifest.name + + gui.App.addOriginAccessWhitelistEntry('http://github.com/', 'app', 'myapp', true); + + +/* CLIPBOARD */ + + // We can not create a clipboard, we have to receive the system clipboard + var clipboard = gui.Clipboard.get(); + + // Read from clipboard + var text = clipboard.get('text'); + console.log(text); + + // Or write something + clipboard.set('I love node-webkit :)', 'text'); + + // And clear it! + clipboard.clear(); + + +/* TRAY */ + + // Create a tray icon + var tray = new gui.Tray({ title: 'Tray', icon: 'img/icon.png' }); + + // Give it a menu + var menu = new gui.Menu(); + menu.append(new gui.MenuItem({ type: 'checkbox', label: 'box1' })); + tray.menu = menu; + + // Remove the tray + tray.remove(); + tray = null; + + +/* SHELL */ + + // Open URL with default browser. + gui.Shell.openExternal('https://github.com/rogerwang/node-webkit'); + + // Open a text file with default text editor. + gui.Shell.openItem('test.txt'); + + // Open a file in file explorer. + gui.Shell.showItemInFolder('test.txt'); \ No newline at end of file diff --git a/node-webkit/node-webkit.d.ts b/node-webkit/node-webkit.d.ts new file mode 100644 index 000000000..92afbff2d --- /dev/null +++ b/node-webkit/node-webkit.d.ts @@ -0,0 +1,221 @@ +// Type definitions for node-webkit +// Project: https://github.com/rogerwang/node-webkit +// Definitions by: Pedro Casaubon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module nw.gui { + + interface IEventEmitter { + addListener(event: string, listener: Function): EventEmitter; + on(event: string, listener: Function): EventEmitter; + once(event: string, listener: Function): EventEmitter; + removeListener(event: string, listener: Function): EventEmitter; + removeAllListeners(event?: string): EventEmitter; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + } + + class EventEmitter implements IEventEmitter { + addListener(event: string, listener: Function): EventEmitter; + on(event: string, listener: Function): EventEmitter; + once(event: string, listener: Function): EventEmitter; + removeListener(event: string, listener: Function): EventEmitter; + removeAllListeners(event?: string): EventEmitter; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + } + + export interface MenuConfig { + type?: string; + } + + export interface HideMenusOptions { + hideEdit: boolean; + hideWindow: boolean; + } + + export interface MenuItemConfig { + label?: string; + click?: Function; + type?: string; + submenu?: Menu; + icon?: string; + tooltip?: string; + checked?: boolean; + enabled?: boolean; + key?: string; + modifiers?: string; + } + + export class MenuItem extends EventEmitter implements MenuItemConfig { + constructor(config: MenuItemConfig); + label: string; + click: Function; + type: string; + submenu: Menu; + icon: string; + tooltip: string; + checked: boolean; + enabled: boolean; + key: string; + modifiers: string; + } + + export class Menu { + constructor(config?: MenuConfig); + items: MenuItem[]; + append(item: MenuItem): void; + remove(item: MenuItem): void; + insert(item: MenuItem, atPosition: number): void; + removeAt(index: number): void; + popup(x: number, y: number): void; + // since v0.10.0-rc1 + createMacBuiltin(appname: string, options?: HideMenusOptions): void; + + } + + export interface ShortcutOption { + key: string; + active: Function; + failed: Function; + } + + export class Shortcut extends EventEmitter { + constructor(option: ShortcutOption); + key: string; + active: Function; + failed: Function; + } + + export interface WindowManifestOptions { + + title?: string; + icon?: string; + toolbar?: boolean; + frame?: boolean; + width?: number; + height?: number; + position?: string; + min_width?: number; + min_height?: number; + max_width?: number; + max_height?: number; + } + + export class Window extends EventEmitter { + static get(windowObject?: any): Window; + static open(url: string, options?: WindowManifestOptions): Window; + x: number; + y: number; + width: number; + height: number; + title: string; + menu: Menu; + isFullScreen: boolean; + isKioskMode: boolean; + zoomLevel: number; + moveTo(x: number, y: number): void; + moveBy(x: number, y: number): void; + resizeTo(width: number, height: number): void; + resizeBy(width: number, height: number): void; + focus(): void; + blur(): void; + show(): void; + hide(): void; + close(force?: boolean): void; + reload(): void; + reloadIgnoringCache(): void; + maximize(): void; + unmaximize(): void; + minimize(): void; + restore(): void; + enterFullscreen(): void; + leaveFullscreen(): void; + toggleFullscreen(): void; + enterKioskMode(): void; + leaveKioskMode(): void; + toggleKioskMode(): void; + showDevTools(id?: string, headless?: boolean): void; + showDevTools(id: HTMLIFrameElement, headless?: boolean): void; + closeDevTools(): void; + isDevToolsOpen(): boolean; + setMaximumSize(width: number, height: number): void; + setMinimumSize(width: number, height: number): void; + setResizable(resizable: boolean): void; + setAlwaysOnTop(top: boolean): void; + setPosition(position: string): void; + setShowInTaskbar(show: boolean): void; + requestAttention(attention: boolean): void; + requestAttention(attention: number): void; + capturePage(callback: Function, imageformat?: string): void; + capturePage(callback: Function, config_object: { format: string; datatype: string }): void; + setProgressBar(progress: number): void; + setBadgeLabel(label: string): void; + eval(frame: HTMLIFrameElement, script: string): void; + } + + export interface App { + argv: any; + fullArgv: any; + dataPath: string; + manifest: any; + clearCache(): void; + closeAllWindows(): void; + crashBrowser(): void; + crashRenderer(): void; + getProxyForURL(url: string): void; + quit(): void; + setCrashDumpDir(dir: string): void; + addOriginAccessWhitelistEntry( + sourceOrigin: string + , destinationProtocol: string + , destinationHost: string + , allowDestinationSubdomains: boolean + ): void; + removeOriginAccessWhitelistEntry( + sourceOrigin: string + , destinationProtocol: string + , destinationHost: string + , allowDestinationSubdomains: boolean + ): void; + registerGlobalHotKey(shortcut: Shortcut): void; + unregisterGlobalHotKey(shortcut: Shortcut): void; + } + + export class Clipboard { + static get(): Clipboard; + get(type?: string): string; + set(data: string, type?: string): void; + clear(): void; + } + + export interface TrayOption { + title?: string; + tooltip?: string; + icon?: string; + alticon?: string; + menu?: Menu; + } + + export class Tray implements TrayOption { + constructor(option: TrayOption); + title: string; + tooltip: string; + icon: string; + alticon: string; + menu: Menu; + remove(): void; + } + + interface Shell { + openExternal(uri: string): void; + openItem(file_path: string): void; + showItemInFolder(file_path: string): void; + } + + export var App: App; + export var Shell: Shell; + +} From a2c53774bb554ac7f73ab4ff0212ad1eccef48d3 Mon Sep 17 00:00:00 2001 From: nitram509 Date: Fri, 8 Aug 2014 23:11:14 +0200 Subject: [PATCH 298/324] added missing method 'getBoundingRect()' for fabric.js, which is available since ~1.0.4 --- fabricjs/fabricjs.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/fabricjs/fabricjs.d.ts b/fabricjs/fabricjs.d.ts index eec70c8f6..cfca6c481 100644 --- a/fabricjs/fabricjs.d.ts +++ b/fabricjs/fabricjs.d.ts @@ -335,6 +335,7 @@ declare module fabric { drawBorders(context: CanvasRenderingContext2D): IObject; drawCorners(context: CanvasRenderingContext2D): IObject; get (property: string): any; + getBoundingRect(): {left:number; top:number; width:number; height:number}; getBoundingRectHeight(): number; getBoundingRectWidth(): number; getSvgStyles(): string; From c8706caad0a134f84c889381e990454f7791304f Mon Sep 17 00:00:00 2001 From: Anthony Date: Fri, 8 Aug 2014 19:57:23 -0400 Subject: [PATCH 299/324] New definitions for Jasmine data driven tests --- .../jasmine-data_driven_tests-tests.ts | 54 +++++++++++++++++++ .../jasmine-data_driven_tests.d.ts | 7 +++ 2 files changed, 61 insertions(+) create mode 100644 jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts create mode 100644 jasmine-data_driven_tests/jasmine-data_driven_tests.d.ts diff --git a/jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts b/jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts new file mode 100644 index 000000000..df48df8cf --- /dev/null +++ b/jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts @@ -0,0 +1,54 @@ +/// +/// + +all("A data driven test is a suite with multiple specs", + ['a', 'b', 'c'], + (value: string) => { + expect(value).not.toBe('d'); + } +); + +all("A data driven test can have many arguments", + [ + [1, 2, 3], + [2, 4, 6] + ], + (a: number, b: number, c: number) => { + expect(c - (a + b)).toBe(0); + } +); + +all("A data driven test can be asynchronous", + [ + [3, 1], + [5, 2] + ], + (a: number, b: number, done: () => void) => { + setTimeout(() => { + expect(a - b > 0).toBe(true); + done(); + }, 50); + } +); + +xall("A data driven test can be pending", + [1, 2, 3], + (value: number) => { + expect(value < 4).toBe(true); + } +); + +describe("A suite", () => { + var a: number; + + beforeEach(() => { + a = 5; + }); + + all("can contain data driven tests", + [1, 2, 3], + (b: number) => { + expect(a - b > 0).toBe(true); + } + ); +}); \ No newline at end of file diff --git a/jasmine-data_driven_tests/jasmine-data_driven_tests.d.ts b/jasmine-data_driven_tests/jasmine-data_driven_tests.d.ts new file mode 100644 index 000000000..c0936872b --- /dev/null +++ b/jasmine-data_driven_tests/jasmine-data_driven_tests.d.ts @@ -0,0 +1,7 @@ +// Type definitions for Jasmine Data Driven Tests +// Project: https://github.com/gburghardt/jasmine-data_driven_tests +// Definitions by: Anthony MacKinnon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare function all(description: string, dataset: any[], specDefinitions: (...args: any[]) => void): void; +declare function xall(description: string, dataset: any[], specDefinitions: (...args: any[]) => void): void; \ No newline at end of file From 153b4f3fa354d799090212979ae559ec44dd05c4 Mon Sep 17 00:00:00 2001 From: Anthony Date: Sat, 9 Aug 2014 00:15:18 -0400 Subject: [PATCH 300/324] Renamed callback to assertion to be consistent with Jasmine naming --- jasmine-data_driven_tests/jasmine-data_driven_tests.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jasmine-data_driven_tests/jasmine-data_driven_tests.d.ts b/jasmine-data_driven_tests/jasmine-data_driven_tests.d.ts index c0936872b..912720e7f 100644 --- a/jasmine-data_driven_tests/jasmine-data_driven_tests.d.ts +++ b/jasmine-data_driven_tests/jasmine-data_driven_tests.d.ts @@ -3,5 +3,5 @@ // Definitions by: Anthony MacKinnon // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare function all(description: string, dataset: any[], specDefinitions: (...args: any[]) => void): void; -declare function xall(description: string, dataset: any[], specDefinitions: (...args: any[]) => void): void; \ No newline at end of file +declare function all(description: string, dataset: any[], assertion: (...args: any[]) => void): void; +declare function xall(description: string, dataset: any[], assertion: (...args: any[]) => void): void; \ No newline at end of file From 343cca373bca9e0241911b3cace7c4d303e5fd02 Mon Sep 17 00:00:00 2001 From: VILIC VANE Date: Sat, 9 Aug 2014 23:17:03 +0800 Subject: [PATCH 301/324] add definitions for q-retry --- CONTRIBUTORS.md | 1 + q-retry/q-retry-tests.ts | 39 +++++++++++++++++++++++++++++++++++++++ q-retry/q-retry.d.ts | 39 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 79 insertions(+) create mode 100644 q-retry/q-retry-tests.ts create mode 100644 q-retry/q-retry.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 1b2eda33d..fceb55e98 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -291,6 +291,7 @@ All definitions files include a header with the author and editors, so at some p * [ProgressJs](http://usablica.github.io/progress.js/) (by [Shunsuke Ohtani](https://github.com/zaneli)) * [Q](https://github.com/kriskowal/q) (by Barrie Nemetchek, Andrew Gaspar) * [Q-io](https://github.com/kriskowal/q-io) (by [Bart van der Schoor](https://github.com/Bartvds)) +* [q-retry](https://github.com/vilic/q-retry) (by [VILIC VANE](https://github.com/vilic)) * [QUnit](http://qunitjs.com/) (by [Diullei Gomes](https://github.com/Diullei)) * [Raven.js](https://github.com/getsentry/raven-js) (by [Santi Albo](https://github.com/santialbo)) * [Recaptcha.js](https://www.google.com/recaptcha) (by [Brent Jenkins](https://github.com/brentj73)) diff --git a/q-retry/q-retry-tests.ts b/q-retry/q-retry-tests.ts new file mode 100644 index 000000000..bf72f8ad7 --- /dev/null +++ b/q-retry/q-retry-tests.ts @@ -0,0 +1,39 @@ +import Q = require('q-retry'); + +Q + .retry(() => { + return ''; + }) + .then(str => { + str.charAt; + return 0; + }) + .retry(num => { + num.toFixed; + }) + .retry(() => { + + }, 5) + .retry(() => { + + }, (reason, retries) => { + retries.toFixed; + }) + .retry(() => { + + }, (reason, retries) => { + retries.toFixed; + }, 10) + .retry(() => { + return ''; + }, (reason, retries) => { + + }, { + limit: 10, + interval: 1000, + maxInterval: 20000, + intervalMultiplier: 1.5 + }) + .then(str => { + str.charAt; + }); \ No newline at end of file diff --git a/q-retry/q-retry.d.ts b/q-retry/q-retry.d.ts new file mode 100644 index 000000000..fe6b42fd8 --- /dev/null +++ b/q-retry/q-retry.d.ts @@ -0,0 +1,39 @@ +// Type definitions for q-retry +// Project: https://github.com/vilic/q-retry +// Definitions by: VILIC VANE +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Q { + export interface IRetryOptions { + limit?: number; + interval?: number; + maxInterval?: number; + intervalMultiplier?: number; + } + + export function retry(process: () => IPromise, onFail: (reason: any, retries: number) => void, limit: number): Promise; + export function retry(process: () => IPromise, onFail: (reason: any, retries: number) => void, options?: IRetryOptions): Promise; + export function retry(process: () => IPromise, limit: number): Promise; + export function retry(process: () => IPromise, options?: IRetryOptions): Promise; + export function retry(process: () => U, onFail: (reason: any, retries: number) => void, limit: number): Promise; + export function retry(process: () => U, onFail: (reason: any, retries: number) => void, options?: IRetryOptions): Promise; + export function retry(process: () => U, limit: number): Promise; + export function retry(process: () => U, options?: IRetryOptions): Promise; + + interface Promise { + retry(process: (value: T) => IPromise, onFail: (reason: any, retries: number) => void, limit: number): Promise; + retry(process: (value: T) => IPromise, onFail: (reason: any, retries: number) => void, options?: IRetryOptions): Promise; + retry(process: (value: T) => IPromise, limit: number): Promise; + retry(process: (value: T) => IPromise, options?: IRetryOptions): Promise; + retry(process: (value: T) => U, onFail: (reason: any, retries: number) => void, limit: number): Promise; + retry(process: (value: T) => U, onFail: (reason: any, retries: number) => void, options?: IRetryOptions): Promise; + retry(process: (value: T) => U, limit: number): Promise; + retry(process: (value: T) => U, options?: IRetryOptions): Promise; + } +} + +declare module "q-retry" { + export = Q; +} \ No newline at end of file From f402bb57bdc4cba9132a1498e7dc566b68629b98 Mon Sep 17 00:00:00 2001 From: VILIC VANE Date: Sun, 10 Aug 2014 00:55:22 +0800 Subject: [PATCH 302/324] add definitions for promise-pool --- CONTRIBUTORS.md | 1 + promise-pool/promise-pool-tests.ts | 47 +++++++++++ promise-pool/promise-pool.d.ts | 124 +++++++++++++++++++++++++++++ 3 files changed, 172 insertions(+) create mode 100644 promise-pool/promise-pool-tests.ts create mode 100644 promise-pool/promise-pool.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index fceb55e98..960b5dff2 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -289,6 +289,7 @@ All definitions files include a header with the author and editors, so at some p * [PouchDB](http://pouchdb.com) (by [Bill Sears](https://github.com/MrBigDog2U/)) * [PreloadJS](http://www.createjs.com/#!/PreloadJS) (by [Pedro Ferreira](https://bitbucket.org/drk4)) * [ProgressJs](http://usablica.github.io/progress.js/) (by [Shunsuke Ohtani](https://github.com/zaneli)) +* [promise-pool](https://github.com/vilic/promise-pool) (by [VILIC VANE](https://github.com/vilic)) * [Q](https://github.com/kriskowal/q) (by Barrie Nemetchek, Andrew Gaspar) * [Q-io](https://github.com/kriskowal/q-io) (by [Bart van der Schoor](https://github.com/Bartvds)) * [q-retry](https://github.com/vilic/q-retry) (by [VILIC VANE](https://github.com/vilic)) diff --git a/promise-pool/promise-pool-tests.ts b/promise-pool/promise-pool-tests.ts new file mode 100644 index 000000000..783d571ca --- /dev/null +++ b/promise-pool/promise-pool-tests.ts @@ -0,0 +1,47 @@ +import Q = require('q'); +import promisePool = require('promise-pool'); + +var pool = new promisePool.Pool((taskDataId, index) => { + return Q.delay(Math.floor(Math.random() * 5000)).then(function () { + taskDataId == 0; + index == 0; + }); +}, 20); + +pool + .pause() + .delay(5000) + .then(function () { + pool.resume(); + }); + +pool.retries == 0; +pool.retryInterval == 0; +pool.maxRetryInterval == 0; +pool.retryIntervalMultiplier == 0; + +pool.add(0); + +pool + .start(onProgress) + .then(result => { + result.total == 0; + return pool.reset(); + }) + .then(() => { + return pool.start(onProgress); + }) + .then(result => { + result.total == 0; + return pool.reset(); + }) + .then(() => { + pool.endless == true; + }); + +function onProgress(progress: promisePool.IProgress) { + progress.success == true; + progress.fulfilled == 0; + progress.total == 0; + progress.index == 0; +} \ No newline at end of file diff --git a/promise-pool/promise-pool.d.ts b/promise-pool/promise-pool.d.ts new file mode 100644 index 000000000..b38a54262 --- /dev/null +++ b/promise-pool/promise-pool.d.ts @@ -0,0 +1,124 @@ +// Type definitions for promise-pool +// Project: https://github.com/vilic/promise-pool +// Definitions by: VILIC VANE +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "promise-pool" { + /** + * interface for the final result. + */ + export interface IResult { + fulfilled: number; + rejected: number; + total: number; + } + /** + * interface for progress data. + */ + export interface IProgress { + index: number; + success: boolean; + error: any; + retries: number; + fulfilled: number; + rejected: number; + pending: number; + total: number; + } + /** + * tasks pool that manages concurrency. + */ + export class Pool { + /** + * (get/set) the max concurrency of this task pool. + */ + public concurrency: number; + private _tasksData; + /** + * (get/set) the processor function that handles tasks data. + */ + public processor: (data: T, index: number) => Q.Promise; + private _deferred; + private _pauseDeferred; + /** + * (get) the number of successful tasks. + */ + public fulfilled: number; + /** + * (get) the number of failed tasks. + */ + public rejected: number; + /** + * (get) the number of pending tasks. + */ + public pending: number; + /** + * (get) the number of completed tasks and pending tasks in total. + */ + public total: number; + /** + * (get/set) indicates whether this task pool is endless, if so, tasks can still be added even after all previous tasks have been fulfilled. + */ + public endless: boolean; + /** + * (get/set) defaults to 0, the number or retries that this task pool will take for every single task, could be Infinity. + */ + public retries: number; + /** + * (get/set) defaults to 0, interval (milliseconds) between each retries. + */ + public retryInterval: number; + /** + * (get/set) defaults to Infinity, max retry interval when retry interval multiplier applied. + */ + public maxRetryInterval: number; + /** + * (get/set) defaults to 1, the multiplier applies to interval after every retry. + */ + public retryIntervalMultiplier: number; + private _index; + private _currentConcurrency; + public onProgress: (progress: IProgress) => void; + /** + * initialize a task pool. + * @param processor a function takes the data and index as parameters and returns a promise. + * @param concurrency the concurrency of this task pool. + * @param endless defaults to false. indicates whether this task pool is endless, if so, tasks can still be added even after all previous tasks have been fulfilled. + * @param tasksData an initializing array of task data. + */ + constructor(processor: (data: T, index: number) => Q.Promise, concurrency: number, endless?: boolean, tasksData?: T[]); + /** + * add a data item. + * @param taskData task data to add. + */ + public add(taskData: T): void; + /** + * add data items. + * @param tasskData tasks data to add. + */ + public add(tasksData: T[]): void; + /** + * start tasks, return a promise that will be fulfilled after all tasks accomplish if endless is false. + * @param onProgress a callback that will be triggered every time when a single task is fulfilled. + */ + public start(onProgress?: (progress: IProgress) => void): Q.Promise; + private _start(); + private _process(data, index); + private _notifyProgress(index, success, err, retries); + private _next(); + /** + * pause tasks and return a promise that will be fulfilled after the running tasks accomplish. this will wait for running tasks to complete instead of aborting them. + */ + public pause(): Q.Promise; + /** + * resume tasks. + */ + public resume(): void; + /** + * pause tasks, then clear pending tasks data and reset counters. return a promise that will be fulfilled after resetting accomplish. + */ + public reset(): Q.Promise; + } +} \ No newline at end of file From 8ce72b147361bc618129405bd8ccaf5a5ac8e05c Mon Sep 17 00:00:00 2001 From: VILIC VANE Date: Sun, 10 Aug 2014 01:40:01 +0800 Subject: [PATCH 303/324] change processor return type from Q.Promise to Q.IPromise --- promise-pool/promise-pool.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/promise-pool/promise-pool.d.ts b/promise-pool/promise-pool.d.ts index b38a54262..b9214e7f0 100644 --- a/promise-pool/promise-pool.d.ts +++ b/promise-pool/promise-pool.d.ts @@ -39,7 +39,7 @@ declare module "promise-pool" { /** * (get/set) the processor function that handles tasks data. */ - public processor: (data: T, index: number) => Q.Promise; + public processor: (data: T, index: number) => Q.IPromise; private _deferred; private _pauseDeferred; /** @@ -88,7 +88,7 @@ declare module "promise-pool" { * @param endless defaults to false. indicates whether this task pool is endless, if so, tasks can still be added even after all previous tasks have been fulfilled. * @param tasksData an initializing array of task data. */ - constructor(processor: (data: T, index: number) => Q.Promise, concurrency: number, endless?: boolean, tasksData?: T[]); + constructor(processor: (data: T, index: number) => Q.IPromise, concurrency: number, endless?: boolean, tasksData?: T[]); /** * add a data item. * @param taskData task data to add. From 79139ac1702e0089445e2b8f8af4fb3160e2742c Mon Sep 17 00:00:00 2001 From: Anthony Date: Sat, 9 Aug 2014 13:54:31 -0400 Subject: [PATCH 304/324] Added name to contributors --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 5292ba4bf..c53c7559f 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -138,6 +138,7 @@ All definitions files include a header with the author and editors, so at some p * [IxJS (Interactive extensions)](https://github.com/Reactive-Extensions/IxJS) (by [Igor Oleinikov](https://github.com/Igorbek)) * [jake](https://github.com/mde/jake) (by [Kon](http://phyzkit.net/)) * [Jasmine](http://pivotal.github.com/jasmine/) (by [Boris Yankov](https://github.com/borisyankov)) +* [Jasmine-data_driven_tests](https://github.com/gburghardt/jasmine-data_driven_tests) (by [Anthony MacKinnon](https://github.com/AnthonyMacKinnon)) * [Jasmine-jQuery](https://github.com/velesin/jasmine-jquery) (by [Gregor Stamac](https://github.com/gstamac)) * [jDataView](https://github.com/jDataView/jDataView) (by [Ingvar Stepanyan](https://github.com/RReverser)) * [JointJS](http://www.jointjs.com/) (by [Aidan Reel](http://github.com/areel)) From f2de3867de193326103f9a394701efec4b452618 Mon Sep 17 00:00:00 2001 From: Paulo Cesar Date: Sat, 9 Aug 2014 18:15:54 -0300 Subject: [PATCH 305/324] squash! squash! fix tabs rootscope <> iscope --- angularjs/angular.d.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 282463bcb..1c3e96160 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -315,8 +315,7 @@ declare module ng { // Scope // see http://docs.angularjs.org/api/ng.$rootScope.Scope /////////////////////////////////////////////////////////////////////////// - interface IScope { - [index: string]: any; + interface IRootScopeService { $apply(): any; $apply(exp: string): any; $apply(exp: (scope: IScope) => any): any; @@ -353,6 +352,7 @@ declare module ng { $parent: IScope; $root: IRootScopeService; + this: IRootScopeService; $id: string; @@ -967,7 +967,9 @@ declare module ng { // RootScopeService // see http://docs.angularjs.org/api/ng.$rootScope /////////////////////////////////////////////////////////////////////////// - interface IRootScopeService extends IScope {} + interface IScope extends IRootScopeService { + [index: string]: any; + } /////////////////////////////////////////////////////////////////////////// // SCEService From 186c0182cd72798b4aa0ad11b7bf0f47db10ee09 Mon Sep 17 00:00:00 2001 From: Adrien Bustany Date: Sat, 9 Aug 2014 23:44:06 +0200 Subject: [PATCH 306/324] d3: Enable usage as an external module --- d3/d3.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 173603354..2229fa8a4 100755 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -3353,3 +3353,7 @@ declare module D3 { } declare var d3: D3.Base; + +declare module "d3" { + export = d3; +} From 548cb78ce6cd35fba48d31ec693f9dec44af433f Mon Sep 17 00:00:00 2001 From: Adrien Bustany Date: Sat, 9 Aug 2014 23:44:45 +0200 Subject: [PATCH 307/324] d3: Fix file permissions There is no reason to have this file executable. --- d3/d3.d.ts | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 d3/d3.d.ts diff --git a/d3/d3.d.ts b/d3/d3.d.ts old mode 100755 new mode 100644 From 16dffed6f38c4c6f12e42282b4b259336049e4ba Mon Sep 17 00:00:00 2001 From: basarat Date: Sun, 10 Aug 2014 20:59:13 +1000 Subject: [PATCH 308/324] angular: $scope extends $rootScope. closes #2593 --- angularjs/angular.d.ts | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 1c3e96160..cacf7647b 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -312,8 +312,8 @@ declare module ng { } /////////////////////////////////////////////////////////////////////////// - // Scope - // see http://docs.angularjs.org/api/ng.$rootScope.Scope + // Scope and RootScope + // see https://docs.angularjs.org/api/ng/type/$rootScope.Scope and http://docs.angularjs.org/api/ng.$rootScope /////////////////////////////////////////////////////////////////////////// interface IRootScopeService { $apply(): any; @@ -361,6 +361,10 @@ declare module ng { $$phase: any; } + interface IScope extends IRootScopeService { + [index: string]: any; + } + interface IAngularEvent { targetScope: IScope; currentScope: IScope; @@ -963,14 +967,6 @@ declare module ng { /////////////////////////////////////////////////////////////////////////// interface ITemplateCacheService extends ICacheObject {} - /////////////////////////////////////////////////////////////////////////// - // RootScopeService - // see http://docs.angularjs.org/api/ng.$rootScope - /////////////////////////////////////////////////////////////////////////// - interface IScope extends IRootScopeService { - [index: string]: any; - } - /////////////////////////////////////////////////////////////////////////// // SCEService // see http://docs.angularjs.org/api/ng.$sce From 3a8aadde8fbceaf599bde9be121a09508edc8760 Mon Sep 17 00:00:00 2001 From: electricessence Date: Mon, 11 Aug 2014 11:44:18 -0700 Subject: [PATCH 309/324] Updates for current compatibility... 1) Make Object3D inherit from EventDispatcher because it does... 2) Add setSize and domElement to Renderer interface because they are commonly used in boilerplate and it's better to return a "Renderer" depending on what is available. 3) Update ParticleSystemMaterial to PointCloudMaterial since ParticleSystemMaterial is deprecated. --- threejs/three.d.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 748900166..371e37da0 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -891,7 +891,7 @@ declare module THREE { /** * Base class for scene graph objects */ - export class Object3D { + export class Object3D extends EventDispatcher { constructor(); /** @@ -2169,7 +2169,7 @@ declare module THREE { clone(): MeshPhongMaterial; } - export interface ParticleSystemMaterialParameters { + export interface PointCloutMaterialParameters { color?: number; map?: Texture; size?: number; @@ -2178,7 +2178,7 @@ declare module THREE { fog?: boolean; } - export class ParticleSystemMaterial extends Material { + export class PointCloudMaterial extends Material { constructor(parameters?: ParticleSystemMaterialParameters); color: Color; map: Texture; @@ -3806,9 +3806,9 @@ declare module THREE { * @param geometry An instance of Geometry. * @param material An instance of Material (optional). */ - constructor(geometry: Geometry, material?: ParticleSystemMaterial); + constructor(geometry: Geometry, material?: PointCloudMaterial); constructor(geometry: Geometry, material?: ShaderMaterial); - constructor(geometry: BufferGeometry, material?: ParticleSystemMaterial); + constructor(geometry: BufferGeometry, material?: PointCloudMaterial); constructor(geometry: BufferGeometry, material?: ShaderMaterial); /** @@ -3872,6 +3872,8 @@ declare module THREE { export interface Renderer { render(scene: Scene, camera: Camera): void; + setSize(width:number, height:number, updateStyle?:boolean): void; + domElement: HTMLCanvasElement; } export interface CanvasRendererParameters { From 39a3186f8d15cbda489a53cba9c4416e424fdeea Mon Sep 17 00:00:00 2001 From: electricessence Date: Mon, 11 Aug 2014 11:47:40 -0700 Subject: [PATCH 310/324] Fixed typo PointClout to PointCloud --- threejs/three.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 371e37da0..584ad7df9 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -2169,7 +2169,7 @@ declare module THREE { clone(): MeshPhongMaterial; } - export interface PointCloutMaterialParameters { + export interface PointCloudMaterialParameters { color?: number; map?: Texture; size?: number; From 6861331875bc5a6b6e410d5c3e4f00d84b7d56bd Mon Sep 17 00:00:00 2001 From: electricessence Date: Mon, 11 Aug 2014 11:49:19 -0700 Subject: [PATCH 311/324] Fixed tabbing --- threejs/three.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 584ad7df9..7cf3a0d78 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -3872,8 +3872,8 @@ declare module THREE { export interface Renderer { render(scene: Scene, camera: Camera): void; - setSize(width:number, height:number, updateStyle?:boolean): void; - domElement: HTMLCanvasElement; + setSize(width:number, height:number, updateStyle?:boolean): void; + domElement: HTMLCanvasElement; } export interface CanvasRendererParameters { From dbd1973487d4f10fe371e8c19d8fe82f89549dd0 Mon Sep 17 00:00:00 2001 From: Steven Date: Mon, 11 Aug 2014 13:44:29 -0700 Subject: [PATCH 312/324] Updated Force Layout nodes and links Different layouts have different definitions for node objects and link objects. I created a new `GraphNodeForce` and `GraphLinkForce` interface for the Force Layout. See the [docs](https://github.com/mbostock/d3/wiki/Force-Layout#nodes) for more info. --- d3/d3.d.ts | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 2229fa8a4..026b6c405 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -1237,6 +1237,21 @@ declare module D3 { source: GraphNode; target: GraphNode; } + + export interface GraphNodeForce { + index?: number; + x?: number; + y?: number; + px?: number; + py?: number; + fixed?: boolean; + weight?: number; + } + + export interface GraphLinkForce { + source: GraphNodeForce; + target: GraphNodeForce; + } export interface ForceLayout { (): ForceLayout; @@ -1287,14 +1302,14 @@ declare module D3 { }; links: { - (): GraphLink[]; - (arLinks: GraphLink[]): ForceLayout; + (): GraphLinkForce[]; + (arLinks: GraphLinkForce[]): ForceLayout; }; nodes: { - (): GraphNode[]; - (arNodes: GraphNode[]): ForceLayout; + (): GraphNodeForce[]; + (arNodes: GraphNodeForce[]): ForceLayout; }; start(): ForceLayout; From 1ad980949158f2a3d040f51edfdee1cfc7f7fb12 Mon Sep 17 00:00:00 2001 From: nitram509 Date: Mon, 11 Aug 2014 22:52:44 +0200 Subject: [PATCH 313/324] added missing optional method parameter 'intersecting' see http://fabricjs.com/docs/fabric.Object.html#sendBackwards http://fabricjs.com/docs/fabric.Object.html#bringForward --- fabricjs/fabricjs.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fabricjs/fabricjs.d.ts b/fabricjs/fabricjs.d.ts index cfca6c481..d532b1c56 100644 --- a/fabricjs/fabricjs.d.ts +++ b/fabricjs/fabricjs.d.ts @@ -324,7 +324,7 @@ declare module fabric { setWidth(value: number): IObject; // methods - bringForward(): IObject; + bringForward(intersecting?: boolean): IObject; bringToFront(): IObject; center(): IObject; centerH(): IObject; @@ -355,7 +355,7 @@ declare module fabric { scale(value: number): IObject; scaleToHeight(value: number): IObject; scaleToWidth(value: number): IObject; - sendBackwards(): IObject; + sendBackwards(intersecting?: boolean): IObject; sendToBack(): IObject; set (properties: IObjectOptions): IObject; From 455f9dce68a893a55d8ba17ce748b4b2932966be Mon Sep 17 00:00:00 2001 From: vvakame Date: Tue, 12 Aug 2014 17:15:17 +0900 Subject: [PATCH 314/324] update angular-ui-router.d.ts --- angular-ui/angular-ui-router.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/angular-ui/angular-ui-router.d.ts b/angular-ui/angular-ui-router.d.ts index 081d35723..0f8eb5c57 100644 --- a/angular-ui/angular-ui-router.d.ts +++ b/angular-ui/angular-ui-router.d.ts @@ -13,6 +13,7 @@ declare module ng.ui { templateUrl?: any; templateProvider?: () => string; controller?: any; + controllerAs?: string; controllerProvider?: any; resolve?: {}; url?: string; From 98118d8d39d79e538e2acf01fab37a5de8921e74 Mon Sep 17 00:00:00 2001 From: Asger Feldthaus Date: Tue, 12 Aug 2014 16:38:53 +0200 Subject: [PATCH 315/324] three.js: Fix Quaternion.multiplyVector3 --- threejs/three.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 55ecde323..b9442abe3 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -3193,7 +3193,10 @@ declare module THREE { */ multiplyQuaternions(a: Quaternion, b: Quaternion): Quaternion; - multiplyVector3(vector: Vector3, dest: Vector3): Quaternion; + /** + * Deprecated. Use Vector3.applyQuaternion instead + */ + multiplyVector3(vector: Vector3): Vector3; /** * Clones this quaternion. From decf4875a67c28d909ac46c9700e5a71c2d74c82 Mon Sep 17 00:00:00 2001 From: froginvasion Date: Wed, 13 Aug 2014 14:28:33 +0200 Subject: [PATCH 316/324] removed methods in collection that were mixed in that are no longer there. Removed from View, it isnt there anymore since 0.9.0 --- backbone/backbone.d.ts | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index 3aeeb7d90..270b949aa 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -215,12 +215,10 @@ declare module Backbone { any(iterator: (element: TModel, index: number) => boolean, context?: any): boolean; collect(iterator: (element: TModel, index: number, context?: any) => any[], context?: any): any[]; chain(): any; - compact(): TModel[]; contains(value: any): boolean; countBy(iterator: (element: TModel, index: number) => any): _.Dictionary; countBy(attribute: string): _.Dictionary; detect(iterator: (item: any) => boolean, context?: any): any; // ??? - difference(...model: TModel[]): TModel[]; drop(): TModel; drop(n: number): TModel[]; each(iterator: (element: TModel, index: number, list?: any) => void, context?: any): any; @@ -229,7 +227,6 @@ declare module Backbone { find(iterator: (element: TModel, index: number) => boolean, context?: any): TModel; first(): TModel; first(n: number): TModel[]; - flatten(shallow?: boolean): TModel[]; foldl(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; forEach(iterator: (element: TModel, index: number, list?: any) => void, context?: any): any; groupBy(iterator: (element: TModel, index: number) => string, context?: any): _.Dictionary; @@ -239,7 +236,6 @@ declare module Backbone { initial(): TModel; initial(n: number): TModel[]; inject(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; - intersection(...model: TModel[]): TModel[]; isEmpty(object: any): boolean; invoke(methodName: string, arguments?: any[]): any; last(): TModel; @@ -248,7 +244,6 @@ declare module Backbone { map(iterator: (element: TModel, index: number, context?: any) => any[], context?: any): any[]; max(iterator?: (element: TModel, index: number) => any, context?: any): TModel; min(iterator?: (element: TModel, index: number) => any, context?: any): TModel; - object(...values: any[]): any[]; reduce(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; select(iterator: any, context?: any): any[]; size(): number; @@ -257,8 +252,6 @@ declare module Backbone { sortBy(iterator: (element: TModel, index: number) => number, context?: any): TModel[]; sortBy(attribute: string, context?: any): TModel[]; sortedIndex(element: TModel, iterator?: (element: TModel, index: number) => number): number; - range(stop: number, step?: number): any; - range(start: number, stop: number, step?: number): any; reduceRight(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any[]; reject(iterator: (element: TModel, index: number) => boolean, context?: any): TModel[]; rest(): TModel; @@ -266,10 +259,7 @@ declare module Backbone { tail(): TModel; tail(n: number): TModel[]; toArray(): any[]; - union(...model: TModel[]): TModel[]; - uniq(isSorted?: boolean, iterator?: (element: TModel, index: number) => boolean): TModel[]; without(...values: any[]): TModel[]; - zip(...model: TModel[]): TModel[]; } class Router extends Events { @@ -349,7 +339,6 @@ declare module Backbone { model: TModel; collection: Collection; //template: (json, options?) => string; - make(tagName: string, attrs?: any, opts?: any): View; setElement(element: HTMLElement, delegate?: boolean): View; setElement(element: JQuery, delegate?: boolean): View; id: string; From e7e263cae12fa2e8479139eed898ff75bd406085 Mon Sep 17 00:00:00 2001 From: jandersonBB Date: Wed, 13 Aug 2014 14:16:13 -0700 Subject: [PATCH 317/324] Update jasmine.d.ts https://groups.google.com/forum/#!topic/jasmine-js/LwlC-yCksY4 --- jasmine/jasmine.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/jasmine/jasmine.d.ts b/jasmine/jasmine.d.ts index 34e30cdd1..e3f46ca17 100644 --- a/jasmine/jasmine.d.ts +++ b/jasmine/jasmine.d.ts @@ -45,6 +45,7 @@ declare module jasmine { function createSpyObj(baseName: string, methodNames: any[]): T; function pp(value: any): string; function getEnv(): Env; + function addMatchers(matchers: any): Any; interface Any { From 728ef7843f4d09d4514241d1684ad3c7be5400e8 Mon Sep 17 00:00:00 2001 From: Asger Feldthaus Date: Thu, 14 Aug 2014 11:07:02 +0200 Subject: [PATCH 318/324] three.js: Reverted change to MeshFaceMaterial --- threejs/three.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index b9442abe3..e86db17c4 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -2079,7 +2079,7 @@ declare module THREE { clone(): MeshDepthMaterial; } - export class MeshFaceMaterial { + export class MeshFaceMaterial extends Material { constructor(materials?: Material[]); materials: Material[]; From a002a64b22572584599231ab1d19b029eb0e7317 Mon Sep 17 00:00:00 2001 From: yuuki Date: Fri, 15 Aug 2014 13:30:33 +0900 Subject: [PATCH 319/324] Fixed return type --- raphael/raphael.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/raphael/raphael.d.ts b/raphael/raphael.d.ts index e57aa3954..82dba5d4c 100644 --- a/raphael/raphael.d.ts +++ b/raphael/raphael.d.ts @@ -215,7 +215,7 @@ interface RaphaelPaper { renderfix(): void; safari(): void; set(elements?: RaphaelElement[]): RaphaelSet; - setFinish(): void; + setFinish(): RaphaelSet; setSize(width: number, height: number): void; setStart(): void; setViewBox(x: number, y: number, w: number, h: number, fit: boolean): void; From 317fb99d45adda1a5e38e8096e859bba1a211b8b Mon Sep 17 00:00:00 2001 From: Rogier Schouten Date: Fri, 15 Aug 2014 14:11:21 +0200 Subject: [PATCH 320/324] Created typings file for timezonecomplete version 1.4.6 --- .../timezonecomplete-1.3.0-tests.ts | 174 +++ timezonecomplete/timezonecomplete-1.3.0.d.ts | 702 ++++++++++ timezonecomplete/timezonecomplete.d.ts | 1170 +++++++++++------ 3 files changed, 1612 insertions(+), 434 deletions(-) create mode 100644 timezonecomplete/timezonecomplete-1.3.0-tests.ts create mode 100644 timezonecomplete/timezonecomplete-1.3.0.d.ts diff --git a/timezonecomplete/timezonecomplete-1.3.0-tests.ts b/timezonecomplete/timezonecomplete-1.3.0-tests.ts new file mode 100644 index 000000000..142b3f25a --- /dev/null +++ b/timezonecomplete/timezonecomplete-1.3.0-tests.ts @@ -0,0 +1,174 @@ +/// + +import tc = require("timezonecomplete"); + +var b: boolean = tc.isLeapYear(2014); +var n: number = tc.daysInMonth(2014, 10); +var s: string = tc.isoString(2014, 6, 30, 22, 10, 11, 230); + +// DURATION + +var d: tc.Duration; +var d1: tc.Duration = tc.Duration.hours(24); +var d2: tc.Duration = tc.Duration.minutes(24); +var d3: tc.Duration = tc.Duration.seconds(24); +var d4: tc.Duration = tc.Duration.milliseconds(24); +var d5: tc.Duration = new tc.Duration(24); +var d6: tc.Duration = new tc.Duration("00:01"); +var d7: tc.Duration = d6.clone(); + +n = d7.wholeHours(); +n = d7.hours(); +n = d7.minutes(); +n = d7.minute(); +n = d7.seconds(); +n = d7.second(); +n = d7.milliseconds(); +n = d7.millisecond(); +s = d7.sign(); +b = d7.lessThan(d6); +b = d7.greaterThan(d6); +d = d7.min(d6); +d = d7.max(d6); +d = d7.multiply(3); +d = d7.divide(0.3); +d = d7.add(d6); +d = d7.sub(d6); +s = d7.toString(); + +// TIMEZONE + +var t: tc.TimeZone; +var k: tc.TimeZoneKind; + +t = tc.TimeZone.local(); +t = tc.TimeZone.utc(); +t = tc.TimeZone.zone(2); +t = tc.TimeZone.zone("+01:00"); +s = t.name(); +k = t.kind(); +b = t.equals(t); +b = t.isUtc(); +n = t.offsetForUtc(2014, 1, 1, 13, 0, 5, 123); +n = t.offsetForZone(2014, 1, 1, 13, 0, 5, 123); +n = t.offsetForUtcDate(new Date(2014, 1, 1, 13, 0, 5, 123), tc.DateFunctions.Get); +n = t.offsetForZoneDate(new Date(2014, 1, 1, 13, 0, 5, 123), tc.DateFunctions.GetUTC); +s = t.toString(); +s = tc.TimeZone.offsetToString(2); +n = tc.TimeZone.stringToOffset("+00:01"); + +// REALTIMESOURCE + +var date: Date = (new tc.RealTimeSource()).now(); + +// DATETIME + +var dt: tc.DateTime; + +var ts: tc.TimeSource = tc.DateTime.timeSource; + +dt = tc.DateTime.nowLocal(); +dt = tc.DateTime.nowUtc(); +dt = tc.DateTime.now(tc.TimeZone.local()); +dt = new tc.DateTime(); +dt = new tc.DateTime("2014-01-01T13:05:01.123 UTC"); +dt = new tc.DateTime("2014-01-01T13:05:01.123", tc.TimeZone.utc()); +dt = new tc.DateTime(date, tc.DateFunctions.Get); +dt = new tc.DateTime(date, tc.DateFunctions.Get, tc.TimeZone.utc()); +dt = new tc.DateTime(2014, 1, 1, 13, 5, 1, 123); +dt = new tc.DateTime(2014, 1, 1, 13, 5, 1, 123, tc.TimeZone.utc()); +dt = new tc.DateTime(89949284); +dt = new tc.DateTime(89949284, tc.TimeZone.utc()); +dt = dt.clone(); +t = dt.zone(); +n = dt.offset(); +n = dt.year(); +n = dt.month(); +n = dt.day(); +n = dt.hour(); +n = dt.minute(); +n = dt.second(); +n = dt.millisecond(); +n = dt.unixUtcMillis(); +n = dt.utcYear(); +n = dt.utcMonth(); +n = dt.utcDay(); +n = dt.utcHour(); +n = dt.utcMinute(); +n = dt.utcSecond(); +n = dt.utcMillisecond(); +dt.convert(tc.TimeZone.local()); +dt = dt.toZone(tc.TimeZone.utc()); +date = dt.toDate(); +dt = dt.add(tc.Duration.seconds(2)); +dt = dt.add(2, tc.TimeUnit.Year); +dt = dt.add(2, tc.TimeUnit.Month); +dt = dt.add(2, tc.TimeUnit.Week); +dt = dt.add(2, tc.TimeUnit.Day); +dt = dt.add(2, tc.TimeUnit.Hour); +dt = dt.add(2, tc.TimeUnit.Minute); +dt = dt.add(2, tc.TimeUnit.Second); +dt = dt.addLocal(2, tc.TimeUnit.Second); +dt = dt.sub(tc.Duration.seconds(2)); +dt = dt.sub(2, tc.TimeUnit.Year); +dt = dt.sub(2, tc.TimeUnit.Month); +dt = dt.sub(2, tc.TimeUnit.Week); +dt = dt.sub(2, tc.TimeUnit.Day); +dt = dt.sub(2, tc.TimeUnit.Hour); +dt = dt.sub(2, tc.TimeUnit.Minute); +dt = dt.sub(2, tc.TimeUnit.Second); +dt = dt.subLocal(2, tc.TimeUnit.Second); +d = dt.diff(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.lessThan(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.lessEqual(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.greaterThan(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.greaterEqual(new tc.DateTime(9289234, tc.TimeZone.local())); +s = dt.toIsoString(); +s = dt.toString(); +s = dt.toUtcString(); + +var wd: tc.WeekDay; +wd = dt.weekDay(); +wd = dt.utcWeekDay(); + +// PERIOD + +s = tc.periodDstToString(tc.PeriodDst.RegularIntervals); +s = tc.periodDstToString(tc.PeriodDst.RegularLocalTime); + +var p: tc.Period; + +p = new tc.Period(tc.DateTime.nowLocal(), 1, tc.TimeUnit.Hour, tc.PeriodDst.RegularLocalTime); +dt = p.start(); +n = p.amount(); +var tu: tc.TimeUnit = p.unit(); +var pd: tc.PeriodDst = p.dst(); +dt = p.findFirst(tc.DateTime.nowLocal()); +dt = p.findNext(dt); +s = p.toIsoString(); +s = p.toString(); + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/timezonecomplete/timezonecomplete-1.3.0.d.ts b/timezonecomplete/timezonecomplete-1.3.0.d.ts new file mode 100644 index 000000000..6fbea6f6f --- /dev/null +++ b/timezonecomplete/timezonecomplete-1.3.0.d.ts @@ -0,0 +1,702 @@ +// Type definitions for timezonecomplete 1.3.0 +// Project: https://github.com/SpiritIT/timezonecomplete +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Generated by dts-bundle v0.2.0 + +declare module 'timezonecomplete' { + /** + * @return True iff the given year is a leap year. + */ + export function isLeapYear(year: number): boolean; + /** + * @param year The full year + * @param month The month 1-12 + * @return The number of days in the given month + */ + export function daysInMonth(year: number, month: number): number; + /** + * Returns an ISO time string. Note that months are 1-12. + */ + export function isoString(year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number): string; + /** + * Time units + */ + export enum TimeUnit { + Second = 0, + Minute = 1, + Hour = 2, + Day = 3, + Week = 4, + Month = 5, + Year = 6, + } + /** + * Time duration. Create one e.g. like this: var d = Duration.hours(1). + * Note that time durations do not take leap seconds etc. into account: + * one hour is simply represented as 3600000 milliseconds. + */ + export class Duration { + /** + * Construct a time duration + * @param n Number of hours + * @return A duration of n hours + */ + static hours(n: number): Duration; + /** + * Construct a time duration + * @param n Number of minutes + * @return A duration of n minutes + */ + static minutes(n: number): Duration; + /** + * Construct a time duration + * @param n Number of seconds + * @return A duration of n seconds + */ + static seconds(n: number): Duration; + /** + * Construct a time duration + * @param n Number of milliseconds + * @return A duration of n milliseconds + */ + static milliseconds(n: number): Duration; + /** + * Construct a time duration of 0 + */ + constructor(); + /** + * Construct a time duration from a number of milliseconds + */ + constructor(milliseconds: number); + /** + * Construct a time duration from a string in format + * [-]h[:m[:s[.n]]] e.g. -01:00:30.501 + */ + constructor(input: string); + /** + * @return another instance of Duration with the same value. + */ + clone(): Duration; + /** + * The entire duration in milliseconds (negative or positive) + */ + milliseconds(): number; + /** + * The millisecond part of the duration (always positive) + * @return e.g. 400 for a -01:02:03.400 duration + */ + millisecond(): number; + /** + * The entire duration in seconds (negative or positive, fractional) + * @return e.g. 1.5 for a 1500 milliseconds duration + */ + seconds(): number; + /** + * The second part of the duration (always positive) + * @return e.g. 3 for a -01:02:03.400 duration + */ + second(): number; + /** + * The entire duration in minutes (negative or positive, fractional) + * @return e.g. 1.5 for a 90000 milliseconds duration + */ + minutes(): number; + /** + * The minute part of the duration (always positive) + * @return e.g. 2 for a -01:02:03.400 duration + */ + minute(): number; + /** + * The entire duration in hours (negative or positive, fractional) + * @return e.g. 1.5 for a 5400000 milliseconds duration + */ + hours(): number; + /** + * The hour part of the duration (always positive). + * Note that this part can exceed 23 hours, because for + * now, we do not have a days() function + * @return e.g. 25 for a -25:02:03.400 duration + */ + wholeHours(): number; + /** + * Sign + * @return "-" if the duration is negative + */ + sign(): string; + /** + * @return True iff (this < other) + */ + lessThan(other: Duration): boolean; + /** + * @return True iff this and other represent the same time duration + */ + equals(other: Duration): boolean; + /** + * @return True iff this > other + */ + greaterThan(other: Duration): boolean; + /** + * @return The minimum (most negative) of this and other + */ + min(other: Duration): Duration; + /** + * @return The maximum (most positive) of this and other + */ + max(other: Duration): Duration; + /** + * Multiply with a fixed number. + * @return a new Duration of (this * value) + */ + multiply(value: number): Duration; + /** + * Divide by a fixed number. + * @return a new Duration of (this / value) + */ + divide(value: number): Duration; + /** + * Add a duration. + * @return a new Duration of (this + value) + */ + add(value: Duration): Duration; + /** + * Subtract a duration. + * @return a new Duration of (this - value) + */ + sub(value: Duration): Duration; + /** + * String in [-]hh:mm:ss.nnn notation. All fields are + * always present except the sign. + */ + toFullString(): string; + /** + * String in [-]hh[:mm[:ss[.nnn]]] notation. Fields are + * added as necessary + */ + toString(): string; + } + /** + * The type of time zone + */ + export enum TimeZoneKind { + /** + * Local time offset as determined by JavaScript Date class. + */ + Local = 0, + /** + * Fixed offset from UTC, without DST. + */ + Offset = 1, + /** + * IANA timezone managed through Olsen TZ database. Includes + * DST if applicable. + */ + Proper = 2, + } + /** + * Time zone. The object is immutable because it is cached: + * requesting a time zone twice yields the very same object. + * Note that we use time zone offsets inverted w.r.t. JavaScript Date.getTimezoneOffset(), + * i.e. offset 90 means +01:30. + * + * Time zones come in three flavors: the local time zone, as calculated by JavaScript Date, + * a fixed offset ("+01:30") without DST, or a IANA timezone ("Europe/Amsterdam") with DST + * applied depending on the time zone rules. + */ + export class TimeZone { + /** + * The local time zone for a given date. Note that + * the time zone varies with the date: amsterdam time for + * 2014-01-01 is +01:00 and amsterdam time for 2014-07-01 is +02:00 + */ + static local(): TimeZone; + /** + * The UTC time zone. + */ + static utc(): TimeZone; + /** + * Returns a time zone object from the cache. If it does not exist, it is created. + * @return The time zone with the given offset w.r.t. UTC in minutes, e.g. 90 for +01:30 + */ + static zone(offset: number): TimeZone; + /** + * Returns a time zone object from the cache. If it does not exist, it is created. + * @param s: Empty string for local time, a TZ database time zone name (e.g. Europe/Amsterdam) + * or an offset string (either +01:30, +0130, +01, Z). For a full list of names, see: + * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones + */ + static zone(s: string): TimeZone; + /** + * The time zone identifier. Can be an offset "-01:30" or an + * IANA time zone name "Europe/Amsterdam", or "localtime" for + * the local time zone. + */ + name(): string; + /** + * The kind of time zone (Local/Offset/Proper) + */ + kind(): TimeZoneKind; + /** + * Equality operator. Maps zero offsets and different names for UTC onto + * each other. Other time zones are not mapped onto each other. + */ + equals(other: TimeZone): boolean; + /** + * Is this zone equivalent to UTC? + */ + isUtc(): boolean; + /** + * Calculate timezone offset from a UTC time. + * @param year local full year + * @param month local month 1-12 (note this deviates from JavaScript date) + * @param day local day of month 1-31 + * @param hour local hour 0-23 + * @param minute local minute 0-59 + * @param second local second 0-59 + * @param millisecond local millisecond 0-999 + * @return the offset of this time zone with respect to UTC at the given time. + */ + offsetForUtc(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; + /** + * Calculate timezone offset from a zone-local time (NOT a UTC time). + * @param year local full year + * @param month local month 1-12 (note this deviates from JavaScript date) + * @param day local day of month 1-31 + * @param hour local hour 0-23 + * @param minute local minute 0-59 + * @param second local second 0-59 + * @param millisecond local millisecond 0-999 + * @return the offset of this time zone with respect to UTC at the given time. + */ + offsetForZone(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; + /** + * Convenience function, takes values from a Javascript Date + * Calls offsetForUtc() with the contents of the date + * @param date: the date + * @param funcs: the set of functions to use: get() or getUTC() + */ + offsetForUtcDate(date: Date, funcs: DateFunctions): number; + /** + * Convenience function, takes values from a Javascript Date + * Calls offsetForUtc() with the contents of the date + * @param date: the date + * @param funcs: the set of functions to use: get() or getUTC() + */ + offsetForZoneDate(date: Date, funcs: DateFunctions): number; + /** + * The time zone identifier (normalized). + * Either "localtime", IANA name, or "+hh:mm" offset. + */ + toString(): string; + /** + * Convert an offset number into an offset string + * @param offset The offset in minutes from UTC e.g. 90 minutes + * @return the offset in ISO notation "+01:30" for +90 minutes + */ + static offsetToString(offset: number): string; + /** + * String to offset conversion. + * @param s Formats: "-01:00", "-0100", "-01", "Z" + * @return offset w.r.t. UTC in minutes + */ + static stringToOffset(s: string): number; + } + /** + * For testing purposes, we often need to manipulate what the current + * time is. This is an interface for a custom time source object + * so in tests you can use a custom time source. + */ + export interface TimeSource { + /** + * Return the current date+time as a javascript Date object + */ + now(): Date; + } + /** + * Default time source, returns actual time + */ + export class RealTimeSource implements TimeSource { + now(): Date; + } + /** + * Indicates how a Date object should be interpreted. + * Either we can take getYear(), getMonth() etc for our field + * values, or we can take getUTCYear() etc to do that. + */ + export enum DateFunctions { + /** + * Use the Date.getFullYear(), Date.getMonth(), ... functions. + */ + Get = 0, + /** + * Use the Date.getUTCFullYear(), Date.getUTCMonth(), ... functions. + */ + GetUTC = 1, + } + /** + * Day-of-week. Note the enum values correspond to JavaScript day-of-week: + * Sunday = 0, Monday = 1 etc + */ + export enum WeekDay { + Sunday = 0, + Monday = 1, + Tuesday = 2, + Wednesday = 3, + Thursday = 4, + Friday = 5, + Saturday = 6, + } + /** + * Our very own DateTime class which is time zone-aware + * and which can be mocked for testing purposes + */ + export class DateTime { + /** + * Actual time source in use. Setting this property allows to + * fake time in tests. DateTime.nowLocal() and DateTime.nowUtc() + * use this property for obtaining the current time. + */ + static timeSource: TimeSource; + /** + * Current date+time in local time (derived from DateTime.timeSource.now()). + */ + static nowLocal(): DateTime; + /** + * Current date+time in UTC time (derived from DateTime.timeSource.now()). + */ + static nowUtc(): DateTime; + /** + * Current date+time in the given time zone (derived from DateTime.timeSource.now()). + * @param timeZone The desired time zone. + */ + static now(timeZone: TimeZone): DateTime; + /** + * Constructor. Creates current time in local timezone. + */ + constructor(); + /** + * Constructor + * @param isoString String in ISO 8601 format. Instead of ISO time zone, + * it may include a space and then and IANA time zone. + * e.g. "2007-04-05T12:30:40.500" (no time zone, naive date) + * e.g. "2007-04-05T12:30:40.500+01:00" (UTC offset without daylight saving time) + * or "2007-04-05T12:30:40.500Z" (UTC) + * or "2007-04-05T12:30:40.500 Europe/Amsterdam" (IANA time zone, with daylight saving time if applicable) + * @param timeZone if given, the date in the string is assumed to be in this time zone. + * Note that it is NOT CONVERTED to the time zone. Useful + * for strings without a time zone + */ + constructor(isoString: string, timeZone?: TimeZone); + /** + * Constructor. You provide a date, then you say whether to take the + * date.getYear()/getXxx methods or the date.getUTCYear()/date.getUTCXxx methods, + * and then you state which time zone that date is in. + * + * @param date A date object. + * @param getters Specifies which set of Date getters contains the date in the given time zone: the + * Date.getXxx() methods or the Date.getUTCXxx() methods. + * @param timeZone The time zone that the given date is assumed to be in (may be null for unaware dates) + */ + constructor(date: Date, getFuncs: DateFunctions, timeZone?: TimeZone); + /** + * Constructor. Note that unlike JavaScript dates we require fields to be in normal ranges. + * Use the add(duration) or sub(duration) for arithmetic. + * @param year The full year (e.g. 2014) + * @param month The month [1-12] (note this deviates from JavaScript Date) + * @param day The day of the month [1-31] + * @param hour The hour of the day [0-24) + * @param minute The minute of the hour [0-59] + * @param second The second of the minute [0-59] + * @param millisecond The millisecond of the second [0-999] + * @param timeZone The time zone, or null (for unaware dates) + */ + constructor(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number, timeZone?: TimeZone); + /** + * Constructor + * @param unixTimestamp milliseconds since 1970-01-01T00:00:00.000 + * @param timeZone the time zone that the timestamp is assumed to be in (usually UTC). + */ + constructor(unixTimestamp: number, timeZone?: TimeZone); + /** + * @return a copy of this object + */ + clone(): DateTime; + /** + * @return The time zone that the date is in. May be null for unaware dates. + */ + zone(): TimeZone; + /** + * @return the offset w.r.t. UTC in minutes. Returns 0 for unaware dates and for UTC dates. + */ + offset(): number; + /** + * @return The full year e.g. 2014 + */ + year(): number; + /** + * @return The month 1-12 (note this deviates from JavaScript Date) + */ + month(): number; + /** + * @return The day of the month 1-31 + */ + day(): number; + /** + * @return The hour 0-23 + */ + hour(): number; + /** + * @return the minutes 0-59 + */ + minute(): number; + /** + * @return the seconds 0-59 + */ + second(): number; + /** + * @return the milliseconds 0-999 + */ + millisecond(): number; + /** + * @return the day-of-week (the enum values correspond to JavaScript + * week day numbers) + */ + weekDay(): WeekDay; + /** + * @return Milliseconds since 1970-01-01T00:00:00.000Z + */ + unixUtcMillis(): number; + /** + * @return The full year e.g. 2014 + */ + utcYear(): number; + /** + * @return The UTC month 1-12 (note this deviates from JavaScript Date) + */ + utcMonth(): number; + /** + * @return The UTC day of the month 1-31 + */ + utcDay(): number; + /** + * @return The UTC hour 0-23 + */ + utcHour(): number; + /** + * @return The UTC minutes 0-59 + */ + utcMinute(): number; + /** + * @return The UTC seconds 0-59 + */ + utcSecond(): number; + /** + * @return The UTC milliseconds 0-999 + */ + utcMillisecond(): number; + /** + * @return the UTC day-of-week (the enum values correspond to JavaScript + * week day numbers) + */ + utcWeekDay(): WeekDay; + /** + * Convert this date to the given time zone (in-place). + * Throws if this date does not have a time zone. + * @return this (for chaining) + */ + convert(zone?: TimeZone): DateTime; + /** + * Returns this date converted to the given time zone. + * Unaware dates can only be converted to unaware dates (clone) + * For unaware dates, an exception is thrown + * @param zone The new time zone. This may be null to create unaware date. + * @return The converted date + */ + toZone(zone?: TimeZone): DateTime; + /** + * Convert to JavaScript date with the zone time in the getX() methods. + * Unless the timezone is local, the Date.getUTCX() methods will NOT be correct. + */ + toDate(): Date; + /** + * Add a time duration. Note that this simply adds a number + * of milliseconds to UTC and converts back to zone(), + * so in the presence of e.g. leap seconds there may be a + * shift in the seconds field if you add an hour. + * There is not DST handling and no leap second handling. + * @return this + duration + */ + add(duration: Duration): DateTime; + /** + * Add an amount of time to UTC, taking leap seconds etc into account. + * Adding e.g. 1 hour will increment the utcHour() field + * date by one. In case of DST changes, the local hour() field + * may not increase or increase by 2 hours. So if you add a month, the + * local time may vary by an hour. There will not be a shift + * in seconds due to leap seconds. + */ + add(amount: number, unit: TimeUnit): DateTime; + /** + * Add an amount of time to the zone time, as regularly as possible. + * Adding e.g. 1 hour will increment the hour() field of the zone + * date by one. In case of DST changes, the utcHour() field may + * increase by 1 or increase by 2. Adding a day will leave the time portion + * intact. However, adding an hour around a forward DST change adds two hours, + * since there is a zone time (2AM in Holland) that does not exist. + */ + addLocal(amount: number, unit: TimeUnit): DateTime; + /** + * Same as add(-1*duration); + */ + sub(duration: Duration): DateTime; + /** + * Same as add(-1*amount, unit); + */ + sub(amount: number, unit: TimeUnit): DateTime; + /** + * Same as addLocal(-1*amount, unit); + */ + subLocal(amount: number, unit: TimeUnit): DateTime; + /** + * Time difference between two DateTimes + * @return this - other + */ + diff(other: DateTime): Duration; + /** + * @return True iff (this < other) + */ + lessThan(other: DateTime): boolean; + /** + * @return True iff (this <= other) + */ + lessEqual(other: DateTime): boolean; + /** + * @return True iff this and other represent the same time in UTC + */ + equals(other: DateTime): boolean; + /** + * @return True iff this and other represent the same time and + * have the same zone + */ + identical(other: DateTime): boolean; + /** + * @return True iff this > other + */ + greaterThan(other: DateTime): boolean; + /** + * @return True iff this >= other + */ + greaterEqual(other: DateTime): boolean; + /** + * Proper ISO 8601 format string with any IANA zone converted to ISO offset + * E.g. "2014-01-01T23:15:33+01:00" for Europe/Amsterdam + */ + toIsoString(): string; + /** + * Modified ISO 8601 format string with IANA name if applicable. + * E.g. "2014-01-01T23:15:33.000 Europe/Amsterdam" + */ + toString(): string; + /** + * Modified ISO 8601 format string in UTC without time zone info + */ + toUtcString(): string; + } + /** + * Specifies how the period should repeat across the day + * during DST changes. + */ + export enum PeriodDst { + /** + * Keep repeating in similar intervals measured in UTC, + * unaffected by Daylight Saving Time. + * E.g. a repetition of one hour will take one real hour + * every time, even in a time zone with DST. + * Leap seconds, leap days and month length + * differences will still make the intervals different. + */ + RegularIntervals = 0, + /** + * Ensure that the time at which the intervals occur stay + * at the same place in the day, local time. So e.g. + * a period of one day, starting at 8:05AM Europe/Amsterdam time + * will always start at 8:05 Europe/Amsterdam. This means that + * in UTC time, some intervals will be 25 hours and some + * 23 hours during DST changes. + * Another example: an hourly interval will be hourly in local time, + * skipping an hour in UTC for a DST backward change. + */ + RegularLocalTime = 1, + } + /** + * Convert a PeriodDst to a string: "regular intervals" or "regular local time" + */ + export function periodDstToString(p: PeriodDst): string; + /** + * Repeating time period: consists of a starting point and + * a time length. This class accounts for leap seconds and leap days. + */ + export class Period { + /** + * Constructor + * LIMITATION: if dst equals RegularLocalTime, and unit is Second, Minute or Hour, + * then the amount must be a factor of 24. So 120 seconds is allowed while 121 seconds is not. + * This is due to the enormous processing power required by these cases. They are not + * implemented and you will get an assert. + * + * @param start The start of the period. If the period is in Months or Years, and + * the day is 29 or 30 or 31, the results are maximised to end-of-month. + * @param amount The amount of units. + * @param unit The unit. + * @param dst Specifies how to handle Daylight Saving Time. Not relevant + * if the time zone of the start datetime does not have DST. + */ + constructor(start: DateTime, amount: number, unit: TimeUnit, dst: PeriodDst); + /** + * The start date + */ + start(): DateTime; + /** + * The amount of units + */ + amount(): number; + /** + * The unit + */ + unit(): TimeUnit; + /** + * The dst handling mode + */ + dst(): PeriodDst; + /** + * The first occurrence of the period greater than + * the given date. The given date need not be at a period boundary. + * Pre: the fromdate and startdate must either both have timezones or not + * @param fromDate: the date after which to return the next date + * @return the first date matching the period after fromDate, given + * in the same zone as the fromDate. + */ + findFirst(fromDate: DateTime): DateTime; + /** + * Returns the next timestamp in the period. The given timestamp must + * be at a period boundary, otherwise the answer is incorrect. + * This function has MUCH better performance than findFirst. + * Returns the datetime "count" times away from the given datetime. + * @param prev Boundary date. Must have a time zone (any time zone) iff the period start date has one. + * @param count Optional, must be >= 1 and whole. + * @return (prev + count * period), in the same timezone as prev. + */ + findNext(prev: DateTime, count?: number): DateTime; + /** + * Returns an ISO duration string + * P[n]Y[n]M[n]DT[n]H[n]M[n][.n]S or P[n]W + */ + toIsoString(): string; + /** + * A string representation e.g. + * "10 years, starting at 2014-03-01T12:00:00 Europe/Amsterdam keeping regular intervals". + */ + toString(): string; + } +} + diff --git a/timezonecomplete/timezonecomplete.d.ts b/timezonecomplete/timezonecomplete.d.ts index 6fbea6f6f..46b202e8f 100644 --- a/timezonecomplete/timezonecomplete.d.ts +++ b/timezonecomplete/timezonecomplete.d.ts @@ -1,24 +1,54 @@ -// Type definitions for timezonecomplete 1.3.0 +// Type definitions for timezonecomplete 1.4.6 // Project: https://github.com/SpiritIT/timezonecomplete // Definitions by: Rogier Schouten // Definitions: https://github.com/borisyankov/DefinitelyTyped // Generated by dts-bundle v0.2.0 declare module 'timezonecomplete' { + import basics = require("__timezonecomplete/basics"); + export import TimeUnit = basics.TimeUnit; + export import WeekDay = basics.WeekDay; + export import isLeapYear = basics.isLeapYear; + export import daysInMonth = basics.daysInMonth; + export import daysInYear = basics.daysInYear; + export import dayOfYear = basics.dayOfYear; + export import lastWeekDayOfMonth = basics.lastWeekDayOfMonth; + export import weekDayOnOrAfter = basics.weekDayOnOrAfter; + export import weekDayOnOrBefore = basics.weekDayOnOrBefore; + import datetime = require("__timezonecomplete/datetime"); + export import DateTime = datetime.DateTime; + import duration = require("__timezonecomplete/duration"); + export import Duration = duration.Duration; + import javascript = require("__timezonecomplete/javascript"); + export import DateFunctions = javascript.DateFunctions; + import period = require("__timezonecomplete/period"); + export import Period = period.Period; + export import PeriodDst = period.PeriodDst; + export import periodDstToString = period.periodDstToString; + import timesource = require("__timezonecomplete/timesource"); + export import TimeSource = timesource.TimeSource; + export import RealTimeSource = timesource.RealTimeSource; + import timezone = require("__timezonecomplete/timezone"); + export import NormalizeOption = timezone.NormalizeOption; + export import TimeZoneKind = timezone.TimeZoneKind; + export import TimeZone = timezone.TimeZone; +} + +declare module '__timezonecomplete/basics' { + import javascript = require("__timezonecomplete/javascript"); /** - * @return True iff the given year is a leap year. + * Day-of-week. Note the enum values correspond to JavaScript day-of-week: + * Sunday = 0, Monday = 1 etc */ - export function isLeapYear(year: number): boolean; - /** - * @param year The full year - * @param month The month 1-12 - * @return The number of days in the given month - */ - export function daysInMonth(year: number, month: number): number; - /** - * Returns an ISO time string. Note that months are 1-12. - */ - export function isoString(year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number): string; + export enum WeekDay { + Sunday = 0, + Monday = 1, + Tuesday = 2, + Wednesday = 3, + Thursday = 4, + Friday = 5, + Saturday = 6, + } /** * Time units */ @@ -31,6 +61,476 @@ declare module 'timezonecomplete' { Month = 5, Year = 6, } + /** + * @return True iff the given year is a leap year. + */ + export function isLeapYear(year: number): boolean; + /** + * The days in a given year + */ + export function daysInYear(year: number): number; + /** + * @param year The full year + * @param month The month 1-12 + * @return The number of days in the given month + */ + export function daysInMonth(year: number, month: number): number; + /** + * Returns the day of the year of the given date [0..365]. January first is 0. + * + * @param year The year e.g. 1986 + * @param month Month 1-12 + * @param day Day of month 1-31 + */ + export function dayOfYear(year: number, month: number, day: number): number; + /** + * Returns the last instance of the given weekday in the given month + * + * @param year The year + * @param month the month 1-12 + * @param weekDay the desired week day + * + * @return the last occurrence of the week day in the month + */ + export function lastWeekDayOfMonth(year: number, month: number, weekDay: WeekDay): number; + /** + * Returns the day-of-month that is on the given weekday and which is >= the given day. + * Throws if the month has no such day. + */ + export function weekDayOnOrAfter(year: number, month: number, day: number, weekDay: WeekDay): number; + /** + * Returns the day-of-month that is on the given weekday and which is <= the given day. + * Throws if the month has no such day. + */ + export function weekDayOnOrBefore(year: number, month: number, day: number, weekDay: WeekDay): number; + /** + * Convert a unix milli timestamp into a TimeT structure. + * This does NOT take leap seconds into account. + */ + export function unixToTimeNoLeapSecs(unixMillis: number): TimeStruct; + /** + * Convert a year, month, day etc into a unix milli timestamp. + * This does NOT take leap seconds into account. + * + * @param year Year e.g. 1970 + * @param month Month 1-12 + * @param day Day 1-31 + * @param hour Hour 0-23 + * @param minute Minute 0-59 + * @param second Second 0-59 (no leap seconds) + * @param milli Millisecond 0-999 + */ + export function timeToUnixNoLeapSecs(year?: number, month?: number, day?: number, hour?: number, minute?: number, second?: number, milli?: number): number; + /** + * Convert a TimeT structure into a unix milli timestamp. + * This does NOT take leap seconds into account. + */ + export function timeToUnixNoLeapSecs(tm: TimeStruct): number; + /** + * Return the day-of-week. + * This does NOT take leap seconds into account. + */ + export function weekDayNoLeapSecs(unixMillis: number): WeekDay; + /** + * Basic representation of a date and time + */ + export class TimeStruct { + /** + * Year, 1970-... + */ + year: number; + /** + * Month 1-12 + */ + month: number; + /** + * Day of month, 1-31 + */ + day: number; + /** + * Hour 0-23 + */ + hour: number; + /** + * Minute 0-59 + */ + minute: number; + /** + * Seconds, 0-59 + */ + second: number; + /** + * Milliseconds 0-999 + */ + milli: number; + /** + * Create a TimeStruct from a number of unix milliseconds + */ + static fromUnix(unixMillis: number): TimeStruct; + /** + * Create a TimeStruct from a JavaScript date + * + * @param d The date + * @param df Which functions to take (getX() or getUTCX()) + */ + static fromDate(d: Date, df: javascript.DateFunctions): TimeStruct; + /** + * Returns a TimeStruct from an ISO 8601 string WITHOUT time zone + */ + static fromString(s: string): TimeStruct; + /** + * Constructor + * + * @param year Year e.g. 1970 + * @param month Month 1-12 + * @param day Day 1-31 + * @param hour Hour 0-23 + * @param minute Minute 0-59 + * @param second Second 0-59 (no leap seconds) + * @param milli Millisecond 0-999 + */ + constructor(/** + * Year, 1970-... + */ + year?: number, /** + * Month 1-12 + */ + month?: number, /** + * Day of month, 1-31 + */ + day?: number, /** + * Hour 0-23 + */ + hour?: number, /** + * Minute 0-59 + */ + minute?: number, /** + * Seconds, 0-59 + */ + second?: number, /** + * Milliseconds 0-999 + */ + milli?: number); + /** + * Validate a TimeStruct, returns false if invalid. + */ + validate(): boolean; + /** + * The day-of-year 0-365 + */ + yearDay(): number; + /** + * Returns this time as a unix millisecond timestamp + * Does NOT take leap seconds into account. + */ + toUnixNoLeapSecs(): number; + /** + * Deep equals + */ + equals(other: TimeStruct): boolean; + /** + * < operator + */ + lessThan(other: TimeStruct): boolean; + clone(): TimeStruct; + valueOf(): number; + /** + * ISO 8601 string YYYY-MM-DDThh:mm:ss.nnn + */ + toString(): string; + inspect(): string; + } +} + +declare module '__timezonecomplete/datetime' { + import basics = require("__timezonecomplete/basics"); + import duration = require("__timezonecomplete/duration"); + import javascript = require("__timezonecomplete/javascript"); + import timesource = require("__timezonecomplete/timesource"); + import timezone = require("__timezonecomplete/timezone"); + /** + * DateTime class which is time zone-aware + * and which can be mocked for testing purposes. + */ + export class DateTime { + /** + * Actual time source in use. Setting this property allows to + * fake time in tests. DateTime.nowLocal() and DateTime.nowUtc() + * use this property for obtaining the current time. + */ + static timeSource: timesource.TimeSource; + /** + * Current date+time in local time (derived from DateTime.timeSource.now()). + */ + static nowLocal(): DateTime; + /** + * Current date+time in UTC time (derived from DateTime.timeSource.now()). + */ + static nowUtc(): DateTime; + /** + * Current date+time in the given time zone (derived from DateTime.timeSource.now()). + * @param timeZone The desired time zone. + */ + static now(timeZone: timezone.TimeZone): DateTime; + /** + * Constructor. Creates current time in local timezone. + */ + constructor(); + /** + * Constructor + * Non-existing local times are normalized by rounding up to the next DST offset. + * + * @param isoString String in ISO 8601 format. Instead of ISO time zone, + * it may include a space and then and IANA time zone. + * e.g. "2007-04-05T12:30:40.500" (no time zone, naive date) + * e.g. "2007-04-05T12:30:40.500+01:00" (UTC offset without daylight saving time) + * or "2007-04-05T12:30:40.500Z" (UTC) + * or "2007-04-05T12:30:40.500 Europe/Amsterdam" (IANA time zone, with daylight saving time if applicable) + * @param timeZone if given, the date in the string is assumed to be in this time zone. + * Note that it is NOT CONVERTED to the time zone. Useful + * for strings without a time zone + */ + constructor(isoString: string, timeZone?: timezone.TimeZone); + /** + * Constructor. You provide a date, then you say whether to take the + * date.getYear()/getXxx methods or the date.getUTCYear()/date.getUTCXxx methods, + * and then you state which time zone that date is in. + * Non-existing local times are normalized by rounding up to the next DST offset. + * Note that the Date class has bugs and inconsistencies when constructing them with times around + * DST changes. + * + * @param date A date object. + * @param getters Specifies which set of Date getters contains the date in the given time zone: the + * Date.getXxx() methods or the Date.getUTCXxx() methods. + * @param timeZone The time zone that the given date is assumed to be in (may be null for unaware dates) + */ + constructor(date: Date, getFuncs: javascript.DateFunctions, timeZone?: timezone.TimeZone); + /** + * Constructor. Note that unlike JavaScript dates we require fields to be in normal ranges. + * Use the add(duration) or sub(duration) for arithmetic. + * @param year The full year (e.g. 2014) + * @param month The month [1-12] (note this deviates from JavaScript Date) + * @param day The day of the month [1-31] + * @param hour The hour of the day [0-24) + * @param minute The minute of the hour [0-59] + * @param second The second of the minute [0-59] + * @param millisecond The millisecond of the second [0-999] + * @param timeZone The time zone, or null (for unaware dates) + */ + constructor(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number, timeZone?: timezone.TimeZone); + /** + * Constructor + * @param unixTimestamp milliseconds since 1970-01-01T00:00:00.000 + * @param timeZone the time zone that the timestamp is assumed to be in (usually UTC). + */ + constructor(unixTimestamp: number, timeZone?: timezone.TimeZone); + /** + * @return a copy of this object + */ + clone(): DateTime; + /** + * @return The time zone that the date is in. May be null for unaware dates. + */ + zone(): timezone.TimeZone; + /** + * @return the offset w.r.t. UTC in minutes. Returns 0 for unaware dates and for UTC dates. + */ + offset(): number; + /** + * @return The full year e.g. 2014 + */ + year(): number; + /** + * @return The month 1-12 (note this deviates from JavaScript Date) + */ + month(): number; + /** + * @return The day of the month 1-31 + */ + day(): number; + /** + * @return The hour 0-23 + */ + hour(): number; + /** + * @return the minutes 0-59 + */ + minute(): number; + /** + * @return the seconds 0-59 + */ + second(): number; + /** + * @return the milliseconds 0-999 + */ + millisecond(): number; + /** + * @return the day-of-week (the enum values correspond to JavaScript + * week day numbers) + */ + weekDay(): basics.WeekDay; + /** + * @return Milliseconds since 1970-01-01T00:00:00.000Z + */ + unixUtcMillis(): number; + /** + * @return The full year e.g. 2014 + */ + utcYear(): number; + /** + * @return The UTC month 1-12 (note this deviates from JavaScript Date) + */ + utcMonth(): number; + /** + * @return The UTC day of the month 1-31 + */ + utcDay(): number; + /** + * @return The UTC hour 0-23 + */ + utcHour(): number; + /** + * @return The UTC minutes 0-59 + */ + utcMinute(): number; + /** + * @return The UTC seconds 0-59 + */ + utcSecond(): number; + /** + * @return The UTC milliseconds 0-999 + */ + utcMillisecond(): number; + /** + * @return the UTC day-of-week (the enum values correspond to JavaScript + * week day numbers) + */ + utcWeekDay(): basics.WeekDay; + /** + * Convert this date to the given time zone (in-place). + * Throws if this date does not have a time zone. + * @return this (for chaining) + */ + convert(zone?: timezone.TimeZone): DateTime; + /** + * Returns this date converted to the given time zone. + * Unaware dates can only be converted to unaware dates (clone) + * Converting an unaware date to an aware date throws an exception. Use the constructor + * if you really need to do that. + * + * @param zone The new time zone. This may be null to create unaware date. + * @return The converted date + */ + toZone(zone?: timezone.TimeZone): DateTime; + /** + * Convert to JavaScript date with the zone time in the getX() methods. + * Unless the timezone is local, the Date.getUTCX() methods will NOT be correct. + * This is because Date calculates getUTCX() from getX() applying local time zone. + */ + toDate(): Date; + /** + * Add a time duration relative to UTC. Note that this simply adds a number + * of milliseconds to UTC and converts back to zone(), + * There is not DST handling. + * @return this + duration + */ + add(duration: duration.Duration): DateTime; + /** + * Add an amount of time relative to UTC, as regularly as possible. + * + * Adding e.g. 1 hour will increment the utcHour() field, adding 1 month + * increments the utcMonth() field. + * Adding an amount of units leaves lower units intact. E.g. + * adding a month will leave the day() field untouched if possible. + * + * Note adding Months or Years will clamp the date to the end-of-month if + * the start date was at the end of a month, i.e. contrary to JavaScript + * Date#setUTCMonth() it will not overflow into the next month + * + * In case of DST changes, the utc time fields are still untouched but local + * time fields may shift. + */ + add(amount: number, unit: basics.TimeUnit): DateTime; + /** + * Add an amount of time to the zone time, as regularly as possible. + * + * Adding e.g. 1 hour will increment the hour() field of the zone + * date by one. In case of DST changes, the time fields may additionally + * increase by the DST offset, if a non-existing local time would + * be reached otherwise. + * + * Adding a unit of time will leave lower-unit fields intact, unless the result + * would be a non-existing time. Then an extra DST offset is added. + * + * Note adding Months or Years will clamp the date to the end-of-month if + * the start date was at the end of a month, i.e. contrary to JavaScript + * Date#setUTCMonth() it will not overflow into the next month + */ + addLocal(amount: number, unit: basics.TimeUnit): DateTime; + /** + * Same as add(-1*duration); + */ + sub(duration: duration.Duration): DateTime; + /** + * Same as add(-1*amount, unit); + */ + sub(amount: number, unit: basics.TimeUnit): DateTime; + /** + * Same as addLocal(-1*amount, unit); + */ + subLocal(amount: number, unit: basics.TimeUnit): DateTime; + /** + * Time difference between two DateTimes + * @return this - other + */ + diff(other: DateTime): duration.Duration; + /** + * @return True iff (this < other) + */ + lessThan(other: DateTime): boolean; + /** + * @return True iff (this <= other) + */ + lessEqual(other: DateTime): boolean; + /** + * @return True iff this and other represent the same time in UTC + */ + equals(other: DateTime): boolean; + /** + * @return True iff this and other represent the same time and + * have the same zone + */ + identical(other: DateTime): boolean; + /** + * @return True iff this > other + */ + greaterThan(other: DateTime): boolean; + /** + * @return True iff this >= other + */ + greaterEqual(other: DateTime): boolean; + /** + * Proper ISO 8601 format string with any IANA zone converted to ISO offset + * E.g. "2014-01-01T23:15:33+01:00" for Europe/Amsterdam + */ + toIsoString(): string; + /** + * Modified ISO 8601 format string with IANA name if applicable. + * E.g. "2014-01-01T23:15:33.000 Europe/Amsterdam" + */ + toString(): string; + /** + * Used by util.inspect() + */ + inspect(): string; + /** + * Modified ISO 8601 format string in UTC without time zone info + */ + toUtcString(): string; + } +} + +declare module '__timezonecomplete/duration' { /** * Time duration. Create one e.g. like this: var d = Duration.hours(1). * Note that time durations do not take leap seconds etc. into account: @@ -174,154 +674,18 @@ declare module 'timezonecomplete' { * added as necessary */ toString(): string; + /** + * Used by util.inspect() + */ + inspect(): string; } - /** - * The type of time zone - */ - export enum TimeZoneKind { - /** - * Local time offset as determined by JavaScript Date class. - */ - Local = 0, - /** - * Fixed offset from UTC, without DST. - */ - Offset = 1, - /** - * IANA timezone managed through Olsen TZ database. Includes - * DST if applicable. - */ - Proper = 2, - } - /** - * Time zone. The object is immutable because it is cached: - * requesting a time zone twice yields the very same object. - * Note that we use time zone offsets inverted w.r.t. JavaScript Date.getTimezoneOffset(), - * i.e. offset 90 means +01:30. - * - * Time zones come in three flavors: the local time zone, as calculated by JavaScript Date, - * a fixed offset ("+01:30") without DST, or a IANA timezone ("Europe/Amsterdam") with DST - * applied depending on the time zone rules. - */ - export class TimeZone { - /** - * The local time zone for a given date. Note that - * the time zone varies with the date: amsterdam time for - * 2014-01-01 is +01:00 and amsterdam time for 2014-07-01 is +02:00 - */ - static local(): TimeZone; - /** - * The UTC time zone. - */ - static utc(): TimeZone; - /** - * Returns a time zone object from the cache. If it does not exist, it is created. - * @return The time zone with the given offset w.r.t. UTC in minutes, e.g. 90 for +01:30 - */ - static zone(offset: number): TimeZone; - /** - * Returns a time zone object from the cache. If it does not exist, it is created. - * @param s: Empty string for local time, a TZ database time zone name (e.g. Europe/Amsterdam) - * or an offset string (either +01:30, +0130, +01, Z). For a full list of names, see: - * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones - */ - static zone(s: string): TimeZone; - /** - * The time zone identifier. Can be an offset "-01:30" or an - * IANA time zone name "Europe/Amsterdam", or "localtime" for - * the local time zone. - */ - name(): string; - /** - * The kind of time zone (Local/Offset/Proper) - */ - kind(): TimeZoneKind; - /** - * Equality operator. Maps zero offsets and different names for UTC onto - * each other. Other time zones are not mapped onto each other. - */ - equals(other: TimeZone): boolean; - /** - * Is this zone equivalent to UTC? - */ - isUtc(): boolean; - /** - * Calculate timezone offset from a UTC time. - * @param year local full year - * @param month local month 1-12 (note this deviates from JavaScript date) - * @param day local day of month 1-31 - * @param hour local hour 0-23 - * @param minute local minute 0-59 - * @param second local second 0-59 - * @param millisecond local millisecond 0-999 - * @return the offset of this time zone with respect to UTC at the given time. - */ - offsetForUtc(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; - /** - * Calculate timezone offset from a zone-local time (NOT a UTC time). - * @param year local full year - * @param month local month 1-12 (note this deviates from JavaScript date) - * @param day local day of month 1-31 - * @param hour local hour 0-23 - * @param minute local minute 0-59 - * @param second local second 0-59 - * @param millisecond local millisecond 0-999 - * @return the offset of this time zone with respect to UTC at the given time. - */ - offsetForZone(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; - /** - * Convenience function, takes values from a Javascript Date - * Calls offsetForUtc() with the contents of the date - * @param date: the date - * @param funcs: the set of functions to use: get() or getUTC() - */ - offsetForUtcDate(date: Date, funcs: DateFunctions): number; - /** - * Convenience function, takes values from a Javascript Date - * Calls offsetForUtc() with the contents of the date - * @param date: the date - * @param funcs: the set of functions to use: get() or getUTC() - */ - offsetForZoneDate(date: Date, funcs: DateFunctions): number; - /** - * The time zone identifier (normalized). - * Either "localtime", IANA name, or "+hh:mm" offset. - */ - toString(): string; - /** - * Convert an offset number into an offset string - * @param offset The offset in minutes from UTC e.g. 90 minutes - * @return the offset in ISO notation "+01:30" for +90 minutes - */ - static offsetToString(offset: number): string; - /** - * String to offset conversion. - * @param s Formats: "-01:00", "-0100", "-01", "Z" - * @return offset w.r.t. UTC in minutes - */ - static stringToOffset(s: string): number; - } - /** - * For testing purposes, we often need to manipulate what the current - * time is. This is an interface for a custom time source object - * so in tests you can use a custom time source. - */ - export interface TimeSource { - /** - * Return the current date+time as a javascript Date object - */ - now(): Date; - } - /** - * Default time source, returns actual time - */ - export class RealTimeSource implements TimeSource { - now(): Date; - } +} + +declare module '__timezonecomplete/javascript' { /** * Indicates how a Date object should be interpreted. * Either we can take getYear(), getMonth() etc for our field - * values, or we can take getUTCYear() etc to do that. + * values, or we can take getUTCYear(), getUtcMonth() etc to do that. */ export enum DateFunctions { /** @@ -333,275 +697,11 @@ declare module 'timezonecomplete' { */ GetUTC = 1, } - /** - * Day-of-week. Note the enum values correspond to JavaScript day-of-week: - * Sunday = 0, Monday = 1 etc - */ - export enum WeekDay { - Sunday = 0, - Monday = 1, - Tuesday = 2, - Wednesday = 3, - Thursday = 4, - Friday = 5, - Saturday = 6, - } - /** - * Our very own DateTime class which is time zone-aware - * and which can be mocked for testing purposes - */ - export class DateTime { - /** - * Actual time source in use. Setting this property allows to - * fake time in tests. DateTime.nowLocal() and DateTime.nowUtc() - * use this property for obtaining the current time. - */ - static timeSource: TimeSource; - /** - * Current date+time in local time (derived from DateTime.timeSource.now()). - */ - static nowLocal(): DateTime; - /** - * Current date+time in UTC time (derived from DateTime.timeSource.now()). - */ - static nowUtc(): DateTime; - /** - * Current date+time in the given time zone (derived from DateTime.timeSource.now()). - * @param timeZone The desired time zone. - */ - static now(timeZone: TimeZone): DateTime; - /** - * Constructor. Creates current time in local timezone. - */ - constructor(); - /** - * Constructor - * @param isoString String in ISO 8601 format. Instead of ISO time zone, - * it may include a space and then and IANA time zone. - * e.g. "2007-04-05T12:30:40.500" (no time zone, naive date) - * e.g. "2007-04-05T12:30:40.500+01:00" (UTC offset without daylight saving time) - * or "2007-04-05T12:30:40.500Z" (UTC) - * or "2007-04-05T12:30:40.500 Europe/Amsterdam" (IANA time zone, with daylight saving time if applicable) - * @param timeZone if given, the date in the string is assumed to be in this time zone. - * Note that it is NOT CONVERTED to the time zone. Useful - * for strings without a time zone - */ - constructor(isoString: string, timeZone?: TimeZone); - /** - * Constructor. You provide a date, then you say whether to take the - * date.getYear()/getXxx methods or the date.getUTCYear()/date.getUTCXxx methods, - * and then you state which time zone that date is in. - * - * @param date A date object. - * @param getters Specifies which set of Date getters contains the date in the given time zone: the - * Date.getXxx() methods or the Date.getUTCXxx() methods. - * @param timeZone The time zone that the given date is assumed to be in (may be null for unaware dates) - */ - constructor(date: Date, getFuncs: DateFunctions, timeZone?: TimeZone); - /** - * Constructor. Note that unlike JavaScript dates we require fields to be in normal ranges. - * Use the add(duration) or sub(duration) for arithmetic. - * @param year The full year (e.g. 2014) - * @param month The month [1-12] (note this deviates from JavaScript Date) - * @param day The day of the month [1-31] - * @param hour The hour of the day [0-24) - * @param minute The minute of the hour [0-59] - * @param second The second of the minute [0-59] - * @param millisecond The millisecond of the second [0-999] - * @param timeZone The time zone, or null (for unaware dates) - */ - constructor(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number, timeZone?: TimeZone); - /** - * Constructor - * @param unixTimestamp milliseconds since 1970-01-01T00:00:00.000 - * @param timeZone the time zone that the timestamp is assumed to be in (usually UTC). - */ - constructor(unixTimestamp: number, timeZone?: TimeZone); - /** - * @return a copy of this object - */ - clone(): DateTime; - /** - * @return The time zone that the date is in. May be null for unaware dates. - */ - zone(): TimeZone; - /** - * @return the offset w.r.t. UTC in minutes. Returns 0 for unaware dates and for UTC dates. - */ - offset(): number; - /** - * @return The full year e.g. 2014 - */ - year(): number; - /** - * @return The month 1-12 (note this deviates from JavaScript Date) - */ - month(): number; - /** - * @return The day of the month 1-31 - */ - day(): number; - /** - * @return The hour 0-23 - */ - hour(): number; - /** - * @return the minutes 0-59 - */ - minute(): number; - /** - * @return the seconds 0-59 - */ - second(): number; - /** - * @return the milliseconds 0-999 - */ - millisecond(): number; - /** - * @return the day-of-week (the enum values correspond to JavaScript - * week day numbers) - */ - weekDay(): WeekDay; - /** - * @return Milliseconds since 1970-01-01T00:00:00.000Z - */ - unixUtcMillis(): number; - /** - * @return The full year e.g. 2014 - */ - utcYear(): number; - /** - * @return The UTC month 1-12 (note this deviates from JavaScript Date) - */ - utcMonth(): number; - /** - * @return The UTC day of the month 1-31 - */ - utcDay(): number; - /** - * @return The UTC hour 0-23 - */ - utcHour(): number; - /** - * @return The UTC minutes 0-59 - */ - utcMinute(): number; - /** - * @return The UTC seconds 0-59 - */ - utcSecond(): number; - /** - * @return The UTC milliseconds 0-999 - */ - utcMillisecond(): number; - /** - * @return the UTC day-of-week (the enum values correspond to JavaScript - * week day numbers) - */ - utcWeekDay(): WeekDay; - /** - * Convert this date to the given time zone (in-place). - * Throws if this date does not have a time zone. - * @return this (for chaining) - */ - convert(zone?: TimeZone): DateTime; - /** - * Returns this date converted to the given time zone. - * Unaware dates can only be converted to unaware dates (clone) - * For unaware dates, an exception is thrown - * @param zone The new time zone. This may be null to create unaware date. - * @return The converted date - */ - toZone(zone?: TimeZone): DateTime; - /** - * Convert to JavaScript date with the zone time in the getX() methods. - * Unless the timezone is local, the Date.getUTCX() methods will NOT be correct. - */ - toDate(): Date; - /** - * Add a time duration. Note that this simply adds a number - * of milliseconds to UTC and converts back to zone(), - * so in the presence of e.g. leap seconds there may be a - * shift in the seconds field if you add an hour. - * There is not DST handling and no leap second handling. - * @return this + duration - */ - add(duration: Duration): DateTime; - /** - * Add an amount of time to UTC, taking leap seconds etc into account. - * Adding e.g. 1 hour will increment the utcHour() field - * date by one. In case of DST changes, the local hour() field - * may not increase or increase by 2 hours. So if you add a month, the - * local time may vary by an hour. There will not be a shift - * in seconds due to leap seconds. - */ - add(amount: number, unit: TimeUnit): DateTime; - /** - * Add an amount of time to the zone time, as regularly as possible. - * Adding e.g. 1 hour will increment the hour() field of the zone - * date by one. In case of DST changes, the utcHour() field may - * increase by 1 or increase by 2. Adding a day will leave the time portion - * intact. However, adding an hour around a forward DST change adds two hours, - * since there is a zone time (2AM in Holland) that does not exist. - */ - addLocal(amount: number, unit: TimeUnit): DateTime; - /** - * Same as add(-1*duration); - */ - sub(duration: Duration): DateTime; - /** - * Same as add(-1*amount, unit); - */ - sub(amount: number, unit: TimeUnit): DateTime; - /** - * Same as addLocal(-1*amount, unit); - */ - subLocal(amount: number, unit: TimeUnit): DateTime; - /** - * Time difference between two DateTimes - * @return this - other - */ - diff(other: DateTime): Duration; - /** - * @return True iff (this < other) - */ - lessThan(other: DateTime): boolean; - /** - * @return True iff (this <= other) - */ - lessEqual(other: DateTime): boolean; - /** - * @return True iff this and other represent the same time in UTC - */ - equals(other: DateTime): boolean; - /** - * @return True iff this and other represent the same time and - * have the same zone - */ - identical(other: DateTime): boolean; - /** - * @return True iff this > other - */ - greaterThan(other: DateTime): boolean; - /** - * @return True iff this >= other - */ - greaterEqual(other: DateTime): boolean; - /** - * Proper ISO 8601 format string with any IANA zone converted to ISO offset - * E.g. "2014-01-01T23:15:33+01:00" for Europe/Amsterdam - */ - toIsoString(): string; - /** - * Modified ISO 8601 format string with IANA name if applicable. - * E.g. "2014-01-01T23:15:33.000 Europe/Amsterdam" - */ - toString(): string; - /** - * Modified ISO 8601 format string in UTC without time zone info - */ - toUtcString(): string; - } +} + +declare module '__timezonecomplete/period' { + import basics = require("__timezonecomplete/basics"); + import datetime = require("__timezonecomplete/datetime"); /** * Specifies how the period should repeat across the day * during DST changes. @@ -651,11 +751,11 @@ declare module 'timezonecomplete' { * @param dst Specifies how to handle Daylight Saving Time. Not relevant * if the time zone of the start datetime does not have DST. */ - constructor(start: DateTime, amount: number, unit: TimeUnit, dst: PeriodDst); + constructor(start: datetime.DateTime, amount: number, unit: basics.TimeUnit, dst: PeriodDst); /** * The start date */ - start(): DateTime; + start(): datetime.DateTime; /** * The amount of units */ @@ -663,7 +763,7 @@ declare module 'timezonecomplete' { /** * The unit */ - unit(): TimeUnit; + unit(): basics.TimeUnit; /** * The dst handling mode */ @@ -676,7 +776,7 @@ declare module 'timezonecomplete' { * @return the first date matching the period after fromDate, given * in the same zone as the fromDate. */ - findFirst(fromDate: DateTime): DateTime; + findFirst(fromDate: datetime.DateTime): datetime.DateTime; /** * Returns the next timestamp in the period. The given timestamp must * be at a period boundary, otherwise the answer is incorrect. @@ -686,17 +786,219 @@ declare module 'timezonecomplete' { * @param count Optional, must be >= 1 and whole. * @return (prev + count * period), in the same timezone as prev. */ - findNext(prev: DateTime, count?: number): DateTime; + findNext(prev: datetime.DateTime, count?: number): datetime.DateTime; /** - * Returns an ISO duration string - * P[n]Y[n]M[n]DT[n]H[n]M[n][.n]S or P[n]W + * Returns an ISO duration string e.g. + * 2014-01-01T12:00:00.000+01:00/P1H + * 2014-01-01T12:00:00.000+01:00/PT1M (one minute) + * 2014-01-01T12:00:00.000+01:00/P1M (one month) */ toIsoString(): string; /** * A string representation e.g. - * "10 years, starting at 2014-03-01T12:00:00 Europe/Amsterdam keeping regular intervals". + * "10 years, starting at 2014-03-01T12:00:00 Europe/Amsterdam, keeping regular intervals". */ toString(): string; + /** + * Used by util.inspect() + */ + inspect(): string; + } +} + +declare module '__timezonecomplete/timesource' { + /** + * For testing purposes, we often need to manipulate what the current + * time is. This is an interface for a custom time source object + * so in tests you can use a custom time source. + */ + export interface TimeSource { + /** + * Return the current date+time as a javascript Date object + */ + now(): Date; + } + /** + * Default time source, returns actual time + */ + export class RealTimeSource implements TimeSource { + now(): Date; + } +} + +declare module '__timezonecomplete/timezone' { + import javascript = require("__timezonecomplete/javascript"); + /** + * The type of time zone + */ + export enum TimeZoneKind { + /** + * Local time offset as determined by JavaScript Date class. + */ + Local = 0, + /** + * Fixed offset from UTC, without DST. + */ + Offset = 1, + /** + * IANA timezone managed through Olsen TZ database. Includes + * DST if applicable. + */ + Proper = 2, + } + /** + * Option for TimeZone#normalizeLocal() + */ + export enum NormalizeOption { + /** + * Normalize non-existing times by ADDING the DST offset + */ + Up = 0, + /** + * Normalize non-existing times by SUBTRACTING the DST offset + */ + Down = 1, + } + /** + * Time zone. The object is immutable because it is cached: + * requesting a time zone twice yields the very same object. + * Note that we use time zone offsets inverted w.r.t. JavaScript Date.getTimezoneOffset(), + * i.e. offset 90 means +01:30. + * + * Time zones come in three flavors: the local time zone, as calculated by JavaScript Date, + * a fixed offset ("+01:30") without DST, or a IANA timezone ("Europe/Amsterdam") with DST + * applied depending on the time zone rules. + */ + export class TimeZone { + /** + * The local time zone for a given date. Note that + * the time zone varies with the date: amsterdam time for + * 2014-01-01 is +01:00 and amsterdam time for 2014-07-01 is +02:00 + */ + static local(): TimeZone; + /** + * The UTC time zone. + */ + static utc(): TimeZone; + /** + * Returns a time zone object from the cache. If it does not exist, it is created. + * @return The time zone with the given offset w.r.t. UTC in minutes, e.g. 90 for +01:30 + */ + static zone(offset: number): TimeZone; + /** + * Returns a time zone object from the cache. If it does not exist, it is created. + * @param s: Empty string for local time, a TZ database time zone name (e.g. Europe/Amsterdam) + * or an offset string (either +01:30, +0130, +01, Z). For a full list of names, see: + * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones + */ + static zone(s: string): TimeZone; + /** + * Do not use this constructor, use the static + * TimeZone.zone() method instead. + * @param name NORMALIZED name, assumed to be correct + */ + constructor(name: string); + /** + * The time zone identifier. Can be an offset "-01:30" or an + * IANA time zone name "Europe/Amsterdam", or "localtime" for + * the local time zone. + */ + name(): string; + /** + * The kind of time zone (Local/Offset/Proper) + */ + kind(): TimeZoneKind; + /** + * Equality operator. Maps zero offsets and different names for UTC onto + * each other. Other time zones are not mapped onto each other. + */ + equals(other: TimeZone): boolean; + /** + * Is this zone equivalent to UTC? + */ + isUtc(): boolean; + /** + * Does this zone have Daylight Saving Time at all? + */ + hasDst(): boolean; + /** + * Calculate timezone offset from a UTC time. + * @param year local full year + * @param month local month 1-12 (note this deviates from JavaScript date) + * @param day local day of month 1-31 + * @param hour local hour 0-23 + * @param minute local minute 0-59 + * @param second local second 0-59 + * @param millisecond local millisecond 0-999 + * @return the offset of this time zone with respect to UTC at the given time, in minutes. + */ + offsetForUtc(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; + /** + * Calculate timezone offset from a zone-local time (NOT a UTC time). + * @param year local full year + * @param month local month 1-12 (note this deviates from JavaScript date) + * @param day local day of month 1-31 + * @param hour local hour 0-23 + * @param minute local minute 0-59 + * @param second local second 0-59 + * @param millisecond local millisecond 0-999 + * @return the offset of this time zone with respect to UTC at the given time, in minutes. + */ + offsetForZone(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; + /** + * Note: will be removed in version 2.0.0 + * + * Convenience function, takes values from a Javascript Date + * Calls offsetForUtc() with the contents of the date + * + * @param date: the date + * @param funcs: the set of functions to use: get() or getUTC() + */ + offsetForUtcDate(date: Date, funcs: javascript.DateFunctions): number; + /** + * Note: will be removed in version 2.0.0 + * + * Convenience function, takes values from a Javascript Date + * Calls offsetForUtc() with the contents of the date + * + * @param date: the date + * @param funcs: the set of functions to use: get() or getUTC() + */ + offsetForZoneDate(date: Date, funcs: javascript.DateFunctions): number; + /** + * Normalizes non-existing local times by adding a forward offset change. + * During a forward standard offset change or DST offset change, some amount of + * local time is skipped. Therefore, this amount of local time does not exist. + * This function adds the amount of forward change to any non-existing time. After all, + * this is probably what the user meant. + * + * @param localUnixMillis Unix timestamp in zone time + * @param opt (optional) Round up or down? Default: up + * + * @returns Unix timestamp in zone time, normalized. + */ + normalizeZoneTime(localUnixMillis: number, opt?: NormalizeOption): number; + /** + * The time zone identifier (normalized). + * Either "localtime", IANA name, or "+hh:mm" offset. + */ + toString(): string; + /** + * Used by util.inspect() + */ + inspect(): string; + /** + * Convert an offset number into an offset string + * @param offset The offset in minutes from UTC e.g. 90 minutes + * @return the offset in ISO notation "+01:30" for +90 minutes + */ + static offsetToString(offset: number): string; + /** + * String to offset conversion. + * @param s Formats: "-01:00", "-0100", "-01", "Z" + * @return offset w.r.t. UTC in minutes + */ + static stringToOffset(s: string): number; } } From 0ac4c6c592b3bcfa4dfa84c3b7d831384aac50cb Mon Sep 17 00:00:00 2001 From: Rogier Schouten Date: Fri, 15 Aug 2014 14:19:58 +0200 Subject: [PATCH 321/324] Adjusted tests for 1.4.6 --- timezonecomplete/timezonecomplete-tests.ts | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/timezonecomplete/timezonecomplete-tests.ts b/timezonecomplete/timezonecomplete-tests.ts index 142b3f25a..9f3833f71 100644 --- a/timezonecomplete/timezonecomplete-tests.ts +++ b/timezonecomplete/timezonecomplete-tests.ts @@ -2,9 +2,18 @@ import tc = require("timezonecomplete"); -var b: boolean = tc.isLeapYear(2014); -var n: number = tc.daysInMonth(2014, 10); -var s: string = tc.isoString(2014, 6, 30, 22, 10, 11, 230); +var b: boolean; +var n: number; +var s: string; +var w: tc.WeekDay; + +b = tc.isLeapYear(2014); +n = tc.daysInMonth(2014, 10); +n = tc.daysInYear(2014); +n = tc.dayOfYear(2014, 1, 2); +w = tc.lastWeekDayOfMonth(2014, 1, tc.WeekDay.Sunday); +n = tc.weekDayOnOrAfter(2014, 1, 14, tc.WeekDay.Monday); +n = tc.weekDayOnOrBefore(2014, 1, 14, tc.WeekDay.Monday); // DURATION From ee6f317c09bebe1e398b155793338967f6efd34c Mon Sep 17 00:00:00 2001 From: Pedro Casaubon Date: Fri, 15 Aug 2014 15:51:08 +0200 Subject: [PATCH 322/324] Updated code to align to best practices Removed optional members in callbacks Removed explicit type inference for DT tests --- dropboxjs/dropboxjs-tests.ts | 4 ++-- dropboxjs/dropboxjs.d.ts | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/dropboxjs/dropboxjs-tests.ts b/dropboxjs/dropboxjs-tests.ts index efc6a3693..ad8e608a4 100644 --- a/dropboxjs/dropboxjs-tests.ts +++ b/dropboxjs/dropboxjs-tests.ts @@ -37,7 +37,7 @@ browserClient.authenticate((error:any, client:Dropbox.Client) => { alert(data); // data has the file's contents }); - client.readdir("/", (err: Dropbox.ApiError, filenames: string[], stat: Dropbox.File.Stat, folderEntries?: Dropbox.File.Stat[]) => { + client.readdir("/", (err: Dropbox.ApiError, filenames: string[], stat: Dropbox.File.Stat, folderEntries: Dropbox.File.Stat[]) => { if (error) { alert(error); // Something went wrong. } @@ -46,7 +46,7 @@ browserClient.authenticate((error:any, client:Dropbox.Client) => { }); }); -var serverClient:Dropbox.Client = new Dropbox.Client({ +var serverClient = new Dropbox.Client({ key: "your-key-here", secret: "your-secret-here" }); diff --git a/dropboxjs/dropboxjs.d.ts b/dropboxjs/dropboxjs.d.ts index c40a69f4b..ab3dbe2ee 100644 --- a/dropboxjs/dropboxjs.d.ts +++ b/dropboxjs/dropboxjs.d.ts @@ -455,12 +455,12 @@ declare module Dropbox { resumableUploadStep(data: any, cursor: Http.UploadCursor, callback: ResumableUploadStepCallback): XMLHttpRequest; resumableUploadFinish(path: string, cursor: Http.UploadCursor, callback: ClientFileWriteCallback): XMLHttpRequest; resumableUploadFinish(path: string, cursor: Http.UploadCursor, options: ClientFileWriteOptions, callback: ClientFileWriteCallback): XMLHttpRequest; - stat(path: string, callback: (err: ApiError, stat: File.Stat, folderEntries?: File.Stat[]) => void): XMLHttpRequest; - stat(path: string, options: File.StatOptions, callback: (err: ApiError, stat: File.Stat, folderEntries?: File.Stat[]) => void): XMLHttpRequest; - readdir(path: string, callback: (err: ApiError, filenames: string[], stat: File.Stat, folderEntries?: File.Stat[]) => void): XMLHttpRequest; - readdir(path: string, options: ReadDirOptions, callback: (err: ApiError, filenames: string[], stat: File.Stat, folderEntries?: File.Stat[]) => void): XMLHttpRequest; - metadata(path: string, callback: (err: ApiError, stat: File.Stat, folderEntries?: File.Stat[]) => void): void; - metadata(path: string, options: File.StatOptions, callback: (err: ApiError, stat: File.Stat, folderEntries?: File.Stat[]) => void): void; + stat(path: string, callback: (err: ApiError, stat: File.Stat, folderEntries: File.Stat[]) => void): XMLHttpRequest; + stat(path: string, options: File.StatOptions, callback: (err: ApiError, stat: File.Stat, folderEntries: File.Stat[]) => void): XMLHttpRequest; + readdir(path: string, callback: (err: ApiError, filenames: string[], stat: File.Stat, folderEntries: File.Stat[]) => void): XMLHttpRequest; + readdir(path: string, options: ReadDirOptions, callback: (err: ApiError, filenames: string[], stat: File.Stat, folderEntries: File.Stat[]) => void): XMLHttpRequest; + metadata(path: string, callback: (err: ApiError, stat: File.Stat, folderEntries: File.Stat[]) => void): void; + metadata(path: string, options: File.StatOptions, callback: (err: ApiError, stat: File.Stat, folderEntries: File.Stat[]) => void): void; makeUrl(path: string, callback: (err: ApiError, shareUrl: File.ShareUrl) => void): XMLHttpRequest; makeUrl(path: string, options: MakeURLOptions, callback: (err: ApiError, shareUrl: File.ShareUrl) => void): XMLHttpRequest; history(path: string, callback: (err: ApiError, fileVersions: File.Stat[]) => void): XMLHttpRequest; From a2f96a4233934ff0bc1b42a873f1ed6a90ec0b12 Mon Sep 17 00:00:00 2001 From: Rogier Schouten Date: Fri, 15 Aug 2014 15:54:09 +0200 Subject: [PATCH 323/324] Fixed unittest failure on old tests. --- timezonecomplete/timezonecomplete-1.2.0-tests.ts | 4 ++-- timezonecomplete/timezonecomplete-1.2.0.d.ts | 2 +- timezonecomplete/timezonecomplete-1.3.0-tests.ts | 4 ++-- timezonecomplete/timezonecomplete-1.3.0.d.ts | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/timezonecomplete/timezonecomplete-1.2.0-tests.ts b/timezonecomplete/timezonecomplete-1.2.0-tests.ts index 03f94e44b..3ed4db796 100644 --- a/timezonecomplete/timezonecomplete-1.2.0-tests.ts +++ b/timezonecomplete/timezonecomplete-1.2.0-tests.ts @@ -1,6 +1,6 @@ -/// +/// -import tc = require("timezonecomplete"); +import tc = require("timezonecomplete-1.2.0"); var b: boolean = tc.isLeapYear(2014); var n: number = tc.daysInMonth(2014, 10); diff --git a/timezonecomplete/timezonecomplete-1.2.0.d.ts b/timezonecomplete/timezonecomplete-1.2.0.d.ts index 2f1b969bc..1a39be00e 100644 --- a/timezonecomplete/timezonecomplete-1.2.0.d.ts +++ b/timezonecomplete/timezonecomplete-1.2.0.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped // Generated by dts-bundle 0.1.1 -declare module 'timezonecomplete' { +declare module 'timezonecomplete-1.2.0' { /** * @return True iff the given year is a leap year. */ diff --git a/timezonecomplete/timezonecomplete-1.3.0-tests.ts b/timezonecomplete/timezonecomplete-1.3.0-tests.ts index 142b3f25a..08145d275 100644 --- a/timezonecomplete/timezonecomplete-1.3.0-tests.ts +++ b/timezonecomplete/timezonecomplete-1.3.0-tests.ts @@ -1,6 +1,6 @@ -/// +/// -import tc = require("timezonecomplete"); +import tc = require("timezonecomplete-1.3.0"); var b: boolean = tc.isLeapYear(2014); var n: number = tc.daysInMonth(2014, 10); diff --git a/timezonecomplete/timezonecomplete-1.3.0.d.ts b/timezonecomplete/timezonecomplete-1.3.0.d.ts index 6fbea6f6f..d4960def4 100644 --- a/timezonecomplete/timezonecomplete-1.3.0.d.ts +++ b/timezonecomplete/timezonecomplete-1.3.0.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped // Generated by dts-bundle v0.2.0 -declare module 'timezonecomplete' { +declare module 'timezonecomplete-1.3.0' { /** * @return True iff the given year is a leap year. */ From d7d5f7fc987c01049a19ef2af26daa8eb05f1e35 Mon Sep 17 00:00:00 2001 From: Basarat Ali Syed Date: Sat, 16 Aug 2014 12:32:41 +1000 Subject: [PATCH 324/324] Dropbox: Document reason for dummy class https://github.com/Microsoft/TypeScript/issues/371 --- dropboxjs/dropboxjs.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dropboxjs/dropboxjs.d.ts b/dropboxjs/dropboxjs.d.ts index ab3dbe2ee..f9a2c9a40 100644 --- a/dropboxjs/dropboxjs.d.ts +++ b/dropboxjs/dropboxjs.d.ts @@ -290,6 +290,7 @@ declare module Dropbox { } module AuthDriver { + /** Do not use class! TypeScript definition implementation detail : https://github.com/Microsoft/TypeScript/issues/371 */ class IAuthDriver { doAuthorize(authUrl: string, stateParam: string, client: Client, callback?: QueryParamsCallback): void; } @@ -504,4 +505,4 @@ declare module Dropbox { appHash(): string; } -} \ No newline at end of file +}