From 4f3550010afe786b638ae63d433ddfa9528c955b Mon Sep 17 00:00:00 2001 From: Michal Miszczyszyn Date: Tue, 17 Nov 2015 20:06:22 +0100 Subject: [PATCH 001/105] jquery: Fix noConflict return type. Fix #5840 --- 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 29b7697b2..9f75f9a9d 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -795,7 +795,7 @@ interface JQueryStatic { * * @param removeAll A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself). */ - noConflict(removeAll?: boolean): Object; + noConflict(removeAll?: boolean): JQueryStatic; /** * Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. From 94cc10600a5dc2990cce89b4c1d7b38f1f0277a1 Mon Sep 17 00:00:00 2001 From: r-ising Date: Mon, 7 Dec 2015 14:31:58 +0100 Subject: [PATCH 002/105] update node.d.ts (publicEncrypt & privateDecrypt) added rsa function to encrypt and decrypt --- node/node.d.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/node/node.d.ts b/node/node.d.ts index 017ca8e6b..483c51d51 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1670,6 +1670,17 @@ declare module "crypto" { export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; export function pseudoRandomBytes(size: number): Buffer; export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; + export interface RsaPublicKey { + key: string; + padding: any; + } + export interface RsaPrivateKey { + key: string; + passphrase: string, + padding: any; + } + export function publicEncrypt(public_key: string|RsaPublicKey, buffer: Buffer): Buffer + export function privateDecrypt(private_key: string|RsaPrivateKey, buffer: Buffer): Buffer } declare module "stream" { From 4406eae2c1b0795b18007488b77641286ed06e85 Mon Sep 17 00:00:00 2001 From: r-ising Date: Thu, 10 Dec 2015 15:02:09 +0100 Subject: [PATCH 003/105] update node.d.ts in publicEncrypt- and privateDecrypt-function is passpharse and padding optional --- node/node.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index 483c51d51..0bfd5b4d9 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1672,12 +1672,12 @@ declare module "crypto" { export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; export interface RsaPublicKey { key: string; - padding: any; + padding?: any; } export interface RsaPrivateKey { key: string; - passphrase: string, - padding: any; + passphrase?: string, + padding?: any; } export function publicEncrypt(public_key: string|RsaPublicKey, buffer: Buffer): Buffer export function privateDecrypt(private_key: string|RsaPrivateKey, buffer: Buffer): Buffer From 4c47190e53bf61091ff9cbb1c093e2477fbe4333 Mon Sep 17 00:00:00 2001 From: David Asmuth Date: Sat, 30 Jan 2016 21:10:08 +0100 Subject: [PATCH 004/105] corrected method spelling Body.setInertia; corrected Method signature of Body.setParts --- matter-js/matter-js.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/matter-js/matter-js.d.ts b/matter-js/matter-js.d.ts index ed5412b52..c49633ba9 100644 --- a/matter-js/matter-js.d.ts +++ b/matter-js/matter-js.d.ts @@ -612,7 +612,7 @@ declare module Matter { * @param {body} body * @param {number} inertia */ - static setInterna(body: Body, interna: number): void; + static setInertia(body: Body, interna: number): void; /** * Sets the body's vertices and updates body properties accordingly, including inertia, area and mass (with respect to `body.density`). * Vertices will be automatically transformed to be orientated around their centre of mass as the origin. @@ -636,7 +636,7 @@ declare module Matter { * @param [body] parts * @param {bool} [autoHull=true] */ - static setParts(body: Body, parts: Body, autoHull: boolean): void; + static setParts(body: Body, parts: Body[], autoHull?: boolean): void; /** * Sets the position of the body instantly. Velocity, angle, force etc. are unchanged. * @method setPosition From 6faa4c6e0830373dadd08a560b0aed7485e547de Mon Sep 17 00:00:00 2001 From: David Asmuth Date: Sat, 30 Jan 2016 23:19:15 +0100 Subject: [PATCH 005/105] fixed event inputs --- matter-js/matter-js.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/matter-js/matter-js.d.ts b/matter-js/matter-js.d.ts index c49633ba9..2f42dd667 100644 --- a/matter-js/matter-js.d.ts +++ b/matter-js/matter-js.d.ts @@ -2959,7 +2959,7 @@ declare module Matter { * @param {} event.source The source object of the event * @param {} event.name The name of the event */ - static on(obj: Engine, name: "sleepStart", callback: (e: IEvent) => void): void; + static on(obj: Body, name: "sleepStart", callback: (e: IEvent) => void): void; /** * Fired when a body ends sleeping (where `this` is the body). * @@ -2969,7 +2969,7 @@ declare module Matter { * @param {} event.source The source object of the event * @param {} event.name The name of the event */ - static on(obj: Engine, name: "sleepEnd", callback: (e: IEvent) => void): void; + static on(obj: Body, name: "sleepEnd", callback: (e: IEvent) => void): void; /** * Fired when a call to `Composite.add` is made, before objects have been added. @@ -3158,7 +3158,7 @@ declare module Matter { * @param name * @param callback */ - static on(obj: Engine, name: "mousedown", callback: (e: any) => void): void; + static on(obj: MouseConstraint, name: "mousedown", callback: (e: any) => void): void; /** * Fired when the mouse has moved (or a touch moves) during the last step @@ -3166,7 +3166,7 @@ declare module Matter { * @param name * @param callback */ - static on(obj: Engine, name: "mousemove", callback: (e: any) => void): void; + static on(obj: MouseConstraint, name: "mousemove", callback: (e: any) => void): void; /** * Fired when the mouse is up (or a touch has ended) during the last step @@ -3174,10 +3174,10 @@ declare module Matter { * @param name * @param callback */ - static on(obj: Engine, name: "mouseup", callback: (e: any) => void): void; + static on(obj: MouseConstraint, name: "mouseup", callback: (e: any) => void): void; - static on(obj: Engine, name: string, callback: (e: any) => void): void; + static on(obj: any, name: string, callback: (e: any) => void): void; /** * Removes the given event callback. If no callback, clears all callbacks in eventNames. If no eventNames, clears all events. From 7b8b36274298d279dceae3828433f3abe46e34ab Mon Sep 17 00:00:00 2001 From: Boris Prpic Date: Sun, 7 Feb 2016 21:11:51 +0100 Subject: [PATCH 006/105] Updates IComponentOptions for angular 1.5 components As per https://docs.angularjs.org/guide/component components does not support restrict or isolate but they do require --- angularjs/angular.d.ts | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 67b3eb488..26304d7ce 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1710,20 +1710,12 @@ declare module angular { * Define DOM attribute binding to component properties. Component properties are always bound to the component * controller and not to the scope. */ - bindings?: any; + bindings?: Object; /** * Whether transclusion is enabled. Enabled by default. */ transclude?: boolean; - /** - * Whether the new scope is isolated. Isolated by default. - */ - isolate?: boolean; - /** - * String of subset of EACM which restricts the component to specific directive declaration style. If omitted, - * this defaults to 'E'. - */ - restrict?: string; + require? : string | Array; $canActivate?: () => boolean; $routeConfig?: RouteDefinition[]; } @@ -1774,12 +1766,12 @@ declare module angular { name?: string; priority?: number; replace?: boolean; - require?: any; + require? : string | Array; restrict?: string; scope?: any; - template?: any; + template?: string | Function; templateNamespace?: string; - templateUrl?: any; + templateUrl?: string | Function; terminal?: boolean; transclude?: any; } From 119c65b3117150bda202a49549c2cfea25ab4e57 Mon Sep 17 00:00:00 2001 From: Boris Prpic Date: Mon, 8 Feb 2016 00:00:17 +0100 Subject: [PATCH 007/105] Fixed require In component require works different from directive. Now its Object --- 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 26304d7ce..a8fae4e74 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1715,7 +1715,7 @@ declare module angular { * Whether transclusion is enabled. Enabled by default. */ transclude?: boolean; - require? : string | Array; + require? : {}; $canActivate?: () => boolean; $routeConfig?: RouteDefinition[]; } From f8e2d6025e973a7c4a1b2e12b36dba471a599afe Mon Sep 17 00:00:00 2001 From: Boris Prpic Date: Mon, 8 Feb 2016 00:04:14 +0100 Subject: [PATCH 008/105] Fixes require again --- 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 a8fae4e74..a591410a2 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1715,7 +1715,7 @@ declare module angular { * Whether transclusion is enabled. Enabled by default. */ transclude?: boolean; - require? : {}; + require? : Object; $canActivate?: () => boolean; $routeConfig?: RouteDefinition[]; } From 9d92676adba28922cb151a036c7e75c2bde380ca Mon Sep 17 00:00:00 2001 From: Prannay Budhraja Date: Wed, 10 Feb 2016 17:45:05 -0800 Subject: [PATCH 009/105] Update dexie.d.ts to version 1.2 From dexie.js source repo commit 92372b017810704bd7f812e7b0b86df866e8d222 -- Allow dexie to be referenced in typescript projects. e.g. ``` import * as Dexie from 'dexie'; ``` Dexie will now be properly typed without having to reference Dexie.d.ts in DefinitelyTyped or through src/Dexie.d.ts (which isn't exposed in npm anyways) --- dexie/dexie.d.ts | 54 +++++++++++++++++++++++++++--------------------- 1 file changed, 30 insertions(+), 24 deletions(-) diff --git a/dexie/dexie.d.ts b/dexie/dexie.d.ts index 13b9b31e0..f4b68a1c4 100644 --- a/dexie/dexie.d.ts +++ b/dexie/dexie.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Dexie v1.1 +// Type definitions for Dexie v1.2 // Project: https://github.com/dfahlander/Dexie.js // Definitions by: David Fahlander // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -50,7 +50,7 @@ declare class Dexie { versionchange: Dexie.DexieVersionChangeEvent; }; - open(): Dexie.Promise; + open(): Dexie.Promise; table(tableName: string): Dexie.Table; @@ -78,6 +78,8 @@ declare class Dexie { delete(): Dexie.Promise; + exists(name : string) : Dexie.Promise; + isOpen(): boolean; hasFailed(): boolean; @@ -104,9 +106,9 @@ declare module Dexie { catch(onRejected: (error: any) => Promise): Promise; - catch(ExceptionType: Function, onRejected: (error : any) => Promise): Promise; + catch(ExceptionType: Function, onRejected: (error: any) => Promise): Promise; - catch(errorName: string, onRejected: (error : any) => Promise): Promise; + catch(errorName: string, onRejected: (error: any) => Promise): Promise; finally(onFinally: () => any): Promise; @@ -131,7 +133,7 @@ declare module Dexie { var PSD: any; var on: { - (eventName: string, subscriber: (...args : any[]) => any): void; + (eventName: string, subscriber: (...args: any[]) => any): void; error: DexieErrorEvent; } } @@ -162,28 +164,27 @@ declare module Dexie { } interface DexieEvent { - subscribe(fn: () => any) : void; - unsubscribe(fn: () => any) : void; - fire() : any; + subscribe(fn: () => any): void; + unsubscribe(fn: () => any): void; + fire(): any; } interface DexieErrorEvent { - subscribe(fn: (error: any) => any) : void; - unsubscribe(fn: (error: any) => any) : void; - fire(error: any) : any; + subscribe(fn: (error: any) => any): void; + unsubscribe(fn: (error: any) => any): void; + fire(error: any): any; } interface DexieVersionChangeEvent { - subscribe(fn: (event: IDBVersionChangeEvent) => any) : void; - unsubscribe(fn: (event: IDBVersionChangeEvent) => any) : void; - fire(event: IDBVersionChangeEvent) : any; + subscribe(fn: (event: IDBVersionChangeEvent) => any): void; + unsubscribe(fn: (event: IDBVersionChangeEvent) => any): void; + fire(event: IDBVersionChangeEvent): any; } - interface DexieOnReadyEvent - { - subscribe(fn: () => any, bSticky: boolean) : void; - unsubscribe(fn: () => any) : void; - fire() : any; + interface DexieOnReadyEvent { + subscribe(fn: () => any, bSticky: boolean): void; + unsubscribe(fn: () => any): void; + fire(): any; } interface Table { @@ -221,7 +222,7 @@ declare module Dexie { reverse(): Collection; mapToClass(constructor: Function): Function; add(item: T, key?: Key): Promise; - update(key: Key, changes: { [keyPath: string]: any }) : Promise; + update(key: Key, changes: { [keyPath: string]: any }): Promise; put(item: T, key?: Key): Promise; delete(key: Key): Promise; clear(): Promise; @@ -256,7 +257,14 @@ declare module Dexie { equals(key: Array): Collection; equalsIgnoreCase(key: string): Collection; startsWith(key: string): Collection; + startsWithAnyOf(prefixes: string[]): Collection; + startsWithAnyOf(...prefixes: string[]): Collection; startsWithIgnoreCase(key: string): Collection; + noneOf(keys: Array): Collection; + notEqual(key: number): Collection; + notEqual(key: string): Collection; + notEqual(key: Date): Collection; + notEqual(key: Array): Collection; } interface Collection { @@ -306,7 +314,7 @@ declare module Dexie { interface IndexSpec { name: string; - keyPath: any; + keyPath: any; // string | Array unique: boolean; multi: boolean; auto: boolean; @@ -315,6 +323,4 @@ declare module Dexie { } } -declare module 'dexie' { - export = Dexie; -} +export = Dexie; From 80c19345b84626c404ecc1bdc68c7ee6297b4f7f Mon Sep 17 00:00:00 2001 From: Alex Tkachman Date: Wed, 10 Feb 2016 14:08:52 +0200 Subject: [PATCH 010/105] angular.IRoute.controller can be defined as array --- angularjs/angular-route-tests.ts | 9 +++++++++ angularjs/angular-route.d.ts | 3 ++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/angularjs/angular-route-tests.ts b/angularjs/angular-route-tests.ts index 0260359fb..ab5fba0b6 100644 --- a/angularjs/angular-route-tests.ts +++ b/angularjs/angular-route-tests.ts @@ -1,3 +1,4 @@ +/// /// /** @@ -32,6 +33,14 @@ $routeProvider return "I return a string" } }) + .when('/projects/:projectId/dashboard5', { + controller: ['$log',function($log:ng.ILogService){ + $log.info('I am array') + }], + templateUrl: function ($routeParams?: ng.route.IRouteParamsService) { + return "I return a string" + } + }) .otherwise({ redirectTo: '/' }) .otherwise({ redirectTo: ($routeParams?: ng.route.IRouteParamsService, $locationPath?: string, $locationSearch?: any) => "" }); diff --git a/angularjs/angular-route.d.ts b/angularjs/angular-route.d.ts index eafdf714c..ec49b3cd9 100644 --- a/angularjs/angular-route.d.ts +++ b/angularjs/angular-route.d.ts @@ -47,6 +47,7 @@ declare module angular.route { } + type InlineAnnotatedFunction = Function|Array /** * see http://docs.angularjs.org/api/ngRoute/provider/$routeProvider#when for API documentation @@ -56,7 +57,7 @@ declare module angular.route { * {(string|function()=} * Controller fn that should be associated with newly created scope or the name of a registered controller if passed as a string. */ - controller?: string|Function; + controller?: string|InlineAnnotatedFunction; /** * A controller alias name. If present the controller will be published to scope under the controllerAs name. */ From ea3fcdda9ee552359e6f4b5552da2cfde840591e Mon Sep 17 00:00:00 2001 From: Ugaitz Urien Date: Thu, 11 Feb 2016 16:03:23 +0100 Subject: [PATCH 011/105] Controller field in a component can accept string, function or an array with parameters an function ["service1","service2", ControllerFunction] --- 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 67b3eb488..4a9a9cec7 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1685,7 +1685,7 @@ declare module angular { * Controller constructor function that should be associated with newly created scope or the name of a registered * controller if passed as a string. Empty function by default. */ - controller?: string | Function; + controller?: any; /** * An identifier name for a reference to the controller. If present, the controller will be published to scope under * the controllerAs name. If not present, this will default to be the same as the component name. From ee1e270d1d35e4328ff6310d58ab3fa420f35ee2 Mon Sep 17 00:00:00 2001 From: Prannay Budhraja Date: Thu, 11 Feb 2016 14:18:57 -0800 Subject: [PATCH 012/105] revert dexie export back to module definition --- dexie/dexie.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/dexie/dexie.d.ts b/dexie/dexie.d.ts index f4b68a1c4..2220bac56 100644 --- a/dexie/dexie.d.ts +++ b/dexie/dexie.d.ts @@ -323,4 +323,6 @@ declare module Dexie { } } -export = Dexie; +declare module 'dexie' { + export = Dexie; +} From 8d9e2d7993a2ac7d38427bd08bee641251f2dfd4 Mon Sep 17 00:00:00 2001 From: Chris Pearce Date: Fri, 12 Feb 2016 03:56:28 +0000 Subject: [PATCH 013/105] Added options parameters to decode method of jsonwebtoken Added options parameters to decode method of jsonwebtoken --- jsonwebtoken/jsonwebtoken-tests.ts | 6 ++++++ jsonwebtoken/jsonwebtoken.d.ts | 8 +++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/jsonwebtoken/jsonwebtoken-tests.ts b/jsonwebtoken/jsonwebtoken-tests.ts index 6aadaa82c..f4f63a12c 100644 --- a/jsonwebtoken/jsonwebtoken-tests.ts +++ b/jsonwebtoken/jsonwebtoken-tests.ts @@ -74,3 +74,9 @@ jwt.verify(token, cert, { ignoreExpiration: true }, function(err, decoded) { * https://github.com/auth0/node-jsonwebtoken#jwtdecodetoken */ var decoded = jwt.decode(token); + +decoded = jwt.decode(token, { complete: false }); + +decoded = jwt.decode(token, { json: false }); + +decoded = jwt.decode(token, { complete: false, json: false }); diff --git a/jsonwebtoken/jsonwebtoken.d.ts b/jsonwebtoken/jsonwebtoken.d.ts index a616027e9..b5a2708d2 100644 --- a/jsonwebtoken/jsonwebtoken.d.ts +++ b/jsonwebtoken/jsonwebtoken.d.ts @@ -43,6 +43,11 @@ declare module "jsonwebtoken" { maxAge?: string; } + export interface DecodeOptions { + complete?: boolean; + json?: boolean; + } + export interface VerifyCallback { (err: Error, decoded: any): void; } @@ -93,7 +98,8 @@ declare module "jsonwebtoken" { /** * Returns the decoded payload without verifying if the signature is valid. * @param {String} token - JWT string to decode + * @param {DecodeOptions} [options] - Options for decoding * @returns {Object} The decoded Token */ - function decode(token: string): any; + function decode(token: string, options?: DecodeOptions): any; } From 5d3116c83ea2aa0afcfef61c8cbbf6d7a4cbc09f Mon Sep 17 00:00:00 2001 From: nkovacic Date: Fri, 12 Feb 2016 11:03:00 +0100 Subject: [PATCH 014/105] Added commonJS support --- angular-ui-bootstrap/angular-ui-bootstrap.d.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts index 8ebfdb6c2..5b9d09d46 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts @@ -6,7 +6,15 @@ /// // Support for AMD require -declare module 'angular-bootstrap' {} +declare module 'angular-bootstrap' { + let _: string; + export = _; +} + +declare module 'angular-ui-bootstrap' { + let _: string; + export = _; +} declare module angular.ui.bootstrap { From f6e1b46bac6e4bd4dbe62a8474fa86ad2c33b374 Mon Sep 17 00:00:00 2001 From: amadeuszprus Date: Fri, 12 Feb 2016 11:04:10 +0100 Subject: [PATCH 015/105] added options scrollTo and scrollBy to jquery.slimScroll --- jquery.slimScroll/jquery.slimScroll.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/jquery.slimScroll/jquery.slimScroll.d.ts b/jquery.slimScroll/jquery.slimScroll.d.ts index d894828eb..e2b1b4523 100644 --- a/jquery.slimScroll/jquery.slimScroll.d.ts +++ b/jquery.slimScroll/jquery.slimScroll.d.ts @@ -49,6 +49,10 @@ interface IJQuerySlimScrollOptions { borderRadius?: string; // sets border radius of the rail railBorderRadius?: string; + // jumps to the specified scroll value + scrollTo?: string; + // increases/decreases current scroll value by specified amount + scrollBy?: string; } interface JQuery { From 354369f5072ffcb9ba08453ffda80c16ec5dc8f1 Mon Sep 17 00:00:00 2001 From: nkovacic Date: Fri, 12 Feb 2016 11:17:47 +0100 Subject: [PATCH 016/105] Added angular touchspin --- angular-touchspin/angular-touchspin-tests.ts | 29 +++++++++++++ angular-touchspin/angular-touchspin.d.ts | 43 ++++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 angular-touchspin/angular-touchspin-tests.ts create mode 100644 angular-touchspin/angular-touchspin.d.ts diff --git a/angular-touchspin/angular-touchspin-tests.ts b/angular-touchspin/angular-touchspin-tests.ts new file mode 100644 index 000000000..c6e229c7f --- /dev/null +++ b/angular-touchspin/angular-touchspin-tests.ts @@ -0,0 +1,29 @@ +/// +/// + +angular + .module('touchspin-tests', ['lm.touchspin']) + .config(function(touchspinConfigProvider: angularTouchSpin.ITouchSpinConfigProvider) { + touchspinConfigProvider.defaults({ + min: 0, + max: 0, + step: 0, + decimals: 0, + stepInterval: 0, + forceStepDivisibility: '', // none | floor | round | ceil + stepIntervalDelay: 0, + verticalButtons: true, + verticalUpClass: '', + verticalDownClass: '', + initVal: 0, + prefix: '', + postfix: '', + prefixExtraClass: '', + postfixExtraClass: '', + mousewheel: true, + buttonDownClass: '', + buttonUpClass: '', + buttonDownTxt: '', + buttonUpTxt: '' + }); + }); diff --git a/angular-touchspin/angular-touchspin.d.ts b/angular-touchspin/angular-touchspin.d.ts new file mode 100644 index 000000000..08cc353a3 --- /dev/null +++ b/angular-touchspin/angular-touchspin.d.ts @@ -0,0 +1,43 @@ +// Type definitions for Angular Touchspin v1.0.0 +// Project: https://github.com/nkovacic/angular-touchspin +// Definitions by: Niko Kovačič +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +//// + + +declare module "angular-touchspin" { + let _: string; + export = _; +} + +declare module angularTouchSpin { + interface ITouchSpinOptions { + min?: number; + max?: number; + step?: number; + decimals?: number; + stepInterval?: number; + forceStepDivisibility?: string; // none | floor | round | ceil + stepIntervalDelay?: number; + verticalButtons?: boolean; + verticalUpClass?: string; + verticalDownClass?: string; + initVal?: number; + prefix?: string; + postfix?: string; + prefixExtraClass?: string; + postfixExtraClass?: string; + mousewheel?: boolean; + buttonDownClass?: string; + buttonUpClass?: string; + buttonDownTxt?: string; + buttonUpTxt?: string; + } + + interface ITouchSpinConfig extends ITouchSpinOptions { } + + interface ITouchSpinConfigProvider { + defaults(touchSpinOptions: ITouchSpinOptions): void; + } +} \ No newline at end of file From 0df3cf83907e5cf8bcc9263e7dfc921df162c296 Mon Sep 17 00:00:00 2001 From: rhysd Date: Sat, 13 Feb 2016 01:47:25 +0900 Subject: [PATCH 017/105] Add type definitions for deep-extend module Project: https://github.com/unclechu/node-deep-extend --- deep-extend/deep-extend-tests.ts | 36 ++++++++++++++++++++++++++++++++ deep-extend/deep-extend.d.ts | 15 +++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 deep-extend/deep-extend-tests.ts create mode 100644 deep-extend/deep-extend.d.ts diff --git a/deep-extend/deep-extend-tests.ts b/deep-extend/deep-extend-tests.ts new file mode 100644 index 000000000..f5e35af35 --- /dev/null +++ b/deep-extend/deep-extend-tests.ts @@ -0,0 +1,36 @@ +/// + +import deepExtend = require('deep-extend'); +var obj1 = { + a: 1, + b: 2, + d: { + a: 1, + b: [true], + c: { test1: 123, test2: 321 } + }, + f: 5, + g: 123, + i: 321, + j: [1, 2] +}; +var obj2 = { + b: 3, + c: 5, + d: { + b: { first: 'one', second: 'two' }, + c: { test2: 222 } + }, + e: { one: 1, two: 2 }, + f: [42], + g: function(){}, + h: /abc/g, + i: null as {aaa: boolean}, + j: [3, 4] +}; + +deepExtend(obj1, obj2); +deepExtend(obj1, obj2, {ccc: 3}); +deepExtend(obj1, obj2, {ccc: 3}, {ddd: 4}); + + diff --git a/deep-extend/deep-extend.d.ts b/deep-extend/deep-extend.d.ts new file mode 100644 index 000000000..164e337a9 --- /dev/null +++ b/deep-extend/deep-extend.d.ts @@ -0,0 +1,15 @@ +// Type definitions for open 0.4.1 +// Project: https://github.com/unclechu/node-deep-extend +// Definitions by: rhysd +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'deep-extend' { + /* + * Recursive object extending. + */ + function deepExtend(target: T, source: U): T & U; + function deepExtend(target: T, source1: U, source2: V): T & U & V; + function deepExtend(target: T, source1: U, source2: V, source3: W): T & U & V & W; + function deepExtend(target: any, ...sources: any[]): any; + export = deepExtend; +} From a617153d464e26092a0286418116d156d652932b Mon Sep 17 00:00:00 2001 From: rhysd Date: Sat, 13 Feb 2016 02:03:21 +0900 Subject: [PATCH 018/105] Add type definitions for electron-window-state module Project: https://github.com/mawie81/electron-window-state --- .../electron-window-state-tests.ts | 35 ++++++++ .../electron-window-state.d.ts | 90 +++++++++++++++++++ 2 files changed, 125 insertions(+) create mode 100644 electron-window-state/electron-window-state-tests.ts create mode 100644 electron-window-state/electron-window-state.d.ts diff --git a/electron-window-state/electron-window-state-tests.ts b/electron-window-state/electron-window-state-tests.ts new file mode 100644 index 000000000..2d1dfbfe7 --- /dev/null +++ b/electron-window-state/electron-window-state-tests.ts @@ -0,0 +1,35 @@ +/// + +import {app, BrowserWindow} from 'electron'; +import windowStateKeeper = require('electron-window-state'); + +let win: Electron.BrowserWindow = null; + +app.on('ready', function () { + const mainWindowState = windowStateKeeper({ + defaultWidth: 1000, + defaultHeight: 800 + }); + + win = new BrowserWindow({ + 'x': mainWindowState.x, + 'y': mainWindowState.y, + 'width': mainWindowState.width, + 'height': mainWindowState.height, + }); + + mainWindowState.manage(win); +}); + +const s2 = windowStateKeeper({ + defaultWidth: 1000, + defaultHeight: 800, + file: __dirname + '/foo.json', + path: __dirname, + maximize: true, + fullScreen: false, +}); + +console.log(s2.isMaximized, s2.isFullScreen); + +s2.saveState(win); diff --git a/electron-window-state/electron-window-state.d.ts b/electron-window-state/electron-window-state.d.ts new file mode 100644 index 000000000..dfcb297e4 --- /dev/null +++ b/electron-window-state/electron-window-state.d.ts @@ -0,0 +1,90 @@ +// Type definitions for electron-window-state 2.0.0 +// Project: https://github.com/mawie81/electron-window-state +// Definitions by: rhysd +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace ElectronWindowState { + interface WindowState { + /* + * The saved x coordinate of the loaded state. + * undefined if the state has not been saved yet. + */ + x: number; + /* + * The saved y coordinate of the loaded state. + * undefined if the state has not been saved yet. + */ + y: number; + /* + * The saved width of loaded state. + * defaultWidth if the state has not been saved yet. + */ + width: number; + /* + * The saved heigth of loaded state. + * defaultHeight if the state has not been saved yet. + */ + height: number; + /* + * true if the window state was saved while the the window was maximized. + * undefined if the state has not been saved yet. + */ + isMaximized: boolean; + /* + * true if the window state was saved while the the window was in full screen + * mode. undefined if the state has not been saved yet. + */ + isFullScreen: boolean; + /* + * Register listeners on the given BrowserWindow for events that are related + * to size or position changes (resize, move). + * It will also restore the window's maximized or full screen state. + * When the window is closed we automatically remove the listeners and save the state. + */ + manage(win: Electron.BrowserWindow): void; + /* + * Saves the current state of the given BrowserWindow. + * This exists mostly for legacy purposes, and in most cases it's better to just use manage. + */ + saveState(win: Electron.BrowserWindow): void; + } + interface WindowStateKeeperOptions { + /* + * The width that should be returned if no file exists yet. Defaults to 800. + */ + defaultWidth?: number; + /* + * The height that should be returned if no file exists yet. Defaults to 600. + */ + defaultHeight?: number; + /* + * The path where the state file should be written to. + * Defaults to app.getPath('userData') + */ + path?: string; + /* + * The name of file. Defaults to window-state.json + */ + file?: string; + /* + * Should we automatically maximize the window, + * if it was last closed maximized. Defaults to true + */ + maximize?: boolean; + /* + * Should we automatically restore the window to full screen, + * if it was last closed full screen. Defaults to true + */ + fullScreen?: boolean; + } +} + +declare module 'electron-window-state' { + /* + * Load the previous state with fallback to defaults + */ + function windowStateKeeper(opts: ElectronWindowState.WindowStateKeeperOptions): ElectronWindowState.WindowState; + export = windowStateKeeper; +} From 73e7e4af0c78f2bd893da263248a3132283b86a2 Mon Sep 17 00:00:00 2001 From: Ryan Schmukler Date: Fri, 12 Feb 2016 12:49:36 -0500 Subject: [PATCH 019/105] expand pikaday definitions to include ranges --- pikaday/pikaday.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pikaday/pikaday.d.ts b/pikaday/pikaday.d.ts index a0f1ab58b..4229213f0 100644 --- a/pikaday/pikaday.d.ts +++ b/pikaday/pikaday.d.ts @@ -39,6 +39,10 @@ declare class Pikaday { setMaxDate(date:Date):void; + setEndRange(date:Date):void; + + setStartRange(date:Date):void; + isVisible():boolean; show():void; From c22a5e55b062c7b2af9df92ea0820c2afa153b2a Mon Sep 17 00:00:00 2001 From: Andrew Fong Date: Fri, 12 Feb 2016 21:40:38 +0000 Subject: [PATCH 020/105] Infer array type when using _.difference --- lodash/lodash-tests.ts | 16 ++++++++-------- lodash/lodash.d.ts | 4 ++-- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 9e3e9ada6..17dfb80e4 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -217,15 +217,15 @@ module TestDifference { { let result: TResult[]; - result = _.difference(array); - result = _.difference(array, array); - result = _.difference(array, list, array); - result = _.difference(array, array, list, array); + result = _.difference(array); + result = _.difference(array, array); + result = _.difference(array, list, array); + result = _.difference(array, array, list, array); - result = _.difference(list); - result = _.difference(list, list); - result = _.difference(list, array, list); - result = _.difference(list, list, array, list); + result = _.difference(list); + result = _.difference(list, list); + result = _.difference(list, array, list); + result = _.difference(list, list, array, list); } { diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 7ddc02dca..6618209cb 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -515,8 +515,8 @@ declare module _ { * @return Returns the new array of filtered values. */ difference( - array: any[]|List, - ...values: any[] + array: T[]|List, + ...values: Array> ): T[]; } From 7677a9f3aa9755b24ee85853766da8c8e11f7280 Mon Sep 17 00:00:00 2001 From: Boris Prpic Date: Sat, 13 Feb 2016 02:30:12 +0100 Subject: [PATCH 021/105] Update angular.d.ts --- 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 a591410a2..fda3f9fa0 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1710,7 +1710,7 @@ declare module angular { * Define DOM attribute binding to component properties. Component properties are always bound to the component * controller and not to the scope. */ - bindings?: Object; + bindings?: any; /** * Whether transclusion is enabled. Enabled by default. */ @@ -1766,7 +1766,7 @@ declare module angular { name?: string; priority?: number; replace?: boolean; - require? : string | Array; + require? : any; restrict?: string; scope?: any; template?: string | Function; From 71fed47a63d8e3a005d7c4fd189a749c6ade6869 Mon Sep 17 00:00:00 2001 From: Andrew Eisenberg Date: Fri, 12 Feb 2016 21:41:13 -0800 Subject: [PATCH 022/105] Proxyquire uses a fluent api All of its api configuration methods return an object with the `Proxyquire` type. --- proxyquire/proxyquire.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/proxyquire/proxyquire.d.ts b/proxyquire/proxyquire.d.ts index 06e1c773e..87254a055 100644 --- a/proxyquire/proxyquire.d.ts +++ b/proxyquire/proxyquire.d.ts @@ -14,12 +14,12 @@ interface Proxyquire { noCallThru(): Proxyquire; callThru(): Proxyquire; - noPreserveCache(): void; - preserveCache(): void; + noPreserveCache(): Proxyquire; + preserveCache(): Proxyquire; } declare module 'proxyquire' { var p: Proxyquire; export = p; -} \ No newline at end of file +} From 59cdd05b8016b7fa908b99c857fbeb06eaf0d162 Mon Sep 17 00:00:00 2001 From: jKey Lu Date: Sat, 13 Feb 2016 22:04:32 +0800 Subject: [PATCH 023/105] add definitions for koa-compose --- koa-compose/koa-compose-2.3.1-tests.ts | 15 +++++++++++++++ koa-compose/koa-compose-2.3.1.d.ts | 20 ++++++++++++++++++++ koa-compose/koa-compose-tests.ts | 18 ++++++++++++++++++ koa-compose/koa-compose.d.ts | 20 ++++++++++++++++++++ 4 files changed, 73 insertions(+) create mode 100644 koa-compose/koa-compose-2.3.1-tests.ts create mode 100644 koa-compose/koa-compose-2.3.1.d.ts create mode 100644 koa-compose/koa-compose-tests.ts create mode 100644 koa-compose/koa-compose.d.ts diff --git a/koa-compose/koa-compose-2.3.1-tests.ts b/koa-compose/koa-compose-2.3.1-tests.ts new file mode 100644 index 000000000..72a4e08bc --- /dev/null +++ b/koa-compose/koa-compose-2.3.1-tests.ts @@ -0,0 +1,15 @@ +/// + +import compose = require('koa-compose'); + +var fn1: compose.Middleware = function *(next: void) { + console.log('in fn1'); + yield next; +} + +var fn2: compose.Middleware = function *(next: void) { + console.log('in fn2'); + yield next; +} + +var fn = compose([fn1, fn2]); \ No newline at end of file diff --git a/koa-compose/koa-compose-2.3.1.d.ts b/koa-compose/koa-compose-2.3.1.d.ts new file mode 100644 index 000000000..f8130bf0a --- /dev/null +++ b/koa-compose/koa-compose-2.3.1.d.ts @@ -0,0 +1,20 @@ +// Type definitions for koa v2.3.1 +// Project: https://github.com/koajs/compose +// Definitions by: jKey Lu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "koa-compose" { + function compose(middleware: compose.Middleware[]): compose.ComposedMiddleware; + + module compose { + interface Middleware { + (next?: void): IterableIterator; + } + + interface ComposedMiddleware { + (): IterableIterator; + } + } + + export = compose; +} \ No newline at end of file diff --git a/koa-compose/koa-compose-tests.ts b/koa-compose/koa-compose-tests.ts new file mode 100644 index 000000000..122817929 --- /dev/null +++ b/koa-compose/koa-compose-tests.ts @@ -0,0 +1,18 @@ +/// + +import compose = require('koa-compose'); + +var fn1: compose.Middleware = function(context: any, next: () => Promise): Promise { + return Promise + .resolve(console.log('in fn1')) + .then(() => next()); +}; + +var fn2: compose.Middleware = function(context: any, next: () => Promise): Promise { + return Promise + .resolve(console.log('in fn2')) + .then(() => next()); +}; + + +var fn = compose([fn1, fn2]); \ No newline at end of file diff --git a/koa-compose/koa-compose.d.ts b/koa-compose/koa-compose.d.ts new file mode 100644 index 000000000..0521124b4 --- /dev/null +++ b/koa-compose/koa-compose.d.ts @@ -0,0 +1,20 @@ +// Type definitions for koa v3.0.0 +// Project: https://github.com/koajs/compose +// Definitions by: jKey Lu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "koa-compose" { + function compose(middleware: compose.Middleware[]): compose.ComposedMiddleware; + + module compose { + interface Middleware { + (context: any, next?: () => Promise): Promise; + } + + interface ComposedMiddleware { + (context: any): Promise; + } + } + + export = compose; +} \ No newline at end of file From 018bdf04bdc4a0a5cf365508cb645a1bbf525364 Mon Sep 17 00:00:00 2001 From: John Cant Date: Sat, 13 Feb 2016 15:48:22 +0000 Subject: [PATCH 024/105] Add definition for protractor-helpers v1.0.0 --- .../protractor-helpers-tests.ts | 114 ++++++++++++++++++ protractor-helpers/protractor-helpers.d.ts | 111 +++++++++++++++++ 2 files changed, 225 insertions(+) create mode 100644 protractor-helpers/protractor-helpers-tests.ts create mode 100644 protractor-helpers/protractor-helpers.d.ts diff --git a/protractor-helpers/protractor-helpers-tests.ts b/protractor-helpers/protractor-helpers-tests.ts new file mode 100644 index 000000000..b80c57c53 --- /dev/null +++ b/protractor-helpers/protractor-helpers-tests.ts @@ -0,0 +1,114 @@ +/// + +import helpers = require('protractor-helpers'); + +function testElementArrayFinder() { + + var single1 : protractor.ElementFinder = $$('.foo').getByText('Hello'); + var multiple : protractor.ElementArrayFinder = $$('.foo').$$data('Hello'); + +} + +function testElementFinder () { + var single2 : protractor.ElementFinder = $('.foo').$data('Hello'); +} + +function testGlobals() { + + var single : protractor.ElementFinder = $data('Hello'); + var multiple : protractor.ElementArrayFinder = $$data('Hello'); + +} + +function testHelpers() { + + var q0 : webdriver.promise.IThenable = helpers.not($('.foo').isDisplayed()); + // TODO - Check impl + var q1 : webdriver.promise.IThenable<{[key: string]:string}> = helpers.translate(["foo", "bar"]); + var q2 : webdriver.promise.IThenable<{[key: string]:string}> = helpers.translate(["foo", "bar"], {name: 'foo'}); + var q3 : webdriver.promise.IThenable = helpers.translate("foo"); + var q4 : webdriver.promise.IThenable = helpers.translate("foo", {name: 'foo'}); + + helpers.safeGet('https://foo/'); + + helpers.maximizeWindow(500, 500); + helpers.maximizeWindow(500); + helpers.maximizeWindow(undefined, 500); + helpers.maximizeWindow(); + + helpers.resetPosition(); + helpers.moveToElement(".foo"); // TODO - ? + + helpers.displayHover($('.foo')); + + helpers.waitForElement($('.foo')); + helpers.waitForElement($('.foo'), 1000); + helpers.waitForElementToDisappear($('.foo'));; + helpers.waitForElementToDisappear($('.foo'), 1000); + + helpers.selectOptionByText($('select'), "GB"); + helpers.selectOptionByIndex($('select'), 1); + + helpers.selectOption($$('select option').first()); + + var ff : boolean = helpers.isFirefox(); + var ie : boolean = helpers.isIE(); + + var msg : string = helpers.createMessage("actual", "message", true); + var msg : string = helpers.createMessage($('.foo'), "message", true); + var msg : string = helpers.createMessage($$('.foo'), "message", true); + + helpers.clearAndSetValue($('input'), 'Foo'); + + var hc : webdriver.promise.IThenable = helpers.hasClass($('.foo'), 'foo'); + + var hv : webdriver.promise.IThenable = helpers.hasValue($('input[type=text]'), 'foo'); + var hv1 : webdriver.promise.IThenable = helpers.hasValue($('input[type=numeric]'), 12); + var hl : webdriver.promise.IThenable = helpers.hasLink($('div'), 'http://foo.com'); + var disabled : webdriver.promise.IThenable = helpers.isDisabled($('foo')); + var checked : webdriver.promise.IThenable = helpers.isChecked($('foo')); + + var q5 : webdriver.promise.IThenable = helpers.getFilteredConsoleErrors(); + +} + +function testLocators() { + + element(by.dataHook("foo")); + element(by.dataHook("foo", $('.parentfoo'))); + element(by.dataHook("foo", undefined , ".foo")); + element(by.dataHook("foo", $('.parentfoo'), ".foo")); // TODO - This might not make much sense, but can technically be used in working code. Opinions welcome + + element.all(by.dataHook("foo")); + element.all(by.dataHook("foo", $('parentfoo'))); + element.all(by.dataHook("foo", undefined , ".foo")); + element.all(by.dataHook("foo", $('parentfoo'), ".foo")); // TODO - This might not make much sense, but can technically be used in working code. Opinions welcome + +} + +function testMatchers() { + + var expectResult : boolean; + expectResult = expect($('.foo')).toBePresent(); + expectResult = expect($('.foo')).toBeDisplayed(); + expectResult = expect($$('.foo').count()).toHaveCountOf(1); + expectResult = expect($('.foo')).toHaveText("bla"); + expectResult = expect($('.foo')).toMatchRegex(/bla/); + expectResult = expect($('.foo').getText()).toMatchMoney(123, "£"); + expectResult = expect($('.foo').getText()).toMatchMoneyWithFraction(123.45, "£"); + expectResult = expect($('input')).toHaveValue(12); + expectResult = expect($('input')).toHaveValue("bla"); + expectResult = expect($('.foo')).toHaveClass("foo"); + expectResult = expect($('.foo')).toHaveUrl('https://foo.com'); + expectResult = expect($('.foo')).toBeDisabled(); + expectResult = expect($('.foo')).toBeChecked(); + expectResult = expect($('.foo')).toBeValid(); + expectResult = expect($('.foo')).toBeInvalid(); + expectResult = expect($('.foo')).toBeInvalidRequired(); + expectResult = expect($('.foo')).toMatchTranslated("foo"); + expectResult = expect($('.foo')).toMatchTranslated("foo", {foo: "bar"}); + expectResult = expect($('.foo')).toMatchTranslated(["foo"]); + expectResult = expect($('.foo')).toMatchTranslated(["foo", "bla"], {foo: "bar"}); + +} + diff --git a/protractor-helpers/protractor-helpers.d.ts b/protractor-helpers/protractor-helpers.d.ts new file mode 100644 index 000000000..8d08f7fc9 --- /dev/null +++ b/protractor-helpers/protractor-helpers.d.ts @@ -0,0 +1,111 @@ +// Type definitions for protractor-helpers v1.0.0 +// Project: https://github.com/wix/protractor-helpers +// Definitions by: John Cant +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// +/// + +// ElementArrayFinder + +declare module protractor { + interface ElementArrayFinder { + getByText(text: string) : protractor.ElementFinder; + $$data(hook: string) : protractor.ElementArrayFinder; + } + + interface ElementFinder { + $data(hook: string) : protractor.ElementFinder; + } +} + +// Globals + +declare function $data(hook: string) : protractor.ElementFinder; +declare function $$data(hook: string) : protractor.ElementArrayFinder; + + +// Locators + +// TODO - find out about result of querySelector and querySelector all. +// Are they Locator s? +declare module protractor { + interface IProtractorLocatorStrategy { + dataHook(hook: string, optParentElement?: protractor.ElementFinder, optRootSelector?: string) : webdriver.Locator; + dataHookAll(hook: string, optParentElement?: protractor.ElementFinder, optRootSelector?: string) : webdriver.Locator; + } +} + +// Matchers +// TODO - Typescript doesn't really help much here +// we don't know what type is being tested. +// Fixing this would require modifying the +// jasmine d.ts. + +declare module jasmine { + interface Matchers { + toBePresent() : boolean; + toBeDisplayed() : boolean; + toHaveCountOf(expectedCount : number) : boolean; + toHaveText(expectedText : string) : boolean; + toMatchRegex(regex : RegExp) : boolean; + toMatchMoney(expectedValue : number, currencySymbol? : string) : boolean; + toMatchMoneyWithFraction(expectedValue : number, currencySymbol?: string) : boolean; + toHaveValue(actual: string | number) : boolean; + toHaveClass(className : string) : boolean; + toHaveUrl(url : string) : boolean; + toBeDisabled() : boolean; + toBeChecked() : boolean; + toBeValid() : boolean; + toBeInvalid() : boolean; + toBeInvalidRequired() : boolean; + // Copied definitions from angular-translate. + toMatchTranslated(translationId : string, interpolateParams? : any) : boolean; + toMatchTranslated(translationId : string[], interpolateParams? : any) : boolean; + } +} + + +declare module "protractor-helpers" { + + function not(arg: webdriver.promise.IThenable) : webdriver.promise.IThenable; + + // Copied definitions from angular-translate. + function translate(translationId: string, interpolateParams?: any): webdriver.promise.IThenable; + function translate(translationId: string[], interpolateParams?: any): webdriver.promise.IThenable<{ [key: string]: string }>; + + function safeGet(url: string) : void; + + function maximizeWindow(width?: number, height?: number) : void; // TODO + function resetPosition() : void; + function moveToElement(hook: string) : void; + function displayHover(element: protractor.ElementFinder) : void; + + function waitForElement(element: protractor.ElementFinder, timeout?: number) : void; + function waitForElementToDisappear(element: protractor.ElementFinder, timeout?: number) : void; + + function selectOptionByText(select: protractor.ElementFinder, text: string) : void; + function selectOptionByIndex(select: protractor.ElementFinder, index: number) : void; + + function selectOption(option: protractor.ElementFinder) : void + + function isFirefox() : boolean; + function isIE() : boolean; + + function createMessage(actual : string, message : string, isNot : any) : string; // isNot : boolean too inflexible + function createMessage(actual : protractor.ElementFinder, message : string, isNot : any) : string; // isNot : boolean too inflexible + function createMessage(actual : protractor.ElementArrayFinder, message : string, isNot : any) : string; // isNot : boolean too inflexible + + function clearAndSetValue(input : protractor.ElementFinder, value : string) : void; // TODO - sendKeys(value) + + function hasClass(element: protractor.ElementFinder, className: string) : webdriver.promise.IThenable; + function hasValue(element: protractor.ElementFinder, expectedValue: string) : webdriver.promise.IThenable; + function hasValue(element: protractor.ElementFinder, expectedValue: number) : webdriver.promise.IThenable; + function hasLink(element: protractor.ElementFinder, url: string) : webdriver.promise.IThenable; + function isDisabled(element: protractor.ElementFinder) : webdriver.promise.IThenable; + function isChecked(element: protractor.ElementFinder) : webdriver.promise.IThenable; + function getFilteredConsoleErrors() : webdriver.promise.IThenable; // TODO - discuss handling in IE + +} + From 5f3b413653e738d5d9bfd1575d075e5334b5e564 Mon Sep 17 00:00:00 2001 From: Pavel Date: Sat, 13 Feb 2016 18:23:39 +0000 Subject: [PATCH 025/105] Updated definitions of the ColProps. Hidden flags. https://react-bootstrap.github.io/components.html#grid-props-col xsHidden smHidden mdHidden lgHidden --- react-bootstrap/react-bootstrap.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/react-bootstrap/react-bootstrap.d.ts b/react-bootstrap/react-bootstrap.d.ts index c6e30d081..af1cc7338 100644 --- a/react-bootstrap/react-bootstrap.d.ts +++ b/react-bootstrap/react-bootstrap.d.ts @@ -692,18 +692,22 @@ declare module "react-bootstrap" { className?: string; componentClass?: any; // TODO: Add more specific type lg?: number; + lgHidden?: boolean; lgOffset?: number; lgPull?: number; lgPush?: number; md?: number; + mdHidden?: boolean; mdOffset?: number; mdPull?: number; mdPush?: number; sm?: number; + smHidden?: boolean; smOffset?: number; smPull?: number; smPush?: number; xs?: number; + xsHidden?: boolean; xsOffset?: number; xsPull?: number; xsPush?: number; From 229cb92825ec05c986dff721018b7130126f09a9 Mon Sep 17 00:00:00 2001 From: Demis Bellot Date: Sat, 13 Feb 2016 14:32:52 -0500 Subject: [PATCH 026/105] Add new ss-utils API's + fix existing type definition --- ss-utils/ss-utils-tests.ts | 7 +++++-- ss-utils/ss-utils.d.ts | 10 +++++++--- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/ss-utils/ss-utils-tests.ts b/ss-utils/ss-utils-tests.ts index 5ecaaef96..0282aef21 100644 --- a/ss-utils/ss-utils-tests.ts +++ b/ss-utils/ss-utils-tests.ts @@ -58,12 +58,15 @@ function test_ssutils_Static(){ dateFmt = $.ss.dfmt(new Date(2001,1,1)); dateFmt = $.ss.dfmthm(new Date(2001,1,1)); dateFmt = $.ss.tfmt12(new Date(2001,1,1)); - var parts:string[] = $.ss.splitOnFirst("A,B,C"); - parts = $.ss.splitOnLast("A,B,C"); + var parts:string[] = $.ss.splitOnFirst("A;B;C",";"); + parts = $.ss.splitOnLast("A;B;C", ";"); var selectedText = $.ss.getSelection(); var qs:{ [index: string]: string } = $.ss.queryString("http://google.com?a=b&c=d"); var relativePath = $.ss.createUrl("/path/to/{File}", {File:"file.js"}); var readableText = $.ss.humanize("TheVariableName"); + $.ss.normalizeKey("aAa"); + $.ss.normalize({"AA":1,"bB":2,"C":{"A":11,"B":22},"D":[1,2],"E":[{"A":111,"B":222}]}); + $.ss.normalize({"AA":1,"bB":2,"C":{"A":11,"B":22},"D":[1,2],"E":[{"A":111,"B":222}]}, true); $.ss.parseResponseStatus('{"message":"test"}'); $.ss.postJSON("/path/to/url", {json:"data"}, function(r:any) {}); diff --git a/ss-utils/ss-utils.d.ts b/ss-utils/ss-utils.d.ts index 9154e478f..d86f227c7 100644 --- a/ss-utils/ss-utils.d.ts +++ b/ss-utils/ss-utils.d.ts @@ -17,12 +17,16 @@ declare namespace ssutils { dfmt: (d: Date) => string; dfmthm: (d: Date) => string; tfmt12: (d: Date) => string; - splitOnFirst: (s: string) => string[]; - splitOnLast: (s: string) => string[]; + splitOnFirst: (s: string, delimiter:string) => string[]; + splitOnLast: (s: string, delimiter: string) => string[]; getSelection: () => string; + combinePaths: (...paths:string[]) => string; queryString: (url: string) => { [index: string]: string }; - createUrl: (route: string, args?: any) => string; + createPath: (route: string, args: any) => string; + createUrl: (route: string, args: any) => string; humanize: (s: string) => string; + normalizeKey: (key: string) => string; + normalize: (dto: any, deep?:boolean) => any; parseResponseStatus: (json: string, defaultMsg?: string) => any; postJSON: (url: string, data: Object | String, success?: Function, error?: Function) => any; From 0c8b8219167d47b6e1e5bb47abdb054f3000ef58 Mon Sep 17 00:00:00 2001 From: Kohei Hisakuni Date: Sat, 13 Feb 2016 12:53:18 -0800 Subject: [PATCH 027/105] Make sure vexflow can be loaded with jspm --- vexflow/vexflow.d.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 5c304fa30..fd41619ef 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -6,7 +6,7 @@ //inconsistent namespace: this is a helper funtion from tables.js and should not pollute the global namespace! declare function sanitizeDuration(duration : string) : string; -declare namespace Vex { +declare module Vex { function L(block : string, args : any[]) : void; function Merge(destination : T, source : Object) : T; @@ -1411,3 +1411,7 @@ declare namespace Vex { } } } + +declare module "vexflow" { + export = Vex; +} From 1c4a34873c9e70cce86edd0e61c559e43dfa5f75 Mon Sep 17 00:00:00 2001 From: Boris Prpic Date: Sat, 13 Feb 2016 21:54:57 +0100 Subject: [PATCH 028/105] Component controller can be array angular.module(.....).component("componentName", { controller: ["$rootScope",function($rootScope) { }], template: .... } --- 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 fda3f9fa0..656e62865 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1685,7 +1685,7 @@ declare module angular { * Controller constructor function that should be associated with newly created scope or the name of a registered * controller if passed as a string. Empty function by default. */ - controller?: string | Function; + controller?: any; /** * An identifier name for a reference to the controller. If present, the controller will be published to scope under * the controllerAs name. If not present, this will default to be the same as the component name. From 39baf904d4e672e3ed88d293282a14989331b3f7 Mon Sep 17 00:00:00 2001 From: Ingvar Stepanyan Date: Sat, 13 Feb 2016 22:00:25 +0000 Subject: [PATCH 029/105] Fix chrome.events.Event definition Made all methods to strictly accept same type of function; fixes removeListener incompatibility. --- chrome/chrome.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts index 17613b88c..70c897421 100755 --- a/chrome/chrome.d.ts +++ b/chrome/chrome.d.ts @@ -2537,14 +2537,14 @@ declare module chrome.events { } /** An object which allows the addition and removal of listeners for a Chrome event. */ - interface Event { + interface Event { /** * Registers an event listener callback to an event. * @param callback Called when an event occurs. The parameters of this function depend on the type of event. * The callback parameter should be a function that looks like this: * function() {...}; */ - addListener(callback: Function): void; + addListener(callback: T): void; /** * Returns currently registered rules. * @param callback Called with registered rules. @@ -2565,7 +2565,7 @@ declare module chrome.events { /** * @param callback Listener whose registration status shall be tested. */ - hasListener(callback: Function): boolean; + hasListener(callback: T): boolean; /** * Unregisters currently registered rules. * @param ruleIdentifiers If an array is passed, only rules with identifiers contained in this array are unregistered. @@ -2596,7 +2596,7 @@ declare module chrome.events { * The callback parameter should be a function that looks like this: * function() {...}; */ - removeListener(callback: () => void): void; + removeListener(callback: T): void; hasListeners(): boolean; } From 7fca7ec726811d1c57d44674fba17abb209a1419 Mon Sep 17 00:00:00 2001 From: Karl Bennett Date: Sun, 14 Feb 2016 11:19:32 +1300 Subject: [PATCH 030/105] Added definitions for the jsmockito library. --- jsmockito/jsmockito-tests.ts | 195 ++++++++++ jsmockito/jsmockito.d.ts | 713 +++++++++++++++++++++++++++++++++++ 2 files changed, 908 insertions(+) create mode 100644 jsmockito/jsmockito-tests.ts create mode 100644 jsmockito/jsmockito.d.ts diff --git a/jsmockito/jsmockito-tests.ts b/jsmockito/jsmockito-tests.ts new file mode 100644 index 000000000..3b12ffba5 --- /dev/null +++ b/jsmockito/jsmockito-tests.ts @@ -0,0 +1,195 @@ +/// + +function test_version() { + var version: string = JsMockito.version; +} + +// JsMockito.JsMockitoStubBuilder + + +function test_then() { + new JsMockito.JsMockitoStubBuilder().then(function () {}); + new JsMockito.JsMockitoStubBuilder().then(function () {}, function () {}, function () {}); +} + +function test_thenReturn() { + new JsMockito.JsMockitoStubBuilder().thenReturn(1); + new JsMockito.JsMockitoStubBuilder().thenReturn("two", [3, 4], {5: 6}, function (seven: number) {return seven;}); +} + +function test_thenThrow() { + new JsMockito.JsMockitoStubBuilder().thenThrow(new Error()); + new JsMockito.JsMockitoStubBuilder().thenThrow(new EvalError(), new RangeError(), new ReferenceError()); +} + +// JsMockito + +function test_JsMockito_isMock() { + var result = JsMockito.isMock(new TestClass()); +} + +function test_JsMockito_when() { + JsMockito.when(new TestClass()).test().thenReturn(true); +} + +function test_JsMockito_verify() { + JsMockito.verify(new TestClass(), new TestVerifier()).test(); +} + +function test_JsMockito_verifyZeroInteractions() { + JsMockito.verifyZeroInteractions(new TestClass()); + JsMockito.verifyZeroInteractions(new TestClass(), new TestClass(), new TestClass()); +} + +function test_JsMockito_verifyNoMoreInteractions() { + JsMockito.verifyNoMoreInteractions(new TestClass()); + JsMockito.verifyNoMoreInteractions(new TestClass(), new TestClass(), new TestClass()); +} + +function test_JsMockito_spy() { + var testClass = JsMockito.spy(new TestClass()); + testClass.test(); +} + +function test_JsMockito_mockFunction() { + JsMockito.mockFunction()(); + JsMockito.mockFunction("name")(); + JsMockito.mockFunction("name", function() {})(); +} + +function test_JsMockito_mock() { + JsMockito.mock(TestClass).test(); + JsMockito.mock(Array).push("one"); +} + +// JsMockito.Verifiers + +function test_JsMockito_Verifiers_never() { + JsMockito.verify(new TestClass(), JsMockito.Verifiers.never()).test(); +} + +function test_JsMockito_Verifiers_zeroInteractions() { + JsMockito.verify(new TestClass(), JsMockito.Verifiers.zeroInteractions()).test(); +} + +function test_JsMockito_Verifiers_noMoreInteractions() { + JsMockito.verify(new TestClass(), JsMockito.Verifiers.noMoreInteractions()).test(); +} + +function test_JsMockito_Verifiers_times() { + JsMockito.verify(new TestClass(), JsMockito.Verifiers.times(1)).test(); +} + +function test_JsMockito_Verifiers_once() { + JsMockito.verify(new TestClass(), JsMockito.Verifiers.once()).test(); +} + +// JsMockito.Integration + +function test_JsMockito_Integration_importTo() { + JsMockito.Integration.importTo(this); +} + +function test_JsMockito_Integration_screwunit() { + JsMockito.Integration.screwunit(); +} + +function test_JsMockito_Integration_JsTestDriver() { + JsMockito.Integration.JsTestDriver(); +} + +function test_JsMockito_Integration_JsUnitTest() { + JsMockito.Integration.JsUnitTest(); +} + +function test_JsMockito_Integration_YUITest() { + JsMockito.Integration.YUITest(); +} + +function test_JsMockito_Integration_QUnit() { + JsMockito.Integration.QUnit(); +} + +function test_JsMockito_Integration_jsUnity() { + JsMockito.Integration.jsUnity(); +} + +function test_JsMockito_Integration_jSpec() { + JsMockito.Integration.jSpec(); +} + +// Global Functions + +function test_isMock() { + var result = isMock(new TestClass()); +} + +function test_when() { + when(new TestClass()).test().thenReturn(true); +} + +function test_verify() { + verify(new TestClass(), new TestVerifier()).test(); +} + +function test_verifyZeroInteractions() { + verifyZeroInteractions(new TestClass()); + verifyZeroInteractions(new TestClass(), new TestClass(), new TestClass()); +} + +function test_verifyNoMoreInteractions() { + verifyNoMoreInteractions(new TestClass()); + verifyNoMoreInteractions(new TestClass(), new TestClass(), new TestClass()); +} + +function test_spy() { + var testClass = spy(new TestClass()); + testClass.test(); + + var array = spy([]); + array.push("one"); +} + +function test_mockFunction() { + mockFunction()(); + mockFunction("name")(); + mockFunction("name", function() {})(); +} + +function test_mock() { + var testClass = mock(TestClass); + testClass.test(); + + var array = mock(Array); + array.push("one"); +} + +function test_never() { + verify(new TestClass(), never()).test(); +} + +function test_zeroInteractions() { + verify(new TestClass(), zeroInteractions()).test(); +} + +function test_noMoreInteractions() { + verify(new TestClass(), noMoreInteractions()).test(); +} + +function test_times() { + verify(new TestClass(), times(1)).test(); +} + +function test_once() { + verify(new TestClass(), once()).test(); +} + +// Test Definitions + +declare class TestClass { + test(): any; +} + +declare class TestVerifier implements JsMockito.Verifier { + +} diff --git a/jsmockito/jsmockito.d.ts b/jsmockito/jsmockito.d.ts new file mode 100644 index 000000000..401cb9f93 --- /dev/null +++ b/jsmockito/jsmockito.d.ts @@ -0,0 +1,713 @@ +// Type definitions for JsMockito 1.0.4 +// Project: http://github.com/chrisleishman/jsmockito +// Definitions by: Karl Bennett +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Top-level module for the JsMockito mocking library. + * + * @author Karl Bennett + */ + +/** + *

Contents

+ * + *
    + *
  1. Let's verify some behaviour!
  2. + *
  3. How about some stubbing?
  4. + *
  5. Matching Arguments
  6. + *
  7. Verifying exact number of invocations / at least once / + * never
  8. + *
  9. Matching the context ('this')
  10. + *
  11. Making sure interactions never happened on a mock
  12. + *
  13. Finding redundant invocations
  14. + *
+ * + *

In the following examples object mocking is done with Array as this is + * well understood, although you probably wouldn't mock this in normal test + * development.

+ * + *

1. Let's verify some behaviour!

+ * + *

For an object:

+ *
+ * //mock creation
+ * var mockedArray = mock(Array);
+ *
+ * //using mock object
+ * mockedArray.push("one");
+ * mockedArray.reverse();
+ *
+ * //verification
+ * verify(mockedArray).push("one");
+ * verify(mockedArray).reverse();
+ * 
+ * + *

For a function:

+ *
+ * //mock creation
+ * var mockedFunc = mockFunction();
+ *
+ * //using mock function
+ * mockedFunc('hello world');
+ * mockedFunc.call(this, 'foobar');
+ * mockedFunc.apply(this, [ 'barfoo' ]);
+ *
+ * //verification
+ * verify(mockedFunc)('hello world');
+ * verify(mockedFunc)('foobar');
+ * verify(mockedFunc)('barfoo');
+ * 
+ * + *

Once created a mock will remember all interactions. Then you selectively + * verify whatever interactions you are interested in.

+ * + *

2. How about some stubbing?

+ * + *

For an object:

+ *
+ * var mockedArray = mock(Array);
+ *
+ * //stubbing
+ * when(mockedArray).slice(0).thenReturn('f');
+ * when(mockedArray).slice(1).thenThrow('An exception');
+ * when(mockedArray).slice(2).then(function() { return 1+2 });
+ *
+ * //the following returns "f"
+ * assertThat(mockedArray.slice(0), equalTo('f'));
+ *
+ * //the following throws exception 'An exception'
+ * var ex = undefined;
+ * try {
+ *   mockedArray.slice(1);
+ * } catch (e) {
+ *   ex = e;
+ * }
+ * assertThat(ex, equalTo('An exception');
+ *
+ * //the following invokes the stub method, which returns 3
+ * assertThat(mockedArray.slice(2), equalTo(3));
+ *
+ * //the following returns undefined as slice(999) was not stubbed
+ * assertThat(mockedArray.slice(999), typeOf('undefined'));
+ *
+ * //stubs can take multiple values to return in order (same for 'thenThrow' and 'then' as well)
+ * when(mockedArray).pop().thenReturn('a', 'b', 'c');
+ * assertThat(mockedArray.pop(), equalTo('a'));
+ * assertThat(mockedArray.pop(), equalTo('b'));
+ * assertThat(mockedArray.pop(), equalTo('c'));
+ * assertThat(mockedArray.pop(), equalTo('c'));
+ *
+ * //stubs can also be chained to return values in order
+ * when(mockedArray).unshift().thenReturn('a').thenReturn('b').then(function() { return 'c' });
+ * assertThat(mockedArray.unshift(), equalTo('a'));
+ * assertThat(mockedArray.unshift(), equalTo('b'));
+ * assertThat(mockedArray.unshift(), equalTo('c'));
+ * assertThat(mockedArray.unshift(), equalTo('c'));
+ *
+ * //stub matching can overlap, allowing for specific cases and defaults
+ * when(mockedArray).slice(3).thenReturn('abcde');
+ * when(mockedArray).slice(3, lessThan(0)).thenReturn('edcba');
+ * assertThat(mockedArray.slice(3, -1), equalTo('edcba'));
+ * assertThat(mockedArray.slice(3, 1), equalTo('abcde'));
+ * assertThat(mockedArray.slice(3), equalTo('abcde'));
+ *
+ * //can also verify a stubbed invocation, although this is usually redundant
+ * verify(mockedArray).slice(0);
+ * 
+ * + *

For a function:

+ *
+ * var mockedFunc = mockFunction();
+ *
+ * //stubbing
+ * when(mockedFunc)(0).thenReturn('f');
+ * when(mockedFunc)(1).thenThrow('An exception');
+ * when(mockedFunc)(2).then(function() { return 1+2 });
+ *
+ * //the following returns "f"
+ * assertThat(mockedFunc(0), equalTo('f'))
+ *
+ * //following throws exception 'An exception'
+ * mockedFunc(1);
+ * //the following throws exception 'An exception'
+ * var ex = undefined;
+ * try {
+ *   mockedFunc(1);
+ * } catch (e) {
+ *   ex = e;
+ * }
+ * assertThat(ex, equalTo('An exception');
+ *
+ * //the following invokes the stub method, which returns 3
+ * assertThat(mockedFunc(2), equalTo(3));
+ *
+ * //following returns undefined as mockedFunc(999) was not stubbed
+ * assertThat(mockedFunc(999), typeOf('undefined'));
+ *
+ * //stubs can take multiple values to return in order (same for 'thenThrow' and 'then' as well)
+ * when(mockedFunc)(3).thenReturn('a', 'b', 'c');
+ * assertThat(mockedFunc(3), equalTo('a'));
+ * assertThat(mockedFunc(3), equalTo('b'));
+ * assertThat(mockedFunc(3), equalTo('c'));
+ * assertThat(mockedFunc(3), equalTo('c'));
+ *
+ * //stubs can also be chained to return values in order
+ * when(mockedFunc)(4).thenReturn('a').thenReturn('b').then(function() { return 'c' });
+ * assertThat(mockedFunc(4), equalTo('a'));
+ * assertThat(mockedFunc(4), equalTo('b'));
+ * assertThat(mockedFunc(4), equalTo('c'));
+ * assertThat(mockedFunc(4), equalTo('c'));
+ *
+ * //stub matching can overlap, allowing for specific cases and defaults
+ * when(mockedFunc)(5).thenReturn('abcde')
+ * when(mockedFunc)(5, lessThan(0)).thenReturn('edcba')
+ * assertThat(mockedFunc(5, -1), equalTo('edcba'))
+ * assertThat(mockedFunc(5, 1), equalTo('abcde'))
+ * assertThat(mockedFunc(5), equalTo('abcde'))
+ *
+ * //can also verify a stubbed invocation, although this is usually redundant
+ * verify(mockedFunc)(0);
+ * 
+ * + *
    + *
  • By default mocks return undefined from all invocations;
  • + *
  • Stubs can be overwritten;
  • + *
  • Once stubbed, the method will always return the stubbed value regardless + * of how many times it is called;
  • + *
  • Last stubbing is more important - when you stubbed the same method with + * the same (or overlapping) matchers many times.
  • + *
+ * + *

3. Matching Arguments

+ * + *

JsMockito verifies arguments using + * JsHamcrest matchers. + * + *

+ * var mockedArray = mock(Array);
+ * var mockedFunc = mockFunction();
+ *
+ * //stubbing using JsHamcrest
+ * when(mockedArray).slice(lessThan(10)).thenReturn('f');
+ * when(mockedFunc)(containsString('world')).thenReturn('foobar');
+ *
+ * //following returns "f"
+ * mockedArray.slice(5);
+ *
+ * //following returns "foobar"
+ * mockedFunc('hello world');
+ *
+ * //you can also use matchers in verification
+ * verify(mockedArray).slice(greaterThan(4));
+ * verify(mockedFunc)(equalTo('hello world'));
+ *
+ * //if not specified then the matcher is anything(), thus either of these
+ * //will match an invocation with a single argument
+ * verify(mockedFunc)();
+ * verify(mockedFunc)(anything());
+ * 
+ * + *
    + *
  • If the argument provided during verification/stubbing is not a + * JsHamcrest matcher, then 'equalTo(arg)' is used instead;
  • + *
  • Where a function/method was invoked with an argument, but the stub or + * verification does not provide a matcher, then anything() is assumed;
  • + *
  • The reverse, however, is not true - the anything() matcher will + * not match an argument that was never provided.
  • + *
+ * + *

4. Verifying exact number of invocations / at least once / + * never

+ * + *
+ * var mockedArray = mock(Array);
+ * var mockedFunc = mockFunction();
+ *
+ * mockedArray.slice(5);
+ * mockedArray.slice(6);
+ * mockedFunc('a');
+ * mockedFunc('b');
+ *
+ * //verification of multiple matching invocations
+ * verify(mockedArray, times(2)).slice(anything());
+ * verify(mockedFunc, times(2))(anything());
+ *
+ * //the default is times(1), making these are equivalent
+ * verify(mockedArray, times(1)).slice(5);
+ * verify(mockedArray).slice(5);
+ * 
+ * + *

5. Matching the context ('this')

+ * + * Functions can be invoked with a specific context, using the 'call' or + * 'apply' methods. JsMockito mock functions (and mock object methods) + * will remember this context and verification/stubbing can match on it. + * + *

For a function:

+ *
+ * var mockedFunc = mockFunction();
+ * var context1 = {};
+ * var context2 = {};
+ *
+ * when(mockedFunc).call(equalTo(context2), anything()).thenReturn('hello');
+ *
+ * mockedFunc.call(context1, 'foo');
+ * //the following returns 'hello'
+ * mockedFunc.apply(context2, [ 'bar' ]);
+ *
+ * verify(mockedFunc).apply(context1, [ 'foo' ]);
+ * verify(mockedFunc).call(context2, 'bar');
+ * 
+ * + *

For object method invocations, the context is usually the object itself. + * But sometimes people do strange things, and you need to test it - so + * the same approach can be used for an object:

+ *
+ * var mockedArray = mock(Array);
+ * var otherContext = {};
+ *
+ * when(mockedArray).slice.call(otherContext, 5).thenReturn('h');
+ *
+ * //the following returns 'h'
+ * mockedArray.slice.apply(otherContext, [ 5 ]);
+ *
+ * verify(mockedArray).slice.call(equalTo(otherContext), 5);
+ * 
+ * + *
    + *
  • For mock functions, the default context matcher is anything();
  • + *
  • For mock object methods, the default context matcher is + * sameAs(mockObj).
  • + *
+ * + *

6. Making sure interactions never happened on a mock

+ * + *
+ * var mockOne = mock(Array);
+ * var mockTwo = mock(Array);
+ * var mockThree = mockFunction();
+ *
+ * //only mockOne is interacted with
+ * mockOne.push(5);
+ *
+ * //verify a method was never called
+ * verify(mockOne, never()).unshift('a');
+ *
+ * //verify that other mocks were not interacted with
+ * verifyZeroInteractions(mockTwo, mockThree);
+ * 
+ * + *

7. Finding redundant invocations

+ * + *
+ * var mockArray = mock(Array);
+ *
+ * mockArray.push(5);
+ * mockArray.push(8);
+ *
+ * verify(mockArray).push(5);
+ *
+ * // following verification will fail
+ * verifyNoMoreInteractions(mockArray);
+ * 
+ */ +declare module JsMockito { + + /** + * Library version. + */ + export var version: string; + + /** + * Builder for a textual description. + */ + export class JsMockitoStubBuilder { + + /** + * Provide functions to be run in place of the mocked method. + * + * @param func Functions to be run in order of execution. + * @return {JsMockitoStubBuilder} Itself for method chaining + */ + then(...func: ((obj: any) => any)[]): JsMockitoStubBuilder; + + /** + * Provide values to be returned by the mocked function. + * + * @param obj Values to be returned in order of execution. + * @return {JsMockitoStubBuilder} Itself for method chaining + */ + thenReturn(...obj: any[]): JsMockitoStubBuilder; + + /** + * Provide exceptions to be thrown by the mocked function. + * + * @param obj Exceptions to be thrown in order of execution. + * @return {JsMockitoStubBuilder} Itself for method chaining + */ + thenThrow(...obj: Error[]): JsMockitoStubBuilder; + } + + /** + * Used to verify how many times a function of method is called. + */ + export interface Verifier { + } + + /** + * Test if a given variable is a mock + * + * @param maybeMock An object + * @return {boolean} true if the variable is a mock + */ + export function isMock(maybeMock: any): boolean; + + /** + * Add a stub for a mock object method or mock function + * + * @param mock A mock object or mock anonymous function + * @return {T} A stub builder on which the method or function to be stubbed can be invoked + */ + export function when(mock: T): T; + + /** + * Verify that a mock object method or mock function was invoked + * + * @param mock A mock object or mock anonymous function + * @param verifier Optional JsMockito.Verifier instance (default: JsMockito.Verifiers.once()) + * @return {T} A verifier on which the method or function to be verified can be invoked + */ + export function verify(mock: T, verifier: Verifier): T; + + /** + * Verify that no mock object methods or the mock function were ever invoked + * + * @param mock A mock object or mock anonymous function (multiple accepted) + */ + export function verifyZeroInteractions(...mock: any[]): void; + + /** + * Verify that no mock object method or mock function invocations remain + * unverified + * + * @param mock A mock object or mock anonymous function (multiple accepted) + */ + export function verifyNoMoreInteractions(...mock: any[]): void; + + /** + * Create a mock that proxies a real function or object. All un-stubbed + * invocations will be passed through to the real implementation, but can + * still be verified. + * + * @param delegate A 'real' (concrete) object or function that the mock will delegate unstubbed invocations to + * @return {T} A mock object (as per mock) or mock function (as per mockFunction) + */ + export function spy(delegate: T): T; + + /** + * Create a mockable and stubbable anonymous function. + * + *

Once created, the function can be invoked and will return undefined for + * any interactions that do not match stub declarations.

+ * + *
+     * var mockFunc = JsMockito.mockFunction();
+     * JsMockito.when(mockFunc).call(anything(), 1, 5).thenReturn(6);
+     * mockFunc(1, 5); // result is 6
+     * JsMockito.verify(mockFunc)(1, greaterThan(2));
+     * 
+ * + * @param funcName The name of the mock function to use in messages (defaults to 'func') + * @param delegate The function to delegate unstubbed calls to (optional) + * @return {T} an anonymous function + */ + export function mockFunction(): Function; + export function mockFunction(funcName: string): Function; + export function mockFunction(funcName: string, delegate: Function): Function; + + /** + * Create a mockable and stubbable objects. + * + *

A mock is created with the constructor for an object as an argument. + * Once created, the mock object will have all the same methods as the source + * object which, when invoked, will return undefined by default.

+ * + *

Stub declarations may then be made for these methods to have them return + * useful values or perform actions when invoked.

+ * + *
+     * MyObject = function() {
+     *   this.add = function(a, b) { return a + b }
+     * };
+     *
+     * var mockObj = JsMockito.mock(MyObject);
+     * mockObj.add(5, 4); // result is undefined
+     *
+     * JsMockito.when(mockFunc).add(1, 2).thenReturn(6);
+     * mockObj.add(1, 2); // result is 6
+     *
+     * JsMockito.verify(mockObj).add(1, greaterThan(2)); // ok
+     * JsMockito.verify(mockObj).add(1, equalTo(2)); // ok
+     * JsMockito.verify(mockObj).add(1, 4); // will throw an exception
+     * 
+ * + * @param Obj {function} the constructor for the object to be mocked + * @return {object} a mock object + */ + export function mock(Obj: { new(): T ;}): T; + + module Verifiers { + + /** + * Test that a invocation never occurred. For example: + *
+         * verify(mock, never()).method();
+         * 
+ * @see JsMockito.Verifiers.times(0) + */ + export function never(): Verifier; + + /** Test that no interaction were made on the mock. For example: + *
+         * verify(mock, zeroInteractions());
+         * 
+ * @see JsMockito.verifyZeroInteractions() + */ + export function zeroInteractions(): Verifier; + + /** Test that no further interactions remain unverified on the mock. For + * example: + *
+         * verify(mock, noMoreInteractions());
+         * 
+ * @see JsMockito.verifyNoMoreInteractions() + */ + export function noMoreInteractions(): Verifier; + + /** + * Test that an invocation occurred a specific number of times. For example: + *
+         * verify(mock, times(2)).method();
+         * 
+ * + * @param wanted The number of desired invocations + */ + export function times(wanted: number): Verifier; + + /** + * Test that an invocation occurred exactly once. For example: + *
+         * verify(mock, once()).method();
+         * 
+ * This is the default verifier. + * @see JsMockito.Verifiers.times(1) + */ + export function once(): Verifier; + } + + module Integration { + + /** + * Import the public JsMockito API into the specified object (namespace) + * + * @param {object} target An object (namespace) that will be populated with + * the functions from the public JsMockito API + */ + export function importTo(target: any): void; + + /** + * Make the public JsMockito API available in Screw.Unit + * @see JsMockito.Integration.importTo(Screw.Matchers) + */ + export function screwunit(): void; + + /** + * Make the public JsMockito API available to JsTestDriver + * @see JsMockito.Integration.importTo(window) + */ + export function JsTestDriver(): void; + + /** + * Make the public JsMockito API available to JsUnitTest + * @see JsMockito.Integration.importTo(JsUnitTest.Unit.Testcase.prototype) + */ + export function JsUnitTest(): void; + + /** + * Make the public JsMockito API available to YUITest + * @see JsMockito.Integration.importTo(window) + */ + export function YUITest(): void; + + /** + * Make the public JsMockito API available to QUnit + * @see JsMockito.Integration.importTo(window) + */ + export function QUnit(): void; + + /** + * Make the public JsMockito API available to jsUnity + * @see JsMockito.Integration.importTo(jsUnity.env.defaultScope) + */ + export function jsUnity(): void; + + /** + * Make the public JsMockito API available to jSpec + * @see JsMockito.Integration.importTo(jSpec.defaultContext) + */ + export function jSpec(): void; + } +} + +// +// Functions that are copied by JsMockito.Integration.importTo() to the global scope are repeated here. +// + +/** + * Test if a given variable is a mock + * + * @param maybeMock An object + * @return {boolean} true if the variable is a mock + */ +declare function isMock(maybeMock: any): boolean; + +/** + * Add a stub for a mock object method or mock function + * + * @param mock A mock object or mock anonymous function + * @return {T} A stub builder on which the method or function to be stubbed can be invoked + */ +declare function when(mock: T): T; + +/** + * Verify that a mock object method or mock function was invoked + * + * @param mock A mock object or mock anonymous function + * @param verifier Optional JsMockito.Verifier instance (default: JsMockito.Verifiers.once()) + * @return {T} A verifier on which the method or function to be verified can be invoked + */ +declare function verify(mock: T, verifier: JsMockito.Verifier): T; + +/** + * Verify that no mock object methods or the mock function were ever invoked + * + * @param mock A mock object or mock anonymous function (multiple accepted) + */ +declare function verifyZeroInteractions(...mock: any[]): void; + +/** + * Verify that no mock object method or mock function invocations remain + * unverified + * + * @param mock A mock object or mock anonymous function (multiple accepted) + */ +declare function verifyNoMoreInteractions(...mock: any[]): void; + +/** + * Create a mock that proxies a real function or object. All un-stubbed + * invocations will be passed through to the real implementation, but can + * still be verified. + * + * @param delegate A 'real' (concrete) object or function that the mock will delegate unstubbed invocations to + * @return {T} A mock object (as per mock) or mock function (as per mockFunction) + */ +declare function spy(delegate: T): T; + +/** + * Create a mockable and stubbable anonymous function. + * + *

Once created, the function can be invoked and will return undefined for + * any interactions that do not match stub declarations.

+ * + *
+ * var mockFunc = JsMockito.mockFunction();
+ * JsMockito.when(mockFunc).call(anything(), 1, 5).thenReturn(6);
+ * mockFunc(1, 5); // result is 6
+ * JsMockito.verify(mockFunc)(1, greaterThan(2));
+ * 
+ * + * @param funcName The name of the mock function to use in messages (defaults to 'func') + * @param delegate The function to delegate unstubbed calls to (optional) + * @return {T} an anonymous function + */ +declare function mockFunction(): Function; +declare function mockFunction(funcName: string): Function; +declare function mockFunction(funcName: string, delegate: Function): Function; + +/** + * Create a mockable and stubbable objects. + * + *

A mock is created with the constructor for an object as an argument. + * Once created, the mock object will have all the same methods as the source + * object which, when invoked, will return undefined by default.

+ * + *

Stub declarations may then be made for these methods to have them return + * useful values or perform actions when invoked.

+ * + *
+ * MyObject = function() {
+     *   this.add = function(a, b) { return a + b }
+     * };
+ *
+ * var mockObj = JsMockito.mock(MyObject);
+ * mockObj.add(5, 4); // result is undefined
+ *
+ * JsMockito.when(mockFunc).add(1, 2).thenReturn(6);
+ * mockObj.add(1, 2); // result is 6
+ *
+ * JsMockito.verify(mockObj).add(1, greaterThan(2)); // ok
+ * JsMockito.verify(mockObj).add(1, equalTo(2)); // ok
+ * JsMockito.verify(mockObj).add(1, 4); // will throw an exception
+ * 
+ * + * @param Obj {function} the constructor for the object to be mocked + * @return {object} a mock object + */ +declare function mock(Obj: { new(): T ;}): T; + +/** + * Test that a invocation never occurred. For example: + *
+ * verify(mock, never()).method();
+ * 
+ * @see JsMockito.Verifiers.times(0) + */ +declare function never(): JsMockito.Verifier; + +/** Test that no interaction were made on the mock. For example: + *
+ * verify(mock, zeroInteractions());
+ * 
+ * @see JsMockito.verifyZeroInteractions() + */ +declare function zeroInteractions(): JsMockito.Verifier; + +/** Test that no further interactions remain unverified on the mock. For + * example: + *
+ * verify(mock, noMoreInteractions());
+ * 
+ * @see JsMockito.verifyNoMoreInteractions() + */ +declare function noMoreInteractions(): JsMockito.Verifier; + +/** + * Test that an invocation occurred a specific number of times. For example: + *
+ * verify(mock, times(2)).method();
+ * 
+ * + * @param wanted The number of desired invocations + */ +declare function times(wanted: number): JsMockito.Verifier; + +/** + * Test that an invocation occurred exactly once. For example: + *
+ * verify(mock, once()).method();
+ * 
+ * This is the default verifier. + * @see JsMockito.Verifiers.times(1) + */ +declare function once(): JsMockito.Verifier; From 6bfb511a610e56980b27a0c02f5a9d6823066472 Mon Sep 17 00:00:00 2001 From: Ingvar Stepanyan Date: Sun, 14 Feb 2016 00:04:48 +0000 Subject: [PATCH 031/105] Fix chrome.events.Event refs to use strict version --- chrome/chrome.d.ts | 1039 +++++++------------------------------------- 1 file changed, 146 insertions(+), 893 deletions(-) diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts index 70c897421..b1e3acb27 100755 --- a/chrome/chrome.d.ts +++ b/chrome/chrome.d.ts @@ -135,13 +135,7 @@ declare module chrome.alarms { name: string; } - interface AlarmEvent extends chrome.events.Event { - /** - * The callback parameter should be a function that looks like this: - * function( Alarm alarm) {...}; - */ - addListener(callback: (alarm: Alarm) => void): void; - } + interface AlarmEvent extends chrome.events.Event<(alarm: Alarm) => void> {} /** * Creates an alarm. Near the time(s) specified by alarmInfo, the onAlarm event is fired. If there is another alarm with the same name (or no name if none is specified), it will be cancelled and replaced by this alarm. @@ -286,61 +280,19 @@ declare module chrome.bookmarks { childIds: string[]; } - interface BookmarkRemovedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string id, object removeInfo) {...}; - */ - addListener(callback: (id: string, removeInfo: BookmarkRemoveInfo) => void): void; - } + interface BookmarkRemovedEvent extends chrome.events.Event<(id: string, removeInfo: BookmarkRemoveInfo) => void> {} - interface BookmarkImportEndedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function() {...}; - */ - addListener(callback: () => void): void; - } + interface BookmarkImportEndedEvent extends chrome.events.Event<() => void> {} - interface BookmarkMovedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string id, object moveInfo) {...}; - */ - addListener(callback: (id: string, moveInfo: BookmarkMoveInfo) => void): void; - } + interface BookmarkMovedEvent extends chrome.events.Event<(id: string, moveInfo: BookmarkMoveInfo) => void> {} - interface BookmarkImportBeganEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function() {...}; - */ - addListener(callback: () => void): void; - } + interface BookmarkImportBeganEvent extends chrome.events.Event<() => void> {} - interface BookmarkChangedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string id, object changeInfo) {...}; - */ - addListener(callback: (id: string, changeInfo: BookmarkChangeInfo) => void): void; - } + interface BookmarkChangedEvent extends chrome.events.Event<(id: string, changeInfo: BookmarkChangeInfo) => void> {} - interface BookmarkCreatedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string id, BookmarkTreeNode bookmark) {...}; - */ - addListener(callback: (id: string, bookmark: BookmarkTreeNode) => void): void; - } + interface BookmarkCreatedEvent extends chrome.events.Event<(id: string, bookmark: BookmarkTreeNode) => void> {} - interface BookmarkChildrenReordered extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string id, object reorderInfo) {...}; - */ - addListener(callback: (id: string, reorderInfo: BookmarkReorderInfo) => void): void; - } + interface BookmarkChildrenReordered extends chrome.events.Event<(id: string, reorderInfo: BookmarkReorderInfo) => void> {} interface BookmarkSearchQuery { query?: string; @@ -524,13 +476,7 @@ declare module chrome.browserAction { popup: string; } - interface BrowserClickedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( tabs.Tab tab) {...}; - */ - addListener(callback: (tab: chrome.tabs.Tab) => void): void; - } + interface BrowserClickedEvent extends chrome.events.Event<(tab: chrome.tabs.Tab) => void> {} /** * Since Chrome 22. @@ -787,13 +733,7 @@ declare module chrome.commands { shortcut?: string; } - interface CommandEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string command) {...}; - */ - addListener(callback: (command: string) => void): void; - } + interface CommandEvent extends chrome.events.Event<(command: string) => void> {} /** * Returns all the registered extension commands for this extension and their shortcut (if active). @@ -1118,15 +1058,7 @@ declare module chrome.contextMenus { type?: string; } - interface MenuClickedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object info, tabs.Tab tab) {...}; - * Parameter info: Information sent when a context menu item is clicked. - * Parameter tab: The details of the tab where the click took place. If the click did not take place in a tab, this parameter will be missing. - */ - addListener(callback: (info: OnClickData, tab?: chrome.tabs.Tab) => void): void; - } + interface MenuClickedEvent extends chrome.events.Event<(info: OnClickData, tab?: chrome.tabs.Tab) => void> {} /** * Since Chrome 38. @@ -1287,13 +1219,7 @@ declare module chrome.cookies { cause: string; } - interface CookieChangedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object changeInfo) {...}; - */ - addListener(callback: (changeInfo: CookieChangeInfo) => void): void; - } + interface CookieChangedEvent extends chrome.events.Event<(changeInfo: CookieChangeInfo) => void> {} /** * Lists all existing cookie stores. @@ -1396,26 +1322,9 @@ declare module "chrome.debugger" { faviconUrl?: string; } - interface DebuggerDetachedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( Debuggee source, DetachReason reason) {...}; - * Parameter source: The debuggee that was detached. - * Parameter reason: Since Chrome 24. Connection termination reason. - */ - addListener(callback: (source: Debuggee, reason: string) => void): void; - } + interface DebuggerDetachedEvent extends chrome.events.Event<(source: Debuggee, reason: string) => void> {} - interface DebuggerEventEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( Debuggee source, string method, object params) {...}; - * Parameter source: The debuggee that generated this event. - * Parameter method: Method name. Should be one of the notifications defined by the remote debugging protocol. - * Parameter params: JSON object with the parameters. Structure of the parameters varies depending on the method name and is defined by the 'parameters' attribute of the event description in the remote debugging protocol. - */ - addListener(callback: (source: Debuggee, method: string, params?: Object) => void): void; - } + interface DebuggerEventEvent extends chrome.events.Event<(source: Debuggee, method: string, params?: Object) => void> {} /** * Attaches debugger to the given target. @@ -1631,9 +1540,7 @@ declare module chrome.declarativeWebRequest { filter: RequestCookie; } - interface RequestedEvent extends chrome.events.Event { - addListener(callback: Function): void; - } + interface RequestedEvent extends chrome.events.Event {} var onRequest: RequestedEvent; } @@ -1734,22 +1641,9 @@ declare module chrome.devtools.inspectedWindow { value: string; } - interface ResourceAddedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( Resource resource) {...}; - */ - addListener(callback: (resource: Resource) => void): void; - } + interface ResourceAddedEvent extends chrome.events.Event<(resource: Resource) => void> {} - interface ResourceContentCommittedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( Resource resource, string content) {...}; - * Parameter content: New content of the resource. - */ - addListener(callback: (resource: Resource, content: string) => void): void; - } + interface ResourceContentCommittedEvent extends chrome.events.Event<(resource: Resource, content: string) => void> {} /** The ID of the tab being inspected. This ID may be used with chrome.tabs.* API. */ var tabId: number; @@ -1801,23 +1695,9 @@ declare module chrome.devtools.network { getContent(callback: (content: string, encoding: string) => void): void; } - interface RequestFinishedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( Request request) {...}; - * Parameter request: Description of a network request in the form of a HAR entry. See HAR specification for details. - */ - addListener(callback: (request: Request) => void): void; - } + interface RequestFinishedEvent extends chrome.events.Event<(request: Request) => void> {} - interface NavigatedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string url) {...}; - * Parameter url: URL of the new page. - */ - addListener(callback: (url: string) => void): void; - } + interface NavigatedEvent extends chrome.events.Event<(url: string) => void> {} /** * Returns HAR log that contains all known network requests. @@ -1842,32 +1722,11 @@ declare module chrome.devtools.network { * Availability: Since Chrome 18. */ declare module chrome.devtools.panels { - interface PanelShownEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(global window) {...}; - * Parameter window: The JavaScript window object of panel's page. - */ - addListener(callback: (window: chrome.windows.Window) => void): void; - } + interface PanelShownEvent extends chrome.events.Event<(window: chrome.windows.Window) => void> {} - interface PanelHiddenEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function() {...}; - */ - addListener(callback: () => void): void; - } + interface PanelHiddenEvent extends chrome.events.Event<() => void> {} - interface PanelSearchEvent extends chrome.events.Event { - /** - * The callback parameter should be a function that looks like this: - * function(string action, string queryString) {...}; - * Parameter action: Type of search action being performed. - * Optional parameter queryString: Query string (only for 'performSearch'). - */ - addListener(callback: (action: string, queryString?: string) => void): void; - } + interface PanelSearchEvent extends chrome.events.Event<(action: string, queryString?: string) => void> {} /** Represents a panel created by extension. */ interface ExtensionPanel { @@ -1886,13 +1745,7 @@ declare module chrome.devtools.panels { onSearch: PanelSearchEvent; } - interface ButtonClickedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function() {...}; - */ - addListener(callback: () => void): void; - } + interface ButtonClickedEvent extends chrome.events.Event<() => void> {} /** A button created by the extension. */ interface Button { @@ -1907,13 +1760,7 @@ declare module chrome.devtools.panels { onClicked: ButtonClickedEvent; } - interface SelectionChangedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function() {...}; - */ - addListener(callback: () => void): void; - } + interface SelectionChangedEvent extends chrome.events.Event<() => void> {} /** Represents the Elements panel. */ interface ElementsPanel { @@ -1948,22 +1795,9 @@ declare module chrome.devtools.panels { onSelectionChanged: SelectionChangedEvent; } - interface ExtensionSidebarPaneShownEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(global window) {...}; - * Parameter window: The JavaScript window object of the sidebar page, if one was set with the setPage() method. - */ - addListener(callback: (window: chrome.windows.Window) => void): void; - } + interface ExtensionSidebarPaneShownEvent extends chrome.events.Event<(window: chrome.windows.Window) => void> {} - interface ExtensionSidebarPaneHiddenEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function() {...}; - */ - addListener(callback: () => void): void; - } + interface ExtensionSidebarPaneHiddenEvent extends chrome.events.Event<() => void> {} /** A sidebar created by the extension. */ interface ExtensionSidebarPane { @@ -2279,39 +2113,13 @@ declare module chrome.downloads { conflictAction?: string; } - interface DownloadChangedEvent extends chrome.events.Event { - /** - * When any of a DownloadItem's properties except bytesReceived and estimatedEndTime changes, this event fires with the downloadId and an object containing the properties that changed. - * @param callback The callback parameter should be a function that looks like this: - * function(object downloadDelta) {...}; - */ - addListener(callback: (downloadDelta: DownloadDelta) => void): void; - } + interface DownloadChangedEvent extends chrome.events.Event<(downloadDelta: DownloadDelta) => void> {} - interface DownloadCreatedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( DownloadItem downloadItem) {...}; - */ - addListener(callback: (downloadItem: DownloadItem) => void): void; - } + interface DownloadCreatedEvent extends chrome.events.Event<(downloadItem: DownloadItem) => void> {} - interface DownloadErasedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(integer downloadId) {...}; - * Parameter downloadId: The id of the DownloadItem that was erased. - */ - addListener(callback: (downloadId: number) => void): void; - } + interface DownloadErasedEvent extends chrome.events.Event<(downloadId: number) => void> {} - interface DownloadDeterminingFilenameEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( DownloadItem downloadItem, function suggest) {...}; - */ - addListener(callback: (downloadItem: DownloadItem, suggest: (suggestion?: DownloadFilenameSuggestion) => void) => void): void; - } + interface DownloadDeterminingFilenameEvent extends chrome.events.Event<(downloadItem: DownloadItem, suggest: (suggestion?: DownloadFilenameSuggestion) => void) => void> {} /** * Find DownloadItem. Set query to the empty object to get all DownloadItem. To get a specific DownloadItem, set only the id field. To page through a large number of items, set orderBy: ['-startTime'], set limit to the number of items per page, and set startedAfter to the startTime of the last item from the last page. @@ -2639,21 +2447,7 @@ declare module chrome.extension { message: string; } - interface OnRequestEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(any request, runtime.MessageSender sender, function sendResponse) {...}; - * Parameter request: The request sent by the calling script. - * Parameter sendResponse: Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object, or undefined if there is no response. If you have more than one onRequest listener in the same document, then only one may send a response. - */ - addListener(callback: (request: any, sender: runtime.MessageSender, sendResponse: (response: any) => void) => void): void; - /** - * @param callback The callback parameter should be a function that looks like this: - * function(runtime.MessageSender sender, function sendResponse) {...}; - * Parameter sendResponse: Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object, or undefined if there is no response. If you have more than one onRequest listener in the same document, then only one may send a response. - */ - addListener(callback: (sender: runtime.MessageSender, sendResponse: (response: any) => void) => void): void; - } + interface OnRequestEvent extends chrome.events.Event<((request: any, sender: runtime.MessageSender, sendResponse: (response: any) => void) => void) | ((sender: runtime.MessageSender, sendResponse: (response: any) => void) => void)> {} /** * Since Chrome 7. @@ -2764,15 +2558,7 @@ declare module chrome.fileBrowserHandler { entries: any[]; } - interface FileBrowserHandlerExecuteEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string id, FileHandlerExecuteEventDetails details) {...}; - * Parameter id: File browser action id as specified in the listener component's manifest. - * Parameter details: File handler execute event details. - */ - addListener(callback: (id: string, details: FileHandlerExecuteEventDetails) => void): void; - } + interface FileBrowserHandlerExecuteEvent extends chrome.events.Event<(id: string, details: FileHandlerExecuteEventDetails) => void> {} /** * Prompts user to select file path under which file should be saved. When the file is selected, file access permission required to use the file (read, write and create) are granted to the caller. The file will not actually get created during the function call, so function caller must ensure its existence before using it. The function has to be invoked with a user gesture. @@ -3018,117 +2804,33 @@ declare module chrome.fileSystemProvider { operationRequestId: number; } - interface RequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: RequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void): void; - } + interface RequestedEvent extends chrome.events.Event<(options: RequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - interface MetadataRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: MetadataRequestedEventOptions, successCallback: (metadata: EntryMetadata) => void, errorCallback: (error: string) => void) => void): void; - } + interface MetadataRequestedEvent extends chrome.events.Event<(options: MetadataRequestedEventOptions, successCallback: (metadata: EntryMetadata) => void, errorCallback: (error: string) => void) => void> {} - interface DirectoryPathRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: DirectoryPathRequestedEventOptions, successCallback: (entries: EntryMetadata[], hasMore: boolean) => void, errorCallback: (error: string) => void) => void): void; - } + interface DirectoryPathRequestedEvent extends chrome.events.Event<(options: DirectoryPathRequestedEventOptions, successCallback: (entries: EntryMetadata[], hasMore: boolean) => void, errorCallback: (error: string) => void) => void> {} - interface OpenFileRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: OpenFileRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void): void; - } + interface OpenFileRequestedEvent extends chrome.events.Event<(options: OpenFileRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - interface OpenedFileRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: OpenedFileRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void): void; - } + interface OpenedFileRequestedEvent extends chrome.events.Event<(options: OpenedFileRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - interface OpenedFileOffsetRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: OpenedFileOffsetRequestedEventOptions, successCallback: (data: ArrayBuffer, hasMore: boolean) => void, errorCallback: (error: string) => void) => void): void; - } + interface OpenedFileOffsetRequestedEvent extends chrome.events.Event<(options: OpenedFileOffsetRequestedEventOptions, successCallback: (data: ArrayBuffer, hasMore: boolean) => void, errorCallback: (error: string) => void) => void> {} - interface DirectoryPathRecursiveRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: DirectoryPathRecursiveRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void): void; - } + interface DirectoryPathRecursiveRequestedEvent extends chrome.events.Event<(options: DirectoryPathRecursiveRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - interface EntryPathRecursiveRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: EntryPathRecursiveRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void): void; - } + interface EntryPathRecursiveRequestedEvent extends chrome.events.Event<(options: EntryPathRecursiveRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - interface FilePathRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: FilePathRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void): void; - } + interface FilePathRequestedEvent extends chrome.events.Event<(options: FilePathRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - interface SourceTargetPathRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: SourceTargetPathRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void): void; - } + interface SourceTargetPathRequestedEvent extends chrome.events.Event<(options: SourceTargetPathRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - interface FilePathLengthRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: FilePathLengthRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void): void; - } + interface FilePathLengthRequestedEvent extends chrome.events.Event<(options: FilePathLengthRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - interface OpenedFileIoRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: OpenedFileIoRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void): void; - } + interface OpenedFileIoRequestedEvent extends chrome.events.Event<(options: OpenedFileIoRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - interface OperationRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: OperationRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void): void; - } + interface OperationRequestedEvent extends chrome.events.Event<(options: OperationRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - interface OptionlessRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(function successCallback, function errorCallback) {...}; - */ - addListener(callback: (successCallback: Function, errorCallback: (error: string) => void) => void): void; - } + interface OptionlessRequestedEvent extends chrome.events.Event<(successCallback: Function, errorCallback: (error: string) => void) => void> {} /** * Mounts a file system with the given fileSystemId and displayName. displayName will be shown in the left panel of Files.app. displayName can contain any characters including '/', but cannot be an empty string. displayName must be descriptive but doesn't have to be unique. The fileSystemId must not be an empty string. @@ -3289,37 +2991,13 @@ declare module chrome.fontSettings { fontId: string; } - interface DefaultFixedFontSizeChangedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object details) {...}; - */ - addListener(callback: (details: FontSizeDetails) => void): void; - } + interface DefaultFixedFontSizeChangedEvent extends chrome.events.Event<(details: FontSizeDetails) => void> {} - interface DefaultFontSizeChangedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object details) {...}; - */ - addListener(callback: (details: FontSizeDetails) => void): void; - } + interface DefaultFontSizeChangedEvent extends chrome.events.Event<(details: FontSizeDetails) => void> {} - interface MinimumFontSizeChangedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object details) {...}; - */ - addListener(callback: (details: FontSizeDetails) => void): void; - } + interface MinimumFontSizeChangedEvent extends chrome.events.Event<(details: FontSizeDetails) => void> {} - interface FontChangedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object details) {...}; - */ - addListener(callback: (details: FullFontDetails) => void): void; - } + interface FontChangedEvent extends chrome.events.Event<(details: FullFontDetails) => void> {} /** * Sets the default font size. @@ -3461,31 +3139,11 @@ declare module chrome.gcm { detail: Object; } - interface MessageReceptionEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object message) {...}; - * Parameter message: A message received from another party via GCM. - */ - addListener(callback: (message: IncomingMessage) => void): void; - } + interface MessageReceptionEvent extends chrome.events.Event<(message: IncomingMessage) => void> {} - interface MessageDeletionEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function() {...}; - */ - addListener(callback: () => void): void; - } + interface MessageDeletionEvent extends chrome.events.Event<() => void> {} - interface GcmErrorEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object error) {...}; - * Parameter error: An error that occured while trying to send the message either in Chrome or on the GCM server. Application can retry sending the message with a reasonable backoff and possibly longer time-to-live. - */ - addListener(callback: (error: GcmError) => void): void; - } + interface GcmErrorEvent extends chrome.events.Event<(error: GcmError) => void> {} /** The maximum size (in bytes) of all key/value pairs in a message. */ var MAX_MESSAGE_SIZE: number; @@ -3593,21 +3251,9 @@ declare module chrome.history { urls?: string[]; } - interface HistoryVisitedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( HistoryItem result) {...}; - */ - addListener(callback: (result: HistoryItem) => void): void; - } + interface HistoryVisitedEvent extends chrome.events.Event<(result: HistoryItem) => void> {} - interface HistoryVisitRemovedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object removed) {...}; - */ - addListener(callback: (removed: RemovedResult) => void): void; - } + interface HistoryVisitRemovedEvent extends chrome.events.Event<(removed: RemovedResult) => void> {} /** * Searches the history for the last visit time of each page matching the query. @@ -3741,13 +3387,7 @@ declare module chrome.identity { interactive?: boolean; } - interface SignInChangeEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( AccountInfo account, boolean signedIn) {...}; - */ - addListener(callback: (account: AccountInfo, signedIn: boolean) => void): void; - } + interface SignInChangeEvent extends chrome.events.Event<(account: AccountInfo, signedIn: boolean) => void> {} /** * Retrieves a list of AccountInfo objects describing the accounts present on the profile. @@ -3814,13 +3454,7 @@ declare module chrome.identity { * @since Chrome 6. */ declare module chrome.idle { - interface IdleStateChangedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( IdleState newState) {...}; - */ - addListener(callback: (newState: string) => void): void; - } + interface IdleStateChangedEvent extends chrome.events.Event<(newState: string) => void> {} /** * Returns "locked" if the system is locked, "idle" if the user has not generated any input for a specified number of seconds, or "active" otherwise. @@ -4109,101 +3743,25 @@ declare module chrome.input.ime { anchor: number; } - interface BlurEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(integer contextID) {...}; - * Parameter contextID: The ID of the text field that has lost focus. The ID is invalid after this call - */ - addListener(callback: (contextID: number) => void): void; - } + interface BlurEvent extends chrome.events.Event<(contextID: number) => void> {} - interface CandidateClickedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string engineID, integer candidateID, MouseButton button) {...}; - * Parameter engineID: ID of the engine receiving the event - * Parameter candidateID: ID of the candidate that was clicked. - * Parameter button: Which mouse buttons was clicked. - */ - addListener(callback: (engineID: string, candidateID: number, button: string) => void): void; - } + interface CandidateClickedEvent extends chrome.events.Event<(engineID: string, candidateID: number, button: string) => void> {} - interface KeyEventEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string engineID, KeyboardEvent keyData) {...}; - * Parameter engineID: ID of the engine receiving the event - * Parameter keyData: Data on the key event - */ - addListener(callback: (engineID: string, keyData: KeyboardEvent) => void): void; - } + interface KeyEventEvent extends chrome.events.Event<(engineID: string, keyData: KeyboardEvent) => void> {} - interface DeactivatedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string engineID) {...}; - * Parameter engineID: ID of the engine receiving the event - */ - addListener(callback: (engineID: string) => void): void; - } + interface DeactivatedEvent extends chrome.events.Event<(engineID: string) => void> {} - interface InputContextUpdateEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( InputContext context) {...}; - * Parameter context: An InputContext object describing the text field that has changed. - */ - addListener(callback: (context: InputContext) => void): void; - } + interface InputContextUpdateEvent extends chrome.events.Event<(context: InputContext) => void> {} - interface ActivateEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string engineID, ScreenType screen) {...}; - * Parameter engineID: ID of the engine receiving the event - * Parameter The screen type under which the IME is activated. - */ - addListener(callback: (engineID: string, screen: string) => void): void; - } + interface ActivateEvent extends chrome.events.Event<(engineID: string, screen: string) => void> {} - interface FocusEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( InputContext context) {...}; - * Parameter context: Describes the text field that has acquired focus. - */ - addListener(callback: (context: InputContext) => void): void; - } + interface FocusEvent extends chrome.events.Event<(context: InputContext) => void> {} - interface MenuItemActivatedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string engineID, string name) {...}; - * Parameter engineID: ID of the engine receiving the event - * Parameter name: Name of the MenuItem which was activated - */ - addListener(callback: (engineID: string, name: string) => void): void; - } + interface MenuItemActivatedEvent extends chrome.events.Event<(engineID: string, name: string) => void> {} - interface SurroundingTextChangedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string engineID, object surroundingInfo) {...}; - * Parameter engineID: ID of the engine receiving the event - * Parameter surroundingInfo: The surrounding information. - */ - addListener(callback: (engineID: string, surroundingInfo: SurroundingTextInfo) => void): void; - } + interface SurroundingTextChangedEvent extends chrome.events.Event<(engineID: string, surroundingInfo: SurroundingTextInfo) => void> {} - interface InputResetEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string engineID) {...}; - * Parameter engineID: ID of the engine receiving the event - */ - addListener(callback: (engineID: string) => void): void; - } + interface InputResetEvent extends chrome.events.Event<(engineID: string) => void> {} /** * Adds the provided menu items to the language menu when this IME is active. @@ -4435,38 +3993,13 @@ declare module chrome.management { showConfirmDialog?: boolean; } - interface ManagementDisabledEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( ExtensionInfo info) {...}; - */ - addListener(callback: (info: ExtensionInfo) => void): void; - } + interface ManagementDisabledEvent extends chrome.events.Event<(info: ExtensionInfo) => void> {} - interface ManagementUninstalledEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string id) {...}; - * Parameter id: The id of the extension, app, or theme that was uninstalled. - */ - addListener(callback: (id: string) => void): void; - } + interface ManagementUninstalledEvent extends chrome.events.Event<(id: string) => void> {} - interface ManagementInstalledEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( ExtensionInfo info) {...}; - */ - addListener(callback: (info: ExtensionInfo) => void): void; - } + interface ManagementInstalledEvent extends chrome.events.Event<(info: ExtensionInfo) => void> {} - interface ManagementEnabledEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( ExtensionInfo info) {...}; - */ - addListener(callback: (info: ExtensionInfo) => void): void; - } + interface ManagementEnabledEvent extends chrome.events.Event<(info: ExtensionInfo) => void> {} /** * Enables or disables an app or extension. @@ -4613,14 +4146,7 @@ declare module chrome.networking.config { Security?: string; } - interface CaptivePorttalDetectedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( NetworkInfo networkInfo) {...}; - * Parameter networkInfo: Information about the network on which a captive portal was detected. - */ - addListener(callback: (networkInfo: NetworkInfo) => void): void; - } + interface CaptivePorttalDetectedEvent extends chrome.events.Event<(networkInfo: NetworkInfo) => void> {} /** * Allows an extension to define network filters for the networks it can handle. A call to this function will remove all filters previously installed by the extension before setting the new list. @@ -4719,45 +4245,15 @@ declare module chrome.notifications { imageUrl?: string; } - interface NotificationClosedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string notificationId, boolean byUser) {...}; - */ - addListener(callback: (notificationId: string, byUser: boolean) => void): void; - } + interface NotificationClosedEvent extends chrome.events.Event<(notificationId: string, byUser: boolean) => void> {} - interface NotificationClickedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string notificationId) {...}; - */ - addListener(callback: (notificationId: string) => void): void; - } + interface NotificationClickedEvent extends chrome.events.Event<(notificationId: string) => void> {} - interface NotificationButtonClickedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string notificationId, integer buttonIndex) {...}; - */ - addListener(callback: (notificationId: string, buttonIndex: number) => void): void; - } + interface NotificationButtonClickedEvent extends chrome.events.Event<(notificationId: string, buttonIndex: number) => void> {} - interface NotificationPermissionLevelChangedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( PermissionLevel level) {...}; - */ - addListener(callback: (level: string) => void): void; - } + interface NotificationPermissionLevelChangedEvent extends chrome.events.Event<(level: string) => void> {} - interface NotificationShowSettingsEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function() {...}; - */ - addListener(callback: () => void): void; - } + interface NotificationShowSettingsEvent extends chrome.events.Event<() => void> {} /** The notification closed, either by the system or by user action. */ export var onClosed: NotificationClosedEvent; @@ -4857,40 +4353,13 @@ declare module chrome.omnibox { description: string; } - interface OmniboxInputEnteredEvent extends chrome.events.Event { - /** - * The callback parameter should be a function that looks like this: - * function(string text, OnInputEnteredDisposition disposition) {...}; - */ - addListener(callback: (text: string) => void): void; - } + interface OmniboxInputEnteredEvent extends chrome.events.Event<(text: string) => void> {} - interface OmniboxInputChangedEvent extends chrome.events.Event { - /** - * The callback parameter should be a function that looks like this: - * function(string text, function suggest) {...}; - * Parameter suggest: A callback passed to the onInputChanged event used for sending suggestions back to the browser. - * The suggest parameter should be a function that looks like this: - * function(array of SuggestResult suggestResults) {...}; - */ - addListener(callback: (text: string, suggest: (suggestResults: SuggestResult[]) => void) => void): void; - } + interface OmniboxInputChangedEvent extends chrome.events.Event<(text: string, suggest: (suggestResults: SuggestResult[]) => void) => void> {} - interface OmniboxInputStartedEvent extends chrome.events.Event { - /** - * The callback parameter should be a function that looks like this: - * function() {...}; - */ - addListener(callback: () => void): void; - } + interface OmniboxInputStartedEvent extends chrome.events.Event<() => void> {} - interface OmniboxInputCancelledEvent extends chrome.events.Event { - /** - * The callback parameter should be a function that looks like this: - * function() {...}; - */ - addListener(callback: () => void): void; - } + interface OmniboxInputCancelledEvent extends chrome.events.Event<() => void> {} /** * Sets the description and styling for the default suggestion. The default suggestion is the text that is displayed in the first suggestion row underneath the URL bar. @@ -4917,13 +4386,7 @@ declare module chrome.omnibox { * @since Chrome 5. */ declare module chrome.pageAction { - interface PageActionClickedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( tabs.Tab tab) {...}; - */ - addListener(callback: (tab: chrome.tabs.Tab) => void): void; - } + interface PageActionClickedEvent extends chrome.events.Event<(tab: chrome.tabs.Tab) => void> {} interface TitleDetails { /** The id of the tab for which you want to modify the page action. */ @@ -5232,45 +4695,13 @@ declare module chrome.printerProvider { document: Blob; } - interface PrinterRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(function resultCallback) {...}; - * Parameter resultCallback: Callback to return printer list. Every listener must call callback exactly once. - */ - addListener(callback: (resultCallback: (printerInfo: PrinterInfo[]) => void) => void): void; - } + interface PrinterRequestedEvent extends chrome.events.Event<(resultCallback: (printerInfo: PrinterInfo[]) => void) => void> {} - interface PrinterInfoRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( usb.Device device, function resultCallback) {...}; - * Parameter device: The USB device. - * Parameter resultCallback: Callback to return printer info. The receiving listener must call callback exactly once. If the parameter to this callback is undefined that indicates that the application has determined that the device is not supported. - */ - addListener(callback: (device: any, resultCallback: (printerInfo?: PrinterInfo) => void) => void): void; - } + interface PrinterInfoRequestedEvent extends chrome.events.Event<(device: any, resultCallback: (printerInfo?: PrinterInfo) => void) => void> {} - interface CapabilityRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string printerId, function resultCallback) {...}; - * Parameter printerId: Unique ID of the printer whose capabilities are requested. - * Parameter resultCallback: Callback to return device capabilities in CDD format. The receiving listener must call callback exectly once. - */ - addListener(callback: (printerId: string, resultCallback: (capabilities: PrinterCapabilities) => void) => void): void; - } + interface CapabilityRequestedEvent extends chrome.events.Event<(printerId: string, resultCallback: (capabilities: PrinterCapabilities) => void) => void> {} - interface PrintRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object printJob, function resultCallback) {...}; - * Parameter printJob: The printing request parameters. - * Parameter resultCallback: Callback that should be called when the printing request is completed. - * Parameter result (for resultCallback): OK: Operation completed successfully. FAILED: General failure. INVALID_TICKET: Print ticket is invalid. For example, ticket is inconsistent with capabilities or extension is not able to handle all settings from the ticket. INVALID_DATA: Document is invalid. For example, data may be corrupted or the format is incompatible with the extension. - */ - addListener(callback: (printJob: PrintJob, resultCallback: (result: string) => void) => void): void; - } + interface PrintRequestedEvent extends chrome.events.Event<(printJob: PrintJob, resultCallback: (result: string) => void) => void> {} /** Event fired when print manager requests printers provided by extensions. */ export var onGetPrintersRequested: PrinterRequestedEvent; @@ -5407,13 +4838,7 @@ declare module chrome.proxy { fatal: boolean; } - interface ProxyErrorEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object details) {...}; - */ - addListener(callback: (details: ErrorDetails) => void): void; - } + interface ProxyErrorEvent extends chrome.events.Event<(details: ErrorDetails) => void> {} var settings: chrome.types.ChromeSetting; /** Notifies about proxy errors. */ @@ -5527,7 +4952,7 @@ declare module chrome.runtime { */ sender?: MessageSender; /** An object which allows the addition and removal of listeners for a Chrome event. */ - onDisconnect: chrome.events.Event; + onDisconnect: chrome.events.Event<() => void>; /** An object which allows the addition and removal of listeners for a Chrome event. */ onMessage: PortMessageEvent; name: string; @@ -5543,46 +4968,19 @@ declare module chrome.runtime { version: string; } - interface PortMessageEvent extends chrome.events.Event { - addListener(callback: (message: Object, port: Port) => void): void; - } + interface PortMessageEvent extends chrome.events.Event<(message: Object, port: Port) => void> {} - interface ExtensionMessageEvent extends chrome.events.Event { - /** - * @param callback - * Optional parameter message: The message sent by the calling script. - * Parameter sendResponse: Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object. If you have more than one onMessage listener in the same document, then only one may send a response. This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called). - */ - addListener(callback: (message: any, sender: MessageSender, sendResponse: (response: any) => void) => void): void; - } + interface ExtensionMessageEvent extends chrome.events.Event<(message: any, sender: MessageSender, sendResponse: (response: any) => void) => void> {} - interface ExtensionConnectEvent extends chrome.events.Event { - addListener(callback: (port: Port) => void): void; - } + interface ExtensionConnectEvent extends chrome.events.Event<(port: Port) => void> {} - interface RuntimeInstalledEvent extends chrome.events.Event { - addListener(callback: (details: InstalledDetails) => void): void; - } + interface RuntimeInstalledEvent extends chrome.events.Event<(details: InstalledDetails) => void> {} - interface RuntimeEvent extends chrome.events.Event { - addListener(callback: () => void): void; - } + interface RuntimeEvent extends chrome.events.Event<() => void> {} - interface RuntimeRestartRequiredEvent extends chrome.events.Event { - /** - * @param callback - * Parameter reason: The reason that the event is being dispatched. One of: "app_update", "os_update", or "periodic" - */ - addListener(callback: (reason: string) => void): void; - } + interface RuntimeRestartRequiredEvent extends chrome.events.Event<(reason: string) => void> {} - interface RuntimeUpdateAvailableEvent extends chrome.events.Event { - /** - * @param callback - * Parameter details: The manifest details of the available update. - */ - addListener(callback: (details: UpdateAvailableDetails) => void): void; - } + interface RuntimeUpdateAvailableEvent extends chrome.events.Event<(details: UpdateAvailableDetails) => void> {} /** * Attempts to connect to connect listeners within an extension/app (such as the background page), or other extensions/apps. This is useful for content scripts connecting to their extension processes, inter-app/extension communication, and web messaging. Note that this does not connect to any listeners in a content script. Extensions may connect to content scripts embedded in tabs via tabs.connect. @@ -5763,9 +5161,7 @@ declare module chrome.scriptBadge { popup: string; } - interface ScriptBadgeClickedEvent extends chrome.events.Event { - addListener(callback: (tab: chrome.tabs.Tab) => void): void; - } + interface ScriptBadgeClickedEvent extends chrome.events.Event<(tab: chrome.tabs.Tab) => void> {} export function getPopup(details: GetPopupDetails, callback: Function): void; export function getAttention(details: AttentionDetails): void; @@ -5813,9 +5209,7 @@ declare module chrome.sessions { sessions: Session[]; } - interface SessionChangedEvent extends chrome.events.Event { - addListener(callback: () => void): void; - } + interface SessionChangedEvent extends chrome.events.Event<() => void> {} /** The maximum number of sessions.Session that will be included in a requested list. */ export var MAX_SESSION_RESULTS: number; @@ -5978,14 +5372,7 @@ declare module chrome.storage { MAX_WRITE_OPERATIONS_PER_MINUTE: number; } - interface StorageChangedEvent extends chrome.events.Event { - /** - * @param callback - * Parameter changes: Object mapping each key that changed to its corresponding storage.StorageChange for that item. - * Parameter areaName: Since Chrome 22. The name of the storage area ("sync", "local" or "managed") the changes are for. - */ - addListener(callback: (changes: { [key: string]: StorageChange }, areaName: string) => void): void; - } + interface StorageChangedEvent extends chrome.events.Event<(changes: { [key: string]: StorageChange }, areaName: string) => void> {} /** Items in the local storage area are local to each machine. */ var local: LocalStorageArea; @@ -6159,13 +5546,9 @@ declare module chrome.system.storage { availableCapacity: number; } - interface SystemStorageAttachedEvent extends chrome.events.Event { - addListener(callback: (info: StorageUnitInfo) => void): void; - } + interface SystemStorageAttachedEvent extends chrome.events.Event<(info: StorageUnitInfo) => void> {} - interface SystemStorageDetachedEvent extends chrome.events.Event { - addListener(callback: (id: string) => void): void; - } + interface SystemStorageDetachedEvent extends chrome.events.Event<(id: string) => void> {} /** Get the storage information from the system. The argument passed to the callback is an array of StorageUnitInfo objects. */ export function getInfo(callback: (info: StorageUnitInfo[]) => void): void; @@ -6219,13 +5602,7 @@ declare module chrome.tabCapture { videoConstraints?: MediaStreamConstraints; } - interface CaptureStatusChangedEvent extends chrome.events.Event { - /** - * @param callback - * Parameter info: CaptureInfo with new capture status for the tab. - */ - addListener(callback: (info: CaptureInfo) => void): void; - } + interface CaptureStatusChangedEvent extends chrome.events.Event<(info: CaptureInfo) => void> {} /** * Captures the visible area of the currently active tab. Capture can only be started on the currently active tab after the extension has been invoked. Capture is maintained across page navigations within the tab, and stops when the tab is closed, or the media stream is closed by the extension. @@ -6659,58 +6036,27 @@ declare module chrome.tabs { zoomSettings: ZoomSettings; } - interface TabHighlightedEvent extends chrome.events.Event { - addListener(callback: (highlightInfo: HighlightInfo) => void): void; - } + interface TabHighlightedEvent extends chrome.events.Event<(highlightInfo: HighlightInfo) => void> {} - interface TabRemovedEvent extends chrome.events.Event { - addListener(callback: (tabId: number, removeInfo: TabRemoveInfo) => void): void; - } + interface TabRemovedEvent extends chrome.events.Event<(tabId: number, removeInfo: TabRemoveInfo) => void> {} - interface TabUpdatedEvent extends chrome.events.Event { - /** - * @param callback - * Parameter changeInfo: Lists the changes to the state of the tab that was updated. - * Parameter tab: Gives the state of the tab that was updated. - */ - addListener(callback: (tabId: number, changeInfo: TabChangeInfo, tab: Tab) => void): void; - } + interface TabUpdatedEvent extends chrome.events.Event<(tabId: number, changeInfo: TabChangeInfo, tab: Tab) => void> {} - interface TabAttachedEvent extends chrome.events.Event { - addListener(callback: (tabId: number, attachInfo: TabAttachInfo) => void): void; - } + interface TabAttachedEvent extends chrome.events.Event<(tabId: number, attachInfo: TabAttachInfo) => void> {} - interface TabMovedEvent extends chrome.events.Event { - addListener(callback: (tabId: number, moveInfo: TabMoveInfo) => void): void; - } + interface TabMovedEvent extends chrome.events.Event<(tabId: number, moveInfo: TabMoveInfo) => void> {} - interface TabDetachedEvent extends chrome.events.Event { - addListener(callback: (tabId: number, detachInfo: TabDetachInfo) => void): void; - } + interface TabDetachedEvent extends chrome.events.Event<(tabId: number, detachInfo: TabDetachInfo) => void> {} - interface TabCreatedEvent extends chrome.events.Event { - /** - * @param callback - * Parameter tab: Details of the tab that was created. - */ - addListener(callback: (tab: Tab) => void): void; - } + interface TabCreatedEvent extends chrome.events.Event<(tab: Tab) => void> {} - interface TabActivatedEvent extends chrome.events.Event { - addListener(callback: (activeInfo: TabActiveInfo) => void): void; - } + interface TabActivatedEvent extends chrome.events.Event<(activeInfo: TabActiveInfo) => void> {} - interface TabReplacedEvent extends chrome.events.Event { - addListener(callback: (addedTabId: number, removedTabId: number) => void): void; - } + interface TabReplacedEvent extends chrome.events.Event<(addedTabId: number, removedTabId: number) => void> {} - interface TabSelectedEvent extends chrome.events.Event { - addListener(callback: (tabId: number, selectInfo: TabWindowInfo) => void): void; - } + interface TabSelectedEvent extends chrome.events.Event<(tabId: number, selectInfo: TabWindowInfo) => void> {} - interface TabZoomChangeEvent extends chrome.events.Event { - addListener(callback: (ZoomChangeInfo: ZoomChangeInfo) => void): void; - } + interface TabZoomChangeEvent extends chrome.events.Event<(ZoomChangeInfo: ZoomChangeInfo) => void> {} /** * Injects JavaScript code into a page. For details, see the programmatic injection section of the content scripts doc. @@ -7185,30 +6531,22 @@ declare module chrome.ttsEngine { pitch?: number; } - interface TtsEngineSpeakEvent extends chrome.events.Event { - /** - * @param callback - * Parameter utterance: The text to speak, specified as either plain text or an SSML document. If your engine does not support SSML, you should strip out all XML markup and synthesize only the underlying text content. The value of this parameter is guaranteed to be no more than 32,768 characters. If this engine does not support speaking that many characters at a time, the utterance should be split into smaller chunks and queued internally without returning an error. - * Parameter options: Options specified to the tts.speak() method. - * Parameter sendTtsEvent: Call this function with events that occur in the process of speaking the utterance. - */ - addListener(callback: (utterance: string, options: SpeakOptions, sendTtsEvent: (event: chrome.tts.TtsEvent) => void) => void): void; - } + interface TtsEngineSpeakEvent extends chrome.events.Event<(utterance: string, options: SpeakOptions, sendTtsEvent: (event: chrome.tts.TtsEvent) => void) => void> {} /** Called when the user makes a call to tts.speak() and one of the voices from this extension's manifest is the first to match the options object. */ var onSpeak: TtsEngineSpeakEvent; /** Fired when a call is made to tts.stop and this extension may be in the middle of speaking. If an extension receives a call to onStop and speech is already stopped, it should do nothing (not raise an error). If speech is in the paused state, this should cancel the paused state. */ - var onStop: chrome.events.Event; + var onStop: chrome.events.Event<() => void>; /** * Optional: if an engine supports the pause event, it should pause the current utterance being spoken, if any, until it receives a resume event or stop event. Note that a stop event should also clear the paused state. * @since Chrome 29. */ - var onPause: chrome.events.Event; + var onPause: chrome.events.Event<() => void>; /** * Optional: if an engine supports the pause event, it should also support the resume event, to continue speaking the current utterance, if any. Note that a stop event should also clear the paused state. * @since Chrome 29. */ - var onResume: chrome.events.Event; + var onResume: chrome.events.Event<() => void>; } //////////////////// @@ -7277,9 +6615,7 @@ declare module chrome.types { incognitoSpecific?: boolean; } - interface ChromeSettingChangedEvent extends chrome.events.Event { - addListener(callback: DetailsCallback): void; - } + interface ChromeSettingChangedEvent extends chrome.events.Event {} /** An interface that allows access to a Chrome browser setting. See accessibilityFeatures for an example. */ interface ChromeSetting { @@ -7336,55 +6672,15 @@ declare module chrome.vpnProvider { dnsServer: string[]; } - interface VpnPlatformMessageEvent extends chrome.events.Event { - /** - * @param callback - * Parameter id: ID of the configuration the message is intended for. - * Parameter message: The message received from the platform. - * * connected: VPN configuration connected. - * * disconnected: VPN configuration disconnected. - * * error: An error occurred in VPN connection, for example a timeout. A description of the error is give as the error argument to onPlatformMessage. - * Parameter error: Error message when there is an error. - */ - addListener(callback: (id: string, message: string, error: string) => void): void; - } + interface VpnPlatformMessageEvent extends chrome.events.Event<(id: string, message: string, error: string) => void> {} - interface VpnPacketReceptionEvent extends chrome.events.Event { - /** - * @param callback - * Parameter data: The IP packet received from the platform. - */ - addListener(callback: (data: ArrayBuffer) => void): void; - } + interface VpnPacketReceptionEvent extends chrome.events.Event<(data: ArrayBuffer) => void> {} - interface VpnConfigRemovalEvent extends chrome.events.Event { - /** - * @param callback - * Parameter id: ID of the removed configuration. - */ - addListener(callback: (id: string) => void): void; - } + interface VpnConfigRemovalEvent extends chrome.events.Event<(id: string) => void> {} - interface VpnConfigCreationEvent extends chrome.events.Event { - /** - * @param callback - * Parameter id: ID of the configuration created. - * Parameter name: Name of the configuration created. - * Parameter data: Configuration data provided by the administrator. - */ - addListener(callback: (id: string, name: string, data: Object) => void): void; - } + interface VpnConfigCreationEvent extends chrome.events.Event<(id: string, name: string, data: Object) => void> {} - interface VpnUiEvent extends chrome.events.Event { - /** - * @param callback - * Parameter event: The UI event that is triggered. - * * showAddDialog: Request the VPN client to show add configuration dialog to the user. - * * showConfigureDialog: Request the VPN client to show configuration settings dialog to the user. - * Optional parameter id: ID of the configuration for which the UI event was triggered. - */ - addListener(callback: (event: string, id?: string) => void): void; - } + interface VpnUiEvent extends chrome.events.Event<(event: string, id?: string) => void> {} /** * Creates a new VPN configuration that persists across multiple login sessions of the user. @@ -7577,33 +6873,21 @@ declare module chrome.webNavigation { url: chrome.events.UrlFilter[]; } - interface WebNavigationEvent extends chrome.events.Event { - addListener(callback: (details: WebNavigationCallbackDetails) => void, filters?: WebNavigationEventFilter): void; + interface WebNavigationEvent extends chrome.events.Event<(details: T) => void> { + addListener(callback: (details: T) => void, filters?: WebNavigationEventFilter): void; } + + interface WebNavigationFramedEvent extends WebNavigationEvent {} - interface WebNavigationFramedEvent extends WebNavigationEvent { - addListener(callback: (details: WebNavigationFramedCallbackDetails) => void, filters?: WebNavigationEventFilter): void; - } + interface WebNavigationFramedErrorEvent extends WebNavigationEvent {} - interface WebNavigationFramedErrorEvent extends WebNavigationFramedEvent { - addListener(callback: (details: WebNavigationFramedErrorCallbackDetails) => void, filters?: WebNavigationEventFilter): void; - } + interface WebNavigationSourceEvent extends WebNavigationEvent {} - interface WebNavigationSourceEvent extends WebNavigationEvent { - addListener(callback: (details: WebNavigationSourceCallbackDetails) => void, filters?: WebNavigationEventFilter): void; - } + interface WebNavigationParentedEvent extends WebNavigationEvent {} - interface WebNavigationParentedEvent extends WebNavigationEvent { - addListener(callback: (details: WebNavigationParentedCallbackDetails) => void, filters?: WebNavigationEventFilter): void; - } + interface WebNavigationTransitionalEvent extends WebNavigationEvent {} - interface WebNavigationTransitionalEvent extends WebNavigationEvent { - addListener(callback: (details: WebNavigationTransitionCallbackDetails) => void, filters?: WebNavigationEventFilter): void; - } - - interface WebNavigationReplacementEvent extends WebNavigationEvent { - addListener(callback: (details: WebNavigationReplacementCallbackDetails) => void, filters?: WebNavigationEventFilter): void; - } + interface WebNavigationReplacementEvent extends WebNavigationEvent {} /** * Retrieves information about the given frame. A frame refers to an ') - */ - youTubeCode?: string; - /** - * Vimeo embed code. %id% is replaced by video id. (default: '') - */ - vimeoCode?: string; - } - - export interface RoyalSliderBlockOptions { - /** - * true or false (default: true) - */ - fadeEffect?: boolean; - /** - * Move effect direction.Can be 'left', 'right', 'top', 'bottom' or 'none'. (default: 'top') - */ - moveEffect?: string; - /** - * Distance for move effect in pixels. (default: 20) - */ - moveOffset?: number; - /** - * Transition speed of block, in ms. (default: 400) - */ - speed?: number; - /** - * Easing function of block animation.Read more in easing section of docs. (default: 'easeOutSine' ) - */ - easing?: string; - /** - * Delay between each block show up, in ms. (default: 200) - */ - delay?: number; - } - - export interface RoyalSliderVisibleOptions { - /** - * Enable visible-nearby. (default: true) - */ - enabled?: boolean; - /** - * Ratio that determines area of center image.For example for 0.6 - 60 % of slider area will get center image and 20% for two images on sides. (default: 0.6) - */ - centerArea?: number; - /** - * Alignment of center image, if you set it to false center image will be aligned to left. (default: true) - */ - center?: boolean; - /** - * Disables navigation to next slide by clicking on current slide (if navigateByClick is true). (default: true) - */ - navigateByCenterClick?: boolean; - /** - * Used for responsive design. Changes centerArea value to breakpointCenterArea when width of slider is less then value in this option. Set to 0 to disable. (default: 0) - */ - breakpoint?: number; - /** - * Same as centerArea option, just for breakpoint. Can be changed dynamically via `sliderInstance.st.breakpointCenterArea`. (default: 0.8) - */ - breakpointCenterArea?: number; - } - - export interface RoyalSliderOptions { - /** - * Automatically updates slider height based on base width. (default: false) - */ - autoScaleSlider?: boolean; - /** - * Base slider width.Slider will autocalculate the ratio based on these values. (default: 800) - */ - autoScaleSliderWidth?: number; - /** - * 400 Base slider height - */ - autoScaleSliderHeight?: number; - /** - * Scale mode for images."fill", "fit", "fit-if-smaller" or "none". (default: 'fit-if-smaller') - */ - imageScaleMode?: string; - /** - * Aligns image to center of slide. (default: true) - */ - imageAlignCenter?: boolean; - /** - * Distance between image and edge of slide (doesn't work with 'fill' scale mode). (default: 4) - */ - imageScalePadding?: number; - /** - * Navigation type, can be 'bullets', 'thumbnails', 'tabs' or 'none' (default: 'bullets') - */ - controlNavigation?: string; - /** - * Direction arrows navigation. (default: true) - */ - arrowsNav?: boolean; - /** - * Auto hide arrows. (default: true) - */ - arrowsNavAutoHide?: boolean; - /** - * Hides arrows completely on touch devices. (default: false) - */ - arrowsNavHideOnTouch?: boolean; - /** - * Adds base width to all images for better-looking loading. Can be specified separately for each image. (default: null) - */ - imgWidth?: number; - /** - * Adds base height to all images for better-looking loading. Can be specified separately for each image. (default: null) - */ - imgHeight?: number; - /** - * Spacing between slides in pixels. (default: 8) - */ - slidesSpacing?: number; - /** - * Start slide index. (default: 0) - */ - startSlideId?: number; - /** - * Makes slider to go from last slide to first. (default: false) - */ - loop?: boolean; - /** - * Makes slider to go from last slide to first with rewind. Overrides prev option. (default: false) - */ - loopRewind?: boolean; - /** - * Randomizes all slides at start. (default: false) - */ - randomizeSlides?: boolean; - /** - * Number of slides to preload on sides.If you set it to 0, only one slide will be kept in the display list at once. (default: 4) - */ - numImagesToPreload?: number; - /** - * Enables spinning preloader, you may style it via CSS (class rsPreloader). (default: true) - */ - usePreloader?: boolean; - /** - * Can be 'vertical' or 'horizontal'. (default: 'horizontal') - */ - slidesOrientation?: string; - /** - * 'move' or 'fade'. Important note about fade transition, slides must have background as only one image is animating. (default: 'move') - */ - transitionType?: string; - /** - * Slider transition speed, in ms. (default: 600) - */ - transitionSpeed?: number; - /** - * Easing function for simple transition.Read more in the easing section of the documentation. (default: 'easeInOutSine') - */ - easeInOut?: string; - /** - * Easing function of animation after ending of the swipe gesture. Read more in the easing section of the documentation. (default: 'easeOutSine') - */ - easeOut?: string; - /** - * If set to true adds arrows and fullscreen button inside rsOverflow container, otherwise inside root slider container. (default: true) - */ - controlsInside?: boolean; - /** - * Navigates forward by clicking on slide. (default: true) - */ - navigateByClick?: boolean; - /** - * Mouse drag navigation over slider. (default: true) - */ - sliderDrag?: boolean; - /** - * Touch navigation of slider. (default: true) - */ - sliderTouch?: boolean; - /** - * Navigate slider with keyboard left and right arrows. (default: false) - */ - keyboardNavEnabled?: boolean; - /** - * Fades in slide after it's loaded. (default: true) - */ - fadeinLoadedSlide?: boolean; - /** - * Allows usage of CSS3 transitions. Might be useful if you're experiencing font-rendering problems, or other CSS3-related bugs. (default: true) - */ - allowCSS3?: boolean; - /** - * Adds global caption element to slider, read more in the global caption section of documentation. (default: false) - */ - globalCaption?: boolean; - /** - * Adds rsActiveSlide class to current slide before transition. (default: false) - */ - addActiveClass?: boolean; - /** - * Minimum distance in pixels to show next slide while dragging. (default: 10) - */ - minSlideOffset?: number; - /** - * Scales and animates height based on current slide. Please note: if you have images in slide that don't have rsImg class) or don't have fixed size, use $(window).load() instead of $(document).ready() before initializing slider. Also, autoHeight doesn't work with properties like autoScaleSlider, imageScaleMode and imageAlignCenter. (default: false) - */ - autoHeight?: boolean;// false - /** - * Overrides HTML of slides, used for creating of slides from HTML that is not attached to DOM. More info in knowledge base. (default: null) - */ - slides?: Element; - /** - * Thumbnail options - */ - thumbs?: RoyalSliderThumbsOptions; - /** - * You may specify larger images when slider is in fullscreen mode by adding data-rsBigImg attribute to rsImg element. A few examples: - */ - fullscreen?: RoyalSliderFullscreenOptions; - /** - * Deep linking module makes URL automatically change when you switch slides and you can easily link to specific slide (aka permalink). - */ - deeplinking?: RoyalSliderDeeplinkingOptions; - /** - * Autoplay slideshow can be enabled via slider options. Delay between items can be set globally via delay option, or specifically for each item by adding data-rsDelay="1000" to root element of the slide (1000 = 1sec). - */ - autoplay?: RoyalSliderAutoplayOptions; - /** - * To add video to slide, you need to add data-rsVideo="" attribute to image. It can contain link to YouTube or Vimeo video. - */ - video?: RoyalSliderVideoOptions; - /** - * All elements inside slide that have class rsABlock will be treated by slider as animated blocks (tag name doesn't matter). Blocks can not be nested, but you can put multiple instances of them into one slide, or make slide itself animated block. - */ - block?: RoyalSliderBlockOptions; - /** - * Module "reveals" next and previous slides, like in this template. - */ - visibleNearby?: RoyalSliderVisibleOptions; - } - - export interface RoyalSlider { //TODO: extends/implements JQuery? (giving problems due to next(), prev(), width and height and 'selector'. - /** - * go to slide with id - */ - goTo(id: number): void; - /** - * next slide - */ - next(): void; - /** - * prev slide - */ - prev(): void; - /** - * removes all events and clears all slider data (use on ajax sites to avoid memory leaks) - */ - destroy(): void; - /** - * Dynamic slides adding/removing - */ - appendSlide(element: JQuery, index?: number): void; - /** - * Remove slide - */ - removeSlide(index?: number): void; - /** - * updates size of slider. Use after you resize slider with js. - */ - updateSliderSize(forceResize?: boolean): void; - /** - * changes orientation of thumbnails - */ - setThumbsOrientation(orientation: string): void; - /** - * updates size of thumbnails - */ - updateThumbsSize(): void; - /** - * Enter Fullscreen mode - */ - enterFullscreen(): void; - /** - * Exit Fullscreen mode - */ - exitFullscreen(): void; - /** - * Start autoplay - */ - startAutoPlay(): void; - /** - * Stop autoplay - */ - stopAutoPlay(): void; - /** - * Toggle autoplay between start and stop - */ - toggleAutoPlay(): void; - /** - * Toggle video between start and stop - */ - toggleVideo(): void; - /** - * Play video - */ - playVideo(): void; - /** - * Stop video - */ - stopVideo(): void; - /** - * current slide index - */ - currSlideId: number; - /** - * current slide object - */ - currSlide: JQuery; - /** - * total number of slides - */ - numSlides: number; - /** - * indicates if slider is in fullscreen mode - */ - isFullscreen: boolean; - /** - * indicates if browser supports native fullscreen - */ - nativeFS: boolean; - /** - * width of slider - */ - width: number; - /** - * height of slider - */ - height: number; - /** - * Boolean, changes on mouseup, indicates if slide was dragged. Used to check if event is drag or click. - */ - dragSuccess: boolean; - /** - * contains all data about each slide - */ - slides: any[]; //TODO: what type? - /** - * Contains list of HTML slides that are added to slider - */ - slidesJQ: JQuery[]; //TODO: what type? - /** - * Object with slider settings - */ - st: RoyalSliderOptions; - /** - * jQuery object with slider events - */ - ev: JQuery; - } -} - -interface JQuery { - /** - * Creates a new royal-slider with the specified, or default, options. - * - * @param options The options - */ - royalSlider(options?: RoyalSlider.RoyalSliderOptions): JQuery; +// Type definitions for jQuery royal-slider v9.4.0 +// Project: http://dimsemenov.com/plugins/royal-slider/documentation/ +// Definitions by: Christiaan Rakowski +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module RoyalSlider { + export interface RoyalSliderThumbsOptions { + /** + * Thumbnails mouse drag. (default: true) + */ + drag?: boolean; + /** + * Thumbnails touch. (default: true) + */ + touch?: boolean; + /** + * 'horizontal' or 'vertical'. (default: 'horizontal') + */ + orientation?: string; + /** + * Thumbnails arrows. (default: true) + */ + arrows?: boolean; + /** + * Spacing between thumbs. (default: 4) + */ + spacing?: number; + /** + * Auto hide thumbnails arrows on hover. (default: false) + */ + arrowsAutoHide?: boolean; + /** + * Automatically centers container with thumbs if there are small number of items (default: true) + */ + autoCenter?: boolean; + /** + * Thumbnails transition speed. (default: 600) + */ + transitionSpeed?: number; + /** + * Reduces size of main viewport area by thumbnails width or height, use it when you set 100 % width to slider.This option is always true, when slider is in fullscreen mode. (default: true) + */ + fitInViewport?: boolean; + /** + * Margin that equals thumbs spacing for first and last item. (default: true) + */ + firstMargin?: boolean; + /** + * Replaces default thumbnail arrow. You have to add it to DOM manually. (default: null) + */ + arrowLeft?: JQuery; + /** + * Replaces default thumbnail arrow. You have to add it to DOM manually. (default: null) + */ + arrowRight?: JQuery; + /** + * Adds span element with class thumbIco to every thumbnail. Useful for styling (default: false) + */ + appendSpan?: boolean; + } + + export interface RoyalSliderFullscreenOptions { + /** + * Fullscreen functions enabled. (default: false) + */ + enabled?: boolean; + /** + * Force keyboard arrows nav in fullscreen. (default: true) + */ + keyboardNav?: boolean; + /** + * Fullscreen button at top right. (default: true) + */ + buttonFS?: boolean; + /** + * Native browser fullscreen. (default: false) + */ + nativeFS?: boolean; + } + + export interface RoyalSliderDeeplinkingOptions { + /** + * Linking to slides by appending #SLIDE_INDEX to url.Slides count starts from 1. If change is set to false hash is only read once, after page load. (default: false) + */ + enabled?: boolean; + /** + * Automatically change URL after transition and listen for hash change. (default: false) + */ + change?: boolean; + /** + * Prefix that will be added to hash. For example if you set it to 'gallery-', hash would look like this: #gallery-5 (default: '') + */ + prefix?: string; + } + + export interface RoyalSliderAutoplayOptions { + /** + * Enable autoplay or not. (default: false) + */ + enabled?: boolean; + /** + * Stop autoplay at first user action. (default: true) + */ + stopAtAction?: boolean; + /** + * Pause autoplay on hover. (default: true) + */ + pauseOnHover?: boolean; + /** + * Delay between items in ms. (default: 300) + */ + delay?: number; + } + + export interface RoyalSliderVideoOptions { + /** + * Auto hide arrows when video is playing (default: true) + */ + autoHideArrows?: boolean; + /** + * Auto hide navigation when video is playing. (default: false) + */ + autoHideControlNav?: boolean; + /** + * Auto hide animated blocks when video is playing. (default: false) + */ + autoHideBlocks?: boolean; + /** + * Youtube embed code. %id% is replaced by video id. (default: '') + */ + youTubeCode?: string; + /** + * Vimeo embed code. %id% is replaced by video id. (default: '') + */ + vimeoCode?: string; + } + + export interface RoyalSliderBlockOptions { + /** + * true or false (default: true) + */ + fadeEffect?: boolean; + /** + * Move effect direction.Can be 'left', 'right', 'top', 'bottom' or 'none'. (default: 'top') + */ + moveEffect?: string; + /** + * Distance for move effect in pixels. (default: 20) + */ + moveOffset?: number; + /** + * Transition speed of block, in ms. (default: 400) + */ + speed?: number; + /** + * Easing function of block animation.Read more in easing section of docs. (default: 'easeOutSine' ) + */ + easing?: string; + /** + * Delay between each block show up, in ms. (default: 200) + */ + delay?: number; + } + + export interface RoyalSliderVisibleOptions { + /** + * Enable visible-nearby. (default: true) + */ + enabled?: boolean; + /** + * Ratio that determines area of center image.For example for 0.6 - 60 % of slider area will get center image and 20% for two images on sides. (default: 0.6) + */ + centerArea?: number; + /** + * Alignment of center image, if you set it to false center image will be aligned to left. (default: true) + */ + center?: boolean; + /** + * Disables navigation to next slide by clicking on current slide (if navigateByClick is true). (default: true) + */ + navigateByCenterClick?: boolean; + /** + * Used for responsive design. Changes centerArea value to breakpointCenterArea when width of slider is less then value in this option. Set to 0 to disable. (default: 0) + */ + breakpoint?: number; + /** + * Same as centerArea option, just for breakpoint. Can be changed dynamically via `sliderInstance.st.breakpointCenterArea`. (default: 0.8) + */ + breakpointCenterArea?: number; + } + + export interface RoyalSliderOptions { + /** + * Automatically updates slider height based on base width. (default: false) + */ + autoScaleSlider?: boolean; + /** + * Base slider width.Slider will autocalculate the ratio based on these values. (default: 800) + */ + autoScaleSliderWidth?: number; + /** + * 400 Base slider height + */ + autoScaleSliderHeight?: number; + /** + * Scale mode for images."fill", "fit", "fit-if-smaller" or "none". (default: 'fit-if-smaller') + */ + imageScaleMode?: string; + /** + * Aligns image to center of slide. (default: true) + */ + imageAlignCenter?: boolean; + /** + * Distance between image and edge of slide (doesn't work with 'fill' scale mode). (default: 4) + */ + imageScalePadding?: number; + /** + * Navigation type, can be 'bullets', 'thumbnails', 'tabs' or 'none' (default: 'bullets') + */ + controlNavigation?: string; + /** + * Direction arrows navigation. (default: true) + */ + arrowsNav?: boolean; + /** + * Auto hide arrows. (default: true) + */ + arrowsNavAutoHide?: boolean; + /** + * Hides arrows completely on touch devices. (default: false) + */ + arrowsNavHideOnTouch?: boolean; + /** + * Adds base width to all images for better-looking loading. Can be specified separately for each image. (default: null) + */ + imgWidth?: number; + /** + * Adds base height to all images for better-looking loading. Can be specified separately for each image. (default: null) + */ + imgHeight?: number; + /** + * Spacing between slides in pixels. (default: 8) + */ + slidesSpacing?: number; + /** + * Start slide index. (default: 0) + */ + startSlideId?: number; + /** + * Makes slider to go from last slide to first. (default: false) + */ + loop?: boolean; + /** + * Makes slider to go from last slide to first with rewind. Overrides prev option. (default: false) + */ + loopRewind?: boolean; + /** + * Randomizes all slides at start. (default: false) + */ + randomizeSlides?: boolean; + /** + * Number of slides to preload on sides.If you set it to 0, only one slide will be kept in the display list at once. (default: 4) + */ + numImagesToPreload?: number; + /** + * Enables spinning preloader, you may style it via CSS (class rsPreloader). (default: true) + */ + usePreloader?: boolean; + /** + * Can be 'vertical' or 'horizontal'. (default: 'horizontal') + */ + slidesOrientation?: string; + /** + * 'move' or 'fade'. Important note about fade transition, slides must have background as only one image is animating. (default: 'move') + */ + transitionType?: string; + /** + * Slider transition speed, in ms. (default: 600) + */ + transitionSpeed?: number; + /** + * Easing function for simple transition.Read more in the easing section of the documentation. (default: 'easeInOutSine') + */ + easeInOut?: string; + /** + * Easing function of animation after ending of the swipe gesture. Read more in the easing section of the documentation. (default: 'easeOutSine') + */ + easeOut?: string; + /** + * If set to true adds arrows and fullscreen button inside rsOverflow container, otherwise inside root slider container. (default: true) + */ + controlsInside?: boolean; + /** + * Navigates forward by clicking on slide. (default: true) + */ + navigateByClick?: boolean; + /** + * Mouse drag navigation over slider. (default: true) + */ + sliderDrag?: boolean; + /** + * Touch navigation of slider. (default: true) + */ + sliderTouch?: boolean; + /** + * Navigate slider with keyboard left and right arrows. (default: false) + */ + keyboardNavEnabled?: boolean; + /** + * Fades in slide after it's loaded. (default: true) + */ + fadeinLoadedSlide?: boolean; + /** + * Allows usage of CSS3 transitions. Might be useful if you're experiencing font-rendering problems, or other CSS3-related bugs. (default: true) + */ + allowCSS3?: boolean; + /** + * Adds global caption element to slider, read more in the global caption section of documentation. (default: false) + */ + globalCaption?: boolean; + /** + * Adds rsActiveSlide class to current slide before transition. (default: false) + */ + addActiveClass?: boolean; + /** + * Minimum distance in pixels to show next slide while dragging. (default: 10) + */ + minSlideOffset?: number; + /** + * Scales and animates height based on current slide. Please note: if you have images in slide that don't have rsImg class) or don't have fixed size, use $(window).load() instead of $(document).ready() before initializing slider. Also, autoHeight doesn't work with properties like autoScaleSlider, imageScaleMode and imageAlignCenter. (default: false) + */ + autoHeight?: boolean;// false + /** + * Overrides HTML of slides, used for creating of slides from HTML that is not attached to DOM. More info in knowledge base. (default: null) + */ + slides?: Element; + /** + * Thumbnail options + */ + thumbs?: RoyalSliderThumbsOptions; + /** + * You may specify larger images when slider is in fullscreen mode by adding data-rsBigImg attribute to rsImg element. A few examples: + */ + fullscreen?: RoyalSliderFullscreenOptions; + /** + * Deep linking module makes URL automatically change when you switch slides and you can easily link to specific slide (aka permalink). + */ + deeplinking?: RoyalSliderDeeplinkingOptions; + /** + * Autoplay slideshow can be enabled via slider options. Delay between items can be set globally via delay option, or specifically for each item by adding data-rsDelay="1000" to root element of the slide (1000 = 1sec). + */ + autoplay?: RoyalSliderAutoplayOptions; + /** + * To add video to slide, you need to add data-rsVideo="" attribute to image. It can contain link to YouTube or Vimeo video. + */ + video?: RoyalSliderVideoOptions; + /** + * All elements inside slide that have class rsABlock will be treated by slider as animated blocks (tag name doesn't matter). Blocks can not be nested, but you can put multiple instances of them into one slide, or make slide itself animated block. + */ + block?: RoyalSliderBlockOptions; + /** + * Module "reveals" next and previous slides, like in this template. + */ + visibleNearby?: RoyalSliderVisibleOptions; + } + + export interface RoyalSlider { //TODO: extends/implements JQuery? (giving problems due to next(), prev(), width and height and 'selector'. + /** + * go to slide with id + */ + goTo(id: number): void; + /** + * next slide + */ + next(): void; + /** + * prev slide + */ + prev(): void; + /** + * removes all events and clears all slider data (use on ajax sites to avoid memory leaks) + */ + destroy(): void; + /** + * Dynamic slides adding/removing + */ + appendSlide(element: JQuery, index?: number): void; + /** + * Remove slide + */ + removeSlide(index?: number): void; + /** + * updates size of slider. Use after you resize slider with js. + */ + updateSliderSize(forceResize?: boolean): void; + /** + * changes orientation of thumbnails + */ + setThumbsOrientation(orientation: string): void; + /** + * updates size of thumbnails + */ + updateThumbsSize(): void; + /** + * Enter Fullscreen mode + */ + enterFullscreen(): void; + /** + * Exit Fullscreen mode + */ + exitFullscreen(): void; + /** + * Start autoplay + */ + startAutoPlay(): void; + /** + * Stop autoplay + */ + stopAutoPlay(): void; + /** + * Toggle autoplay between start and stop + */ + toggleAutoPlay(): void; + /** + * Toggle video between start and stop + */ + toggleVideo(): void; + /** + * Play video + */ + playVideo(): void; + /** + * Stop video + */ + stopVideo(): void; + /** + * current slide index + */ + currSlideId: number; + /** + * current slide object + */ + currSlide: JQuery; + /** + * total number of slides + */ + numSlides: number; + /** + * indicates if slider is in fullscreen mode + */ + isFullscreen: boolean; + /** + * indicates if browser supports native fullscreen + */ + nativeFS: boolean; + /** + * width of slider + */ + width: number; + /** + * height of slider + */ + height: number; + /** + * Boolean, changes on mouseup, indicates if slide was dragged. Used to check if event is drag or click. + */ + dragSuccess: boolean; + /** + * contains all data about each slide + */ + slides: any[]; //TODO: what type? + /** + * Contains list of HTML slides that are added to slider + */ + slidesJQ: JQuery[]; //TODO: what type? + /** + * Object with slider settings + */ + st: RoyalSliderOptions; + /** + * jQuery object with slider events + */ + ev: JQuery; + } +} + +interface JQuery { + /** + * Creates a new royal-slider with the specified, or default, options. + * + * @param options The options + */ + royalSlider(options?: RoyalSlider.RoyalSliderOptions): JQuery; } \ No newline at end of file diff --git a/rtree/rtree.d.ts b/rtree/rtree.d.ts index fa6276c6e..752d2e89e 100644 --- a/rtree/rtree.d.ts +++ b/rtree/rtree.d.ts @@ -1,25 +1,25 @@ -// Type definitions for rtree 1.4.0 -// Project: https://github.com/leaflet-extras/RTree -// Definitions by: Omede Firouz -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -interface Rectangle { - x: number; - y: number; - w: number; - h: number; -} - -interface RTreeStatic { - insert(bounds: Rectangle, element: Object): boolean; - remove(area: Rectangle, element?: Object): any[]; - geoJSON(geoJSON: any): void; - bbox(arg1: any, arg2?: any, arg3?: number, arg4?: number): any[]; - search(area: Rectangle, return_node?: boolean, return_array?: any[]): any[]; -} - -interface RTreeFactory { - (max_node_width?: number): RTreeStatic; -} - -declare var RTree: RTreeFactory; +// Type definitions for rtree 1.4.0 +// Project: https://github.com/leaflet-extras/RTree +// Definitions by: Omede Firouz +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface Rectangle { + x: number; + y: number; + w: number; + h: number; +} + +interface RTreeStatic { + insert(bounds: Rectangle, element: Object): boolean; + remove(area: Rectangle, element?: Object): any[]; + geoJSON(geoJSON: any): void; + bbox(arg1: any, arg2?: any, arg3?: number, arg4?: number): any[]; + search(area: Rectangle, return_node?: boolean, return_array?: any[]): any[]; +} + +interface RTreeFactory { + (max_node_width?: number): RTreeStatic; +} + +declare var RTree: RTreeFactory; diff --git a/rx-angular/rx.angular-tests.ts b/rx-angular/rx.angular-tests.ts index 3caf01170..32240b660 100644 --- a/rx-angular/rx.angular-tests.ts +++ b/rx-angular/rx.angular-tests.ts @@ -1,21 +1,21 @@ -// Type definitions for angularjs extensions to rxjs -// Project: http://reactivex.io/ -// Definitions by: Mick Delaney -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -var app = angular.module('testModule'); - -interface AppScope extends rx.angular.IRxScope { -} - -app.controller('Ctrl', ($scope: AppScope) => { - - this.inputObservable = $scope.$toObservable('term') - .throttle(400) - .safeApply($scope, (results: any) => { - this.results = results; - }); - -}); +// Type definitions for angularjs extensions to rxjs +// Project: http://reactivex.io/ +// Definitions by: Mick Delaney +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +var app = angular.module('testModule'); + +interface AppScope extends rx.angular.IRxScope { +} + +app.controller('Ctrl', ($scope: AppScope) => { + + this.inputObservable = $scope.$toObservable('term') + .throttle(400) + .safeApply($scope, (results: any) => { + this.results = results; + }); + +}); diff --git a/rx-angular/rx.angular.d.ts b/rx-angular/rx.angular.d.ts index 8b1b94d84..c7dfceff7 100644 --- a/rx-angular/rx.angular.d.ts +++ b/rx-angular/rx.angular.d.ts @@ -1,33 +1,33 @@ -// Type definitions for angularjs extensions to rxjs -// Project: http://reactivex.io/ -// Definitions by: Mick Delaney -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// -/// -/// - -declare module Rx { - - interface IObservable { - safeApply($scope: ng.IScope, callback: (data: T) => void): Rx.Observable; - } - - export interface ScopeScheduler extends IScheduler { - constructor(scope: ng.IScope) : ScopeScheduler; - } - - export interface ScopeSchedulerStatic extends SchedulerStatic { - new ($scope: angular.IScope): ScopeScheduler; - } - - export var ScopeScheduler: ScopeSchedulerStatic; -} - -declare module rx.angular { - - export interface IRxScope extends ng.IScope { - $toObservable(property: string): Rx.Observable; - } -} - +// Type definitions for angularjs extensions to rxjs +// Project: http://reactivex.io/ +// Definitions by: Mick Delaney +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// +/// + +declare module Rx { + + interface IObservable { + safeApply($scope: ng.IScope, callback: (data: T) => void): Rx.Observable; + } + + export interface ScopeScheduler extends IScheduler { + constructor(scope: ng.IScope) : ScopeScheduler; + } + + export interface ScopeSchedulerStatic extends SchedulerStatic { + new ($scope: angular.IScope): ScopeScheduler; + } + + export var ScopeScheduler: ScopeSchedulerStatic; +} + +declare module rx.angular { + + export interface IRxScope extends ng.IScope { + $toObservable(property: string): Rx.Observable; + } +} + diff --git a/s3rver/s3rver-tests.ts b/s3rver/s3rver-tests.ts index afa7e9227..d8f25f4fb 100644 --- a/s3rver/s3rver-tests.ts +++ b/s3rver/s3rver-tests.ts @@ -1,14 +1,14 @@ -/// - -import S3rver = require('s3rver'); - -var s3rver = new S3rver({ - port: 5694, - hostname: 'localhost', - silent: true, - indexDocument: 'index.html', - errorDocument: '', - directory: '/tmp/s3rver_test_directory' -}).run((err, hostname, port, directory) => {}); - -s3rver.close(); +/// + +import S3rver = require('s3rver'); + +var s3rver = new S3rver({ + port: 5694, + hostname: 'localhost', + silent: true, + indexDocument: 'index.html', + errorDocument: '', + directory: '/tmp/s3rver_test_directory' +}).run((err, hostname, port, directory) => {}); + +s3rver.close(); diff --git a/s3rver/s3rver.d.ts b/s3rver/s3rver.d.ts index e34650986..3eb6c73be 100644 --- a/s3rver/s3rver.d.ts +++ b/s3rver/s3rver.d.ts @@ -1,32 +1,32 @@ -// Type definitions for S3rver -// Project: https://github.com/jamhall/s3rver -// Definitions by: David Broder-Rodgers -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare module "s3rver" { - import * as http from "http"; - - class S3rver { - constructor(options: S3rverOptions) - setPort(port: number): S3rver; - setHostname(hostname: string): S3rver; - setDirectory(directory: string): S3rver; - setSilent(silent: boolean): S3rver; - setIndexDocument(indexDocument: string): S3rver; - setErrorDocument(errorDocument: string): S3rver; - run(callback: (error: Error, hostname: string, port: number, directory: string) => void): http.Server; - } - - interface S3rverOptions { - port?: number; - hostname?: string; - silent?: boolean; - indexDocument?: string; - errorDocument?: string; - directory: string; - } - - export = S3rver; -} +// Type definitions for S3rver +// Project: https://github.com/jamhall/s3rver +// Definitions by: David Broder-Rodgers +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "s3rver" { + import * as http from "http"; + + class S3rver { + constructor(options: S3rverOptions) + setPort(port: number): S3rver; + setHostname(hostname: string): S3rver; + setDirectory(directory: string): S3rver; + setSilent(silent: boolean): S3rver; + setIndexDocument(indexDocument: string): S3rver; + setErrorDocument(errorDocument: string): S3rver; + run(callback: (error: Error, hostname: string, port: number, directory: string) => void): http.Server; + } + + interface S3rverOptions { + port?: number; + hostname?: string; + silent?: boolean; + indexDocument?: string; + errorDocument?: string; + directory: string; + } + + export = S3rver; +} diff --git a/sammyjs/sammyjs-tests.ts b/sammyjs/sammyjs-tests.ts index 1aa151d6e..6a54a8019 100644 --- a/sammyjs/sammyjs-tests.ts +++ b/sammyjs/sammyjs-tests.ts @@ -1,554 +1,554 @@ -/// - -function test_general() { - // Example from homepage - var app = Sammy('#main', function () { - var _this: Sammy.Application = this; - _this.use('Mustache'); - _this.get('#/', function () { - var _this: Sammy.RenderContext; - _this.load('posts.json') - .renderEach('post.mustache') - .swap(); - }); - }); - - app.run('#/'); - - var _this: Sammy.Application; - _this.get('#/', function (context) { - var _this: Sammy.RenderContext; - _this.load('data/items.json') - .then(function (items) { - $.each(items, function (i, item) { - context.log(item.title, '-', item.artist); - }); - }); - }); -} - -function test_app() { - var s = new Sammy.Object({ first_name: 'Sammy', last_name: 'Davis Jr.' }); - s.toHTML(); - - var app = $.sammy(function () { - - var current_user = false; - function checkLoggedIn(callback) { - var _this: Sammy.EventContext; - if (!current_user) { - $.getJSON('/session', function (json) { - if (json.login) { - current_user = json; - callback(); - } else { - current_user = false; - _this.redirect('#/login'); - } - }); - } else { - callback(); - } - }; - var _this: Sammy.Application; - _this.around(checkLoggedIn); - }); - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.before('#/route', function () { }); - _this.before({ except: { path: '#/route' } }, function () { - _this.log('not before #/route'); - }); - _this.get('#/', function () { }); - _this.get('#/route', function () { }); - }); - - var app = $.sammy(), - context = { verb: 'get', path: '#/mypath' }; - - app.contextMatchesOptions(context, '#/mypath'); - app.contextMatchesOptions(context, '#/otherpath'); - app.contextMatchesOptions(context, { only: { path: '#/mypath' } }); - app.contextMatchesOptions(context, { only: { path: '#/otherpath' } }); - app.contextMatchesOptions(context, /path/); - app.contextMatchesOptions(context, /^path/); - app.contextMatchesOptions(context, { only: { verb: 'get' } }); - app.contextMatchesOptions(context, { only: { verb: 'post' } }); - app.contextMatchesOptions(context, { except: { verb: 'post' } }); - app.contextMatchesOptions(context, { except: { verb: 'get' } }); - app.contextMatchesOptions(context, { except: { path: '#/otherpath' } }); - app.contextMatchesOptions(context, { except: { path: '#/mypath' } }); - app.contextMatchesOptions(context, { path: ['#/mypath', '#/otherpath'] }); - app.contextMatchesOptions(context, { path: ['#/otherpath', '#/thirdpath'] }); - app.contextMatchesOptions(context, { only: { path: ['#/mypath', '#/otherpath'] } }); - app.contextMatchesOptions(context, { only: { path: ['#/otherpath', '#/thirdpath'] } }); - app.contextMatchesOptions(context, { except: { path: ['#/mypath', '#/otherpath'] } }); - app.contextMatchesOptions(context, { except: { path: ['#/otherpath', '#/thirdpath'] } }); - - var app = $.sammy(function (app) { - var _this: Sammy.Application; - $.each([1, 2, 3], function (i, num) { - app.helper('helper' + num, function () { - _this.log("I'm helper number " + num); - }); - }); - _this.get('#/', function () { - }); - }); - - var app = $.sammy(function () { - var _this: Sammy.Application; - var better = _this.helpers({ - upcase: function (text) { - return text.toString().toUpperCase(); - } - }); - better.get('#/', function () { - $('#main').html(better.upcase($('#main').text())); - }); - }); - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.mapRoutes([ - ['get', '#/', function () { }], - ['post', '#/create', 'addUser'], - [/dowhatever/, function () { }] - ]); - }); - - var app = $.sammy(function () { }); - $(function () { - app.run(); - }); - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.setLocationProxy(new Sammy.DataLocationProxy(_this)); - }); - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.swap = function (content, callback) { - var context = _this; - context.$element().fadeOut('slow', function () { - context.$element().html(content); - context.$element().fadeIn('slow', function () { - if (callback) { - callback.apply(this); - } - }); - }); - }; - }); - - var MyPlugin = function (app, prepend) { - var _this: Sammy.Application; - _this.helpers({ - myhelper: function (text) { - alert(prepend + " " + text); - } - }); - }; - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.use(MyPlugin, '_this is my plugin'); - _this.get('#/', function () { - }); - }); - - $.sammy(function () { - var _this: Sammy.Application; - _this.use('Mustache'); - _this.use('Storage'); - }); -} - -function test_misc() { - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.setLocationProxy(new Sammy.DataLocationProxy(_this, 'location', 'rel')); - _this.get('about', function () { - var _this: Sammy.EventContext; - _this.partial('about.html'); - }); - }); - - $.sammy(function () { - var _this: Sammy.Application; - _this.get('#/:name', function () { - var _evt: Sammy.EventContext = this; - if (_evt.params['name'] == 'sammy') { - _evt.partial('name.html.erb', { name: 'Sammy' }); - } else { - _evt.redirect('#/somewhere-else') - } - }); - }); - - function evtContextTests() { - var _this: Sammy.EventContext; - _this.redirect('#/other/route'); - _this.redirect('#', 'other', 'route'); - _this.render('mytemplate.mustache', { name: 'quirkey' }) - .appendTo('ul'); - _this.renderEach('mytemplate.mustache', [{ name: 'quirkey' }, { name: 'endor' }]); - - var item = { - name: 'My Item', - price: '$25.50', - meta: { - id: '123' - } - }; - var form = new Sammy.FormBuilder('item', item); - form.text('name'); - - var options = [ - ['Small', 's'], - ['Medium', 'm'], - ['Large', 'l'] - ]; - form.select('size', options); - - $.sammy(function () { - var _this: Sammy.Application; - _this.use('GoogleAnalytics') - _this.get('#/dont/track/me', function () { - var evt: Sammy.GoogleAnalytics = this; - evt.noTrack(); - }); - }); - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.use(Sammy.Haml); - _this.get('#/hello/:name', function () { - var evt: Sammy.Haml = this; - evt.title = 'Hello!'; - evt.name = evt.params.name; - evt.partial('mytemplate.haml'); - }); - }); - app.run() - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.use('Handlebars', 'hb'); - _this.get('#/hello/:name', function () { - var evt: Sammy.Handlebars = this; - evt.title = 'Hello!' - evt.name = evt.params.name; - evt.partial('mytemplate.hb'); - }); - }); - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.use('Handlebars', 'hb'); - _this.get('#/hello/:name/to/:friend', function (context: Sammy.Handlebars) { - context.load('mypartial.hb') - .then(function (partial) { - context.partials = { hello_friend: partial }; - context.name = context.params.name; - // dynamically add a property to the context - (context).friend = context.params.friend; - context.partial('mytemplate.hb'); - }); - }); - }); - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.use('Hogan', 'hg'); - _this.get('#/hello/:name', function () { - var evt: Sammy.Hogan = this; - evt.title = 'Hello!' - evt.name = evt.params.name; - evt.partial('mytemplate.hg'); - }); - }); - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.use('Hogan', 'hg'); - _this.get('#/hello/:name/to/:friend', function (context) { - context.load('mypartial.hg') - .then(function (partial) { - context.partials = { hello_friend: partial }; - context.name = context.params.name; - context.friend = context.params.friend; - context.partial('mytemplate.hg'); - }); - }); - }); - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.use(Sammy.JSON); - _this.get('#/', function () { - var evt: Sammy.JSON = this; - evt.json({ user_id: 123 }); - evt.json("{\"user_id\":\"123\"}"); - evt.json("{\"user_id\":\"123\"}").user_id; - }); - }) - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.use('Mustache', 'ms'); - _this.get('#/hello/:name', function () { - var evt: Sammy.Mustache = this; - evt.title = 'Hello!' - evt.name = evt.params.name; - evt.partial('mytemplate.ms'); - }); - }); - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.use('Mustache', 'ms'); - _this.get('#/hello/:name/to/:friend', function (context: Sammy.Mustache) { - context.load('mypartial.ms') - .then(function (partial) { - context.partials = { hello_friend: partial }; - context.name = context.params.name; - (context).friend = context.params.friend; - context.partial('mytemplate.ms'); - }); - }); - }); - - var app = $.sammy(function (app) { - var _this: Sammy.Application; - _this.use(Sammy.NestedParams); - _this.post('#/parse_me', function (context) { - $.log(context.params); - }); - }); - }; - - var _this: Sammy.Application; - _this.use('Storage'); - _this.use('OAuth2'); - _this.oauthorize = "/oauth/authorize"; - _this.requireOAuth(); - _this.requireOAuth("/private"); - _this.before(function (context) { return context.requireOAuth(); }) - _this.get("/private", function (context) { - _this.requireOAuth(function () { }); - }); - _this.bind("oauth.connected", function () { $("#signin").hide() }); - _this.bind("oauth.disconnected", function () { $("#signin").show() }); - _this.bind("oauth.denied", function (evt, error) { - evt.partial("admin/views/no_access.tmpl", { error: error.message }); - }); - _this.get("#/signout", function (context) { - context.loseAccessToken(); - context.redirect("#/"); - }); - - _this.get('#/', function () { - this.render('mytemplate.template', { name: 'test' }); - }); - - _this.send($.getJSON, '/app.json') - .then(function (json) { - $('#message').text(json['message']); - } - ); - - _this.get('#/', function () { - var evt: Sammy.EventContext = this; - evt.load('myfile.txt') - .then(function (content) { - $('#main').html(content); - }); - }); - - _this.get('#/', function () { - var evt: Sammy.EventContext = this; - evt.load('mytext.json') - .then(function (content) { - var context = this, - data = JSON.parse(content); - context.wait(); - $.post(data.url, {}, function (response) { - context.next(JSON.parse(response)); - }); - }) - .then(function (data) { - $('#message').text(data.status); - }); - }); - - var store = new Sammy.Store({ name: 'mystore', element: '#element', type: 'local' }); - store.set('foo', 'bar'); - store.get('foo'); - store.set('json', { obj: '_this is an obj' }); - store.get('json'); - store.keys(); - store.clear('foo'); - store.keys(); - store.clearAll(); - store.keys(); - - store.each(function (key, value) { - Sammy.log('key', key, 'value', value); - }); - - store = new Sammy.Store(); - store.exists('foo'); - store.fetch('foo', function () { - return 'bar!'; - }); - store.get('foo'); - store.fetch('foo', function () { - return 'baz!'; - }); - - store = new Sammy.Store(); - store.set('one', 'two'); - store.set('two', 'three'); - store.set('1', 'two'); - var returned = store.filter(function (key, value) { - return value === 'two'; - }); - - var store = new Sammy.Store(); - store.load('mytemplate', '/mytemplate.tpl', function () { - store.get('mytemplate') - }); - - store = new Sammy.Store({ name: 'kvo' }); - $('body').bind('set-kvo-foo', function (e, data?) { - Sammy.log(data.key + ' changed to ' + data.value); - }); - store.set('foo', 'bar'); - - $.sammy(function () { - _this.use('Template'); - _this.get('#/', function () { - var evt: Sammy.EventContext = this; - // Adding a dynamic property - (evt).user = { name: 'Aaron Quint' }; - evt.partial('user.template'); - }) - }); - - _this.use(Sammy.Template, 'tpl'); - _this.get('#/', function () { - this.partial('myfile.tpl'); - }); - _this.get('#/', function () { - this.template('myform.tpl', { form: "
" }, { escape_html: false }); - }); -} - -function test_routes() { - var _this: Sammy.Application; - - _this.route('get', '#/', function () { - }); - _this.put('#/post/form', function () { - return false; - }); - _this.get('/test/123', function () { - }); - - _this.get('#/by_name/:name', function () { - alert(this.params['name']); - }); - _this.get(/\#\/by_name\/(.*)/, function () { - alert(this.params['splat']); - }); - _this.get('#/by_name/:name', function () { - this.redirect('#', this.params['name']); - }); - - _this.get('#/by_name/:name', function (context) { - context.redirect('#', this.params['name']); - }); -} - -function test_events() { - var _this: Sammy.Application; - - _this.bind('db-loaded', function (e, data) { - var _this: Sammy.EventContext; - _this.redirect('#/'); - }); - - var app1 = $.sammy(function () { - var _this: Sammy.Application; - _this.bind('test', function () { - var _this: Sammy.EventContext; - _this.trigger('other-event'); - }); - }); - app1.trigger('other-event'); - - var app2 = $.sammy(function () { - var _this: Sammy.Application; - _this.bind('test', function (e, data) { - alert(data['my_data']); - }); - _this.get('#/', function () { - _this.trigger('test', { my_data: 'EVENTED!' }); - }); - }); -} - -function test_plugins() { - var MyPlugin = function (app) { - var _this: Sammy.Application; - _this.helpers({ - alert: function (message) { - _this.log("ALERT! " + message); - } - }); - }; - var app1 = $.sammy(function () { - var _this: Sammy.Application; - _this.use(MyPlugin); - _this.get('#/', function () { - var _this: Sammy.EventContext; - alert("I'm home"); - }); - }); - var MyAdvancedPlugin = function (app, prefix, suffix) { - var _this: Sammy.Application; - _this.helpers({ - alert: function (message) { - _this.log(prefix, message, suffix); - } - }); - }; - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.use(MyAdvancedPlugin, 'BEFORE!', 'AFTER!'); - _this.get('#/', function () { - alert("I'm home"); - }); - }); - - var dbLoadAndDisplay = function (app) { - var _this: Sammy.Application; - _this.get('#/', function () { - this.record = this.app.db[this.app.element_selector]; - this.app.swap(this.record.toHTML()); - }); - _this.bind('run', function () { - }); - }; - - var app1 = Sammy('#div_1', function () { - this.use(dbLoadAndDisplay); - }); - - var app2 = Sammy('#div_2', function () { - this.use(dbLoadAndDisplay); - }); +/// + +function test_general() { + // Example from homepage + var app = Sammy('#main', function () { + var _this: Sammy.Application = this; + _this.use('Mustache'); + _this.get('#/', function () { + var _this: Sammy.RenderContext; + _this.load('posts.json') + .renderEach('post.mustache') + .swap(); + }); + }); + + app.run('#/'); + + var _this: Sammy.Application; + _this.get('#/', function (context) { + var _this: Sammy.RenderContext; + _this.load('data/items.json') + .then(function (items) { + $.each(items, function (i, item) { + context.log(item.title, '-', item.artist); + }); + }); + }); +} + +function test_app() { + var s = new Sammy.Object({ first_name: 'Sammy', last_name: 'Davis Jr.' }); + s.toHTML(); + + var app = $.sammy(function () { + + var current_user = false; + function checkLoggedIn(callback) { + var _this: Sammy.EventContext; + if (!current_user) { + $.getJSON('/session', function (json) { + if (json.login) { + current_user = json; + callback(); + } else { + current_user = false; + _this.redirect('#/login'); + } + }); + } else { + callback(); + } + }; + var _this: Sammy.Application; + _this.around(checkLoggedIn); + }); + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.before('#/route', function () { }); + _this.before({ except: { path: '#/route' } }, function () { + _this.log('not before #/route'); + }); + _this.get('#/', function () { }); + _this.get('#/route', function () { }); + }); + + var app = $.sammy(), + context = { verb: 'get', path: '#/mypath' }; + + app.contextMatchesOptions(context, '#/mypath'); + app.contextMatchesOptions(context, '#/otherpath'); + app.contextMatchesOptions(context, { only: { path: '#/mypath' } }); + app.contextMatchesOptions(context, { only: { path: '#/otherpath' } }); + app.contextMatchesOptions(context, /path/); + app.contextMatchesOptions(context, /^path/); + app.contextMatchesOptions(context, { only: { verb: 'get' } }); + app.contextMatchesOptions(context, { only: { verb: 'post' } }); + app.contextMatchesOptions(context, { except: { verb: 'post' } }); + app.contextMatchesOptions(context, { except: { verb: 'get' } }); + app.contextMatchesOptions(context, { except: { path: '#/otherpath' } }); + app.contextMatchesOptions(context, { except: { path: '#/mypath' } }); + app.contextMatchesOptions(context, { path: ['#/mypath', '#/otherpath'] }); + app.contextMatchesOptions(context, { path: ['#/otherpath', '#/thirdpath'] }); + app.contextMatchesOptions(context, { only: { path: ['#/mypath', '#/otherpath'] } }); + app.contextMatchesOptions(context, { only: { path: ['#/otherpath', '#/thirdpath'] } }); + app.contextMatchesOptions(context, { except: { path: ['#/mypath', '#/otherpath'] } }); + app.contextMatchesOptions(context, { except: { path: ['#/otherpath', '#/thirdpath'] } }); + + var app = $.sammy(function (app) { + var _this: Sammy.Application; + $.each([1, 2, 3], function (i, num) { + app.helper('helper' + num, function () { + _this.log("I'm helper number " + num); + }); + }); + _this.get('#/', function () { + }); + }); + + var app = $.sammy(function () { + var _this: Sammy.Application; + var better = _this.helpers({ + upcase: function (text) { + return text.toString().toUpperCase(); + } + }); + better.get('#/', function () { + $('#main').html(better.upcase($('#main').text())); + }); + }); + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.mapRoutes([ + ['get', '#/', function () { }], + ['post', '#/create', 'addUser'], + [/dowhatever/, function () { }] + ]); + }); + + var app = $.sammy(function () { }); + $(function () { + app.run(); + }); + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.setLocationProxy(new Sammy.DataLocationProxy(_this)); + }); + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.swap = function (content, callback) { + var context = _this; + context.$element().fadeOut('slow', function () { + context.$element().html(content); + context.$element().fadeIn('slow', function () { + if (callback) { + callback.apply(this); + } + }); + }); + }; + }); + + var MyPlugin = function (app, prepend) { + var _this: Sammy.Application; + _this.helpers({ + myhelper: function (text) { + alert(prepend + " " + text); + } + }); + }; + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.use(MyPlugin, '_this is my plugin'); + _this.get('#/', function () { + }); + }); + + $.sammy(function () { + var _this: Sammy.Application; + _this.use('Mustache'); + _this.use('Storage'); + }); +} + +function test_misc() { + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.setLocationProxy(new Sammy.DataLocationProxy(_this, 'location', 'rel')); + _this.get('about', function () { + var _this: Sammy.EventContext; + _this.partial('about.html'); + }); + }); + + $.sammy(function () { + var _this: Sammy.Application; + _this.get('#/:name', function () { + var _evt: Sammy.EventContext = this; + if (_evt.params['name'] == 'sammy') { + _evt.partial('name.html.erb', { name: 'Sammy' }); + } else { + _evt.redirect('#/somewhere-else') + } + }); + }); + + function evtContextTests() { + var _this: Sammy.EventContext; + _this.redirect('#/other/route'); + _this.redirect('#', 'other', 'route'); + _this.render('mytemplate.mustache', { name: 'quirkey' }) + .appendTo('ul'); + _this.renderEach('mytemplate.mustache', [{ name: 'quirkey' }, { name: 'endor' }]); + + var item = { + name: 'My Item', + price: '$25.50', + meta: { + id: '123' + } + }; + var form = new Sammy.FormBuilder('item', item); + form.text('name'); + + var options = [ + ['Small', 's'], + ['Medium', 'm'], + ['Large', 'l'] + ]; + form.select('size', options); + + $.sammy(function () { + var _this: Sammy.Application; + _this.use('GoogleAnalytics') + _this.get('#/dont/track/me', function () { + var evt: Sammy.GoogleAnalytics = this; + evt.noTrack(); + }); + }); + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.use(Sammy.Haml); + _this.get('#/hello/:name', function () { + var evt: Sammy.Haml = this; + evt.title = 'Hello!'; + evt.name = evt.params.name; + evt.partial('mytemplate.haml'); + }); + }); + app.run() + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.use('Handlebars', 'hb'); + _this.get('#/hello/:name', function () { + var evt: Sammy.Handlebars = this; + evt.title = 'Hello!' + evt.name = evt.params.name; + evt.partial('mytemplate.hb'); + }); + }); + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.use('Handlebars', 'hb'); + _this.get('#/hello/:name/to/:friend', function (context: Sammy.Handlebars) { + context.load('mypartial.hb') + .then(function (partial) { + context.partials = { hello_friend: partial }; + context.name = context.params.name; + // dynamically add a property to the context + (context).friend = context.params.friend; + context.partial('mytemplate.hb'); + }); + }); + }); + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.use('Hogan', 'hg'); + _this.get('#/hello/:name', function () { + var evt: Sammy.Hogan = this; + evt.title = 'Hello!' + evt.name = evt.params.name; + evt.partial('mytemplate.hg'); + }); + }); + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.use('Hogan', 'hg'); + _this.get('#/hello/:name/to/:friend', function (context) { + context.load('mypartial.hg') + .then(function (partial) { + context.partials = { hello_friend: partial }; + context.name = context.params.name; + context.friend = context.params.friend; + context.partial('mytemplate.hg'); + }); + }); + }); + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.use(Sammy.JSON); + _this.get('#/', function () { + var evt: Sammy.JSON = this; + evt.json({ user_id: 123 }); + evt.json("{\"user_id\":\"123\"}"); + evt.json("{\"user_id\":\"123\"}").user_id; + }); + }) + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.use('Mustache', 'ms'); + _this.get('#/hello/:name', function () { + var evt: Sammy.Mustache = this; + evt.title = 'Hello!' + evt.name = evt.params.name; + evt.partial('mytemplate.ms'); + }); + }); + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.use('Mustache', 'ms'); + _this.get('#/hello/:name/to/:friend', function (context: Sammy.Mustache) { + context.load('mypartial.ms') + .then(function (partial) { + context.partials = { hello_friend: partial }; + context.name = context.params.name; + (context).friend = context.params.friend; + context.partial('mytemplate.ms'); + }); + }); + }); + + var app = $.sammy(function (app) { + var _this: Sammy.Application; + _this.use(Sammy.NestedParams); + _this.post('#/parse_me', function (context) { + $.log(context.params); + }); + }); + }; + + var _this: Sammy.Application; + _this.use('Storage'); + _this.use('OAuth2'); + _this.oauthorize = "/oauth/authorize"; + _this.requireOAuth(); + _this.requireOAuth("/private"); + _this.before(function (context) { return context.requireOAuth(); }) + _this.get("/private", function (context) { + _this.requireOAuth(function () { }); + }); + _this.bind("oauth.connected", function () { $("#signin").hide() }); + _this.bind("oauth.disconnected", function () { $("#signin").show() }); + _this.bind("oauth.denied", function (evt, error) { + evt.partial("admin/views/no_access.tmpl", { error: error.message }); + }); + _this.get("#/signout", function (context) { + context.loseAccessToken(); + context.redirect("#/"); + }); + + _this.get('#/', function () { + this.render('mytemplate.template', { name: 'test' }); + }); + + _this.send($.getJSON, '/app.json') + .then(function (json) { + $('#message').text(json['message']); + } + ); + + _this.get('#/', function () { + var evt: Sammy.EventContext = this; + evt.load('myfile.txt') + .then(function (content) { + $('#main').html(content); + }); + }); + + _this.get('#/', function () { + var evt: Sammy.EventContext = this; + evt.load('mytext.json') + .then(function (content) { + var context = this, + data = JSON.parse(content); + context.wait(); + $.post(data.url, {}, function (response) { + context.next(JSON.parse(response)); + }); + }) + .then(function (data) { + $('#message').text(data.status); + }); + }); + + var store = new Sammy.Store({ name: 'mystore', element: '#element', type: 'local' }); + store.set('foo', 'bar'); + store.get('foo'); + store.set('json', { obj: '_this is an obj' }); + store.get('json'); + store.keys(); + store.clear('foo'); + store.keys(); + store.clearAll(); + store.keys(); + + store.each(function (key, value) { + Sammy.log('key', key, 'value', value); + }); + + store = new Sammy.Store(); + store.exists('foo'); + store.fetch('foo', function () { + return 'bar!'; + }); + store.get('foo'); + store.fetch('foo', function () { + return 'baz!'; + }); + + store = new Sammy.Store(); + store.set('one', 'two'); + store.set('two', 'three'); + store.set('1', 'two'); + var returned = store.filter(function (key, value) { + return value === 'two'; + }); + + var store = new Sammy.Store(); + store.load('mytemplate', '/mytemplate.tpl', function () { + store.get('mytemplate') + }); + + store = new Sammy.Store({ name: 'kvo' }); + $('body').bind('set-kvo-foo', function (e, data?) { + Sammy.log(data.key + ' changed to ' + data.value); + }); + store.set('foo', 'bar'); + + $.sammy(function () { + _this.use('Template'); + _this.get('#/', function () { + var evt: Sammy.EventContext = this; + // Adding a dynamic property + (evt).user = { name: 'Aaron Quint' }; + evt.partial('user.template'); + }) + }); + + _this.use(Sammy.Template, 'tpl'); + _this.get('#/', function () { + this.partial('myfile.tpl'); + }); + _this.get('#/', function () { + this.template('myform.tpl', { form: "
" }, { escape_html: false }); + }); +} + +function test_routes() { + var _this: Sammy.Application; + + _this.route('get', '#/', function () { + }); + _this.put('#/post/form', function () { + return false; + }); + _this.get('/test/123', function () { + }); + + _this.get('#/by_name/:name', function () { + alert(this.params['name']); + }); + _this.get(/\#\/by_name\/(.*)/, function () { + alert(this.params['splat']); + }); + _this.get('#/by_name/:name', function () { + this.redirect('#', this.params['name']); + }); + + _this.get('#/by_name/:name', function (context) { + context.redirect('#', this.params['name']); + }); +} + +function test_events() { + var _this: Sammy.Application; + + _this.bind('db-loaded', function (e, data) { + var _this: Sammy.EventContext; + _this.redirect('#/'); + }); + + var app1 = $.sammy(function () { + var _this: Sammy.Application; + _this.bind('test', function () { + var _this: Sammy.EventContext; + _this.trigger('other-event'); + }); + }); + app1.trigger('other-event'); + + var app2 = $.sammy(function () { + var _this: Sammy.Application; + _this.bind('test', function (e, data) { + alert(data['my_data']); + }); + _this.get('#/', function () { + _this.trigger('test', { my_data: 'EVENTED!' }); + }); + }); +} + +function test_plugins() { + var MyPlugin = function (app) { + var _this: Sammy.Application; + _this.helpers({ + alert: function (message) { + _this.log("ALERT! " + message); + } + }); + }; + var app1 = $.sammy(function () { + var _this: Sammy.Application; + _this.use(MyPlugin); + _this.get('#/', function () { + var _this: Sammy.EventContext; + alert("I'm home"); + }); + }); + var MyAdvancedPlugin = function (app, prefix, suffix) { + var _this: Sammy.Application; + _this.helpers({ + alert: function (message) { + _this.log(prefix, message, suffix); + } + }); + }; + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.use(MyAdvancedPlugin, 'BEFORE!', 'AFTER!'); + _this.get('#/', function () { + alert("I'm home"); + }); + }); + + var dbLoadAndDisplay = function (app) { + var _this: Sammy.Application; + _this.get('#/', function () { + this.record = this.app.db[this.app.element_selector]; + this.app.swap(this.record.toHTML()); + }); + _this.bind('run', function () { + }); + }; + + var app1 = Sammy('#div_1', function () { + this.use(dbLoadAndDisplay); + }); + + var app2 = Sammy('#div_2', function () { + this.use(dbLoadAndDisplay); + }); } \ No newline at end of file diff --git a/sammyjs/sammyjs-tests.ts.tscparams b/sammyjs/sammyjs-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/sammyjs/sammyjs-tests.ts.tscparams +++ b/sammyjs/sammyjs-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/sammyjs/sammyjs.d.ts b/sammyjs/sammyjs.d.ts index 5d980a09f..185193bab 100644 --- a/sammyjs/sammyjs.d.ts +++ b/sammyjs/sammyjs.d.ts @@ -1,286 +1,286 @@ -// Type definitions for Sammy.js -// Project: http://sammyjs.org/ -// Definitions by: Boris Yankov , Oisin Grehan -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare function Sammy(): Sammy.Application; -declare function Sammy(selector: string): Sammy.Application; -declare function Sammy(handler: Function): Sammy.Application; -declare function Sammy(selector: string, handler: Function): Sammy.Application; - -declare module Sammy { - interface SammyFunc { - (): Sammy.Application; - (selector: string): Sammy.Application; - (handler: Function): Sammy.Application; - (selector: string, handler: Function): Sammy.Application; - } - - export function Cache(app, options); - export function DataCacheProxy(initial, $element); - export var DataLocationProxy:DataLocationProxy; - export function DefaultLocationProxy(app, run_interval_every); - export function EJS(app, method_alias); - - export function Exceptional(app, errorReporter); - export function Flash(app); - export var FormBuilder: FormBuilder; - export function Form(app); // formFor ( name, object, content_callback ) - - export function Haml(app, method_alias); - export function Handlebars(app, method_alias); - export function Hogan(app, method_alias); - export function Hoptoad(app, errorReporter); - export function JSON(app); - export function Meld(app, method_alias); - export function MemoryCacheProxy(initial); - export function Mustache(app, method_alias); - export function NestedParams(app); - export function OAuth2(app); - export function PathLocationProxy(app); - export function Pure(app, method_alias); - export function PushLocationProxy(app); - export function Session(app, options); - export function Storage(app); - export var Store: Store; - - export function Title(); - export function Template(app, method_alias); - export function Tmpl(app, method_alias); - export function addLogger(logger); - export function log(...args:any[]); - - export class Object { - - constructor(obj: any); - - escapeHTML(s: string): string; - h(s: string): string; - - has(key: string): boolean; - join(...args: any[]): string; - keys(attributes_only?: boolean): string[]; - log(...args: any[]): void; - toHTML(): string; - toHash(): any; - toString(include_functions?: boolean): string; - } - - export interface Application extends Object { - - ROUTE_VERBS: string[]; - APP_EVENTS: string[]; - - (appFn: Function); - - $element(selector?: string): JQuery; - after(callback: Function): Application; - any(verb: string, path: string, callback: Function): void; - around(callback: Function): Application; - before(callback: Function): Application; - before(options: any, callback: Function): Application; - bind(name: string, callback: Function): Application; - bind(name: string, data: any, callback: Function): Application; - bindToAllEvents(callback: Function): Application; - clearTemplateCache(): any; - contextMatchesOptions(context: any, match_options: any, positive?: boolean): boolean; - del(path: string, callback: Function): Application; - del(path: RegExp, callback: Function): Application; - destroy(): Application; - error(message: string, original_error: Error): void; - eventNamespace(): string; - get(path: string, callback: Function): Application; - get(path: RegExp, callback: Function): Application; - getLocation(): string; - helper(name: string, method: Function): any; // Behaviour similar to _.extend - helpers(extensions: any): any; // Behaviour similar to _.extend - isRunning(): boolean; - log(...params: any[]): void; - lookupRoute(verb: string, path: string): any; - mapRoutes(route_array: any[]): Application; - notFound(verb: string, path: string): any; - post(path: string, callback: Function): Application; - post(path: RegExp, callback: Function): Application; - put(path: string, callback: Function): Application; - put(path: RegExp, callback: Function): Application; - refresh(): Application; - routablePath(path: string): string; - route(verb: string, path: string, callback: Function): Application; - route(verb: string, path: RegExp, callback: Function): Application; - run(start_url?: string): Application; - runRoute(verb: string, path?: string, params?: any, target?: any): any; - send(...params: any[]); - setLocation(new_location: string): string; - setLocationProxy(new_proxy: DataLocationProxy): void; - swap(content: any, callback: Function): any; - templateCache(key: string, value: any): any; - toString(): string; - trigger(name: string, data?: any): Application; - unload(): Application; - use(...params: any[]): void; - last_location: string[]; - - // Features provided by oauth2 plugin - oauthorize: string; - requireOAuth(); - requireOAuth(path?:string); - requireOAuth(callback?: Function); - } - - export interface DataLocationProxy { - - new (app, run_interval_every?): DataLocationProxy; - new (app, data_name, href_attribute): DataLocationProxy; - - fullPath(location_obj): string; - bind(): void; - unbind(): void; - setLocation(new_location: string): string; - _startPolling(every: number): void; - } - - export interface EventContext extends Object { - - new (app, verb, path, params, target); - - $element(): JQuery; - engineFor(engine: any): any; - eventNamespace(): string; - interpolate(content: any, data: any, engine: any, partials): EventContext; - json(str: any): any; - json(str: string): any; - load(location: any, options?: any, callback?: Function): any; - loadPartials(partials); - notFound(): any; - partial(location: string, data?: any, callback?: Function, partials?): RenderContext; - partials: any; - params: any; - redirect(...params: any[]): void; - render(location: string, data?: any, callback?: Function, partials?): RenderContext; - renderEach(location: any, data?: { name: string;data?:any}[],callback?: Function): RenderContext; - send(...params: any[]): RenderContext; - swap(contents: any, callback: Function): string; - toString(): string; - trigger(name: string, data?: any): EventContext; - - // Provided by common sammy modules: - name: any; - title: any; - } - - export interface FormBuilder { - - new (name, object); - - checkbox(keypath: string, value: any, ...attributes: any[]): string; - close(): string; - hidden(keypath: string, ...attributes: any[]): string; - label(keypath: string, content: any, ...attributes: any[]): string; - open(...attributes: any[]); - password(keypath: string, ...attributes: any[]): string; - radio(keypath: string, value: any, ...attributes: any[]): string; - select(keypath: string, options: any, ...attributes: any[]): string; - submit(...attributes: any[]): string; - text(keypath: string, ...attributes: any[]): string; - textarea(keypath: string, ...attributes: any[]): string; - } - - export interface Form { - formFor(name: string, object: any, content_callback: Function): FormBuilder; - } - - export interface GoogleAnalytics { - - new (app, tracker); - - noTrack(); - track(path); - } - - export interface Haml extends EventContext { } - - export interface Handlebars extends EventContext { } - - export interface Hogan extends EventContext { } - - export interface JSON extends EventContext { } - - export interface Mustache extends EventContext { } - - export interface RenderContext extends Object { - - new (event_context); - - appendTo(selector: string): RenderContext; - collect(array: any[], callback: Function, now?: boolean): RenderContext; - interpolate(data: any, engine?: any, retain?: boolean): RenderContext; - load(location: string, options?: any, callback?: Function): RenderContext; - loadPartials(partials?: any): RenderContext; - next(content: any): void; - partial(location: string, callback: Function, partials): RenderContext; - partial(location: string, data: any, callback: Function, partials): RenderContext; - prependTo(selector: string): RenderContext; - render(callback: Function): RenderContext; - render(location: string, data: any): RenderContext; - render(location: string, callback: Function, partials?: any): RenderContext; - render(location: string, data: any, callback: Function): RenderContext; - render(location: string, data: any, callback: Function, partials: any): RenderContext; - renderEach(location: string, name?: string, data?: any, callback?: Function): RenderContext; - replace(selector: string): RenderContext; - send(...params: any[]): RenderContext; - swap(callback?: Function): RenderContext; - then(callback: Function): RenderContext; - trigger(name, data); - wait(): void; - } - - export interface StoreOptions { - name?: string; - element?: string; - type?: string; - memory?: any; - data?: any; - cookie?: any; - local?: any; - session?: any; - } - - export interface Store { - - stores: any; - - new (options?:any); - - clear(key: string): any; - clearAll(): void; - each(callback: Function): boolean; - exists(key: string): boolean; - fetch(key: string, callback: Function): any; - filter(callback: Function): boolean; - first(callback: Function): boolean; - get(key: string): any; - isAvailable(): boolean; - keys(): string[]; - load(key: string, path: string, callback: Function): void; - set(key: string, value: any): any; - - Cookie(name, element, options); - Data(name, element); - LocalStorage(name, element); - Memory(name, element); - SessionStorage(name, element); - isAvailable(type); - Template(app, method_alias); - } -} - -declare module "sammy" { - export = Sammy; -} - -interface JQueryStatic { - sammy: Sammy.SammyFunc; - log: Function; -} +// Type definitions for Sammy.js +// Project: http://sammyjs.org/ +// Definitions by: Boris Yankov , Oisin Grehan +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare function Sammy(): Sammy.Application; +declare function Sammy(selector: string): Sammy.Application; +declare function Sammy(handler: Function): Sammy.Application; +declare function Sammy(selector: string, handler: Function): Sammy.Application; + +declare module Sammy { + interface SammyFunc { + (): Sammy.Application; + (selector: string): Sammy.Application; + (handler: Function): Sammy.Application; + (selector: string, handler: Function): Sammy.Application; + } + + export function Cache(app, options); + export function DataCacheProxy(initial, $element); + export var DataLocationProxy:DataLocationProxy; + export function DefaultLocationProxy(app, run_interval_every); + export function EJS(app, method_alias); + + export function Exceptional(app, errorReporter); + export function Flash(app); + export var FormBuilder: FormBuilder; + export function Form(app); // formFor ( name, object, content_callback ) + + export function Haml(app, method_alias); + export function Handlebars(app, method_alias); + export function Hogan(app, method_alias); + export function Hoptoad(app, errorReporter); + export function JSON(app); + export function Meld(app, method_alias); + export function MemoryCacheProxy(initial); + export function Mustache(app, method_alias); + export function NestedParams(app); + export function OAuth2(app); + export function PathLocationProxy(app); + export function Pure(app, method_alias); + export function PushLocationProxy(app); + export function Session(app, options); + export function Storage(app); + export var Store: Store; + + export function Title(); + export function Template(app, method_alias); + export function Tmpl(app, method_alias); + export function addLogger(logger); + export function log(...args:any[]); + + export class Object { + + constructor(obj: any); + + escapeHTML(s: string): string; + h(s: string): string; + + has(key: string): boolean; + join(...args: any[]): string; + keys(attributes_only?: boolean): string[]; + log(...args: any[]): void; + toHTML(): string; + toHash(): any; + toString(include_functions?: boolean): string; + } + + export interface Application extends Object { + + ROUTE_VERBS: string[]; + APP_EVENTS: string[]; + + (appFn: Function); + + $element(selector?: string): JQuery; + after(callback: Function): Application; + any(verb: string, path: string, callback: Function): void; + around(callback: Function): Application; + before(callback: Function): Application; + before(options: any, callback: Function): Application; + bind(name: string, callback: Function): Application; + bind(name: string, data: any, callback: Function): Application; + bindToAllEvents(callback: Function): Application; + clearTemplateCache(): any; + contextMatchesOptions(context: any, match_options: any, positive?: boolean): boolean; + del(path: string, callback: Function): Application; + del(path: RegExp, callback: Function): Application; + destroy(): Application; + error(message: string, original_error: Error): void; + eventNamespace(): string; + get(path: string, callback: Function): Application; + get(path: RegExp, callback: Function): Application; + getLocation(): string; + helper(name: string, method: Function): any; // Behaviour similar to _.extend + helpers(extensions: any): any; // Behaviour similar to _.extend + isRunning(): boolean; + log(...params: any[]): void; + lookupRoute(verb: string, path: string): any; + mapRoutes(route_array: any[]): Application; + notFound(verb: string, path: string): any; + post(path: string, callback: Function): Application; + post(path: RegExp, callback: Function): Application; + put(path: string, callback: Function): Application; + put(path: RegExp, callback: Function): Application; + refresh(): Application; + routablePath(path: string): string; + route(verb: string, path: string, callback: Function): Application; + route(verb: string, path: RegExp, callback: Function): Application; + run(start_url?: string): Application; + runRoute(verb: string, path?: string, params?: any, target?: any): any; + send(...params: any[]); + setLocation(new_location: string): string; + setLocationProxy(new_proxy: DataLocationProxy): void; + swap(content: any, callback: Function): any; + templateCache(key: string, value: any): any; + toString(): string; + trigger(name: string, data?: any): Application; + unload(): Application; + use(...params: any[]): void; + last_location: string[]; + + // Features provided by oauth2 plugin + oauthorize: string; + requireOAuth(); + requireOAuth(path?:string); + requireOAuth(callback?: Function); + } + + export interface DataLocationProxy { + + new (app, run_interval_every?): DataLocationProxy; + new (app, data_name, href_attribute): DataLocationProxy; + + fullPath(location_obj): string; + bind(): void; + unbind(): void; + setLocation(new_location: string): string; + _startPolling(every: number): void; + } + + export interface EventContext extends Object { + + new (app, verb, path, params, target); + + $element(): JQuery; + engineFor(engine: any): any; + eventNamespace(): string; + interpolate(content: any, data: any, engine: any, partials): EventContext; + json(str: any): any; + json(str: string): any; + load(location: any, options?: any, callback?: Function): any; + loadPartials(partials); + notFound(): any; + partial(location: string, data?: any, callback?: Function, partials?): RenderContext; + partials: any; + params: any; + redirect(...params: any[]): void; + render(location: string, data?: any, callback?: Function, partials?): RenderContext; + renderEach(location: any, data?: { name: string;data?:any}[],callback?: Function): RenderContext; + send(...params: any[]): RenderContext; + swap(contents: any, callback: Function): string; + toString(): string; + trigger(name: string, data?: any): EventContext; + + // Provided by common sammy modules: + name: any; + title: any; + } + + export interface FormBuilder { + + new (name, object); + + checkbox(keypath: string, value: any, ...attributes: any[]): string; + close(): string; + hidden(keypath: string, ...attributes: any[]): string; + label(keypath: string, content: any, ...attributes: any[]): string; + open(...attributes: any[]); + password(keypath: string, ...attributes: any[]): string; + radio(keypath: string, value: any, ...attributes: any[]): string; + select(keypath: string, options: any, ...attributes: any[]): string; + submit(...attributes: any[]): string; + text(keypath: string, ...attributes: any[]): string; + textarea(keypath: string, ...attributes: any[]): string; + } + + export interface Form { + formFor(name: string, object: any, content_callback: Function): FormBuilder; + } + + export interface GoogleAnalytics { + + new (app, tracker); + + noTrack(); + track(path); + } + + export interface Haml extends EventContext { } + + export interface Handlebars extends EventContext { } + + export interface Hogan extends EventContext { } + + export interface JSON extends EventContext { } + + export interface Mustache extends EventContext { } + + export interface RenderContext extends Object { + + new (event_context); + + appendTo(selector: string): RenderContext; + collect(array: any[], callback: Function, now?: boolean): RenderContext; + interpolate(data: any, engine?: any, retain?: boolean): RenderContext; + load(location: string, options?: any, callback?: Function): RenderContext; + loadPartials(partials?: any): RenderContext; + next(content: any): void; + partial(location: string, callback: Function, partials): RenderContext; + partial(location: string, data: any, callback: Function, partials): RenderContext; + prependTo(selector: string): RenderContext; + render(callback: Function): RenderContext; + render(location: string, data: any): RenderContext; + render(location: string, callback: Function, partials?: any): RenderContext; + render(location: string, data: any, callback: Function): RenderContext; + render(location: string, data: any, callback: Function, partials: any): RenderContext; + renderEach(location: string, name?: string, data?: any, callback?: Function): RenderContext; + replace(selector: string): RenderContext; + send(...params: any[]): RenderContext; + swap(callback?: Function): RenderContext; + then(callback: Function): RenderContext; + trigger(name, data); + wait(): void; + } + + export interface StoreOptions { + name?: string; + element?: string; + type?: string; + memory?: any; + data?: any; + cookie?: any; + local?: any; + session?: any; + } + + export interface Store { + + stores: any; + + new (options?:any); + + clear(key: string): any; + clearAll(): void; + each(callback: Function): boolean; + exists(key: string): boolean; + fetch(key: string, callback: Function): any; + filter(callback: Function): boolean; + first(callback: Function): boolean; + get(key: string): any; + isAvailable(): boolean; + keys(): string[]; + load(key: string, path: string, callback: Function): void; + set(key: string, value: any): any; + + Cookie(name, element, options); + Data(name, element); + LocalStorage(name, element); + Memory(name, element); + SessionStorage(name, element); + isAvailable(type); + Template(app, method_alias); + } +} + +declare module "sammy" { + export = Sammy; +} + +interface JQueryStatic { + sammy: Sammy.SammyFunc; + log: Function; +} diff --git a/sammyjs/sammyjs.d.ts.tscparams b/sammyjs/sammyjs.d.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/sammyjs/sammyjs.d.ts.tscparams +++ b/sammyjs/sammyjs.d.ts.tscparams @@ -1 +1 @@ - + diff --git a/scroller/easyscroller.d.ts b/scroller/easyscroller.d.ts index fc0418a57..28359932f 100644 --- a/scroller/easyscroller.d.ts +++ b/scroller/easyscroller.d.ts @@ -1,15 +1,15 @@ -// Type definitions for Zynga EasyScroller -// Project: https://github.com/zynga/scroller -// Definitions by: Boris Yankov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -/// - -declare class EasyScroller { - constructor (content: any, options: ScrollerOptions); - - render(): void; - reflow(): void; - bindEvents(): void; -} +// Type definitions for Zynga EasyScroller +// Project: https://github.com/zynga/scroller +// Definitions by: Boris Yankov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +declare class EasyScroller { + constructor (content: any, options: ScrollerOptions); + + render(): void; + reflow(): void; + bindEvents(): void; +} diff --git a/scroller/scroller-tests.ts b/scroller/scroller-tests.ts index 411ddab92..6a5a29be9 100644 --- a/scroller/scroller-tests.ts +++ b/scroller/scroller-tests.ts @@ -1,260 +1,260 @@ -/// - -var clientWidth: any; -var clientHeight: any; -var render: any; - -var Tiling: any; - -function test_basic() { - var scrollerObj = new Scroller(function (left, top, zoom) { - }, { - scrollingY: false - }); - scrollerObj.setDimensions(1000, 1000, 3000, 3000); -} - -function test_canvas() { - var contentWidth = 2000; - var contentHeight = 2000; - var cellWidth = 100; - var cellHeight = 100; - var content = document.getElementById('content'); - var context = content.getContext('2d'); - var tiling = new Tiling(); - var render = function (left, top, zoom) { - content.width = clientWidth; - content.height = clientHeight; - context.clearRect(0, 0, clientWidth, clientHeight); - tiling.setup(clientWidth, clientHeight, contentWidth, contentHeight, cellWidth, cellHeight); - tiling.render(left, top, zoom, paint); - }; - var paint = function (row, col, left, top, width, height, zoom) { - context.fillStyle = row % 2 + col % 2 > 0 ? "#ddd" : "#fff"; - context.fillRect(left, top, width, height); - context.fillStyle = "black"; - context.font = (14 * zoom).toFixed(2) + 'px "Helvetica Neue", Helvetica, Arial, sans-serif'; - context.fillText(row + "," + col, left + (6 * zoom), top + (18 * zoom)); - }; -} - -function test_domlist() { - var container = document.getElementById("container"); - var content = document.getElementById("content"); - var refreshElem = content.getElementsByTagName("div")[0]; - var scroller = new Scroller(render, { - scrollingX: false - }); - scroller.activatePullToRefresh(50, function () { - refreshElem.className += " active"; - refreshElem.innerHTML = "Release to Refresh"; - }, function () { - refreshElem.className = refreshElem.className.replace(" active", ""); - refreshElem.innerHTML = "Pull to Refresh"; - }, function () { - refreshElem.className += " running"; - refreshElem.innerHTML = "Refreshing..."; - setTimeout(function () { - refreshElem.className = refreshElem.className.replace(" running", ""); - insertItems(); - scroller.finishPullToRefresh(); - }, 2000); - }); - var rect = container.getBoundingClientRect(); - scroller.setPosition(rect.left + container.clientLeft, rect.top + container.clientTop); - var insertItems = function () { - for (var i = 0; i < 15; i++) { - var row = document.createElement("div"); - row.className = "row"; - row.style.backgroundColor = i % 2 > 0 ? "#ddd" : ""; - row.innerHTML = Math.random(); - if (content.firstChild == content.lastChild) { - content.appendChild(row); - } else { - content.insertBefore(row, content.childNodes[1]) - } - } - scroller.setDimensions(container.clientWidth, container.clientHeight, content.offsetWidth, content.offsetHeight - 50); - }; - insertItems(); - if ('ontouchstart' in window) { - container.addEventListener("touchstart", function (e) { - // Don't react if initial down happens on a form element - if ((e.target).tagName.match(/input|textarea|select/i)) { - return; - } - scroller.doTouchStart((e).touches, e.timeStamp); - e.preventDefault(); - }, false); - document.addEventListener("touchmove", function (e) { - scroller.doTouchMove((e).touches, e.timeStamp); - }, false); - document.addEventListener("touchend", function (e) { - scroller.doTouchEnd(e.timeStamp); - }, false); - } else { - var mousedown = false; - container.addEventListener("mousedown", function (e) { - if ((e.target).tagName.match(/input|textarea|select/i)) { - return; - } - scroller.doTouchStart([{ - pageX: (e).pageX, - pageY: (e).pageY - }], e.timeStamp); - mousedown = true; - }, false); - document.addEventListener("mousemove", function (e) { - if (!mousedown) { - return; - } - scroller.doTouchMove([{ - pageX: (e).pageX, - pageY: (e).pageY - }], e.timeStamp); - mousedown = true; - }, false); - document.addEventListener("mouseup", function (e) { - if (!mousedown) { - return; - } - scroller.doTouchEnd(e.timeStamp); - mousedown = false; - }, false); - } -} - -function test_dompaging() { - var container = document.getElementById("container"); - var content = document.getElementById("content"); - var size = 400; - var frag = document.createDocumentFragment(); - for (var cell = 0, cl = content.clientWidth / size; cell < cl; cell++) { - var elem = document.createElement("div"); - elem.className = "cell"; - elem.style.backgroundColor = cell % 2 > 0 ? "#ddd" : ""; - elem.innerHTML = cell; - frag.appendChild(elem); - } - content.appendChild(frag); - var scroller = new Scroller(render, { - scrollingY: false, - paging: true - }); - var rect = container.getBoundingClientRect(); - scroller.setPosition(rect.left + container.clientLeft, rect.top + container.clientTop); - scroller.setDimensions(container.clientWidth, container.clientHeight, content.offsetWidth, content.offsetHeight); - if ('ontouchstart' in window) { - container.addEventListener("touchstart", function (e) { - if ((e.target).tagName.match(/input|textarea|select/i)) { - return; - } - scroller.doTouchStart((e).touches, e.timeStamp); - e.preventDefault(); - }, false); - document.addEventListener("touchmove", function (e) { - scroller.doTouchMove((e).touches, e.timeStamp); - }, false); - document.addEventListener("touchend", function (e) { - scroller.doTouchEnd(e.timeStamp); - }, false); - } else { - var mousedown = false; - container.addEventListener("mousedown", function (e) { - if ((e.target).tagName.match(/input|textarea|select/i)) { - return; - } - scroller.doTouchStart([{ - pageX: (e).pageX, - pageY: (e).pageY - }], e.timeStamp); - mousedown = true; - }, false); - document.addEventListener("mousemove", function (e) { - if (!mousedown) { - return; - } - scroller.doTouchMove([{ - pageX: (e).pageX, - pageY: (e).pageY - }], e.timeStamp); - mousedown = true; - }, false); - - document.addEventListener("mouseup", function (e) { - if (!mousedown) { - return; - } - scroller.doTouchEnd(e.timeStamp); - mousedown = false; - }, false); - } -} - -function test_domsnapping() { - var container = document.getElementById("container"); - var content = document.getElementById("content"); - var size = 100; - var frag = document.createDocumentFragment(); - for (var row = 0, rl = content.clientHeight / size; row < rl; row++) { - for (var cell = 0, cl = content.clientWidth / size; cell < cl; cell++) { - var elem = document.createElement("div"); - elem.className = "cell"; - elem.style.backgroundColor = row % 2 + cell % 2 > 0 ? "#ddd" : ""; - elem.innerHTML = row + "," + cell; - frag.appendChild(elem); - } - } - content.appendChild(frag); - var scroller = new Scroller(render, { - snapping: true - }); - var rect = container.getBoundingClientRect(); - scroller.setPosition(rect.left + container.clientLeft, rect.top + container.clientTop); - scroller.setDimensions(container.clientWidth, container.clientHeight, content.offsetWidth, content.offsetHeight); - scroller.setSnapSize(100, 100); - if ('ontouchstart' in window) { - container.addEventListener("touchstart", function (e) { - if ((e.target).tagName.match(/input|textarea|select/i)) { - return; - } - scroller.doTouchStart((e).touches, e.timeStamp); - e.preventDefault(); - }, false); - document.addEventListener("touchmove", function (e) { - scroller.doTouchMove((e).touches, e.timeStamp); - }, false); - document.addEventListener("touchend", function (e) { - scroller.doTouchEnd(e.timeStamp); - }, false); - } else { - var mousedown = false; - container.addEventListener("mousedown", function (e) { - if ((e.target).tagName.match(/input|textarea|select/i)) { - return; - } - scroller.doTouchStart([{ - pageX: (e).pageX, - pageY: (e).pageY - }], e.timeStamp); - mousedown = true; - }, false); - document.addEventListener("mousemove", function (e) { - if (!mousedown) { - return; - } - scroller.doTouchMove([{ - pageX: (e).pageX, - pageY: (e).pageY - }], e.timeStamp); - mousedown = true; - }, false); - document.addEventListener("mouseup", function (e) { - if (!mousedown) { - return; - } - scroller.doTouchEnd(e.timeStamp); - mousedown = false; - }, false); - } +/// + +var clientWidth: any; +var clientHeight: any; +var render: any; + +var Tiling: any; + +function test_basic() { + var scrollerObj = new Scroller(function (left, top, zoom) { + }, { + scrollingY: false + }); + scrollerObj.setDimensions(1000, 1000, 3000, 3000); +} + +function test_canvas() { + var contentWidth = 2000; + var contentHeight = 2000; + var cellWidth = 100; + var cellHeight = 100; + var content = document.getElementById('content'); + var context = content.getContext('2d'); + var tiling = new Tiling(); + var render = function (left, top, zoom) { + content.width = clientWidth; + content.height = clientHeight; + context.clearRect(0, 0, clientWidth, clientHeight); + tiling.setup(clientWidth, clientHeight, contentWidth, contentHeight, cellWidth, cellHeight); + tiling.render(left, top, zoom, paint); + }; + var paint = function (row, col, left, top, width, height, zoom) { + context.fillStyle = row % 2 + col % 2 > 0 ? "#ddd" : "#fff"; + context.fillRect(left, top, width, height); + context.fillStyle = "black"; + context.font = (14 * zoom).toFixed(2) + 'px "Helvetica Neue", Helvetica, Arial, sans-serif'; + context.fillText(row + "," + col, left + (6 * zoom), top + (18 * zoom)); + }; +} + +function test_domlist() { + var container = document.getElementById("container"); + var content = document.getElementById("content"); + var refreshElem = content.getElementsByTagName("div")[0]; + var scroller = new Scroller(render, { + scrollingX: false + }); + scroller.activatePullToRefresh(50, function () { + refreshElem.className += " active"; + refreshElem.innerHTML = "Release to Refresh"; + }, function () { + refreshElem.className = refreshElem.className.replace(" active", ""); + refreshElem.innerHTML = "Pull to Refresh"; + }, function () { + refreshElem.className += " running"; + refreshElem.innerHTML = "Refreshing..."; + setTimeout(function () { + refreshElem.className = refreshElem.className.replace(" running", ""); + insertItems(); + scroller.finishPullToRefresh(); + }, 2000); + }); + var rect = container.getBoundingClientRect(); + scroller.setPosition(rect.left + container.clientLeft, rect.top + container.clientTop); + var insertItems = function () { + for (var i = 0; i < 15; i++) { + var row = document.createElement("div"); + row.className = "row"; + row.style.backgroundColor = i % 2 > 0 ? "#ddd" : ""; + row.innerHTML = Math.random(); + if (content.firstChild == content.lastChild) { + content.appendChild(row); + } else { + content.insertBefore(row, content.childNodes[1]) + } + } + scroller.setDimensions(container.clientWidth, container.clientHeight, content.offsetWidth, content.offsetHeight - 50); + }; + insertItems(); + if ('ontouchstart' in window) { + container.addEventListener("touchstart", function (e) { + // Don't react if initial down happens on a form element + if ((e.target).tagName.match(/input|textarea|select/i)) { + return; + } + scroller.doTouchStart((e).touches, e.timeStamp); + e.preventDefault(); + }, false); + document.addEventListener("touchmove", function (e) { + scroller.doTouchMove((e).touches, e.timeStamp); + }, false); + document.addEventListener("touchend", function (e) { + scroller.doTouchEnd(e.timeStamp); + }, false); + } else { + var mousedown = false; + container.addEventListener("mousedown", function (e) { + if ((e.target).tagName.match(/input|textarea|select/i)) { + return; + } + scroller.doTouchStart([{ + pageX: (e).pageX, + pageY: (e).pageY + }], e.timeStamp); + mousedown = true; + }, false); + document.addEventListener("mousemove", function (e) { + if (!mousedown) { + return; + } + scroller.doTouchMove([{ + pageX: (e).pageX, + pageY: (e).pageY + }], e.timeStamp); + mousedown = true; + }, false); + document.addEventListener("mouseup", function (e) { + if (!mousedown) { + return; + } + scroller.doTouchEnd(e.timeStamp); + mousedown = false; + }, false); + } +} + +function test_dompaging() { + var container = document.getElementById("container"); + var content = document.getElementById("content"); + var size = 400; + var frag = document.createDocumentFragment(); + for (var cell = 0, cl = content.clientWidth / size; cell < cl; cell++) { + var elem = document.createElement("div"); + elem.className = "cell"; + elem.style.backgroundColor = cell % 2 > 0 ? "#ddd" : ""; + elem.innerHTML = cell; + frag.appendChild(elem); + } + content.appendChild(frag); + var scroller = new Scroller(render, { + scrollingY: false, + paging: true + }); + var rect = container.getBoundingClientRect(); + scroller.setPosition(rect.left + container.clientLeft, rect.top + container.clientTop); + scroller.setDimensions(container.clientWidth, container.clientHeight, content.offsetWidth, content.offsetHeight); + if ('ontouchstart' in window) { + container.addEventListener("touchstart", function (e) { + if ((e.target).tagName.match(/input|textarea|select/i)) { + return; + } + scroller.doTouchStart((e).touches, e.timeStamp); + e.preventDefault(); + }, false); + document.addEventListener("touchmove", function (e) { + scroller.doTouchMove((e).touches, e.timeStamp); + }, false); + document.addEventListener("touchend", function (e) { + scroller.doTouchEnd(e.timeStamp); + }, false); + } else { + var mousedown = false; + container.addEventListener("mousedown", function (e) { + if ((e.target).tagName.match(/input|textarea|select/i)) { + return; + } + scroller.doTouchStart([{ + pageX: (e).pageX, + pageY: (e).pageY + }], e.timeStamp); + mousedown = true; + }, false); + document.addEventListener("mousemove", function (e) { + if (!mousedown) { + return; + } + scroller.doTouchMove([{ + pageX: (e).pageX, + pageY: (e).pageY + }], e.timeStamp); + mousedown = true; + }, false); + + document.addEventListener("mouseup", function (e) { + if (!mousedown) { + return; + } + scroller.doTouchEnd(e.timeStamp); + mousedown = false; + }, false); + } +} + +function test_domsnapping() { + var container = document.getElementById("container"); + var content = document.getElementById("content"); + var size = 100; + var frag = document.createDocumentFragment(); + for (var row = 0, rl = content.clientHeight / size; row < rl; row++) { + for (var cell = 0, cl = content.clientWidth / size; cell < cl; cell++) { + var elem = document.createElement("div"); + elem.className = "cell"; + elem.style.backgroundColor = row % 2 + cell % 2 > 0 ? "#ddd" : ""; + elem.innerHTML = row + "," + cell; + frag.appendChild(elem); + } + } + content.appendChild(frag); + var scroller = new Scroller(render, { + snapping: true + }); + var rect = container.getBoundingClientRect(); + scroller.setPosition(rect.left + container.clientLeft, rect.top + container.clientTop); + scroller.setDimensions(container.clientWidth, container.clientHeight, content.offsetWidth, content.offsetHeight); + scroller.setSnapSize(100, 100); + if ('ontouchstart' in window) { + container.addEventListener("touchstart", function (e) { + if ((e.target).tagName.match(/input|textarea|select/i)) { + return; + } + scroller.doTouchStart((e).touches, e.timeStamp); + e.preventDefault(); + }, false); + document.addEventListener("touchmove", function (e) { + scroller.doTouchMove((e).touches, e.timeStamp); + }, false); + document.addEventListener("touchend", function (e) { + scroller.doTouchEnd(e.timeStamp); + }, false); + } else { + var mousedown = false; + container.addEventListener("mousedown", function (e) { + if ((e.target).tagName.match(/input|textarea|select/i)) { + return; + } + scroller.doTouchStart([{ + pageX: (e).pageX, + pageY: (e).pageY + }], e.timeStamp); + mousedown = true; + }, false); + document.addEventListener("mousemove", function (e) { + if (!mousedown) { + return; + } + scroller.doTouchMove([{ + pageX: (e).pageX, + pageY: (e).pageY + }], e.timeStamp); + mousedown = true; + }, false); + document.addEventListener("mouseup", function (e) { + if (!mousedown) { + return; + } + scroller.doTouchEnd(e.timeStamp); + mousedown = false; + }, false); + } } \ No newline at end of file diff --git a/scroller/scroller-tests.ts.tscparams b/scroller/scroller-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/scroller/scroller-tests.ts.tscparams +++ b/scroller/scroller-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/scroller/scroller.d.ts b/scroller/scroller.d.ts index b1312ff35..5b1ccba2c 100644 --- a/scroller/scroller.d.ts +++ b/scroller/scroller.d.ts @@ -1,50 +1,50 @@ -// Type definitions for Zynga Scroller -// Project: https://github.com/zynga/scroller -// Definitions by: Boris Yankov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -interface ScrollerOptions { - scrollingX?: boolean; - scrollingY?: boolean; - animating?: boolean; - animationDuration?: number; - bouncing?: boolean; - locking?: boolean; - paging?: boolean; - snapping?: boolean; - zooming?: boolean; - minZoom?: number; - maxZoom?: number; - speedMultiplier?: number; -} - -interface ScrollValues { - left: number; - top: number; -} - -interface ScrollValuesWithZoom extends ScrollValues { - zoom: number; -} - -declare class Scroller { - constructor (callback: (left: number, top: number, zoom: number) => void , options: ScrollerOptions); - - setDimensions(clientWidth: number, clientHeight: number, contentWidth: number, contentHeight: number): void; - setPosition(left: number, top: number): void; - setSnapSize(width: number, height: number): void; - activatePullToRefresh(height: number, activateCallback: Function, deactivateCallback: Function, startCallback: Function): void; - finishPullToRefresh(): void; - getValues(): ScrollValuesWithZoom; - getScrollMax(): ScrollValues; - zoomTo(level: number, animate?: boolean, originLeft?: number, originTop?: number, callback?: Function): void; - zoomBy(factor: number, animate?: boolean, originLeft?: number, originTop?: number, callback?: Function): void; - scrollTo(left?: number, top?: number, animate?: boolean, zoom?: number): void; - scrollBy(left?: number, top?: number, animate?: boolean): void; - - doMouseZoom(wheelDelta: number, timeStamp: number, pageX: number, pageY: number): void; - doTouchStart(touches: any[], timeStamp: number): void; - doTouchMove(touches: any[], timeStamp: number, scale?: number): void; - doTouchEnd(timeStamp: number): void; -} +// Type definitions for Zynga Scroller +// Project: https://github.com/zynga/scroller +// Definitions by: Boris Yankov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +interface ScrollerOptions { + scrollingX?: boolean; + scrollingY?: boolean; + animating?: boolean; + animationDuration?: number; + bouncing?: boolean; + locking?: boolean; + paging?: boolean; + snapping?: boolean; + zooming?: boolean; + minZoom?: number; + maxZoom?: number; + speedMultiplier?: number; +} + +interface ScrollValues { + left: number; + top: number; +} + +interface ScrollValuesWithZoom extends ScrollValues { + zoom: number; +} + +declare class Scroller { + constructor (callback: (left: number, top: number, zoom: number) => void , options: ScrollerOptions); + + setDimensions(clientWidth: number, clientHeight: number, contentWidth: number, contentHeight: number): void; + setPosition(left: number, top: number): void; + setSnapSize(width: number, height: number): void; + activatePullToRefresh(height: number, activateCallback: Function, deactivateCallback: Function, startCallback: Function): void; + finishPullToRefresh(): void; + getValues(): ScrollValuesWithZoom; + getScrollMax(): ScrollValues; + zoomTo(level: number, animate?: boolean, originLeft?: number, originTop?: number, callback?: Function): void; + zoomBy(factor: number, animate?: boolean, originLeft?: number, originTop?: number, callback?: Function): void; + scrollTo(left?: number, top?: number, animate?: boolean, zoom?: number): void; + scrollBy(left?: number, top?: number, animate?: boolean): void; + + doMouseZoom(wheelDelta: number, timeStamp: number, pageX: number, pageY: number): void; + doTouchStart(touches: any[], timeStamp: number): void; + doTouchMove(touches: any[], timeStamp: number, scale?: number): void; + doTouchEnd(timeStamp: number): void; +} diff --git a/select2/select2-tests.ts b/select2/select2-tests.ts index b63d3cc1e..2ab6e94af 100644 --- a/select2/select2-tests.ts +++ b/select2/select2-tests.ts @@ -1,199 +1,199 @@ -/// -/// - -$("#e9").select2(); -$("#e2").select2({ - placeholder: "Select a State", - allowClear: true -}); -$("#e2_2").select2({ - placeholder: "Select a State" -}); -$("#e3").select2({ - minimumInputLength: 2 -}); -function format(state) { - if (!state.id) return state.text; - return "" + state.text; -} -$("#e4").select2({ - formatResult: format, - formatSelection: format -}); -$("#e5").select2({ - minimumInputLength: 1, - query: function (query) { - var data = { results: [] }, i, j, s; - for (i = 1; i < 5; i++) { - s = ""; - for (j = 0; j < i; j++) { s = s + query.term; } - data.results.push({ id: query.term + i, text: s }); - } - } -}); -$("#e19").select2({ maximumSelectionSize: 3 }); -$("#e10").select2({ - data: [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }] -}); - -var data = [{ id: 0, tag: 'enhancement' }, { id: 1, tag: 'bug' }, { id: 2, tag: 'duplicate' }, { id: 3, tag: 'invalid' }, { id: 4, tag: 'wontfix' }]; - -$("#e10_2").select2({ - data: { results: data, text: 'tag' }, - formatSelection: format, - formatResult: format -}); - -$("#e10_3").select2({ - data: { results: data, text: function (item) { console.log('called with', item); return item.tag; } }, - formatSelection: format, - formatResult: format -}); -var movieFormatResult, movieFormatSelection; -$("#e6").select2({ - placeholder: "Search for a movie", - minimumInputLength: 1, - ajax: { - url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json", - dataType: 'jsonp', - cache: false, - data: function (term, page) { - return { - q: term, - page_limit: 10, - apikey: "ju6z9mjyajq2djue3gbvv26t" - }; - }, - results: function (data, page) { - return { results: data.movies }; - } - }, - formatResult: movieFormatResult, - formatSelection: movieFormatSelection, - dropdownCssClass: "bigdrop" -}); -$("#e6").select2({ - placeholder: "Search for a movie", - minimumInputLength: 1, - ajax: { - url: () => { return "http://api.rottentomatoes.com/api/public/v1.0/movies.json"; }, - dataType: 'jsonp', - data: function (term, page) { - return { - q: term, - page_limit: 10, - apikey: "ju6z9mjyajq2djue3gbvv26t" - }; - }, - results: function (data, page) { - return { results: data.movies }; - } - }, - formatResult: movieFormatResult, - formatSelection: movieFormatSelection, - dropdownCssClass: "bigdrop" -}); -$("#e7").select2({ - placeholder: "Search for a movie", - minimumInputLength: 3, - ajax: { - url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json", - dataType: 'jsonp', - quietMillis: 100, - data: function (term, page) { - return { - q: term, - page_limit: 10, - page: page, - apikey: "ju6z9mjyajq2djue3gbvv26t" - }; - }, - results: function (data, page) { - var more = (page * 10) < data.total; - return { results: data.movies, more: more }; - } - }, - formatResult: movieFormatResult, - formatSelection: movieFormatSelection, - dropdownCssClass: "bigdrop" -}); - -$("#e8").select2(); -$("#e8_get").click(function () { alert("Selected value is: " + $("#e8").select2("val")); }); -$("#e8_set").click(function () { $("#e8").select2("val", "CA"); }); -$("#e8_cl").click(function () { $("#e8").select2("val", ""); }); -$("#e8_get2").click(function () { alert("Selected data is: " + JSON.stringify($("#e8").select2("data"))); }); -$("#e8_set2").click(function () { $("#e8").select2("data", { id: "CA", text: "California" }); }); -$("#e8_open").click(function () { $("#e8").select2("open"); }); -$("#e8_close").click(function () { $("#e8").select2("close"); }); -$("#e8_2").select2(); -$("#e8_2_get").click(function () { alert("Selected value is: " + $("#e8_2").select2("val")); }); -$("#e8_2_set").click(function () { $("#e8_2").select2("val", ["CA", "MA"]); }); -$("#e8_2_get2").click(function () { alert("Selected value is: " + JSON.stringify($("#e8_2").select2("data"))); }); -$("#e8_2_set2").click(function () { $("#e8_2").select2("data", [{ id: "CA", text: "California" }, { id: "MA", text: "Massachusetts" }]); }); -$("#e8_2_cl").click(function () { $("#e8_2").select2("val", ""); }); -$("#e8_2_open").click(function () { $("#e8_2").select2("open"); }); -$("#e8_2_close").click(function () { $("#e8_2").select2("close"); }); -$("#e11").select2({ - placeholder: "Select report type", - allowClear: true, - data: [{ id: 0, text: 'story' }, { id: 1, text: 'bug' }, { id: 2, text: 'task' }] -}); -$("#e11_2").select2({ - createSearchChoice: function (term, data) { if ($(data).filter(function () { return this.text.localeCompare(term) === 0; }).length === 0) { return { id: term, text: term }; } }, - multiple: true, - data: [{ id: 0, text: 'story' }, { id: 1, text: 'bug' }, { id: 2, text: 'task' }] -}); -function log(e) { - var item = $("
  • " + e + "
  • "); - $("#events_11").append(item); - item.animate({ opacity: 1 }, 10000, 'linear', function () { item.animate({ opacity: 0 }, 2000, 'linear', function () { item.remove(); }); }); -} -$("#e11") - // TS 0.9.5: correct overload not resolved https://typescript.codeplex.com/discussions/472172 - .on("change", function (e: Select2JQueryEventObject) { log(JSON.stringify({ val: e.val, added: e.added, removed: e.removed })); }) - .on("open", function () { log("open"); }); -$("#e11_2") - .on("change", function (e: Select2JQueryEventObject) { log(JSON.stringify({ val: e.val, added: e.added, removed: e.removed })); }) - .on("open", function () { log("open"); }); -$("#e12").select2({ tags: ["red", "green", "blue"] }); -$("#e20").select2({ - tags: ["red", "green", "blue"], - tokenSeparators: [",", " "] -}); -$("#e13").select2(); -$("#e13_ca").click(function () { $("#e13").val("CA").trigger("change"); }); -$("#e13_ak_co").click(function () { $("#e13").val(["AK", "CO"]).trigger("change"); }); -$("#e14").val(["AL", "AZ"]).select2(); -$("#e14_init").click(function () { $("#e14").select2(); }); -$("#e14_destroy").click(function () { $("#e14").select2("destroy"); }); -$("#e15").select2({ tags: ["red", "green", "blue", "orange", "white", "black", "purple", "cyan", "teal"] }); -$("#e15").on("change", function () { $("#e15_val").html($("#e15").val()); }); - -$("#e16").select2(); -$("#e16_2").select2(); -$("#e16_enable").click(function () { $("#e16,#e16_2").select2("enable"); }); -$("#e16_disable").click(function () { $("#e16,#e16_2").select2("disable"); }); -$("#e17").select2({ - matcher: function (term, text) { return text.toUpperCase().indexOf(term.toUpperCase()) == 0; } -}); -$("#e17_2").select2({ - matcher: function (term, text, opt) { - return text.toUpperCase().indexOf(term.toUpperCase()) >= 0 - || opt.attr("alt").toUpperCase().indexOf(term.toUpperCase()) >= 0; - } -}); -$("#e18,#e18_2").select2(); -alert("Selected value is: " + $("#e8").select2("val")); $("#e8").select2("val", { id: "CA", text: "Califoria" }); - -$("#e8").select2("val"); -$("#e8").select2("val", "CA"); -$("#e8").select2("data"); -$("#e8").select2("data", { id: "CA", text: "Califoria" }); -$("#e8").select2("destroy"); -$("#e8").select2("open"); -$("#e8").select2("enable", false); -$("#e8").select2("readonly", false); -$("#e8").select2('container'); -$("#e8").select2('onSortStart'); -$("#e8").select2('onSortEnd'); +/// +/// + +$("#e9").select2(); +$("#e2").select2({ + placeholder: "Select a State", + allowClear: true +}); +$("#e2_2").select2({ + placeholder: "Select a State" +}); +$("#e3").select2({ + minimumInputLength: 2 +}); +function format(state) { + if (!state.id) return state.text; + return "" + state.text; +} +$("#e4").select2({ + formatResult: format, + formatSelection: format +}); +$("#e5").select2({ + minimumInputLength: 1, + query: function (query) { + var data = { results: [] }, i, j, s; + for (i = 1; i < 5; i++) { + s = ""; + for (j = 0; j < i; j++) { s = s + query.term; } + data.results.push({ id: query.term + i, text: s }); + } + } +}); +$("#e19").select2({ maximumSelectionSize: 3 }); +$("#e10").select2({ + data: [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }] +}); + +var data = [{ id: 0, tag: 'enhancement' }, { id: 1, tag: 'bug' }, { id: 2, tag: 'duplicate' }, { id: 3, tag: 'invalid' }, { id: 4, tag: 'wontfix' }]; + +$("#e10_2").select2({ + data: { results: data, text: 'tag' }, + formatSelection: format, + formatResult: format +}); + +$("#e10_3").select2({ + data: { results: data, text: function (item) { console.log('called with', item); return item.tag; } }, + formatSelection: format, + formatResult: format +}); +var movieFormatResult, movieFormatSelection; +$("#e6").select2({ + placeholder: "Search for a movie", + minimumInputLength: 1, + ajax: { + url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json", + dataType: 'jsonp', + cache: false, + data: function (term, page) { + return { + q: term, + page_limit: 10, + apikey: "ju6z9mjyajq2djue3gbvv26t" + }; + }, + results: function (data, page) { + return { results: data.movies }; + } + }, + formatResult: movieFormatResult, + formatSelection: movieFormatSelection, + dropdownCssClass: "bigdrop" +}); +$("#e6").select2({ + placeholder: "Search for a movie", + minimumInputLength: 1, + ajax: { + url: () => { return "http://api.rottentomatoes.com/api/public/v1.0/movies.json"; }, + dataType: 'jsonp', + data: function (term, page) { + return { + q: term, + page_limit: 10, + apikey: "ju6z9mjyajq2djue3gbvv26t" + }; + }, + results: function (data, page) { + return { results: data.movies }; + } + }, + formatResult: movieFormatResult, + formatSelection: movieFormatSelection, + dropdownCssClass: "bigdrop" +}); +$("#e7").select2({ + placeholder: "Search for a movie", + minimumInputLength: 3, + ajax: { + url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json", + dataType: 'jsonp', + quietMillis: 100, + data: function (term, page) { + return { + q: term, + page_limit: 10, + page: page, + apikey: "ju6z9mjyajq2djue3gbvv26t" + }; + }, + results: function (data, page) { + var more = (page * 10) < data.total; + return { results: data.movies, more: more }; + } + }, + formatResult: movieFormatResult, + formatSelection: movieFormatSelection, + dropdownCssClass: "bigdrop" +}); + +$("#e8").select2(); +$("#e8_get").click(function () { alert("Selected value is: " + $("#e8").select2("val")); }); +$("#e8_set").click(function () { $("#e8").select2("val", "CA"); }); +$("#e8_cl").click(function () { $("#e8").select2("val", ""); }); +$("#e8_get2").click(function () { alert("Selected data is: " + JSON.stringify($("#e8").select2("data"))); }); +$("#e8_set2").click(function () { $("#e8").select2("data", { id: "CA", text: "California" }); }); +$("#e8_open").click(function () { $("#e8").select2("open"); }); +$("#e8_close").click(function () { $("#e8").select2("close"); }); +$("#e8_2").select2(); +$("#e8_2_get").click(function () { alert("Selected value is: " + $("#e8_2").select2("val")); }); +$("#e8_2_set").click(function () { $("#e8_2").select2("val", ["CA", "MA"]); }); +$("#e8_2_get2").click(function () { alert("Selected value is: " + JSON.stringify($("#e8_2").select2("data"))); }); +$("#e8_2_set2").click(function () { $("#e8_2").select2("data", [{ id: "CA", text: "California" }, { id: "MA", text: "Massachusetts" }]); }); +$("#e8_2_cl").click(function () { $("#e8_2").select2("val", ""); }); +$("#e8_2_open").click(function () { $("#e8_2").select2("open"); }); +$("#e8_2_close").click(function () { $("#e8_2").select2("close"); }); +$("#e11").select2({ + placeholder: "Select report type", + allowClear: true, + data: [{ id: 0, text: 'story' }, { id: 1, text: 'bug' }, { id: 2, text: 'task' }] +}); +$("#e11_2").select2({ + createSearchChoice: function (term, data) { if ($(data).filter(function () { return this.text.localeCompare(term) === 0; }).length === 0) { return { id: term, text: term }; } }, + multiple: true, + data: [{ id: 0, text: 'story' }, { id: 1, text: 'bug' }, { id: 2, text: 'task' }] +}); +function log(e) { + var item = $("
  • " + e + "
  • "); + $("#events_11").append(item); + item.animate({ opacity: 1 }, 10000, 'linear', function () { item.animate({ opacity: 0 }, 2000, 'linear', function () { item.remove(); }); }); +} +$("#e11") + // TS 0.9.5: correct overload not resolved https://typescript.codeplex.com/discussions/472172 + .on("change", function (e: Select2JQueryEventObject) { log(JSON.stringify({ val: e.val, added: e.added, removed: e.removed })); }) + .on("open", function () { log("open"); }); +$("#e11_2") + .on("change", function (e: Select2JQueryEventObject) { log(JSON.stringify({ val: e.val, added: e.added, removed: e.removed })); }) + .on("open", function () { log("open"); }); +$("#e12").select2({ tags: ["red", "green", "blue"] }); +$("#e20").select2({ + tags: ["red", "green", "blue"], + tokenSeparators: [",", " "] +}); +$("#e13").select2(); +$("#e13_ca").click(function () { $("#e13").val("CA").trigger("change"); }); +$("#e13_ak_co").click(function () { $("#e13").val(["AK", "CO"]).trigger("change"); }); +$("#e14").val(["AL", "AZ"]).select2(); +$("#e14_init").click(function () { $("#e14").select2(); }); +$("#e14_destroy").click(function () { $("#e14").select2("destroy"); }); +$("#e15").select2({ tags: ["red", "green", "blue", "orange", "white", "black", "purple", "cyan", "teal"] }); +$("#e15").on("change", function () { $("#e15_val").html($("#e15").val()); }); + +$("#e16").select2(); +$("#e16_2").select2(); +$("#e16_enable").click(function () { $("#e16,#e16_2").select2("enable"); }); +$("#e16_disable").click(function () { $("#e16,#e16_2").select2("disable"); }); +$("#e17").select2({ + matcher: function (term, text) { return text.toUpperCase().indexOf(term.toUpperCase()) == 0; } +}); +$("#e17_2").select2({ + matcher: function (term, text, opt) { + return text.toUpperCase().indexOf(term.toUpperCase()) >= 0 + || opt.attr("alt").toUpperCase().indexOf(term.toUpperCase()) >= 0; + } +}); +$("#e18,#e18_2").select2(); +alert("Selected value is: " + $("#e8").select2("val")); $("#e8").select2("val", { id: "CA", text: "Califoria" }); + +$("#e8").select2("val"); +$("#e8").select2("val", "CA"); +$("#e8").select2("data"); +$("#e8").select2("data", { id: "CA", text: "Califoria" }); +$("#e8").select2("destroy"); +$("#e8").select2("open"); +$("#e8").select2("enable", false); +$("#e8").select2("readonly", false); +$("#e8").select2('container'); +$("#e8").select2('onSortStart'); +$("#e8").select2('onSortEnd'); diff --git a/select2/select2-tests.ts.tscparams b/select2/select2-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/select2/select2-tests.ts.tscparams +++ b/select2/select2-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/sencha_touch/SenchaTouch-Tests.ts.tscparams b/sencha_touch/SenchaTouch-Tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/sencha_touch/SenchaTouch-Tests.ts.tscparams +++ b/sencha_touch/SenchaTouch-Tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/sharepoint/SharePoint-tests.ts b/sharepoint/SharePoint-tests.ts index 0e6b53e54..5b73493b3 100644 --- a/sharepoint/SharePoint-tests.ts +++ b/sharepoint/SharePoint-tests.ts @@ -1,2566 +1,2566 @@ -/// -/// -/// -/// - - -//code from http://sptypescript.codeplex.com/ -//BasicTasksJSOM.ts -// Website tasks -function retrieveWebsite(resultpanel:HTMLElement) { - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - clientContext.load(oWebsite); - - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - resultpanel.innerHTML = "Web site title: " + oWebsite.get_title(); - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function retrieveWebsiteProps(resultpanel: HTMLElement) { - - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - - clientContext.load(oWebsite, "Description", "Created"); - - clientContext.executeQueryAsync(successHandler,errorHandler); - - function successHandler() { - resultpanel.innerHTML = "Description: " + oWebsite.get_description() + - "
    Date created: " + oWebsite.get_created(); - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function writeWebsiteProps(resultpanel: HTMLElement) { - - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - - oWebsite.set_description("This is an updated description."); - oWebsite.update(); - - clientContext.load(oWebsite, "Description"); - - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - - function successHandler() { - resultpanel.innerHTML = "Web site description: " + oWebsite.get_description(); - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -// Lists tasks -function readAllProps(resultpanel: HTMLElement) { - - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - - var collList = oWebsite.get_lists(); - clientContext.load(collList); - - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - - var listEnumerator = collList.getEnumerator(); - - var listInfo = ""; - while (listEnumerator.moveNext()) { - var oList = listEnumerator.get_current(); - listInfo += "Title: " + oList.get_title() + " Created: " + - oList.get_created().toString() + "
    "; - } - - resultpanel.innerHTML = listInfo; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function readSpecificProps(resultpanel: HTMLElement) { - - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - - var collList = oWebsite.get_lists(); - - clientContext.load(collList, "Include(Title, Id)"); - - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - - var listEnumerator = collList.getEnumerator(); - - var listInfo = ""; - while (listEnumerator.moveNext()) { - var oList = listEnumerator.get_current(); - listInfo += "Title: " + oList.get_title() + - " ID: " + oList.get_id().toString() + "
    "; - } - - resultpanel.innerHTML = listInfo; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function readColl(resultpanel: HTMLElement) { - - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var collList = oWebsite.get_lists(); - - var listInfoCollection = clientContext.loadQuery(collList, "Include(Title, Id)"); - - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - var listInfo = ""; - for (var i = 0; i < listInfoCollection.length; i++) { - var oList = listInfoCollection[i]; - listInfo += "Title: " + oList.get_title() + - " ID: " + oList.get_id().toString() + "
    "; - } - - resultpanel.innerHTML = listInfo; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function readFilter(resultpanel: HTMLElement) { - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var collList = oWebsite.get_lists(); - - var listInfoArray = clientContext.loadQuery(collList, - "Include(Title,Fields.Include(Title,InternalName))"); - - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - - for (var i = 0; i < listInfoArray.length; i++) { - var oList = listInfoArray[i]; - var collField = oList.get_fields(); - var fieldEnumerator = collField.getEnumerator(); - - var listInfo = ""; - while (fieldEnumerator.moveNext()) { - var oField = fieldEnumerator.get_current(); - var regEx = new RegExp("name", "ig"); - - if (regEx.test(oField.get_internalName())) { - listInfo += "List: " + oList.get_title() + - "
        Field Title: " + oField.get_title() + - "
        Field Internal name: " + oField.get_internalName(); - } - } - } - - resultpanel.innerHTML = listInfo; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -// Create, update and delete lists -function createList(resultpanel: HTMLElement) { - - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - - var listCreationInfo = new SP.ListCreationInformation(); - listCreationInfo.set_title("My Announcements List"); - listCreationInfo.set_templateType(SP.ListTemplateType.announcements); - - var oList = oWebsite.get_lists().add(listCreationInfo); - clientContext.load(oList); - - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - resultpanel.innerHTML = "Go to the list."; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function updateList(resultpanel: HTMLElement) { - - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - - var oList = oWebsite.get_lists().getByTitle("My Announcements List"); - oList.set_description("New Announcements List"); - oList.update(); - - clientContext.load(oList); - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - resultpanel.innerHTML = "Check the description in the list."; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function addField(resultpanel: HTMLElement) { - - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var oList = oWebsite.get_lists().getByTitle("My Announcements List"); - - var oField = oList.get_fields().addFieldAsXml( - "", - true, - SP.AddFieldOptions.defaultValue - ); - - var fieldNumber = clientContext.castTo(oField, SP.FieldNumber); - fieldNumber.set_maximumValue(100); - fieldNumber.set_minimumValue(35); - fieldNumber.update(); - - clientContext.load(oField); - - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - resultpanel.innerHTML = "The list with a new field."; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function deleteList(resultpanel: HTMLElement) { - var listTitle = "My Announcements List"; - - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var oList = oWebsite.get_lists().getByTitle(listTitle); - oList.deleteObject(); - - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - resultpanel.innerHTML = listTitle + " deleted."; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -// Create, update and delete folders -function createFolder(resultpanel: HTMLElement) { - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var oList = oWebsite.get_lists().getByTitle("Shared Documents"); - - var itemCreateInfo = new SP.ListItemCreationInformation(); - itemCreateInfo.set_underlyingObjectType(SP.FileSystemObjectType.folder); - itemCreateInfo.set_leafName("My new folder!"); - var oListItem = oList.addItem(itemCreateInfo); - oListItem.update(); - - clientContext.load(oListItem); - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - resultpanel.innerHTML = "Go to the document library to see your new folder."; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function updateFolder(resultpanel: HTMLElement) { - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var oList = oWebsite.get_lists().getByTitle("Shared Documents"); - - var oListItem = oList.getItemById(1); - oListItem.set_item("FileLeafRef", "My updated folder"); - oListItem.update(); - - clientContext.load(oListItem); - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - resultpanel.innerHTML = "Go to the document library to see your updated folder."; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function deleteFolder(resultpanel: HTMLElement) { - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var oList = oWebsite.get_lists().getByTitle("Shared Documents"); - - var oListItem = oList.getItemById(1); - oListItem.deleteObject(); - - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - resultpanel.innerHTML = "Go to the document library to make sure the folder is no longer there."; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -// List item tasks -function readItems(resultpanel: HTMLElement) { - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var oList = oWebsite.get_lists().getByTitle("Announcements"); - var camlQuery = new SP.CamlQuery(); - camlQuery.set_viewXml( - '' + - '1' + - '10' - ); - var collListItem = oList.getItems(camlQuery); - - clientContext.load(collListItem); - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - var listItemEnumerator = collListItem.getEnumerator(); - - var listItemInfo = ""; - while (listItemEnumerator.moveNext()) { - var oListItem = listItemEnumerator.get_current(); - listItemInfo += "ID: " + oListItem.get_id() + "
    " + - "Title: " + oListItem.get_item("Title") + "
    " + - "Body: " + oListItem.get_item("Body") + "
    "; - } - - resultpanel.innerHTML = listItemInfo; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function readInclude(resultpanel: HTMLElement) { - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var oList = oWebsite.get_lists().getByTitle("Announcements"); - var camlQuery = new SP.CamlQuery(); - camlQuery.set_viewXml('100'); - - var collListItem = oList.getItems(camlQuery); - - clientContext.load(collListItem, "Include(Id, DisplayName, HasUniqueRoleAssignments)"); - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - var listItemEnumerator = collListItem.getEnumerator(); - - var listItemInfo = ""; - while (listItemEnumerator.moveNext()) { - var oListItem = listItemEnumerator.get_current(); - listItemInfo += "ID: " + oListItem.get_id() + "
    " + - "Display name: " + oListItem.get_displayName() + "
    " + - "Unique role assignments: " + oListItem.get_hasUniqueRoleAssignments() + "
    "; - } - - resultpanel.innerHTML = listItemInfo; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -// Create, update and delete list items -function createListItem(resultpanel: HTMLElement) { - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var oList = oWebsite.get_lists().getByTitle("Announcements"); - - var itemCreateInfo = new SP.ListItemCreationInformation(); - var oListItem = oList.addItem(itemCreateInfo); - oListItem.set_item("Title", "My New Item!"); - oListItem.set_item("Body", "Hello World!"); - oListItem.update(); - - clientContext.load(oListItem); - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - resultpanel.innerHTML = "Go to the list to see your new item."; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function updateListItem(resultpanel: HTMLElement) { - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var oList = oWebsite.get_lists().getByTitle("Announcements"); - - var oListItem = oList.getItemById(1); - oListItem.set_item("Title", "My updated title"); - oListItem.update(); - - clientContext.load(oListItem); - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - resultpanel.innerHTML = "Go to the list to see your updated item."; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function deleteListItem(resultpanel: HTMLElement) { - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var oList = oWebsite.get_lists().getByTitle("Announcements"); - - var oListItem = oList.getItemById(1); - oListItem.deleteObject(); - - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - resultpanel.innerHTML = "Go to the list to make sure the item is no longer there."; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - - - -/** Lightweight client-side rendering template overrides.*/ -module CSR { - - export interface UpdatedValueCallback { - (value: any, fieldSchema?: SPClientTemplates.FieldSchema_InForm): void; - } - - /** Creates new overrides. Call .register() at the end.*/ - export function override(listTemplateType?: number, baseViewId?: number|string): ICSR { - return new csr(listTemplateType, baseViewId) - .onPreRender(hookFormContext) - .onPostRender(fixCsrCustomLayout); - - function hookFormContext(ctx: IFormRenderContexWithHook) { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { - - for (var i = 0; i < ctx.ListSchema.Field.length; i++) { - var fieldSchemaInForm = ctx.ListSchema.Field[i]; - - if (!ctx.FormContextHook) { - ctx.FormContextHook = {} - - var oldRegisterGetValueCallback = ctx.FormContext.registerGetValueCallback; - ctx.FormContext.registerGetValueCallback = (fieldName, callback) => { - ctx.FormContextHook[fieldName].getValue = callback; - oldRegisterGetValueCallback(fieldName, callback); - }; - - var oldUpdateControlValue = ctx.FormContext.updateControlValue; - ctx.FormContext.updateControlValue = (fieldName: string, value: any) => { - oldUpdateControlValue(fieldName, value); - - var hookedContext = ensureFormContextHookField(ctx.FormContextHook, fieldName); - hookedContext.lastValue = value; - - var updatedCallbacks = ctx.FormContextHook[fieldName].updatedValueCallbacks; - for (var i = 0; i < updatedCallbacks.length; i++) { - updatedCallbacks[i](value, hookedContext.fieldSchema); - } - - } - } - ensureFormContextHookField(ctx.FormContextHook, fieldSchemaInForm.Name).fieldSchema = fieldSchemaInForm; - } - } - } - - function fixCsrCustomLayout(ctx: SPClientTemplates.RenderContext_Form) { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid - || ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { - return; - } - - if (ctx.ListSchema.Field.length > 1) { - var wpq = ctx.FormUniqueId; - var webpart = $get('WebPart' + wpq); - var forms = webpart.getElementsByClassName('ms-formtable'); - - if (forms.length > 0) { - var placeholder = $get(wpq + 'ClientFormTopContainer'); - var fragment = document.createDocumentFragment(); - for (var i = 0; i < placeholder.children.length; i++) { - fragment.appendChild(placeholder.children.item(i)); - } - - var form = forms.item(0); - form.parentNode.replaceChild(fragment, form); - } - - var old = ctx.CurrentItem; - ctx.CurrentItem = ctx.ListData.Items[0]; - var fields = ctx.ListSchema.Field; - for (var j = 0; j < fields.length; j++) { - var field = fields[j]; - var pHolderId = wpq + ctx.FormContext.listAttributes.Id + field.Name; - var span = $get(pHolderId); - if (span) { - span.outerHTML = ctx.RenderFieldByName(ctx, field.Name); - } - } - ctx.CurrentItem = old; - } - - } - - - } - - -//typescripttempltes.ts - declare var Strings:any; - export function getFieldValue(ctx: SPClientTemplates.RenderContext_Form, fieldName: string): any { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { - var contextWithHook = ctx; - if (contextWithHook.FormContextHook - && contextWithHook.FormContextHook[fieldName] - && contextWithHook.FormContextHook[fieldName].getValue) { - return contextWithHook.FormContextHook[fieldName].getValue(); - } - } - return null; - } - - export function getFieldSchema(ctx: SPClientTemplates.RenderContext_Form, fieldName: string): SPClientTemplates.FieldSchema_InForm { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { - var contextWithHook = ctx; - if (contextWithHook.FormContextHook - && contextWithHook.FormContextHook[fieldName]) { - return contextWithHook.FormContextHook[fieldName].fieldSchema; - } - } - return null; - } - - export function addUpdatedValueCallback(ctx: SPClientTemplates.RenderContext_Form, fieldName: string, callback: UpdatedValueCallback): void { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { - var contextWithHook = ctx; - if (contextWithHook.FormContextHook) { - var f = ensureFormContextHookField(contextWithHook.FormContextHook, fieldName); - var callbacks = f.updatedValueCallbacks; - if (callbacks.indexOf(callback) == -1) { - callbacks.push(callback); - if (f.lastValue) { - callback(f.lastValue, f.fieldSchema); - } - } - } - } - - } - - export function removeUpdatedValueCallback(ctx: SPClientTemplates.RenderContext_Form, fieldName: string, callback: UpdatedValueCallback): void { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { - var contextWithHook = ctx; - if (contextWithHook.FormContextHook) { - var callbacks = ensureFormContextHookField(contextWithHook.FormContextHook, fieldName).updatedValueCallbacks; - var index = callbacks.indexOf(callback); - if (index != -1) { - callbacks.splice(index, 1); - } - } - } - } - - export function getControl(schema: SPClientTemplates.FieldSchema_InForm): HTMLInputElement { - var id = schema.Name + '_' + schema.Id + '_$' + schema.FieldType + 'Field'; - //TODO: Handle different input types - return $get(id); - } - - export function getFieldTemplate(field: SPClientTemplates.FieldSchema, mode: SPClientTemplates.ClientControlMode): SPClientTemplates.FieldCallback { - var ctx = { ListSchema: { Field: [field] }, FieldControlModes: {} }; - ctx.FieldControlModes[field.Name] = mode; - var templates = SPClientTemplates.TemplateManager.GetTemplates(ctx); - return templates.Fields[field.Name]; - } - - - class csr implements ICSR, SPClientTemplates.TemplateOverridesOptions { - - public Templates: SPClientTemplates.TemplateOverrides; - public OnPreRender: SPClientTemplates.RenderCallback[]; - public OnPostRender: SPClientTemplates.RenderCallback[]; - private IsRegistered: boolean; - - - constructor(public ListTemplateType?: number, public BaseViewID?: any) { - this.Templates = { Fields: {} }; - this.OnPreRender = [] ; - this.OnPostRender = []; - this.IsRegistered = false; - } - - /* tier 1 methods */ - view(template: any): ICSR { - this.Templates.View = template; - return this; - } - - item(template: any): ICSR { - this.Templates.Item = template; - return this; - } - - header(template: any): ICSR { - this.Templates.Header = template; - return this; - } - - body(template: any): ICSR { - this.Templates.Body = template; - return this; - } - - footer(template: any): ICSR { - this.Templates.Footer = template; - return this; - } - - fieldView(fieldName: string, template: any): ICSR { - this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; - this.Templates.Fields[fieldName].View = template; - return this; - } - - fieldDisplay(fieldName: string, template: any): ICSR { - this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; - this.Templates.Fields[fieldName].DisplayForm = template; - return this; - } - - fieldNew(fieldName: string, template: any): ICSR { - this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; - this.Templates.Fields[fieldName].NewForm = template; - return this; - } - - fieldEdit(fieldName: string, template: any): ICSR { - this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; - this.Templates.Fields[fieldName].EditForm = template; - return this; - } - - /* tier 2 methods */ - template(name: string, template: any): ICSR { - this.Templates[name] = template; - return this; - } - - fieldTemplate(fieldName: string, name: string, template: any): ICSR { - this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; - this.Templates.Fields[fieldName][name] = template; - return this; - } - - /* common */ - onPreRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR { - for (var i = 0; i < callbacks.length; i++) { - this.OnPreRender.push(callbacks[i]); - } - return this; - } - - onPostRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR { - for (var i = 0; i < callbacks.length; i++) { - this.OnPostRender.push(callbacks[i]); - } - return this; - } - - onPreRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR { - return this.onPreRender((ctx: SPClientTemplates.RenderContext) => { - var ctxInView = ctx; - - //ListSchema schma exists in Form and in View render context - var fields = ctxInView.ListSchema.Field; - if (fields) { - for (var i = 0; i < fields.length; i++) { - if (fields[i].Name === field) { - callback(fields[i], ctx); - } - } - } - }); - } - - onPostRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR { - return this.onPostRender((ctx: SPClientTemplates.RenderContext) => { - var ctxInView = ctx; - - //ListSchema schma exists in Form and in View render context - var fields = ctxInView.ListSchema.Field; - if (fields) { - for (var i = 0; i < fields.length; i++) { - if (fields[i].Name === field) { - callback(fields[i], ctx); - } - } - } - }); - } - - makeReadOnly(fieldName: string): ICSR { - return this - .onPreRenderField(fieldName, (schema, ctx) => { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid - || ctx.ControlMode == SPClientTemplates.ClientControlMode.DisplayForm) return; - (schema).ReadOnlyField = true; - (schema).ReadOnly = "TRUE"; - - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { - var ctxInView = ctx; - if (ctxInView.inGridMode) { - //TODO: Disable editing in grid mode - - } - - } else { - var ctxInForm = ctx; - if (schema.Type != 'User' && schema.Type != 'UserMulti') { - - var template = getFieldTemplate(schema, SPClientTemplates.ClientControlMode.DisplayForm); - ctxInForm.Templates.Fields[fieldName] = template; - ctxInForm.FormContext.registerGetValueCallback(fieldName, () => ctxInForm.ListData.Items[0][fieldName]); - - } - } - - }) - .onPostRenderField(fieldName, (schema: SPClientTemplates.FieldSchema_InForm_User, ctx) => { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { - if (schema.Type == 'User' || schema.Type == 'UserMulti') { - SP.SOD.executeFunc('clientpeoplepicker.js', 'SPClientPeoplePicker', () => { - var topSpanId = schema.Name + '_' + schema.Id + '_$ClientPeoplePicker'; - var retryCount = 10; - var callback = () => { - var pp = SPClientPeoplePicker.SPClientPeoplePickerDict[topSpanId]; - if (!pp) { - if (retryCount--) setTimeout(callback, 1); - } else { - pp.SetEnabledState(false); - pp.DeleteProcessedUser = function () { }; - } - }; - callback(); - }); - } - } - }); - } - - makeHidden(fieldName: string): ICSR { - return this.onPreRenderField(fieldName, (schema, ctx) => { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid) return; - (schema).Hidden = true; - - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { - var ctxInView = ctx; - - if (ctxInView.inGridMode) { - //TODO: Hide item in grid mode - } else { - ctxInView.ListSchema.Field.splice(ctxInView.ListSchema.Field.indexOf(schema), 1); - } - - } else { - var ctxInForm = ctx; - - var pHolderId = ctxInForm.FormUniqueId + ctxInForm.FormContext.listAttributes.Id + fieldName; - var placeholder = $get(pHolderId); - var current = placeholder; - while (current.tagName.toUpperCase() !== "TR") { - current = current.parentElement; - } - var row = current; - row.style.display = 'none'; - - } - - }); - } - - filteredLookup(fieldName: string, camlFilter: string, listname?: string, lookupField?: string): ICSR { - - - return this.fieldEdit(fieldName, SPFieldCascadedLookup_Edit) - .fieldNew(fieldName, SPFieldCascadedLookup_Edit); - - - function SPFieldCascadedLookup_Edit(rCtx: SPClientTemplates.RenderContext_FieldInForm) { - - var parseRegex = /\{[^\}]+\}/g; - var dependencyExpressions: string[] = []; - var result: RegExpExecArray; - while ((result = parseRegex.exec(camlFilter))) { - dependencyExpressions.push(stripBraces(result[0])); - } - var dependencyValues: { [expr: string]: string } = {}; - - var _dropdownElt: HTMLSelectElement; - var _myData: SPClientTemplates.ClientFormContext; - - - if (rCtx == null) - return ''; - _myData = SPClientTemplates.Utility.GetFormContextForCurrentField(rCtx); - - if (_myData == null || _myData.fieldSchema == null) - return ''; - - - var _schema = _myData.fieldSchema; - - var validators = new SPClientForms.ClientValidation.ValidatorSet(); - validators.RegisterValidator(new BooleanValueValidator(() => _optionsLoaded, "Wait until lookup values loaded and try again")); - - if (_myData.fieldSchema.Required) { - validators.RegisterValidator(new SPClientForms.ClientValidation.RequiredValidator()); - } - _myData.registerClientValidator(_myData.fieldName, validators); - - var _dropdownId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$LookupField'; - var _valueStr = _myData.fieldValue != null ? _myData.fieldValue : ''; - var _selectedValue = SPClientTemplates.Utility.ParseLookupValue(_valueStr).LookupId; - var _noValueSelected = _selectedValue == 0; - var _optionsLoaded = false; - var pendingLoads = 0; - - if (_noValueSelected) - _valueStr = ''; - - _myData.registerInitCallback(_myData.fieldName, InitLookupControl); - - _myData.registerFocusCallback(_myData.fieldName, function () { - if (_dropdownElt != null) - _dropdownElt.focus(); - }); - _myData.registerValidationErrorCallback(_myData.fieldName, function (errorResult) { - SPFormControl_AppendValidationErrorMessage(_dropdownId, errorResult); - }); - _myData.registerGetValueCallback(_myData.fieldName, GetCurrentLookupValue); - _myData.updateControlValue(_myData.fieldName, _valueStr); - - return BuildLookupDropdownControl(); - - function InitLookupControl() { - _dropdownElt = document.getElementById(_dropdownId); - if (_dropdownElt != null) - AddEvtHandler(_dropdownElt, "onchange", OnLookupValueChanged); - - SP.SOD.executeFunc('sp.js', 'SP.ClientContext', () => { - bindDependentControls(dependencyExpressions); - loadOptions(true); - }); - } - - - function BuildLookupDropdownControl() { - var result = ''; - result += '
    '; - return result; - } - - - function OnLookupValueChanged() { - if (_optionsLoaded) { - if (_dropdownElt != null) { - _myData.updateControlValue(_myData.fieldName, GetCurrentLookupValue()); - _selectedValue = parseInt(_dropdownElt.value, 10); - } - } - } - - function GetCurrentLookupValue() { - if (_dropdownElt == null) - return ''; - return _dropdownElt.value == '0' || _dropdownElt.value == '' ? '' : _dropdownElt.value + ';#' + _dropdownElt.options[_dropdownElt.selectedIndex].text; - } - - function stripBraces(input: string): string { - return input.substring(1, input.length - 1); - } - - function getDependencyValue(expr: string, value: string, listId: string, expressionParts: string[], callback: () => void) { - var isLookupValue = !!listId; - if (isLookupValue) { - var lookup = SPClientTemplates.Utility.ParseLookupValue(value); - if (expressionParts.length == 1 && expressionParts[0] == 'Value') { - value = lookup.LookupValue; - expressionParts.shift(); - } else { - value = lookup.LookupId.toString(); - } - } - - if (expressionParts.length == 0) { - dependencyValues[expr] = value; - callback(); - } else { - var ctx = SP.ClientContext.get_current(); - var web = ctx.get_web(); - //TODO: Handle lookup to another web - var list = web.get_lists().getById(listId); - var item = list.getItemById(parseInt(value, 10)); - var field = list.get_fields().getByInternalNameOrTitle(expressionParts.shift()); - ctx.load(item); - ctx.load(field); - - ctx.executeQueryAsync((o, e) => { - var value = item.get_item(field.get_internalName()); - - if (field.get_typeAsString() == 'Lookup') { - field = ctx.castTo(field, SP.FieldLookup); - var lookup = (value); - value = lookup.get_lookupId() + ';#' + lookup.get_lookupValue(); - listId = (field).get_lookupList(); - } - - getDependencyValue(expr, value, listId, expressionParts, callback); - - }, (o, args) => { console.log(args.get_message()); }); - } - } - - function bindDependentControls(dependencyExpressions: string[]) { - dependencyExpressions.forEach(expr => { - var exprParts = expr.split("."); - var field = exprParts.shift(); - - CSR.addUpdatedValueCallback(rCtx, field, - (v, s) => { - getDependencyValue(expr, v, - (s).LookupListId, - exprParts.slice(0), - loadOptions); - }); - - }); - } - - - function loadOptions(isFirstLoad?: boolean) { - _optionsLoaded = false; - pendingLoads++; - - var ctx = SP.ClientContext.get_current(); - //TODO: Handle lookup to another web - var web = ctx.get_web(); - var listId = _schema.LookupListId; - var list = !listname ? web.get_lists().getById(listId) : web.get_lists().getByTitle(listname); - var query = new SP.CamlQuery(); - - var predicate = camlFilter.replace(parseRegex, (v, a) => { - var expr = stripBraces(v); - return dependencyValues[expr] ? dependencyValues[expr] : ''; - }); - - //TODO: Handle ShowField attribure - if (predicate.substr(0, 5) == '' + - predicate + - ' ' + - ''); - } - var results = list.getItems(query); - ctx.load(results); - - - ctx.executeQueryAsync((o, e) => { - var selected = false; - - while (_dropdownElt.options.length) { - _dropdownElt.options.remove(0); - } - - if (!_schema.Required) { - var defaultOpt = new Option(Strings.STS.L_LookupFieldNoneOption, '0', selected, selected); - _dropdownElt.options.add(defaultOpt); - selected = _selectedValue == 0; - } - var isEmptyList = true; - - var enumerator = results.getEnumerator(); - while (enumerator.moveNext()) { - var c = enumerator.get_current(); - var id: number; - var text: string; - - if (!lookupField) { - id = c.get_id(); - text = c.get_item('Title'); - } else { - var value = c.get_item(lookupField); - id = value.get_lookupId(); - text = value.get_lookupValue(); - } - var isSelected = _selectedValue == id; - if (isSelected) { - selected = true; - } - var opt = new Option(text, id.toString(), isSelected, isSelected); - _dropdownElt.options.add(opt); - isEmptyList = false; - } - pendingLoads--; - _optionsLoaded = true; - if (!pendingLoads) { - if (isFirstLoad) { - if (_selectedValue == 0 && !selected) { - _dropdownElt.selectedIndex = 0; - OnLookupValueChanged(); - } - } else { - if (_selectedValue != 0 && !selected) { - _dropdownElt.selectedIndex = 0; - } - OnLookupValueChanged(); - } - } - - - }, (o, args) => { console.log(args.get_message()); }); - } - } - - } - - koEditField(fieldName: string, template: string, vm: IKoFieldInForm, dependencyFields?: string[]): ICSR { - return this.fieldEdit(fieldName, koEditField_Edit) - .fieldNew(fieldName, koEditField_Edit); - - - function koEditField_Edit(rCtx: SPClientTemplates.RenderContext_FieldInForm) { - if (rCtx == null) - return ''; - var _myData = SPClientTemplates.Utility.GetFormContextForCurrentField(rCtx); - - if (_myData == null || _myData.fieldSchema == null) - return ''; - var elementId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$' + _myData.fieldSchema.Type; - - vm.renderingContext = rCtx; - - - if (dependencyFields) { - dependencyFields.forEach(dependencyField => { - if (!vm[dependencyField]) { - vm[dependencyField] = ko.observable(CSR.getFieldValue(rCtx, dependencyField)); - } - CSR.addUpdatedValueCallback(rCtx, dependencyField, v => { - vm[dependencyField](v); - }); - }); - } - - - if (!vm.value) { - vm.value = ko.observable(); - } - - vm.value.subscribe(v => { _myData.updateControlValue(fieldName, v); }); - _myData.registerGetValueCallback(fieldName, () => vm.value()); - - - _myData.registerInitCallback(fieldName, () => { - ko.applyBindings(vm, $get(elementId)); - }); - - return '
    '+template+'
    '; - } - } - - computedValue(targetField: string, transform: (...values: string[]) => string, ...sourceField: string[]): ICSR { - var dependentValues: { [field: string]: string } = {}; - - return this.onPostRenderField(targetField, (schema, ctx: SPClientTemplates.RenderContext_FieldInForm) => { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { - var targetControl = CSR.getControl(schema); - sourceField.forEach((field) => { - CSR.addUpdatedValueCallback(ctx, field, v => { - dependentValues[field] = v; - targetControl.value = transform.apply(this, - sourceField.map(n => dependentValues[n] || '')); - - }); - }); - } - }); - } - - setInitialValue(fieldName: string, value: any, ignoreNull?: boolean): ICSR { - if (value || !ignoreNull) { - return this.onPreRenderField(fieldName, (schema, ctx: SPClientTemplates.RenderContext_FieldInForm) => { - ctx.ListData.Items[0][fieldName] = value; - }); - } else { - return this; - } - } - - - autofill(fieldName: string, init: (ctx: IAutoFillFieldContext) => () => void): ICSR { - return this - .fieldNew(fieldName, SPFieldLookup_Autofill_Edit) - .fieldEdit(fieldName, SPFieldLookup_Autofill_Edit); - - function SPFieldLookup_Autofill_Edit(rCtx: SPClientTemplates.RenderContext_FieldInForm) { - if (rCtx == null) - return ''; - var _myData = SPClientTemplates.Utility.GetFormContextForCurrentField(rCtx); - - if (_myData == null || _myData.fieldSchema == null) - return ''; - - var _autoFillControl: SPClientAutoFill; - var _textInputElt: HTMLInputElement; - var _textInputId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$' + _myData.fieldSchema.Type + 'Field'; - var _autofillContainerId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$AutoFill'; - - var validators = new SPClientForms.ClientValidation.ValidatorSet(); - if (_myData.fieldSchema.Required) { - validators.RegisterValidator(new SPClientForms.ClientValidation.RequiredValidator()); - } - _myData.registerClientValidator(_myData.fieldName, validators); - - _myData.registerInitCallback(_myData.fieldName, initAutoFillControl); - _myData.registerFocusCallback(_myData.fieldName, function () { - if (_textInputElt != null) - _textInputElt.focus(); - }); - _myData.registerValidationErrorCallback(_myData.fieldName, function (errorResult) { - SPFormControl_AppendValidationErrorMessage(_textInputId, errorResult); - }); - _myData.registerGetValueCallback(_myData.fieldName, () => _myData.fieldValue); - _myData.updateControlValue(_myData.fieldName, _myData.fieldValue); - - return buildAutoFillControl(); - - function initAutoFillControl() { - _textInputElt = document.getElementById(_textInputId); - - SP.SOD.executeFunc("autofill.js", "SPClientAutoFill", () => { - _autoFillControl = new SPClientAutoFill(_textInputId, _autofillContainerId, (_) => callback()); - var callback = init({ - renderContext: rCtx, - fieldContext: _myData, - autofill: _autoFillControl, - control: _textInputElt, - }); - - //_autoFillControl.AutoFillMinTextLength = 2; - //_autoFillControl.VisibleItemCount = 15; - //_autoFillControl.AutoFillTimeout = 500; - }); - - } - //function OnPopulate(targetElement: HTMLInputElement) { - - //} - - //function OnLookupValueChanged() { - // _myData.updateControlValue(_myData.fieldName, GetCurrentLookupValue()); - //} - //function GetCurrentLookupValue() { - // return _valueStr; - //} - function buildAutoFillControl() { - var result: string[] = []; - result.push('
    '); - result.push(''); - - result.push("
    "); - result.push("
    "); - - return result.join(""); - } - } - - - } - - seachLookup(fieldName: string): ICSR { - return this.autofill(fieldName, (ctx: IAutoFillFieldContext) => { - var _myData = ctx.fieldContext; - var _schema = _myData.fieldSchema; - if (_myData.fieldSchema.Type != 'Lookup') { - return null; - } - - var _valueStr = _myData.fieldValue != null ? _myData.fieldValue : ''; - var _selectedValue = SPClientTemplates.Utility.ParseLookupValue(_valueStr); - var _noValueSelected = _selectedValue.LookupId == 0; - ctx.control.value = _selectedValue.LookupValue; - $addHandler(ctx.control, "blur", _ => { - if (ctx.control.value == '') { - _myData.fieldValue = ''; - _myData.updateControlValue(fieldName, _myData.fieldValue); - } - }); - - if (_noValueSelected) - _myData.fieldValue = ''; - - var _autoFillControl = ctx.autofill; - _autoFillControl.AutoFillMinTextLength = 2; - _autoFillControl.VisibleItemCount = 15; - _autoFillControl.AutoFillTimeout = 500; - - return () => { - var value = ctx.control.value; - _autoFillControl.PopulateAutoFill([AutoFillOptionBuilder.buildLoadingItem('Please wait...')], onSelectItem); - - SP.SOD.executeFunc("sp.search.js", "Microsoft.SharePoint.Client.Search.Query", () => { - var Search = Microsoft.SharePoint.Client.Search.Query; - var ctx = SP.ClientContext.get_current(); - var query = new Search.KeywordQuery(ctx); - query.set_rowLimit(_autoFillControl.VisibleItemCount); - query.set_queryText('contentclass:STS_ListItem ListID:{' + _schema.LookupListId + '} ' + value); - var selectProps = query.get_selectProperties(); - selectProps.clear(); - //TODO: Handle ShowField attribute - selectProps.add('Title'); - selectProps.add('ListItemId'); - var executor = new Search.SearchExecutor(ctx); - var result = executor.executeQuery(query); - ctx.executeQueryAsync( - () => { - //TODO: Discover proper way to load collection - var tableCollection = new Search.ResultTableCollection(); - tableCollection.initPropertiesFromJson(result.get_value()); - - var relevantResults = tableCollection.get_item(0); - var rows = relevantResults.get_resultRows(); - - var items = []; - for (var i = 0; i < rows.length; i++) { - items.push(AutoFillOptionBuilder.buildOptionItem(parseInt(rows[i]["ListItemId"], 10), rows[i]["Title"])); - } - - items.push(AutoFillOptionBuilder.buildSeparatorItem()); - - if (relevantResults.get_totalRows() == 0) - items.push(AutoFillOptionBuilder.buildFooterItem("No results. Please refine your query.")); - else - items.push(AutoFillOptionBuilder.buildFooterItem("Showing " + rows.length + " of" + relevantResults.get_totalRows() + " items!")); - - _autoFillControl.PopulateAutoFill(items, onSelectItem); - - }, - (sender, args) => { - _autoFillControl.PopulateAutoFill([AutoFillOptionBuilder.buildFooterItem("Error executing query/ See log for details.")], onSelectItem); - console.log(args.get_message()); - }); - }); - } - - function onSelectItem(targetInputId, item: ISPClientAutoFillData) { - var targetElement = ctx.control; - targetElement.value = item[SPClientAutoFill.DisplayTextProperty]; - _selectedValue.LookupId = item[SPClientAutoFill.KeyProperty]; - _selectedValue.LookupValue = item[SPClientAutoFill.DisplayTextProperty]; - _myData.fieldValue = item[SPClientAutoFill.KeyProperty] + ';#' + item[SPClientAutoFill.TitleTextProperty]; - _myData.updateControlValue(_myData.fieldSchema.Name, _myData.fieldValue); - } - - }); - } - - lookupAddNew(fieldName: string, prompt: string, showDialog?: boolean, contentTypeId?: string): ICSR { - return this.onPostRenderField(fieldName, - (schema: SPClientTemplates.FieldSchema_InForm_Lookup, ctx: SPClientTemplates.RenderContext_FieldInForm) => { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) - - var control = CSR.getControl(schema); - if (control) { - var weburl = _spPageContextInfo.webServerRelativeUrl; - if (weburl[weburl.length - 1] == '/') { - weburl = weburl.substring(0, weburl.length - 1); - } - var newFormUrl = weburl + '/_layouts/listform.aspx/listform.aspx?PageType=8' - + "&ListId=" + encodeURIComponent('{' + schema.LookupListId + '}'); - if (contentTypeId) { - newFormUrl += '&ContentTypeId=' + contentTypeId; - } - - var link = document.createElement('a'); - link.href = "javascript:NewItem2(event, \'" + newFormUrl + "&Source=" + encodeURIComponent(document.location.href) + "')"; - link.textContent = prompt; - if (control.nextElementSibling) { - control.parentElement.insertBefore(link, control.nextElementSibling); - } else { - control.parentElement.appendChild(link); - } - - if (showDialog) { - $addHandler(link, "click", (e: Sys.UI.DomEvent) => { - SP.SOD.executeFunc('sp.ui.dialog.js', 'SP.UI.ModalDialog.ShowPopupDialog', () => { - SP.UI.ModalDialog.ShowPopupDialog(newFormUrl); - }); - e.stopPropagation(); - e.preventDefault(); - }); - } - } - }); - } - - register() { - if (!this.IsRegistered) { - SPClientTemplates.TemplateManager.RegisterTemplateOverrides(this); - this.IsRegistered = true; - } - } - } - - export class AutoFillOptionBuilder { - - static buildFooterItem(title: string): ISPClientAutoFillData { - var item = {}; - - item[SPClientAutoFill.DisplayTextProperty] = title; - item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Footer; - - return item; - } - - static buildOptionItem(id: number, title: string, displayText?: string, subDisplayText?: string): ISPClientAutoFillData { - - var item = {}; - - item[SPClientAutoFill.KeyProperty] = id; - item[SPClientAutoFill.DisplayTextProperty] = displayText || title; - item[SPClientAutoFill.SubDisplayTextProperty] = subDisplayText; - item[SPClientAutoFill.TitleTextProperty] = title; - item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Option; - - return item; - } - - static buildSeparatorItem(): ISPClientAutoFillData { - var item = {}; - item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Separator; - return item; - } - - static buildLoadingItem(title: string): ISPClientAutoFillData { - var item = {}; - - item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Loading; - item[SPClientAutoFill.DisplayTextProperty] = title; - return item; - } - - } - - /** Lightweight client-side rendering template overrides.*/ - export interface ICSR { - /** Override rendering template. - @param name Name of template to override. - @param template New template. - */ - template(name: string, template: string): ICSR; - - /** Override rendering template. - @param name Name of template to override. - @param template New template. - */ - template(name: string, template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; - - /** Override field rendering template. - @param name Internal name of field to override. - @param name Name of template to override. - @param template New template. - */ - fieldTemplate(field: string, name: string, template: string): ICSR; - - /** Override field rendering template. - @param name Internal name of field to override. - @param name Name of template to override. - @param template New template. - */ - fieldTemplate(field: string, name: string, template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; - - /** Sets pre-render callbacks. Callback called before rendering starts. - @param callbacks pre-render callbacks. - */ - onPreRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR; - - /** Sets post-render callbacks. Callback called after rendered html inserted to DOM. - @param callbacks post-render callbacks. - */ - onPostRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR; - - /** Sets pre-render callbacks for field. Callback called before rendering starts. Correctly handles form rendering. - @param fieldName Internal name of the field. - @param callbacks pre-render callbacks. - */ - onPreRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR; - - /** Sets post-render callbacks. Callback called after rendered html inserted to DOM. Correctly handles form rendering. - @param fieldName Internal name of the field. - @param callbacks post-render callbacks. - */ - onPostRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR; - - /** Registers overrides in client-side templating engine.*/ - register(): void; - - /** Override View rendering template. - @param template New view template. - */ - view(template: string): ICSR; - - /** Override View rendering template. - @param template New view template. - */ - view(template: (ctx: SPClientTemplates.RenderContext_InView) => string): ICSR; - view(template: (ctx: SPClientTemplates.RenderContext_Form) => string): ICSR; - - /** Override Item rendering template. - @param template New item template. - */ - item(template: string): ICSR; - - /** Override Item rendering template. - @param template New item template. - */ - item(template: (ctx: SPClientTemplates.RenderContext_ItemInView) => string): ICSR; - item(template: (ctx: SPClientTemplates.RenderContext_Form) => string): ICSR; - - /** Override Header rendering template. - @param template New header template. - */ - header(template: string): ICSR; - - /** Override Header rendering template. - @param template New header template. - */ - header(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; - - /** Override Body rendering template. - @param template New body template. - */ - body(template: string): ICSR; - - /** Override Body rendering template. - @param template New body template. - */ - body(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; - - /** Override Footer rendering template. - @param template New footer template. - */ - footer(template: string): ICSR; - - /** Override Footer rendering template. - @param template New footer template. - */ - footer(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; - - /** Override View rendering template for specified field. - @param fieldName Internal name of the field. - @param template New View template. - */ - fieldView(fieldName: string, template: string): ICSR; - - /** Override View rendering template for specified field. - @param fieldName Internal name of the field. - @param template New View template. - */ - fieldView(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInView) => string): ICSR; - - /** Override DisplyForm rendering template for specified field. - @param fieldName Internal name of the field. - @param template New DisplyForm template. - */ - fieldDisplay(fieldName: string, template: string): ICSR; - - /** Override DisplyForm rendering template. - @param fieldName Internal name of the field. - @param template New DisplyForm template. - */ - fieldDisplay(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; - - /** Override EditForm rendering template for specified field. - @param fieldName Internal name of the field. - @param template New EditForm template. - */ - fieldEdit(fieldName: string, template: string): ICSR; - - /** Override EditForm rendering template. - @param fieldName Internal name of the field. - @param template New EditForm template. - */ - fieldEdit(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; - - /** Override NewForm rendering template for specified field. - @param fieldName Internal name of the field. - @param template New NewForm template. - */ - fieldNew(fieldName: string, template: string): ICSR; - - /** Override NewForm rendering template. - @param fieldName Internal name of the field. - @param template New NewForm template. - */ - fieldNew(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; - - - /** Set initial value for field. - @param fieldName Internal name of the field. - @param value Initial value for field. - */ - setInitialValue(fieldName: string, value: any): ICSR; - - /** Make field hidden in list view and standard forms. - @param fieldName Internal name of the field. - */ - makeHidden(fieldName: string): ICSR - - - /** Replace New and Edit templates for field to Display template. - @param fieldName Internal name of the field. - */ - makeReadOnly(fieldName: string): ICSR - - /** Create cascaded Lookup Field. - @param fieldName Internal name of the field. - @param camlFilter CAML predicate expression (inside Where clause). Use {FieldName} tokens for dependency fields substitutions. - */ - filteredLookup(fieldName: string, camlFilter: string, listname?: string, lookupField?: string): ICSR - - /** Auto computes text-based field value based on another fields. - @param targetField Internal name of the field. - @param transform Function combines source field values. - @param sourceField Internal names of source fields. - */ - computedValue(targetField: string, transform: (...values: string[]) => string, ...sourceField: string[]): ICSR - - /** Field text value with autocomplete based on autofill.js - @param fieldName Internal name of the field. - @param ctx AutoFill context. - */ - autofill(fieldName: string, init: (ctx: IAutoFillFieldContext) => () => void): ICSR - - /** Replace defult dropdown to search-based autocomplete for Lookup field. - @param fieldName Internal name of the field. - */ - seachLookup(fieldName: string): ICSR; - - /** Adds link to add new value to lookup list. - @param fieldName Internal name of the field. - @param prompt Text to display as a link to add new value. - @param contentTypeID Default content type for new item. - */ - lookupAddNew(fieldName: string, prompt: string, showDialog?: boolean, contentTypeId?: string): ICSR; - - koEditField(fieldName: string, template: string, vm: IKoFieldInForm, dependencyFields?: string[]): ICSR; - - - } - - export interface IAutoFillFieldContext { - renderContext: SPClientTemplates.RenderContext_FieldInForm; - fieldContext: SPClientTemplates.ClientFormContext; - autofill: SPClientAutoFill; - control: HTMLInputElement; - } - - export interface IKoFieldInForm { - renderingContext?:SPClientTemplates.RenderContext_FieldInForm; - value?:KnockoutObservable; - } - - - interface IFormRenderContexWithHook extends SPClientTemplates.RenderContext_FieldInForm { - FormContextHook: IFormContextHook; - } - - interface IFormContextHook { - [fieldName: string]: IFormContextHookField; - } - - interface IFormContextHookField { - fieldSchema?: SPClientTemplates.FieldSchema_InForm; - lastValue?: any; - getValue?: () => any; - updatedValueCallbacks: UpdatedValueCallback[]; - } - - - function ensureFormContextHookField(hook: IFormContextHook, fieldName: string): IFormContextHookField { - return hook[fieldName] = hook[fieldName] || { - updatedValueCallbacks: [] - }; - - } - - class BooleanValueValidator implements SPClientForms.ClientValidation.IValidator { - constructor(public valueGetter: () => boolean, public validationMessage: string) { } - - Validate(value: any): SPClientForms.ClientValidation.ValidationResult { - return new SPClientForms.ClientValidation.ValidationResult(!this.valueGetter(), this.validationMessage); - } - } - -} - -if (typeof SP == 'object' && SP && typeof SP.SOD == 'object' && SP.SOD) { - SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs("typescripttemplates.ts"); -} - - -//mquery.ts - - - - -module spdevlab { - export module mQuery { - export class DynamicTable { - - // private fields - _domContainer:HTMLElement; - _tableContainer:MQueryResultSetElements; - - _rowTemplateId:string = null; - _rowTemplateContent:string = null; - - _options = { - tableCnt: '.spdev-rep-tb', - addCnt: '.spdev-rep-tb-add', - removeCnt: '.spdev-rep-tb-del' - }; - - // public methods - init(domContainer: HTMLElement, options) { - - if (m$.isDefinedAndNotNull(options)) { - m$.extend(this._options, options); - } - - this._initContainers(domContainer); - - this._initRowTemplate(); - this._initEvents(); - this._showUI(); - } - - // private methods - _initContainers(domContainer) { - - this._domContainer = domContainer; - this._tableContainer = m$(this._options.tableCnt, this._domContainer); - } - - _showUI() { - m$(this._domContainer).css("display", ""); - } - - _initEvents() { - - m$(this._options.addCnt, this._domContainer).click(() => { - - if (m$.isDefinedAndNotNull(this._rowTemplateContent)) { - - m$(this._tableContainer).append(this._rowTemplateContent); - - m$("tr:last-child " + this._options.removeCnt, this._tableContainer).click( (e) => { - - var targetElement = e.currentTarget; - var parentRow = m$(targetElement).parents("tr").first(); - - m$(parentRow).remove(); - }); - } - - return false; - }); - } - - _initRowTemplate() { - var templateId = m$(this._tableContainer).attr("template-id"); - - if (m$.isDefinedAndNotNull(templateId)) { - this._rowTemplateId = templateId; - this._rowTemplateContent = DynamicTable._templates[templateId]; - } - } - - static _templates:string[] = []; - static initTables() { - // init templates - m$('script').forEach((template:HTMLElement) => { - - var id = m$(template).attr("dynamic-table-template-id"); - - if (m$.isDefinedAndNotNull(id)) { - DynamicTable._templates[id] = template.innerHTML; - } - }); - - // init tables - m$(".spdev-rep-tb-cnt").forEach( divContainer => { - - var dynamicTable = new DynamicTable(); - - dynamicTable.init(divContainer, { - removeCnt: '.spdev-rep-tb-del-override' - }); - }); - } - - }; - - - } -} - -m$.ready(() => { - spdevlab.mQuery.DynamicTable.initTables(); -}); - - -//whoisapppart.ts - - -module _ { - var queryString = parseQueryString(); - var isIframe = queryString['DisplayMode'] == 'iframe' - var spHostUrl = queryString['SPHostUrl']; - var editmode = Number(queryString['editmode']); - var includeDetails = queryString['boolProp'] == 'true'; - - prepareVisual(); - m$.ready(() => { - loadPeoplePicker('peoplePicker'); - partProperties(); - - if (isIframe) { - partResize(); - } - }); - - //Load the people picker - function loadPeoplePicker(peoplePickerElementId: string) { - var schema: ISPClientPeoplePickerSchema = { - PrincipalAccountType: "User", - AllowMultipleValues: false, - Width: 300, - OnUserResolvedClientScript: onUserResolvedClientScript - } - - SPClientPeoplePicker.InitializeStandalonePeoplePicker(peoplePickerElementId, null, schema); - } - - function onUserResolvedClientScript(el: string, users: ISPClientPeoplePickerEntity[]) { - if (users.length > 0) { - var person = users[0]; - var accountName = person.Key; - - var context = SP.ClientContext.get_current(); - - var peopleManager = new SP.UserProfiles.PeopleManager(context); - var personProperties = peopleManager.getPropertiesFor(accountName); - - context.load(personProperties); - context.executeQueryAsync((sender, args) => { - - $get("basicInfo").style.display = 'block'; - - var userPic = personProperties.get_userProfileProperties()["PictureURL"]; - $get("pic").innerHTML = ' + personProperties.get_displayName() + '; - - $get("name").innerHTML = '' + personProperties.get_displayName() + ''; - $get("email").innerHTML = '' + personProperties.get_email() + ''; - $get("title").innerHTML = personProperties.get_title(); - $get("department").innerHTML = person.EntityData.Department; - $get("phone").innerHTML = person.EntityData.MobilePhone; - - var properties = personProperties.get_userProfileProperties(); - var messageText = ""; - for (var key in properties) { - messageText += "
    [" + key + "]: \"" + properties[key] + "\""; - } - $get("detailInfo").innerHTML = messageText; - - if (isIframe) { - partResize(); - } - - }, (sender, args) => { alert('Error: ' + args.get_message()); }); - - } - } - - function partProperties() { - - if (editmode == 1) { - $get("editmodehdr").style.display = "inline"; - $get("content").style.display = "none"; - } - else if (includeDetails) { - $get('detailInfo').style.display = 'block'; - - $get("editmodehdr").style.display = "none"; - $get("content").style.display = "inline"; - } - } - - function partResize() { - var bounds = Sys.UI.DomElement.getBounds(document.body); - parent.postMessage('resize(' + bounds.width + ',' + bounds.height + ')', '*'); - } - - function prepareVisual() { - if (isIframe) { - //Create a Link element for the defaultcss.ashx resource - var linkElement = document.createElement('link'); - linkElement.setAttribute('rel', 'stylesheet'); - linkElement.setAttribute('href', spHostUrl + '/_layouts/15/defaultcss.ashx'); - - //Add the linkElement as a child to the head section of the html - document.head.appendChild(linkElement); - } else { - - m$.ready(() => { - var nav = new SP.UI.Controls.Navigation('navigation', { - appIconUrl: queryString['SPHostLogo'], - appTitle: document.title - }); - nav.setVisible(true); - $get('apppart-notification').style.display = 'block'; - document.body.style.overflow = 'visible'; - }); - } - } - - function parseQueryString() { - var result = {}; - var qs = document.location.search.split('?')[1]; - if (qs) { - var parts = qs.split('&'); - for (var i = 0; i < parts.length; i++) { - if (parts[i]) { - var pair = parts[i].split('='); - result[pair[0]] = decodeURIComponent(pair[1]); - } - } - } - return result; - } -} - -//taxonomy -module SP { - - // Class - export class ClientContextPromise extends SP.ClientContext { - /** To use this function, you must ensure that jQuery and CSOMPromise js files are loaded to the page */ - executeQueryPromise(): JQueryPromise { - var deferred = jQuery.Deferred(); - this.executeQueryAsync(function (sender, args) { - deferred.resolve(sender, args); - }, - function (sender, args) { - deferred.reject(sender, args); - }) - return deferred.promise(); - } - - constructor(serverRelativeUrlOrFullUrl: string) { - super(serverRelativeUrlOrFullUrl); - } - - static get_current(): ClientContextPromise { - return new ClientContextPromise(_spPageContextInfo.siteServerRelativeUrl); - } - - } - -} - -SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs("CSOMPromise.ts"); - -module _ { - var context: SP.ClientContextPromise; - var web: SP.Web; - var site: SP.Site; - var session: SP.Taxonomy.TaxonomySession; - var termStore: SP.Taxonomy.TermStore; - var groups: SP.Taxonomy.TermGroupCollection; - - // This code runs when the DOM is ready and creates a context object - // which is needed to use the SharePoint object model. - // It also wires up the click handlers for the two HTML buttons in Default.aspx. - $(document).ready(function () { - context = SP.ClientContextPromise.get_current(); - site = context.get_site(); - web = context.get_web(); - $('#listExisting').click(function () { listGroups(); }); - $('#createTerms').click(function () { createTerms(); }); - }); - - // When the listExisting button is clicked, start by loading - // a TaxonomySession for the current context. Also get and load - // the associated term store. - function listGroups() { - session = SP.Taxonomy.TaxonomySession.getTaxonomySession(context); - termStore = session.getDefaultSiteCollectionTermStore(); - context.load(session); - context.load(termStore); - context.executeQueryAsync(onListTaxonomySession, onFailListTaxonomySession); - } - - // Runs when the executeQueryAsync method in the listGroups function has succeeded. - // In this case, get and load the groups associated with the term store that we - // know we now have a reference to. - function onListTaxonomySession() { - groups = termStore.get_groups(); - context.load(groups); - context.executeQueryAsync(onRetrieveGroups, onFailRetrieveGroups); - } - - // Runs when the executeQueryAsync method in the onListTaxonomySession function has succeeded. - // In this case, loop through all the groups and add a clickable div element to the report area - // for each group. - // NOTE: We clear the report area first to ensure we have a clean place to write to. - // Also note how we create a click event handler for each div on-the-fly, and that we pass in the - // current group ID to that function. So when the user clicks one of these divs, we will know which - // one was clicked. - function onRetrieveGroups() { - $('#report').children().remove(); - - var groupEnum = groups.getEnumerator(); - - // For each group, we'll build a clickable div. - while (groupEnum.moveNext()) { - (() => { - var currentGroup = groupEnum.get_current(); - var groupName = document.createElement("div"); - groupName.setAttribute("style", "float:none;cursor:pointer"); - var groupID = currentGroup.get_id(); - groupName.setAttribute("id", groupID.toString()); - $(groupName).click(() => showTermSets(groupID)); - groupName.appendChild(document.createTextNode(currentGroup.get_name())); - $('#report').append(groupName); - })(); - } - } - - // This is the function that runs when the user clicks one of the divs - // that we created in the onRetrieveGroups function. We can know which - // div was clicked by interrogating the groupID parameter. So what we'll - // do is retrieve a reference to the group with the same ID as the div, and - // then add the term sets that belong to that group under the div that was clicked. - function showTermSets(groupID: SP.Guid) { - - // First thing is to remnove the divs under the group DIV to ensure we have a clean place to write to. - // The reason we don't clear them all is becuase we want to retain the text node of the - // group div. I.E. that's why we use "parentDiv.childNodes.length>1" as our loop - // controller. - var parentDiv = document.getElementById(groupID.toString()); - while (parentDiv.childNodes.length > 1) { - parentDiv.removeChild(parentDiv.lastChild); - } - - // For each term set, we'll build a clickable div - var currentGroup = groups.getById(groupID); - - // We need to load and populate the matching group first, or the - // term sets that it contains will be inaccessible to our code. - context.load(currentGroup); - var termSets: SP.Taxonomy.TermSetCollection; - context.executeQueryPromise() - .then( - () => { - // The group is now available becuase this is the - // success callback. So now we'll load and populate the - // term set collection. We have to do this before we can - // iterate through the collection, so we can do this - // with the following nested executeQueryAsync method call. - termSets = currentGroup.get_termSets(); - context.load(termSets); - return context.executeQueryPromise() - }) - .then(() => { - // The term sets are now available becuase this is the - // success callback. So now we'll iterate through the collection - // and create the clickable div. Also note how we create a - // click event handler for each div on-the-fly, and that we pass in the - // current group ID and term set ID to that function. So when the user - // clicks one of these divs, we will know which - // one was clicked by its term set ID, and to which group it belongs by its - // group ID. We also pass in the event object, so that we can cancel the bubble - // because this clickable div will be inside a parent clickable div and we - // don't want the parent's event to fire. - var termSetEnum = termSets.getEnumerator(); - while (termSetEnum.moveNext()) { - (() => { - var currentTermSet = termSetEnum.get_current(); - var termSetName = document.createElement("div"); - termSetName.appendChild(document.createTextNode(" + " + currentTermSet.get_name())); - termSetName.setAttribute("style", "float:none;cursor:pointer;"); - var termSetID = currentTermSet.get_id(); - termSetName.setAttribute("id", termSetID.toString()); - $(termSetName).click(e => showTerms(e, groupID, termSetID)); - parentDiv.appendChild(termSetName); - })(); - } - - }) - .fail(() => parentDiv.appendChild(document.createTextNode("An error occurred in loading the term sets for this group"))); - } - - - // This is the function that runs when the user clicks one of the divs - // that we created in the showTermSets function. We can know which - // div was clicked by interrogating the termSetID parameter. So what we'll - // do is retrieve a reference to the term set with the same ID as the div, and - // then add the term that belong to that term set under the div that was clicked. - - function showTerms(event: JQueryEventObject, groupID: SP.Guid, termSetID: SP.Guid) { - - // First, cancel the bubble so that the group div click handler does not also fire - // because that removes all term set divs and we don't want that here. - event.cancelBubble = true; - - // Get a reference to the term set div that was click and - // remove its children (apart from the TextNode that is currently - // showing the term set name. - var parentDiv = document.getElementById(termSetID.toString()); - while (parentDiv.childNodes.length > 1) { - parentDiv.removeChild(parentDiv.lastChild); - } - - // We need to load and populate the matching group first, or the - // term sets that it contains will be inaccessible to our code. - var currentGroup = groups.getById(groupID); - var termSets:SP.Taxonomy.TermSetCollection; - var currentTermSet:SP.Taxonomy.TermSet; - var terms:SP.Taxonomy.TermCollection; - - context.load(currentGroup); - context - .executeQueryPromise() - .then(() => { - // The group is now available becuase this is the - // success callback. So now we'll load and populate the - // term set collection. We have to do this before we can - // iterate through the collection, so we can do this - // with the following nested executeQueryAsync method call. - termSets = currentGroup.get_termSets(); - context.load(termSets); - return context.executeQueryPromise(); - }) - .then(() => { - currentTermSet = termSets.getById(termSetID); - context.load(currentTermSet); - return context.executeQueryPromise(); - }) - .then(() => { - terms = currentTermSet.get_terms(); - context.load(terms); - return context.executeQueryPromise(); - }) - .then(() => { - var termsEnum = terms.getEnumerator(); - while (termsEnum.moveNext()) { - var currentTerm = termsEnum.get_current(); - - var term = document.createElement("div"); - term.appendChild(document.createTextNode(" - " + currentTerm.get_name())); - term.setAttribute("style", "float:none;margin-left:10px;"); - parentDiv.appendChild(term); - } - }) - .fail(() => parentDiv.appendChild(document.createTextNode("An error occurred when trying to retrieve terms in this term set"))); - } - - // Runs when the executeQueryAsync method in the onListTaxonomySession function has failed. - // In this case, clear the report area in the page and tell the user what went wrong. - function onFailRetrieveGroups(sender, args) { - $('#report').children().remove(); - $('#report').append("Failed to retrieve groups. Error:" + args.get_message()); - } - - // Runs when the executeQueryAsync method in the listGroups function has failed. - // In this case, clear the report area in the page and tell the user what went wrong. - function onFailListTaxonomySession(sender, args) { - $('#report').children().remove(); - $('#report').append("Failed to get session. Error: " + args.get_message()); - } - - - // When the createTerms button is clicked, start by loading - // a TaxonomySession for the current context. Also get and load - // the associated term store. - function createTerms() { - session = SP.Taxonomy.TaxonomySession.getTaxonomySession(context); - termStore = session.getDefaultSiteCollectionTermStore(); - context.load(session); - context.load(termStore); - context.executeQueryAsync(onGetTaxonomySession, onFailTaxonomySession); - } - - - // This function is the success callback for loading the session and store from the createTerms function - function onGetTaxonomySession() { - // Create six GUIDs that we will need when we create a new group, term set, and associated terms - var guidGroupValue = SP.Guid.newGuid(); - var guidTermSetValue = SP.Guid.newGuid(); - var guidTerm1 = SP.Guid.newGuid(); - var guidTerm2 = SP.Guid.newGuid(); - var guidTerm3 = SP.Guid.newGuid(); - var guidTerm4 = SP.Guid.newGuid(); - - // Create a new group - var myGroup = termStore.createGroup("CustomTerms", guidGroupValue); - - // Create a new term set in the newly-created group - var myTermSet = myGroup.createTermSet("Privacy", guidTermSetValue, 1033); - - // Create four new terms in the newly-created term set - myTermSet.createTerm("Top Secret", 1033, guidTerm1); - myTermSet.createTerm("Company Confidential", 1033, guidTerm2); - myTermSet.createTerm("Partners Only", 1033, guidTerm3); - myTermSet.createTerm("Public", 1033, guidTerm4); - - // Ensure the groups variable has been set, because when this all succeeds we will - // effectively run the same code as if the user had clicked the listGroups button - groups = termStore.get_groups(); - context.load(groups); - - // Execute all the preceeding statements in this function - context.executeQueryAsync(onAddTerms, onFailAddTerms); - - } - - // If all is well with creating the terms, then this function will run. - // Effectively this runs the same code as if the user had clicked the listGroups button - // so the user will see their newly-created group - function onAddTerms() { - listGroups(); - } - - // Runs when the executeQueryAsync method in the onGetTaxonomySession function has failed. - // In this case, clear the report area in the page and tell the user what went wrong. - function onFailAddTerms(sender, args) { - $('#report').children().remove(); - $('#report').append("Failed to add terms. Error: " + args.get_message()); - } - - // Runs when the executeQueryAsync method in the createTerms function has failed. - // In this case, clear the report area in the page and tell the user what went wrong. - function onFailTaxonomySession(sender, args) { - $('#report').children().remove(); - $('#report').append("Failed to get session. Error: " + args.get_message()); - } - -}; - -//publishing.ts -// Variables used in various callbacks -JSRequest.EnsureSetup(); - -SP.SOD.execute('mquery.js', 'm$.ready', () => { - var context = SP.ClientContext.get_current(); - var web = context.get_web(); - m$('#CreatePage').click(createPage); -}); - -function createPage(evt) { - SP.SOD.execute('sp.js', 'SP.ClientConext', () => { - SP.SOD.execute('sp.publishing.js', 'SP.Publishing', () => { - var context = SP.ClientContext.get_current(); - - - var hostUrl = decodeURIComponent(JSRequest.QueryString["SPHostUrl"]); - var hostcontext = new SP.AppContextSite(context, hostUrl); - var web = hostcontext.get_web(); - var pubWeb = SP.Publishing.PublishingWeb.getPublishingWeb(context, web); - context.load(web); - context.load(pubWeb); - context.executeQueryAsync( - // Success callback after getting the host Web as a PublishingWeb. - // We now want to add a new Publishing Page. - function () { - var pageInfo = new SP.Publishing.PublishingPageInformation(); - var newPage = pubWeb.addPublishingPage(pageInfo); - context.load(newPage); - context.executeQueryAsync( - function () { - - // Success callback after adding a new Publishing Page. - // We want to get the actual list item that is represented by the Publishing Page. - var listItem = newPage.get_listItem(); - context.load(listItem); - context.executeQueryAsync( - - // Success callback after getting the actual list item that is - // represented by the Publishing Page. - // We can now get its FieldValues, one of which is its FileLeafRef value. - // We can then use that value to build the Url to the new page - // and set the href or our link to that Url. - function () { - var link = document.getElementById("linkToPage"); - link.setAttribute("href", web.get_url() + "/Pages/" + listItem.get_fieldValues().FileLeafRef); - link.innerText = "Go to new page!"; - }, - - // Failure callback after getting the actual list item that is - // represented by the Publishing Page. - function (sender, args) { - alert('Failed to get new page: ' + args.get_message()); - } - ); - }, - // Failure callback after trying to add a new Publishing Page. - function (sender, args) { - alert('Failed to Add Page: ' + args.get_message()); - } - ); - }, - // Failure callback after trying to get the host Web as a PublishingWeb. - function (sender, args) { - alert('Failed to get the PublishingWeb: ' + args.get_message()); - } - ); - }); - }); -} - -//likes -module SampleReputation { - - interface MyList extends SPClientTemplates.RenderContext_InView { - listId: string; - } - - class MyItem { - - id: number; - title: string; - likesCount: number; - isLikedByCurrentUser: boolean; - - constructor(public row: SPClientTemplates.Item) { - this.id = parseInt(row['ID']); - this.title = row['Title']; - this.likesCount = parseInt(row['LikesCount']) || 0; - this.isLikedByCurrentUser = this.getLike(row['LikedBy']); - } - - private getLike(likedBy): boolean { - if (likedBy && likedBy.length > 0) { - for (var i = 0; i < likedBy.length; i++) { - if (likedBy[i].id == _spPageContextInfo.userId) { - return true; - } - } - } - return false; - } - } - - function init() { - SP.SOD.registerSod('reputation.js', '/_layouts/15/reputation.js'); - SP.SOD.registerSod('typescripttemplates.ts', '/SPTypeScript/Extensions/typescripttemplates.js'); - SP.SOD.executeFunc('typescripttemplates.ts', 'CSR', () => { - CSR.override(10004, 1) - .onPreRender((ctx: MyList) => { - ctx.listId = ctx.listName.substring(1, 37); - }) - .header('
      ') - .body(renderTemplate) - .footer('
    ') - .register(); - }); - - SP.SOD.execute('mQuery.js', 'm$.ready', () => { - RegisterModuleInit('/SPTypeScript/ReputationModule/likes.js', init); - }); - - - SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs('likes.js'); - } - - function renderTemplate(ctx: MyList) { - var rows = ctx.ListData.Row; - var result = ''; - for (var i = 0; i < rows.length; i++) { - var item = new MyItem(rows[i]); - result += '\ -
  • ' + item.title +'\ - \ - ' + getLikeText(item.isLikedByCurrentUser) + '' + item.likesCount + '\ - \ -
  • '; - } - return result; - } - - function getLikeText(isLikedByCurrentUser: boolean) { - return isLikedByCurrentUser ? '\u2665' : '\u2661'; - } - - export function setLike(itemId: number, listId: string): void { - var context = SP.ClientContext.get_current(); - var isLiked = m$('#likesCountText' + itemId)[0].textContent == '\u2661'; - SP.SOD.executeFunc('reputation.js', 'Microsoft.Office.Server.ReputationModel.Reputation', function () { - Microsoft.Office.Server.ReputationModel.Reputation.setLike(context, listId, itemId, isLiked); - context.executeQueryAsync( - () => { - m$('#likesCountText' + itemId)[0].textContent = getLikeText(isLiked); - var likesCount = parseInt(m$('#likesCount' + itemId)[0].textContent); - m$('#likesCount' + itemId)[0].textContent = (isLiked ? likesCount + 1 : likesCount - 1).toString(); - }, - (sender, args) => { - alert(args.get_message()); - }); - }); - } - - init(); -} - - - -//code from https://github.com/gandjustas/SharePointAngularTS -module App { - "use strict"; -var app = angular.module("app", []); -} - -// Install the angularjs.TypeScript.DefinitelyTyped NuGet package -module App { - "use strict"; - - interface Iappcontroller { - title: string; - activate: () => void; - } - - class appcontroller implements Iappcontroller { - title: string = "appcontroller"; - lists: SP.List[]; - - static $inject: string[] = ["$SharePoint", "$spnotify"]; - - constructor(private $SharePoint: App.ISharePoint, private $n:App.ISpNotify) { - this.activate(); - } - - activate() { - var loading = this.$n.showLoading(true) - this.$SharePoint - .getLists() - .then(l => this.lists = l ) - .catch((e: string) => this.$n.show(e, true)) - .finally(() => this.$n.remove(loading) ); - ; - - } - } - - angular.module("app").controller("appcontroller", appcontroller); -} - - - -module App { - "use strict"; - - export interface ISharePoint { - getLists: () => ng.IPromise; - } - - class SharePointServcie implements ISharePoint { - static $inject: string[] = ["$q"]; - - constructor(public $q: ng.IQService) { - } - - getLists() { - var promise = this.$q.defer(); - SP.SOD.executeFunc("sp.js", "SP.ClientContext", () => { - var ctx = SP.ClientContext.get_current(); - var hostUrl = decodeURIComponent(SP.ScriptHelpers.getDocumentQueryPairs()['SPHostUrl']); - var appCtx = new SP.AppContextSite(ctx, hostUrl); - var hostWeb = appCtx.get_web(); - var lists = hostWeb.get_lists(); - ctx.load(lists); - - ctx.executeQueryAsync(() => { - var result: SP.List[] = []; - for (var e = lists.getEnumerator(); e.moveNext();) { - result.push(e.get_current()); - } - promise.resolve(result); - }, - (o, args) => { promise.reject(args.get_message()); }); - }); - return promise.promise; - } - } - - angular.module("app").service("$SharePoint", SharePointServcie); -} - - -// Install the angularjs.TypeScript.DefinitelyTyped NuGet package -module App { - "use strict"; - - export interface ISpNotify { - showLoading(sticky?: boolean) : string; - show(msg: string, sticky?: boolean): string; - remove(id: string):void; - } - - class SpNotify implements ISpNotify { - static $inject: string[] = []; - - - showLoading(sticky: boolean = false) { - return SP.UI.Notify.showLoadingNotification(sticky); - } - - show(msg: string, sticky: boolean = false) { - return SP.UI.Notify.addNotification(msg, sticky); - } - - remove(id: string) { - SP.UI.Notify.removeNotification(id); - } - } - - angular.module("app").service("$spnotify", SpNotify); -} - +/// +/// +/// +/// + + +//code from http://sptypescript.codeplex.com/ +//BasicTasksJSOM.ts +// Website tasks +function retrieveWebsite(resultpanel:HTMLElement) { + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + clientContext.load(oWebsite); + + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + resultpanel.innerHTML = "Web site title: " + oWebsite.get_title(); + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function retrieveWebsiteProps(resultpanel: HTMLElement) { + + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + + clientContext.load(oWebsite, "Description", "Created"); + + clientContext.executeQueryAsync(successHandler,errorHandler); + + function successHandler() { + resultpanel.innerHTML = "Description: " + oWebsite.get_description() + + "
    Date created: " + oWebsite.get_created(); + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function writeWebsiteProps(resultpanel: HTMLElement) { + + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + + oWebsite.set_description("This is an updated description."); + oWebsite.update(); + + clientContext.load(oWebsite, "Description"); + + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + + function successHandler() { + resultpanel.innerHTML = "Web site description: " + oWebsite.get_description(); + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +// Lists tasks +function readAllProps(resultpanel: HTMLElement) { + + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + + var collList = oWebsite.get_lists(); + clientContext.load(collList); + + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + + var listEnumerator = collList.getEnumerator(); + + var listInfo = ""; + while (listEnumerator.moveNext()) { + var oList = listEnumerator.get_current(); + listInfo += "Title: " + oList.get_title() + " Created: " + + oList.get_created().toString() + "
    "; + } + + resultpanel.innerHTML = listInfo; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function readSpecificProps(resultpanel: HTMLElement) { + + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + + var collList = oWebsite.get_lists(); + + clientContext.load(collList, "Include(Title, Id)"); + + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + + var listEnumerator = collList.getEnumerator(); + + var listInfo = ""; + while (listEnumerator.moveNext()) { + var oList = listEnumerator.get_current(); + listInfo += "Title: " + oList.get_title() + + " ID: " + oList.get_id().toString() + "
    "; + } + + resultpanel.innerHTML = listInfo; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function readColl(resultpanel: HTMLElement) { + + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var collList = oWebsite.get_lists(); + + var listInfoCollection = clientContext.loadQuery(collList, "Include(Title, Id)"); + + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + var listInfo = ""; + for (var i = 0; i < listInfoCollection.length; i++) { + var oList = listInfoCollection[i]; + listInfo += "Title: " + oList.get_title() + + " ID: " + oList.get_id().toString() + "
    "; + } + + resultpanel.innerHTML = listInfo; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function readFilter(resultpanel: HTMLElement) { + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var collList = oWebsite.get_lists(); + + var listInfoArray = clientContext.loadQuery(collList, + "Include(Title,Fields.Include(Title,InternalName))"); + + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + + for (var i = 0; i < listInfoArray.length; i++) { + var oList = listInfoArray[i]; + var collField = oList.get_fields(); + var fieldEnumerator = collField.getEnumerator(); + + var listInfo = ""; + while (fieldEnumerator.moveNext()) { + var oField = fieldEnumerator.get_current(); + var regEx = new RegExp("name", "ig"); + + if (regEx.test(oField.get_internalName())) { + listInfo += "List: " + oList.get_title() + + "
        Field Title: " + oField.get_title() + + "
        Field Internal name: " + oField.get_internalName(); + } + } + } + + resultpanel.innerHTML = listInfo; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +// Create, update and delete lists +function createList(resultpanel: HTMLElement) { + + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + + var listCreationInfo = new SP.ListCreationInformation(); + listCreationInfo.set_title("My Announcements List"); + listCreationInfo.set_templateType(SP.ListTemplateType.announcements); + + var oList = oWebsite.get_lists().add(listCreationInfo); + clientContext.load(oList); + + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + resultpanel.innerHTML = "Go to the list."; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function updateList(resultpanel: HTMLElement) { + + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + + var oList = oWebsite.get_lists().getByTitle("My Announcements List"); + oList.set_description("New Announcements List"); + oList.update(); + + clientContext.load(oList); + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + resultpanel.innerHTML = "Check the description in the list."; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function addField(resultpanel: HTMLElement) { + + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var oList = oWebsite.get_lists().getByTitle("My Announcements List"); + + var oField = oList.get_fields().addFieldAsXml( + "", + true, + SP.AddFieldOptions.defaultValue + ); + + var fieldNumber = clientContext.castTo(oField, SP.FieldNumber); + fieldNumber.set_maximumValue(100); + fieldNumber.set_minimumValue(35); + fieldNumber.update(); + + clientContext.load(oField); + + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + resultpanel.innerHTML = "The list with a new field."; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function deleteList(resultpanel: HTMLElement) { + var listTitle = "My Announcements List"; + + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var oList = oWebsite.get_lists().getByTitle(listTitle); + oList.deleteObject(); + + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + resultpanel.innerHTML = listTitle + " deleted."; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +// Create, update and delete folders +function createFolder(resultpanel: HTMLElement) { + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var oList = oWebsite.get_lists().getByTitle("Shared Documents"); + + var itemCreateInfo = new SP.ListItemCreationInformation(); + itemCreateInfo.set_underlyingObjectType(SP.FileSystemObjectType.folder); + itemCreateInfo.set_leafName("My new folder!"); + var oListItem = oList.addItem(itemCreateInfo); + oListItem.update(); + + clientContext.load(oListItem); + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + resultpanel.innerHTML = "Go to the document library to see your new folder."; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function updateFolder(resultpanel: HTMLElement) { + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var oList = oWebsite.get_lists().getByTitle("Shared Documents"); + + var oListItem = oList.getItemById(1); + oListItem.set_item("FileLeafRef", "My updated folder"); + oListItem.update(); + + clientContext.load(oListItem); + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + resultpanel.innerHTML = "Go to the document library to see your updated folder."; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function deleteFolder(resultpanel: HTMLElement) { + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var oList = oWebsite.get_lists().getByTitle("Shared Documents"); + + var oListItem = oList.getItemById(1); + oListItem.deleteObject(); + + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + resultpanel.innerHTML = "Go to the document library to make sure the folder is no longer there."; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +// List item tasks +function readItems(resultpanel: HTMLElement) { + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var oList = oWebsite.get_lists().getByTitle("Announcements"); + var camlQuery = new SP.CamlQuery(); + camlQuery.set_viewXml( + '' + + '1' + + '10' + ); + var collListItem = oList.getItems(camlQuery); + + clientContext.load(collListItem); + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + var listItemEnumerator = collListItem.getEnumerator(); + + var listItemInfo = ""; + while (listItemEnumerator.moveNext()) { + var oListItem = listItemEnumerator.get_current(); + listItemInfo += "ID: " + oListItem.get_id() + "
    " + + "Title: " + oListItem.get_item("Title") + "
    " + + "Body: " + oListItem.get_item("Body") + "
    "; + } + + resultpanel.innerHTML = listItemInfo; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function readInclude(resultpanel: HTMLElement) { + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var oList = oWebsite.get_lists().getByTitle("Announcements"); + var camlQuery = new SP.CamlQuery(); + camlQuery.set_viewXml('100'); + + var collListItem = oList.getItems(camlQuery); + + clientContext.load(collListItem, "Include(Id, DisplayName, HasUniqueRoleAssignments)"); + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + var listItemEnumerator = collListItem.getEnumerator(); + + var listItemInfo = ""; + while (listItemEnumerator.moveNext()) { + var oListItem = listItemEnumerator.get_current(); + listItemInfo += "ID: " + oListItem.get_id() + "
    " + + "Display name: " + oListItem.get_displayName() + "
    " + + "Unique role assignments: " + oListItem.get_hasUniqueRoleAssignments() + "
    "; + } + + resultpanel.innerHTML = listItemInfo; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +// Create, update and delete list items +function createListItem(resultpanel: HTMLElement) { + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var oList = oWebsite.get_lists().getByTitle("Announcements"); + + var itemCreateInfo = new SP.ListItemCreationInformation(); + var oListItem = oList.addItem(itemCreateInfo); + oListItem.set_item("Title", "My New Item!"); + oListItem.set_item("Body", "Hello World!"); + oListItem.update(); + + clientContext.load(oListItem); + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + resultpanel.innerHTML = "Go to the list to see your new item."; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function updateListItem(resultpanel: HTMLElement) { + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var oList = oWebsite.get_lists().getByTitle("Announcements"); + + var oListItem = oList.getItemById(1); + oListItem.set_item("Title", "My updated title"); + oListItem.update(); + + clientContext.load(oListItem); + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + resultpanel.innerHTML = "Go to the list to see your updated item."; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function deleteListItem(resultpanel: HTMLElement) { + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var oList = oWebsite.get_lists().getByTitle("Announcements"); + + var oListItem = oList.getItemById(1); + oListItem.deleteObject(); + + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + resultpanel.innerHTML = "Go to the list to make sure the item is no longer there."; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + + + +/** Lightweight client-side rendering template overrides.*/ +module CSR { + + export interface UpdatedValueCallback { + (value: any, fieldSchema?: SPClientTemplates.FieldSchema_InForm): void; + } + + /** Creates new overrides. Call .register() at the end.*/ + export function override(listTemplateType?: number, baseViewId?: number|string): ICSR { + return new csr(listTemplateType, baseViewId) + .onPreRender(hookFormContext) + .onPostRender(fixCsrCustomLayout); + + function hookFormContext(ctx: IFormRenderContexWithHook) { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + + for (var i = 0; i < ctx.ListSchema.Field.length; i++) { + var fieldSchemaInForm = ctx.ListSchema.Field[i]; + + if (!ctx.FormContextHook) { + ctx.FormContextHook = {} + + var oldRegisterGetValueCallback = ctx.FormContext.registerGetValueCallback; + ctx.FormContext.registerGetValueCallback = (fieldName, callback) => { + ctx.FormContextHook[fieldName].getValue = callback; + oldRegisterGetValueCallback(fieldName, callback); + }; + + var oldUpdateControlValue = ctx.FormContext.updateControlValue; + ctx.FormContext.updateControlValue = (fieldName: string, value: any) => { + oldUpdateControlValue(fieldName, value); + + var hookedContext = ensureFormContextHookField(ctx.FormContextHook, fieldName); + hookedContext.lastValue = value; + + var updatedCallbacks = ctx.FormContextHook[fieldName].updatedValueCallbacks; + for (var i = 0; i < updatedCallbacks.length; i++) { + updatedCallbacks[i](value, hookedContext.fieldSchema); + } + + } + } + ensureFormContextHookField(ctx.FormContextHook, fieldSchemaInForm.Name).fieldSchema = fieldSchemaInForm; + } + } + } + + function fixCsrCustomLayout(ctx: SPClientTemplates.RenderContext_Form) { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid + || ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { + return; + } + + if (ctx.ListSchema.Field.length > 1) { + var wpq = ctx.FormUniqueId; + var webpart = $get('WebPart' + wpq); + var forms = webpart.getElementsByClassName('ms-formtable'); + + if (forms.length > 0) { + var placeholder = $get(wpq + 'ClientFormTopContainer'); + var fragment = document.createDocumentFragment(); + for (var i = 0; i < placeholder.children.length; i++) { + fragment.appendChild(placeholder.children.item(i)); + } + + var form = forms.item(0); + form.parentNode.replaceChild(fragment, form); + } + + var old = ctx.CurrentItem; + ctx.CurrentItem = ctx.ListData.Items[0]; + var fields = ctx.ListSchema.Field; + for (var j = 0; j < fields.length; j++) { + var field = fields[j]; + var pHolderId = wpq + ctx.FormContext.listAttributes.Id + field.Name; + var span = $get(pHolderId); + if (span) { + span.outerHTML = ctx.RenderFieldByName(ctx, field.Name); + } + } + ctx.CurrentItem = old; + } + + } + + + } + + +//typescripttempltes.ts + declare var Strings:any; + export function getFieldValue(ctx: SPClientTemplates.RenderContext_Form, fieldName: string): any { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx; + if (contextWithHook.FormContextHook + && contextWithHook.FormContextHook[fieldName] + && contextWithHook.FormContextHook[fieldName].getValue) { + return contextWithHook.FormContextHook[fieldName].getValue(); + } + } + return null; + } + + export function getFieldSchema(ctx: SPClientTemplates.RenderContext_Form, fieldName: string): SPClientTemplates.FieldSchema_InForm { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx; + if (contextWithHook.FormContextHook + && contextWithHook.FormContextHook[fieldName]) { + return contextWithHook.FormContextHook[fieldName].fieldSchema; + } + } + return null; + } + + export function addUpdatedValueCallback(ctx: SPClientTemplates.RenderContext_Form, fieldName: string, callback: UpdatedValueCallback): void { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx; + if (contextWithHook.FormContextHook) { + var f = ensureFormContextHookField(contextWithHook.FormContextHook, fieldName); + var callbacks = f.updatedValueCallbacks; + if (callbacks.indexOf(callback) == -1) { + callbacks.push(callback); + if (f.lastValue) { + callback(f.lastValue, f.fieldSchema); + } + } + } + } + + } + + export function removeUpdatedValueCallback(ctx: SPClientTemplates.RenderContext_Form, fieldName: string, callback: UpdatedValueCallback): void { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx; + if (contextWithHook.FormContextHook) { + var callbacks = ensureFormContextHookField(contextWithHook.FormContextHook, fieldName).updatedValueCallbacks; + var index = callbacks.indexOf(callback); + if (index != -1) { + callbacks.splice(index, 1); + } + } + } + } + + export function getControl(schema: SPClientTemplates.FieldSchema_InForm): HTMLInputElement { + var id = schema.Name + '_' + schema.Id + '_$' + schema.FieldType + 'Field'; + //TODO: Handle different input types + return $get(id); + } + + export function getFieldTemplate(field: SPClientTemplates.FieldSchema, mode: SPClientTemplates.ClientControlMode): SPClientTemplates.FieldCallback { + var ctx = { ListSchema: { Field: [field] }, FieldControlModes: {} }; + ctx.FieldControlModes[field.Name] = mode; + var templates = SPClientTemplates.TemplateManager.GetTemplates(ctx); + return templates.Fields[field.Name]; + } + + + class csr implements ICSR, SPClientTemplates.TemplateOverridesOptions { + + public Templates: SPClientTemplates.TemplateOverrides; + public OnPreRender: SPClientTemplates.RenderCallback[]; + public OnPostRender: SPClientTemplates.RenderCallback[]; + private IsRegistered: boolean; + + + constructor(public ListTemplateType?: number, public BaseViewID?: any) { + this.Templates = { Fields: {} }; + this.OnPreRender = [] ; + this.OnPostRender = []; + this.IsRegistered = false; + } + + /* tier 1 methods */ + view(template: any): ICSR { + this.Templates.View = template; + return this; + } + + item(template: any): ICSR { + this.Templates.Item = template; + return this; + } + + header(template: any): ICSR { + this.Templates.Header = template; + return this; + } + + body(template: any): ICSR { + this.Templates.Body = template; + return this; + } + + footer(template: any): ICSR { + this.Templates.Footer = template; + return this; + } + + fieldView(fieldName: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName].View = template; + return this; + } + + fieldDisplay(fieldName: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName].DisplayForm = template; + return this; + } + + fieldNew(fieldName: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName].NewForm = template; + return this; + } + + fieldEdit(fieldName: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName].EditForm = template; + return this; + } + + /* tier 2 methods */ + template(name: string, template: any): ICSR { + this.Templates[name] = template; + return this; + } + + fieldTemplate(fieldName: string, name: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName][name] = template; + return this; + } + + /* common */ + onPreRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR { + for (var i = 0; i < callbacks.length; i++) { + this.OnPreRender.push(callbacks[i]); + } + return this; + } + + onPostRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR { + for (var i = 0; i < callbacks.length; i++) { + this.OnPostRender.push(callbacks[i]); + } + return this; + } + + onPreRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR { + return this.onPreRender((ctx: SPClientTemplates.RenderContext) => { + var ctxInView = ctx; + + //ListSchema schma exists in Form and in View render context + var fields = ctxInView.ListSchema.Field; + if (fields) { + for (var i = 0; i < fields.length; i++) { + if (fields[i].Name === field) { + callback(fields[i], ctx); + } + } + } + }); + } + + onPostRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR { + return this.onPostRender((ctx: SPClientTemplates.RenderContext) => { + var ctxInView = ctx; + + //ListSchema schma exists in Form and in View render context + var fields = ctxInView.ListSchema.Field; + if (fields) { + for (var i = 0; i < fields.length; i++) { + if (fields[i].Name === field) { + callback(fields[i], ctx); + } + } + } + }); + } + + makeReadOnly(fieldName: string): ICSR { + return this + .onPreRenderField(fieldName, (schema, ctx) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid + || ctx.ControlMode == SPClientTemplates.ClientControlMode.DisplayForm) return; + (schema).ReadOnlyField = true; + (schema).ReadOnly = "TRUE"; + + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { + var ctxInView = ctx; + if (ctxInView.inGridMode) { + //TODO: Disable editing in grid mode + + } + + } else { + var ctxInForm = ctx; + if (schema.Type != 'User' && schema.Type != 'UserMulti') { + + var template = getFieldTemplate(schema, SPClientTemplates.ClientControlMode.DisplayForm); + ctxInForm.Templates.Fields[fieldName] = template; + ctxInForm.FormContext.registerGetValueCallback(fieldName, () => ctxInForm.ListData.Items[0][fieldName]); + + } + } + + }) + .onPostRenderField(fieldName, (schema: SPClientTemplates.FieldSchema_InForm_User, ctx) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + if (schema.Type == 'User' || schema.Type == 'UserMulti') { + SP.SOD.executeFunc('clientpeoplepicker.js', 'SPClientPeoplePicker', () => { + var topSpanId = schema.Name + '_' + schema.Id + '_$ClientPeoplePicker'; + var retryCount = 10; + var callback = () => { + var pp = SPClientPeoplePicker.SPClientPeoplePickerDict[topSpanId]; + if (!pp) { + if (retryCount--) setTimeout(callback, 1); + } else { + pp.SetEnabledState(false); + pp.DeleteProcessedUser = function () { }; + } + }; + callback(); + }); + } + } + }); + } + + makeHidden(fieldName: string): ICSR { + return this.onPreRenderField(fieldName, (schema, ctx) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid) return; + (schema).Hidden = true; + + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { + var ctxInView = ctx; + + if (ctxInView.inGridMode) { + //TODO: Hide item in grid mode + } else { + ctxInView.ListSchema.Field.splice(ctxInView.ListSchema.Field.indexOf(schema), 1); + } + + } else { + var ctxInForm = ctx; + + var pHolderId = ctxInForm.FormUniqueId + ctxInForm.FormContext.listAttributes.Id + fieldName; + var placeholder = $get(pHolderId); + var current = placeholder; + while (current.tagName.toUpperCase() !== "TR") { + current = current.parentElement; + } + var row = current; + row.style.display = 'none'; + + } + + }); + } + + filteredLookup(fieldName: string, camlFilter: string, listname?: string, lookupField?: string): ICSR { + + + return this.fieldEdit(fieldName, SPFieldCascadedLookup_Edit) + .fieldNew(fieldName, SPFieldCascadedLookup_Edit); + + + function SPFieldCascadedLookup_Edit(rCtx: SPClientTemplates.RenderContext_FieldInForm) { + + var parseRegex = /\{[^\}]+\}/g; + var dependencyExpressions: string[] = []; + var result: RegExpExecArray; + while ((result = parseRegex.exec(camlFilter))) { + dependencyExpressions.push(stripBraces(result[0])); + } + var dependencyValues: { [expr: string]: string } = {}; + + var _dropdownElt: HTMLSelectElement; + var _myData: SPClientTemplates.ClientFormContext; + + + if (rCtx == null) + return ''; + _myData = SPClientTemplates.Utility.GetFormContextForCurrentField(rCtx); + + if (_myData == null || _myData.fieldSchema == null) + return ''; + + + var _schema = _myData.fieldSchema; + + var validators = new SPClientForms.ClientValidation.ValidatorSet(); + validators.RegisterValidator(new BooleanValueValidator(() => _optionsLoaded, "Wait until lookup values loaded and try again")); + + if (_myData.fieldSchema.Required) { + validators.RegisterValidator(new SPClientForms.ClientValidation.RequiredValidator()); + } + _myData.registerClientValidator(_myData.fieldName, validators); + + var _dropdownId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$LookupField'; + var _valueStr = _myData.fieldValue != null ? _myData.fieldValue : ''; + var _selectedValue = SPClientTemplates.Utility.ParseLookupValue(_valueStr).LookupId; + var _noValueSelected = _selectedValue == 0; + var _optionsLoaded = false; + var pendingLoads = 0; + + if (_noValueSelected) + _valueStr = ''; + + _myData.registerInitCallback(_myData.fieldName, InitLookupControl); + + _myData.registerFocusCallback(_myData.fieldName, function () { + if (_dropdownElt != null) + _dropdownElt.focus(); + }); + _myData.registerValidationErrorCallback(_myData.fieldName, function (errorResult) { + SPFormControl_AppendValidationErrorMessage(_dropdownId, errorResult); + }); + _myData.registerGetValueCallback(_myData.fieldName, GetCurrentLookupValue); + _myData.updateControlValue(_myData.fieldName, _valueStr); + + return BuildLookupDropdownControl(); + + function InitLookupControl() { + _dropdownElt = document.getElementById(_dropdownId); + if (_dropdownElt != null) + AddEvtHandler(_dropdownElt, "onchange", OnLookupValueChanged); + + SP.SOD.executeFunc('sp.js', 'SP.ClientContext', () => { + bindDependentControls(dependencyExpressions); + loadOptions(true); + }); + } + + + function BuildLookupDropdownControl() { + var result = ''; + result += '
    '; + return result; + } + + + function OnLookupValueChanged() { + if (_optionsLoaded) { + if (_dropdownElt != null) { + _myData.updateControlValue(_myData.fieldName, GetCurrentLookupValue()); + _selectedValue = parseInt(_dropdownElt.value, 10); + } + } + } + + function GetCurrentLookupValue() { + if (_dropdownElt == null) + return ''; + return _dropdownElt.value == '0' || _dropdownElt.value == '' ? '' : _dropdownElt.value + ';#' + _dropdownElt.options[_dropdownElt.selectedIndex].text; + } + + function stripBraces(input: string): string { + return input.substring(1, input.length - 1); + } + + function getDependencyValue(expr: string, value: string, listId: string, expressionParts: string[], callback: () => void) { + var isLookupValue = !!listId; + if (isLookupValue) { + var lookup = SPClientTemplates.Utility.ParseLookupValue(value); + if (expressionParts.length == 1 && expressionParts[0] == 'Value') { + value = lookup.LookupValue; + expressionParts.shift(); + } else { + value = lookup.LookupId.toString(); + } + } + + if (expressionParts.length == 0) { + dependencyValues[expr] = value; + callback(); + } else { + var ctx = SP.ClientContext.get_current(); + var web = ctx.get_web(); + //TODO: Handle lookup to another web + var list = web.get_lists().getById(listId); + var item = list.getItemById(parseInt(value, 10)); + var field = list.get_fields().getByInternalNameOrTitle(expressionParts.shift()); + ctx.load(item); + ctx.load(field); + + ctx.executeQueryAsync((o, e) => { + var value = item.get_item(field.get_internalName()); + + if (field.get_typeAsString() == 'Lookup') { + field = ctx.castTo(field, SP.FieldLookup); + var lookup = (value); + value = lookup.get_lookupId() + ';#' + lookup.get_lookupValue(); + listId = (field).get_lookupList(); + } + + getDependencyValue(expr, value, listId, expressionParts, callback); + + }, (o, args) => { console.log(args.get_message()); }); + } + } + + function bindDependentControls(dependencyExpressions: string[]) { + dependencyExpressions.forEach(expr => { + var exprParts = expr.split("."); + var field = exprParts.shift(); + + CSR.addUpdatedValueCallback(rCtx, field, + (v, s) => { + getDependencyValue(expr, v, + (s).LookupListId, + exprParts.slice(0), + loadOptions); + }); + + }); + } + + + function loadOptions(isFirstLoad?: boolean) { + _optionsLoaded = false; + pendingLoads++; + + var ctx = SP.ClientContext.get_current(); + //TODO: Handle lookup to another web + var web = ctx.get_web(); + var listId = _schema.LookupListId; + var list = !listname ? web.get_lists().getById(listId) : web.get_lists().getByTitle(listname); + var query = new SP.CamlQuery(); + + var predicate = camlFilter.replace(parseRegex, (v, a) => { + var expr = stripBraces(v); + return dependencyValues[expr] ? dependencyValues[expr] : ''; + }); + + //TODO: Handle ShowField attribure + if (predicate.substr(0, 5) == '' + + predicate + + ' ' + + ''); + } + var results = list.getItems(query); + ctx.load(results); + + + ctx.executeQueryAsync((o, e) => { + var selected = false; + + while (_dropdownElt.options.length) { + _dropdownElt.options.remove(0); + } + + if (!_schema.Required) { + var defaultOpt = new Option(Strings.STS.L_LookupFieldNoneOption, '0', selected, selected); + _dropdownElt.options.add(defaultOpt); + selected = _selectedValue == 0; + } + var isEmptyList = true; + + var enumerator = results.getEnumerator(); + while (enumerator.moveNext()) { + var c = enumerator.get_current(); + var id: number; + var text: string; + + if (!lookupField) { + id = c.get_id(); + text = c.get_item('Title'); + } else { + var value = c.get_item(lookupField); + id = value.get_lookupId(); + text = value.get_lookupValue(); + } + var isSelected = _selectedValue == id; + if (isSelected) { + selected = true; + } + var opt = new Option(text, id.toString(), isSelected, isSelected); + _dropdownElt.options.add(opt); + isEmptyList = false; + } + pendingLoads--; + _optionsLoaded = true; + if (!pendingLoads) { + if (isFirstLoad) { + if (_selectedValue == 0 && !selected) { + _dropdownElt.selectedIndex = 0; + OnLookupValueChanged(); + } + } else { + if (_selectedValue != 0 && !selected) { + _dropdownElt.selectedIndex = 0; + } + OnLookupValueChanged(); + } + } + + + }, (o, args) => { console.log(args.get_message()); }); + } + } + + } + + koEditField(fieldName: string, template: string, vm: IKoFieldInForm, dependencyFields?: string[]): ICSR { + return this.fieldEdit(fieldName, koEditField_Edit) + .fieldNew(fieldName, koEditField_Edit); + + + function koEditField_Edit(rCtx: SPClientTemplates.RenderContext_FieldInForm) { + if (rCtx == null) + return ''; + var _myData = SPClientTemplates.Utility.GetFormContextForCurrentField(rCtx); + + if (_myData == null || _myData.fieldSchema == null) + return ''; + var elementId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$' + _myData.fieldSchema.Type; + + vm.renderingContext = rCtx; + + + if (dependencyFields) { + dependencyFields.forEach(dependencyField => { + if (!vm[dependencyField]) { + vm[dependencyField] = ko.observable(CSR.getFieldValue(rCtx, dependencyField)); + } + CSR.addUpdatedValueCallback(rCtx, dependencyField, v => { + vm[dependencyField](v); + }); + }); + } + + + if (!vm.value) { + vm.value = ko.observable(); + } + + vm.value.subscribe(v => { _myData.updateControlValue(fieldName, v); }); + _myData.registerGetValueCallback(fieldName, () => vm.value()); + + + _myData.registerInitCallback(fieldName, () => { + ko.applyBindings(vm, $get(elementId)); + }); + + return '
    '+template+'
    '; + } + } + + computedValue(targetField: string, transform: (...values: string[]) => string, ...sourceField: string[]): ICSR { + var dependentValues: { [field: string]: string } = {}; + + return this.onPostRenderField(targetField, (schema, ctx: SPClientTemplates.RenderContext_FieldInForm) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var targetControl = CSR.getControl(schema); + sourceField.forEach((field) => { + CSR.addUpdatedValueCallback(ctx, field, v => { + dependentValues[field] = v; + targetControl.value = transform.apply(this, + sourceField.map(n => dependentValues[n] || '')); + + }); + }); + } + }); + } + + setInitialValue(fieldName: string, value: any, ignoreNull?: boolean): ICSR { + if (value || !ignoreNull) { + return this.onPreRenderField(fieldName, (schema, ctx: SPClientTemplates.RenderContext_FieldInForm) => { + ctx.ListData.Items[0][fieldName] = value; + }); + } else { + return this; + } + } + + + autofill(fieldName: string, init: (ctx: IAutoFillFieldContext) => () => void): ICSR { + return this + .fieldNew(fieldName, SPFieldLookup_Autofill_Edit) + .fieldEdit(fieldName, SPFieldLookup_Autofill_Edit); + + function SPFieldLookup_Autofill_Edit(rCtx: SPClientTemplates.RenderContext_FieldInForm) { + if (rCtx == null) + return ''; + var _myData = SPClientTemplates.Utility.GetFormContextForCurrentField(rCtx); + + if (_myData == null || _myData.fieldSchema == null) + return ''; + + var _autoFillControl: SPClientAutoFill; + var _textInputElt: HTMLInputElement; + var _textInputId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$' + _myData.fieldSchema.Type + 'Field'; + var _autofillContainerId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$AutoFill'; + + var validators = new SPClientForms.ClientValidation.ValidatorSet(); + if (_myData.fieldSchema.Required) { + validators.RegisterValidator(new SPClientForms.ClientValidation.RequiredValidator()); + } + _myData.registerClientValidator(_myData.fieldName, validators); + + _myData.registerInitCallback(_myData.fieldName, initAutoFillControl); + _myData.registerFocusCallback(_myData.fieldName, function () { + if (_textInputElt != null) + _textInputElt.focus(); + }); + _myData.registerValidationErrorCallback(_myData.fieldName, function (errorResult) { + SPFormControl_AppendValidationErrorMessage(_textInputId, errorResult); + }); + _myData.registerGetValueCallback(_myData.fieldName, () => _myData.fieldValue); + _myData.updateControlValue(_myData.fieldName, _myData.fieldValue); + + return buildAutoFillControl(); + + function initAutoFillControl() { + _textInputElt = document.getElementById(_textInputId); + + SP.SOD.executeFunc("autofill.js", "SPClientAutoFill", () => { + _autoFillControl = new SPClientAutoFill(_textInputId, _autofillContainerId, (_) => callback()); + var callback = init({ + renderContext: rCtx, + fieldContext: _myData, + autofill: _autoFillControl, + control: _textInputElt, + }); + + //_autoFillControl.AutoFillMinTextLength = 2; + //_autoFillControl.VisibleItemCount = 15; + //_autoFillControl.AutoFillTimeout = 500; + }); + + } + //function OnPopulate(targetElement: HTMLInputElement) { + + //} + + //function OnLookupValueChanged() { + // _myData.updateControlValue(_myData.fieldName, GetCurrentLookupValue()); + //} + //function GetCurrentLookupValue() { + // return _valueStr; + //} + function buildAutoFillControl() { + var result: string[] = []; + result.push('
    '); + result.push(''); + + result.push("
    "); + result.push("
    "); + + return result.join(""); + } + } + + + } + + seachLookup(fieldName: string): ICSR { + return this.autofill(fieldName, (ctx: IAutoFillFieldContext) => { + var _myData = ctx.fieldContext; + var _schema = _myData.fieldSchema; + if (_myData.fieldSchema.Type != 'Lookup') { + return null; + } + + var _valueStr = _myData.fieldValue != null ? _myData.fieldValue : ''; + var _selectedValue = SPClientTemplates.Utility.ParseLookupValue(_valueStr); + var _noValueSelected = _selectedValue.LookupId == 0; + ctx.control.value = _selectedValue.LookupValue; + $addHandler(ctx.control, "blur", _ => { + if (ctx.control.value == '') { + _myData.fieldValue = ''; + _myData.updateControlValue(fieldName, _myData.fieldValue); + } + }); + + if (_noValueSelected) + _myData.fieldValue = ''; + + var _autoFillControl = ctx.autofill; + _autoFillControl.AutoFillMinTextLength = 2; + _autoFillControl.VisibleItemCount = 15; + _autoFillControl.AutoFillTimeout = 500; + + return () => { + var value = ctx.control.value; + _autoFillControl.PopulateAutoFill([AutoFillOptionBuilder.buildLoadingItem('Please wait...')], onSelectItem); + + SP.SOD.executeFunc("sp.search.js", "Microsoft.SharePoint.Client.Search.Query", () => { + var Search = Microsoft.SharePoint.Client.Search.Query; + var ctx = SP.ClientContext.get_current(); + var query = new Search.KeywordQuery(ctx); + query.set_rowLimit(_autoFillControl.VisibleItemCount); + query.set_queryText('contentclass:STS_ListItem ListID:{' + _schema.LookupListId + '} ' + value); + var selectProps = query.get_selectProperties(); + selectProps.clear(); + //TODO: Handle ShowField attribute + selectProps.add('Title'); + selectProps.add('ListItemId'); + var executor = new Search.SearchExecutor(ctx); + var result = executor.executeQuery(query); + ctx.executeQueryAsync( + () => { + //TODO: Discover proper way to load collection + var tableCollection = new Search.ResultTableCollection(); + tableCollection.initPropertiesFromJson(result.get_value()); + + var relevantResults = tableCollection.get_item(0); + var rows = relevantResults.get_resultRows(); + + var items = []; + for (var i = 0; i < rows.length; i++) { + items.push(AutoFillOptionBuilder.buildOptionItem(parseInt(rows[i]["ListItemId"], 10), rows[i]["Title"])); + } + + items.push(AutoFillOptionBuilder.buildSeparatorItem()); + + if (relevantResults.get_totalRows() == 0) + items.push(AutoFillOptionBuilder.buildFooterItem("No results. Please refine your query.")); + else + items.push(AutoFillOptionBuilder.buildFooterItem("Showing " + rows.length + " of" + relevantResults.get_totalRows() + " items!")); + + _autoFillControl.PopulateAutoFill(items, onSelectItem); + + }, + (sender, args) => { + _autoFillControl.PopulateAutoFill([AutoFillOptionBuilder.buildFooterItem("Error executing query/ See log for details.")], onSelectItem); + console.log(args.get_message()); + }); + }); + } + + function onSelectItem(targetInputId, item: ISPClientAutoFillData) { + var targetElement = ctx.control; + targetElement.value = item[SPClientAutoFill.DisplayTextProperty]; + _selectedValue.LookupId = item[SPClientAutoFill.KeyProperty]; + _selectedValue.LookupValue = item[SPClientAutoFill.DisplayTextProperty]; + _myData.fieldValue = item[SPClientAutoFill.KeyProperty] + ';#' + item[SPClientAutoFill.TitleTextProperty]; + _myData.updateControlValue(_myData.fieldSchema.Name, _myData.fieldValue); + } + + }); + } + + lookupAddNew(fieldName: string, prompt: string, showDialog?: boolean, contentTypeId?: string): ICSR { + return this.onPostRenderField(fieldName, + (schema: SPClientTemplates.FieldSchema_InForm_Lookup, ctx: SPClientTemplates.RenderContext_FieldInForm) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) + + var control = CSR.getControl(schema); + if (control) { + var weburl = _spPageContextInfo.webServerRelativeUrl; + if (weburl[weburl.length - 1] == '/') { + weburl = weburl.substring(0, weburl.length - 1); + } + var newFormUrl = weburl + '/_layouts/listform.aspx/listform.aspx?PageType=8' + + "&ListId=" + encodeURIComponent('{' + schema.LookupListId + '}'); + if (contentTypeId) { + newFormUrl += '&ContentTypeId=' + contentTypeId; + } + + var link = document.createElement('a'); + link.href = "javascript:NewItem2(event, \'" + newFormUrl + "&Source=" + encodeURIComponent(document.location.href) + "')"; + link.textContent = prompt; + if (control.nextElementSibling) { + control.parentElement.insertBefore(link, control.nextElementSibling); + } else { + control.parentElement.appendChild(link); + } + + if (showDialog) { + $addHandler(link, "click", (e: Sys.UI.DomEvent) => { + SP.SOD.executeFunc('sp.ui.dialog.js', 'SP.UI.ModalDialog.ShowPopupDialog', () => { + SP.UI.ModalDialog.ShowPopupDialog(newFormUrl); + }); + e.stopPropagation(); + e.preventDefault(); + }); + } + } + }); + } + + register() { + if (!this.IsRegistered) { + SPClientTemplates.TemplateManager.RegisterTemplateOverrides(this); + this.IsRegistered = true; + } + } + } + + export class AutoFillOptionBuilder { + + static buildFooterItem(title: string): ISPClientAutoFillData { + var item = {}; + + item[SPClientAutoFill.DisplayTextProperty] = title; + item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Footer; + + return item; + } + + static buildOptionItem(id: number, title: string, displayText?: string, subDisplayText?: string): ISPClientAutoFillData { + + var item = {}; + + item[SPClientAutoFill.KeyProperty] = id; + item[SPClientAutoFill.DisplayTextProperty] = displayText || title; + item[SPClientAutoFill.SubDisplayTextProperty] = subDisplayText; + item[SPClientAutoFill.TitleTextProperty] = title; + item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Option; + + return item; + } + + static buildSeparatorItem(): ISPClientAutoFillData { + var item = {}; + item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Separator; + return item; + } + + static buildLoadingItem(title: string): ISPClientAutoFillData { + var item = {}; + + item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Loading; + item[SPClientAutoFill.DisplayTextProperty] = title; + return item; + } + + } + + /** Lightweight client-side rendering template overrides.*/ + export interface ICSR { + /** Override rendering template. + @param name Name of template to override. + @param template New template. + */ + template(name: string, template: string): ICSR; + + /** Override rendering template. + @param name Name of template to override. + @param template New template. + */ + template(name: string, template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Override field rendering template. + @param name Internal name of field to override. + @param name Name of template to override. + @param template New template. + */ + fieldTemplate(field: string, name: string, template: string): ICSR; + + /** Override field rendering template. + @param name Internal name of field to override. + @param name Name of template to override. + @param template New template. + */ + fieldTemplate(field: string, name: string, template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Sets pre-render callbacks. Callback called before rendering starts. + @param callbacks pre-render callbacks. + */ + onPreRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR; + + /** Sets post-render callbacks. Callback called after rendered html inserted to DOM. + @param callbacks post-render callbacks. + */ + onPostRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR; + + /** Sets pre-render callbacks for field. Callback called before rendering starts. Correctly handles form rendering. + @param fieldName Internal name of the field. + @param callbacks pre-render callbacks. + */ + onPreRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR; + + /** Sets post-render callbacks. Callback called after rendered html inserted to DOM. Correctly handles form rendering. + @param fieldName Internal name of the field. + @param callbacks post-render callbacks. + */ + onPostRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR; + + /** Registers overrides in client-side templating engine.*/ + register(): void; + + /** Override View rendering template. + @param template New view template. + */ + view(template: string): ICSR; + + /** Override View rendering template. + @param template New view template. + */ + view(template: (ctx: SPClientTemplates.RenderContext_InView) => string): ICSR; + view(template: (ctx: SPClientTemplates.RenderContext_Form) => string): ICSR; + + /** Override Item rendering template. + @param template New item template. + */ + item(template: string): ICSR; + + /** Override Item rendering template. + @param template New item template. + */ + item(template: (ctx: SPClientTemplates.RenderContext_ItemInView) => string): ICSR; + item(template: (ctx: SPClientTemplates.RenderContext_Form) => string): ICSR; + + /** Override Header rendering template. + @param template New header template. + */ + header(template: string): ICSR; + + /** Override Header rendering template. + @param template New header template. + */ + header(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Override Body rendering template. + @param template New body template. + */ + body(template: string): ICSR; + + /** Override Body rendering template. + @param template New body template. + */ + body(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Override Footer rendering template. + @param template New footer template. + */ + footer(template: string): ICSR; + + /** Override Footer rendering template. + @param template New footer template. + */ + footer(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Override View rendering template for specified field. + @param fieldName Internal name of the field. + @param template New View template. + */ + fieldView(fieldName: string, template: string): ICSR; + + /** Override View rendering template for specified field. + @param fieldName Internal name of the field. + @param template New View template. + */ + fieldView(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInView) => string): ICSR; + + /** Override DisplyForm rendering template for specified field. + @param fieldName Internal name of the field. + @param template New DisplyForm template. + */ + fieldDisplay(fieldName: string, template: string): ICSR; + + /** Override DisplyForm rendering template. + @param fieldName Internal name of the field. + @param template New DisplyForm template. + */ + fieldDisplay(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; + + /** Override EditForm rendering template for specified field. + @param fieldName Internal name of the field. + @param template New EditForm template. + */ + fieldEdit(fieldName: string, template: string): ICSR; + + /** Override EditForm rendering template. + @param fieldName Internal name of the field. + @param template New EditForm template. + */ + fieldEdit(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; + + /** Override NewForm rendering template for specified field. + @param fieldName Internal name of the field. + @param template New NewForm template. + */ + fieldNew(fieldName: string, template: string): ICSR; + + /** Override NewForm rendering template. + @param fieldName Internal name of the field. + @param template New NewForm template. + */ + fieldNew(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; + + + /** Set initial value for field. + @param fieldName Internal name of the field. + @param value Initial value for field. + */ + setInitialValue(fieldName: string, value: any): ICSR; + + /** Make field hidden in list view and standard forms. + @param fieldName Internal name of the field. + */ + makeHidden(fieldName: string): ICSR + + + /** Replace New and Edit templates for field to Display template. + @param fieldName Internal name of the field. + */ + makeReadOnly(fieldName: string): ICSR + + /** Create cascaded Lookup Field. + @param fieldName Internal name of the field. + @param camlFilter CAML predicate expression (inside Where clause). Use {FieldName} tokens for dependency fields substitutions. + */ + filteredLookup(fieldName: string, camlFilter: string, listname?: string, lookupField?: string): ICSR + + /** Auto computes text-based field value based on another fields. + @param targetField Internal name of the field. + @param transform Function combines source field values. + @param sourceField Internal names of source fields. + */ + computedValue(targetField: string, transform: (...values: string[]) => string, ...sourceField: string[]): ICSR + + /** Field text value with autocomplete based on autofill.js + @param fieldName Internal name of the field. + @param ctx AutoFill context. + */ + autofill(fieldName: string, init: (ctx: IAutoFillFieldContext) => () => void): ICSR + + /** Replace defult dropdown to search-based autocomplete for Lookup field. + @param fieldName Internal name of the field. + */ + seachLookup(fieldName: string): ICSR; + + /** Adds link to add new value to lookup list. + @param fieldName Internal name of the field. + @param prompt Text to display as a link to add new value. + @param contentTypeID Default content type for new item. + */ + lookupAddNew(fieldName: string, prompt: string, showDialog?: boolean, contentTypeId?: string): ICSR; + + koEditField(fieldName: string, template: string, vm: IKoFieldInForm, dependencyFields?: string[]): ICSR; + + + } + + export interface IAutoFillFieldContext { + renderContext: SPClientTemplates.RenderContext_FieldInForm; + fieldContext: SPClientTemplates.ClientFormContext; + autofill: SPClientAutoFill; + control: HTMLInputElement; + } + + export interface IKoFieldInForm { + renderingContext?:SPClientTemplates.RenderContext_FieldInForm; + value?:KnockoutObservable; + } + + + interface IFormRenderContexWithHook extends SPClientTemplates.RenderContext_FieldInForm { + FormContextHook: IFormContextHook; + } + + interface IFormContextHook { + [fieldName: string]: IFormContextHookField; + } + + interface IFormContextHookField { + fieldSchema?: SPClientTemplates.FieldSchema_InForm; + lastValue?: any; + getValue?: () => any; + updatedValueCallbacks: UpdatedValueCallback[]; + } + + + function ensureFormContextHookField(hook: IFormContextHook, fieldName: string): IFormContextHookField { + return hook[fieldName] = hook[fieldName] || { + updatedValueCallbacks: [] + }; + + } + + class BooleanValueValidator implements SPClientForms.ClientValidation.IValidator { + constructor(public valueGetter: () => boolean, public validationMessage: string) { } + + Validate(value: any): SPClientForms.ClientValidation.ValidationResult { + return new SPClientForms.ClientValidation.ValidationResult(!this.valueGetter(), this.validationMessage); + } + } + +} + +if (typeof SP == 'object' && SP && typeof SP.SOD == 'object' && SP.SOD) { + SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs("typescripttemplates.ts"); +} + + +//mquery.ts + + + + +module spdevlab { + export module mQuery { + export class DynamicTable { + + // private fields + _domContainer:HTMLElement; + _tableContainer:MQueryResultSetElements; + + _rowTemplateId:string = null; + _rowTemplateContent:string = null; + + _options = { + tableCnt: '.spdev-rep-tb', + addCnt: '.spdev-rep-tb-add', + removeCnt: '.spdev-rep-tb-del' + }; + + // public methods + init(domContainer: HTMLElement, options) { + + if (m$.isDefinedAndNotNull(options)) { + m$.extend(this._options, options); + } + + this._initContainers(domContainer); + + this._initRowTemplate(); + this._initEvents(); + this._showUI(); + } + + // private methods + _initContainers(domContainer) { + + this._domContainer = domContainer; + this._tableContainer = m$(this._options.tableCnt, this._domContainer); + } + + _showUI() { + m$(this._domContainer).css("display", ""); + } + + _initEvents() { + + m$(this._options.addCnt, this._domContainer).click(() => { + + if (m$.isDefinedAndNotNull(this._rowTemplateContent)) { + + m$(this._tableContainer).append(this._rowTemplateContent); + + m$("tr:last-child " + this._options.removeCnt, this._tableContainer).click( (e) => { + + var targetElement = e.currentTarget; + var parentRow = m$(targetElement).parents("tr").first(); + + m$(parentRow).remove(); + }); + } + + return false; + }); + } + + _initRowTemplate() { + var templateId = m$(this._tableContainer).attr("template-id"); + + if (m$.isDefinedAndNotNull(templateId)) { + this._rowTemplateId = templateId; + this._rowTemplateContent = DynamicTable._templates[templateId]; + } + } + + static _templates:string[] = []; + static initTables() { + // init templates + m$('script').forEach((template:HTMLElement) => { + + var id = m$(template).attr("dynamic-table-template-id"); + + if (m$.isDefinedAndNotNull(id)) { + DynamicTable._templates[id] = template.innerHTML; + } + }); + + // init tables + m$(".spdev-rep-tb-cnt").forEach( divContainer => { + + var dynamicTable = new DynamicTable(); + + dynamicTable.init(divContainer, { + removeCnt: '.spdev-rep-tb-del-override' + }); + }); + } + + }; + + + } +} + +m$.ready(() => { + spdevlab.mQuery.DynamicTable.initTables(); +}); + + +//whoisapppart.ts + + +module _ { + var queryString = parseQueryString(); + var isIframe = queryString['DisplayMode'] == 'iframe' + var spHostUrl = queryString['SPHostUrl']; + var editmode = Number(queryString['editmode']); + var includeDetails = queryString['boolProp'] == 'true'; + + prepareVisual(); + m$.ready(() => { + loadPeoplePicker('peoplePicker'); + partProperties(); + + if (isIframe) { + partResize(); + } + }); + + //Load the people picker + function loadPeoplePicker(peoplePickerElementId: string) { + var schema: ISPClientPeoplePickerSchema = { + PrincipalAccountType: "User", + AllowMultipleValues: false, + Width: 300, + OnUserResolvedClientScript: onUserResolvedClientScript + } + + SPClientPeoplePicker.InitializeStandalonePeoplePicker(peoplePickerElementId, null, schema); + } + + function onUserResolvedClientScript(el: string, users: ISPClientPeoplePickerEntity[]) { + if (users.length > 0) { + var person = users[0]; + var accountName = person.Key; + + var context = SP.ClientContext.get_current(); + + var peopleManager = new SP.UserProfiles.PeopleManager(context); + var personProperties = peopleManager.getPropertiesFor(accountName); + + context.load(personProperties); + context.executeQueryAsync((sender, args) => { + + $get("basicInfo").style.display = 'block'; + + var userPic = personProperties.get_userProfileProperties()["PictureURL"]; + $get("pic").innerHTML = ' + personProperties.get_displayName() + '; + + $get("name").innerHTML = '' + personProperties.get_displayName() + ''; + $get("email").innerHTML = '' + personProperties.get_email() + ''; + $get("title").innerHTML = personProperties.get_title(); + $get("department").innerHTML = person.EntityData.Department; + $get("phone").innerHTML = person.EntityData.MobilePhone; + + var properties = personProperties.get_userProfileProperties(); + var messageText = ""; + for (var key in properties) { + messageText += "
    [" + key + "]: \"" + properties[key] + "\""; + } + $get("detailInfo").innerHTML = messageText; + + if (isIframe) { + partResize(); + } + + }, (sender, args) => { alert('Error: ' + args.get_message()); }); + + } + } + + function partProperties() { + + if (editmode == 1) { + $get("editmodehdr").style.display = "inline"; + $get("content").style.display = "none"; + } + else if (includeDetails) { + $get('detailInfo').style.display = 'block'; + + $get("editmodehdr").style.display = "none"; + $get("content").style.display = "inline"; + } + } + + function partResize() { + var bounds = Sys.UI.DomElement.getBounds(document.body); + parent.postMessage('resize(' + bounds.width + ',' + bounds.height + ')', '*'); + } + + function prepareVisual() { + if (isIframe) { + //Create a Link element for the defaultcss.ashx resource + var linkElement = document.createElement('link'); + linkElement.setAttribute('rel', 'stylesheet'); + linkElement.setAttribute('href', spHostUrl + '/_layouts/15/defaultcss.ashx'); + + //Add the linkElement as a child to the head section of the html + document.head.appendChild(linkElement); + } else { + + m$.ready(() => { + var nav = new SP.UI.Controls.Navigation('navigation', { + appIconUrl: queryString['SPHostLogo'], + appTitle: document.title + }); + nav.setVisible(true); + $get('apppart-notification').style.display = 'block'; + document.body.style.overflow = 'visible'; + }); + } + } + + function parseQueryString() { + var result = {}; + var qs = document.location.search.split('?')[1]; + if (qs) { + var parts = qs.split('&'); + for (var i = 0; i < parts.length; i++) { + if (parts[i]) { + var pair = parts[i].split('='); + result[pair[0]] = decodeURIComponent(pair[1]); + } + } + } + return result; + } +} + +//taxonomy +module SP { + + // Class + export class ClientContextPromise extends SP.ClientContext { + /** To use this function, you must ensure that jQuery and CSOMPromise js files are loaded to the page */ + executeQueryPromise(): JQueryPromise { + var deferred = jQuery.Deferred(); + this.executeQueryAsync(function (sender, args) { + deferred.resolve(sender, args); + }, + function (sender, args) { + deferred.reject(sender, args); + }) + return deferred.promise(); + } + + constructor(serverRelativeUrlOrFullUrl: string) { + super(serverRelativeUrlOrFullUrl); + } + + static get_current(): ClientContextPromise { + return new ClientContextPromise(_spPageContextInfo.siteServerRelativeUrl); + } + + } + +} + +SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs("CSOMPromise.ts"); + +module _ { + var context: SP.ClientContextPromise; + var web: SP.Web; + var site: SP.Site; + var session: SP.Taxonomy.TaxonomySession; + var termStore: SP.Taxonomy.TermStore; + var groups: SP.Taxonomy.TermGroupCollection; + + // This code runs when the DOM is ready and creates a context object + // which is needed to use the SharePoint object model. + // It also wires up the click handlers for the two HTML buttons in Default.aspx. + $(document).ready(function () { + context = SP.ClientContextPromise.get_current(); + site = context.get_site(); + web = context.get_web(); + $('#listExisting').click(function () { listGroups(); }); + $('#createTerms').click(function () { createTerms(); }); + }); + + // When the listExisting button is clicked, start by loading + // a TaxonomySession for the current context. Also get and load + // the associated term store. + function listGroups() { + session = SP.Taxonomy.TaxonomySession.getTaxonomySession(context); + termStore = session.getDefaultSiteCollectionTermStore(); + context.load(session); + context.load(termStore); + context.executeQueryAsync(onListTaxonomySession, onFailListTaxonomySession); + } + + // Runs when the executeQueryAsync method in the listGroups function has succeeded. + // In this case, get and load the groups associated with the term store that we + // know we now have a reference to. + function onListTaxonomySession() { + groups = termStore.get_groups(); + context.load(groups); + context.executeQueryAsync(onRetrieveGroups, onFailRetrieveGroups); + } + + // Runs when the executeQueryAsync method in the onListTaxonomySession function has succeeded. + // In this case, loop through all the groups and add a clickable div element to the report area + // for each group. + // NOTE: We clear the report area first to ensure we have a clean place to write to. + // Also note how we create a click event handler for each div on-the-fly, and that we pass in the + // current group ID to that function. So when the user clicks one of these divs, we will know which + // one was clicked. + function onRetrieveGroups() { + $('#report').children().remove(); + + var groupEnum = groups.getEnumerator(); + + // For each group, we'll build a clickable div. + while (groupEnum.moveNext()) { + (() => { + var currentGroup = groupEnum.get_current(); + var groupName = document.createElement("div"); + groupName.setAttribute("style", "float:none;cursor:pointer"); + var groupID = currentGroup.get_id(); + groupName.setAttribute("id", groupID.toString()); + $(groupName).click(() => showTermSets(groupID)); + groupName.appendChild(document.createTextNode(currentGroup.get_name())); + $('#report').append(groupName); + })(); + } + } + + // This is the function that runs when the user clicks one of the divs + // that we created in the onRetrieveGroups function. We can know which + // div was clicked by interrogating the groupID parameter. So what we'll + // do is retrieve a reference to the group with the same ID as the div, and + // then add the term sets that belong to that group under the div that was clicked. + function showTermSets(groupID: SP.Guid) { + + // First thing is to remnove the divs under the group DIV to ensure we have a clean place to write to. + // The reason we don't clear them all is becuase we want to retain the text node of the + // group div. I.E. that's why we use "parentDiv.childNodes.length>1" as our loop + // controller. + var parentDiv = document.getElementById(groupID.toString()); + while (parentDiv.childNodes.length > 1) { + parentDiv.removeChild(parentDiv.lastChild); + } + + // For each term set, we'll build a clickable div + var currentGroup = groups.getById(groupID); + + // We need to load and populate the matching group first, or the + // term sets that it contains will be inaccessible to our code. + context.load(currentGroup); + var termSets: SP.Taxonomy.TermSetCollection; + context.executeQueryPromise() + .then( + () => { + // The group is now available becuase this is the + // success callback. So now we'll load and populate the + // term set collection. We have to do this before we can + // iterate through the collection, so we can do this + // with the following nested executeQueryAsync method call. + termSets = currentGroup.get_termSets(); + context.load(termSets); + return context.executeQueryPromise() + }) + .then(() => { + // The term sets are now available becuase this is the + // success callback. So now we'll iterate through the collection + // and create the clickable div. Also note how we create a + // click event handler for each div on-the-fly, and that we pass in the + // current group ID and term set ID to that function. So when the user + // clicks one of these divs, we will know which + // one was clicked by its term set ID, and to which group it belongs by its + // group ID. We also pass in the event object, so that we can cancel the bubble + // because this clickable div will be inside a parent clickable div and we + // don't want the parent's event to fire. + var termSetEnum = termSets.getEnumerator(); + while (termSetEnum.moveNext()) { + (() => { + var currentTermSet = termSetEnum.get_current(); + var termSetName = document.createElement("div"); + termSetName.appendChild(document.createTextNode(" + " + currentTermSet.get_name())); + termSetName.setAttribute("style", "float:none;cursor:pointer;"); + var termSetID = currentTermSet.get_id(); + termSetName.setAttribute("id", termSetID.toString()); + $(termSetName).click(e => showTerms(e, groupID, termSetID)); + parentDiv.appendChild(termSetName); + })(); + } + + }) + .fail(() => parentDiv.appendChild(document.createTextNode("An error occurred in loading the term sets for this group"))); + } + + + // This is the function that runs when the user clicks one of the divs + // that we created in the showTermSets function. We can know which + // div was clicked by interrogating the termSetID parameter. So what we'll + // do is retrieve a reference to the term set with the same ID as the div, and + // then add the term that belong to that term set under the div that was clicked. + + function showTerms(event: JQueryEventObject, groupID: SP.Guid, termSetID: SP.Guid) { + + // First, cancel the bubble so that the group div click handler does not also fire + // because that removes all term set divs and we don't want that here. + event.cancelBubble = true; + + // Get a reference to the term set div that was click and + // remove its children (apart from the TextNode that is currently + // showing the term set name. + var parentDiv = document.getElementById(termSetID.toString()); + while (parentDiv.childNodes.length > 1) { + parentDiv.removeChild(parentDiv.lastChild); + } + + // We need to load and populate the matching group first, or the + // term sets that it contains will be inaccessible to our code. + var currentGroup = groups.getById(groupID); + var termSets:SP.Taxonomy.TermSetCollection; + var currentTermSet:SP.Taxonomy.TermSet; + var terms:SP.Taxonomy.TermCollection; + + context.load(currentGroup); + context + .executeQueryPromise() + .then(() => { + // The group is now available becuase this is the + // success callback. So now we'll load and populate the + // term set collection. We have to do this before we can + // iterate through the collection, so we can do this + // with the following nested executeQueryAsync method call. + termSets = currentGroup.get_termSets(); + context.load(termSets); + return context.executeQueryPromise(); + }) + .then(() => { + currentTermSet = termSets.getById(termSetID); + context.load(currentTermSet); + return context.executeQueryPromise(); + }) + .then(() => { + terms = currentTermSet.get_terms(); + context.load(terms); + return context.executeQueryPromise(); + }) + .then(() => { + var termsEnum = terms.getEnumerator(); + while (termsEnum.moveNext()) { + var currentTerm = termsEnum.get_current(); + + var term = document.createElement("div"); + term.appendChild(document.createTextNode(" - " + currentTerm.get_name())); + term.setAttribute("style", "float:none;margin-left:10px;"); + parentDiv.appendChild(term); + } + }) + .fail(() => parentDiv.appendChild(document.createTextNode("An error occurred when trying to retrieve terms in this term set"))); + } + + // Runs when the executeQueryAsync method in the onListTaxonomySession function has failed. + // In this case, clear the report area in the page and tell the user what went wrong. + function onFailRetrieveGroups(sender, args) { + $('#report').children().remove(); + $('#report').append("Failed to retrieve groups. Error:" + args.get_message()); + } + + // Runs when the executeQueryAsync method in the listGroups function has failed. + // In this case, clear the report area in the page and tell the user what went wrong. + function onFailListTaxonomySession(sender, args) { + $('#report').children().remove(); + $('#report').append("Failed to get session. Error: " + args.get_message()); + } + + + // When the createTerms button is clicked, start by loading + // a TaxonomySession for the current context. Also get and load + // the associated term store. + function createTerms() { + session = SP.Taxonomy.TaxonomySession.getTaxonomySession(context); + termStore = session.getDefaultSiteCollectionTermStore(); + context.load(session); + context.load(termStore); + context.executeQueryAsync(onGetTaxonomySession, onFailTaxonomySession); + } + + + // This function is the success callback for loading the session and store from the createTerms function + function onGetTaxonomySession() { + // Create six GUIDs that we will need when we create a new group, term set, and associated terms + var guidGroupValue = SP.Guid.newGuid(); + var guidTermSetValue = SP.Guid.newGuid(); + var guidTerm1 = SP.Guid.newGuid(); + var guidTerm2 = SP.Guid.newGuid(); + var guidTerm3 = SP.Guid.newGuid(); + var guidTerm4 = SP.Guid.newGuid(); + + // Create a new group + var myGroup = termStore.createGroup("CustomTerms", guidGroupValue); + + // Create a new term set in the newly-created group + var myTermSet = myGroup.createTermSet("Privacy", guidTermSetValue, 1033); + + // Create four new terms in the newly-created term set + myTermSet.createTerm("Top Secret", 1033, guidTerm1); + myTermSet.createTerm("Company Confidential", 1033, guidTerm2); + myTermSet.createTerm("Partners Only", 1033, guidTerm3); + myTermSet.createTerm("Public", 1033, guidTerm4); + + // Ensure the groups variable has been set, because when this all succeeds we will + // effectively run the same code as if the user had clicked the listGroups button + groups = termStore.get_groups(); + context.load(groups); + + // Execute all the preceeding statements in this function + context.executeQueryAsync(onAddTerms, onFailAddTerms); + + } + + // If all is well with creating the terms, then this function will run. + // Effectively this runs the same code as if the user had clicked the listGroups button + // so the user will see their newly-created group + function onAddTerms() { + listGroups(); + } + + // Runs when the executeQueryAsync method in the onGetTaxonomySession function has failed. + // In this case, clear the report area in the page and tell the user what went wrong. + function onFailAddTerms(sender, args) { + $('#report').children().remove(); + $('#report').append("Failed to add terms. Error: " + args.get_message()); + } + + // Runs when the executeQueryAsync method in the createTerms function has failed. + // In this case, clear the report area in the page and tell the user what went wrong. + function onFailTaxonomySession(sender, args) { + $('#report').children().remove(); + $('#report').append("Failed to get session. Error: " + args.get_message()); + } + +}; + +//publishing.ts +// Variables used in various callbacks +JSRequest.EnsureSetup(); + +SP.SOD.execute('mquery.js', 'm$.ready', () => { + var context = SP.ClientContext.get_current(); + var web = context.get_web(); + m$('#CreatePage').click(createPage); +}); + +function createPage(evt) { + SP.SOD.execute('sp.js', 'SP.ClientConext', () => { + SP.SOD.execute('sp.publishing.js', 'SP.Publishing', () => { + var context = SP.ClientContext.get_current(); + + + var hostUrl = decodeURIComponent(JSRequest.QueryString["SPHostUrl"]); + var hostcontext = new SP.AppContextSite(context, hostUrl); + var web = hostcontext.get_web(); + var pubWeb = SP.Publishing.PublishingWeb.getPublishingWeb(context, web); + context.load(web); + context.load(pubWeb); + context.executeQueryAsync( + // Success callback after getting the host Web as a PublishingWeb. + // We now want to add a new Publishing Page. + function () { + var pageInfo = new SP.Publishing.PublishingPageInformation(); + var newPage = pubWeb.addPublishingPage(pageInfo); + context.load(newPage); + context.executeQueryAsync( + function () { + + // Success callback after adding a new Publishing Page. + // We want to get the actual list item that is represented by the Publishing Page. + var listItem = newPage.get_listItem(); + context.load(listItem); + context.executeQueryAsync( + + // Success callback after getting the actual list item that is + // represented by the Publishing Page. + // We can now get its FieldValues, one of which is its FileLeafRef value. + // We can then use that value to build the Url to the new page + // and set the href or our link to that Url. + function () { + var link = document.getElementById("linkToPage"); + link.setAttribute("href", web.get_url() + "/Pages/" + listItem.get_fieldValues().FileLeafRef); + link.innerText = "Go to new page!"; + }, + + // Failure callback after getting the actual list item that is + // represented by the Publishing Page. + function (sender, args) { + alert('Failed to get new page: ' + args.get_message()); + } + ); + }, + // Failure callback after trying to add a new Publishing Page. + function (sender, args) { + alert('Failed to Add Page: ' + args.get_message()); + } + ); + }, + // Failure callback after trying to get the host Web as a PublishingWeb. + function (sender, args) { + alert('Failed to get the PublishingWeb: ' + args.get_message()); + } + ); + }); + }); +} + +//likes +module SampleReputation { + + interface MyList extends SPClientTemplates.RenderContext_InView { + listId: string; + } + + class MyItem { + + id: number; + title: string; + likesCount: number; + isLikedByCurrentUser: boolean; + + constructor(public row: SPClientTemplates.Item) { + this.id = parseInt(row['ID']); + this.title = row['Title']; + this.likesCount = parseInt(row['LikesCount']) || 0; + this.isLikedByCurrentUser = this.getLike(row['LikedBy']); + } + + private getLike(likedBy): boolean { + if (likedBy && likedBy.length > 0) { + for (var i = 0; i < likedBy.length; i++) { + if (likedBy[i].id == _spPageContextInfo.userId) { + return true; + } + } + } + return false; + } + } + + function init() { + SP.SOD.registerSod('reputation.js', '/_layouts/15/reputation.js'); + SP.SOD.registerSod('typescripttemplates.ts', '/SPTypeScript/Extensions/typescripttemplates.js'); + SP.SOD.executeFunc('typescripttemplates.ts', 'CSR', () => { + CSR.override(10004, 1) + .onPreRender((ctx: MyList) => { + ctx.listId = ctx.listName.substring(1, 37); + }) + .header('
      ') + .body(renderTemplate) + .footer('
    ') + .register(); + }); + + SP.SOD.execute('mQuery.js', 'm$.ready', () => { + RegisterModuleInit('/SPTypeScript/ReputationModule/likes.js', init); + }); + + + SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs('likes.js'); + } + + function renderTemplate(ctx: MyList) { + var rows = ctx.ListData.Row; + var result = ''; + for (var i = 0; i < rows.length; i++) { + var item = new MyItem(rows[i]); + result += '\ +
  • ' + item.title +'\ + \ + ' + getLikeText(item.isLikedByCurrentUser) + '' + item.likesCount + '\ + \ +
  • '; + } + return result; + } + + function getLikeText(isLikedByCurrentUser: boolean) { + return isLikedByCurrentUser ? '\u2665' : '\u2661'; + } + + export function setLike(itemId: number, listId: string): void { + var context = SP.ClientContext.get_current(); + var isLiked = m$('#likesCountText' + itemId)[0].textContent == '\u2661'; + SP.SOD.executeFunc('reputation.js', 'Microsoft.Office.Server.ReputationModel.Reputation', function () { + Microsoft.Office.Server.ReputationModel.Reputation.setLike(context, listId, itemId, isLiked); + context.executeQueryAsync( + () => { + m$('#likesCountText' + itemId)[0].textContent = getLikeText(isLiked); + var likesCount = parseInt(m$('#likesCount' + itemId)[0].textContent); + m$('#likesCount' + itemId)[0].textContent = (isLiked ? likesCount + 1 : likesCount - 1).toString(); + }, + (sender, args) => { + alert(args.get_message()); + }); + }); + } + + init(); +} + + + +//code from https://github.com/gandjustas/SharePointAngularTS +module App { + "use strict"; +var app = angular.module("app", []); +} + +// Install the angularjs.TypeScript.DefinitelyTyped NuGet package +module App { + "use strict"; + + interface Iappcontroller { + title: string; + activate: () => void; + } + + class appcontroller implements Iappcontroller { + title: string = "appcontroller"; + lists: SP.List[]; + + static $inject: string[] = ["$SharePoint", "$spnotify"]; + + constructor(private $SharePoint: App.ISharePoint, private $n:App.ISpNotify) { + this.activate(); + } + + activate() { + var loading = this.$n.showLoading(true) + this.$SharePoint + .getLists() + .then(l => this.lists = l ) + .catch((e: string) => this.$n.show(e, true)) + .finally(() => this.$n.remove(loading) ); + ; + + } + } + + angular.module("app").controller("appcontroller", appcontroller); +} + + + +module App { + "use strict"; + + export interface ISharePoint { + getLists: () => ng.IPromise; + } + + class SharePointServcie implements ISharePoint { + static $inject: string[] = ["$q"]; + + constructor(public $q: ng.IQService) { + } + + getLists() { + var promise = this.$q.defer(); + SP.SOD.executeFunc("sp.js", "SP.ClientContext", () => { + var ctx = SP.ClientContext.get_current(); + var hostUrl = decodeURIComponent(SP.ScriptHelpers.getDocumentQueryPairs()['SPHostUrl']); + var appCtx = new SP.AppContextSite(ctx, hostUrl); + var hostWeb = appCtx.get_web(); + var lists = hostWeb.get_lists(); + ctx.load(lists); + + ctx.executeQueryAsync(() => { + var result: SP.List[] = []; + for (var e = lists.getEnumerator(); e.moveNext();) { + result.push(e.get_current()); + } + promise.resolve(result); + }, + (o, args) => { promise.reject(args.get_message()); }); + }); + return promise.promise; + } + } + + angular.module("app").service("$SharePoint", SharePointServcie); +} + + +// Install the angularjs.TypeScript.DefinitelyTyped NuGet package +module App { + "use strict"; + + export interface ISpNotify { + showLoading(sticky?: boolean) : string; + show(msg: string, sticky?: boolean): string; + remove(id: string):void; + } + + class SpNotify implements ISpNotify { + static $inject: string[] = []; + + + showLoading(sticky: boolean = false) { + return SP.UI.Notify.showLoadingNotification(sticky); + } + + show(msg: string, sticky: boolean = false) { + return SP.UI.Notify.addNotification(msg, sticky); + } + + remove(id: string) { + SP.UI.Notify.removeNotification(id); + } + } + + angular.module("app").service("$spnotify", SpNotify); +} + diff --git a/sharepoint/SharePoint-tests.ts.tscparams b/sharepoint/SharePoint-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/sharepoint/SharePoint-tests.ts.tscparams +++ b/sharepoint/SharePoint-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/siesta/siesta-tests.ts.tscparams b/siesta/siesta-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/siesta/siesta-tests.ts.tscparams +++ b/siesta/siesta-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/siesta/siesta.d.ts.tscparams b/siesta/siesta.d.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/siesta/siesta.d.ts.tscparams +++ b/siesta/siesta.d.ts.tscparams @@ -1 +1 @@ - + diff --git a/signalr/signalr-tests.ts b/signalr/signalr-tests.ts index 3ef8cad87..5c79f8270 100644 --- a/signalr/signalr-tests.ts +++ b/signalr/signalr-tests.ts @@ -1,137 +1,137 @@ -/// - -function test_client() { - var connection = $.connection('/echo'); - connection.received(function (data) { - console.log(data); - }); - connection.error(function (error) { - console.warn(error); - }); - connection.stateChanged(function (change) { - if (change.newState === $.signalR.connectionState.reconnecting) { - console.log('Re-connecting'); - } - else if (change.newState === $.signalR.connectionState.connected) { - console.log('The server is online'); - } - }); - connection.reconnected(function () { - console.log('Reconnected'); - }); - connection.start(); - connection.start(function () { - console.log("connection started!"); - }); - connection.stop(); - connection.start().done(function () { - console.log("connection started!"); - }); - connection.start({ transport: 'longPolling' }); - connection.start({ transport: $.signalR.transports.webSockets }); - connection.start({ transport: ['longPolling', 'webSockets'] }); - connection.start({ waitForPageLoad: false }); - connection.start({ transport: 'longPolling' }, function () { - console.log('connection started!'); - }); - connection.send("Hello World"); - var connection = $.connection('http://localhost:8081/echo'); - connection.start({ jsonp: true }); -} - -function test_connection() { - var connection = $.connection('/echo'); - connection.received(function (data) { - $('#messages').append('
  • ' + data + '
  • '); - }); - connection.start(); - $("#broadcast").click(function () { - connection.send($('#msg').val()); - }); -} - -interface MyHubConnection extends HubConnection { - someState: string; - SomeFunction: Function; - - // My Hubs Client functions: - client: { - addMessage: (message: string) => void; - }; - // My Hubs Server function: - server: { - send(message: string): any; - }; -} - -interface SignalR { - chat: MyHubConnection; - myHub: MyHubConnection; -} - -function test_hubs() { - var chat = $.connection.chat; - $.connection.hub.start() - .done(function () { alert("Now connected!"); }) - .fail(function () { alert("Could not Connect!"); }); - - $.connection.hub.logging = true; - var myHub = $.connection.myHub; - myHub.someState = "SomeValue"; - function connectionReady() { - alert("Done calling first hub serverside-function"); - }; - myHub.SomeFunction = function () { - alert("serverside called 'Clients.SomeClientFunction()'"); - }; - $.connection.hub.error(function () { - alert("An error occured"); - }); - $.connection.hub.start() - .done(function () { - myHub.SomeFunction("whatever") - .done(connectionReady); - }) - .fail(function () { - alert("Could not Connect!"); - }); - - $.connection.hub.url = 'http://localhost:8081/signalr' - $.connection.hub.start(); - - var connection = $.hubConnection(); - var proxy = connection.createHubProxy('chat'); - var proxy = connection.createHubProxy('chat'), - msg = 'hello', - room = 'main'; - proxy.invoke('send', msg); - proxy.invoke('send', msg, room); - proxy.invoke('add', 1, 2) - .done(function (result: any) { - console.log('The result is ' + result); - }); - proxy.on('addMessage', function (msg?) { - console.log(msg); - }); - var connection = $.hubConnection('http://localhost:8081/'); - connection.start({ jsonp: true }); -} - -// Sample from : https://github.com/SignalR/SignalR/wiki/QuickStart-Hubs#javascript--html -$(function () { - // Proxy created on the fly - var chat = $.connection.chat; - - // Declare a function on the chat hub so the server can invoke it - chat.client.addMessage = function (message) { - $('#messages').append('
  • ' + message + '
  • '); - }; - - // Start the connection - $.connection.hub.start().done(function () { - $("#broadcast").click(function () { - // Call the chat method on the server - chat.server.send($('#msg').val()); - }); - }); +/// + +function test_client() { + var connection = $.connection('/echo'); + connection.received(function (data) { + console.log(data); + }); + connection.error(function (error) { + console.warn(error); + }); + connection.stateChanged(function (change) { + if (change.newState === $.signalR.connectionState.reconnecting) { + console.log('Re-connecting'); + } + else if (change.newState === $.signalR.connectionState.connected) { + console.log('The server is online'); + } + }); + connection.reconnected(function () { + console.log('Reconnected'); + }); + connection.start(); + connection.start(function () { + console.log("connection started!"); + }); + connection.stop(); + connection.start().done(function () { + console.log("connection started!"); + }); + connection.start({ transport: 'longPolling' }); + connection.start({ transport: $.signalR.transports.webSockets }); + connection.start({ transport: ['longPolling', 'webSockets'] }); + connection.start({ waitForPageLoad: false }); + connection.start({ transport: 'longPolling' }, function () { + console.log('connection started!'); + }); + connection.send("Hello World"); + var connection = $.connection('http://localhost:8081/echo'); + connection.start({ jsonp: true }); +} + +function test_connection() { + var connection = $.connection('/echo'); + connection.received(function (data) { + $('#messages').append('
  • ' + data + '
  • '); + }); + connection.start(); + $("#broadcast").click(function () { + connection.send($('#msg').val()); + }); +} + +interface MyHubConnection extends HubConnection { + someState: string; + SomeFunction: Function; + + // My Hubs Client functions: + client: { + addMessage: (message: string) => void; + }; + // My Hubs Server function: + server: { + send(message: string): any; + }; +} + +interface SignalR { + chat: MyHubConnection; + myHub: MyHubConnection; +} + +function test_hubs() { + var chat = $.connection.chat; + $.connection.hub.start() + .done(function () { alert("Now connected!"); }) + .fail(function () { alert("Could not Connect!"); }); + + $.connection.hub.logging = true; + var myHub = $.connection.myHub; + myHub.someState = "SomeValue"; + function connectionReady() { + alert("Done calling first hub serverside-function"); + }; + myHub.SomeFunction = function () { + alert("serverside called 'Clients.SomeClientFunction()'"); + }; + $.connection.hub.error(function () { + alert("An error occured"); + }); + $.connection.hub.start() + .done(function () { + myHub.SomeFunction("whatever") + .done(connectionReady); + }) + .fail(function () { + alert("Could not Connect!"); + }); + + $.connection.hub.url = 'http://localhost:8081/signalr' + $.connection.hub.start(); + + var connection = $.hubConnection(); + var proxy = connection.createHubProxy('chat'); + var proxy = connection.createHubProxy('chat'), + msg = 'hello', + room = 'main'; + proxy.invoke('send', msg); + proxy.invoke('send', msg, room); + proxy.invoke('add', 1, 2) + .done(function (result: any) { + console.log('The result is ' + result); + }); + proxy.on('addMessage', function (msg?) { + console.log(msg); + }); + var connection = $.hubConnection('http://localhost:8081/'); + connection.start({ jsonp: true }); +} + +// Sample from : https://github.com/SignalR/SignalR/wiki/QuickStart-Hubs#javascript--html +$(function () { + // Proxy created on the fly + var chat = $.connection.chat; + + // Declare a function on the chat hub so the server can invoke it + chat.client.addMessage = function (message) { + $('#messages').append('
  • ' + message + '
  • '); + }; + + // Start the connection + $.connection.hub.start().done(function () { + $("#broadcast").click(function () { + // Call the chat method on the server + chat.server.send($('#msg').val()); + }); + }); }); \ No newline at end of file diff --git a/signalr/signalr.d.ts b/signalr/signalr.d.ts index 515b1864f..d899416dd 100644 --- a/signalr/signalr.d.ts +++ b/signalr/signalr.d.ts @@ -1,113 +1,113 @@ -// Type definitions for SignalR 1.0 -// Project: http://www.asp.net/signalr -// Definitions by: Boris Yankov , T. Michael Keesey -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -/// - -interface HubMethod { - (callback: (data: string) => void ): any; -} - -interface SignalREvents { - onStart: string; - onStarting: string; - onReceived: string; - onError: string; - onConnectionSlow: string; - onReconnect: string; - onStateChanged: string; - onDisconnect: string; -} - -interface SignalRStateChange { - oldState: number; - newState: number; -} - -interface SignalR { - events: SignalREvents; - connectionState: any; - transports: any; - - hub: HubConnection; - id: string; - logging: boolean; - messageId: string; - url: string; - qs: any; - state: number; - - (url: string, queryString?: any, logging?: boolean): SignalR; - hubConnection(url?: string): SignalR; - - log(msg: string, logging: boolean): void; - isCrossDomain(url: string): boolean; - changeState(connection: SignalR, expectedState: number, newState: number): boolean; - isDisconnecting(connection: SignalR): boolean; - - // createHubProxy(hubName: string): SignalR; - - start(): JQueryPromise; - start(callback: () => void ): JQueryPromise; - start(settings: ConnectionSettings): JQueryPromise; - start(settings: ConnectionSettings, callback: () => void ): JQueryPromise; - - - send(data: string): void; - stop(async?: boolean, notifyServer?: boolean): void; - - starting(handler: () => void ): SignalR; - received(handler: (data: any) => void ): SignalR; - error(handler: (error: Error) => void ): SignalR; - stateChanged(handler: (change: SignalRStateChange) => void ): SignalR; - disconnected(handler: () => void ): SignalR; - connectionSlow(handler: () => void ): SignalR; - sending(handler: () => void ): SignalR; - reconnecting(handler: () => void): SignalR; - reconnected(handler: () => void): SignalR; -} - -interface HubProxy { - (connection: HubConnection, hubName: string): HubProxy; - state: any; - connection: HubConnection; - hubName: string; - init(connection: HubConnection, hubName: string): void; - hasSubscriptions(): boolean; - on(eventName: string, callback: (...msg: any[]) => void ): HubProxy; - off(eventName: string, callback: (msg: any) => void ): HubProxy; - invoke(methodName: string, ...args: any[]): JQueryDeferred; -} - -interface HubConnectionSettings { - queryString?: string; - logging?: boolean; - useDefaultPath?: boolean; -} - -interface HubConnection extends SignalR { - //(url?: string, queryString?: any, logging?: boolean): HubConnection; - proxies: any; - transport: { name: string, supportsKeepAlive: () => boolean }; - received(callback: (data: { Id: any; Method: any; Hub: any; State: any; Args: any; }) => void ): HubConnection; - createHubProxy(hubName: string): HubProxy; -} - -interface SignalRfn { - init(url: any, qs: any, logging: any): any; -} - -interface ConnectionSettings { - transport?: any; - callback?: any; - waitForPageLoad?: boolean; - jsonp?: boolean; -} - -interface JQueryStatic { - signalR: SignalR; - connection: SignalR; - hubConnection(url?: string, options?: HubConnectionSettings): HubConnection; -} +// Type definitions for SignalR 1.0 +// Project: http://www.asp.net/signalr +// Definitions by: Boris Yankov , T. Michael Keesey +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +interface HubMethod { + (callback: (data: string) => void ): any; +} + +interface SignalREvents { + onStart: string; + onStarting: string; + onReceived: string; + onError: string; + onConnectionSlow: string; + onReconnect: string; + onStateChanged: string; + onDisconnect: string; +} + +interface SignalRStateChange { + oldState: number; + newState: number; +} + +interface SignalR { + events: SignalREvents; + connectionState: any; + transports: any; + + hub: HubConnection; + id: string; + logging: boolean; + messageId: string; + url: string; + qs: any; + state: number; + + (url: string, queryString?: any, logging?: boolean): SignalR; + hubConnection(url?: string): SignalR; + + log(msg: string, logging: boolean): void; + isCrossDomain(url: string): boolean; + changeState(connection: SignalR, expectedState: number, newState: number): boolean; + isDisconnecting(connection: SignalR): boolean; + + // createHubProxy(hubName: string): SignalR; + + start(): JQueryPromise; + start(callback: () => void ): JQueryPromise; + start(settings: ConnectionSettings): JQueryPromise; + start(settings: ConnectionSettings, callback: () => void ): JQueryPromise; + + + send(data: string): void; + stop(async?: boolean, notifyServer?: boolean): void; + + starting(handler: () => void ): SignalR; + received(handler: (data: any) => void ): SignalR; + error(handler: (error: Error) => void ): SignalR; + stateChanged(handler: (change: SignalRStateChange) => void ): SignalR; + disconnected(handler: () => void ): SignalR; + connectionSlow(handler: () => void ): SignalR; + sending(handler: () => void ): SignalR; + reconnecting(handler: () => void): SignalR; + reconnected(handler: () => void): SignalR; +} + +interface HubProxy { + (connection: HubConnection, hubName: string): HubProxy; + state: any; + connection: HubConnection; + hubName: string; + init(connection: HubConnection, hubName: string): void; + hasSubscriptions(): boolean; + on(eventName: string, callback: (...msg: any[]) => void ): HubProxy; + off(eventName: string, callback: (msg: any) => void ): HubProxy; + invoke(methodName: string, ...args: any[]): JQueryDeferred; +} + +interface HubConnectionSettings { + queryString?: string; + logging?: boolean; + useDefaultPath?: boolean; +} + +interface HubConnection extends SignalR { + //(url?: string, queryString?: any, logging?: boolean): HubConnection; + proxies: any; + transport: { name: string, supportsKeepAlive: () => boolean }; + received(callback: (data: { Id: any; Method: any; Hub: any; State: any; Args: any; }) => void ): HubConnection; + createHubProxy(hubName: string): HubProxy; +} + +interface SignalRfn { + init(url: any, qs: any, logging: any): any; +} + +interface ConnectionSettings { + transport?: any; + callback?: any; + waitForPageLoad?: boolean; + jsonp?: boolean; +} + +interface JQueryStatic { + signalR: SignalR; + connection: SignalR; + hubConnection(url?: string, options?: HubConnectionSettings): HubConnection; +} diff --git a/socket.io-client/socket.io-client-tests.ts b/socket.io-client/socket.io-client-tests.ts index cd9be6d3d..f2563fc46 100644 --- a/socket.io-client/socket.io-client-tests.ts +++ b/socket.io-client/socket.io-client-tests.ts @@ -1,61 +1,61 @@ -/// - -function testUsingWithNodeHTTPServer() { - var socket = io('http://localhost'); - socket.on('news', function (data: any) { - console.log(data); - socket.emit('my other event', { my: 'data' }); - }); -} - -function testUsingWithExpress() { - var socket = io.connect('http://localhost'); - socket.on('news', function (data: any) { - console.log(data); - socket.emit('my other event', { my: 'data' }); - }); -} - -function testUsingWithTheExpressFramework() { - var socket = io.connect('http://localhost'); - socket.on('news', function (data: any) { - console.log(data); - socket.emit('my other event', { my: 'data' }); - }); -} - -function testRestrictingYourselfToANamespace() { - var chat = io.connect('http://localhost/chat') - , news = io.connect('http://localhost/news'); - - chat.on('connect', function () { - chat.emit('hi!'); - }); - - news.on('news', function () { - news.emit('woot'); - }); -} - -function testSendingAndGettingData() { - var socket = io(); - socket.on('connect', function () { - socket.emit('ferret', 'tobi', function (data: any) { - console.log(data); - }); - }); -} - -function testUsingItJustAsACrossBrowserWebSocket() { - var socket = io('http://localhost/'); - socket.on('connect', function () { - socket.emit('hi'); - - socket.on('message', function (msg: any) { - }); - }); -} - -function testSettingReconnectionAttempts() { - var manager = io.Manager({ reconnection: true, timeout: 0, reconnectionAttempts: 2, reconnectionDelay: 10 }); -} +/// + +function testUsingWithNodeHTTPServer() { + var socket = io('http://localhost'); + socket.on('news', function (data: any) { + console.log(data); + socket.emit('my other event', { my: 'data' }); + }); +} + +function testUsingWithExpress() { + var socket = io.connect('http://localhost'); + socket.on('news', function (data: any) { + console.log(data); + socket.emit('my other event', { my: 'data' }); + }); +} + +function testUsingWithTheExpressFramework() { + var socket = io.connect('http://localhost'); + socket.on('news', function (data: any) { + console.log(data); + socket.emit('my other event', { my: 'data' }); + }); +} + +function testRestrictingYourselfToANamespace() { + var chat = io.connect('http://localhost/chat') + , news = io.connect('http://localhost/news'); + + chat.on('connect', function () { + chat.emit('hi!'); + }); + + news.on('news', function () { + news.emit('woot'); + }); +} + +function testSendingAndGettingData() { + var socket = io(); + socket.on('connect', function () { + socket.emit('ferret', 'tobi', function (data: any) { + console.log(data); + }); + }); +} + +function testUsingItJustAsACrossBrowserWebSocket() { + var socket = io('http://localhost/'); + socket.on('connect', function () { + socket.emit('hi'); + + socket.on('message', function (msg: any) { + }); + }); +} + +function testSettingReconnectionAttempts() { + var manager = io.Manager({ reconnection: true, timeout: 0, reconnectionAttempts: 2, reconnectionDelay: 10 }); +} diff --git a/sortablejs/sortablejs-tests.ts b/sortablejs/sortablejs-tests.ts index 56b8b0a32..8c45596cb 100755 --- a/sortablejs/sortablejs-tests.ts +++ b/sortablejs/sortablejs-tests.ts @@ -1,299 +1,299 @@ -// Examples from project repo used for tests. - -/// - -var simpleList = document.getElementById('list'); -var list = simpleList; -var el = document.getElementById('el'); -var sortable = new Sortable(simpleList, {}); -var order = sortable.toArray(); -var angular: any; -var Ply: any; - -sortable.sort(order.reverse()); - -Sortable.create(list, { - delay: 500, - chosenClass: "chosen" -}); - -Sortable.create(el, { - handle: ".my-handle" -}); - -Sortable.create(list, { - filter: ".js-remove, .js-edit", - onFilter: function(event) { - var item = event.item, - control = event.target; - - if (Sortable.utils.is(control, ".js-remove")) { - item.parentNode.removeChild(item); - } - else if (Sortable.utils.is(control, ".js-edit")) { - // .. - } - } -}); - -Sortable.create(el, { - group: "localStorage-example", - store: { - get: function(sortable) { - var order = localStorage.getItem(sortable.options.group); - - return order ? order.split('|') : []; - }, - set: function(sortable) { - var order = sortable.toArray(); - - localStorage.setItem(sortable.options.group, order.join('|')); - } - } -}); - -Sortable.create(simpleList, { - forceFallback: true -}); - -Sortable.create(simpleList, { - ghostClass: 'ghost' -}); - -simpleList.innerHTML = Array.apply(null, new Array(100)).map(function(value: any, iterator: number) { - return `
    item ${iterator + 1}
    `; -}).join(''); - -Sortable.create(simpleList, { - delay: 500, - chosenClass: 'chosen' -}); - -simpleList.innerHTML = Array.apply(null, new Array(10)).map(function(value: any, iterator: number) { - return '
    item ' + - (iterator + 1) + - '
    '; -}).join(''); - -Sortable.create(simpleList, {}); - -simpleList.innerHTML = Array.apply(null, new Array(100)).map(function(value: any, iterator: number) { - return '
    item ' + - (iterator + 1) + - '
    '; -}).join(''); - -(function() { - 'use strict'; - - var byId = function(id: string) { return document.getElementById(id); }, - - loadScripts = function(desc: any, callback: any) { - var deps: string[] = []; - var key: string; - var idx = 0; - - for (key in desc) { - deps.push(key); - } - - (function _next() { - var pid: number, - name = deps[idx], - script = document.createElement('script'); - - script.type = 'text/javascript'; - script.src = desc[deps[idx]]; - - document.getElementsByTagName('head')[0].appendChild(script); - })() - }, - - console = window.console; - - - if (!console.log) { - console.log = function() { - alert([].join.apply(arguments, ' ')); - }; - } - - - Sortable.create(byId('foo'), { - group: "words", - animation: 150, - store: { - get: function(sortable) { - var order = localStorage.getItem(sortable.options.group); - return order ? order.split('|') : []; - }, - set: function(sortable) { - var order = sortable.toArray(); - localStorage.setItem(sortable.options.group, order.join('|')); - } - }, - onAdd: function(evt) { console.log('onAdd.foo:', [evt.item, evt.from]); }, - onUpdate: function(evt) { console.log('onUpdate.foo:', [evt.item, evt.from]); }, - onRemove: function(evt) { console.log('onRemove.foo:', [evt.item, evt.from]); }, - onStart: function(evt) { console.log('onStart.foo:', [evt.item, evt.from]); }, - onSort: function(evt) { console.log('onStart.foo:', [evt.item, evt.from]); }, - onEnd: function(evt) { console.log('onEnd.foo:', [evt.item, evt.from]); } - }); - - - Sortable.create(byId('bar'), { - group: "words", - animation: 150, - onAdd: function(evt) { console.log('onAdd.bar:', evt.item); }, - onUpdate: function(evt) { console.log('onUpdate.bar:', evt.item); }, - onRemove: function(evt) { console.log('onRemove.bar:', evt.item); }, - onStart: function(evt) { console.log('onStart.foo:', evt.item); }, - onEnd: function(evt) { console.log('onEnd.foo:', evt.item); } - }); - - - // Multi groups - Sortable.create(byId('multi'), { - animation: 150, - draggable: '.tile', - handle: '.tile__name' - }); - - [].forEach.call(byId('multi').getElementsByClassName('tile__list'), function(el: any) { - Sortable.create(el, { - group: 'photo', - animation: 150 - }); - }); - - - // Editable list - var editableList = Sortable.create(byId('editable'), { - animation: 150, - filter: '.js-remove', - onFilter: function(evt) { - evt.item.parentNode.removeChild(evt.item); - } - }); - - - byId('addUser').onclick = function() { - Ply.dialog('prompt', { - title: 'Add', - form: { name: 'name' } - }).done(function(ui: any) { - var el = document.createElement('li'); - el.innerHTML = ui.data.name + ''; - editableList.el.appendChild(el); - }); - }; - - - // Advanced groups - [{ - name: 'advanced', - pull: true, - put: true - }, - { - name: 'advanced', - pull: 'clone', - put: false - }, { - name: 'advanced', - pull: false, - put: true - }].forEach(function(groupOpts, i) { - Sortable.create(byId('advanced-' + (i + 1)), { - sort: (i != 1), - group: groupOpts, - animation: 150 - }); - }); - - - // 'handle' option - Sortable.create(byId('handle-1'), { - handle: '.drag-handle', - animation: 150 - }); - - - // Angular example - angular.module('todoApp', ['ng-sortable']) - .constant('ngSortableConfig', { - onEnd: function() { - console.log('default onEnd()'); - } - }) - .controller('TodoController', ['$scope', function($scope: any) { - $scope.todos = [ - { text: 'learn angular', done: true }, - { text: 'build an angular app', done: false } - ]; - - $scope.addTodo = function() { - $scope.todos.push({ text: $scope.todoText, done: false }); - $scope.todoText = ''; - }; - - $scope.remaining = function() { - var count = 0; - angular.forEach($scope.todos, function(todo: any) { - count += todo.done ? 0 : 1; - }); - return count; - }; - - $scope.archive = function() { - var oldTodos = $scope.todos; - $scope.todos = []; - angular.forEach(oldTodos, function(todo: any) { - if (!todo.done) $scope.todos.push(todo); - }); - }; - }]) - .controller('TodoControllerNext', ['$scope', function($scope: any) { - $scope.todos = [ - { text: 'learn Sortable', done: true }, - { text: 'use ng-sortable', done: false }, - { text: 'Enjoy', done: false } - ]; - - $scope.remaining = function() { - var count = 0; - angular.forEach($scope.todos, function(todo: any) { - count += todo.done ? 0 : 1; - }); - return count; - }; - - $scope.sortableConfig = { group: 'todo', animation: 150 }; - 'Start End Add Update Remove Sort'.split(' ').forEach(function(name: string) { - $scope.sortableConfig['on' + name] = console.log.bind(console, name); - }); - }]); -})(); - -// Background -document.addEventListener("DOMContentLoaded", function() { - function setNoiseBackground(el: any, width: number, height: number, opacity: number) { - var canvas = document.createElement("canvas"); - var context = canvas.getContext("2d"); - - canvas.width = width; - canvas.height = height; - - for (var i = 0; i < width; i++) { - for (var j = 0; j < height; j++) { - var val = Math.floor(Math.random() * 255); - context.fillStyle = "rgba(" + val + "," + val + "," + val + "," + opacity + ")"; - context.fillRect(i, j, 1, 1); - } - } - - el.style.background = "url(" + canvas.toDataURL("image/png") + ")"; - } - - setNoiseBackground(document.getElementsByTagName('body')[0], 50, 50, 0.02); -}, false); +// Examples from project repo used for tests. + +/// + +var simpleList = document.getElementById('list'); +var list = simpleList; +var el = document.getElementById('el'); +var sortable = new Sortable(simpleList, {}); +var order = sortable.toArray(); +var angular: any; +var Ply: any; + +sortable.sort(order.reverse()); + +Sortable.create(list, { + delay: 500, + chosenClass: "chosen" +}); + +Sortable.create(el, { + handle: ".my-handle" +}); + +Sortable.create(list, { + filter: ".js-remove, .js-edit", + onFilter: function(event) { + var item = event.item, + control = event.target; + + if (Sortable.utils.is(control, ".js-remove")) { + item.parentNode.removeChild(item); + } + else if (Sortable.utils.is(control, ".js-edit")) { + // .. + } + } +}); + +Sortable.create(el, { + group: "localStorage-example", + store: { + get: function(sortable) { + var order = localStorage.getItem(sortable.options.group); + + return order ? order.split('|') : []; + }, + set: function(sortable) { + var order = sortable.toArray(); + + localStorage.setItem(sortable.options.group, order.join('|')); + } + } +}); + +Sortable.create(simpleList, { + forceFallback: true +}); + +Sortable.create(simpleList, { + ghostClass: 'ghost' +}); + +simpleList.innerHTML = Array.apply(null, new Array(100)).map(function(value: any, iterator: number) { + return `
    item ${iterator + 1}
    `; +}).join(''); + +Sortable.create(simpleList, { + delay: 500, + chosenClass: 'chosen' +}); + +simpleList.innerHTML = Array.apply(null, new Array(10)).map(function(value: any, iterator: number) { + return '
    item ' + + (iterator + 1) + + '
    '; +}).join(''); + +Sortable.create(simpleList, {}); + +simpleList.innerHTML = Array.apply(null, new Array(100)).map(function(value: any, iterator: number) { + return '
    item ' + + (iterator + 1) + + '
    '; +}).join(''); + +(function() { + 'use strict'; + + var byId = function(id: string) { return document.getElementById(id); }, + + loadScripts = function(desc: any, callback: any) { + var deps: string[] = []; + var key: string; + var idx = 0; + + for (key in desc) { + deps.push(key); + } + + (function _next() { + var pid: number, + name = deps[idx], + script = document.createElement('script'); + + script.type = 'text/javascript'; + script.src = desc[deps[idx]]; + + document.getElementsByTagName('head')[0].appendChild(script); + })() + }, + + console = window.console; + + + if (!console.log) { + console.log = function() { + alert([].join.apply(arguments, ' ')); + }; + } + + + Sortable.create(byId('foo'), { + group: "words", + animation: 150, + store: { + get: function(sortable) { + var order = localStorage.getItem(sortable.options.group); + return order ? order.split('|') : []; + }, + set: function(sortable) { + var order = sortable.toArray(); + localStorage.setItem(sortable.options.group, order.join('|')); + } + }, + onAdd: function(evt) { console.log('onAdd.foo:', [evt.item, evt.from]); }, + onUpdate: function(evt) { console.log('onUpdate.foo:', [evt.item, evt.from]); }, + onRemove: function(evt) { console.log('onRemove.foo:', [evt.item, evt.from]); }, + onStart: function(evt) { console.log('onStart.foo:', [evt.item, evt.from]); }, + onSort: function(evt) { console.log('onStart.foo:', [evt.item, evt.from]); }, + onEnd: function(evt) { console.log('onEnd.foo:', [evt.item, evt.from]); } + }); + + + Sortable.create(byId('bar'), { + group: "words", + animation: 150, + onAdd: function(evt) { console.log('onAdd.bar:', evt.item); }, + onUpdate: function(evt) { console.log('onUpdate.bar:', evt.item); }, + onRemove: function(evt) { console.log('onRemove.bar:', evt.item); }, + onStart: function(evt) { console.log('onStart.foo:', evt.item); }, + onEnd: function(evt) { console.log('onEnd.foo:', evt.item); } + }); + + + // Multi groups + Sortable.create(byId('multi'), { + animation: 150, + draggable: '.tile', + handle: '.tile__name' + }); + + [].forEach.call(byId('multi').getElementsByClassName('tile__list'), function(el: any) { + Sortable.create(el, { + group: 'photo', + animation: 150 + }); + }); + + + // Editable list + var editableList = Sortable.create(byId('editable'), { + animation: 150, + filter: '.js-remove', + onFilter: function(evt) { + evt.item.parentNode.removeChild(evt.item); + } + }); + + + byId('addUser').onclick = function() { + Ply.dialog('prompt', { + title: 'Add', + form: { name: 'name' } + }).done(function(ui: any) { + var el = document.createElement('li'); + el.innerHTML = ui.data.name + ''; + editableList.el.appendChild(el); + }); + }; + + + // Advanced groups + [{ + name: 'advanced', + pull: true, + put: true + }, + { + name: 'advanced', + pull: 'clone', + put: false + }, { + name: 'advanced', + pull: false, + put: true + }].forEach(function(groupOpts, i) { + Sortable.create(byId('advanced-' + (i + 1)), { + sort: (i != 1), + group: groupOpts, + animation: 150 + }); + }); + + + // 'handle' option + Sortable.create(byId('handle-1'), { + handle: '.drag-handle', + animation: 150 + }); + + + // Angular example + angular.module('todoApp', ['ng-sortable']) + .constant('ngSortableConfig', { + onEnd: function() { + console.log('default onEnd()'); + } + }) + .controller('TodoController', ['$scope', function($scope: any) { + $scope.todos = [ + { text: 'learn angular', done: true }, + { text: 'build an angular app', done: false } + ]; + + $scope.addTodo = function() { + $scope.todos.push({ text: $scope.todoText, done: false }); + $scope.todoText = ''; + }; + + $scope.remaining = function() { + var count = 0; + angular.forEach($scope.todos, function(todo: any) { + count += todo.done ? 0 : 1; + }); + return count; + }; + + $scope.archive = function() { + var oldTodos = $scope.todos; + $scope.todos = []; + angular.forEach(oldTodos, function(todo: any) { + if (!todo.done) $scope.todos.push(todo); + }); + }; + }]) + .controller('TodoControllerNext', ['$scope', function($scope: any) { + $scope.todos = [ + { text: 'learn Sortable', done: true }, + { text: 'use ng-sortable', done: false }, + { text: 'Enjoy', done: false } + ]; + + $scope.remaining = function() { + var count = 0; + angular.forEach($scope.todos, function(todo: any) { + count += todo.done ? 0 : 1; + }); + return count; + }; + + $scope.sortableConfig = { group: 'todo', animation: 150 }; + 'Start End Add Update Remove Sort'.split(' ').forEach(function(name: string) { + $scope.sortableConfig['on' + name] = console.log.bind(console, name); + }); + }]); +})(); + +// Background +document.addEventListener("DOMContentLoaded", function() { + function setNoiseBackground(el: any, width: number, height: number, opacity: number) { + var canvas = document.createElement("canvas"); + var context = canvas.getContext("2d"); + + canvas.width = width; + canvas.height = height; + + for (var i = 0; i < width; i++) { + for (var j = 0; j < height; j++) { + var val = Math.floor(Math.random() * 255); + context.fillStyle = "rgba(" + val + "," + val + "," + val + "," + opacity + ")"; + context.fillRect(i, j, 1, 1); + } + } + + el.style.background = "url(" + canvas.toDataURL("image/png") + ")"; + } + + setNoiseBackground(document.getElementsByTagName('body')[0], 50, 50, 0.02); +}, false); diff --git a/sortablejs/sortablejs.d.ts b/sortablejs/sortablejs.d.ts index 6a745ab31..e633830e5 100755 --- a/sortablejs/sortablejs.d.ts +++ b/sortablejs/sortablejs.d.ts @@ -1,208 +1,208 @@ -// Type definitions for Sortable.js v1.3.0-rc1 -// Project: https://github.com/RubaXa/Sortable -// Definitions by: Maw-Fox -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module Sortablejs { - interface SortableOptions { - group?: any; - sort?: boolean; - delay?: number; - disabled?: boolean; - store?: { - get: (sortable: Sortable) => any[]; - set: (sortable: Sortable) => any; - }; - animation?: number; - handle?: string; - filter?: any; - draggable?: string; - ghostClass?: string; - chosenClass?: string; - dataIdAttr?: string; - forceFallback?: boolean; - fallbackClass?: string; - fallbackOnBody?: boolean; - scroll?: boolean; - scrollSensitivity?: number; - scrollSpeed?: number; - setData?: (dataTransfer: any, draggedElement: any) => any; - onStart?: (event: any) => any; - onEnd?: (event: any) => any; - onAdd?: (event: any) => any; - onUpdate?: (event: any) => any; - onSort?: (event: any) => any; - onRemove?: (event: any) => any; - onFilter?: (event: any) => any; - onMove?: (event: any) => boolean; - } - - interface SortableUtils { - /** - * Attach an event handler function - * @param {HTMLElement} element an HTMLElement. - * @param {string} event an Event context. - * @param {Function} fn - */ - on(element: any, event: string, fn: (event: any) => any): void; - - /** - * Remove an event handler function - * @param {HTMLElement} element an HTMLElement. - * @param {string} event an Event context. - * @param {Function} fn a callback. - */ - off(element: any, event: string, fn: (event: any) => any): void; - - /** - * Get the values of all the CSS properties. - * @param {HTMLElement} element an HTMLElement. - * @returns {Object} - */ - css(element: any): any; - - /** - * Get the value of style properties. - * @param {HTMLElement} element an HTMLElement. - * @param {string} prop a property key. - * @returns {*} - */ - css(element: any, prop: string): any; - - /** - * Set one CSS property. - * @param {HTMLElement} element an HTMLElement. - * @param {string} prop a property key. - * @param {string} value a property value. - */ - css(element: any, prop: string, value: string): void; - - /** - * Set CSS properties. - * @param {HTMLElement} element an HTMLElement. - * @param {Object} props a properties object. - */ - css(element: any, props: any): void; - - /** - * Get elements by tag name. - * @param {HTMLElement} context an HTMLElement. - * @param {string} tagName A tag name. - * @param {function} [iterator] An iterator. - * @returns {HTMLElement[]} - */ - find(context: any, tagName: string, iterator?: (value: any) => any): any[]; - - /** - * Takes a function and returns a new one that will always have a particular context. - * @param {*} context an HTMLElement. - * @param {function} fn a function. - * @returns {function} - */ - bind(context: any, fn: () => any): () => any; - - /** - * Check the current matched set of elements against a selector. - * @param {HTMLElement} element an HTMLElement. - * @param {string} selector an element selector. - * @returns {boolean} - */ - is(element: any, selector: string): boolean; - - /** - * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * @param {HTMLElement} element an HTMLElement. - * @param {string} selector an element seletor. - * @param {HTMLElement} [context] a specific element's context. - * @returns {HTMLElement} - */ - closest(element: any, selector: string, context?: any): any; - - /** - * Add or remove one classes from each element - * @param {HTMLElement} element an HTMLElement. - * @param {string} name a class name. - * @param {boolean} state a class's state. - */ - toggleClass(element: any, name: string, state: boolean): void; - } - - class DOMRect { - public bottom: number; - public height: number; - public left: number; - public right: number; - public top: number; - public width: number; - public x: number; - public y: number; - } - - class Sortable { - public options: SortableOptions; - public el: any; - - /** - * Sortable's main constructor. - * @param {HTMLElement} element Any variety of HTMLElement. - * @param {SortableOptions} options Sortable options object. - */ - constructor(element: any, options: SortableOptions); - - static active: Sortable; - static utils: SortableUtils; - - /** - * Creation of new instances. - * @param {HTMLElement} element Any variety of HTMLElement. - * @param {SortableOptions} options Sortable options object. - * @returns {Sortable} - */ - static create(element: any, options: SortableOptions): Sortable; - - /** - * Options getter/setter - * @param {string} name a SortableOptions property. - * @param {*} [value] a Value. - * @returns {*} - */ - option(name: string, value: any): any; - option(name: string): any; - - /** - * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * @param {string|HTMLElement} element an HTMLElement or selector string. - * @returns {HTMLElement} - */ - closest(element: any): any; - - /** - * Sorts the elements according to the array. - * @param {string[]} order an array of strings to sort. - */ - sort(order: string[]): void; - - /** - * Saving and restoring of the sort. - */ - save(): void; - - /** - * Removes the sortable functionality completely. - */ - destroy(): void; - - /** - * Serializes the sortable's item data-id's (dataIdAttr option) into an array of string. - * @returns {string[]} - */ - toArray(): string[]; - } -} - -import Sortable = Sortablejs.Sortable; - -declare module 'Sortable' { - import Sortable = Sortablejs.Sortable; - export = Sortable; -} +// Type definitions for Sortable.js v1.3.0-rc1 +// Project: https://github.com/RubaXa/Sortable +// Definitions by: Maw-Fox +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Sortablejs { + interface SortableOptions { + group?: any; + sort?: boolean; + delay?: number; + disabled?: boolean; + store?: { + get: (sortable: Sortable) => any[]; + set: (sortable: Sortable) => any; + }; + animation?: number; + handle?: string; + filter?: any; + draggable?: string; + ghostClass?: string; + chosenClass?: string; + dataIdAttr?: string; + forceFallback?: boolean; + fallbackClass?: string; + fallbackOnBody?: boolean; + scroll?: boolean; + scrollSensitivity?: number; + scrollSpeed?: number; + setData?: (dataTransfer: any, draggedElement: any) => any; + onStart?: (event: any) => any; + onEnd?: (event: any) => any; + onAdd?: (event: any) => any; + onUpdate?: (event: any) => any; + onSort?: (event: any) => any; + onRemove?: (event: any) => any; + onFilter?: (event: any) => any; + onMove?: (event: any) => boolean; + } + + interface SortableUtils { + /** + * Attach an event handler function + * @param {HTMLElement} element an HTMLElement. + * @param {string} event an Event context. + * @param {Function} fn + */ + on(element: any, event: string, fn: (event: any) => any): void; + + /** + * Remove an event handler function + * @param {HTMLElement} element an HTMLElement. + * @param {string} event an Event context. + * @param {Function} fn a callback. + */ + off(element: any, event: string, fn: (event: any) => any): void; + + /** + * Get the values of all the CSS properties. + * @param {HTMLElement} element an HTMLElement. + * @returns {Object} + */ + css(element: any): any; + + /** + * Get the value of style properties. + * @param {HTMLElement} element an HTMLElement. + * @param {string} prop a property key. + * @returns {*} + */ + css(element: any, prop: string): any; + + /** + * Set one CSS property. + * @param {HTMLElement} element an HTMLElement. + * @param {string} prop a property key. + * @param {string} value a property value. + */ + css(element: any, prop: string, value: string): void; + + /** + * Set CSS properties. + * @param {HTMLElement} element an HTMLElement. + * @param {Object} props a properties object. + */ + css(element: any, props: any): void; + + /** + * Get elements by tag name. + * @param {HTMLElement} context an HTMLElement. + * @param {string} tagName A tag name. + * @param {function} [iterator] An iterator. + * @returns {HTMLElement[]} + */ + find(context: any, tagName: string, iterator?: (value: any) => any): any[]; + + /** + * Takes a function and returns a new one that will always have a particular context. + * @param {*} context an HTMLElement. + * @param {function} fn a function. + * @returns {function} + */ + bind(context: any, fn: () => any): () => any; + + /** + * Check the current matched set of elements against a selector. + * @param {HTMLElement} element an HTMLElement. + * @param {string} selector an element selector. + * @returns {boolean} + */ + is(element: any, selector: string): boolean; + + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * @param {HTMLElement} element an HTMLElement. + * @param {string} selector an element seletor. + * @param {HTMLElement} [context] a specific element's context. + * @returns {HTMLElement} + */ + closest(element: any, selector: string, context?: any): any; + + /** + * Add or remove one classes from each element + * @param {HTMLElement} element an HTMLElement. + * @param {string} name a class name. + * @param {boolean} state a class's state. + */ + toggleClass(element: any, name: string, state: boolean): void; + } + + class DOMRect { + public bottom: number; + public height: number; + public left: number; + public right: number; + public top: number; + public width: number; + public x: number; + public y: number; + } + + class Sortable { + public options: SortableOptions; + public el: any; + + /** + * Sortable's main constructor. + * @param {HTMLElement} element Any variety of HTMLElement. + * @param {SortableOptions} options Sortable options object. + */ + constructor(element: any, options: SortableOptions); + + static active: Sortable; + static utils: SortableUtils; + + /** + * Creation of new instances. + * @param {HTMLElement} element Any variety of HTMLElement. + * @param {SortableOptions} options Sortable options object. + * @returns {Sortable} + */ + static create(element: any, options: SortableOptions): Sortable; + + /** + * Options getter/setter + * @param {string} name a SortableOptions property. + * @param {*} [value] a Value. + * @returns {*} + */ + option(name: string, value: any): any; + option(name: string): any; + + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * @param {string|HTMLElement} element an HTMLElement or selector string. + * @returns {HTMLElement} + */ + closest(element: any): any; + + /** + * Sorts the elements according to the array. + * @param {string[]} order an array of strings to sort. + */ + sort(order: string[]): void; + + /** + * Saving and restoring of the sort. + */ + save(): void; + + /** + * Removes the sortable functionality completely. + */ + destroy(): void; + + /** + * Serializes the sortable's item data-id's (dataIdAttr option) into an array of string. + * @returns {string[]} + */ + toArray(): string[]; + } +} + +import Sortable = Sortablejs.Sortable; + +declare module 'Sortable' { + import Sortable = Sortablejs.Sortable; + export = Sortable; +} diff --git a/soundjs/soundjs.d.ts b/soundjs/soundjs.d.ts index 445006cab..37af7431e 100644 --- a/soundjs/soundjs.d.ts +++ b/soundjs/soundjs.d.ts @@ -1,147 +1,147 @@ -// Type definitions for SoundJS 0.6.0 -// Project: http://www.createjs.com/#!/SoundJS -// Definitions by: Pedro Ferreira -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/* - Copyright (c) 2012 Pedro Ferreira - 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. -*/ - -// Library documentation : http://www.createjs.com/Docs/SoundJS/modules/SoundJS.html - -/// -/// - -declare module createjs { - - export class AbstractPlugin - { - // methods - create(src: string, startTime: number, duration: number): AbstractSoundInstance; - getVolume(): number; - isPreloadComplete(src: string): boolean; - isPreloadStarted(src: string): boolean; - isSupported(): boolean; - preload(loader: Object): void; - register(loadItem: string, instances: number): Object; - removeAllSounds(src: string): void; - removeSound(src: string): void; - setMute(value: boolean): boolean; - setVolume(value: number): boolean; - } - - export class AbstractSoundInstance extends EventDispatcher - { - constructor(src: string, startTime: number, duration: number, playbackResource: Object); - - // properties - duration: number; - loop: number; - muted: boolean; - pan: number; - paused: boolean; - playbackResource: Object; - playState: string; - position: number; - src: string; - uniqueId: number | string; - volume: number; - - // methods - destroy(): void; - getDuration(): number; - getLoop(): number; - getMute(): boolean; - getPan(): number; - getPaused(): boolean; - getPosition(): number; - getVolume(): number; - play(interrupt?: string | Object, delay?: number, offset?: number, loop?: number, volume?: number, pan?: number): AbstractSoundInstance; - setDuration(value: number): AbstractSoundInstance; - setLoop(value: number): void; - setMute(value: boolean): AbstractSoundInstance; - setPan(value: number): AbstractSoundInstance; - setPlayback(value: Object): AbstractSoundInstance; - setPosition(value: number): AbstractSoundInstance; - setVolume(value: number): AbstractSoundInstance; - stop(): AbstractSoundInstance; - } - - export class FlashAudioLoader extends AbstractLoader - { - // properties - flashId: string; - - // methods - setFlash(flash: Object): void; - } - - export class FlashAudioPlugin extends AbstractPlugin - { - // properties - flashReady: boolean; - showOutput: boolean; - static swfPath: string; - - // methods - static isSupported(): boolean; - } - - export class FlashAudioSoundInstance extends AbstractSoundInstance - { - constructor(src: string, startTime: number, duration: number, playbackResource: Object); - } - - /** - * @deprecated - use FlashAudioPlugin - */ - export class FlashPlugin { - constructor(); - - // properties - static buildDate: string; - flashReady: boolean; - showOutput: boolean; - static swfPath: string; - static version: string; - - // methods - create(src: string): AbstractSoundInstance; - getVolume(): number; - isPreloadStarted(src: string): boolean; - static isSupported(): boolean; - preload(src: string, instance: Object): void; - register(src: string, instances: number): Object; - removeAllSounds (): void; - removeSound(src: string): void; - setMute(value: boolean): boolean; - setVolume(value: number): boolean; - } - - export class HTMLAudioPlugin extends AbstractPlugin - { - constructor(); - - // properties - defaultNumChannels: number; - enableIOS: boolean; // deprecated - static MAX_INSTANCES: number; - - // methods - static isSupported(): boolean; - } - - export class HTMLAudioSoundInstance extends AbstractSoundInstance - { - constructor(src: string, startTime: number, duration: number, playbackResource: Object); - } - - export class HTMLAudioTagPool - { - +// Type definitions for SoundJS 0.6.0 +// Project: http://www.createjs.com/#!/SoundJS +// Definitions by: Pedro Ferreira +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* + Copyright (c) 2012 Pedro Ferreira + 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. +*/ + +// Library documentation : http://www.createjs.com/Docs/SoundJS/modules/SoundJS.html + +/// +/// + +declare module createjs { + + export class AbstractPlugin + { + // methods + create(src: string, startTime: number, duration: number): AbstractSoundInstance; + getVolume(): number; + isPreloadComplete(src: string): boolean; + isPreloadStarted(src: string): boolean; + isSupported(): boolean; + preload(loader: Object): void; + register(loadItem: string, instances: number): Object; + removeAllSounds(src: string): void; + removeSound(src: string): void; + setMute(value: boolean): boolean; + setVolume(value: number): boolean; + } + + export class AbstractSoundInstance extends EventDispatcher + { + constructor(src: string, startTime: number, duration: number, playbackResource: Object); + + // properties + duration: number; + loop: number; + muted: boolean; + pan: number; + paused: boolean; + playbackResource: Object; + playState: string; + position: number; + src: string; + uniqueId: number | string; + volume: number; + + // methods + destroy(): void; + getDuration(): number; + getLoop(): number; + getMute(): boolean; + getPan(): number; + getPaused(): boolean; + getPosition(): number; + getVolume(): number; + play(interrupt?: string | Object, delay?: number, offset?: number, loop?: number, volume?: number, pan?: number): AbstractSoundInstance; + setDuration(value: number): AbstractSoundInstance; + setLoop(value: number): void; + setMute(value: boolean): AbstractSoundInstance; + setPan(value: number): AbstractSoundInstance; + setPlayback(value: Object): AbstractSoundInstance; + setPosition(value: number): AbstractSoundInstance; + setVolume(value: number): AbstractSoundInstance; + stop(): AbstractSoundInstance; + } + + export class FlashAudioLoader extends AbstractLoader + { + // properties + flashId: string; + + // methods + setFlash(flash: Object): void; + } + + export class FlashAudioPlugin extends AbstractPlugin + { + // properties + flashReady: boolean; + showOutput: boolean; + static swfPath: string; + + // methods + static isSupported(): boolean; + } + + export class FlashAudioSoundInstance extends AbstractSoundInstance + { + constructor(src: string, startTime: number, duration: number, playbackResource: Object); + } + + /** + * @deprecated - use FlashAudioPlugin + */ + export class FlashPlugin { + constructor(); + + // properties + static buildDate: string; + flashReady: boolean; + showOutput: boolean; + static swfPath: string; + static version: string; + + // methods + create(src: string): AbstractSoundInstance; + getVolume(): number; + isPreloadStarted(src: string): boolean; + static isSupported(): boolean; + preload(src: string, instance: Object): void; + register(src: string, instances: number): Object; + removeAllSounds (): void; + removeSound(src: string): void; + setMute(value: boolean): boolean; + setVolume(value: number): boolean; + } + + export class HTMLAudioPlugin extends AbstractPlugin + { + constructor(); + + // properties + defaultNumChannels: number; + enableIOS: boolean; // deprecated + static MAX_INSTANCES: number; + + // methods + static isSupported(): boolean; + } + + export class HTMLAudioSoundInstance extends AbstractSoundInstance + { + constructor(src: string, startTime: number, duration: number, playbackResource: Object); + } + + export class HTMLAudioTagPool + { + } export class PlayPropsConfig @@ -156,110 +156,110 @@ declare module createjs { volume:number; static create( value:PlayPropsConfig|any ): PlayPropsConfig; set ( props:any ): PlayPropsConfig; - } - - export class Sound extends EventDispatcher - { - // properties - static activePlugin: Object; - static alternateExtensions: any[]; - static defaultInterruptBehavior: string; - static EXTENSION_MAP: Object; - static INTERRUPT_ANY: string; - static INTERRUPT_EARLY: string; - static INTERRUPT_LATE: string; - static INTERRUPT_NONE: string; - static PLAY_FAILED: string; - static PLAY_FINISHED: string; - static PLAY_INITED: string; - static PLAY_INTERRUPTED: string; - static PLAY_SUCCEEDED: string; + } + + export class Sound extends EventDispatcher + { + // properties + static activePlugin: Object; + static alternateExtensions: any[]; + static defaultInterruptBehavior: string; + static EXTENSION_MAP: Object; + static INTERRUPT_ANY: string; + static INTERRUPT_EARLY: string; + static INTERRUPT_LATE: string; + static INTERRUPT_NONE: string; + static PLAY_FAILED: string; + static PLAY_FINISHED: string; + static PLAY_INITED: string; + static PLAY_INTERRUPTED: string; + static PLAY_SUCCEEDED: string; static SUPPORTED_EXTENSIONS: string[]; static muted: boolean; - static volume: number; - static capabilities: any; - - // methods - static createInstance(src: string): AbstractSoundInstance; - static getCapabilities(): Object; - static getCapability(key: string): number | boolean; - static getMute(): boolean; - static getVolume(): number; - static initializeDefaultPlugins(): boolean; - static isReady(): boolean; - static loadComplete(src: string): boolean; - static play(src: string, interrupt?: any, delay?: number, offset?: number, loop?: number, volume?: number, pan?: number): AbstractSoundInstance; - static registerManifest(manifest: Object[], basePath: string): Object; - static registerPlugins(plugins: any[]): boolean; - static registerSound(src: string | Object, id?: string, data?: number | Object, basePath?: string): Object; - static registerSounds(sounds: Object[], basePath?: string): Object[]; - static removeAllSounds(): void; - static removeManifest(manifest: any[], basePath: string): Object; - static removeSound(src: string | Object, basePath: string): boolean; - static setMute(value: boolean): boolean; - static setVolume(value: number): void; - static stop(): void; - - // EventDispatcher mixins - static addEventListener(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): Function; - static addEventListener(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): Function; - static addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): Object; - static addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): Object; - static dispatchEvent(eventObj: Object | string | Event, target?: Object): boolean; - static hasEventListener(type: string): boolean; - static off(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): void; - static off(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): void; - static off(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): void; - static off(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): void; - static off(type: string, listener: Function, useCapture?: boolean): void; // It is necessary for "arguments.callee" - static on(type: string, listener: (eventObj: Object) => boolean, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Function; - static on(type: string, listener: (eventObj: Object) => void, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Function; - static on(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Object; - static on(type: string, listener: { handleEvent: (eventObj: Object) => void; }, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Object; - static removeAllEventListeners(type?: string): void; - static removeEventListener(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): void; - static removeEventListener(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): void; - static removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): void; - static removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): void; - static removeEventListener(type: string, listener: Function, useCapture?: boolean): void; // It is necessary for "arguments.callee" - static toString(): string; - static willTrigger(type: string): boolean; - } - - export class SoundJS { - static buildDate: string; - static version: string; - } - - export class WebAudioLoader - { - static context: AudioContext; - } - - export class WebAudioPlugin extends AbstractPlugin - { - constructor(); - - // properties - static context: AudioContext; - context: AudioContext; - dynamicsCompressorNode: DynamicsCompressorNode; - gainNode: GainNode; - - // methods - static isSupported(): boolean; - static playEmptySound(): void; - } - - export class WebAudioSoundInstance extends AbstractSoundInstance - { - constructor(src: string, startTime: number, duration: number, playbackResource: Object); - - // properties - static context: AudioContext; - static destinationNode: AudioNode; - gainNode: GainNode; - panNode: PannerNode; - sourceNode: AudioNode; - } -} + static volume: number; + static capabilities: any; + + // methods + static createInstance(src: string): AbstractSoundInstance; + static getCapabilities(): Object; + static getCapability(key: string): number | boolean; + static getMute(): boolean; + static getVolume(): number; + static initializeDefaultPlugins(): boolean; + static isReady(): boolean; + static loadComplete(src: string): boolean; + static play(src: string, interrupt?: any, delay?: number, offset?: number, loop?: number, volume?: number, pan?: number): AbstractSoundInstance; + static registerManifest(manifest: Object[], basePath: string): Object; + static registerPlugins(plugins: any[]): boolean; + static registerSound(src: string | Object, id?: string, data?: number | Object, basePath?: string): Object; + static registerSounds(sounds: Object[], basePath?: string): Object[]; + static removeAllSounds(): void; + static removeManifest(manifest: any[], basePath: string): Object; + static removeSound(src: string | Object, basePath: string): boolean; + static setMute(value: boolean): boolean; + static setVolume(value: number): void; + static stop(): void; + + // EventDispatcher mixins + static addEventListener(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): Function; + static addEventListener(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): Function; + static addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): Object; + static addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): Object; + static dispatchEvent(eventObj: Object | string | Event, target?: Object): boolean; + static hasEventListener(type: string): boolean; + static off(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): void; + static off(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): void; + static off(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): void; + static off(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): void; + static off(type: string, listener: Function, useCapture?: boolean): void; // It is necessary for "arguments.callee" + static on(type: string, listener: (eventObj: Object) => boolean, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Function; + static on(type: string, listener: (eventObj: Object) => void, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Function; + static on(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Object; + static on(type: string, listener: { handleEvent: (eventObj: Object) => void; }, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Object; + static removeAllEventListeners(type?: string): void; + static removeEventListener(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): void; + static removeEventListener(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): void; + static removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): void; + static removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): void; + static removeEventListener(type: string, listener: Function, useCapture?: boolean): void; // It is necessary for "arguments.callee" + static toString(): string; + static willTrigger(type: string): boolean; + } + + export class SoundJS { + static buildDate: string; + static version: string; + } + + export class WebAudioLoader + { + static context: AudioContext; + } + + export class WebAudioPlugin extends AbstractPlugin + { + constructor(); + + // properties + static context: AudioContext; + context: AudioContext; + dynamicsCompressorNode: DynamicsCompressorNode; + gainNode: GainNode; + + // methods + static isSupported(): boolean; + static playEmptySound(): void; + } + + export class WebAudioSoundInstance extends AbstractSoundInstance + { + constructor(src: string, startTime: number, duration: number, playbackResource: Object); + + // properties + static context: AudioContext; + static destinationNode: AudioNode; + gainNode: GainNode; + panNode: PannerNode; + sourceNode: AudioNode; + } +} diff --git a/spin/spin-tests.ts b/spin/spin-tests.ts index 4751b2076..1816b784b 100644 --- a/spin/spin-tests.ts +++ b/spin/spin-tests.ts @@ -1,34 +1,34 @@ -/// - -var spinner = new Spinner().spin(); -target.appendChild(spinner.el); - -var target = document.getElementById('foo'); -var opts = { speed: 5, color: '#abcdef' }; -var spinner2 = new Spinner(opts).spin(target); - -var opts2 = { - lines: 10, - length: 20, - width: 7, - radius: 14, - corners: 0.6, - rotate: 0, - direction: 1, - color: ['#aaa', '#fedcba', '#fff', '#aef02b'], - speed: 1.5, - trail: 50, - shadow: true, - hwaccel: true, - className: 'spinner', - zIndex: 5, - top: '28', - left: 'auto', - scale: 1, - opacity: 0.25, - fps: 20, - position: 'absolute' -}; - -var newTarget = document.getElementById('bar'); -var spinner3 = new Spinner(opts2).spin(newTarget); +/// + +var spinner = new Spinner().spin(); +target.appendChild(spinner.el); + +var target = document.getElementById('foo'); +var opts = { speed: 5, color: '#abcdef' }; +var spinner2 = new Spinner(opts).spin(target); + +var opts2 = { + lines: 10, + length: 20, + width: 7, + radius: 14, + corners: 0.6, + rotate: 0, + direction: 1, + color: ['#aaa', '#fedcba', '#fff', '#aef02b'], + speed: 1.5, + trail: 50, + shadow: true, + hwaccel: true, + className: 'spinner', + zIndex: 5, + top: '28', + left: 'auto', + scale: 1, + opacity: 0.25, + fps: 20, + position: 'absolute' +}; + +var newTarget = document.getElementById('bar'); +var spinner3 = new Spinner(opts2).spin(newTarget); diff --git a/spin/spin.d.ts b/spin/spin.d.ts index 9924aa2c1..4fcfb6b68 100644 --- a/spin/spin.d.ts +++ b/spin/spin.d.ts @@ -1,50 +1,50 @@ -// Type definitions for Spin.js 2.3.2 -// Project: http://fgnass.github.com/spin.js/ -// Definitions by: Boris Yankov , Theodore Brown -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -interface SpinnerOptions { - lines?: number; // The number of lines to draw - length?: number; // The length of each line - width?: number; // The line thickness - radius?: number; // The radius of the inner circle - corners?: number; // Corner roundness (0..1) - rotate?: number; // The rotation offset - direction?: number; // 1: clockwise, -1: counterclockwise - color?: any; // #rgb or #rrggbb or array of colors - speed?: number; // Rounds per second - trail?: number; // Afterglow percentage - shadow?: boolean; // Whether to render a shadow - hwaccel?: boolean; // Whether to use hardware acceleration - className?: string; // The CSS class to assign to the spinner - zIndex?: number; // The z-index (defaults to 2000000000) - top?: string; // Top position relative to parent in px - left?: string; // Left position relative to parent in px - scale?: number; // Scales overall size of the spinner - opacity?: number; // Opacity of the lines - fps?: number; // Frames per second when using setTimeout() as a fallback for CSS - position?: string; // Element positioning -} - - -declare class Spinner { - /** The Spinner's HTML element - can be used to manually insert the spinner into the DOM */ - public el: HTMLElement; - constructor(options?: SpinnerOptions); - - /** - * Adds the spinner to the given target element. If this instance is already - * spinning, it is automatically removed from its previous target by calling - * stop() internally. - */ - spin(target?: HTMLElement): Spinner; - - /** - * Stops and removes the Spinner. - * Stopped spinners may be reused by calling spin() again. - */ - stop(): Spinner; - lines(el:HTMLElement, o:SpinnerOptions):HTMLElement; - opacity(el:HTMLElement, i:number, val:number, o:SpinnerOptions):void; -} +// Type definitions for Spin.js 2.3.2 +// Project: http://fgnass.github.com/spin.js/ +// Definitions by: Boris Yankov , Theodore Brown +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +interface SpinnerOptions { + lines?: number; // The number of lines to draw + length?: number; // The length of each line + width?: number; // The line thickness + radius?: number; // The radius of the inner circle + corners?: number; // Corner roundness (0..1) + rotate?: number; // The rotation offset + direction?: number; // 1: clockwise, -1: counterclockwise + color?: any; // #rgb or #rrggbb or array of colors + speed?: number; // Rounds per second + trail?: number; // Afterglow percentage + shadow?: boolean; // Whether to render a shadow + hwaccel?: boolean; // Whether to use hardware acceleration + className?: string; // The CSS class to assign to the spinner + zIndex?: number; // The z-index (defaults to 2000000000) + top?: string; // Top position relative to parent in px + left?: string; // Left position relative to parent in px + scale?: number; // Scales overall size of the spinner + opacity?: number; // Opacity of the lines + fps?: number; // Frames per second when using setTimeout() as a fallback for CSS + position?: string; // Element positioning +} + + +declare class Spinner { + /** The Spinner's HTML element - can be used to manually insert the spinner into the DOM */ + public el: HTMLElement; + constructor(options?: SpinnerOptions); + + /** + * Adds the spinner to the given target element. If this instance is already + * spinning, it is automatically removed from its previous target by calling + * stop() internally. + */ + spin(target?: HTMLElement): Spinner; + + /** + * Stops and removes the Spinner. + * Stopped spinners may be reused by calling spin() again. + */ + stop(): Spinner; + lines(el:HTMLElement, o:SpinnerOptions):HTMLElement; + opacity(el:HTMLElement, i:number, val:number, o:SpinnerOptions):void; +} diff --git a/stack-mapper/stack-mapper-tests.ts b/stack-mapper/stack-mapper-tests.ts index 98dd70ef1..734b7ab3c 100644 --- a/stack-mapper/stack-mapper-tests.ts +++ b/stack-mapper/stack-mapper-tests.ts @@ -1,8 +1,8 @@ -/// - -import stackMapper = require("stack-mapper"); - -var map: any = {}; -var sm: stackMapper.StackMapper = stackMapper(map); -var input: stackMapper.Callsite[] = [{ filename: "boo", line: 1, column: 10 }]; -var cs: stackMapper.Callsite[] = sm.map(input); +/// + +import stackMapper = require("stack-mapper"); + +var map: any = {}; +var sm: stackMapper.StackMapper = stackMapper(map); +var input: stackMapper.Callsite[] = [{ filename: "boo", line: 1, column: 10 }]; +var cs: stackMapper.Callsite[] = sm.map(input); diff --git a/stack-mapper/stack-mapper.d.ts b/stack-mapper/stack-mapper.d.ts index 3426f5b9d..ed0afdf7f 100644 --- a/stack-mapper/stack-mapper.d.ts +++ b/stack-mapper/stack-mapper.d.ts @@ -1,46 +1,46 @@ -// Type definitions for stack-mapper 0.2.2 -// Project: https://github.com/thlorenz/stack-mapper -// Definitions by: Rogier Schouten -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module "stack-mapper" { - - module stackMapper { - - export class StackMapper { - - /** - * Maps the trace statements of the given error stack and replaces locations - * referencing code in the generated file with the locations inside the original files. - * - * @name map - * @function - * @param {Array} array of callsite objects (see readme for details about Callsite object) - * @return {Array.} info about the error stack with adapted locations, each with the following properties - * - filename: original filename - * - line: origial line in that filename of the trace - * - column: origial column on that line of the trace - */ - public map(stack: Callsite[]): Callsite[]; - } - - export interface Callsite { - filename: string; - line: number; - column: number; - } - - } - - /** - * Returns a Stackmapper that will use the given source map to map error trace locations. - * - * @name stackMapper - * @function - * @param {Object} sourcemap source map for the generated file - * @return {StackMapper} stack mapper for the particular source map - */ - function stackMapper(sourcemap: any): stackMapper.StackMapper; - - export = stackMapper; -} +// Type definitions for stack-mapper 0.2.2 +// Project: https://github.com/thlorenz/stack-mapper +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "stack-mapper" { + + module stackMapper { + + export class StackMapper { + + /** + * Maps the trace statements of the given error stack and replaces locations + * referencing code in the generated file with the locations inside the original files. + * + * @name map + * @function + * @param {Array} array of callsite objects (see readme for details about Callsite object) + * @return {Array.} info about the error stack with adapted locations, each with the following properties + * - filename: original filename + * - line: origial line in that filename of the trace + * - column: origial column on that line of the trace + */ + public map(stack: Callsite[]): Callsite[]; + } + + export interface Callsite { + filename: string; + line: number; + column: number; + } + + } + + /** + * Returns a Stackmapper that will use the given source map to map error trace locations. + * + * @name stackMapper + * @function + * @param {Object} sourcemap source map for the generated file + * @return {StackMapper} stack mapper for the particular source map + */ + function stackMapper(sourcemap: any): stackMapper.StackMapper; + + export = stackMapper; +} diff --git a/state-machine/state-machine-tests.ts b/state-machine/state-machine-tests.ts index 24321fc60..7c7c705e3 100644 --- a/state-machine/state-machine-tests.ts +++ b/state-machine/state-machine-tests.ts @@ -1,30 +1,30 @@ -/// - -interface StateMachineTest extends StateMachine { - warn?: StateMachineEvent; - panic?: StateMachineEvent; - calm?: StateMachineEvent; - clear?: StateMachineEvent; -} - -var fsm: StateMachineTest = StateMachine.create({ - initial: 'green', - events: [ - { name: 'warn', from: 'green', to: 'yellow' }, - { name: 'panic', from: 'yellow', to: 'red' }, - { name: 'calm', from: 'red', to: 'yellow' }, - { name: 'clear', from: 'yellow', to: 'green' } - ], - callbacks: { - onpanic: function (event?, from?, to?, msg?) { alert('panic! ' + msg); }, - onclear: function (event?, from?, to?, msg?) { alert('thanks to ' + msg); }, - ongreen: function (event?, from?, to?) { document.body.className = 'green'; }, - onyellow: function (event?, from?, to?) { document.body.className = 'yellow'; }, - onred: function (event?, from?, to?) { document.body.className = 'red'; }, - } -}); - -//fsm.warn(); // transition from green to yellow -//fsm.panic("ERROR ALERT"); // transition from yellow to red -//fsm.calm(); // transition from red to yellow -//fsm.clear("All clear"); // transition from yellow to green +/// + +interface StateMachineTest extends StateMachine { + warn?: StateMachineEvent; + panic?: StateMachineEvent; + calm?: StateMachineEvent; + clear?: StateMachineEvent; +} + +var fsm: StateMachineTest = StateMachine.create({ + initial: 'green', + events: [ + { name: 'warn', from: 'green', to: 'yellow' }, + { name: 'panic', from: 'yellow', to: 'red' }, + { name: 'calm', from: 'red', to: 'yellow' }, + { name: 'clear', from: 'yellow', to: 'green' } + ], + callbacks: { + onpanic: function (event?, from?, to?, msg?) { alert('panic! ' + msg); }, + onclear: function (event?, from?, to?, msg?) { alert('thanks to ' + msg); }, + ongreen: function (event?, from?, to?) { document.body.className = 'green'; }, + onyellow: function (event?, from?, to?) { document.body.className = 'yellow'; }, + onred: function (event?, from?, to?) { document.body.className = 'red'; }, + } +}); + +//fsm.warn(); // transition from green to yellow +//fsm.panic("ERROR ALERT"); // transition from yellow to red +//fsm.calm(); // transition from red to yellow +//fsm.clear("All clear"); // transition from yellow to green diff --git a/state-machine/state-machine.d.ts b/state-machine/state-machine.d.ts index d17c58dc6..2253cdeec 100644 --- a/state-machine/state-machine.d.ts +++ b/state-machine/state-machine.d.ts @@ -1,83 +1,83 @@ -// Type definitions for Finite State Machine 2.2 -// Project: https://github.com/jakesgordon/javascript-state-machine -// Definitions by: Boris Yankov , Maarten Docter , William Sears -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -interface StateMachineErrorCallback { - (eventName?: string, from?: string, to?: string, args?: any[], errorCode?: number, errorMessage?: string, ex?: Error): void; // NB. errorCode? See: StateMachine.Error -} - -interface StateMachineEventDef { - name: string; - from: any; // string or string[] - to: string; -} - -interface StateMachineEvent { - (...args: any[]): void; -} - -interface StateMachineConfig { - initial?: any; // string or { state: 'foo', event: 'setup', defer: true|false } - events?: StateMachineEventDef[]; - callbacks?: { - [s: string]: (event?: string, from?: string, to?: string, ...args: any[]) => any; - }; - target?: StateMachine; - error?: StateMachineErrorCallback; -} - -interface StateMachineStatic { - - VERSION: string; // = "2.2.0" - WILDCARD: string; // = '*' - ASYNC: string; // = 'async' - - Result: { - SUCCEEDED: number; // = 1, the event transitioned successfully from one state to another - NOTRANSITION: number; // = 2, the event was successfull but no state transition was necessary - CANCELLED: number; // = 3, the event was cancelled by the caller in a beforeEvent callback - ASYNC: number; // = 4, the event is asynchronous and the caller is in control of when the transition occurs - }; - - Error: { - INVALID_TRANSITION: number; // = 100, caller tried to fire an event that was innapropriate in the current state - PENDING_TRANSITION: number; // = 200, caller tried to fire an event while an async transition was still pending - INVALID_CALLBACK: number; // = 300, caller provided callback function threw an exception - }; - - create(config: StateMachineConfig, target?: StateMachine): StateMachine; -} - -interface StateMachineTransition { - (): void; - cancel(): void; -} - -interface StateMachineIs { - (state: string): boolean; -} - -interface StateMachineCan { - (evt: string): boolean; -} - -interface StateMachine { - current: string; - is: StateMachineIs; - can: StateMachineCan; - cannot: StateMachineCan; - error: StateMachineErrorCallback; - - /* transition - only available when performing async state transitions; otherwise null. Can be a: - [1] fsm.transition(); // called from async callback - [2] fsm.transition.cancel(); - */ - transition: StateMachineTransition; -} - -declare var StateMachine: StateMachineStatic; - -declare module "state-machine" { - export = StateMachine; -} +// Type definitions for Finite State Machine 2.2 +// Project: https://github.com/jakesgordon/javascript-state-machine +// Definitions by: Boris Yankov , Maarten Docter , William Sears +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface StateMachineErrorCallback { + (eventName?: string, from?: string, to?: string, args?: any[], errorCode?: number, errorMessage?: string, ex?: Error): void; // NB. errorCode? See: StateMachine.Error +} + +interface StateMachineEventDef { + name: string; + from: any; // string or string[] + to: string; +} + +interface StateMachineEvent { + (...args: any[]): void; +} + +interface StateMachineConfig { + initial?: any; // string or { state: 'foo', event: 'setup', defer: true|false } + events?: StateMachineEventDef[]; + callbacks?: { + [s: string]: (event?: string, from?: string, to?: string, ...args: any[]) => any; + }; + target?: StateMachine; + error?: StateMachineErrorCallback; +} + +interface StateMachineStatic { + + VERSION: string; // = "2.2.0" + WILDCARD: string; // = '*' + ASYNC: string; // = 'async' + + Result: { + SUCCEEDED: number; // = 1, the event transitioned successfully from one state to another + NOTRANSITION: number; // = 2, the event was successfull but no state transition was necessary + CANCELLED: number; // = 3, the event was cancelled by the caller in a beforeEvent callback + ASYNC: number; // = 4, the event is asynchronous and the caller is in control of when the transition occurs + }; + + Error: { + INVALID_TRANSITION: number; // = 100, caller tried to fire an event that was innapropriate in the current state + PENDING_TRANSITION: number; // = 200, caller tried to fire an event while an async transition was still pending + INVALID_CALLBACK: number; // = 300, caller provided callback function threw an exception + }; + + create(config: StateMachineConfig, target?: StateMachine): StateMachine; +} + +interface StateMachineTransition { + (): void; + cancel(): void; +} + +interface StateMachineIs { + (state: string): boolean; +} + +interface StateMachineCan { + (evt: string): boolean; +} + +interface StateMachine { + current: string; + is: StateMachineIs; + can: StateMachineCan; + cannot: StateMachineCan; + error: StateMachineErrorCallback; + + /* transition - only available when performing async state transitions; otherwise null. Can be a: + [1] fsm.transition(); // called from async callback + [2] fsm.transition.cancel(); + */ + transition: StateMachineTransition; +} + +declare var StateMachine: StateMachineStatic; + +declare module "state-machine" { + export = StateMachine; +} diff --git a/statsd-client/statsd-client-tests.ts b/statsd-client/statsd-client-tests.ts index 6854790e6..2dc6f0144 100644 --- a/statsd-client/statsd-client-tests.ts +++ b/statsd-client/statsd-client-tests.ts @@ -1,57 +1,57 @@ -/// - -import SDC = require("statsd-client"); - -var sdc = new SDC( { host: 'statsd.example.com' }); - -var timer = new Date(); -sdc.increment('some.counter'); // Increment by one. -sdc.gauge('some.gauge', 10); // Set gauge to 10 -sdc.timing('some.timer', timer); // Calculates time diff - -sdc.close(); // Optional - stop NOW - -// Initialization -sdc = new SDC({host: 'statsd.example.com', port: 8124, debug: true}); - -// Counting stuff -sdc.increment('systemname.subsystem.value'); // Increment by one -sdc.decrement('systemname.subsystem.value', -10); // Decrement by 10 -sdc.counter('systemname.subsystem.value', 100); // Increment by 100 - -// Gauges -sdc.gauge('what.you.gauge', 100); -sdc.gaugeDelta('what.you.gauge', 20); // Will now count 120 -sdc.gaugeDelta('what.you.gauge', -70); // Will now count 50 -sdc.gauge('what.you.gauge', 10); // Will now count 10 - -// Set -sdc.set('your.set', 200); - -// Timeouts -var start = new Date(); -setTimeout(function () { - sdc.timing('random.timeout', start); -}, 100 * Math.random()); - -// Stopping gracefully -var start = new Date(); -setTimeout(function () { - sdc.timing('random.timeout', start); // 2 - implicitly re-creates socket. - sdc.close(); // 3 - Closes socket after last use. -}, 100 * Math.random()); -sdc.close(); // 1 - Closes socket early. - -// Prefix magic -// Create generic client -var sdc = new SDC({host: 'statsd.example.com', prefix: 'systemname'}); -sdc.increment('foo'); // Increments 'systemname.foo' -// ... do great stuff ... - -// Subsystem A -var sdcA = sdc.getChildClient('a'); -sdcA.increment('foo'); // Increments 'systemname.a.foo' - -// Subsystem B -var sdcB = sdc.getChildClient('b'); -sdcB.increment('foo'); // Increments 'systemname.b.foo' +/// + +import SDC = require("statsd-client"); + +var sdc = new SDC( { host: 'statsd.example.com' }); + +var timer = new Date(); +sdc.increment('some.counter'); // Increment by one. +sdc.gauge('some.gauge', 10); // Set gauge to 10 +sdc.timing('some.timer', timer); // Calculates time diff + +sdc.close(); // Optional - stop NOW + +// Initialization +sdc = new SDC({host: 'statsd.example.com', port: 8124, debug: true}); + +// Counting stuff +sdc.increment('systemname.subsystem.value'); // Increment by one +sdc.decrement('systemname.subsystem.value', -10); // Decrement by 10 +sdc.counter('systemname.subsystem.value', 100); // Increment by 100 + +// Gauges +sdc.gauge('what.you.gauge', 100); +sdc.gaugeDelta('what.you.gauge', 20); // Will now count 120 +sdc.gaugeDelta('what.you.gauge', -70); // Will now count 50 +sdc.gauge('what.you.gauge', 10); // Will now count 10 + +// Set +sdc.set('your.set', 200); + +// Timeouts +var start = new Date(); +setTimeout(function () { + sdc.timing('random.timeout', start); +}, 100 * Math.random()); + +// Stopping gracefully +var start = new Date(); +setTimeout(function () { + sdc.timing('random.timeout', start); // 2 - implicitly re-creates socket. + sdc.close(); // 3 - Closes socket after last use. +}, 100 * Math.random()); +sdc.close(); // 1 - Closes socket early. + +// Prefix magic +// Create generic client +var sdc = new SDC({host: 'statsd.example.com', prefix: 'systemname'}); +sdc.increment('foo'); // Increments 'systemname.foo' +// ... do great stuff ... + +// Subsystem A +var sdcA = sdc.getChildClient('a'); +sdcA.increment('foo'); // Increments 'systemname.a.foo' + +// Subsystem B +var sdcB = sdc.getChildClient('b'); +sdcB.increment('foo'); // Increments 'systemname.b.foo' diff --git a/statsd-client/statsd-client.d.ts b/statsd-client/statsd-client.d.ts index 86e317afa..08649fe08 100644 --- a/statsd-client/statsd-client.d.ts +++ b/statsd-client/statsd-client.d.ts @@ -1,103 +1,103 @@ -// Type definitions for statsd-client v0.1.0 -// Project: https://github.com/msiebuhr/node-statsd-client -// Definitions by: Peter Kooijmans -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module "statsd-client" { - - interface CommonOptions { - /** - * Prefix all stats with this value (default ""). - */ - prefix?: string; - - /** - * Print what is being sent to stderr (default false). - */ - debug?: boolean; - - /** - * User specifically wants to use tcp (default false) - */ - tcp?: boolean; - - /** - * Dual-use timer. Will flush metrics every interval. For UDP, - * it auto-closes the socket after this long without activity - * (default 1000 ms; 0 disables this). For TCP, it auto-closes - * the socket after socketTimeoutsToClose number of timeouts - * have elapsed without activity. - */ - socketTimeout?: number; - } - - interface TcpOptions extends CommonOptions { - /** - * Where to send the stats (default localhost). - */ - host?: string; - - /** - * Port to contact the statsd-daemon on (default 8125). - */ - port?: number; - - /** - * Number of timeouts in which the socket auto-closes if it - * has been inactive. (default 10; 1 to auto-close after a - * single timeout). - */ - socketTimeoutsToClose: number; - } - - interface UdpOptions extends CommonOptions { - /** - * Where to send the stats (default localhost). - */ - host?: string; - - /** - * Port to contact the statsd-daemon on (default 8125). - */ - port?: number; - } - - interface HttpOptions extends CommonOptions { - /** - * Where to send the stats (default localhost). - */ - host?: string; - - /** - * Additional headers to send (default {}). - */ - headers?: { [index : string] : string }; - - /** - * What HTTP method to use (default "PUT"). - */ - method?: string; - } - - class StatsdClient { - constructor(options: TcpOptions | UdpOptions | HttpOptions); - - counter(metric: string, delta: number): void; - increment(metric: string, delta?: number): void; - decrement(metric: string, delta?: number): void; - - gauge(name: string, value: number): void; - gaugeDelta(name: string, delta: number): void; - - set(name: string, value: number): void; - - timing(name: string, start: Date): void; - timing(name: string, duration: number): void; - - close(): void; - - getChildClient(name: string): StatsdClient; - } - - export = StatsdClient; -} +// Type definitions for statsd-client v0.1.0 +// Project: https://github.com/msiebuhr/node-statsd-client +// Definitions by: Peter Kooijmans +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "statsd-client" { + + interface CommonOptions { + /** + * Prefix all stats with this value (default ""). + */ + prefix?: string; + + /** + * Print what is being sent to stderr (default false). + */ + debug?: boolean; + + /** + * User specifically wants to use tcp (default false) + */ + tcp?: boolean; + + /** + * Dual-use timer. Will flush metrics every interval. For UDP, + * it auto-closes the socket after this long without activity + * (default 1000 ms; 0 disables this). For TCP, it auto-closes + * the socket after socketTimeoutsToClose number of timeouts + * have elapsed without activity. + */ + socketTimeout?: number; + } + + interface TcpOptions extends CommonOptions { + /** + * Where to send the stats (default localhost). + */ + host?: string; + + /** + * Port to contact the statsd-daemon on (default 8125). + */ + port?: number; + + /** + * Number of timeouts in which the socket auto-closes if it + * has been inactive. (default 10; 1 to auto-close after a + * single timeout). + */ + socketTimeoutsToClose: number; + } + + interface UdpOptions extends CommonOptions { + /** + * Where to send the stats (default localhost). + */ + host?: string; + + /** + * Port to contact the statsd-daemon on (default 8125). + */ + port?: number; + } + + interface HttpOptions extends CommonOptions { + /** + * Where to send the stats (default localhost). + */ + host?: string; + + /** + * Additional headers to send (default {}). + */ + headers?: { [index : string] : string }; + + /** + * What HTTP method to use (default "PUT"). + */ + method?: string; + } + + class StatsdClient { + constructor(options: TcpOptions | UdpOptions | HttpOptions); + + counter(metric: string, delta: number): void; + increment(metric: string, delta?: number): void; + decrement(metric: string, delta?: number): void; + + gauge(name: string, value: number): void; + gaugeDelta(name: string, delta: number): void; + + set(name: string, value: number): void; + + timing(name: string, start: Date): void; + timing(name: string, duration: number): void; + + close(): void; + + getChildClient(name: string): StatsdClient; + } + + export = StatsdClient; +} diff --git a/swap-case/swap-case.d.ts b/swap-case/swap-case.d.ts index a45aaf650..46e34cfd4 100644 --- a/swap-case/swap-case.d.ts +++ b/swap-case/swap-case.d.ts @@ -1,9 +1,9 @@ -// Type definitions for swap-case -// Project: https://github.com/blakeembrey/swap-case -// Definitions by: Sam Saint-Pettersen -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module "swap-case" { - function swapCase(string: string, locale?: string): string; - export = swapCase; -} +// Type definitions for swap-case +// Project: https://github.com/blakeembrey/swap-case +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "swap-case" { + function swapCase(string: string, locale?: string): string; + export = swapCase; +} diff --git a/swiper/swiper-tests.ts.tscparams b/swiper/swiper-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/swiper/swiper-tests.ts.tscparams +++ b/swiper/swiper-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/swiper/swiper.d.ts.tscparams b/swiper/swiper.d.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/swiper/swiper.d.ts.tscparams +++ b/swiper/swiper.d.ts.tscparams @@ -1 +1 @@ - + diff --git a/swipeview/swipeview-tests.ts b/swipeview/swipeview-tests.ts index 02564e11b..e9781133f 100644 --- a/swipeview/swipeview-tests.ts +++ b/swipeview/swipeview-tests.ts @@ -1,252 +1,252 @@ -/// - -function demo1() { - document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false); - -var - el, - i, - page, - dots = document.querySelectorAll('#nav li'), - slides = [ - { - img: 'images/pic01.jpg', - width: 300, - height: 213, - desc: 'Piazza del Duomo, Florence, Italy' - }, - { - img: 'images/pic02.jpg', - width: 300, - height: 164, - desc: 'Tuscan Landscape' - } - ]; - - var gallery = new SwipeView('#wrapper', { numberOfPages: slides.length }); - - // Load initial data - for (i = 0; i < 3; i++) { - page = i == 0 ? slides.length - 1 : i - 1; - el = document.createElement('img'); - el.className = 'loading'; - el.src = slides[page].img; - el.width = slides[page].width; - el.height = slides[page].height; - el.onload = function () { this.className = ''; } - gallery.masterPages[i].appendChild(el); - - el = document.createElement('span'); - el.innerHTML = slides[page].desc; - gallery.masterPages[i].appendChild(el) - } - - gallery.onFlip(function () { - var el, - upcoming, - i; - - for (i = 0; i < 3; i++) { - upcoming = (gallery.masterPages[i].dataset).upcomingPageIndex; - - if (upcoming != (gallery.masterPages[i].dataset).pageIndex) { - el = gallery.masterPages[i].querySelector('img'); - el.className = 'loading'; - el.src = slides[upcoming].img; - el.width = slides[upcoming].width; - el.height = slides[upcoming].height; - - el = gallery.masterPages[i].querySelector('span'); - el.innerHTML = slides[upcoming].desc; - } - } - }); - - gallery.onMoveOut(function () { - gallery.masterPages[gallery.currentMasterPage].className = gallery.masterPages[gallery.currentMasterPage].className.replace(/(^|\s)swipeview-active(\s|$)/, ''); - }); - - gallery.onMoveIn(function () { - var className = gallery.masterPages[gallery.currentMasterPage].className; - /(^|\s)swipeview-active(\s|$)/.test(className) || (gallery.masterPages[gallery.currentMasterPage].className = !className ? 'swipeview-active' : className + ' swipeview-active'); - }); -} - -function demo2() { -var carousel: SwipeView, - el, - i, - page, - slides = [ - 'Swipe to know more >>>
    Or scroll down for Lorem Ipsum', - '1. A robot may not injure a human being or, through inaction, allow a human being to come to harm.', - '2. A robot must obey the orders given to it by human beings, except where such orders would conflict with the First Law.', - '3. A robot must protect its own existence as long as such protection does not conflict with the First or Second Laws.' - ]; - - carousel = new SwipeView('#wrapper', { - numberOfPages: slides.length, - hastyPageFlip: true - }); - - // Load initial data - for (i = 0; i < 3; i++) { - page = i == 0 ? slides.length - 1 : i - 1; - - el = document.createElement('span'); - el.innerHTML = slides[page]; - carousel.masterPages[i].appendChild(el) - } - - carousel.onFlip(function () { - var el, - upcoming, - i; - - for (i = 0; i < 3; i++) { - upcoming = (carousel.masterPages[i].dataset).upcomingPageIndex; - - if (upcoming != (carousel.masterPages[i].dataset).pageIndex) { - el = carousel.masterPages[i].querySelector('span'); - el.innerHTML = slides[upcoming]; - } - } - }); -} - -function demo3() { - document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false); - - window.addEventListener('load', function () { - var ereader: SwipeView, - el, - i, - pageIndex, - pages = [], - req = new XMLHttpRequest(); - - ereader = new SwipeView('#wrapper', { hastyPageFlip: true }); - - // Ajax request - req.open('GET', 'flowers.txt', true); - req.onreadystatechange = function () { - if (req.readyState != 4) return; - - paginate(req.status != 200 && (req.status != 304 ? false : req.responseText)); - - req = null; - } - req.send(null); - - function paginate(book) { - var that = this, - container, - helper, - words = [], - segment, - wordCount = 80, - avgWordCount = 0, - progressTotal = 0, - progressCurrent = 0, - progressMaxWidth = document.getElementById('progressbar').clientWidth, - progressToBookRatio = 0, - progressBar = document.querySelector('#progressbar > span'), - size; - - if (!book) return; - - book = book.replace(/\n\n/g, '

    ').replace(/\n/g, ' '); - progressTotal = book.length; - progressToBookRatio = progressMaxWidth / book.length; - - container = document.createElement('div'); - container.style.visibility = 'hidden'; - container.innerHTML = '
    '; - ereader.slider.appendChild(container); - helper = document.getElementById('ereader-helper'); - helper.innerHTML = ''; - - var loopy = function () { - words = book.split(' ', wordCount); - segment = words.join(' '); - helper.innerHTML = segment; - - if (helper.offsetHeight > ereader.wrapperHeight) { - if (size == -1) { - words.pop(); - segment = words.join(' '); - - pages.push(segment); - book = book.substr(segment.length); - avgWordCount = Math.round((wordCount + avgWordCount) / 2); - wordCount = avgWordCount; - size = 0; - progressTotal -= segment.length; - } else { - size = 1; - wordCount--; - } - } else { - if (size == 1) { - pages.push(segment); - book = book.substr(segment.length); - avgWordCount = Math.round((wordCount + avgWordCount) / 2); - wordCount = avgWordCount; - size = 0; - progressTotal -= segment.length; - } else { - if (segment == book) { - pages.push(segment); - book = ''; - } - - size = -1; - wordCount++; - } - } - - if (book) { - progressBar.style.width = 150 - Math.round(progressToBookRatio * progressTotal) + 'px'; - setTimeout(loopy, 1); - } else { - book = null; - words = null; - segment = null; - helper.innerHTML = ''; - ereader.slider.removeChild(container); - - ereader.updatePageCount(pages.length); - (ereader.masterPages[0].dataset).pageIndex = pages.length - 1; - (ereader.masterPages[0].dataset).upcomingPageIndex = (ereader.masterPages[0].dataset).pageIndex; - - // Load initial data - for (i = 0; i < 3; i++) { - pageIndex = i == 0 ? pages.length - 1 : i - 1; - el = document.createElement('div'); - el.innerHTML = pages[pageIndex]; - ereader.masterPages[i].appendChild(el) - } - - document.getElementById('loading').style.display = 'none'; - } - } - - loopy(); - } - - ereader.onFlip(function () { - var el, - upcoming, - i; - - for (i = 0; i < 3; i++) { - upcoming = (ereader.masterPages[i].dataset).upcomingPageIndex; - - if (upcoming != (ereader.masterPages[i].dataset).pageIndex) { - el = ereader.masterPages[i].querySelector('div'); - el.innerHTML = pages[upcoming]; - } - } - }); - }, false); +/// + +function demo1() { + document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false); + +var + el, + i, + page, + dots = document.querySelectorAll('#nav li'), + slides = [ + { + img: 'images/pic01.jpg', + width: 300, + height: 213, + desc: 'Piazza del Duomo, Florence, Italy' + }, + { + img: 'images/pic02.jpg', + width: 300, + height: 164, + desc: 'Tuscan Landscape' + } + ]; + + var gallery = new SwipeView('#wrapper', { numberOfPages: slides.length }); + + // Load initial data + for (i = 0; i < 3; i++) { + page = i == 0 ? slides.length - 1 : i - 1; + el = document.createElement('img'); + el.className = 'loading'; + el.src = slides[page].img; + el.width = slides[page].width; + el.height = slides[page].height; + el.onload = function () { this.className = ''; } + gallery.masterPages[i].appendChild(el); + + el = document.createElement('span'); + el.innerHTML = slides[page].desc; + gallery.masterPages[i].appendChild(el) + } + + gallery.onFlip(function () { + var el, + upcoming, + i; + + for (i = 0; i < 3; i++) { + upcoming = (gallery.masterPages[i].dataset).upcomingPageIndex; + + if (upcoming != (gallery.masterPages[i].dataset).pageIndex) { + el = gallery.masterPages[i].querySelector('img'); + el.className = 'loading'; + el.src = slides[upcoming].img; + el.width = slides[upcoming].width; + el.height = slides[upcoming].height; + + el = gallery.masterPages[i].querySelector('span'); + el.innerHTML = slides[upcoming].desc; + } + } + }); + + gallery.onMoveOut(function () { + gallery.masterPages[gallery.currentMasterPage].className = gallery.masterPages[gallery.currentMasterPage].className.replace(/(^|\s)swipeview-active(\s|$)/, ''); + }); + + gallery.onMoveIn(function () { + var className = gallery.masterPages[gallery.currentMasterPage].className; + /(^|\s)swipeview-active(\s|$)/.test(className) || (gallery.masterPages[gallery.currentMasterPage].className = !className ? 'swipeview-active' : className + ' swipeview-active'); + }); +} + +function demo2() { +var carousel: SwipeView, + el, + i, + page, + slides = [ + 'Swipe to know more >>>
    Or scroll down for Lorem Ipsum', + '1. A robot may not injure a human being or, through inaction, allow a human being to come to harm.', + '2. A robot must obey the orders given to it by human beings, except where such orders would conflict with the First Law.', + '3. A robot must protect its own existence as long as such protection does not conflict with the First or Second Laws.' + ]; + + carousel = new SwipeView('#wrapper', { + numberOfPages: slides.length, + hastyPageFlip: true + }); + + // Load initial data + for (i = 0; i < 3; i++) { + page = i == 0 ? slides.length - 1 : i - 1; + + el = document.createElement('span'); + el.innerHTML = slides[page]; + carousel.masterPages[i].appendChild(el) + } + + carousel.onFlip(function () { + var el, + upcoming, + i; + + for (i = 0; i < 3; i++) { + upcoming = (carousel.masterPages[i].dataset).upcomingPageIndex; + + if (upcoming != (carousel.masterPages[i].dataset).pageIndex) { + el = carousel.masterPages[i].querySelector('span'); + el.innerHTML = slides[upcoming]; + } + } + }); +} + +function demo3() { + document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false); + + window.addEventListener('load', function () { + var ereader: SwipeView, + el, + i, + pageIndex, + pages = [], + req = new XMLHttpRequest(); + + ereader = new SwipeView('#wrapper', { hastyPageFlip: true }); + + // Ajax request + req.open('GET', 'flowers.txt', true); + req.onreadystatechange = function () { + if (req.readyState != 4) return; + + paginate(req.status != 200 && (req.status != 304 ? false : req.responseText)); + + req = null; + } + req.send(null); + + function paginate(book) { + var that = this, + container, + helper, + words = [], + segment, + wordCount = 80, + avgWordCount = 0, + progressTotal = 0, + progressCurrent = 0, + progressMaxWidth = document.getElementById('progressbar').clientWidth, + progressToBookRatio = 0, + progressBar = document.querySelector('#progressbar > span'), + size; + + if (!book) return; + + book = book.replace(/\n\n/g, '

    ').replace(/\n/g, ' '); + progressTotal = book.length; + progressToBookRatio = progressMaxWidth / book.length; + + container = document.createElement('div'); + container.style.visibility = 'hidden'; + container.innerHTML = '
    '; + ereader.slider.appendChild(container); + helper = document.getElementById('ereader-helper'); + helper.innerHTML = ''; + + var loopy = function () { + words = book.split(' ', wordCount); + segment = words.join(' '); + helper.innerHTML = segment; + + if (helper.offsetHeight > ereader.wrapperHeight) { + if (size == -1) { + words.pop(); + segment = words.join(' '); + + pages.push(segment); + book = book.substr(segment.length); + avgWordCount = Math.round((wordCount + avgWordCount) / 2); + wordCount = avgWordCount; + size = 0; + progressTotal -= segment.length; + } else { + size = 1; + wordCount--; + } + } else { + if (size == 1) { + pages.push(segment); + book = book.substr(segment.length); + avgWordCount = Math.round((wordCount + avgWordCount) / 2); + wordCount = avgWordCount; + size = 0; + progressTotal -= segment.length; + } else { + if (segment == book) { + pages.push(segment); + book = ''; + } + + size = -1; + wordCount++; + } + } + + if (book) { + progressBar.style.width = 150 - Math.round(progressToBookRatio * progressTotal) + 'px'; + setTimeout(loopy, 1); + } else { + book = null; + words = null; + segment = null; + helper.innerHTML = ''; + ereader.slider.removeChild(container); + + ereader.updatePageCount(pages.length); + (ereader.masterPages[0].dataset).pageIndex = pages.length - 1; + (ereader.masterPages[0].dataset).upcomingPageIndex = (ereader.masterPages[0].dataset).pageIndex; + + // Load initial data + for (i = 0; i < 3; i++) { + pageIndex = i == 0 ? pages.length - 1 : i - 1; + el = document.createElement('div'); + el.innerHTML = pages[pageIndex]; + ereader.masterPages[i].appendChild(el) + } + + document.getElementById('loading').style.display = 'none'; + } + } + + loopy(); + } + + ereader.onFlip(function () { + var el, + upcoming, + i; + + for (i = 0; i < 3; i++) { + upcoming = (ereader.masterPages[i].dataset).upcomingPageIndex; + + if (upcoming != (ereader.masterPages[i].dataset).pageIndex) { + el = ereader.masterPages[i].querySelector('div'); + el.innerHTML = pages[upcoming]; + } + } + }); + }, false); } \ No newline at end of file diff --git a/swipeview/swipeview-tests.ts.tscparams b/swipeview/swipeview-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/swipeview/swipeview-tests.ts.tscparams +++ b/swipeview/swipeview-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/swipeview/swipeview.d.ts b/swipeview/swipeview.d.ts index 8e079fa7d..d45404712 100644 --- a/swipeview/swipeview.d.ts +++ b/swipeview/swipeview.d.ts @@ -1,43 +1,43 @@ -// Type definitions for SwipeView 1.0 -// Project: http://cubiq.org/swipeview -// Definitions by: Boris Yankov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -interface SwipeViewEvent { - (fn: Function): void; -} - -interface SwipeViewOptions { - text?: string; - numberOfPages?: number; - snapThreshold?: number; - hastyPageFlip?: boolean; - loop?: boolean; -} - -declare class SwipeView { - - masterPages: HTMLElement[]; - currentMasterPage: number; - wrapper: HTMLElement; - slider: HTMLElement; - - constructor (element: string); - constructor (element: string, options: SwipeViewOptions); - - destroy(): void; - refreshSize(): void; - updatePageCount(n: number): void; - goToPage(p: number): void; - next(): void; - prev(): void; - handleEvent(e: Event): void; - - onFlip: SwipeViewEvent; - onMoveOut: SwipeViewEvent; - onMoveIn: SwipeViewEvent; - onTouchStart: SwipeViewEvent; - - wrapperHeight: number; +// Type definitions for SwipeView 1.0 +// Project: http://cubiq.org/swipeview +// Definitions by: Boris Yankov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +interface SwipeViewEvent { + (fn: Function): void; +} + +interface SwipeViewOptions { + text?: string; + numberOfPages?: number; + snapThreshold?: number; + hastyPageFlip?: boolean; + loop?: boolean; +} + +declare class SwipeView { + + masterPages: HTMLElement[]; + currentMasterPage: number; + wrapper: HTMLElement; + slider: HTMLElement; + + constructor (element: string); + constructor (element: string, options: SwipeViewOptions); + + destroy(): void; + refreshSize(): void; + updatePageCount(n: number): void; + goToPage(p: number): void; + next(): void; + prev(): void; + handleEvent(e: Event): void; + + onFlip: SwipeViewEvent; + onMoveOut: SwipeViewEvent; + onMoveIn: SwipeViewEvent; + onTouchStart: SwipeViewEvent; + + wrapperHeight: number; } \ No newline at end of file diff --git a/tedious/tedious-tests.ts b/tedious/tedious-tests.ts index f7346a174..bbfdb7629 100644 --- a/tedious/tedious-tests.ts +++ b/tedious/tedious-tests.ts @@ -1,34 +1,34 @@ - -/// - -"use strict"; - -import tedious = require("tedious"); - -var config: tedious.ConnectionConfig = { - userName: "rogier", - password: "rogiers password", - server: "127.0.0.1", - options: { - database: "somedb", - instanceName: "someinstance", - } -} - -var connection = new tedious.Connection(config); -connection.on("connect", (): void => { - console.log("hurray"); -}); - -connection.beginTransaction((error: Error): void => {}, "some name"); -connection.rollbackTransaction((error: Error): void => {}); -connection.commitTransaction((error: Error): void => {}); - - -var request = new tedious.Request("SELECT * FROM foo", (error: Error, rowCount: number): void => { -}); -request.on("row", (row: tedious.ColumnValue[]): void => { -}); -connection.execSql(request); - - + +/// + +"use strict"; + +import tedious = require("tedious"); + +var config: tedious.ConnectionConfig = { + userName: "rogier", + password: "rogiers password", + server: "127.0.0.1", + options: { + database: "somedb", + instanceName: "someinstance", + } +} + +var connection = new tedious.Connection(config); +connection.on("connect", (): void => { + console.log("hurray"); +}); + +connection.beginTransaction((error: Error): void => {}, "some name"); +connection.rollbackTransaction((error: Error): void => {}); +connection.commitTransaction((error: Error): void => {}); + + +var request = new tedious.Request("SELECT * FROM foo", (error: Error, rowCount: number): void => { +}); +request.on("row", (row: tedious.ColumnValue[]): void => { +}); +connection.execSql(request); + + diff --git a/tedious/tedious.d.ts b/tedious/tedious.d.ts index db317a353..71f46f1c7 100644 --- a/tedious/tedious.d.ts +++ b/tedious/tedious.d.ts @@ -1,526 +1,526 @@ -// Type definitions for tedious 1.8.0 -// Project: https://pekim.github.io/tedious -// Definitions by: Rogier Schouten -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare module 'tedious' { - - import events = require("events"); - - export interface ColumnType { - /** - * The column's type, such as VarChar, Int or Binary. - */ - name: string; - } - - export interface ColumnMetaData { - /** - * The column's name - */ - colName: string; - - /** - * The column type. - */ - type: ColumnType; - - /** - * The precision. Only applicable to numeric and decimal. - */ - precision?: number; - - /** - * The scale. Only applicable to numeric, decimal, time, datetime2 and datetimeoffset. - */ - scale?: number; - - /** - * The length, for char, varchar, nvarchar and varbinary. - */ - dataLength?: number; - } - - export interface DebugOptions { - /** - * A boolean, controlling whether debug events will be emitted with text describing packet details (default: false). - */ - packet?: boolean; - - /** - * A boolean, controlling whether debug events will be emitted with text describing packet data details (default: false). - */ - data?: boolean; - - /** - * A boolean, controlling whether debug events will be emitted with text describing packet payload details (default: false). - */ - payload?: boolean; - - /** - * A boolean, controlling whether debug events will be emitted with text describing token stream tokens (default: false). - */ - token?: boolean; - } - - export enum ISOLATION_LEVEL { - NO_CHANGE = 0x00, - READ_UNCOMMITTED = 0x01, - READ_COMMITTED = 0x02, - REPEATABLE_READ = 0x03, - SERIALIZABLE = 0x04, - SNAPSHOT = 0x05 - } - - /** - * Unfortunately these aren't valid JavaScript identifiers - * so I cannot list the values here as enum values - 7_1 = 0x71000001, - 7_2 = 0x72090002, - 7_3_A = 0x730A0003, - 7_3_B = 0x730B0003, - 7_4 = 0x74000004 - */ - export var TDS_VERSION: { [index: string]: number }; - - export interface TediousType { - type: string; - name: string; - } - - export interface TediousTypes { - BigInt: TediousType; - Binary: TediousType; - Bit: TediousType; - BitN: TediousType; - Char: TediousType; - DateN: TediousType; - DateTime2N: TediousType; - DateTime: TediousType; - DateTimeN: TediousType; - DateTimeOffsetN: TediousType; - Decimal: TediousType; - DecimalN: TediousType; - Float: TediousType; - FloatN: TediousType; - Image: TediousType; - Int: TediousType; - IntN: TediousType; - Money: TediousType; - MoneyN: TediousType; - NChar: TediousType; - NText: TediousType; - NVarChar: TediousType; - Null: TediousType; - Numeric: TediousType; - NumericN: TediousType; - Real: TediousType; - SmallDateTime: TediousType; - SmallInt : TediousType; - SmallMoney: TediousType; - TVP: TediousType; - Text: TediousType; - TimeN: TediousType; - TinyInt: TediousType; - UDT: TediousType; - UniqueIdentifierN: TediousType; - VarBinary: TediousType; - VarChar: TediousType; - Xml: TediousType; - } - - export var TYPES: TediousTypes; - - export interface ConnectionOptions { - - /** - * Port to connect to (default: 1433). Mutually exclusive with options.instanceName. - */ - port?: number; - - /** - * The instance name to connect to. The SQL Server Browser service must be running on the database server, - * and UDP port 1444 on the database server must be reachable. (no default) Mutually exclusive with options.port. - */ - instanceName?: string; - - /** - * Database to connect to (default: dependent on server configuration). - */ - database?: string; - - /** - * By default, if the database requestion by options.database cannot be accessed, - * the connection will fail with an error. However, if options.fallbackToDefaultDb is set to true, - * then the user's default database will be * used instead (Default: false). - */ - fallbackToDefaultDb?: boolean; - - /** - * The number of milliseconds before the attempt to connect is considered failed (default: 15000). - */ - connectTimeout?: number; - - /** - * The number of milliseconds before a request is considered failed, or 0 for no timeout (default: 15000). - */ - requestTimeout?: number; - - /** - * The number of milliseconds before the cancel (abort) of a request is considered failed (default: 5000). - */ - cancelTimeout?: number; - - /** - * The size of TDS packets (subject to negotiation with the server). Should be a power of 2. (default: 4096). - */ - packetSize?: number; - - /** - * A boolean determining whether to pass time values in UTC or local time. (default: true). - */ - useUTC?: boolean; - - /** - * A boolean determining whether to rollback a transaction automatically if any error is encountered - * during the given transaction's execution. This sets the value for SET XACT_ABORT during the initial - * SQL phase of a connection (documentation). - */ - abortTransactionOnError?: boolean; - - /** - * A string indicating which network interface (ip addres) to use when connecting to SQL Server. - */ - localAddress?: string; - - /** - * A boolean determining whether to return rows as arrays or key-value collections. (default: false). - */ - useColumnNames?: boolean; - - /** - * A boolean, controlling whether the column names returned will have the first letter converted - * to lower case (true) or not. This value is ignored if you provide a columnNameReplacer. (default: false). - */ - camelCaseColumns?: boolean; - - /** - * A function with parameters (columnName, index, columnMetaData) and returning a string. If provided, - * this will be called once per column per result-set. The returned value will be used instead of the - * SQL-provided column name on row and meta data objects. This allows you to dynamically convert between - * naming conventions. (default: null). - */ - columnNameReplacer?: (columnName: string, index: number, columnMetaData: ColumnMetaData) => string; - - /** - * Debug options - */ - debug?: DebugOptions; - - /** - * The default isolation level that transactions will be run with. (default: READ_COMMITED). - */ - isolationLevel?: ISOLATION_LEVEL; - - /** - * The default isolation level for new connections. All out-of-transaction queries are executed with this setting. (default: READ_COMMITED) - */ - connectionIsolationLevel?: ISOLATION_LEVEL; - - /** - * A boolean, determining whether the connection will request read only access from a SQL Server Availability Group. For more information, see here. (default: false). - */ - readOnlyIntent?: boolean; - - /** - * A boolean determining whether or not the connection will be encrypted. Set to true if you're on Windows Azure. (default: false). - */ - encrypt?: boolean; - - /** - * When encryption is used, an object may be supplied that will be used for the first argument when calling tls.createSecurePair (default: {}). - */ - cryptoCredentialsDetails?: Object; - - /** - * A boolean, that when true will expose received rows in Requests' done* events. See done, doneInProc and doneProc. (default: false) - * Caution: If many row are received, enabling this option could result in excessive memory usage. - */ - rowCollectionOnDone?: boolean; - - /** - * A boolean, that when true will expose received rows in Requests' completion callback. See new Request. (default: false) - * Caution: If many row are received, enabling this option could result in excessive memory usage. - */ - rowCollectionOnRequestCompletion?: boolean; - - /** - * The version of TDS to use. If server doesn't support specified version, negotiated version is used instead. (default: 7_4). - * Take this from tedious.TDS_VERSION.7_4 . - */ - tdsVersion?: number; - } - - export interface ConnectionConfig { - /** - * User name to use for authentication. - */ - userName?: string; - - /** - * Password to use for authentication. - */ - password?: string; - - /** - * Hostname to connect to. - */ - server?: string; - - /** - * Once you set domain, driver will connect to SQL Server using domain login. - */ - domain?: string; - - /** - * Further options - */ - options?: ConnectionOptions; - } - - export interface ParameterOptions { - // for VarChar, NVarChar, VarBinary - length?: number; - // precision for Numeric, Decimal - precision?: number; - // scale for Numeric, Decimal, Time, DateTime2, DateTimeOffset - scale?: number; - } - - /** - * Type of each column in the Request#row event - */ - export interface ColumnValue { - metadata: ColumnMetaData; - value: any; - } - - /** - * A Request instance represents a request that can be executed on a connection - * @event 'columnMetadata' This event, describing result set columns, will be emitted before row events are emitted. This event may be emited multiple times when more than one recordset is produced by the statement. - * @event 'row' A row resulting from execution of the SQL statement - * @event 'done' All rows from a result set have been provided (through row events). This token is used to indicate the completion of a SQL statement. As multiple SQL statements can be sent to the server in a single SQL batch, multiple done events can be generated. An done event is emited for each SQL statement in the SQL batch except variable declarations. For execution of SQL statements within stored procedures, doneProc and doneInProc events are used in place of done events. - * @event 'doneInProc' Indicates the completion status of a SQL statement within a stored procedure. All rows from a statement in a stored procedure have been provided (through row events). - * @event 'doneProc' Indicates the completion status of a stored procedure. This is also generated for stored procedures executed through SQL statements. - * @event 'returnValue' A value for an output parameter (that was added to the request with addOutputParameter(...)). See also Using Parameters. - */ - export class Request extends events.EventEmitter { - - /** - * Constructor - * @param sql The SQL statement to be executed (or a procedure name, if the request is to be used with connection.callProcedure). - * @param callback The callback is called when the request has completed, either successfully or with an error. If an error occurs during execution of the statement(s), then err will describe the error. - * As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called. - * rowCount: The number of rows emitted as result of executing the SQL statement. - * rows: Rows as a result of executing the SQL statement. Will only be avaiable if Connection's config.options.rowCollectionOnRequestCompletion is true. - */ - constructor(sql: string, callback: (error: Error, rowCount: number, rows: any[]) => void); - - /** - * Add an input parameter to the request. - * @param name The parameter name. This should correspond to a parameter in the SQL, or a parameter that a called procedure expects. The name should not start '@'. - * @param type One of the supported data types. - * @param value The value that the parameter is to be given. The Javascript type of the argument should match that documented for data types. - * @param options Additional type options. Optional. - */ - addParameter(name: string, type: TediousType, value: any, options?: ParameterOptions): void; - - /** - * Add an output parameter to the request. The parameter's value will be provide by an emitted returnValue event. - * @param name The parameter name. This should correspond to a parameter in the SQL, or a parameter that a called procedure expects. - * @param type One of the supported data types. - * @param value The value that the parameter is to be given. The Javascript type of the argument should match that documented for data types. Optional. - * @param options Additional type options. Optional. - */ - addOutputParameter(name: string, type: TediousType, value?: any, options?: ParameterOptions): void; - } - - export interface BulkLoadColumnOpts extends ParameterOptions { - // indicates whether the column accepts NULL values. - nullable: boolean; - // If the name of the column is different from the name of the property found on rowObj arguments passed to , then you can use this option to specify the property name. - objName?: string; - } - - export interface BulkLoad { - - /** - * Adds a column to the bulk load. The column definitions should match the table you are trying to insert into. Attempting to call addColumn after the first row has been added will throw an exception. - * @param name The name of the column. - * @param type One of the supported data types. - * @param options Additional column type information. At a minimum, nullable must be set to true or false. - */ - addColumn(name: string, type: TediousType, options: BulkLoadColumnOpts): void; - - /** - * Adds a row to the bulk insert. This method accepts arguments in three different formats: - * @param rowObj An object of key/value pairs representing column name (or objName) and value. - */ - addRow(row: Object): void; - /** - * Adds a row to the bulk insert. This method accepts arguments in three different formats: - * @param columnArray An array representing the values of each column in the same order which they were added to the bulkLoad object. - */ - addRow(columnArray: any[]): void; - /** - * Adds a row to the bulk insert. This method accepts arguments in three different formats: - * @param args If there are at least two columns, values can be passed as multiple arguments instead of an array. They must be in the same order the columns were added in. - */ - addRow(...args: any[]): void; - - /** - * This is simply a helper utility function which returns a CREATE TABLE SQL statement based on the columns added to the bulkLoad object. This may be particularly handy when you want to insert into a temporary table (a table which starts with #). A side note on bulk inserting into temporary tables: if you want to access a local temporary table after executing the bulk load, you'll need to use the same connection and execute your requests using connection.execSqlBatch instead of .execSql. - */ - getTableCreationSql(): string; - } - - /** - * message interface used by the infoMessage and errorMessage events of Connection - */ - export interface InfoObject { - /** - * Error number - */ - number: number; - /** - * The error state, used as a modifier to the error number. - */ - state: any; - /** - * The class (severity) of the error. A class of less than 10 indicates an informational message. - */ - class: number; - /** - * The message text. - */ - message: string; - /** - * The stored procedure name (if a stored procedure generated the message). - */ - procName: string; - /** - * The line number in the SQL batch or stored procedure that caused the error. Line numbers begin at 1; therefore, if the line number is not applicable to the message, the value of LineNumber will be 0. - */ - lineNumber: number; - } - - /** - * Connection - * @event 'connect' The attempt to connect and validate has completed. - * @event 'end' The connection has ended. This may be as a result of the client calling close(), the server closing the connection, or a network error. - * @event 'error' Internal error occurs. - * @event 'debug' A debug message is available. It may be logged or ignored. - * @event 'infoMessage' The server has issued an information message. - * @event 'errorMessage' The server has issued an error message. - * @event 'databaseChange' The server has reported that the active database has changed. This may be as a result of a sucessful login, or a use statement. - * @event 'languageChange' The server has reported that the language has changed. - * @event 'charsetChange' The server has reported that the charset has changed. - * @event 'secure' A secure connection has been established. - */ - export class Connection extends events.EventEmitter { - - constructor(config: ConnectionConfig); - - /** - * Start a transaction. As only one request at a time may be executed on - * a connection, another request should not be initiated until this callback is called. - * @param callback The callback is called when the request to start the transaction has completed, either successfully or with an error. If an error occured then err will describe the error. - * @param name A string representing a name to associate with the transaction. Optional, and defaults to an empty string. Required when isolationLevel is present. - * @param isolationLevel The isolation level that the transaction is to be run with. - */ - beginTransaction(callback: (error?: Error) => void, name?: string, isolationLevel?: ISOLATION_LEVEL): void; - - /** - * Commit a transaction. - * There should be an active transaction. That is, beginTransaction should have been previously called. - * @param callback The callback is called when the request to commit the transaction has completed, either successfully or with an error. If an error occured then err will describe the error. - * As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called. - */ - commitTransaction(callback: (error: Error) => void): void; - - /** - * Rollback a transaction. There should be an active transaction. That is, beginTransaction should have been previously called. - * @param callback The callback is called when the request to rollback the transaction has completed, either successfully or with an error. If an error occured then err will describe the error. - * As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called. - */ - rollbackTransaction(callback: (error: Error) => void): void; - - /** - * Prepare the SQL represented by the request. The request can then be used in subsequent calls to execute and unprepare - * @param request A Request object representing the request. Parameters only require a name and type. Parameter values are ignored. - */ - prepare(request: Request): void; - - /** - * Release the SQL Server resources associated with a previously prepared request. - */ - unprepare(request: Request): void; - - /** - * Call a stored procedure represented by request. - */ - callProcedure(request: Request): void; - - /** - * Execute the SQL represented by request. - * As sp_executesql is used to execute the SQL, if the same SQL is executed multiples times using this function, the SQL Server query optimizer is likely to reuse the execution plan it generates for the first execution. - * Beware of the way that scoping rules apply, and how they may affect local temp tables. If you're running in to scoping issues, then execSqlBatch may be a better choice. See also issue #24. - */ - execSql(request: Request): void; - - /** - * Execute the SQL batch represented by request. There is no param support, and unlike execSql, it is not likely that SQL Server will reuse the execution plan it generates for the SQL. - * In almost all cases, execSql will be a better choice. - */ - execSqlBatch(request: Request): void; - - /** - * Execute previously prepared SQL, using the supplied parameters. - * @param request A previously prepared Request. - * @param parameters An object whose names correspond to the names of parameters that were added to the request before it was prepared. The object's values are passed as the parameters' values when the request is executed. - */ - execute(request: Request, parameters: {}): void; - - /** - * Creates a new BulkLoad instance. - * @param tableName The name of the table to bulk-insert into. - * @param callback A function which will be called after the BulkLoad finishes executing. rowCount will equal the number of rows inserted. - */ - newBulkLoad(tableName: string, callback: (error: Error, rowCount: number) => void): BulkLoad; - - /** - * Executes a BulkLoad. - */ - execBulkLoad(bulkLoad: BulkLoad): void; - - /** - * Reset the connection to its initial state. Can be useful for connection pool implementations. - * @param callback The callback is called when the connection reset has completed, either successfully or with an error. If an error occured then err will describe the error. - * As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called. - */ - reset(callback: (error: Error) => void): void; - - /** - * Cancel currently executed request. - */ - cancel(): void; - - /** - * Closes the connection to the database. The end will be emmited once the connection has been closed. - */ - close(): void; - - } -} +// Type definitions for tedious 1.8.0 +// Project: https://pekim.github.io/tedious +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'tedious' { + + import events = require("events"); + + export interface ColumnType { + /** + * The column's type, such as VarChar, Int or Binary. + */ + name: string; + } + + export interface ColumnMetaData { + /** + * The column's name + */ + colName: string; + + /** + * The column type. + */ + type: ColumnType; + + /** + * The precision. Only applicable to numeric and decimal. + */ + precision?: number; + + /** + * The scale. Only applicable to numeric, decimal, time, datetime2 and datetimeoffset. + */ + scale?: number; + + /** + * The length, for char, varchar, nvarchar and varbinary. + */ + dataLength?: number; + } + + export interface DebugOptions { + /** + * A boolean, controlling whether debug events will be emitted with text describing packet details (default: false). + */ + packet?: boolean; + + /** + * A boolean, controlling whether debug events will be emitted with text describing packet data details (default: false). + */ + data?: boolean; + + /** + * A boolean, controlling whether debug events will be emitted with text describing packet payload details (default: false). + */ + payload?: boolean; + + /** + * A boolean, controlling whether debug events will be emitted with text describing token stream tokens (default: false). + */ + token?: boolean; + } + + export enum ISOLATION_LEVEL { + NO_CHANGE = 0x00, + READ_UNCOMMITTED = 0x01, + READ_COMMITTED = 0x02, + REPEATABLE_READ = 0x03, + SERIALIZABLE = 0x04, + SNAPSHOT = 0x05 + } + + /** + * Unfortunately these aren't valid JavaScript identifiers + * so I cannot list the values here as enum values + 7_1 = 0x71000001, + 7_2 = 0x72090002, + 7_3_A = 0x730A0003, + 7_3_B = 0x730B0003, + 7_4 = 0x74000004 + */ + export var TDS_VERSION: { [index: string]: number }; + + export interface TediousType { + type: string; + name: string; + } + + export interface TediousTypes { + BigInt: TediousType; + Binary: TediousType; + Bit: TediousType; + BitN: TediousType; + Char: TediousType; + DateN: TediousType; + DateTime2N: TediousType; + DateTime: TediousType; + DateTimeN: TediousType; + DateTimeOffsetN: TediousType; + Decimal: TediousType; + DecimalN: TediousType; + Float: TediousType; + FloatN: TediousType; + Image: TediousType; + Int: TediousType; + IntN: TediousType; + Money: TediousType; + MoneyN: TediousType; + NChar: TediousType; + NText: TediousType; + NVarChar: TediousType; + Null: TediousType; + Numeric: TediousType; + NumericN: TediousType; + Real: TediousType; + SmallDateTime: TediousType; + SmallInt : TediousType; + SmallMoney: TediousType; + TVP: TediousType; + Text: TediousType; + TimeN: TediousType; + TinyInt: TediousType; + UDT: TediousType; + UniqueIdentifierN: TediousType; + VarBinary: TediousType; + VarChar: TediousType; + Xml: TediousType; + } + + export var TYPES: TediousTypes; + + export interface ConnectionOptions { + + /** + * Port to connect to (default: 1433). Mutually exclusive with options.instanceName. + */ + port?: number; + + /** + * The instance name to connect to. The SQL Server Browser service must be running on the database server, + * and UDP port 1444 on the database server must be reachable. (no default) Mutually exclusive with options.port. + */ + instanceName?: string; + + /** + * Database to connect to (default: dependent on server configuration). + */ + database?: string; + + /** + * By default, if the database requestion by options.database cannot be accessed, + * the connection will fail with an error. However, if options.fallbackToDefaultDb is set to true, + * then the user's default database will be * used instead (Default: false). + */ + fallbackToDefaultDb?: boolean; + + /** + * The number of milliseconds before the attempt to connect is considered failed (default: 15000). + */ + connectTimeout?: number; + + /** + * The number of milliseconds before a request is considered failed, or 0 for no timeout (default: 15000). + */ + requestTimeout?: number; + + /** + * The number of milliseconds before the cancel (abort) of a request is considered failed (default: 5000). + */ + cancelTimeout?: number; + + /** + * The size of TDS packets (subject to negotiation with the server). Should be a power of 2. (default: 4096). + */ + packetSize?: number; + + /** + * A boolean determining whether to pass time values in UTC or local time. (default: true). + */ + useUTC?: boolean; + + /** + * A boolean determining whether to rollback a transaction automatically if any error is encountered + * during the given transaction's execution. This sets the value for SET XACT_ABORT during the initial + * SQL phase of a connection (documentation). + */ + abortTransactionOnError?: boolean; + + /** + * A string indicating which network interface (ip addres) to use when connecting to SQL Server. + */ + localAddress?: string; + + /** + * A boolean determining whether to return rows as arrays or key-value collections. (default: false). + */ + useColumnNames?: boolean; + + /** + * A boolean, controlling whether the column names returned will have the first letter converted + * to lower case (true) or not. This value is ignored if you provide a columnNameReplacer. (default: false). + */ + camelCaseColumns?: boolean; + + /** + * A function with parameters (columnName, index, columnMetaData) and returning a string. If provided, + * this will be called once per column per result-set. The returned value will be used instead of the + * SQL-provided column name on row and meta data objects. This allows you to dynamically convert between + * naming conventions. (default: null). + */ + columnNameReplacer?: (columnName: string, index: number, columnMetaData: ColumnMetaData) => string; + + /** + * Debug options + */ + debug?: DebugOptions; + + /** + * The default isolation level that transactions will be run with. (default: READ_COMMITED). + */ + isolationLevel?: ISOLATION_LEVEL; + + /** + * The default isolation level for new connections. All out-of-transaction queries are executed with this setting. (default: READ_COMMITED) + */ + connectionIsolationLevel?: ISOLATION_LEVEL; + + /** + * A boolean, determining whether the connection will request read only access from a SQL Server Availability Group. For more information, see here. (default: false). + */ + readOnlyIntent?: boolean; + + /** + * A boolean determining whether or not the connection will be encrypted. Set to true if you're on Windows Azure. (default: false). + */ + encrypt?: boolean; + + /** + * When encryption is used, an object may be supplied that will be used for the first argument when calling tls.createSecurePair (default: {}). + */ + cryptoCredentialsDetails?: Object; + + /** + * A boolean, that when true will expose received rows in Requests' done* events. See done, doneInProc and doneProc. (default: false) + * Caution: If many row are received, enabling this option could result in excessive memory usage. + */ + rowCollectionOnDone?: boolean; + + /** + * A boolean, that when true will expose received rows in Requests' completion callback. See new Request. (default: false) + * Caution: If many row are received, enabling this option could result in excessive memory usage. + */ + rowCollectionOnRequestCompletion?: boolean; + + /** + * The version of TDS to use. If server doesn't support specified version, negotiated version is used instead. (default: 7_4). + * Take this from tedious.TDS_VERSION.7_4 . + */ + tdsVersion?: number; + } + + export interface ConnectionConfig { + /** + * User name to use for authentication. + */ + userName?: string; + + /** + * Password to use for authentication. + */ + password?: string; + + /** + * Hostname to connect to. + */ + server?: string; + + /** + * Once you set domain, driver will connect to SQL Server using domain login. + */ + domain?: string; + + /** + * Further options + */ + options?: ConnectionOptions; + } + + export interface ParameterOptions { + // for VarChar, NVarChar, VarBinary + length?: number; + // precision for Numeric, Decimal + precision?: number; + // scale for Numeric, Decimal, Time, DateTime2, DateTimeOffset + scale?: number; + } + + /** + * Type of each column in the Request#row event + */ + export interface ColumnValue { + metadata: ColumnMetaData; + value: any; + } + + /** + * A Request instance represents a request that can be executed on a connection + * @event 'columnMetadata' This event, describing result set columns, will be emitted before row events are emitted. This event may be emited multiple times when more than one recordset is produced by the statement. + * @event 'row' A row resulting from execution of the SQL statement + * @event 'done' All rows from a result set have been provided (through row events). This token is used to indicate the completion of a SQL statement. As multiple SQL statements can be sent to the server in a single SQL batch, multiple done events can be generated. An done event is emited for each SQL statement in the SQL batch except variable declarations. For execution of SQL statements within stored procedures, doneProc and doneInProc events are used in place of done events. + * @event 'doneInProc' Indicates the completion status of a SQL statement within a stored procedure. All rows from a statement in a stored procedure have been provided (through row events). + * @event 'doneProc' Indicates the completion status of a stored procedure. This is also generated for stored procedures executed through SQL statements. + * @event 'returnValue' A value for an output parameter (that was added to the request with addOutputParameter(...)). See also Using Parameters. + */ + export class Request extends events.EventEmitter { + + /** + * Constructor + * @param sql The SQL statement to be executed (or a procedure name, if the request is to be used with connection.callProcedure). + * @param callback The callback is called when the request has completed, either successfully or with an error. If an error occurs during execution of the statement(s), then err will describe the error. + * As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called. + * rowCount: The number of rows emitted as result of executing the SQL statement. + * rows: Rows as a result of executing the SQL statement. Will only be avaiable if Connection's config.options.rowCollectionOnRequestCompletion is true. + */ + constructor(sql: string, callback: (error: Error, rowCount: number, rows: any[]) => void); + + /** + * Add an input parameter to the request. + * @param name The parameter name. This should correspond to a parameter in the SQL, or a parameter that a called procedure expects. The name should not start '@'. + * @param type One of the supported data types. + * @param value The value that the parameter is to be given. The Javascript type of the argument should match that documented for data types. + * @param options Additional type options. Optional. + */ + addParameter(name: string, type: TediousType, value: any, options?: ParameterOptions): void; + + /** + * Add an output parameter to the request. The parameter's value will be provide by an emitted returnValue event. + * @param name The parameter name. This should correspond to a parameter in the SQL, or a parameter that a called procedure expects. + * @param type One of the supported data types. + * @param value The value that the parameter is to be given. The Javascript type of the argument should match that documented for data types. Optional. + * @param options Additional type options. Optional. + */ + addOutputParameter(name: string, type: TediousType, value?: any, options?: ParameterOptions): void; + } + + export interface BulkLoadColumnOpts extends ParameterOptions { + // indicates whether the column accepts NULL values. + nullable: boolean; + // If the name of the column is different from the name of the property found on rowObj arguments passed to , then you can use this option to specify the property name. + objName?: string; + } + + export interface BulkLoad { + + /** + * Adds a column to the bulk load. The column definitions should match the table you are trying to insert into. Attempting to call addColumn after the first row has been added will throw an exception. + * @param name The name of the column. + * @param type One of the supported data types. + * @param options Additional column type information. At a minimum, nullable must be set to true or false. + */ + addColumn(name: string, type: TediousType, options: BulkLoadColumnOpts): void; + + /** + * Adds a row to the bulk insert. This method accepts arguments in three different formats: + * @param rowObj An object of key/value pairs representing column name (or objName) and value. + */ + addRow(row: Object): void; + /** + * Adds a row to the bulk insert. This method accepts arguments in three different formats: + * @param columnArray An array representing the values of each column in the same order which they were added to the bulkLoad object. + */ + addRow(columnArray: any[]): void; + /** + * Adds a row to the bulk insert. This method accepts arguments in three different formats: + * @param args If there are at least two columns, values can be passed as multiple arguments instead of an array. They must be in the same order the columns were added in. + */ + addRow(...args: any[]): void; + + /** + * This is simply a helper utility function which returns a CREATE TABLE SQL statement based on the columns added to the bulkLoad object. This may be particularly handy when you want to insert into a temporary table (a table which starts with #). A side note on bulk inserting into temporary tables: if you want to access a local temporary table after executing the bulk load, you'll need to use the same connection and execute your requests using connection.execSqlBatch instead of .execSql. + */ + getTableCreationSql(): string; + } + + /** + * message interface used by the infoMessage and errorMessage events of Connection + */ + export interface InfoObject { + /** + * Error number + */ + number: number; + /** + * The error state, used as a modifier to the error number. + */ + state: any; + /** + * The class (severity) of the error. A class of less than 10 indicates an informational message. + */ + class: number; + /** + * The message text. + */ + message: string; + /** + * The stored procedure name (if a stored procedure generated the message). + */ + procName: string; + /** + * The line number in the SQL batch or stored procedure that caused the error. Line numbers begin at 1; therefore, if the line number is not applicable to the message, the value of LineNumber will be 0. + */ + lineNumber: number; + } + + /** + * Connection + * @event 'connect' The attempt to connect and validate has completed. + * @event 'end' The connection has ended. This may be as a result of the client calling close(), the server closing the connection, or a network error. + * @event 'error' Internal error occurs. + * @event 'debug' A debug message is available. It may be logged or ignored. + * @event 'infoMessage' The server has issued an information message. + * @event 'errorMessage' The server has issued an error message. + * @event 'databaseChange' The server has reported that the active database has changed. This may be as a result of a sucessful login, or a use statement. + * @event 'languageChange' The server has reported that the language has changed. + * @event 'charsetChange' The server has reported that the charset has changed. + * @event 'secure' A secure connection has been established. + */ + export class Connection extends events.EventEmitter { + + constructor(config: ConnectionConfig); + + /** + * Start a transaction. As only one request at a time may be executed on + * a connection, another request should not be initiated until this callback is called. + * @param callback The callback is called when the request to start the transaction has completed, either successfully or with an error. If an error occured then err will describe the error. + * @param name A string representing a name to associate with the transaction. Optional, and defaults to an empty string. Required when isolationLevel is present. + * @param isolationLevel The isolation level that the transaction is to be run with. + */ + beginTransaction(callback: (error?: Error) => void, name?: string, isolationLevel?: ISOLATION_LEVEL): void; + + /** + * Commit a transaction. + * There should be an active transaction. That is, beginTransaction should have been previously called. + * @param callback The callback is called when the request to commit the transaction has completed, either successfully or with an error. If an error occured then err will describe the error. + * As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called. + */ + commitTransaction(callback: (error: Error) => void): void; + + /** + * Rollback a transaction. There should be an active transaction. That is, beginTransaction should have been previously called. + * @param callback The callback is called when the request to rollback the transaction has completed, either successfully or with an error. If an error occured then err will describe the error. + * As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called. + */ + rollbackTransaction(callback: (error: Error) => void): void; + + /** + * Prepare the SQL represented by the request. The request can then be used in subsequent calls to execute and unprepare + * @param request A Request object representing the request. Parameters only require a name and type. Parameter values are ignored. + */ + prepare(request: Request): void; + + /** + * Release the SQL Server resources associated with a previously prepared request. + */ + unprepare(request: Request): void; + + /** + * Call a stored procedure represented by request. + */ + callProcedure(request: Request): void; + + /** + * Execute the SQL represented by request. + * As sp_executesql is used to execute the SQL, if the same SQL is executed multiples times using this function, the SQL Server query optimizer is likely to reuse the execution plan it generates for the first execution. + * Beware of the way that scoping rules apply, and how they may affect local temp tables. If you're running in to scoping issues, then execSqlBatch may be a better choice. See also issue #24. + */ + execSql(request: Request): void; + + /** + * Execute the SQL batch represented by request. There is no param support, and unlike execSql, it is not likely that SQL Server will reuse the execution plan it generates for the SQL. + * In almost all cases, execSql will be a better choice. + */ + execSqlBatch(request: Request): void; + + /** + * Execute previously prepared SQL, using the supplied parameters. + * @param request A previously prepared Request. + * @param parameters An object whose names correspond to the names of parameters that were added to the request before it was prepared. The object's values are passed as the parameters' values when the request is executed. + */ + execute(request: Request, parameters: {}): void; + + /** + * Creates a new BulkLoad instance. + * @param tableName The name of the table to bulk-insert into. + * @param callback A function which will be called after the BulkLoad finishes executing. rowCount will equal the number of rows inserted. + */ + newBulkLoad(tableName: string, callback: (error: Error, rowCount: number) => void): BulkLoad; + + /** + * Executes a BulkLoad. + */ + execBulkLoad(bulkLoad: BulkLoad): void; + + /** + * Reset the connection to its initial state. Can be useful for connection pool implementations. + * @param callback The callback is called when the connection reset has completed, either successfully or with an error. If an error occured then err will describe the error. + * As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called. + */ + reset(callback: (error: Error) => void): void; + + /** + * Cancel currently executed request. + */ + cancel(): void; + + /** + * Closes the connection to the database. The end will be emmited once the connection has been closed. + */ + close(): void; + + } +} diff --git a/teechart/teechart.d.ts b/teechart/teechart.d.ts index 6e7ac3944..e40e517bd 100644 --- a/teechart/teechart.d.ts +++ b/teechart/teechart.d.ts @@ -1,683 +1,683 @@ -// Type definitions for TeeChart 1.3 -// Project: http://www.steema.com -// Definitions by: Steema Software -// Definitions: https://github.com/borisyankov/DefinitelyTyped -/** - * TeeChart(tm) for TypeScript - * - * v1.3 October 2012 - * Copyright(c) 2012 by Steema Software SL. All Rights Reserved. - * http://www.steema.com - * - * Licensed with commercial and non-commercial attributes, - * specifically: http://www.steema.com/licensing/html5 - * - * TypeScript is a Microsoft product: www.typescriptlang.org - * - */ - -/** - * @author Steema Software - * @version 1.3 - */ - - -declare module Tee { - - interface IPoint { - x: number; - y: number; - } - - interface IRectangle { - x: number; - y: number; - width: number; - height: number; - - contains(point: IPoint): boolean; - } - - interface ITool { - active: boolean; - chart: IChart; - - mousedown(event): boolean; - mousemove(event): boolean; - clicked(p:IPoint): boolean; - draw(): void; - } - - interface IGradient { - chart: IChart; - visible: boolean; - - colors: string[]; - direction: string; - stops: number[]; - offset: IPoint; - } - - interface IShadow { - chart: IChart; - visible: boolean; - blur:number; - color: string; - width:number; - height:number; - } - - interface IStroke { - chart: IChart; - fill: string; - size: number; - join: string; - cap: string; - dash: number[]; - gradient: IGradient; - } - - interface IFont { - chart: IChart; - style: string; - gradient: IGradient; - fill: string; - stroke: IStroke; - shadow: IShadow; - textAlign: string; - baseLine: string; - - getSize():number; - setSize(size:number):void; - } - - interface IImage { - url: string; - chart: IChart; - visible: boolean; - } - - interface IFormat { - font: IFont; - gradient: IGradient; - shadow: IShadow; - stroke: IStroke; - round: IPoint; - transparency: number; - image: IImage; - fill: string; - - textHeight(text:string): number; - textWidth(text:string): number; - drawText(bounds:IRectangle, text:string); - rectangle(x:number, y:number, width:number, height:number); - poligon(points:IPoint[]); - ellipse(x:number, y:number, width:number, height:number); - } - - interface IMargins { - left: number; - top: number; - right: number; - bottom: number; - } - - interface IAnnotation extends ITool { - position: IPoint; - margins: IMargins; - items: IAnnotation[]; - bounds: IRectangle; - visible: boolean; - transparent: boolean; - text: string; - format: IFormat; - - add(text: string): IAnnotation; - resize(): void; - clicked(point: IPoint): boolean; - draw(): void; - } - - interface IPanel { - format: IFormat; - transparent: boolean; - margins: IMargins; - } - - interface ITitle extends IAnnotation { - expand: boolean; - padding: number; - transparent: boolean; - } - - interface IPalette { - colors: string[]; - - get(index: number): string; - } - - interface IArrow extends IFormat { - length: number; - underline: boolean; - } - - interface IMarks extends IAnnotation { - arrow: IArrow; - series: ISeries; - - style: string; - - drawEvery: number; - visible: boolean; - } - - interface ISeriesData { - values: number[]; - labels: string[]; - source: any; - } - - interface ICursor { - cursor: string; - } - - interface ISeriesNoBounds { - data: ISeriesData; - marks: IMarks; - - yMandatory: boolean; - horizAxis: string; - vertAxis: string; - - format: IFormat; - hover: IFormat; - - visible: boolean; - - cursor: ICursor; - over: number; - - palette: IPalette; - colorEach: string; - - useAxes: boolean; - decimals: number; - - title: string; - - //refresh(failure: function): void; - - toPercent(index: number): string; - markText(index: number): string; - - valueText(index: number): string; - - associatedToAxis(axis: IAxis): boolean; - - calc(index: number, position: IPoint): void; - - clicked(position: IPoint): number; - - minXValue(): number; - maxXValue(): number; - - minYValue(): number; - maxYValue(): number; - - count(): number; - - addRandom(count: number, range?: number, x?: boolean): ISeries; - } - - interface ISeries extends ISeriesNoBounds { - bounds(rectangle: IRectangle): void; - } - - interface IAxisLabels { - chart: IChart; - format: IFormat; - decimals: number; - padding: number; - separation: number; // % - visible: boolean; - rotation: number; - alternate: boolean; - maxWidth: number; - - labelStyle: string; - dateFormat: string; - - getLabel(value: number): string; - width(value: number): number; - - } - - interface IGrid { - chart: IChart; - format: IFormat; - visible: boolean; - lineDash: boolean; - } - - interface ITicks { - chart: IChart; - stroke: IStroke; - visible: boolean; - length: number; - } - - interface IMinorTicks extends ITicks { - count: number; - } - - interface IAxisTitle extends IAnnotation { - padding: number; - transparent: boolean; - } - - interface IAxis { - chart: IChart; - visible: boolean; - inverted: boolean; - - horizontal: boolean; // readonly - otherSize: boolean; // readonly - bounds: IRectangle; // readonly? - - position: number; - format: IFormat; - custom: boolean; // readonly - - grid: IGrid; - labels: IAxisLabels; - ticks: ITicks; - minorTicks: IMinorTicks; - innerTicks: ITicks; - - title: IAxisTitle; - - automatic: boolean; - minimum: number; - maximum: number; - increment: number; - log: boolean; - - startPos: number; - endPos: number; - - start: number; // % - end: number; // % - - axisSize: number; - - scale: number; - increm: number; - - calc(value: number): number; - fromPos(position: number): number; - fromSize(size: number): number; - - hasAnySeries(): boolean; - scroll(delta: number): void; - setMinMax(minimum: number, maximum: number): void; - } - - interface IAxes { - chart: IChart; - visible: boolean; - - left: IAxis; - top: IAxis; - right: IAxis; - bottom: IAxis; - - items: IAxis[]; - - add(horizontal: boolean, otherSide: boolean): IAxis; - //each(f: function): void; - } - - interface ISymbol { - chart: IChart; - format: IFormat; - width: number; - height: number; - padding: number; - visible: boolean; - } - - interface ILegend { - chart: IChart; - - transparent: boolean; - - format: IFormat; - title: IAnnotation; - - bounds: IRectangle; - position: string; - visible: boolean; - inverted: boolean; - padding: number; - align: number; - - fontColor: boolean; - - dividing: IStroke; - over: number; - symbol: ISymbol; - - itemHeight: number; - innerOff: number; - - legendStyle: string; - textStyle: string; - - availRows(): number; - itemsCount(): number; - totalWidth(): number; - showValues(): boolean; - itemText(series: ISeries, index: number): string; - isVertical(): boolean; - } - - interface IScroll { - chart: IChart; - active: boolean; - enabled: boolean; - direction: string; - mouseButton: number; - - position: IPoint; - } - - interface ISeriesList { - chart: IChart; - items: ISeries[]; - - anyUsesAxes(): boolean; - clicked(position: IPoint): boolean; - //each(f: function): void; - firstVisible(): ISeries; - - } - - interface ITools { - chart: IChart; - items: ITool[]; - - add(tool: ITool): ITool; - } - - interface IWall { - format: IFormat; - visible: boolean; - bounds: IRectangle; - } - - interface IWalls { - visible: boolean; - left: IWall; - right: IWall; - bottom: IWall; - back: IWall; - } - - interface IZoom { - chart: IChart; - active: boolean; - direction: string; - enabled: boolean; - mouseButton: number; - format: IFormat; - - reset(): void; - } - - interface IChart { - addSeries(series:ISeries): ISeries; - draw(context?:CanvasRenderingContext2D); - } - - // SERIES - - interface ICustomBar extends ISeries { - sideMargins: number; - useOrigin: boolean; - origin: number; - - offset: number; - barSize: number; - barStyle: string; - - stacked: string; - } - - interface ISeriesPointer { - chart: IChart; - format: IFormat; - visible: boolean; - colorEach: boolean; - style: string; - width: number; - height: number; - } - - interface ICustomSeries extends ISeries { - pointer: ISeriesPointer; - - stacked: string; - stairs: boolean; - } - - interface ILine extends ICustomSeries { - smooth: number; - } - - interface ISmoothLine extends ILine { - smooth: number; - } - - interface IArea extends ISeries { - useOrigin: boolean; - origin: number; - } - - interface IPie extends ISeries { - donut: number; - rotation: number; - sort: string; - orderAscending: boolean; - explode: number[]; - concentric: boolean; - - calcPos(angle: number, position: IPoint): void; - } - - interface IBubbleData extends ISeriesData { - radius: number[]; - } - - interface IBubble extends ICustomSeries { - data: IBubbleData; - } - - interface IGanttData extends ISeriesData { - start: number[]; - x: number[]; - end: number[]; - } - - interface IGantt extends ISeriesNoBounds { - data: IGanttData; - dateFormat: string; - colorEach: string; - height: number; - margin: IPoint; - - add(index: number, label: string, start: number, end: number): void; - bounds(index: number, rectangle: IRectangle): void; - } - - interface ICandleData extends ISeriesData { - open: number[]; - close: number[]; - high: number[]; - low: number[]; - } - - interface ICandle extends ICustomSeries { - data: ICandleData; - higher: IFormat; - lower: IFormat; - style: string; - } - - // TOOLS - - interface IDragTool extends ITool { - series: ISeries; - } - - interface ICursorTool extends ITool { - direction: string; - size: IPoint; - - followMouse: boolean; - dragging: number; - - format: IFormat; - - horizAxis: IAxis; - vertAxis: IAxis; - - render: string; - - over(point: IPoint): boolean; - setRender(render: string): void; - } - - interface IToolTip extends IAnnotation { - animated: number; - autoHide: boolean; - autoRedraw: boolean; - currentSeries: ISeries; - currentIndex: number; - delay: number; - - hide(): void; - refresh(series: ISeries, index: number): void; - } - - class Point implements IPoint { - public x:number; - public y:number; - } - - class Chart implements IChart { - //public aspect: IAspect; - - public axes: IAxes; - public footer: ITitle; - public legend: ILegend; - public panel: IPanel; - public scroll: IScroll; - public series: ISeriesList; - public title: ITitle; - public tools: ITools; - public walls: IWalls; - public zoom: IZoom; - - public bounds: IRectangle; - public canvas: HTMLCanvasElement; - public chartRect: IRectangle; - public palette: IPalette; - - constructor(canvas: string); - addSeries(series: ISeries): ISeries; - getSeries(index: number): ISeries; - removeSeries(series:ISeries): void; - - draw(context?:CanvasRenderingContext2D); - toImage(image: HTMLImageElement, format:string, quality:number): void; - } - - // SERIES - - var Line: { - prototype: ILine; - new(values?:number[]): ILine; - } - - var PointXY: { - prototype: ICustomSeries; - new(values?:number[]): ICustomSeries; - } - - var Area: { - prototype: IArea; - new(values?:number[]): IArea; - } - - var HorizArea: { - prototype: IArea; - new(values?:number[]): IArea; - } - - var Bar: { - prototype: ICustomBar; - new(values?:number[]): ICustomBar; - } - - var HorizBar: { - prototype: ICustomBar; - new(values?:number[]): ICustomBar; - } - - var Pie: { - prototype: IPie; - new(values?:number[]): IPie; - } - - var Donut: { - prototype: IPie; - new(values?:number[]): IPie; - } - - var Bubble: { - prototype: IBubble; - new(values?:number[]): IBubble; - } - - var Gantt: { - prototype: IGantt; - new(values?:number[]): IGantt; - } - - var Volume: { - prototype: ICustomBar; - new(values?:number[]): ICustomBar; - } - - var Candle: { - prototype: ICandle; - new(values?:number[]): ICandle; - } - - // TOOLS - - var CursorTool: { - prototype: ICursorTool; - new(chart?: Chart): ICursorTool; - } - - var DragTool: { - prototype: IDragTool; - new(chart?: Chart): IDragTool; - } - - var ToolTip: { - prototype: IToolTip; - new(chart?: Chart): IToolTip; - } -} +// Type definitions for TeeChart 1.3 +// Project: http://www.steema.com +// Definitions by: Steema Software +// Definitions: https://github.com/borisyankov/DefinitelyTyped +/** + * TeeChart(tm) for TypeScript + * + * v1.3 October 2012 + * Copyright(c) 2012 by Steema Software SL. All Rights Reserved. + * http://www.steema.com + * + * Licensed with commercial and non-commercial attributes, + * specifically: http://www.steema.com/licensing/html5 + * + * TypeScript is a Microsoft product: www.typescriptlang.org + * + */ + +/** + * @author Steema Software + * @version 1.3 + */ + + +declare module Tee { + + interface IPoint { + x: number; + y: number; + } + + interface IRectangle { + x: number; + y: number; + width: number; + height: number; + + contains(point: IPoint): boolean; + } + + interface ITool { + active: boolean; + chart: IChart; + + mousedown(event): boolean; + mousemove(event): boolean; + clicked(p:IPoint): boolean; + draw(): void; + } + + interface IGradient { + chart: IChart; + visible: boolean; + + colors: string[]; + direction: string; + stops: number[]; + offset: IPoint; + } + + interface IShadow { + chart: IChart; + visible: boolean; + blur:number; + color: string; + width:number; + height:number; + } + + interface IStroke { + chart: IChart; + fill: string; + size: number; + join: string; + cap: string; + dash: number[]; + gradient: IGradient; + } + + interface IFont { + chart: IChart; + style: string; + gradient: IGradient; + fill: string; + stroke: IStroke; + shadow: IShadow; + textAlign: string; + baseLine: string; + + getSize():number; + setSize(size:number):void; + } + + interface IImage { + url: string; + chart: IChart; + visible: boolean; + } + + interface IFormat { + font: IFont; + gradient: IGradient; + shadow: IShadow; + stroke: IStroke; + round: IPoint; + transparency: number; + image: IImage; + fill: string; + + textHeight(text:string): number; + textWidth(text:string): number; + drawText(bounds:IRectangle, text:string); + rectangle(x:number, y:number, width:number, height:number); + poligon(points:IPoint[]); + ellipse(x:number, y:number, width:number, height:number); + } + + interface IMargins { + left: number; + top: number; + right: number; + bottom: number; + } + + interface IAnnotation extends ITool { + position: IPoint; + margins: IMargins; + items: IAnnotation[]; + bounds: IRectangle; + visible: boolean; + transparent: boolean; + text: string; + format: IFormat; + + add(text: string): IAnnotation; + resize(): void; + clicked(point: IPoint): boolean; + draw(): void; + } + + interface IPanel { + format: IFormat; + transparent: boolean; + margins: IMargins; + } + + interface ITitle extends IAnnotation { + expand: boolean; + padding: number; + transparent: boolean; + } + + interface IPalette { + colors: string[]; + + get(index: number): string; + } + + interface IArrow extends IFormat { + length: number; + underline: boolean; + } + + interface IMarks extends IAnnotation { + arrow: IArrow; + series: ISeries; + + style: string; + + drawEvery: number; + visible: boolean; + } + + interface ISeriesData { + values: number[]; + labels: string[]; + source: any; + } + + interface ICursor { + cursor: string; + } + + interface ISeriesNoBounds { + data: ISeriesData; + marks: IMarks; + + yMandatory: boolean; + horizAxis: string; + vertAxis: string; + + format: IFormat; + hover: IFormat; + + visible: boolean; + + cursor: ICursor; + over: number; + + palette: IPalette; + colorEach: string; + + useAxes: boolean; + decimals: number; + + title: string; + + //refresh(failure: function): void; + + toPercent(index: number): string; + markText(index: number): string; + + valueText(index: number): string; + + associatedToAxis(axis: IAxis): boolean; + + calc(index: number, position: IPoint): void; + + clicked(position: IPoint): number; + + minXValue(): number; + maxXValue(): number; + + minYValue(): number; + maxYValue(): number; + + count(): number; + + addRandom(count: number, range?: number, x?: boolean): ISeries; + } + + interface ISeries extends ISeriesNoBounds { + bounds(rectangle: IRectangle): void; + } + + interface IAxisLabels { + chart: IChart; + format: IFormat; + decimals: number; + padding: number; + separation: number; // % + visible: boolean; + rotation: number; + alternate: boolean; + maxWidth: number; + + labelStyle: string; + dateFormat: string; + + getLabel(value: number): string; + width(value: number): number; + + } + + interface IGrid { + chart: IChart; + format: IFormat; + visible: boolean; + lineDash: boolean; + } + + interface ITicks { + chart: IChart; + stroke: IStroke; + visible: boolean; + length: number; + } + + interface IMinorTicks extends ITicks { + count: number; + } + + interface IAxisTitle extends IAnnotation { + padding: number; + transparent: boolean; + } + + interface IAxis { + chart: IChart; + visible: boolean; + inverted: boolean; + + horizontal: boolean; // readonly + otherSize: boolean; // readonly + bounds: IRectangle; // readonly? + + position: number; + format: IFormat; + custom: boolean; // readonly + + grid: IGrid; + labels: IAxisLabels; + ticks: ITicks; + minorTicks: IMinorTicks; + innerTicks: ITicks; + + title: IAxisTitle; + + automatic: boolean; + minimum: number; + maximum: number; + increment: number; + log: boolean; + + startPos: number; + endPos: number; + + start: number; // % + end: number; // % + + axisSize: number; + + scale: number; + increm: number; + + calc(value: number): number; + fromPos(position: number): number; + fromSize(size: number): number; + + hasAnySeries(): boolean; + scroll(delta: number): void; + setMinMax(minimum: number, maximum: number): void; + } + + interface IAxes { + chart: IChart; + visible: boolean; + + left: IAxis; + top: IAxis; + right: IAxis; + bottom: IAxis; + + items: IAxis[]; + + add(horizontal: boolean, otherSide: boolean): IAxis; + //each(f: function): void; + } + + interface ISymbol { + chart: IChart; + format: IFormat; + width: number; + height: number; + padding: number; + visible: boolean; + } + + interface ILegend { + chart: IChart; + + transparent: boolean; + + format: IFormat; + title: IAnnotation; + + bounds: IRectangle; + position: string; + visible: boolean; + inverted: boolean; + padding: number; + align: number; + + fontColor: boolean; + + dividing: IStroke; + over: number; + symbol: ISymbol; + + itemHeight: number; + innerOff: number; + + legendStyle: string; + textStyle: string; + + availRows(): number; + itemsCount(): number; + totalWidth(): number; + showValues(): boolean; + itemText(series: ISeries, index: number): string; + isVertical(): boolean; + } + + interface IScroll { + chart: IChart; + active: boolean; + enabled: boolean; + direction: string; + mouseButton: number; + + position: IPoint; + } + + interface ISeriesList { + chart: IChart; + items: ISeries[]; + + anyUsesAxes(): boolean; + clicked(position: IPoint): boolean; + //each(f: function): void; + firstVisible(): ISeries; + + } + + interface ITools { + chart: IChart; + items: ITool[]; + + add(tool: ITool): ITool; + } + + interface IWall { + format: IFormat; + visible: boolean; + bounds: IRectangle; + } + + interface IWalls { + visible: boolean; + left: IWall; + right: IWall; + bottom: IWall; + back: IWall; + } + + interface IZoom { + chart: IChart; + active: boolean; + direction: string; + enabled: boolean; + mouseButton: number; + format: IFormat; + + reset(): void; + } + + interface IChart { + addSeries(series:ISeries): ISeries; + draw(context?:CanvasRenderingContext2D); + } + + // SERIES + + interface ICustomBar extends ISeries { + sideMargins: number; + useOrigin: boolean; + origin: number; + + offset: number; + barSize: number; + barStyle: string; + + stacked: string; + } + + interface ISeriesPointer { + chart: IChart; + format: IFormat; + visible: boolean; + colorEach: boolean; + style: string; + width: number; + height: number; + } + + interface ICustomSeries extends ISeries { + pointer: ISeriesPointer; + + stacked: string; + stairs: boolean; + } + + interface ILine extends ICustomSeries { + smooth: number; + } + + interface ISmoothLine extends ILine { + smooth: number; + } + + interface IArea extends ISeries { + useOrigin: boolean; + origin: number; + } + + interface IPie extends ISeries { + donut: number; + rotation: number; + sort: string; + orderAscending: boolean; + explode: number[]; + concentric: boolean; + + calcPos(angle: number, position: IPoint): void; + } + + interface IBubbleData extends ISeriesData { + radius: number[]; + } + + interface IBubble extends ICustomSeries { + data: IBubbleData; + } + + interface IGanttData extends ISeriesData { + start: number[]; + x: number[]; + end: number[]; + } + + interface IGantt extends ISeriesNoBounds { + data: IGanttData; + dateFormat: string; + colorEach: string; + height: number; + margin: IPoint; + + add(index: number, label: string, start: number, end: number): void; + bounds(index: number, rectangle: IRectangle): void; + } + + interface ICandleData extends ISeriesData { + open: number[]; + close: number[]; + high: number[]; + low: number[]; + } + + interface ICandle extends ICustomSeries { + data: ICandleData; + higher: IFormat; + lower: IFormat; + style: string; + } + + // TOOLS + + interface IDragTool extends ITool { + series: ISeries; + } + + interface ICursorTool extends ITool { + direction: string; + size: IPoint; + + followMouse: boolean; + dragging: number; + + format: IFormat; + + horizAxis: IAxis; + vertAxis: IAxis; + + render: string; + + over(point: IPoint): boolean; + setRender(render: string): void; + } + + interface IToolTip extends IAnnotation { + animated: number; + autoHide: boolean; + autoRedraw: boolean; + currentSeries: ISeries; + currentIndex: number; + delay: number; + + hide(): void; + refresh(series: ISeries, index: number): void; + } + + class Point implements IPoint { + public x:number; + public y:number; + } + + class Chart implements IChart { + //public aspect: IAspect; + + public axes: IAxes; + public footer: ITitle; + public legend: ILegend; + public panel: IPanel; + public scroll: IScroll; + public series: ISeriesList; + public title: ITitle; + public tools: ITools; + public walls: IWalls; + public zoom: IZoom; + + public bounds: IRectangle; + public canvas: HTMLCanvasElement; + public chartRect: IRectangle; + public palette: IPalette; + + constructor(canvas: string); + addSeries(series: ISeries): ISeries; + getSeries(index: number): ISeries; + removeSeries(series:ISeries): void; + + draw(context?:CanvasRenderingContext2D); + toImage(image: HTMLImageElement, format:string, quality:number): void; + } + + // SERIES + + var Line: { + prototype: ILine; + new(values?:number[]): ILine; + } + + var PointXY: { + prototype: ICustomSeries; + new(values?:number[]): ICustomSeries; + } + + var Area: { + prototype: IArea; + new(values?:number[]): IArea; + } + + var HorizArea: { + prototype: IArea; + new(values?:number[]): IArea; + } + + var Bar: { + prototype: ICustomBar; + new(values?:number[]): ICustomBar; + } + + var HorizBar: { + prototype: ICustomBar; + new(values?:number[]): ICustomBar; + } + + var Pie: { + prototype: IPie; + new(values?:number[]): IPie; + } + + var Donut: { + prototype: IPie; + new(values?:number[]): IPie; + } + + var Bubble: { + prototype: IBubble; + new(values?:number[]): IBubble; + } + + var Gantt: { + prototype: IGantt; + new(values?:number[]): IGantt; + } + + var Volume: { + prototype: ICustomBar; + new(values?:number[]): ICustomBar; + } + + var Candle: { + prototype: ICandle; + new(values?:number[]): ICandle; + } + + // TOOLS + + var CursorTool: { + prototype: ICursorTool; + new(chart?: Chart): ICursorTool; + } + + var DragTool: { + prototype: IDragTool; + new(chart?: Chart): IDragTool; + } + + var ToolTip: { + prototype: IToolTip; + new(chart?: Chart): IToolTip; + } +} diff --git a/teechart/teechart.d.ts.tscparams b/teechart/teechart.d.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/teechart/teechart.d.ts.tscparams +++ b/teechart/teechart.d.ts.tscparams @@ -1 +1 @@ - + diff --git a/threejs/three-tests.ts.tscparams b/threejs/three-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/threejs/three-tests.ts.tscparams +++ b/threejs/three-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/through/through-tests.ts b/through/through-tests.ts index 35822c9e8..83f8e8780 100644 --- a/through/through-tests.ts +++ b/through/through-tests.ts @@ -1,11 +1,11 @@ -/// - -import through = require('through'); - -var i = 0; -through( - function () { - this.queue((i++).toString()); - }, function () { - this.queue(null); - }, { autoDestroy: true }).pipe(process.stdout); +/// + +import through = require('through'); + +var i = 0; +through( + function () { + this.queue((i++).toString()); + }, function () { + this.queue(null); + }, { autoDestroy: true }).pipe(process.stdout); diff --git a/through/through.d.ts b/through/through.d.ts index 70a7d989c..afffcdcc1 100644 --- a/through/through.d.ts +++ b/through/through.d.ts @@ -1,24 +1,24 @@ -// Type definitions for through -// Project: https://github.com/dominictarr/through -// Definitions by: Andrew Gaspar -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare module "through" { - import stream = require("stream"); - - function through(write?: (data: any) => void, - end?: () => void, - opts?: { - autoDestroy: boolean; - }): through.ThroughStream; - - module through { - export interface ThroughStream extends stream.Transform { - autoDestroy: boolean; - } - } - - export = through; -} +// Type definitions for through +// Project: https://github.com/dominictarr/through +// Definitions by: Andrew Gaspar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "through" { + import stream = require("stream"); + + function through(write?: (data: any) => void, + end?: () => void, + opts?: { + autoDestroy: boolean; + }): through.ThroughStream; + + module through { + export interface ThroughStream extends stream.Transform { + autoDestroy: boolean; + } + } + + export = through; +} diff --git a/timezone-js/timezone-js.d.ts b/timezone-js/timezone-js.d.ts index 9aca2738e..069ed67c8 100644 --- a/timezone-js/timezone-js.d.ts +++ b/timezone-js/timezone-js.d.ts @@ -19,50 +19,50 @@ declare module "timezone-js" { setTimezone: (timezone: string) => void; // regular Date members - toString(): string; - toDateString(): string; - toTimeString(): string; - toLocaleString(): string; - toLocaleDateString(): string; - toLocaleTimeString(): string; - valueOf(): number; - getTime(): number; - getFullYear(): number; - getUTCFullYear(): number; - getMonth(): number; - getUTCMonth(): number; - getDate(): number; - getUTCDate(): number; - getDay(): number; - getUTCDay(): number; - getHours(): number; - getUTCHours(): number; - getMinutes(): number; - getUTCMinutes(): number; - getSeconds(): number; - getUTCSeconds(): number; - getMilliseconds(): number; - getUTCMilliseconds(): number; - getTimezoneOffset(): number; - setTime(time: number): number; - - // Note the setters have a non-void return type. Date has them as well, according to TypeScript - setMilliseconds(ms: number): number; - setUTCMilliseconds(ms: number): number; - setSeconds(sec: number, ms?: number): number; - setUTCSeconds(sec: number, ms?: number): number; - setMinutes(min: number, sec?: number, ms?: number): number; - setUTCMinutes(min: number, sec?: number, ms?: number): number; - setHours(hours: number, min?: number, sec?: number, ms?: number): number; - setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number; - setDate(date: number): number; - setUTCDate(date: number): number; - setMonth(month: number, date?: number): number; - setUTCMonth(month: number, date?: number): number; - setFullYear(year: number, month?: number, date?: number): number; - setUTCFullYear(year: number, month?: number, date?: number): number; - toUTCString(): string; - toISOString(): string; + toString(): string; + toDateString(): string; + toTimeString(): string; + toLocaleString(): string; + toLocaleDateString(): string; + toLocaleTimeString(): string; + valueOf(): number; + getTime(): number; + getFullYear(): number; + getUTCFullYear(): number; + getMonth(): number; + getUTCMonth(): number; + getDate(): number; + getUTCDate(): number; + getDay(): number; + getUTCDay(): number; + getHours(): number; + getUTCHours(): number; + getMinutes(): number; + getUTCMinutes(): number; + getSeconds(): number; + getUTCSeconds(): number; + getMilliseconds(): number; + getUTCMilliseconds(): number; + getTimezoneOffset(): number; + setTime(time: number): number; + + // Note the setters have a non-void return type. Date has them as well, according to TypeScript + setMilliseconds(ms: number): number; + setUTCMilliseconds(ms: number): number; + setSeconds(sec: number, ms?: number): number; + setUTCSeconds(sec: number, ms?: number): number; + setMinutes(min: number, sec?: number, ms?: number): number; + setUTCMinutes(min: number, sec?: number, ms?: number): number; + setHours(hours: number, min?: number, sec?: number, ms?: number): number; + setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number; + setDate(date: number): number; + setUTCDate(date: number): number; + setMonth(month: number, date?: number): number; + setUTCMonth(month: number, date?: number): number; + setFullYear(year: number, month?: number, date?: number): number; + setUTCFullYear(year: number, month?: number, date?: number): number; + toUTCString(): string; + toISOString(): string; toJSON(key?: any): string; } diff --git a/timezonecomplete/timezonecomplete-tests.ts b/timezonecomplete/timezonecomplete-tests.ts index cb1c69282..b08cb20b6 100644 --- a/timezonecomplete/timezonecomplete-tests.ts +++ b/timezonecomplete/timezonecomplete-tests.ts @@ -1,234 +1,234 @@ -/// - -import tc = require("timezonecomplete"); - -var b: boolean; -var n: number; -var s: string; -var w: tc.WeekDay; - -n = tc.timeUnitToMilliseconds(tc.TimeUnit.Month); -b = tc.isLeapYear(2014); -n = tc.daysInMonth(2014, 10); -n = tc.daysInYear(2014); -n = tc.dayOfYear(2014, 1, 2); -w = tc.firstWeekDayOfMonth(2014, 1, tc.WeekDay.Sunday); -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); -n = tc.secondOfDay(13, 59, 59); -n = tc.weekOfMonth(2014, 1, 1); - -s = tc.timeUnitToString(tc.TimeUnit.Second); -var tu: tc.TimeUnit = tc.stringToTimeUnit("bla"); - -// 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 = tc.hours(24); -var d6: tc.Duration = tc.minutes(24); -var d7: tc.Duration = tc.seconds(24); -var d8: tc.Duration = tc.milliseconds(24); -var d9: tc.Duration = new tc.Duration(24); -var d10: tc.Duration = new tc.Duration("00:01"); -var d11: tc.Duration = d6.clone(); -var d12: tc.Duration = new tc.Duration(4, tc.TimeUnit.Second); - -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(); - -b = d7.equals(d6); -b = d7.equalsExact(d6); -b = d7.identical(d6); - -// 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"); -t = tc.local(); -t = tc.utc(); -t = tc.zone(2); -t = tc.zone("+01:00"); -t = tc.zone("Europe/Amsterdam", false); -s = t.name(); -k = t.kind(); -b = t.equals(t); -b = t.isUtc(); -b = t.dst(); -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"); -b = t.equals(t); -b = t.identical(t); - -// 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 = tc.DateTime.fromExcel(1.5); -dt = tc.nowLocal(); -dt = tc.nowUtc(); -dt = tc.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.weekNumber(); -n = dt.weekOfMonth(); -n = dt.secondOfDay(); -n = dt.dayOfYear(); -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(); -n = dt.utcWeekNumber(); -n = dt.utcWeekOfMonth(); -n = dt.utcSecondOfDay(); -n = dt.utcDayOfYear(); -s = dt.format("%Y-%m-%d"); -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.addLocal(tc.minutes(2)); -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); -dt = dt.subLocal(tc.minutes(2)); -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())); -dt = dt.min(new tc.DateTime(9289234, tc.TimeZone.local())); -dt = dt.max(new tc.DateTime(9289234, tc.TimeZone.local())); -s = dt.toIsoString(); -s = dt.toString(); -s = dt.toUtcString(); -dt = dt.startOfDay(); - -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); -p = new tc.Period(tc.DateTime.nowLocal(), tc.hours(1), 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(); -b = p.isBoundary(dt); -b = p.equals(p); -b = p.identical(p); - - -// GLOBALS -d = tc.min(tc.Duration.seconds(2), tc.Duration.seconds(3)); -d = tc.max(tc.Duration.seconds(2), tc.Duration.seconds(3)); - -dt = tc.min(new tc.DateTime(2), new tc.DateTime(3)); -dt = tc.max(new tc.DateTime(2), new tc.DateTime(3)); - - - - - - - - - - - - - - - - - - - - - - +/// + +import tc = require("timezonecomplete"); + +var b: boolean; +var n: number; +var s: string; +var w: tc.WeekDay; + +n = tc.timeUnitToMilliseconds(tc.TimeUnit.Month); +b = tc.isLeapYear(2014); +n = tc.daysInMonth(2014, 10); +n = tc.daysInYear(2014); +n = tc.dayOfYear(2014, 1, 2); +w = tc.firstWeekDayOfMonth(2014, 1, tc.WeekDay.Sunday); +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); +n = tc.secondOfDay(13, 59, 59); +n = tc.weekOfMonth(2014, 1, 1); + +s = tc.timeUnitToString(tc.TimeUnit.Second); +var tu: tc.TimeUnit = tc.stringToTimeUnit("bla"); + +// 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 = tc.hours(24); +var d6: tc.Duration = tc.minutes(24); +var d7: tc.Duration = tc.seconds(24); +var d8: tc.Duration = tc.milliseconds(24); +var d9: tc.Duration = new tc.Duration(24); +var d10: tc.Duration = new tc.Duration("00:01"); +var d11: tc.Duration = d6.clone(); +var d12: tc.Duration = new tc.Duration(4, tc.TimeUnit.Second); + +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(); + +b = d7.equals(d6); +b = d7.equalsExact(d6); +b = d7.identical(d6); + +// 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"); +t = tc.local(); +t = tc.utc(); +t = tc.zone(2); +t = tc.zone("+01:00"); +t = tc.zone("Europe/Amsterdam", false); +s = t.name(); +k = t.kind(); +b = t.equals(t); +b = t.isUtc(); +b = t.dst(); +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"); +b = t.equals(t); +b = t.identical(t); + +// 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 = tc.DateTime.fromExcel(1.5); +dt = tc.nowLocal(); +dt = tc.nowUtc(); +dt = tc.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.weekNumber(); +n = dt.weekOfMonth(); +n = dt.secondOfDay(); +n = dt.dayOfYear(); +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(); +n = dt.utcWeekNumber(); +n = dt.utcWeekOfMonth(); +n = dt.utcSecondOfDay(); +n = dt.utcDayOfYear(); +s = dt.format("%Y-%m-%d"); +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.addLocal(tc.minutes(2)); +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); +dt = dt.subLocal(tc.minutes(2)); +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())); +dt = dt.min(new tc.DateTime(9289234, tc.TimeZone.local())); +dt = dt.max(new tc.DateTime(9289234, tc.TimeZone.local())); +s = dt.toIsoString(); +s = dt.toString(); +s = dt.toUtcString(); +dt = dt.startOfDay(); + +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); +p = new tc.Period(tc.DateTime.nowLocal(), tc.hours(1), 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(); +b = p.isBoundary(dt); +b = p.equals(p); +b = p.identical(p); + + +// GLOBALS +d = tc.min(tc.Duration.seconds(2), tc.Duration.seconds(3)); +d = tc.max(tc.Duration.seconds(2), tc.Duration.seconds(3)); + +dt = tc.min(new tc.DateTime(2), new tc.DateTime(3)); +dt = tc.max(new tc.DateTime(2), new tc.DateTime(3)); + + + + + + + + + + + + + + + + + + + + + + diff --git a/timezonecomplete/timezonecomplete.d.ts b/timezonecomplete/timezonecomplete.d.ts index 635f4558f..a9c54e6a0 100644 --- a/timezonecomplete/timezonecomplete.d.ts +++ b/timezonecomplete/timezonecomplete.d.ts @@ -1,1519 +1,1519 @@ -// Type definitions for timezonecomplete 1.15.0 -// Project: https://github.com/SpiritIT/timezonecomplete -// Definitions by: Rogier Schouten -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module 'timezonecomplete' { - import basics = require("__timezonecomplete/basics"); - export import TimeUnit = basics.TimeUnit; - export import WeekDay = basics.WeekDay; - export import timeUnitToMilliseconds = basics.timeUnitToMilliseconds; - export import isLeapYear = basics.isLeapYear; - export import daysInMonth = basics.daysInMonth; - export import daysInYear = basics.daysInYear; - export import firstWeekDayOfMonth = basics.firstWeekDayOfMonth; - export import lastWeekDayOfMonth = basics.lastWeekDayOfMonth; - export import weekDayOnOrAfter = basics.weekDayOnOrAfter; - export import weekDayOnOrBefore = basics.weekDayOnOrBefore; - export import weekNumber = basics.weekNumber; - export import weekOfMonth = basics.weekOfMonth; - export import dayOfYear = basics.dayOfYear; - export import secondOfDay = basics.secondOfDay; - export import timeUnitToString = basics.timeUnitToString; - export import stringToTimeUnit = basics.stringToTimeUnit; - import datetime = require("__timezonecomplete/datetime"); - export import DateTime = datetime.DateTime; - export import now = datetime.now; - export import nowLocal = datetime.nowLocal; - export import nowUtc = datetime.nowUtc; - import duration = require("__timezonecomplete/duration"); - export import Duration = duration.Duration; - export import years = duration.years; - export import months = duration.months; - export import days = duration.days; - export import hours = duration.hours; - export import minutes = duration.minutes; - export import seconds = duration.seconds; - export import milliseconds = duration.milliseconds; - 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; - export import local = timezone.local; - export import utc = timezone.utc; - export import zone = timezone.zone; - import globals = require("__timezonecomplete/globals"); - export import min = globals.min; - export import max = globals.max; -} - -declare module '__timezonecomplete/basics' { - import javascript = require("__timezonecomplete/javascript"); - import DateFunctions = javascript.DateFunctions; - /** - * 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, - } - /** - * Time units - */ - export enum TimeUnit { - Millisecond = 0, - Second = 1, - Minute = 2, - Hour = 3, - Day = 4, - Week = 5, - Month = 6, - Year = 7, - /** - * End-of-enum marker, do not use - */ - MAX = 8, - } - /** - * Approximate number of milliseconds for a time unit. - * A day is assumed to have 24 hours, a month is assumed to equal 30 days - * and a year is set to 360 days (because 12 months of 30 days). - * - * @param unit Time unit e.g. TimeUnit.Month - * @returns The number of milliseconds. - */ - export function timeUnitToMilliseconds(unit: TimeUnit): number; - /** - * Time unit to lowercase string. If amount is specified, then the string is put in plural form - * if necessary. - * @param unit The unit - * @param amount If this is unequal to -1 and 1, then the result is pluralized - */ - export function timeUnitToString(unit: TimeUnit, amount?: number): string; - export function stringToTimeUnit(s: string): TimeUnit; - /** - * @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 first 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 first occurrence of the week day in the month - */ - export function firstWeekDayOfMonth(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; - /** - * The week of this month. There is no official standard for this, - * but we assume the same rules for the weekNumber (i.e. - * week 1 is the week that has the 4th day of the month in it) - * - * @param year The year - * @param month The month [1-12] - * @param day The day [1-31] - * @return Week number [1-5] - */ - export function weekOfMonth(year: number, month: number, day: number): number; - /** - * The ISO 8601 week number for the given date. Week 1 is the week - * that has January 4th in it, and it starts on Monday. - * See https://en.wikipedia.org/wiki/ISO_week_date - * - * @param year Year e.g. 1988 - * @param month Month 1-12 - * @param day Day of month 1-31 - * - * @return Week number 1-53 - */ - export function weekNumber(year: number, month: number, day: number): 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; - /** - * N-th second in the day, counting from 0 - */ - export function secondOfDay(hour: number, minute: number, second: number): number; - /** - * 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: 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 WeekDay = basics.WeekDay; - import TimeUnit = basics.TimeUnit; - import duration = require("__timezonecomplete/duration"); - import Duration = duration.Duration; - import javascript = require("__timezonecomplete/javascript"); - import DateFunctions = javascript.DateFunctions; - import timesource = require("__timezonecomplete/timesource"); - import TimeSource = timesource.TimeSource; - import timezone = require("__timezonecomplete/timezone"); - import TimeZone = timezone.TimeZone; - /** - * Current date+time in local time - */ - export function nowLocal(): DateTime; - /** - * Current date+time in UTC time - */ - export function nowUtc(): DateTime; - /** - * Current date+time in the given time zone - * @param timeZone The desired time zone (optional, defaults to UTC). - */ - export function now(timeZone?: TimeZone): DateTime; - /** - * 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 - */ - static nowLocal(): DateTime; - /** - * Current date+time in UTC time - */ - static nowUtc(): DateTime; - /** - * Current date+time in the given time zone - * @param timeZone The desired time zone (optional, defaults to UTC). - */ - static now(timeZone?: TimeZone): DateTime; - /** - * Create a DateTime from a Lotus 123 / Microsoft Excel date-time value - * i.e. a double representing days since 1-1-1900 where 1900 is incorrectly seen as leap year - */ - static fromExcel(n: number, 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); - /** - * 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: 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; - /** - * Zone name abbreviation at this time - * @param dstDependent (default true) set to false for a DST-agnostic abbreviation - * @return The abbreviation - */ - zoneAbbreviation(dstDependent?: boolean): string; - /** - * @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; - /** - * Returns the day number within the year: Jan 1st has number 0, - * Jan 2nd has number 1 etc. - * - * @return the day-of-year [0-366] - */ - dayOfYear(): number; - /** - * The ISO 8601 week number. Week 1 is the week - * that has January 4th in it, and it starts on Monday. - * See https://en.wikipedia.org/wiki/ISO_week_date - * - * @return Week number [1-53] - */ - weekNumber(): number; - /** - * The week of this month. There is no official standard for this, - * but we assume the same rules for the weekNumber (i.e. - * week 1 is the week that has the 4th day of the month in it) - * - * @return Week number [1-5] - */ - weekOfMonth(): number; - /** - * Returns the number of seconds that have passed on the current day - * Does not consider leap seconds - * - * @return seconds [0-86399] - */ - secondOfDay(): 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; - /** - * Returns the UTC day number within the year: Jan 1st has number 0, - * Jan 2nd has number 1 etc. - * - * @return the day-of-year [0-366] - */ - utcDayOfYear(): 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; - /** - * The ISO 8601 UTC week number. Week 1 is the week - * that has January 4th in it, and it starts on Monday. - * See https://en.wikipedia.org/wiki/ISO_week_date - * - * @return Week number [1-53] - */ - utcWeekNumber(): number; - /** - * The week of this month. There is no official standard for this, - * but we assume the same rules for the weekNumber (i.e. - * week 1 is the week that has the 4th day of the month in it) - * - * @return Week number [1-5] - */ - utcWeekOfMonth(): number; - /** - * Returns the number of seconds that have passed on the current day - * Does not consider leap seconds - * - * @return seconds [0-86399] - */ - utcSecondOfDay(): 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) - * 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): 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. - * @return this + duration - */ - add(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: 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(duration: Duration): DateTime; - 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(duration: Duration): DateTime; - subLocal(amount: number, unit: TimeUnit): DateTime; - /** - * Time difference between two DateTimes - * @return this - other - */ - diff(other: DateTime): Duration; - /** - * Chops off the time part, yields the same date at 00:00:00.000 - * @return a new DateTime - */ - startOfDay(): DateTime; - /** - * @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 moment in time in UTC - */ - equals(other: DateTime): boolean; - /** - * @return True iff this and other represent the same time and 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; - /** - * @return The minimum of this and other - */ - min(other: DateTime): DateTime; - /** - * @return The maximum of this and other - */ - max(other: DateTime): DateTime; - /** - * 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; - /** - * Return a string representation of the DateTime according to the - * specified format. The format is implemented as the LDML standard - * (http://unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns) - * - * @param formatString The format specification (e.g. "dd/MM/yyyy HH:mm:ss") - * @return The string representation of this DateTime - */ - format(formatString: string): 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; - /** - * The valueOf() method returns the primitive value of the specified object. - */ - valueOf(): any; - /** - * Modified ISO 8601 format string in UTC without time zone info - */ - toUtcString(): string; - } -} - -declare module '__timezonecomplete/duration' { - import basics = require("__timezonecomplete/basics"); - import TimeUnit = basics.TimeUnit; - /** - * Construct a time duration - * @param n Number of years (may be fractional or negative) - * @return A duration of n years - */ - export function years(n: number): Duration; - /** - * Construct a time duration - * @param n Number of months (may be fractional or negative) - * @return A duration of n months - */ - export function months(n: number): Duration; - /** - * Construct a time duration - * @param n Number of days (may be fractional or negative) - * @return A duration of n days - */ - export function days(n: number): Duration; - /** - * Construct a time duration - * @param n Number of hours (may be fractional or negative) - * @return A duration of n hours - */ - export function hours(n: number): Duration; - /** - * Construct a time duration - * @param n Number of minutes (may be fractional or negative) - * @return A duration of n minutes - */ - export function minutes(n: number): Duration; - /** - * Construct a time duration - * @param n Number of seconds (may be fractional or negative) - * @return A duration of n seconds - */ - export function seconds(n: number): Duration; - /** - * Construct a time duration - * @param n Number of milliseconds (may be fractional or negative) - * @return A duration of n milliseconds - */ - export function milliseconds(n: number): Duration; - /** - * Time duration which is represented as an amount and a unit e.g. - * '1 Month' or '166 Seconds'. The unit is preserved through calculations. - * - * It has two sets of getter functions: - * - second(), minute(), hour() etc, singular form: these can be used to create string representations. - * These return a part of your string representation. E.g. for 2500 milliseconds, the millisecond() part would be 500 - * - seconds(), minutes(), hours() etc, plural form: these return the total amount represented in the corresponding unit. - */ - export class Duration { - /** - * Construct a time duration - * @param n Number of years (may be fractional or negative) - * @return A duration of n years - */ - static years(n: number): Duration; - /** - * Construct a time duration - * @param n Number of months (may be fractional or negative) - * @return A duration of n months - */ - static months(n: number): Duration; - /** - * Construct a time duration - * @param n Number of days (may be fractional or negative) - * @return A duration of n days - */ - static days(n: number): Duration; - /** - * Construct a time duration - * @param n Number of hours (may be fractional or negative) - * @return A duration of n hours - */ - static hours(n: number): Duration; - /** - * Construct a time duration - * @param n Number of minutes (may be fractional or negative) - * @return A duration of n minutes - */ - static minutes(n: number): Duration; - /** - * Construct a time duration - * @param n Number of seconds (may be fractional or negative) - * @return A duration of n seconds - */ - static seconds(n: number): Duration; - /** - * Construct a time duration - * @param n Number of milliseconds (may be fractional or negative) - * @return A duration of n milliseconds - */ - static milliseconds(n: number): Duration; - /** - * Construct a time duration of 0 - */ - constructor(); - /** - * Construct a time duration from a string in one of two formats: - * 1) [-]hhhh[:mm[:ss[.nnn]]] e.g. '-01:00:30.501' - * 2) amount and unit e.g. '-1 days' or '1 year'. The unit may be in singular or plural form and is case-insensitive - */ - constructor(input: string); - /** - * Construct a duration from an amount and a time unit. - * @param amount Number of units - * @param unit A time unit i.e. TimeUnit.Second, TimeUnit.Hour etc. Default Millisecond. - */ - constructor(amount: number, unit?: TimeUnit); - /** - * @return another instance of Duration with the same value. - */ - clone(): Duration; - /** - * Returns this duration expressed in different unit (positive or negative, fractional). - * This is precise for Year <-> Month and for time-to-time conversion (i.e. Hour-or-less to Hour-or-less). - * It is approximate for any other conversion - */ - as(unit: TimeUnit): number; - /** - * Convert this duration to a Duration in another unit. You always get a clone even if you specify - * the same unit. - * This is precise for Year <-> Month and for time-to-time conversion (i.e. Hour-or-less to Hour-or-less). - * It is approximate for any other conversion - */ - convert(unit: TimeUnit): Duration; - /** - * The entire duration in milliseconds (negative or positive) - * For Day/Month/Year durations, this is approximate! - */ - milliseconds(): number; - /** - * The millisecond part of the duration (always positive) - * For Day/Month/Year durations, this is approximate! - * @return e.g. 400 for a -01:02:03.400 duration - */ - millisecond(): number; - /** - * The entire duration in seconds (negative or positive, fractional) - * For Day/Month/Year durations, this is approximate! - * @return e.g. 1.5 for a 1500 milliseconds duration - */ - seconds(): number; - /** - * The second part of the duration (always positive) - * For Day/Month/Year durations, this is approximate! - * @return e.g. 3 for a -01:02:03.400 duration - */ - second(): number; - /** - * The entire duration in minutes (negative or positive, fractional) - * For Day/Month/Year durations, this is approximate! - * @return e.g. 1.5 for a 90000 milliseconds duration - */ - minutes(): number; - /** - * The minute part of the duration (always positive) - * For Day/Month/Year durations, this is approximate! - * @return e.g. 2 for a -01:02:03.400 duration - */ - minute(): number; - /** - * The entire duration in hours (negative or positive, fractional) - * For Day/Month/Year durations, this is approximate! - * @return e.g. 1.5 for a 5400000 milliseconds duration - */ - hours(): number; - /** - * The hour part of a duration. This assumes that a day has 24 hours (which is not the case - * during DST changes). - */ - hour(): number; - /** - * DEPRECATED - * 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 - * For Day/Month/Year durations, this is approximate! - * @return e.g. 25 for a -25:02:03.400 duration - */ - wholeHours(): number; - /** - * The entire duration in days (negative or positive, fractional) - * This is approximate if this duration is not in days! - */ - days(): number; - /** - * The day part of a duration. This assumes that a month has 30 days. - */ - day(): number; - /** - * The entire duration in days (negative or positive, fractional) - * This is approximate if this duration is not in Months or Years! - */ - months(): number; - /** - * The month part of a duration. - */ - month(): number; - /** - * The entire duration in years (negative or positive, fractional) - * This is approximate if this duration is not in Months or Years! - */ - years(): number; - /** - * Non-fractional positive years - */ - wholeYears(): number; - /** - * Amount of units (positive or negative, fractional) - */ - amount(): number; - /** - * The unit this duration was created with - */ - unit(): TimeUnit; - /** - * Sign - * @return "-" if the duration is negative - */ - sign(): string; - /** - * Approximate if the durations have units that cannot be converted - * @return True iff (this < other) - */ - lessThan(other: Duration): boolean; - /** - * Approximate if the durations have units that cannot be converted - * @return True iff (this <= other) - */ - lessEqual(other: Duration): boolean; - /** - * Similar but not identical - * Approximate if the durations have units that cannot be converted - * @return True iff this and other represent the same time duration - */ - equals(other: Duration): boolean; - /** - * Similar but not identical - * Returns false if we cannot determine whether they are equal in all time zones - * so e.g. 60 minutes equals 1 hour, but 24 hours do NOT equal 1 day - * - * @return True iff this and other represent the same time duration - */ - equalsExact(other: Duration): boolean; - /** - * Same unit and same amount - */ - identical(other: Duration): boolean; - /** - * Approximate if the durations have units that cannot be converted - * @return True iff this > other - */ - greaterThan(other: Duration): boolean; - /** - * Approximate if the durations have units that cannot be converted - * @return True iff this >= other - */ - greaterEqual(other: Duration): boolean; - /** - * Approximate if the durations have units that cannot be converted - * @return The minimum (most negative) of this and other - */ - min(other: Duration): Duration; - /** - * Approximate if the durations have units that cannot be converted - * @return The maximum (most positive) of this and other - */ - max(other: Duration): Duration; - /** - * Approximate if the durations have units that cannot be converted - * Multiply with a fixed number. - * @return a new Duration of (this * value) - */ - multiply(value: number): Duration; - /** - * Approximate if the durations have units that cannot be converted - * 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) with the unit of this duration - */ - add(value: Duration): Duration; - /** - * Subtract a duration. - * @return a new Duration of (this - value) with the unit of this duration - */ - sub(value: Duration): Duration; - /** - * Return the absolute value of the duration i.e. remove the sign. - */ - abs(): Duration; - /** - * DEPRECATED - * String in [-]hhhh:mm:ss.nnn notation. All fields are - * always present except the sign. - */ - toFullString(): string; - /** - * String in [-]hhhh:mm[:ss[.nnn]] notation. - * @param full If true, then all fields are always present except the sign. Otherwise, seconds and milliseconds - * are chopped off if zero - */ - toHmsString(full?: boolean): string; - /** - * String in ISO 8601 notation e.g. 'P1M' for one month or 'PT1M' for one minute - */ - toIsoString(): string; - /** - * String representation with amount and unit e.g. '1.5 years' or '-1 day' - */ - toString(): string; - /** - * Used by util.inspect() - */ - inspect(): string; - /** - * The valueOf() method returns the primitive value of the specified object. - */ - valueOf(): any; - } -} - -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(), getUtcMonth() 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, - } -} - -declare module '__timezonecomplete/period' { - import basics = require("__timezonecomplete/basics"); - import TimeUnit = basics.TimeUnit; - import duration = require("__timezonecomplete/duration"); - import Duration = duration.Duration; - import datetime = require("__timezonecomplete/datetime"); - import DateTime = datetime.DateTime; - /** - * 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, - /** - * End-of-enum marker - */ - MAX = 2, - } - /** - * 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 interval The interval of the period - * @param dst Specifies how to handle Daylight Saving Time. Not relevant - * if the time zone of the start datetime does not have DST. - * Defaults to RegularLocalTime. - */ - constructor(start: DateTime, interval: Duration, dst?: PeriodDst); - /** - * 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. - * Defaults to RegularLocalTime. - */ - constructor(start: DateTime, amount: number, unit: TimeUnit, dst?: PeriodDst); - /** - * The start date - */ - start(): DateTime; - /** - * The interval - */ - interval(): Duration; - /** - * DEPRECATED - * The amount of units of the interval - */ - amount(): number; - /** - * DEPRECATED - * The unit of the interval - */ - 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; - /** - * Checks whether the given date is on a period boundary - * (expensive!) - */ - isBoundary(occurrence: DateTime): boolean; - /** - * Returns true iff this period has the same effect as the given one. - * i.e. a period of 24 hours is equal to one of 1 day if they have the same UTC start moment - * and same dst. - */ - equals(other: Period): boolean; - /** - * Returns true iff this period was constructed with identical arguments to the other one. - */ - identical(other: Period): boolean; - /** - * 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". - */ - 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"); - import DateFunctions = javascript.DateFunctions; - /** - * The local time zone for a given date as per OS settings. Note that time zones are cached - * so you don't necessarily get a new object each time. - */ - export function local(): TimeZone; - /** - * Coordinated Universal Time zone. Note that time zones are cached - * so you don't necessarily get a new object each time. - */ - export function utc(): TimeZone; - /** - * @param offset offset w.r.t. UTC in minutes, e.g. 90 for +01:30. Note that time zones are cached - * so you don't necessarily get a new object each time. - * @returns a time zone with the given fixed offset - */ - export function zone(offset: number): TimeZone; - /** - * Time zone for an offset string or an IANA time zone string. Note that time zones are cached - * so you don't necessarily get a new object each time. - * @param s Empty string for no time zone (null is returned), - * "localtime" 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 - * @param dst Optional, default true: adhere to Daylight Saving Time if applicable. Note for - * "localtime", timezonecomplete will adhere to the computer settings, the DST flag - * does not have any effect. - */ - export function zone(name: string, dst?: boolean): TimeZone; - /** - * 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; - /** - * Time zone with a fixed offset - * @param offset offset w.r.t. UTC in minutes, e.g. 90 for +01:30 - */ - static zone(offset: number): TimeZone; - /** - * Time zone for an offset string or an IANA time zone string. Note that time zones are cached - * so you don't necessarily get a new object each time. - * @param s Empty string for no time zone (null is returned), - * "localtime" 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 - * TZ database zone name may be suffixed with " without DST" to indicate no DST should be applied. - * In that case, the dst parameter is ignored. - * @param dst Optional, default true: adhere to Daylight Saving Time if applicable. Note for - * "localtime", timezonecomplete will adhere to the computer settings, the DST flag - * does not have any effect. - */ - static zone(s: string, dst?: boolean): TimeZone; - /** - * Do not use this constructor, use the static - * TimeZone.zone() method instead. - * @param name NORMALIZED name, assumed to be correct - * @param dst Adhere to Daylight Saving Time if applicable, ignored for local time and fixed offsets - */ - constructor(name: string, dst?: boolean); - /** - * 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; - dst(): boolean; - /** - * 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; - /** - * Returns true iff the constructor arguments were identical, so UTC !== GMT - */ - identical(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 Full year - * @param month Month 1-12 (note this deviates from JavaScript date) - * @param day Day of month 1-31 - * @param hour Hour 0-23 - * @param minute Minute 0-59 - * @param second Second 0-59 - * @param millisecond 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: 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: DateFunctions): number; - /** - * Zone abbreviation at given UTC timestamp e.g. CEST for Central European Summer Time. - * - * @param year Full year - * @param month Month 1-12 (note this deviates from JavaScript date) - * @param day Day of month 1-31 - * @param hour Hour 0-23 - * @param minute Minute 0-59 - * @param second Second 0-59 - * @param millisecond Millisecond 0-999 - * @param dstDependent (default true) set to false for a DST-agnostic abbreviation - * - * @return "local" for local timezone, the offset for an offset zone, or the abbreviation for a proper zone. - */ - abbreviationForUtc(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number, dstDependent?: boolean): string; - /** - * 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; - } -} - -declare module '__timezonecomplete/globals' { - import datetime = require("__timezonecomplete/datetime"); - import DateTime = datetime.DateTime; - import duration = require("__timezonecomplete/duration"); - import Duration = duration.Duration; - /** - * Returns the minimum of two DateTimes - */ - export function min(d1: DateTime, d2: DateTime): DateTime; - /** - * Returns the minimum of two Durations - */ - export function min(d1: Duration, d2: Duration): Duration; - /** - * Returns the maximum of two DateTimes - */ - export function max(d1: DateTime, d2: DateTime): DateTime; - /** - * Returns the maximum of two Durations - */ - export function max(d1: Duration, d2: Duration): Duration; - /** - * Returns the absolute value of a Duration - */ - export function abs(d: Duration): Duration; -} +// Type definitions for timezonecomplete 1.15.0 +// Project: https://github.com/SpiritIT/timezonecomplete +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module 'timezonecomplete' { + import basics = require("__timezonecomplete/basics"); + export import TimeUnit = basics.TimeUnit; + export import WeekDay = basics.WeekDay; + export import timeUnitToMilliseconds = basics.timeUnitToMilliseconds; + export import isLeapYear = basics.isLeapYear; + export import daysInMonth = basics.daysInMonth; + export import daysInYear = basics.daysInYear; + export import firstWeekDayOfMonth = basics.firstWeekDayOfMonth; + export import lastWeekDayOfMonth = basics.lastWeekDayOfMonth; + export import weekDayOnOrAfter = basics.weekDayOnOrAfter; + export import weekDayOnOrBefore = basics.weekDayOnOrBefore; + export import weekNumber = basics.weekNumber; + export import weekOfMonth = basics.weekOfMonth; + export import dayOfYear = basics.dayOfYear; + export import secondOfDay = basics.secondOfDay; + export import timeUnitToString = basics.timeUnitToString; + export import stringToTimeUnit = basics.stringToTimeUnit; + import datetime = require("__timezonecomplete/datetime"); + export import DateTime = datetime.DateTime; + export import now = datetime.now; + export import nowLocal = datetime.nowLocal; + export import nowUtc = datetime.nowUtc; + import duration = require("__timezonecomplete/duration"); + export import Duration = duration.Duration; + export import years = duration.years; + export import months = duration.months; + export import days = duration.days; + export import hours = duration.hours; + export import minutes = duration.minutes; + export import seconds = duration.seconds; + export import milliseconds = duration.milliseconds; + 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; + export import local = timezone.local; + export import utc = timezone.utc; + export import zone = timezone.zone; + import globals = require("__timezonecomplete/globals"); + export import min = globals.min; + export import max = globals.max; +} + +declare module '__timezonecomplete/basics' { + import javascript = require("__timezonecomplete/javascript"); + import DateFunctions = javascript.DateFunctions; + /** + * 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, + } + /** + * Time units + */ + export enum TimeUnit { + Millisecond = 0, + Second = 1, + Minute = 2, + Hour = 3, + Day = 4, + Week = 5, + Month = 6, + Year = 7, + /** + * End-of-enum marker, do not use + */ + MAX = 8, + } + /** + * Approximate number of milliseconds for a time unit. + * A day is assumed to have 24 hours, a month is assumed to equal 30 days + * and a year is set to 360 days (because 12 months of 30 days). + * + * @param unit Time unit e.g. TimeUnit.Month + * @returns The number of milliseconds. + */ + export function timeUnitToMilliseconds(unit: TimeUnit): number; + /** + * Time unit to lowercase string. If amount is specified, then the string is put in plural form + * if necessary. + * @param unit The unit + * @param amount If this is unequal to -1 and 1, then the result is pluralized + */ + export function timeUnitToString(unit: TimeUnit, amount?: number): string; + export function stringToTimeUnit(s: string): TimeUnit; + /** + * @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 first 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 first occurrence of the week day in the month + */ + export function firstWeekDayOfMonth(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; + /** + * The week of this month. There is no official standard for this, + * but we assume the same rules for the weekNumber (i.e. + * week 1 is the week that has the 4th day of the month in it) + * + * @param year The year + * @param month The month [1-12] + * @param day The day [1-31] + * @return Week number [1-5] + */ + export function weekOfMonth(year: number, month: number, day: number): number; + /** + * The ISO 8601 week number for the given date. Week 1 is the week + * that has January 4th in it, and it starts on Monday. + * See https://en.wikipedia.org/wiki/ISO_week_date + * + * @param year Year e.g. 1988 + * @param month Month 1-12 + * @param day Day of month 1-31 + * + * @return Week number 1-53 + */ + export function weekNumber(year: number, month: number, day: number): 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; + /** + * N-th second in the day, counting from 0 + */ + export function secondOfDay(hour: number, minute: number, second: number): number; + /** + * 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: 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 WeekDay = basics.WeekDay; + import TimeUnit = basics.TimeUnit; + import duration = require("__timezonecomplete/duration"); + import Duration = duration.Duration; + import javascript = require("__timezonecomplete/javascript"); + import DateFunctions = javascript.DateFunctions; + import timesource = require("__timezonecomplete/timesource"); + import TimeSource = timesource.TimeSource; + import timezone = require("__timezonecomplete/timezone"); + import TimeZone = timezone.TimeZone; + /** + * Current date+time in local time + */ + export function nowLocal(): DateTime; + /** + * Current date+time in UTC time + */ + export function nowUtc(): DateTime; + /** + * Current date+time in the given time zone + * @param timeZone The desired time zone (optional, defaults to UTC). + */ + export function now(timeZone?: TimeZone): DateTime; + /** + * 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 + */ + static nowLocal(): DateTime; + /** + * Current date+time in UTC time + */ + static nowUtc(): DateTime; + /** + * Current date+time in the given time zone + * @param timeZone The desired time zone (optional, defaults to UTC). + */ + static now(timeZone?: TimeZone): DateTime; + /** + * Create a DateTime from a Lotus 123 / Microsoft Excel date-time value + * i.e. a double representing days since 1-1-1900 where 1900 is incorrectly seen as leap year + */ + static fromExcel(n: number, 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); + /** + * 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: 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; + /** + * Zone name abbreviation at this time + * @param dstDependent (default true) set to false for a DST-agnostic abbreviation + * @return The abbreviation + */ + zoneAbbreviation(dstDependent?: boolean): string; + /** + * @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; + /** + * Returns the day number within the year: Jan 1st has number 0, + * Jan 2nd has number 1 etc. + * + * @return the day-of-year [0-366] + */ + dayOfYear(): number; + /** + * The ISO 8601 week number. Week 1 is the week + * that has January 4th in it, and it starts on Monday. + * See https://en.wikipedia.org/wiki/ISO_week_date + * + * @return Week number [1-53] + */ + weekNumber(): number; + /** + * The week of this month. There is no official standard for this, + * but we assume the same rules for the weekNumber (i.e. + * week 1 is the week that has the 4th day of the month in it) + * + * @return Week number [1-5] + */ + weekOfMonth(): number; + /** + * Returns the number of seconds that have passed on the current day + * Does not consider leap seconds + * + * @return seconds [0-86399] + */ + secondOfDay(): 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; + /** + * Returns the UTC day number within the year: Jan 1st has number 0, + * Jan 2nd has number 1 etc. + * + * @return the day-of-year [0-366] + */ + utcDayOfYear(): 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; + /** + * The ISO 8601 UTC week number. Week 1 is the week + * that has January 4th in it, and it starts on Monday. + * See https://en.wikipedia.org/wiki/ISO_week_date + * + * @return Week number [1-53] + */ + utcWeekNumber(): number; + /** + * The week of this month. There is no official standard for this, + * but we assume the same rules for the weekNumber (i.e. + * week 1 is the week that has the 4th day of the month in it) + * + * @return Week number [1-5] + */ + utcWeekOfMonth(): number; + /** + * Returns the number of seconds that have passed on the current day + * Does not consider leap seconds + * + * @return seconds [0-86399] + */ + utcSecondOfDay(): 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) + * 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): 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. + * @return this + duration + */ + add(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: 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(duration: Duration): DateTime; + 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(duration: Duration): DateTime; + subLocal(amount: number, unit: TimeUnit): DateTime; + /** + * Time difference between two DateTimes + * @return this - other + */ + diff(other: DateTime): Duration; + /** + * Chops off the time part, yields the same date at 00:00:00.000 + * @return a new DateTime + */ + startOfDay(): DateTime; + /** + * @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 moment in time in UTC + */ + equals(other: DateTime): boolean; + /** + * @return True iff this and other represent the same time and 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; + /** + * @return The minimum of this and other + */ + min(other: DateTime): DateTime; + /** + * @return The maximum of this and other + */ + max(other: DateTime): DateTime; + /** + * 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; + /** + * Return a string representation of the DateTime according to the + * specified format. The format is implemented as the LDML standard + * (http://unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns) + * + * @param formatString The format specification (e.g. "dd/MM/yyyy HH:mm:ss") + * @return The string representation of this DateTime + */ + format(formatString: string): 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; + /** + * The valueOf() method returns the primitive value of the specified object. + */ + valueOf(): any; + /** + * Modified ISO 8601 format string in UTC without time zone info + */ + toUtcString(): string; + } +} + +declare module '__timezonecomplete/duration' { + import basics = require("__timezonecomplete/basics"); + import TimeUnit = basics.TimeUnit; + /** + * Construct a time duration + * @param n Number of years (may be fractional or negative) + * @return A duration of n years + */ + export function years(n: number): Duration; + /** + * Construct a time duration + * @param n Number of months (may be fractional or negative) + * @return A duration of n months + */ + export function months(n: number): Duration; + /** + * Construct a time duration + * @param n Number of days (may be fractional or negative) + * @return A duration of n days + */ + export function days(n: number): Duration; + /** + * Construct a time duration + * @param n Number of hours (may be fractional or negative) + * @return A duration of n hours + */ + export function hours(n: number): Duration; + /** + * Construct a time duration + * @param n Number of minutes (may be fractional or negative) + * @return A duration of n minutes + */ + export function minutes(n: number): Duration; + /** + * Construct a time duration + * @param n Number of seconds (may be fractional or negative) + * @return A duration of n seconds + */ + export function seconds(n: number): Duration; + /** + * Construct a time duration + * @param n Number of milliseconds (may be fractional or negative) + * @return A duration of n milliseconds + */ + export function milliseconds(n: number): Duration; + /** + * Time duration which is represented as an amount and a unit e.g. + * '1 Month' or '166 Seconds'. The unit is preserved through calculations. + * + * It has two sets of getter functions: + * - second(), minute(), hour() etc, singular form: these can be used to create string representations. + * These return a part of your string representation. E.g. for 2500 milliseconds, the millisecond() part would be 500 + * - seconds(), minutes(), hours() etc, plural form: these return the total amount represented in the corresponding unit. + */ + export class Duration { + /** + * Construct a time duration + * @param n Number of years (may be fractional or negative) + * @return A duration of n years + */ + static years(n: number): Duration; + /** + * Construct a time duration + * @param n Number of months (may be fractional or negative) + * @return A duration of n months + */ + static months(n: number): Duration; + /** + * Construct a time duration + * @param n Number of days (may be fractional or negative) + * @return A duration of n days + */ + static days(n: number): Duration; + /** + * Construct a time duration + * @param n Number of hours (may be fractional or negative) + * @return A duration of n hours + */ + static hours(n: number): Duration; + /** + * Construct a time duration + * @param n Number of minutes (may be fractional or negative) + * @return A duration of n minutes + */ + static minutes(n: number): Duration; + /** + * Construct a time duration + * @param n Number of seconds (may be fractional or negative) + * @return A duration of n seconds + */ + static seconds(n: number): Duration; + /** + * Construct a time duration + * @param n Number of milliseconds (may be fractional or negative) + * @return A duration of n milliseconds + */ + static milliseconds(n: number): Duration; + /** + * Construct a time duration of 0 + */ + constructor(); + /** + * Construct a time duration from a string in one of two formats: + * 1) [-]hhhh[:mm[:ss[.nnn]]] e.g. '-01:00:30.501' + * 2) amount and unit e.g. '-1 days' or '1 year'. The unit may be in singular or plural form and is case-insensitive + */ + constructor(input: string); + /** + * Construct a duration from an amount and a time unit. + * @param amount Number of units + * @param unit A time unit i.e. TimeUnit.Second, TimeUnit.Hour etc. Default Millisecond. + */ + constructor(amount: number, unit?: TimeUnit); + /** + * @return another instance of Duration with the same value. + */ + clone(): Duration; + /** + * Returns this duration expressed in different unit (positive or negative, fractional). + * This is precise for Year <-> Month and for time-to-time conversion (i.e. Hour-or-less to Hour-or-less). + * It is approximate for any other conversion + */ + as(unit: TimeUnit): number; + /** + * Convert this duration to a Duration in another unit. You always get a clone even if you specify + * the same unit. + * This is precise for Year <-> Month and for time-to-time conversion (i.e. Hour-or-less to Hour-or-less). + * It is approximate for any other conversion + */ + convert(unit: TimeUnit): Duration; + /** + * The entire duration in milliseconds (negative or positive) + * For Day/Month/Year durations, this is approximate! + */ + milliseconds(): number; + /** + * The millisecond part of the duration (always positive) + * For Day/Month/Year durations, this is approximate! + * @return e.g. 400 for a -01:02:03.400 duration + */ + millisecond(): number; + /** + * The entire duration in seconds (negative or positive, fractional) + * For Day/Month/Year durations, this is approximate! + * @return e.g. 1.5 for a 1500 milliseconds duration + */ + seconds(): number; + /** + * The second part of the duration (always positive) + * For Day/Month/Year durations, this is approximate! + * @return e.g. 3 for a -01:02:03.400 duration + */ + second(): number; + /** + * The entire duration in minutes (negative or positive, fractional) + * For Day/Month/Year durations, this is approximate! + * @return e.g. 1.5 for a 90000 milliseconds duration + */ + minutes(): number; + /** + * The minute part of the duration (always positive) + * For Day/Month/Year durations, this is approximate! + * @return e.g. 2 for a -01:02:03.400 duration + */ + minute(): number; + /** + * The entire duration in hours (negative or positive, fractional) + * For Day/Month/Year durations, this is approximate! + * @return e.g. 1.5 for a 5400000 milliseconds duration + */ + hours(): number; + /** + * The hour part of a duration. This assumes that a day has 24 hours (which is not the case + * during DST changes). + */ + hour(): number; + /** + * DEPRECATED + * 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 + * For Day/Month/Year durations, this is approximate! + * @return e.g. 25 for a -25:02:03.400 duration + */ + wholeHours(): number; + /** + * The entire duration in days (negative or positive, fractional) + * This is approximate if this duration is not in days! + */ + days(): number; + /** + * The day part of a duration. This assumes that a month has 30 days. + */ + day(): number; + /** + * The entire duration in days (negative or positive, fractional) + * This is approximate if this duration is not in Months or Years! + */ + months(): number; + /** + * The month part of a duration. + */ + month(): number; + /** + * The entire duration in years (negative or positive, fractional) + * This is approximate if this duration is not in Months or Years! + */ + years(): number; + /** + * Non-fractional positive years + */ + wholeYears(): number; + /** + * Amount of units (positive or negative, fractional) + */ + amount(): number; + /** + * The unit this duration was created with + */ + unit(): TimeUnit; + /** + * Sign + * @return "-" if the duration is negative + */ + sign(): string; + /** + * Approximate if the durations have units that cannot be converted + * @return True iff (this < other) + */ + lessThan(other: Duration): boolean; + /** + * Approximate if the durations have units that cannot be converted + * @return True iff (this <= other) + */ + lessEqual(other: Duration): boolean; + /** + * Similar but not identical + * Approximate if the durations have units that cannot be converted + * @return True iff this and other represent the same time duration + */ + equals(other: Duration): boolean; + /** + * Similar but not identical + * Returns false if we cannot determine whether they are equal in all time zones + * so e.g. 60 minutes equals 1 hour, but 24 hours do NOT equal 1 day + * + * @return True iff this and other represent the same time duration + */ + equalsExact(other: Duration): boolean; + /** + * Same unit and same amount + */ + identical(other: Duration): boolean; + /** + * Approximate if the durations have units that cannot be converted + * @return True iff this > other + */ + greaterThan(other: Duration): boolean; + /** + * Approximate if the durations have units that cannot be converted + * @return True iff this >= other + */ + greaterEqual(other: Duration): boolean; + /** + * Approximate if the durations have units that cannot be converted + * @return The minimum (most negative) of this and other + */ + min(other: Duration): Duration; + /** + * Approximate if the durations have units that cannot be converted + * @return The maximum (most positive) of this and other + */ + max(other: Duration): Duration; + /** + * Approximate if the durations have units that cannot be converted + * Multiply with a fixed number. + * @return a new Duration of (this * value) + */ + multiply(value: number): Duration; + /** + * Approximate if the durations have units that cannot be converted + * 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) with the unit of this duration + */ + add(value: Duration): Duration; + /** + * Subtract a duration. + * @return a new Duration of (this - value) with the unit of this duration + */ + sub(value: Duration): Duration; + /** + * Return the absolute value of the duration i.e. remove the sign. + */ + abs(): Duration; + /** + * DEPRECATED + * String in [-]hhhh:mm:ss.nnn notation. All fields are + * always present except the sign. + */ + toFullString(): string; + /** + * String in [-]hhhh:mm[:ss[.nnn]] notation. + * @param full If true, then all fields are always present except the sign. Otherwise, seconds and milliseconds + * are chopped off if zero + */ + toHmsString(full?: boolean): string; + /** + * String in ISO 8601 notation e.g. 'P1M' for one month or 'PT1M' for one minute + */ + toIsoString(): string; + /** + * String representation with amount and unit e.g. '1.5 years' or '-1 day' + */ + toString(): string; + /** + * Used by util.inspect() + */ + inspect(): string; + /** + * The valueOf() method returns the primitive value of the specified object. + */ + valueOf(): any; + } +} + +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(), getUtcMonth() 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, + } +} + +declare module '__timezonecomplete/period' { + import basics = require("__timezonecomplete/basics"); + import TimeUnit = basics.TimeUnit; + import duration = require("__timezonecomplete/duration"); + import Duration = duration.Duration; + import datetime = require("__timezonecomplete/datetime"); + import DateTime = datetime.DateTime; + /** + * 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, + /** + * End-of-enum marker + */ + MAX = 2, + } + /** + * 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 interval The interval of the period + * @param dst Specifies how to handle Daylight Saving Time. Not relevant + * if the time zone of the start datetime does not have DST. + * Defaults to RegularLocalTime. + */ + constructor(start: DateTime, interval: Duration, dst?: PeriodDst); + /** + * 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. + * Defaults to RegularLocalTime. + */ + constructor(start: DateTime, amount: number, unit: TimeUnit, dst?: PeriodDst); + /** + * The start date + */ + start(): DateTime; + /** + * The interval + */ + interval(): Duration; + /** + * DEPRECATED + * The amount of units of the interval + */ + amount(): number; + /** + * DEPRECATED + * The unit of the interval + */ + 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; + /** + * Checks whether the given date is on a period boundary + * (expensive!) + */ + isBoundary(occurrence: DateTime): boolean; + /** + * Returns true iff this period has the same effect as the given one. + * i.e. a period of 24 hours is equal to one of 1 day if they have the same UTC start moment + * and same dst. + */ + equals(other: Period): boolean; + /** + * Returns true iff this period was constructed with identical arguments to the other one. + */ + identical(other: Period): boolean; + /** + * 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". + */ + 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"); + import DateFunctions = javascript.DateFunctions; + /** + * The local time zone for a given date as per OS settings. Note that time zones are cached + * so you don't necessarily get a new object each time. + */ + export function local(): TimeZone; + /** + * Coordinated Universal Time zone. Note that time zones are cached + * so you don't necessarily get a new object each time. + */ + export function utc(): TimeZone; + /** + * @param offset offset w.r.t. UTC in minutes, e.g. 90 for +01:30. Note that time zones are cached + * so you don't necessarily get a new object each time. + * @returns a time zone with the given fixed offset + */ + export function zone(offset: number): TimeZone; + /** + * Time zone for an offset string or an IANA time zone string. Note that time zones are cached + * so you don't necessarily get a new object each time. + * @param s Empty string for no time zone (null is returned), + * "localtime" 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 + * @param dst Optional, default true: adhere to Daylight Saving Time if applicable. Note for + * "localtime", timezonecomplete will adhere to the computer settings, the DST flag + * does not have any effect. + */ + export function zone(name: string, dst?: boolean): TimeZone; + /** + * 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; + /** + * Time zone with a fixed offset + * @param offset offset w.r.t. UTC in minutes, e.g. 90 for +01:30 + */ + static zone(offset: number): TimeZone; + /** + * Time zone for an offset string or an IANA time zone string. Note that time zones are cached + * so you don't necessarily get a new object each time. + * @param s Empty string for no time zone (null is returned), + * "localtime" 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 + * TZ database zone name may be suffixed with " without DST" to indicate no DST should be applied. + * In that case, the dst parameter is ignored. + * @param dst Optional, default true: adhere to Daylight Saving Time if applicable. Note for + * "localtime", timezonecomplete will adhere to the computer settings, the DST flag + * does not have any effect. + */ + static zone(s: string, dst?: boolean): TimeZone; + /** + * Do not use this constructor, use the static + * TimeZone.zone() method instead. + * @param name NORMALIZED name, assumed to be correct + * @param dst Adhere to Daylight Saving Time if applicable, ignored for local time and fixed offsets + */ + constructor(name: string, dst?: boolean); + /** + * 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; + dst(): boolean; + /** + * 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; + /** + * Returns true iff the constructor arguments were identical, so UTC !== GMT + */ + identical(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 Full year + * @param month Month 1-12 (note this deviates from JavaScript date) + * @param day Day of month 1-31 + * @param hour Hour 0-23 + * @param minute Minute 0-59 + * @param second Second 0-59 + * @param millisecond 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: 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: DateFunctions): number; + /** + * Zone abbreviation at given UTC timestamp e.g. CEST for Central European Summer Time. + * + * @param year Full year + * @param month Month 1-12 (note this deviates from JavaScript date) + * @param day Day of month 1-31 + * @param hour Hour 0-23 + * @param minute Minute 0-59 + * @param second Second 0-59 + * @param millisecond Millisecond 0-999 + * @param dstDependent (default true) set to false for a DST-agnostic abbreviation + * + * @return "local" for local timezone, the offset for an offset zone, or the abbreviation for a proper zone. + */ + abbreviationForUtc(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number, dstDependent?: boolean): string; + /** + * 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; + } +} + +declare module '__timezonecomplete/globals' { + import datetime = require("__timezonecomplete/datetime"); + import DateTime = datetime.DateTime; + import duration = require("__timezonecomplete/duration"); + import Duration = duration.Duration; + /** + * Returns the minimum of two DateTimes + */ + export function min(d1: DateTime, d2: DateTime): DateTime; + /** + * Returns the minimum of two Durations + */ + export function min(d1: Duration, d2: Duration): Duration; + /** + * Returns the maximum of two DateTimes + */ + export function max(d1: DateTime, d2: DateTime): DateTime; + /** + * Returns the maximum of two Durations + */ + export function max(d1: Duration, d2: Duration): Duration; + /** + * Returns the absolute value of a Duration + */ + export function abs(d: Duration): Duration; +} diff --git a/title-case/title-case.d.ts b/title-case/title-case.d.ts index c8e4dee30..1409f6b06 100644 --- a/title-case/title-case.d.ts +++ b/title-case/title-case.d.ts @@ -1,9 +1,9 @@ -// Type definitions for title-case -// Project: https://github.com/blakeembrey/title-case -// Definitions by: Sam Saint-Pettersen -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module "title-case" { - function titleCase(string1: string, string2?: string): string; - export = titleCase; +// Type definitions for title-case +// Project: https://github.com/blakeembrey/title-case +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "title-case" { + function titleCase(string1: string, string2?: string): string; + export = titleCase; } \ No newline at end of file diff --git a/tmp/tmp-tests.ts b/tmp/tmp-tests.ts index c5560e799..c343f5278 100644 --- a/tmp/tmp-tests.ts +++ b/tmp/tmp-tests.ts @@ -1,68 +1,68 @@ -/// -import tmp = require('tmp'); - -tmp.file((err, path, fd, cleanupCallback) => { - if (err) throw err; - - console.log("File: ", path); - console.log("Filedescriptor: ", fd); - - cleanupCallback(); -}); - -tmp.dir((err, path, cleanupCallback) => { - if (err) throw err; - - console.log("Dir: ", path); - - cleanupCallback(); -}); - -tmp.tmpName((err, path) => { - if (err) throw err; - - console.log("Created temporary filename: ", path); -}); - -tmp.file({ mode: 644, prefix: 'prefix-', postfix: '.txt' }, (err, path, fd) => { - if (err) throw err; - - console.log("File: ", path); - console.log("Filedescriptor: ", fd); -}); - -tmp.dir({ mode: 750, prefix: 'myTmpDir_' }, (err, path) => { - if (err) throw err; - - console.log("Dir: ", path); -}); - -tmp.tmpName({ template: '/tmp/tmp-XXXXXX' }, (err, path) => { - if (err) throw err; - - console.log("Created temporary filename: ", path); -}); - -tmp.setGracefulCleanup(); - -var tmpobj = tmp.fileSync(); -console.log("File: ", tmpobj.name); -console.log("Filedescriptor: ", tmpobj.fd); -tmpobj.removeCallback(); - -tmpobj = tmp.dirSync(); -console.log("Dir: ", tmpobj.name); -tmpobj.removeCallback(); - -var name = tmp.tmpNameSync(); -console.log("Created temporary filename: ", name); - -tmpobj = tmp.fileSync({ mode: 644, prefix: 'prefix-', postfix: '.txt' }); -console.log("File: ", tmpobj.name); -console.log("Filedescriptor: ", tmpobj.fd); - -tmpobj = tmp.dirSync({ mode: 750, prefix: 'myTmpDir_' }); -console.log("Dir: ", tmpobj.name); - -var tmpname = tmp.tmpNameSync({ template: '/tmp/tmp-XXXXXX' }); +/// +import tmp = require('tmp'); + +tmp.file((err, path, fd, cleanupCallback) => { + if (err) throw err; + + console.log("File: ", path); + console.log("Filedescriptor: ", fd); + + cleanupCallback(); +}); + +tmp.dir((err, path, cleanupCallback) => { + if (err) throw err; + + console.log("Dir: ", path); + + cleanupCallback(); +}); + +tmp.tmpName((err, path) => { + if (err) throw err; + + console.log("Created temporary filename: ", path); +}); + +tmp.file({ mode: 644, prefix: 'prefix-', postfix: '.txt' }, (err, path, fd) => { + if (err) throw err; + + console.log("File: ", path); + console.log("Filedescriptor: ", fd); +}); + +tmp.dir({ mode: 750, prefix: 'myTmpDir_' }, (err, path) => { + if (err) throw err; + + console.log("Dir: ", path); +}); + +tmp.tmpName({ template: '/tmp/tmp-XXXXXX' }, (err, path) => { + if (err) throw err; + + console.log("Created temporary filename: ", path); +}); + +tmp.setGracefulCleanup(); + +var tmpobj = tmp.fileSync(); +console.log("File: ", tmpobj.name); +console.log("Filedescriptor: ", tmpobj.fd); +tmpobj.removeCallback(); + +tmpobj = tmp.dirSync(); +console.log("Dir: ", tmpobj.name); +tmpobj.removeCallback(); + +var name = tmp.tmpNameSync(); +console.log("Created temporary filename: ", name); + +tmpobj = tmp.fileSync({ mode: 644, prefix: 'prefix-', postfix: '.txt' }); +console.log("File: ", tmpobj.name); +console.log("Filedescriptor: ", tmpobj.fd); + +tmpobj = tmp.dirSync({ mode: 750, prefix: 'myTmpDir_' }); +console.log("Dir: ", tmpobj.name); + +var tmpname = tmp.tmpNameSync({ template: '/tmp/tmp-XXXXXX' }); console.log("Created temporary filename: ", tmpname ); \ No newline at end of file diff --git a/tmp/tmp.d.ts b/tmp/tmp.d.ts index 4625fc19c..99fce6400 100644 --- a/tmp/tmp.d.ts +++ b/tmp/tmp.d.ts @@ -1,48 +1,48 @@ -// Type definitions for tmp v0.0.28 -// Project: https://www.npmjs.com/package/tmp -// Definitions by: Jared Klopper -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module "tmp" { - - module tmp { - interface Options extends SimpleOptions { - mode?: number; - } - - interface SimpleOptions { - prefix?: string; - postfix?: string; - template?: string; - dir?: string; - tries?: number; - keep?: boolean; - unsafeCleanup?: boolean; - } - - interface SynchrounousResult { - name: string; - fd: number; - removeCallback: () => void; - } - - function file(callback: (err: any, path: string, fd: number, cleanupCallback: () => void) => void): void; - function file(config: Options, callback?: (err: any, path: string, fd: number, cleanupCallback: () => void) => void): void; - - function fileSync(config?: Options): SynchrounousResult; - - function dir(callback: (err: any, path: string, cleanupCallback: () => void) => void): void; - function dir(config: Options, callback?: (err: any, path: string, cleanupCallback: () => void) => void): void; - - function dirSync(config?: Options): SynchrounousResult; - - function tmpName(callback: (err: any, path: string) => void): void; - function tmpName(config: SimpleOptions, callback?: (err: any, path: string) => void): void; - - function tmpNameSync(config?: SimpleOptions): string; - - function setGracefulCleanup(): void; - } - - export = tmp; -} +// Type definitions for tmp v0.0.28 +// Project: https://www.npmjs.com/package/tmp +// Definitions by: Jared Klopper +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "tmp" { + + module tmp { + interface Options extends SimpleOptions { + mode?: number; + } + + interface SimpleOptions { + prefix?: string; + postfix?: string; + template?: string; + dir?: string; + tries?: number; + keep?: boolean; + unsafeCleanup?: boolean; + } + + interface SynchrounousResult { + name: string; + fd: number; + removeCallback: () => void; + } + + function file(callback: (err: any, path: string, fd: number, cleanupCallback: () => void) => void): void; + function file(config: Options, callback?: (err: any, path: string, fd: number, cleanupCallback: () => void) => void): void; + + function fileSync(config?: Options): SynchrounousResult; + + function dir(callback: (err: any, path: string, cleanupCallback: () => void) => void): void; + function dir(config: Options, callback?: (err: any, path: string, cleanupCallback: () => void) => void): void; + + function dirSync(config?: Options): SynchrounousResult; + + function tmpName(callback: (err: any, path: string) => void): void; + function tmpName(config: SimpleOptions, callback?: (err: any, path: string) => void): void; + + function tmpNameSync(config?: SimpleOptions): string; + + function setGracefulCleanup(): void; + } + + export = tmp; +} diff --git a/to-title-case-gouch/to-title-case-gouch.d.ts b/to-title-case-gouch/to-title-case-gouch.d.ts index 2faa2d8d0..0c089720f 100644 --- a/to-title-case-gouch/to-title-case-gouch.d.ts +++ b/to-title-case-gouch/to-title-case-gouch.d.ts @@ -1,8 +1,8 @@ -// Type definitions for to-title-case -// Project: https://github.com/gouch/to-title-case -// Definitions by: Sam Saint-Pettersen -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -interface String { - toTitleCase(): string; -} +// Type definitions for to-title-case +// Project: https://github.com/gouch/to-title-case +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface String { + toTitleCase(): string; +} diff --git a/toastr/toastr-tests.ts.tscparams b/toastr/toastr-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/toastr/toastr-tests.ts.tscparams +++ b/toastr/toastr-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/tspromise/tspromise.d.ts b/tspromise/tspromise.d.ts index 0d1132ed1..0228bc946 100644 --- a/tspromise/tspromise.d.ts +++ b/tspromise/tspromise.d.ts @@ -1,40 +1,40 @@ -// Type definitions for tspromise 0.0.4 -// Project: https://github.com/soywiz/tspromise -// Definitions by: Carlos Ballesteros Velasco -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// -declare class Thenable { - then(onFulfilled: (value: T) => Thenable, onRejected?: (error: Error) => TR): Thenable; - then(onFulfilled: (value: T) => Thenable, onRejected?: (error: Error) => void): Thenable; - then(onFulfilled: (value: T) => TR, onRejected?: (error: Error) => void): Thenable; - then(onFulfilled: (value: T) => TR, onRejected?: (error: Error) => TR): Thenable; - catch(onRejected: (error: Error) => T): Thenable; -} - -interface NodeCallback { - (err: Error, value: T): void; -} - -declare module "tspromise" { - class Promise extends Thenable { - constructor(callback: (resolve: (value?: T) => void, reject?: (error: Error) => void) => void); - static resolve(value?: T): Thenable; - static resolve(promise: Thenable): Thenable; - static reject(error: Error): Thenable; - static all(promises: Thenable[]): Thenable; - static async(callback: () => TR): () => Thenable; - static async(callback: (p1: T1) => TR): (p1: T1) => Thenable; - static async(callback: (p1: T1, p2: T2) => TR): (p1: T1, p2: T2) => Thenable; - static async(callback: (p1: T1, p2: T2, p3: T3) => TR): (p1: T1, p2: T2, p3: T3) => Thenable; - static async(callback: (p1: T1, p2: T2, p3: T3, p4: T4) => TR): (p1: T1, p2: T2, p3: T3, p4: T4) => Thenable; - static spawn(generatorFunction: () => TR): Thenable; - static rewriteFolderSync(path: string): void; - static waitAsync(time: number): Thenable<{}>; - static nfcall(obj: any, methodName: String, ...args: any[]): Thenable; - } - - export = Promise; -} - -declare function yield(promise: Thenable): T; +// Type definitions for tspromise 0.0.4 +// Project: https://github.com/soywiz/tspromise +// Definitions by: Carlos Ballesteros Velasco +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +declare class Thenable { + then(onFulfilled: (value: T) => Thenable, onRejected?: (error: Error) => TR): Thenable; + then(onFulfilled: (value: T) => Thenable, onRejected?: (error: Error) => void): Thenable; + then(onFulfilled: (value: T) => TR, onRejected?: (error: Error) => void): Thenable; + then(onFulfilled: (value: T) => TR, onRejected?: (error: Error) => TR): Thenable; + catch(onRejected: (error: Error) => T): Thenable; +} + +interface NodeCallback { + (err: Error, value: T): void; +} + +declare module "tspromise" { + class Promise extends Thenable { + constructor(callback: (resolve: (value?: T) => void, reject?: (error: Error) => void) => void); + static resolve(value?: T): Thenable; + static resolve(promise: Thenable): Thenable; + static reject(error: Error): Thenable; + static all(promises: Thenable[]): Thenable; + static async(callback: () => TR): () => Thenable; + static async(callback: (p1: T1) => TR): (p1: T1) => Thenable; + static async(callback: (p1: T1, p2: T2) => TR): (p1: T1, p2: T2) => Thenable; + static async(callback: (p1: T1, p2: T2, p3: T3) => TR): (p1: T1, p2: T2, p3: T3) => Thenable; + static async(callback: (p1: T1, p2: T2, p3: T3, p4: T4) => TR): (p1: T1, p2: T2, p3: T3, p4: T4) => Thenable; + static spawn(generatorFunction: () => TR): Thenable; + static rewriteFolderSync(path: string): void; + static waitAsync(time: number): Thenable<{}>; + static nfcall(obj: any, methodName: String, ...args: any[]): Thenable; + } + + export = Promise; +} + +declare function yield(promise: Thenable): T; diff --git a/tween.js/tween.js.d.ts b/tween.js/tween.js.d.ts index d83300cba..d4787a86a 100644 --- a/tween.js/tween.js.d.ts +++ b/tween.js/tween.js.d.ts @@ -1,100 +1,100 @@ -// Type definitions for tween.js r12 -// Project: https://github.com/sole/tween.js/ -// Definitions by: sunetos , jzarnikov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module TWEEN { - export var REVISION: string; - export function getAll(): Tween[]; - export function removeAll(): void; - export function add(tween:Tween): void; - export function remove(tween:Tween): void; - export function update(time?:number): boolean; - - export class Tween { - constructor(object?:any); - to(properties:any, duration:number): Tween; - start(time?:number): Tween; - stop(): Tween; - delay(amount:number): Tween; - easing(easing: (k: number) => number): Tween; - interpolation(interpolation: (v:number[], k:number) => number): Tween; - chain(...tweens:Tween[]): Tween; - onStart(callback: (object?: any) => void): Tween; - onUpdate(callback: (object?: any) => void): Tween; - onComplete(callback: (object?: any) => void): Tween; - update(time: number): boolean; - repeat(times: number): Tween; - yoyo(enable: boolean): Tween; - } - export var Easing: TweenEasing; - export var Interpolation: TweenInterpolation; -} - -interface TweenEasing { - Linear: { - None(k:number): number; - }; - Quadratic: { - In(k:number): number; - Out(k:number): number; - InOut(k:number): number; - }; - Cubic: { - In(k:number): number; - Out(k:number): number; - InOut(k:number): number; - }; - Quartic: { - In(k:number): number; - Out(k:number): number; - InOut(k:number): number; - }; - Quintic: { - In(k:number): number; - Out(k:number): number; - InOut(k:number): number; - }; - Sinusoidal: { - In(k:number): number; - Out(k:number): number; - InOut(k:number): number; - }; - Exponential: { - In(k:number): number; - Out(k:number): number; - InOut(k:number): number; - }; - Circular: { - In(k:number): number; - Out(k:number): number; - InOut(k:number): number; - }; - Elastic: { - In(k:number): number; - Out(k:number): number; - InOut(k:number): number; - }; - Back: { - In(k:number): number; - Out(k:number): number; - InOut(k:number): number; - }; - Bounce: { - In(k:number): number; - Out(k:number): number; - InOut(k:number): number; - }; -} - -interface TweenInterpolation { - Linear(v:number[], k:number): number; - Bezier(v:number[], k:number): number; - CatmullRom(v:number[], k:number): number; - - Utils: { - Linear(p0:number, p1:number, t:number): number; - Bernstein(n:number, i:number): number; - Factorial(n:number): number; - }; -} +// Type definitions for tween.js r12 +// Project: https://github.com/sole/tween.js/ +// Definitions by: sunetos , jzarnikov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module TWEEN { + export var REVISION: string; + export function getAll(): Tween[]; + export function removeAll(): void; + export function add(tween:Tween): void; + export function remove(tween:Tween): void; + export function update(time?:number): boolean; + + export class Tween { + constructor(object?:any); + to(properties:any, duration:number): Tween; + start(time?:number): Tween; + stop(): Tween; + delay(amount:number): Tween; + easing(easing: (k: number) => number): Tween; + interpolation(interpolation: (v:number[], k:number) => number): Tween; + chain(...tweens:Tween[]): Tween; + onStart(callback: (object?: any) => void): Tween; + onUpdate(callback: (object?: any) => void): Tween; + onComplete(callback: (object?: any) => void): Tween; + update(time: number): boolean; + repeat(times: number): Tween; + yoyo(enable: boolean): Tween; + } + export var Easing: TweenEasing; + export var Interpolation: TweenInterpolation; +} + +interface TweenEasing { + Linear: { + None(k:number): number; + }; + Quadratic: { + In(k:number): number; + Out(k:number): number; + InOut(k:number): number; + }; + Cubic: { + In(k:number): number; + Out(k:number): number; + InOut(k:number): number; + }; + Quartic: { + In(k:number): number; + Out(k:number): number; + InOut(k:number): number; + }; + Quintic: { + In(k:number): number; + Out(k:number): number; + InOut(k:number): number; + }; + Sinusoidal: { + In(k:number): number; + Out(k:number): number; + InOut(k:number): number; + }; + Exponential: { + In(k:number): number; + Out(k:number): number; + InOut(k:number): number; + }; + Circular: { + In(k:number): number; + Out(k:number): number; + InOut(k:number): number; + }; + Elastic: { + In(k:number): number; + Out(k:number): number; + InOut(k:number): number; + }; + Back: { + In(k:number): number; + Out(k:number): number; + InOut(k:number): number; + }; + Bounce: { + In(k:number): number; + Out(k:number): number; + InOut(k:number): number; + }; +} + +interface TweenInterpolation { + Linear(v:number[], k:number): number; + Bezier(v:number[], k:number): number; + CatmullRom(v:number[], k:number): number; + + Utils: { + Linear(p0:number, p1:number, t:number): number; + Bernstein(n:number, i:number): number; + Factorial(n:number): number; + }; +} diff --git a/tweenjs/tweenjs.d.ts b/tweenjs/tweenjs.d.ts index cb566dfcc..0d3d0d1aa 100644 --- a/tweenjs/tweenjs.d.ts +++ b/tweenjs/tweenjs.d.ts @@ -1,166 +1,166 @@ -// Type definitions for TweenJS 0.6.0 -// Project: http://www.createjs.com/#!/TweenJS -// Definitions by: Pedro Ferreira , Chris Smith -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/* - Copyright (c) 2012 Pedro Ferreira - 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. -*/ - -// Library documentation : http://www.createjs.com/Docs/TweenJS/modules/TweenJS.html - -/// - -declare module createjs { - export class CSSPlugin { - constructor(); - - // properties - static cssSuffixMap: Object; - - // methods - static install(): void; - } - - export class Ease { - // methods - static backIn: (amount: number) => number; - static backInOut: (amount: number) => number; - static backOut: (amount: number) => number; - static bounceIn: (amount: number) => number; - static bounceInOut: (amount: number) => number; - static bounceOut: (amount: number) => number; - static circIn: (amount: number) => number; - static circInOut: (amount: number) => number; - static circOut: (amount: number) => number; - static cubicIn: (amount: number) => number; - static cubicInOut: (amount: number) => number; - static cubicOut: (amount: number) => number; - static elasticIn: (amount: number) => number; - static elasticInOut: (amount: number) => number; - static elasticOut: (amount: number) => number; - static get(amount: number): (amount: number) => number; - static getBackIn(amount: number): (amount: number) => number; - static getBackInOut(amount: number): (amount: number) => number; - static getBackOut(amount: number): (amount: number) => number; - static getElasticIn(amplitude: number, period: number): (amount: number) => number; - static getElasticInOut(amplitude: number, period: number): (amount: number) => number; - static getElasticOut(amplitude: number, period: number): (amount: number) => number; - static getPowIn(pow: number): (amount: number) => number; - static getPowInOut(pow: number): (amount: number) => number; - static getPowOut(pow: number): (amount: number) => number; - static linear: (amount: number) => number; - static none: (amount: number) => number; // same as linear - static quadIn: (amount: number) => number; - static quadInOut: (amount: number) => number; - static quadOut: (amount: number) => number; - static quartIn: (amount: number) => number; - static quartInOut: (amount: number) => number; - static quartOut: (amount: number) => number; - static quintIn: (amount: number) => number; - static quintInOut: (amount: number) => number; - static quintOut: (amount: number) => number; - static sineIn: (amount: number) => number; - static sineInOut: (amount: number) => number; - static sineOut: (amount: number) => number; - } - - export class MotionGuidePlugin { - constructor(); - - //methods - static install(): Object; - } - - /* - NOTE: It is commented out because it conflicts with SamplePlugin Class of PreloadJS. - this class is mainly for documentation purposes. - http://www.createjs.com/Docs/TweenJS/classes/SamplePlugin.html - */ - /* - export class SamplePlugin { - constructor(); - - // properties - static priority: any; - - //methods - static init(tween: Tween, prop: string, value: any): any; - static step(tween: Tween, prop: string, startValue: any, injectProps: Object, endValue: any): void; - static install(): void; - static tween(tween: Tween, prop: string, value: any, startValues: Object, endValues: Object, ratio: number, wait: boolean, end: boolean): any; - } - */ - - export class Timeline extends EventDispatcher { - constructor (tweens: Tween[], labels: Object, props: Object); - - // properties - duration: number; - ignoreGlobalPause: boolean; - loop: boolean; - position: Object; - - // methods - addLabel(label: string, position: number): void; - addTween(...tween: Tween[]): void; - getCurrentLabel(): string; - getLabels(): Object[]; - gotoAndPlay(positionOrLabel: string | number): void; - gotoAndStop(positionOrLabel: string | number): void; - removeTween(...tween: Tween[]): void; - resolve(positionOrLabel: string | number): number; - setLabels(o: Object): void; - setPaused(value: boolean): void; - setPosition(value: number, actionsMode?: number): boolean; - tick(delta: number): void; - updateDuration(): void; - } - - - export class Tween extends EventDispatcher { - constructor(target: Object, props?: Object, pluginData?: Object); - - // properties - duration: number; - static IGNORE: Object; - ignoreGlobalPause: boolean; - static LOOP: number; - loop: boolean; - static NONE: number; - onChange: Function; // deprecated - passive: boolean; - pluginData: Object; - position: number; - static REVERSE: number; - target: Object; - - // methods - call(callback: (tweenObject: Tween) => any, params?: any[], scope?: Object): Tween; // when 'params' isn't given, the callback receives a tweenObject - call(callback: (...params: any[]) => any, params?: any[], scope?: Object): Tween; // otherwise, it receives the params only - static get(target: Object, props?: Object, pluginData?: Object, override?: boolean): Tween; - static hasActiveTweens(target?: Object): boolean; - static installPlugin(plugin: Object, properties: any[]): void; - pause(tween: Tween): Tween; - play(tween: Tween): Tween; - static removeAllTweens(): void; - static removeTweens(target: Object): void; - set(props: Object, target?: Object): Tween; - setPaused(value: boolean): Tween; - setPosition(value: number, actionsMode: number): boolean; - static tick(delta: number, paused: boolean): void; - tick(delta: number): void; - to(props: Object, duration?: number, ease?: (t: number) => number): Tween; - wait(duration: number, passive?: boolean): Tween; - - } - - export class TweenJS { - // properties - static buildDate: string; - static version: string; - } -} +// Type definitions for TweenJS 0.6.0 +// Project: http://www.createjs.com/#!/TweenJS +// Definitions by: Pedro Ferreira , Chris Smith +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* + Copyright (c) 2012 Pedro Ferreira + 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. +*/ + +// Library documentation : http://www.createjs.com/Docs/TweenJS/modules/TweenJS.html + +/// + +declare module createjs { + export class CSSPlugin { + constructor(); + + // properties + static cssSuffixMap: Object; + + // methods + static install(): void; + } + + export class Ease { + // methods + static backIn: (amount: number) => number; + static backInOut: (amount: number) => number; + static backOut: (amount: number) => number; + static bounceIn: (amount: number) => number; + static bounceInOut: (amount: number) => number; + static bounceOut: (amount: number) => number; + static circIn: (amount: number) => number; + static circInOut: (amount: number) => number; + static circOut: (amount: number) => number; + static cubicIn: (amount: number) => number; + static cubicInOut: (amount: number) => number; + static cubicOut: (amount: number) => number; + static elasticIn: (amount: number) => number; + static elasticInOut: (amount: number) => number; + static elasticOut: (amount: number) => number; + static get(amount: number): (amount: number) => number; + static getBackIn(amount: number): (amount: number) => number; + static getBackInOut(amount: number): (amount: number) => number; + static getBackOut(amount: number): (amount: number) => number; + static getElasticIn(amplitude: number, period: number): (amount: number) => number; + static getElasticInOut(amplitude: number, period: number): (amount: number) => number; + static getElasticOut(amplitude: number, period: number): (amount: number) => number; + static getPowIn(pow: number): (amount: number) => number; + static getPowInOut(pow: number): (amount: number) => number; + static getPowOut(pow: number): (amount: number) => number; + static linear: (amount: number) => number; + static none: (amount: number) => number; // same as linear + static quadIn: (amount: number) => number; + static quadInOut: (amount: number) => number; + static quadOut: (amount: number) => number; + static quartIn: (amount: number) => number; + static quartInOut: (amount: number) => number; + static quartOut: (amount: number) => number; + static quintIn: (amount: number) => number; + static quintInOut: (amount: number) => number; + static quintOut: (amount: number) => number; + static sineIn: (amount: number) => number; + static sineInOut: (amount: number) => number; + static sineOut: (amount: number) => number; + } + + export class MotionGuidePlugin { + constructor(); + + //methods + static install(): Object; + } + + /* + NOTE: It is commented out because it conflicts with SamplePlugin Class of PreloadJS. + this class is mainly for documentation purposes. + http://www.createjs.com/Docs/TweenJS/classes/SamplePlugin.html + */ + /* + export class SamplePlugin { + constructor(); + + // properties + static priority: any; + + //methods + static init(tween: Tween, prop: string, value: any): any; + static step(tween: Tween, prop: string, startValue: any, injectProps: Object, endValue: any): void; + static install(): void; + static tween(tween: Tween, prop: string, value: any, startValues: Object, endValues: Object, ratio: number, wait: boolean, end: boolean): any; + } + */ + + export class Timeline extends EventDispatcher { + constructor (tweens: Tween[], labels: Object, props: Object); + + // properties + duration: number; + ignoreGlobalPause: boolean; + loop: boolean; + position: Object; + + // methods + addLabel(label: string, position: number): void; + addTween(...tween: Tween[]): void; + getCurrentLabel(): string; + getLabels(): Object[]; + gotoAndPlay(positionOrLabel: string | number): void; + gotoAndStop(positionOrLabel: string | number): void; + removeTween(...tween: Tween[]): void; + resolve(positionOrLabel: string | number): number; + setLabels(o: Object): void; + setPaused(value: boolean): void; + setPosition(value: number, actionsMode?: number): boolean; + tick(delta: number): void; + updateDuration(): void; + } + + + export class Tween extends EventDispatcher { + constructor(target: Object, props?: Object, pluginData?: Object); + + // properties + duration: number; + static IGNORE: Object; + ignoreGlobalPause: boolean; + static LOOP: number; + loop: boolean; + static NONE: number; + onChange: Function; // deprecated + passive: boolean; + pluginData: Object; + position: number; + static REVERSE: number; + target: Object; + + // methods + call(callback: (tweenObject: Tween) => any, params?: any[], scope?: Object): Tween; // when 'params' isn't given, the callback receives a tweenObject + call(callback: (...params: any[]) => any, params?: any[], scope?: Object): Tween; // otherwise, it receives the params only + static get(target: Object, props?: Object, pluginData?: Object, override?: boolean): Tween; + static hasActiveTweens(target?: Object): boolean; + static installPlugin(plugin: Object, properties: any[]): void; + pause(tween: Tween): Tween; + play(tween: Tween): Tween; + static removeAllTweens(): void; + static removeTweens(target: Object): void; + set(props: Object, target?: Object): Tween; + setPaused(value: boolean): Tween; + setPosition(value: number, actionsMode: number): boolean; + static tick(delta: number, paused: boolean): void; + tick(delta: number): void; + to(props: Object, duration?: number, ease?: (t: number) => number): Tween; + wait(duration: number, passive?: boolean): Tween; + + } + + export class TweenJS { + // properties + static buildDate: string; + static version: string; + } +} diff --git a/typeahead/typeahead-tests.ts b/typeahead/typeahead-tests.ts index be2f3b34b..7debe0044 100644 --- a/typeahead/typeahead-tests.ts +++ b/typeahead/typeahead-tests.ts @@ -96,8 +96,8 @@ function test_typeahead() { suggestion: 'tt-suggestion', empty: 'tt-empty', open: 'tt-open', - cursor: 'tt-cursor', - highlight: 'tt-highlight' + cursor: 'tt-cursor', + highlight: 'tt-highlight' }; } } @@ -203,8 +203,8 @@ function test_bloodhout() { function test_bloodhout_methods() { // initialize - var promise1: JQueryPromise = engine.initialize(); - var promise2: JQueryPromise = engine.initialize(); + var promise1: JQueryPromise = engine.initialize(); + var promise2: JQueryPromise = engine.initialize(); var promise3: JQueryPromise = engine.initialize(true); // add @@ -234,100 +234,100 @@ function test_bloodhout() { function test_bloodhout_options() { function test_bloodhout_options_datumTokenizer() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: (datum: string) => { return new Array(); }, - queryTokenizer: null + datumTokenizer: (datum: string) => { return new Array(); }, + queryTokenizer: null }; } function test_bloodhout_options_queryTokenizer() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: null, - queryTokenizer: (query: string) => { return new Array(); } + datumTokenizer: null, + queryTokenizer: (query: string) => { return new Array(); } }; } function test_bloodhout_options_initialize() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: null, - queryTokenizer: null, - initialize: true + datumTokenizer: null, + queryTokenizer: null, + initialize: true }; } function test_bloodhout_options_sufficient() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: null, - queryTokenizer: null, - sufficient: 5 + datumTokenizer: null, + queryTokenizer: null, + sufficient: 5 }; } function test_bloodhout_options_sorter() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: null, - queryTokenizer: null, - sorter: (a: string, b: string) => { return 0 } + datumTokenizer: null, + queryTokenizer: null, + sorter: (a: string, b: string) => { return 0 } }; } function test_bloodhout_options_local_array() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: null, - queryTokenizer: null, - local: new Array() + datumTokenizer: null, + queryTokenizer: null, + local: new Array() }; } function test_bloodhout_options_local_function() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: null, - queryTokenizer: null, - local: () => { return new Array() } + datumTokenizer: null, + queryTokenizer: null, + local: () => { return new Array() } }; } function test_bloodhout_options_prefetch_string() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: null, - queryTokenizer: null, - prefetch: 'url' + datumTokenizer: null, + queryTokenizer: null, + prefetch: 'url' }; } function test_bloodhout_options_prefetch_object() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: null, - queryTokenizer: null, - prefetch: { url: 'url' } + datumTokenizer: null, + queryTokenizer: null, + prefetch: { url: 'url' } }; } function test_bloodhout_options_remote_string() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: null, - queryTokenizer: null, - remote: 'url' + datumTokenizer: null, + queryTokenizer: null, + remote: 'url' }; } function test_bloodhout_options_remote_object() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: null, - queryTokenizer: null, - remote: { url: 'url' } + datumTokenizer: null, + queryTokenizer: null, + remote: { url: 'url' } }; } function test_bloodhout_options_all() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: (datum: string) => { return new Array(); }, - queryTokenizer: (query: string) => { return new Array(); }, - initialize: true, - sufficient: 5, - sorter: (a: string, b: string) => { return 0 }, - local: () => { return new Array() }, - prefetch: { url: 'url' }, - remote: { url: 'url' } + datumTokenizer: (datum: string) => { return new Array(); }, + queryTokenizer: (query: string) => { return new Array(); }, + initialize: true, + sufficient: 5, + sorter: (a: string, b: string) => { return 0 }, + local: () => { return new Array() }, + prefetch: { url: 'url' }, + remote: { url: 'url' } }; } } @@ -335,35 +335,35 @@ function test_bloodhout() { function test_bloodhout_prefetch_options() { function test_bloodhout_prefetch_options_url() { var options: Bloodhound.PrefetchOptions = { - url: 'url' + url: 'url' }; } function test_bloodhout_prefetch_options_cache() { var options: Bloodhound.PrefetchOptions = { - url: 'url', - cache: true + url: 'url', + cache: true }; } function test_bloodhout_prefetch_options_ttl() { var options: Bloodhound.PrefetchOptions = { - url: 'url', - ttl: 86400000 // 1 day + url: 'url', + ttl: 86400000 // 1 day }; } function test_bloodhout_prefetch_options_cacheKey() { var options: Bloodhound.PrefetchOptions = { - url: 'url', - cacheKey: 'url' + url: 'url', + cacheKey: 'url' }; } function test_bloodhout_prefetch_options_thumbprint() { var options: Bloodhound.PrefetchOptions = { - url: 'url', - thumbprint: 'thumbprint' + url: 'url', + thumbprint: 'thumbprint' }; } @@ -371,15 +371,15 @@ function test_bloodhout() { var ajaxSettings: JQueryAjaxSettings = { url: 'url' }; var options: Bloodhound.PrefetchOptions = { - url: 'url', - prepare: (settings: JQueryAjaxSettings) => { return ajaxSettings; } + url: 'url', + prepare: (settings: JQueryAjaxSettings) => { return ajaxSettings; } }; } function test_bloodhout_prefetch_options_transform() { var options: Bloodhound.PrefetchOptions = { - url: 'url', - transform: (response: string[]) => { return new Array(); } + url: 'url', + transform: (response: string[]) => { return new Array(); } }; } @@ -387,13 +387,13 @@ function test_bloodhout() { var ajaxSettings: JQueryAjaxSettings = { url: 'url' }; var options: Bloodhound.PrefetchOptions = { - url: 'url', - cache: true, - ttl: 86400000, - cacheKey: 'url', - thumbprint: 'thumbprint', - prepare: (settings: JQueryAjaxSettings) => { return ajaxSettings; }, - transform: (response: string[]) => { return new Array(); } + url: 'url', + cache: true, + ttl: 86400000, + cacheKey: 'url', + thumbprint: 'thumbprint', + prepare: (settings: JQueryAjaxSettings) => { return ajaxSettings; }, + transform: (response: string[]) => { return new Array(); } }; } } @@ -401,7 +401,7 @@ function test_bloodhout() { function test_bloodhout_remote_options() { function test_bloodhout_remote_options_url() { var options: Bloodhound.RemoteOptions = { - url: 'url' + url: 'url' }; } @@ -409,36 +409,36 @@ function test_bloodhout() { var ajaxSettings: JQueryAjaxSettings = { url: 'url' }; var options: Bloodhound.RemoteOptions = { - url: 'url', - prepare: (query: string, settings: JQueryAjaxSettings) => { return ajaxSettings; } + url: 'url', + prepare: (query: string, settings: JQueryAjaxSettings) => { return ajaxSettings; } }; } function test_bloodhout_remote_options_wildcard() { var options: Bloodhound.RemoteOptions = { url: 'url', - wildcard: '%QUERY' + wildcard: '%QUERY' }; } function test_bloodhout_remote_options_rateLimitby() { var options: Bloodhound.RemoteOptions = { - url: 'url', - rateLimitby: 'debounce' + url: 'url', + rateLimitby: 'debounce' }; } function test_bloodhout_remote_options_rateLimitWait() { var options: Bloodhound.RemoteOptions = { - url: 'url', - rateLimitWait: 300 + url: 'url', + rateLimitWait: 300 }; } function test_bloodhout_remote_options_transform() { var options: Bloodhound.RemoteOptions = { - url: 'url', - transform: (response: string[]) => { return new Array(); } + url: 'url', + transform: (response: string[]) => { return new Array(); } }; } @@ -446,22 +446,22 @@ function test_bloodhout() { var ajaxSettings: JQueryAjaxSettings = { url: 'url' }; var options: Bloodhound.RemoteOptions = { - url: 'url', - prepare: (query: string, settings: JQueryAjaxSettings) => { return ajaxSettings; }, - wildcard: '%QUERY', - rateLimitby: 'debounce', - rateLimitWait: 300, - transform: (response: string[]) => { return new Array(); } + url: 'url', + prepare: (query: string, settings: JQueryAjaxSettings) => { return ajaxSettings; }, + wildcard: '%QUERY', + rateLimitby: 'debounce', + rateLimitWait: 300, + transform: (response: string[]) => { return new Array(); } }; } } function test_bloodhout_tokenizers() { var tokenizers: Bloodhound.Tokenizers = { - whitespace: (str: string) => { return new Array(); }, - nonword: (str: string) => { return new Array(); }, + whitespace: (str: string) => { return new Array(); }, + nonword: (str: string) => { return new Array(); }, obj: { - whitespace: (str: string) => { return new Array(); }, + whitespace: (str: string) => { return new Array(); }, nonword: (str: string) => { return new Array(); } } }; diff --git a/typeahead/typeahead.d.ts b/typeahead/typeahead.d.ts index 3fba4ff04..90daa580d 100644 --- a/typeahead/typeahead.d.ts +++ b/typeahead/typeahead.d.ts @@ -1,1207 +1,1207 @@ -// Type definitions for typeahead.js 0.11.1 -// Project: http://twitter.github.io/typeahead.js/ -// Definitions by: Ivaylo Gochkov , Gidon Junge -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -interface JQuery { - /** - * For a given input[type="text"], enables typeahead functionality. - * - * @constructor - * @param options Options hash that's used for configuration - * @param datasets Array of datasets - */ - typeahead(options: Twitter.Typeahead.Options, datasets: Twitter.Typeahead.Dataset[]): JQuery; - - /** - * For a given input[type="text"], enables typeahead functionality. - * - * @constructor - * @param options Options hash that's used for configuration - * @param dataset At least one dataset is required - * @param datasets Rest of the datasets. - */ - typeahead(options: Twitter.Typeahead.Options, dataset: Twitter.Typeahead.Dataset, ...datasets: Twitter.Typeahead.Dataset[]): JQuery; - - /** - * Returns the current value of the typeahead. - * The value is the text the user has entered into the input element. - * - * @constructor - * @param methodName Method 'val' - */ - typeahead(methodName: 'val'): string; - - /** - * Accommodates the val overload. - * - * @constructor - * @param methodName Method 'val' - */ - typeahead(methodName: string): string; - - /** - * Sets the value of the typeahead. This should be used in place of jQuery#val. - * - * @constructor - * @param methodName Method 'val' - * @param val The value to be set - */ - typeahead(methodName: 'val', val: string): JQuery; - - /** - * Accommodates the set val overload. - * - * @constructor - * @param methodName Method 'val' - * @param val The value to be set - */ - typeahead(methodName: string, val: string): JQuery; - - /** - * Opens the suggestion menu. - * - * @constructor - * @param methodName Method 'open' - */ - typeahead(methodName: 'open'): JQuery; - - /** - * Closes the suggestion menu. - * - * @constructor - * @param methodName Method 'close' - */ - typeahead(methodName: 'close'): JQuery; - - /** - * Removes typeahead functionality and reverts the input element back to its original state. - * - * @constructor - * @param methodName Method 'destroy' - */ - typeahead(methodName: 'destroy'): JQuery; - - /** - * Attach an event handler function for typeahead:active event to the selected elements. - * - * @param events typeahead:active event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:active", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:active event to the selected elements. - * - * @param events typeahead:active event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:active", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:active event to the selected elements. - * - * @param events typeahead:active event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:active", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:active event to the selected elements. - * - * @param events typeahead:active event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:active", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:idle event to the selected elements. - * - * @param events typeahead:idle event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:idle", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:idle event to the selected elements. - * - * @param events typeahead:idle event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:idle", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:idle event to the selected elements. - * - * @param events typeahead:idle event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:idle", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:idle event to the selected elements. - * - * @param events typeahead:idle event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:idle", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:open event to the selected elements. - * - * @param events typeahead:open event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:open", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:open event to the selected elements. - * - * @param events typeahead:open event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:open", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:open event to the selected elements. - * - * @param events typeahead:open event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:open", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:open event to the selected elements. - * - * @param events typeahead:open event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:open", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:close event to the selected elements. - * - * @param events typeahead:close event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:close", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:close event to the selected elements. - * - * @param events typeahead:close event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:close", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:close event to the selected elements. - * - * @param events typeahead:close event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:close", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:close event to the selected elements. - * - * @param events typeahead:close event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:close", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:change event to the selected elements. - * - * @param events typeahead:change event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:change", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:change event to the selected elements. - * - * @param events typeahead:change event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:change", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:change event to the selected elements. - * - * @param events typeahead:change event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:change", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:change event to the selected elements. - * - * @param events typeahead:change event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:change", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:render event to the selected elements. - * - * @param events typeahead:render event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:render", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:render event to the selected elements. - * - * @param events typeahead:render event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:render", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:render event to the selected elements. - * - * @param events typeahead:render event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:render", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:render event to the selected elements. - * - * @param events typeahead:render event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:render", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:select event to the selected elements. - * - * @param events typeahead:select event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:select", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:select event to the selected elements. - * - * @param events typeahead:select event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:select", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:select event to the selected elements. - * - * @param events typeahead:select event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:select", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:select event to the selected elements. - * - * @param events typeahead:select event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:select", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:autocomplete event to the selected elements. - * - * @param events typeahead:autocomplete event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:autocomplete", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:autocomplete event to the selected elements. - * - * @param events typeahead:autocomplete event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:autocomplete", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:autocomplete event to the selected elements. - * - * @param events typeahead:autocomplete event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:autocomplete", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:autocomplete event to the selected elements. - * - * @param events typeahead:autocomplete event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:autocomplete", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:cursorchange event to the selected elements. - * - * @param events typeahead:cursorchange event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:cursorchange", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:cursorchange event to the selected elements. - * - * @param events typeahead:cursorchange event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:cursorchange", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:cursorchange event to the selected elements. - * - * @param events typeahead:cursorchange event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:cursorchange", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:cursorchange event to the selected elements. - * - * @param events typeahead:cursorchange event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:cursorchange", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asyncrequest event to the selected elements. - * - * @param events typeahead:asyncrequest event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:asyncrequest", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asyncrequest event to the selected elements. - * - * @param events typeahead:asyncrequest event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:asyncrequest", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asyncrequest event to the selected elements. - * - * @param events typeahead:asyncrequest event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:asyncrequest", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asyncrequest event to the selected elements. - * - * @param events typeahead:asyncrequest event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:asyncrequest", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asynccancel event to the selected elements. - * - * @param events typeahead:asynccancel event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:asynccancel", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asynccancel event to the selected elements. - * - * @param events typeahead:asynccancel event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:asynccancel", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asynccancel event to the selected elements. - * - * @param events typeahead:asynccancel event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:asynccancel", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asynccancel event to the selected elements. - * - * @param events typeahead:asynccancel event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:asynccancel", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asyncreceive event to the selected elements. - * - * @param events typeahead:asyncreceive event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:asyncreceive", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asyncreceive event to the selected elements. - * - * @param events typeahead:asyncreceive event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:asyncreceive", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asyncreceive event to the selected elements. - * - * @param events typeahead:asyncreceive event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:asyncreceive", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asyncreceive event to the selected elements. - * - * @param events typeahead:asyncreceive event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:asyncreceive", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:active event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:active", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:active event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:active", handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:idle event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:idle", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:idle event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:idle", handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:open event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:open", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:open event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:open", handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:close event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:close", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:close event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:close", handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:change event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:change", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:change event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:change", handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:render event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:render", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:render event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:render", handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:select event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:select", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:select event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:select", handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:autocomplete event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:autocomplete", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:autocomplete event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:autocomplete", handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:cursorchange event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:cursorchange", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:cursorchange event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:cursorchange", handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:asyncrequest event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:asyncrequest", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:asyncrequest event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:asyncrequest", handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:asynccancel event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:asynccancel", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:asynccancel event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:asynccancel", handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:asyncreceive event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:asyncreceive", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:asyncreceive event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:asyncreceive", handler: (eventObject: JQueryEventObject) => any): JQuery; -} - -declare module Twitter.Typeahead { - interface Options { - /** - * If true, when suggestions are rendered, pattern matches for the current query in text nodes will be wrapped in a strong element with its class set to {{classNames.highlight}}. - * Defaults to false. - */ - highlight?: boolean; - - /** - * If false, the typeahead will not show a hint. - * Defaults to true. - */ - hint?: boolean; - - /** - * The minimum character length needed before suggestions start getting rendered. - * Defaults to 1. - */ - minLength?: number; - - /** - * Used for overriding the default class names. - */ - classNames?: ClassNames; - } - - /** - * A typeahead is composed of one or more datasets. When an end-user - * modifies the value of a typeahead, each dataset will attempt to render - * suggestions for the new value. - * For most use cases, one dataset should suffice. It's only in the scenario - * where you want rendered suggestions to be grouped based on some sort of - * categorical relationship that you'd need to use multiple datasets. For - * example, on twitter.com, the search typeahead groups results into recent - * searches, trends, and accounts – that would be a great use case for using - * multiple datasets. - */ - interface Dataset { - /** - * The backing data source for suggestions. - * Expected to be a function with the signature (query, syncResults, asyncResults). - * syncResults should be called with suggestions computed synchronously and - * asyncResults should be called with suggestions computed asynchronously - * (e.g. suggestions that come for an AJAX request). - * source can also be a Bloodhound instance. - */ - source: Bloodhound | ((query: string, syncResults: (result: T[]) => void, asyncResults?: (result: T[]) => void) => void); - - /** - * Lets the dataset know if async suggestions should be expected. - * If not set, this information is inferred from the signature of - * source i.e. if the source function expects 3 arguments, async will - * be set to true. - */ - async?: boolean; - - /** - * The name of the dataset. - * This will be appended to {{classNames.dataset}} - to form the class name of the containing DOM element. - * Must only consist of underscores, dashes, letters (a-z), and numbers. - * Defaults to a random number. - */ - name?: string; - - /** - * The max number of suggestions to be displayed. Defaults to 5. - */ - limit?: number; - - /** - * For a given suggestion, determines the string representation of it. - * This will be used when setting the value of the input control after - * a suggestion is selected. Can be either a key string or a function - * that transforms a suggestion object into a string. - * Defaults to stringifying the suggestion. - */ - display?: string | ((obj: T) => string); - - /** - * A hash of templates to be used when rendering the dataset. Note a - * precompiled template is a function that takes a JavaScript object as - * its first argument and returns a HTML string. - */ - templates?: Templates; - } - - /** - * A hash of templates to be used when rendering the dataset. Note a - * precompiled template is a function that takes a JavaScript object as - * its first argument and returns a HTML string. - */ - interface Templates { - /** - * Rendered when 0 suggestions are available for the given query. - * Can be either a HTML string or a precompiled template. - * If it's a precompiled template, the passed in context will contain query. - */ - notFound?: string | ((query: string) => string); - - /** - * Rendered when 0 synchronous suggestions are available but asynchronous suggestions are expected. - * Can be either a HTML string or a precompiled template. - * If it's a precompiled template, the passed in context will contain query. - */ - pending?: string | ((query: string) => string); - - /** - * Rendered at the top of the dataset when suggestions are present. Can be either a HTML string or - * a precompiled template. If it's a precompiled template, the passed in context will contain - * query and suggestions. - */ - header?: string | ((query: string, suggestions: T[]) => string); - - /** - * Rendered at the bottom of the dataset when suggestions are present. Can be either a HTML string or - * a precompiled template. If it's a precompiled template, the passed in context will contain - * query and suggestions. - */ - footer?: string | ((query: string, suggestions: T[]) => string); - - /** - * Used to render a single suggestion. If set, this has to be a precompiled template. - * The associated suggestion object will serve as the context. - * Defaults to the value of display wrapped in a div tag i.e.
    {{value}}
    . - */ - suggestion?: (suggestion: T) => string; - } - - /** - * Used for overriding the default class names. - */ - interface ClassNames { - /** - * Added to input that's initialized into a typeahead. Defaults to tt-input. - */ - input?: string; - - /** - * Added to hint input.Defaults to tt- hint. - */ - hint?: string; - - /** - * Added to menu element.Defaults to tt- menu. - */ - menu?: string; - - /** - * Added to dataset elements.to Defaults to tt- dataset. - */ - dataset?: string; - /** - * Added to suggestion elements.Defaults to tt- suggestion. - */ - suggestion?: string; - - /** - * Added to menu element when it contains no content.Defaults to tt- empty. - */ - empty?: string; - - /** - * Added to menu element when it is opened.Defaults to tt- open. - */ - open?: string; - - /** - * Added to suggestion element when menu cursor moves to said suggestion.Defaults to tt- cursor. - */ - cursor?: string; - - /** - * Added to the element that wraps highlighted text.Defaults to tt- highlight. - */ - highlight?: string; - } -} - -declare module Bloodhound { - interface BloodhoundOptions { - /** - * Transforms a datum into an array of string tokens. - * - * @param datum Suggestion. - * @returns An array of string tokens. - */ - datumTokenizer: (datum: T) => string[]; - - /** - * Transforms a query into an array of string tokens. - * - * @param quiery Query. - * @returns An array of string tokens. - */ - queryTokenizer: (query: string) => string[]; - - /** - * If set to false, the Bloodhound instance will not be implicitly - * initialized by the constructor function. Defaults to true. - */ - initialize?: boolean; - - /** - * Given a datum, returns a unique id for it. - * Defaults to JSON.stringify. Note that it is highly recommended - * to override this option. - * - * @param datum Suggestion. - * @returns Unique id for the suggestion. - */ - identify?: (datum: T) => number; - - /** - * If the number of datums provided from the internal search index is - * less than sufficient, remote will be used to backfill search - * requests triggered by calling #search. Defaults to 5. - */ - sufficient?: number; - - /** - * A compare function used to sort data returned from the internal search index. - * - * @param a First suggestion. - * @param b Second suggestion. - * @returns Comparison result. - */ - sorter?: (a: T, b: T) => number; - - /** - * An array of data or a function that returns an array of data. - * The data will be added to the internal search index when #initialize is called. - */ - local?: T[] | (() => T[]); - - /** - * Can be a URL to a JSON file containing an array of data or, - * if more configurability is needed, a prefetch options hash. - */ - prefetch?: string | PrefetchOptions; - - /** - * Can be a URL to fetch data from when the data provided by the internal - * search index is insufficient or, if more configurability is needed, - * a remote options hash. - */ - remote?: string | RemoteOptions; - } - - /** - * Prefetched data is fetched and processed on initialization. If the browser - * supports local storage, the processed data will be cached there to prevent - * additional network requests on subsequent page loads. - * - * WARNING: While it's possible to get away with it for smaller data sets, - * prefetched data isn't meant to contain entire sets of data. Rather, it should - * act as a first-level cache. Ignoring this warning means you'll run the risk - * of hitting local storage limits. - */ - interface PrefetchOptions { - /** - * The URL prefetch data should be loaded from. - */ - url: string; - - /** - * If false, will not attempt to read or write to local storage and - * will always load prefetch data from url on initialization. Defaults to true. - */ - cache?: boolean; - - /** - * The time (in milliseconds) the prefetched data should be cached in - * local storage. Defaults to 86400000 (1 day). - */ - ttl?: number; - - /** - * The key that data will be stored in local storage under. - * Defaults to value of url. - */ - cacheKey?: string; - - /** - * A string used for thumbprinting prefetched data. If this doesn't - * match what's stored in local storage, the data will be refetched. - */ - thumbprint?: string; - - /** - * A function that provides a hook to allow you to prepare the settings - * object passed to transport when a request is about to be made. - * Defaults to the identity function. - * - * @param settings The default settings object created internally by the Bloodhound instance. - * @returns A settings object. - */ - prepare?: (settings: JQueryAjaxSettings) => JQueryAjaxSettings; - - /** - * A function with the signature transform(response) that allows you to - * transform the prefetch response before the Bloodhound instance operates - * on it. Defaults to the identity function. - * - * @param response Prefetch response. - * @returns Transform response. - */ - transform?: (response: T[]) => T[]; - } - - /** - * Bloodhound only goes to the network when the internal search engine cannot - * provide a sufficient number of results. In order to prevent an obscene - * number of requests being made to the remote endpoint, requests are rate-limited. - */ - interface RemoteOptions { - /** - * The URL remote data should be loaded from. - */ - url: string; - - /** - * A function that provides a hook to allow you to prepare the settings - * object passed to transport when a request is about to be made. - * The function signature should be prepare(query, settings), where query - * is the query #search was called with and settings is the default settings - * object created internally by the Bloodhound instance. The prepare function - * should return a settings object. Defaults to the identity function. - * - * @param query The query #search was called with. - * @param settings The default settings object created internally by Bloodhound. - * @returns A JqueryAjaxSettings object. - */ - prepare?: (query: string, settings: JQueryAjaxSettings) => JQueryAjaxSettings; - - /** - * A convenience option for prepare. If set, prepare will be a function - * that replaces the value of this option in url with the URI encoded query. - */ - wildcard?: string; - - /** - * The method used to rate-limit network requests. - * Can be either debounce or throttle. Defaults to debounce. - */ - rateLimitby?: string; - - /** - * The time interval in milliseconds that will be used by rateLimitBy. - * Defaults to 300. - */ - rateLimitWait?: number; - - /** - * A function with the signature transform(response) that allows you to - * transform the remote response before the Bloodhound instance operates on it. - * Defaults to the identity function. - * - * @param response Prefetch response. - * @returns Transform response. - */ - transform?: (response: T[]) => T[]; - } - - /** - * Build-in tokenization methods. - */ - interface Tokenizers { - /** - * Split a given string on whitespace characters. - */ - whitespace(str: string): string[]; - - /** - * Split a given string on non-word characters. - */ - nonword(str: string): string[]; - - /** - * Instances of the build-in tokenization methods. - */ - obj: ObjTokenizer; - } - - interface ObjTokenizer { - /** - * Split a given string on whitespace characters. - */ - whitespace(str: string): string[]; - - /** - * Split a given string on non-word characters. - */ - nonword(str: string): string[]; - } -} - -/** - * Bloodhound is the typeahead.js suggestion engine. Bloodhound is robust, - * flexible, and offers advanced functionalities such as prefetching, - * intelligent caching, fast lookups, and backfilling with remote data. - */ -declare class Bloodhound { - /** - * The constructor function. - * - * @constructor - * @param options Options hash. - */ - constructor(options: Bloodhound.BloodhoundOptions); - - /** - * Returns a reference to Bloodhound and reverts window.Bloodhound to its - * previous value. Can be used to avoid naming collisions. - */ - public static noConflict(): Bloodhound; - - /** - * The Bloodhound suggestion engine is token-based, so how datums and queries are tokenized plays a vital role in the quality of search results. - * Specify how you want datums and queries tokenized. - */ - public static tokenizers: Bloodhound.Tokenizers; - - /** - * Kicks off the initialization of the suggestion engine. Initialization - * entails adding the data provided by local and prefetch to the internal - * search index as well as setting up transport mechanism used by remote. - * Before #initialize is called, the #get and #search methods will effectively be no-ops. - * - * Note, unless the initialize option is false, this method is implicitly called by the constructor. - * - * After initialization, how subsequent invocations of #initialize behave depends on - * the reinitialize argument. If reinitialize is falsy, the method will not execute the - * initialization logic and will just return the same jQuery promise returned - * by the initial invocation. If reinitialize is truthy, the method will behave - * as if it were being called for the first time. - * - * @param reinitialize How subsequent invocations of #initialize will behave. - * @returns jQuery promise. - */ - public initialize(reinitialize?: boolean): JQueryPromise; - - /** - * Takes one argument, data, which is expected to be an array. - * The data passed in will get added to the internal search index. - * - * @param data Data to be added to the internal search index. - */ - public add(data: T[]): void; - - /** - * Returns the data in the local search index corresponding to ids. - * - * @param ids Data ids. - * @returns The corresponding data. - */ - public get(ids: number[]): T[]; - - /** - * Returns the data that matches query. Matches found in the local search - * index will be passed to the sync callback. If the data passed to sync - * doesn't contain at least sufficient number of datums, remote data will - * be requested and then passed to the async callback. - * - * @param query Query. - * @param sync Sync callback - * @param async Async callback. - * @returns The data that matches query. - */ - public search(query: string, sync: (datums: T[]) => void, async: (datums: T[]) => void): T[]; - - /** - * Returns all items from the internal search index. - */ - public all(): T[]; - - /** - * Clears the internal search index that's powered by local, prefetch, and #add. - */ - public clear(): Bloodhound; - - /** - * If you're using prefetch, data gets cached in local storage in an effort to cut down on unnecessary network requests. - * clearPrefetchCache offers a way to programmatically clear said cache. - */ - public clearPrefetchCache(): Bloodhound; - - /** - * If you're using remote, Bloodhound will cache the 10 most recent responses in an effort to provide a better user experience. - * clearRemoteCache offers a way to programmatically clear said cache. - */ - public clearRemoteCache(): Bloodhound; -} - -declare module "bloodhound" { - export = Bloodhound; -} +// Type definitions for typeahead.js 0.11.1 +// Project: http://twitter.github.io/typeahead.js/ +// Definitions by: Ivaylo Gochkov , Gidon Junge +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface JQuery { + /** + * For a given input[type="text"], enables typeahead functionality. + * + * @constructor + * @param options Options hash that's used for configuration + * @param datasets Array of datasets + */ + typeahead(options: Twitter.Typeahead.Options, datasets: Twitter.Typeahead.Dataset[]): JQuery; + + /** + * For a given input[type="text"], enables typeahead functionality. + * + * @constructor + * @param options Options hash that's used for configuration + * @param dataset At least one dataset is required + * @param datasets Rest of the datasets. + */ + typeahead(options: Twitter.Typeahead.Options, dataset: Twitter.Typeahead.Dataset, ...datasets: Twitter.Typeahead.Dataset[]): JQuery; + + /** + * Returns the current value of the typeahead. + * The value is the text the user has entered into the input element. + * + * @constructor + * @param methodName Method 'val' + */ + typeahead(methodName: 'val'): string; + + /** + * Accommodates the val overload. + * + * @constructor + * @param methodName Method 'val' + */ + typeahead(methodName: string): string; + + /** + * Sets the value of the typeahead. This should be used in place of jQuery#val. + * + * @constructor + * @param methodName Method 'val' + * @param val The value to be set + */ + typeahead(methodName: 'val', val: string): JQuery; + + /** + * Accommodates the set val overload. + * + * @constructor + * @param methodName Method 'val' + * @param val The value to be set + */ + typeahead(methodName: string, val: string): JQuery; + + /** + * Opens the suggestion menu. + * + * @constructor + * @param methodName Method 'open' + */ + typeahead(methodName: 'open'): JQuery; + + /** + * Closes the suggestion menu. + * + * @constructor + * @param methodName Method 'close' + */ + typeahead(methodName: 'close'): JQuery; + + /** + * Removes typeahead functionality and reverts the input element back to its original state. + * + * @constructor + * @param methodName Method 'destroy' + */ + typeahead(methodName: 'destroy'): JQuery; + + /** + * Attach an event handler function for typeahead:active event to the selected elements. + * + * @param events typeahead:active event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:active", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:active event to the selected elements. + * + * @param events typeahead:active event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:active", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:active event to the selected elements. + * + * @param events typeahead:active event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:active", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:active event to the selected elements. + * + * @param events typeahead:active event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:active", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:idle event to the selected elements. + * + * @param events typeahead:idle event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:idle", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:idle event to the selected elements. + * + * @param events typeahead:idle event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:idle", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:idle event to the selected elements. + * + * @param events typeahead:idle event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:idle", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:idle event to the selected elements. + * + * @param events typeahead:idle event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:idle", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:open event to the selected elements. + * + * @param events typeahead:open event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:open", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:open event to the selected elements. + * + * @param events typeahead:open event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:open", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:open event to the selected elements. + * + * @param events typeahead:open event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:open", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:open event to the selected elements. + * + * @param events typeahead:open event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:open", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:close event to the selected elements. + * + * @param events typeahead:close event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:close", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:close event to the selected elements. + * + * @param events typeahead:close event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:close", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:close event to the selected elements. + * + * @param events typeahead:close event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:close", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:close event to the selected elements. + * + * @param events typeahead:close event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:close", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:change event to the selected elements. + * + * @param events typeahead:change event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:change", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:change event to the selected elements. + * + * @param events typeahead:change event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:change", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:change event to the selected elements. + * + * @param events typeahead:change event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:change", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:change event to the selected elements. + * + * @param events typeahead:change event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:change", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:render event to the selected elements. + * + * @param events typeahead:render event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:render", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:render event to the selected elements. + * + * @param events typeahead:render event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:render", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:render event to the selected elements. + * + * @param events typeahead:render event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:render", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:render event to the selected elements. + * + * @param events typeahead:render event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:render", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:select event to the selected elements. + * + * @param events typeahead:select event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:select", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:select event to the selected elements. + * + * @param events typeahead:select event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:select", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:select event to the selected elements. + * + * @param events typeahead:select event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:select", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:select event to the selected elements. + * + * @param events typeahead:select event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:select", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:autocomplete event to the selected elements. + * + * @param events typeahead:autocomplete event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:autocomplete", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:autocomplete event to the selected elements. + * + * @param events typeahead:autocomplete event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:autocomplete", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:autocomplete event to the selected elements. + * + * @param events typeahead:autocomplete event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:autocomplete", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:autocomplete event to the selected elements. + * + * @param events typeahead:autocomplete event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:autocomplete", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:cursorchange event to the selected elements. + * + * @param events typeahead:cursorchange event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:cursorchange", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:cursorchange event to the selected elements. + * + * @param events typeahead:cursorchange event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:cursorchange", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:cursorchange event to the selected elements. + * + * @param events typeahead:cursorchange event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:cursorchange", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:cursorchange event to the selected elements. + * + * @param events typeahead:cursorchange event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:cursorchange", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asyncrequest event to the selected elements. + * + * @param events typeahead:asyncrequest event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:asyncrequest", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asyncrequest event to the selected elements. + * + * @param events typeahead:asyncrequest event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:asyncrequest", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asyncrequest event to the selected elements. + * + * @param events typeahead:asyncrequest event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:asyncrequest", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asyncrequest event to the selected elements. + * + * @param events typeahead:asyncrequest event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:asyncrequest", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asynccancel event to the selected elements. + * + * @param events typeahead:asynccancel event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:asynccancel", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asynccancel event to the selected elements. + * + * @param events typeahead:asynccancel event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:asynccancel", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asynccancel event to the selected elements. + * + * @param events typeahead:asynccancel event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:asynccancel", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asynccancel event to the selected elements. + * + * @param events typeahead:asynccancel event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:asynccancel", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asyncreceive event to the selected elements. + * + * @param events typeahead:asyncreceive event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:asyncreceive", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asyncreceive event to the selected elements. + * + * @param events typeahead:asyncreceive event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:asyncreceive", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asyncreceive event to the selected elements. + * + * @param events typeahead:asyncreceive event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:asyncreceive", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asyncreceive event to the selected elements. + * + * @param events typeahead:asyncreceive event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:asyncreceive", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:active event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:active", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:active event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:active", handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:idle event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:idle", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:idle event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:idle", handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:open event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:open", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:open event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:open", handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:close event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:close", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:close event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:close", handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:change event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:change", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:change event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:change", handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:render event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:render", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:render event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:render", handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:select event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:select", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:select event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:select", handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:autocomplete event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:autocomplete", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:autocomplete event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:autocomplete", handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:cursorchange event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:cursorchange", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:cursorchange event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:cursorchange", handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:asyncrequest event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:asyncrequest", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:asyncrequest event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:asyncrequest", handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:asynccancel event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:asynccancel", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:asynccancel event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:asynccancel", handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:asyncreceive event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:asyncreceive", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:asyncreceive event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:asyncreceive", handler: (eventObject: JQueryEventObject) => any): JQuery; +} + +declare module Twitter.Typeahead { + interface Options { + /** + * If true, when suggestions are rendered, pattern matches for the current query in text nodes will be wrapped in a strong element with its class set to {{classNames.highlight}}. + * Defaults to false. + */ + highlight?: boolean; + + /** + * If false, the typeahead will not show a hint. + * Defaults to true. + */ + hint?: boolean; + + /** + * The minimum character length needed before suggestions start getting rendered. + * Defaults to 1. + */ + minLength?: number; + + /** + * Used for overriding the default class names. + */ + classNames?: ClassNames; + } + + /** + * A typeahead is composed of one or more datasets. When an end-user + * modifies the value of a typeahead, each dataset will attempt to render + * suggestions for the new value. + * For most use cases, one dataset should suffice. It's only in the scenario + * where you want rendered suggestions to be grouped based on some sort of + * categorical relationship that you'd need to use multiple datasets. For + * example, on twitter.com, the search typeahead groups results into recent + * searches, trends, and accounts – that would be a great use case for using + * multiple datasets. + */ + interface Dataset { + /** + * The backing data source for suggestions. + * Expected to be a function with the signature (query, syncResults, asyncResults). + * syncResults should be called with suggestions computed synchronously and + * asyncResults should be called with suggestions computed asynchronously + * (e.g. suggestions that come for an AJAX request). + * source can also be a Bloodhound instance. + */ + source: Bloodhound | ((query: string, syncResults: (result: T[]) => void, asyncResults?: (result: T[]) => void) => void); + + /** + * Lets the dataset know if async suggestions should be expected. + * If not set, this information is inferred from the signature of + * source i.e. if the source function expects 3 arguments, async will + * be set to true. + */ + async?: boolean; + + /** + * The name of the dataset. + * This will be appended to {{classNames.dataset}} - to form the class name of the containing DOM element. + * Must only consist of underscores, dashes, letters (a-z), and numbers. + * Defaults to a random number. + */ + name?: string; + + /** + * The max number of suggestions to be displayed. Defaults to 5. + */ + limit?: number; + + /** + * For a given suggestion, determines the string representation of it. + * This will be used when setting the value of the input control after + * a suggestion is selected. Can be either a key string or a function + * that transforms a suggestion object into a string. + * Defaults to stringifying the suggestion. + */ + display?: string | ((obj: T) => string); + + /** + * A hash of templates to be used when rendering the dataset. Note a + * precompiled template is a function that takes a JavaScript object as + * its first argument and returns a HTML string. + */ + templates?: Templates; + } + + /** + * A hash of templates to be used when rendering the dataset. Note a + * precompiled template is a function that takes a JavaScript object as + * its first argument and returns a HTML string. + */ + interface Templates { + /** + * Rendered when 0 suggestions are available for the given query. + * Can be either a HTML string or a precompiled template. + * If it's a precompiled template, the passed in context will contain query. + */ + notFound?: string | ((query: string) => string); + + /** + * Rendered when 0 synchronous suggestions are available but asynchronous suggestions are expected. + * Can be either a HTML string or a precompiled template. + * If it's a precompiled template, the passed in context will contain query. + */ + pending?: string | ((query: string) => string); + + /** + * Rendered at the top of the dataset when suggestions are present. Can be either a HTML string or + * a precompiled template. If it's a precompiled template, the passed in context will contain + * query and suggestions. + */ + header?: string | ((query: string, suggestions: T[]) => string); + + /** + * Rendered at the bottom of the dataset when suggestions are present. Can be either a HTML string or + * a precompiled template. If it's a precompiled template, the passed in context will contain + * query and suggestions. + */ + footer?: string | ((query: string, suggestions: T[]) => string); + + /** + * Used to render a single suggestion. If set, this has to be a precompiled template. + * The associated suggestion object will serve as the context. + * Defaults to the value of display wrapped in a div tag i.e.
    {{value}}
    . + */ + suggestion?: (suggestion: T) => string; + } + + /** + * Used for overriding the default class names. + */ + interface ClassNames { + /** + * Added to input that's initialized into a typeahead. Defaults to tt-input. + */ + input?: string; + + /** + * Added to hint input.Defaults to tt- hint. + */ + hint?: string; + + /** + * Added to menu element.Defaults to tt- menu. + */ + menu?: string; + + /** + * Added to dataset elements.to Defaults to tt- dataset. + */ + dataset?: string; + /** + * Added to suggestion elements.Defaults to tt- suggestion. + */ + suggestion?: string; + + /** + * Added to menu element when it contains no content.Defaults to tt- empty. + */ + empty?: string; + + /** + * Added to menu element when it is opened.Defaults to tt- open. + */ + open?: string; + + /** + * Added to suggestion element when menu cursor moves to said suggestion.Defaults to tt- cursor. + */ + cursor?: string; + + /** + * Added to the element that wraps highlighted text.Defaults to tt- highlight. + */ + highlight?: string; + } +} + +declare module Bloodhound { + interface BloodhoundOptions { + /** + * Transforms a datum into an array of string tokens. + * + * @param datum Suggestion. + * @returns An array of string tokens. + */ + datumTokenizer: (datum: T) => string[]; + + /** + * Transforms a query into an array of string tokens. + * + * @param quiery Query. + * @returns An array of string tokens. + */ + queryTokenizer: (query: string) => string[]; + + /** + * If set to false, the Bloodhound instance will not be implicitly + * initialized by the constructor function. Defaults to true. + */ + initialize?: boolean; + + /** + * Given a datum, returns a unique id for it. + * Defaults to JSON.stringify. Note that it is highly recommended + * to override this option. + * + * @param datum Suggestion. + * @returns Unique id for the suggestion. + */ + identify?: (datum: T) => number; + + /** + * If the number of datums provided from the internal search index is + * less than sufficient, remote will be used to backfill search + * requests triggered by calling #search. Defaults to 5. + */ + sufficient?: number; + + /** + * A compare function used to sort data returned from the internal search index. + * + * @param a First suggestion. + * @param b Second suggestion. + * @returns Comparison result. + */ + sorter?: (a: T, b: T) => number; + + /** + * An array of data or a function that returns an array of data. + * The data will be added to the internal search index when #initialize is called. + */ + local?: T[] | (() => T[]); + + /** + * Can be a URL to a JSON file containing an array of data or, + * if more configurability is needed, a prefetch options hash. + */ + prefetch?: string | PrefetchOptions; + + /** + * Can be a URL to fetch data from when the data provided by the internal + * search index is insufficient or, if more configurability is needed, + * a remote options hash. + */ + remote?: string | RemoteOptions; + } + + /** + * Prefetched data is fetched and processed on initialization. If the browser + * supports local storage, the processed data will be cached there to prevent + * additional network requests on subsequent page loads. + * + * WARNING: While it's possible to get away with it for smaller data sets, + * prefetched data isn't meant to contain entire sets of data. Rather, it should + * act as a first-level cache. Ignoring this warning means you'll run the risk + * of hitting local storage limits. + */ + interface PrefetchOptions { + /** + * The URL prefetch data should be loaded from. + */ + url: string; + + /** + * If false, will not attempt to read or write to local storage and + * will always load prefetch data from url on initialization. Defaults to true. + */ + cache?: boolean; + + /** + * The time (in milliseconds) the prefetched data should be cached in + * local storage. Defaults to 86400000 (1 day). + */ + ttl?: number; + + /** + * The key that data will be stored in local storage under. + * Defaults to value of url. + */ + cacheKey?: string; + + /** + * A string used for thumbprinting prefetched data. If this doesn't + * match what's stored in local storage, the data will be refetched. + */ + thumbprint?: string; + + /** + * A function that provides a hook to allow you to prepare the settings + * object passed to transport when a request is about to be made. + * Defaults to the identity function. + * + * @param settings The default settings object created internally by the Bloodhound instance. + * @returns A settings object. + */ + prepare?: (settings: JQueryAjaxSettings) => JQueryAjaxSettings; + + /** + * A function with the signature transform(response) that allows you to + * transform the prefetch response before the Bloodhound instance operates + * on it. Defaults to the identity function. + * + * @param response Prefetch response. + * @returns Transform response. + */ + transform?: (response: T[]) => T[]; + } + + /** + * Bloodhound only goes to the network when the internal search engine cannot + * provide a sufficient number of results. In order to prevent an obscene + * number of requests being made to the remote endpoint, requests are rate-limited. + */ + interface RemoteOptions { + /** + * The URL remote data should be loaded from. + */ + url: string; + + /** + * A function that provides a hook to allow you to prepare the settings + * object passed to transport when a request is about to be made. + * The function signature should be prepare(query, settings), where query + * is the query #search was called with and settings is the default settings + * object created internally by the Bloodhound instance. The prepare function + * should return a settings object. Defaults to the identity function. + * + * @param query The query #search was called with. + * @param settings The default settings object created internally by Bloodhound. + * @returns A JqueryAjaxSettings object. + */ + prepare?: (query: string, settings: JQueryAjaxSettings) => JQueryAjaxSettings; + + /** + * A convenience option for prepare. If set, prepare will be a function + * that replaces the value of this option in url with the URI encoded query. + */ + wildcard?: string; + + /** + * The method used to rate-limit network requests. + * Can be either debounce or throttle. Defaults to debounce. + */ + rateLimitby?: string; + + /** + * The time interval in milliseconds that will be used by rateLimitBy. + * Defaults to 300. + */ + rateLimitWait?: number; + + /** + * A function with the signature transform(response) that allows you to + * transform the remote response before the Bloodhound instance operates on it. + * Defaults to the identity function. + * + * @param response Prefetch response. + * @returns Transform response. + */ + transform?: (response: T[]) => T[]; + } + + /** + * Build-in tokenization methods. + */ + interface Tokenizers { + /** + * Split a given string on whitespace characters. + */ + whitespace(str: string): string[]; + + /** + * Split a given string on non-word characters. + */ + nonword(str: string): string[]; + + /** + * Instances of the build-in tokenization methods. + */ + obj: ObjTokenizer; + } + + interface ObjTokenizer { + /** + * Split a given string on whitespace characters. + */ + whitespace(str: string): string[]; + + /** + * Split a given string on non-word characters. + */ + nonword(str: string): string[]; + } +} + +/** + * Bloodhound is the typeahead.js suggestion engine. Bloodhound is robust, + * flexible, and offers advanced functionalities such as prefetching, + * intelligent caching, fast lookups, and backfilling with remote data. + */ +declare class Bloodhound { + /** + * The constructor function. + * + * @constructor + * @param options Options hash. + */ + constructor(options: Bloodhound.BloodhoundOptions); + + /** + * Returns a reference to Bloodhound and reverts window.Bloodhound to its + * previous value. Can be used to avoid naming collisions. + */ + public static noConflict(): Bloodhound; + + /** + * The Bloodhound suggestion engine is token-based, so how datums and queries are tokenized plays a vital role in the quality of search results. + * Specify how you want datums and queries tokenized. + */ + public static tokenizers: Bloodhound.Tokenizers; + + /** + * Kicks off the initialization of the suggestion engine. Initialization + * entails adding the data provided by local and prefetch to the internal + * search index as well as setting up transport mechanism used by remote. + * Before #initialize is called, the #get and #search methods will effectively be no-ops. + * + * Note, unless the initialize option is false, this method is implicitly called by the constructor. + * + * After initialization, how subsequent invocations of #initialize behave depends on + * the reinitialize argument. If reinitialize is falsy, the method will not execute the + * initialization logic and will just return the same jQuery promise returned + * by the initial invocation. If reinitialize is truthy, the method will behave + * as if it were being called for the first time. + * + * @param reinitialize How subsequent invocations of #initialize will behave. + * @returns jQuery promise. + */ + public initialize(reinitialize?: boolean): JQueryPromise; + + /** + * Takes one argument, data, which is expected to be an array. + * The data passed in will get added to the internal search index. + * + * @param data Data to be added to the internal search index. + */ + public add(data: T[]): void; + + /** + * Returns the data in the local search index corresponding to ids. + * + * @param ids Data ids. + * @returns The corresponding data. + */ + public get(ids: number[]): T[]; + + /** + * Returns the data that matches query. Matches found in the local search + * index will be passed to the sync callback. If the data passed to sync + * doesn't contain at least sufficient number of datums, remote data will + * be requested and then passed to the async callback. + * + * @param query Query. + * @param sync Sync callback + * @param async Async callback. + * @returns The data that matches query. + */ + public search(query: string, sync: (datums: T[]) => void, async: (datums: T[]) => void): T[]; + + /** + * Returns all items from the internal search index. + */ + public all(): T[]; + + /** + * Clears the internal search index that's powered by local, prefetch, and #add. + */ + public clear(): Bloodhound; + + /** + * If you're using prefetch, data gets cached in local storage in an effort to cut down on unnecessary network requests. + * clearPrefetchCache offers a way to programmatically clear said cache. + */ + public clearPrefetchCache(): Bloodhound; + + /** + * If you're using remote, Bloodhound will cache the 10 most recent responses in an effort to provide a better user experience. + * clearRemoteCache offers a way to programmatically clear said cache. + */ + public clearRemoteCache(): Bloodhound; +} + +declare module "bloodhound" { + export = Bloodhound; +} diff --git a/typescript-services/typescriptServices-tests.ts b/typescript-services/typescriptServices-tests.ts index 1c704b14e..57066d2b4 100644 --- a/typescript-services/typescriptServices-tests.ts +++ b/typescript-services/typescriptServices-tests.ts @@ -6,18 +6,18 @@ function transpile(input: string): string { } // compile -function compile(fileNames: string[], options: ts.CompilerOptions): number { - let program = ts.createProgram(fileNames, options); - let emitResult = program.emit(); - - let allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics); - - allDiagnostics.forEach(diagnostic => { - let { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); - let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); - console.log(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); - }); - - let exitCode = emitResult.emitSkipped ? 1 : 0; - return exitCode; -} +function compile(fileNames: string[], options: ts.CompilerOptions): number { + let program = ts.createProgram(fileNames, options); + let emitResult = program.emit(); + + let allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics); + + allDiagnostics.forEach(diagnostic => { + let { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); + let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); + console.log(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); + }); + + let exitCode = emitResult.emitSkipped ? 1 : 0; + return exitCode; +} diff --git a/typescript-services/typescriptServices.d.ts b/typescript-services/typescriptServices.d.ts index dbd4919bf..3ab20d7c9 100644 --- a/typescript-services/typescriptServices.d.ts +++ b/typescript-services/typescriptServices.d.ts @@ -1,2148 +1,2148 @@ -// Type definitions for TypeScript API v0.4.0 -// Project: http://www.typescriptlang.org/ -// Definitions by: Microsoft TypeScript -// 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. -***************************************************************************** */ - -declare namespace ts { - interface Map { - [index: string]: T; - } - interface FileMap { - get(fileName: string): T; - set(fileName: string, value: T): void; - contains(fileName: string): boolean; - remove(fileName: string): void; - forEachValue(f: (v: T) => void): void; - clear(): void; - } - interface TextRange { - pos: number; - end: number; - } - const enum SyntaxKind { - Unknown = 0, - EndOfFileToken = 1, - SingleLineCommentTrivia = 2, - MultiLineCommentTrivia = 3, - NewLineTrivia = 4, - WhitespaceTrivia = 5, - ShebangTrivia = 6, - ConflictMarkerTrivia = 7, - NumericLiteral = 8, - StringLiteral = 9, - RegularExpressionLiteral = 10, - NoSubstitutionTemplateLiteral = 11, - TemplateHead = 12, - TemplateMiddle = 13, - TemplateTail = 14, - OpenBraceToken = 15, - CloseBraceToken = 16, - OpenParenToken = 17, - CloseParenToken = 18, - OpenBracketToken = 19, - CloseBracketToken = 20, - DotToken = 21, - DotDotDotToken = 22, - SemicolonToken = 23, - CommaToken = 24, - LessThanToken = 25, - LessThanSlashToken = 26, - GreaterThanToken = 27, - LessThanEqualsToken = 28, - GreaterThanEqualsToken = 29, - EqualsEqualsToken = 30, - ExclamationEqualsToken = 31, - EqualsEqualsEqualsToken = 32, - ExclamationEqualsEqualsToken = 33, - EqualsGreaterThanToken = 34, - PlusToken = 35, - MinusToken = 36, - AsteriskToken = 37, - SlashToken = 38, - PercentToken = 39, - PlusPlusToken = 40, - MinusMinusToken = 41, - LessThanLessThanToken = 42, - GreaterThanGreaterThanToken = 43, - GreaterThanGreaterThanGreaterThanToken = 44, - AmpersandToken = 45, - BarToken = 46, - CaretToken = 47, - ExclamationToken = 48, - TildeToken = 49, - AmpersandAmpersandToken = 50, - BarBarToken = 51, - QuestionToken = 52, - ColonToken = 53, - AtToken = 54, - EqualsToken = 55, - PlusEqualsToken = 56, - MinusEqualsToken = 57, - AsteriskEqualsToken = 58, - SlashEqualsToken = 59, - PercentEqualsToken = 60, - LessThanLessThanEqualsToken = 61, - GreaterThanGreaterThanEqualsToken = 62, - GreaterThanGreaterThanGreaterThanEqualsToken = 63, - AmpersandEqualsToken = 64, - BarEqualsToken = 65, - CaretEqualsToken = 66, - Identifier = 67, - BreakKeyword = 68, - CaseKeyword = 69, - CatchKeyword = 70, - ClassKeyword = 71, - ConstKeyword = 72, - ContinueKeyword = 73, - DebuggerKeyword = 74, - DefaultKeyword = 75, - DeleteKeyword = 76, - DoKeyword = 77, - ElseKeyword = 78, - EnumKeyword = 79, - ExportKeyword = 80, - ExtendsKeyword = 81, - FalseKeyword = 82, - FinallyKeyword = 83, - ForKeyword = 84, - FunctionKeyword = 85, - IfKeyword = 86, - ImportKeyword = 87, - InKeyword = 88, - InstanceOfKeyword = 89, - NewKeyword = 90, - NullKeyword = 91, - ReturnKeyword = 92, - SuperKeyword = 93, - SwitchKeyword = 94, - ThisKeyword = 95, - ThrowKeyword = 96, - TrueKeyword = 97, - TryKeyword = 98, - TypeOfKeyword = 99, - VarKeyword = 100, - VoidKeyword = 101, - WhileKeyword = 102, - WithKeyword = 103, - ImplementsKeyword = 104, - InterfaceKeyword = 105, - LetKeyword = 106, - PackageKeyword = 107, - PrivateKeyword = 108, - ProtectedKeyword = 109, - PublicKeyword = 110, - StaticKeyword = 111, - YieldKeyword = 112, - AbstractKeyword = 113, - AsKeyword = 114, - AnyKeyword = 115, - AsyncKeyword = 116, - AwaitKeyword = 117, - BooleanKeyword = 118, - ConstructorKeyword = 119, - DeclareKeyword = 120, - GetKeyword = 121, - IsKeyword = 122, - ModuleKeyword = 123, - NamespaceKeyword = 124, - RequireKeyword = 125, - NumberKeyword = 126, - SetKeyword = 127, - StringKeyword = 128, - SymbolKeyword = 129, - TypeKeyword = 130, - FromKeyword = 131, - OfKeyword = 132, - QualifiedName = 133, - ComputedPropertyName = 134, - TypeParameter = 135, - Parameter = 136, - Decorator = 137, - PropertySignature = 138, - PropertyDeclaration = 139, - MethodSignature = 140, - MethodDeclaration = 141, - Constructor = 142, - GetAccessor = 143, - SetAccessor = 144, - CallSignature = 145, - ConstructSignature = 146, - IndexSignature = 147, - TypePredicate = 148, - TypeReference = 149, - FunctionType = 150, - ConstructorType = 151, - TypeQuery = 152, - TypeLiteral = 153, - ArrayType = 154, - TupleType = 155, - UnionType = 156, - IntersectionType = 157, - ParenthesizedType = 158, - ObjectBindingPattern = 159, - ArrayBindingPattern = 160, - BindingElement = 161, - ArrayLiteralExpression = 162, - ObjectLiteralExpression = 163, - PropertyAccessExpression = 164, - ElementAccessExpression = 165, - CallExpression = 166, - NewExpression = 167, - TaggedTemplateExpression = 168, - TypeAssertionExpression = 169, - ParenthesizedExpression = 170, - FunctionExpression = 171, - ArrowFunction = 172, - DeleteExpression = 173, - TypeOfExpression = 174, - VoidExpression = 175, - AwaitExpression = 176, - PrefixUnaryExpression = 177, - PostfixUnaryExpression = 178, - BinaryExpression = 179, - ConditionalExpression = 180, - TemplateExpression = 181, - YieldExpression = 182, - SpreadElementExpression = 183, - ClassExpression = 184, - OmittedExpression = 185, - ExpressionWithTypeArguments = 186, - AsExpression = 187, - TemplateSpan = 188, - SemicolonClassElement = 189, - Block = 190, - VariableStatement = 191, - EmptyStatement = 192, - ExpressionStatement = 193, - IfStatement = 194, - DoStatement = 195, - WhileStatement = 196, - ForStatement = 197, - ForInStatement = 198, - ForOfStatement = 199, - ContinueStatement = 200, - BreakStatement = 201, - ReturnStatement = 202, - WithStatement = 203, - SwitchStatement = 204, - LabeledStatement = 205, - ThrowStatement = 206, - TryStatement = 207, - DebuggerStatement = 208, - VariableDeclaration = 209, - VariableDeclarationList = 210, - FunctionDeclaration = 211, - ClassDeclaration = 212, - InterfaceDeclaration = 213, - TypeAliasDeclaration = 214, - EnumDeclaration = 215, - ModuleDeclaration = 216, - ModuleBlock = 217, - CaseBlock = 218, - ImportEqualsDeclaration = 219, - ImportDeclaration = 220, - ImportClause = 221, - NamespaceImport = 222, - NamedImports = 223, - ImportSpecifier = 224, - ExportAssignment = 225, - ExportDeclaration = 226, - NamedExports = 227, - ExportSpecifier = 228, - MissingDeclaration = 229, - ExternalModuleReference = 230, - JsxElement = 231, - JsxSelfClosingElement = 232, - JsxOpeningElement = 233, - JsxText = 234, - JsxClosingElement = 235, - JsxAttribute = 236, - JsxSpreadAttribute = 237, - JsxExpression = 238, - CaseClause = 239, - DefaultClause = 240, - HeritageClause = 241, - CatchClause = 242, - PropertyAssignment = 243, - ShorthandPropertyAssignment = 244, - EnumMember = 245, - SourceFile = 246, - JSDocTypeExpression = 247, - JSDocAllType = 248, - JSDocUnknownType = 249, - JSDocArrayType = 250, - JSDocUnionType = 251, - JSDocTupleType = 252, - JSDocNullableType = 253, - JSDocNonNullableType = 254, - JSDocRecordType = 255, - JSDocRecordMember = 256, - JSDocTypeReference = 257, - JSDocOptionalType = 258, - JSDocFunctionType = 259, - JSDocVariadicType = 260, - JSDocConstructorType = 261, - JSDocThisType = 262, - JSDocComment = 263, - JSDocTag = 264, - JSDocParameterTag = 265, - JSDocReturnTag = 266, - JSDocTypeTag = 267, - JSDocTemplateTag = 268, - SyntaxList = 269, - Count = 270, - FirstAssignment = 55, - LastAssignment = 66, - FirstReservedWord = 68, - LastReservedWord = 103, - FirstKeyword = 68, - LastKeyword = 132, - FirstFutureReservedWord = 104, - LastFutureReservedWord = 112, - FirstTypeNode = 149, - LastTypeNode = 158, - FirstPunctuation = 15, - LastPunctuation = 66, - FirstToken = 0, - LastToken = 132, - FirstTriviaToken = 2, - LastTriviaToken = 7, - FirstLiteralToken = 8, - LastLiteralToken = 11, - FirstTemplateToken = 11, - LastTemplateToken = 14, - FirstBinaryOperator = 25, - LastBinaryOperator = 66, - FirstNode = 133, - } - const enum NodeFlags { - Export = 1, - Ambient = 2, - Public = 16, - Private = 32, - Protected = 64, - Static = 128, - Abstract = 256, - Async = 512, - Default = 1024, - MultiLine = 2048, - Synthetic = 4096, - DeclarationFile = 8192, - Let = 16384, - Const = 32768, - OctalLiteral = 65536, - Namespace = 131072, - ExportContext = 262144, - Modifier = 2035, - AccessibilityModifier = 112, - BlockScoped = 49152, - } - const enum JsxFlags { - None = 0, - IntrinsicNamedElement = 1, - IntrinsicIndexedElement = 2, - ClassElement = 4, - UnknownElement = 8, - IntrinsicElement = 3, - } - interface Node extends TextRange { - kind: SyntaxKind; - flags: NodeFlags; - decorators?: NodeArray; - modifiers?: ModifiersArray; - parent?: Node; - } - interface NodeArray extends Array, TextRange { - hasTrailingComma?: boolean; - } - interface ModifiersArray extends NodeArray { - flags: number; - } - interface Identifier extends PrimaryExpression { - text: string; - originalKeywordKind?: SyntaxKind; - } - interface QualifiedName extends Node { - left: EntityName; - right: Identifier; - } - type EntityName = Identifier | QualifiedName; - type DeclarationName = Identifier | LiteralExpression | ComputedPropertyName | BindingPattern; - interface Declaration extends Node { - _declarationBrand: any; - name?: DeclarationName; - } - interface ComputedPropertyName extends Node { - expression: Expression; - } - interface Decorator extends Node { - expression: LeftHandSideExpression; - } - interface TypeParameterDeclaration extends Declaration { - name: Identifier; - constraint?: TypeNode; - expression?: Expression; - } - interface SignatureDeclaration extends Declaration { - typeParameters?: NodeArray; - parameters: NodeArray; - type?: TypeNode; - } - interface VariableDeclaration extends Declaration { - parent?: VariableDeclarationList; - name: Identifier | BindingPattern; - type?: TypeNode; - initializer?: Expression; - } - interface VariableDeclarationList extends Node { - declarations: NodeArray; - } - interface ParameterDeclaration extends Declaration { - dotDotDotToken?: Node; - name: Identifier | BindingPattern; - questionToken?: Node; - type?: TypeNode; - initializer?: Expression; - } - interface BindingElement extends Declaration { - propertyName?: Identifier; - dotDotDotToken?: Node; - name: Identifier | BindingPattern; - initializer?: Expression; - } - interface PropertyDeclaration extends Declaration, ClassElement { - name: DeclarationName; - questionToken?: Node; - type?: TypeNode; - initializer?: Expression; - } - interface ObjectLiteralElement extends Declaration { - _objectLiteralBrandBrand: any; - } - interface PropertyAssignment extends ObjectLiteralElement { - _propertyAssignmentBrand: any; - name: DeclarationName; - questionToken?: Node; - initializer: Expression; - } - interface ShorthandPropertyAssignment extends ObjectLiteralElement { - name: Identifier; - questionToken?: Node; - } - interface VariableLikeDeclaration extends Declaration { - propertyName?: Identifier; - dotDotDotToken?: Node; - name: DeclarationName; - questionToken?: Node; - type?: TypeNode; - initializer?: Expression; - } - interface BindingPattern extends Node { - elements: NodeArray; - } - /** - * Several node kinds share function-like features such as a signature, - * a name, and a body. These nodes should extend FunctionLikeDeclaration. - * Examples: - * - FunctionDeclaration - * - MethodDeclaration - * - AccessorDeclaration - */ - interface FunctionLikeDeclaration extends SignatureDeclaration { - _functionLikeDeclarationBrand: any; - asteriskToken?: Node; - questionToken?: Node; - body?: Block | Expression; - } - interface FunctionDeclaration extends FunctionLikeDeclaration, Statement { - name?: Identifier; - body?: Block; - } - interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { - body?: Block; - } - interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { - body?: Block; - } - interface SemicolonClassElement extends ClassElement { - _semicolonClassElementBrand: any; - } - interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { - _accessorDeclarationBrand: any; - body: Block; - } - interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement { - _indexSignatureDeclarationBrand: any; - } - interface TypeNode extends Node { - _typeNodeBrand: any; - } - interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration { - _functionOrConstructorTypeNodeBrand: any; - } - interface TypeReferenceNode extends TypeNode { - typeName: EntityName; - typeArguments?: NodeArray; - } - interface TypePredicateNode extends TypeNode { - parameterName: Identifier; - type: TypeNode; - } - interface TypeQueryNode extends TypeNode { - exprName: EntityName; - } - interface TypeLiteralNode extends TypeNode, Declaration { - members: NodeArray; - } - interface ArrayTypeNode extends TypeNode { - elementType: TypeNode; - } - interface TupleTypeNode extends TypeNode { - elementTypes: NodeArray; - } - interface UnionOrIntersectionTypeNode extends TypeNode { - types: NodeArray; - } - interface UnionTypeNode extends UnionOrIntersectionTypeNode { - } - interface IntersectionTypeNode extends UnionOrIntersectionTypeNode { - } - interface ParenthesizedTypeNode extends TypeNode { - type: TypeNode; - } - interface StringLiteral extends LiteralExpression, TypeNode { - _stringLiteralBrand: any; - } - interface Expression extends Node { - _expressionBrand: any; - contextualType?: Type; - } - interface UnaryExpression extends Expression { - _unaryExpressionBrand: any; - } - interface PrefixUnaryExpression extends UnaryExpression { - operator: SyntaxKind; - operand: UnaryExpression; - } - interface PostfixUnaryExpression extends PostfixExpression { - operand: LeftHandSideExpression; - operator: SyntaxKind; - } - interface PostfixExpression extends UnaryExpression { - _postfixExpressionBrand: any; - } - interface LeftHandSideExpression extends PostfixExpression { - _leftHandSideExpressionBrand: any; - } - interface MemberExpression extends LeftHandSideExpression { - _memberExpressionBrand: any; - } - interface PrimaryExpression extends MemberExpression { - _primaryExpressionBrand: any; - } - interface DeleteExpression extends UnaryExpression { - expression: UnaryExpression; - } - interface TypeOfExpression extends UnaryExpression { - expression: UnaryExpression; - } - interface VoidExpression extends UnaryExpression { - expression: UnaryExpression; - } - interface AwaitExpression extends UnaryExpression { - expression: UnaryExpression; - } - interface YieldExpression extends Expression { - asteriskToken?: Node; - expression?: Expression; - } - interface BinaryExpression extends Expression { - left: Expression; - operatorToken: Node; - right: Expression; - } - interface ConditionalExpression extends Expression { - condition: Expression; - questionToken: Node; - whenTrue: Expression; - colonToken: Node; - whenFalse: Expression; - } - interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { - name?: Identifier; - body: Block | Expression; - } - interface ArrowFunction extends Expression, FunctionLikeDeclaration { - equalsGreaterThanToken: Node; - } - interface LiteralExpression extends PrimaryExpression { - text: string; - isUnterminated?: boolean; - hasExtendedUnicodeEscape?: boolean; - } - interface TemplateExpression extends PrimaryExpression { - head: LiteralExpression; - templateSpans: NodeArray; - } - interface TemplateSpan extends Node { - expression: Expression; - literal: LiteralExpression; - } - interface ParenthesizedExpression extends PrimaryExpression { - expression: Expression; - } - interface ArrayLiteralExpression extends PrimaryExpression { - elements: NodeArray; - } - interface SpreadElementExpression extends Expression { - expression: Expression; - } - interface ObjectLiteralExpression extends PrimaryExpression, Declaration { - properties: NodeArray; - } - interface PropertyAccessExpression extends MemberExpression { - expression: LeftHandSideExpression; - dotToken: Node; - name: Identifier; - } - interface ElementAccessExpression extends MemberExpression { - expression: LeftHandSideExpression; - argumentExpression?: Expression; - } - interface CallExpression extends LeftHandSideExpression { - expression: LeftHandSideExpression; - typeArguments?: NodeArray; - arguments: NodeArray; - } - interface ExpressionWithTypeArguments extends TypeNode { - expression: LeftHandSideExpression; - typeArguments?: NodeArray; - } - interface NewExpression extends CallExpression, PrimaryExpression { - } - interface TaggedTemplateExpression extends MemberExpression { - tag: LeftHandSideExpression; - template: LiteralExpression | TemplateExpression; - } - type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; - interface AsExpression extends Expression { - expression: Expression; - type: TypeNode; - } - interface TypeAssertion extends UnaryExpression { - type: TypeNode; - expression: UnaryExpression; - } - type AssertionExpression = TypeAssertion | AsExpression; - interface JsxElement extends PrimaryExpression { - openingElement: JsxOpeningElement; - children: NodeArray; - closingElement: JsxClosingElement; - } - interface JsxOpeningElement extends Expression { - _openingElementBrand?: any; - tagName: EntityName; - attributes: NodeArray; - } - interface JsxSelfClosingElement extends PrimaryExpression, JsxOpeningElement { - _selfClosingElementBrand?: any; - } - type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; - interface JsxAttribute extends Node { - name: Identifier; - initializer?: Expression; - } - interface JsxSpreadAttribute extends Node { - expression: Expression; - } - interface JsxClosingElement extends Node { - tagName: EntityName; - } - interface JsxExpression extends Expression { - expression?: Expression; - } - interface JsxText extends Node { - _jsxTextExpressionBrand: any; - } - type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement; - interface Statement extends Node { - _statementBrand: any; - } - interface Block extends Statement { - statements: NodeArray; - } - interface VariableStatement extends Statement { - declarationList: VariableDeclarationList; - } - interface ExpressionStatement extends Statement { - expression: Expression; - } - interface IfStatement extends Statement { - expression: Expression; - thenStatement: Statement; - elseStatement?: Statement; - } - interface IterationStatement extends Statement { - statement: Statement; - } - interface DoStatement extends IterationStatement { - expression: Expression; - } - interface WhileStatement extends IterationStatement { - expression: Expression; - } - interface ForStatement extends IterationStatement { - initializer?: VariableDeclarationList | Expression; - condition?: Expression; - incrementor?: Expression; - } - interface ForInStatement extends IterationStatement { - initializer: VariableDeclarationList | Expression; - expression: Expression; - } - interface ForOfStatement extends IterationStatement { - initializer: VariableDeclarationList | Expression; - expression: Expression; - } - interface BreakOrContinueStatement extends Statement { - label?: Identifier; - } - interface ReturnStatement extends Statement { - expression?: Expression; - } - interface WithStatement extends Statement { - expression: Expression; - statement: Statement; - } - interface SwitchStatement extends Statement { - expression: Expression; - caseBlock: CaseBlock; - } - interface CaseBlock extends Node { - clauses: NodeArray; - } - interface CaseClause extends Node { - expression?: Expression; - statements: NodeArray; - } - interface DefaultClause extends Node { - statements: NodeArray; - } - type CaseOrDefaultClause = CaseClause | DefaultClause; - interface LabeledStatement extends Statement { - label: Identifier; - statement: Statement; - } - interface ThrowStatement extends Statement { - expression: Expression; - } - interface TryStatement extends Statement { - tryBlock: Block; - catchClause?: CatchClause; - finallyBlock?: Block; - } - interface CatchClause extends Node { - variableDeclaration: VariableDeclaration; - block: Block; - } - interface ClassLikeDeclaration extends Declaration { - name?: Identifier; - typeParameters?: NodeArray; - heritageClauses?: NodeArray; - members: NodeArray; - } - interface ClassDeclaration extends ClassLikeDeclaration, Statement { - } - interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { - } - interface ClassElement extends Declaration { - _classElementBrand: any; - } - interface InterfaceDeclaration extends Declaration, Statement { - name: Identifier; - typeParameters?: NodeArray; - heritageClauses?: NodeArray; - members: NodeArray; - } - interface HeritageClause extends Node { - token: SyntaxKind; - types?: NodeArray; - } - interface TypeAliasDeclaration extends Declaration, Statement { - name: Identifier; - typeParameters?: NodeArray; - type: TypeNode; - } - interface EnumMember extends Declaration { - name: DeclarationName; - initializer?: Expression; - } - interface EnumDeclaration extends Declaration, Statement { - name: Identifier; - members: NodeArray; - } - interface ModuleDeclaration extends Declaration, Statement { - name: Identifier | LiteralExpression; - body: ModuleBlock | ModuleDeclaration; - } - interface ModuleBlock extends Node, Statement { - statements: NodeArray; - } - interface ImportEqualsDeclaration extends Declaration, Statement { - name: Identifier; - moduleReference: EntityName | ExternalModuleReference; - } - interface ExternalModuleReference extends Node { - expression?: Expression; - } - interface ImportDeclaration extends Statement { - importClause?: ImportClause; - moduleSpecifier: Expression; - } - interface ImportClause extends Declaration { - name?: Identifier; - namedBindings?: NamespaceImport | NamedImports; - } - interface NamespaceImport extends Declaration { - name: Identifier; - } - interface ExportDeclaration extends Declaration, Statement { - exportClause?: NamedExports; - moduleSpecifier?: Expression; - } - interface NamedImportsOrExports extends Node { - elements: NodeArray; - } - type NamedImports = NamedImportsOrExports; - type NamedExports = NamedImportsOrExports; - interface ImportOrExportSpecifier extends Declaration { - propertyName?: Identifier; - name: Identifier; - } - type ImportSpecifier = ImportOrExportSpecifier; - type ExportSpecifier = ImportOrExportSpecifier; - interface ExportAssignment extends Declaration, Statement { - isExportEquals?: boolean; - expression: Expression; - } - interface FileReference extends TextRange { - fileName: string; - } - interface CommentRange extends TextRange { - hasTrailingNewLine?: boolean; - kind: SyntaxKind; - } - interface JSDocTypeExpression extends Node { - type: JSDocType; - } - interface JSDocType extends TypeNode { - _jsDocTypeBrand: any; - } - interface JSDocAllType extends JSDocType { - _JSDocAllTypeBrand: any; - } - interface JSDocUnknownType extends JSDocType { - _JSDocUnknownTypeBrand: any; - } - interface JSDocArrayType extends JSDocType { - elementType: JSDocType; - } - interface JSDocUnionType extends JSDocType { - types: NodeArray; - } - interface JSDocTupleType extends JSDocType { - types: NodeArray; - } - interface JSDocNonNullableType extends JSDocType { - type: JSDocType; - } - interface JSDocNullableType extends JSDocType { - type: JSDocType; - } - interface JSDocRecordType extends JSDocType, TypeLiteralNode { - members: NodeArray; - } - interface JSDocTypeReference extends JSDocType { - name: EntityName; - typeArguments: NodeArray; - } - interface JSDocOptionalType extends JSDocType { - type: JSDocType; - } - interface JSDocFunctionType extends JSDocType, SignatureDeclaration { - parameters: NodeArray; - type: JSDocType; - } - interface JSDocVariadicType extends JSDocType { - type: JSDocType; - } - interface JSDocConstructorType extends JSDocType { - type: JSDocType; - } - interface JSDocThisType extends JSDocType { - type: JSDocType; - } - interface JSDocRecordMember extends PropertyDeclaration { - name: Identifier | LiteralExpression; - type?: JSDocType; - } - interface JSDocComment extends Node { - tags: NodeArray; - } - interface JSDocTag extends Node { - atToken: Node; - tagName: Identifier; - } - interface JSDocTemplateTag extends JSDocTag { - typeParameters: NodeArray; - } - interface JSDocReturnTag extends JSDocTag { - typeExpression: JSDocTypeExpression; - } - interface JSDocTypeTag extends JSDocTag { - typeExpression: JSDocTypeExpression; - } - interface JSDocParameterTag extends JSDocTag { - preParameterName?: Identifier; - typeExpression?: JSDocTypeExpression; - postParameterName?: Identifier; - isBracketed: boolean; - } - interface SourceFile extends Declaration { - statements: NodeArray; - endOfFileToken: Node; - fileName: string; - text: string; - amdDependencies: { - path: string; - name: string; - }[]; - moduleName: string; - referencedFiles: FileReference[]; - languageVariant: LanguageVariant; - /** - * lib.d.ts should have a reference comment like - * - * /// - * - * If any other file has this comment, it signals not to include lib.d.ts - * because this containing file is intended to act as a default library. - */ - hasNoDefaultLib: boolean; - languageVersion: ScriptTarget; - } - interface ScriptReferenceHost { - getCompilerOptions(): CompilerOptions; - getSourceFile(fileName: string): SourceFile; - getCurrentDirectory(): string; - } - interface ParseConfigHost extends ModuleResolutionHost { - readDirectory(rootDir: string, extension: string, exclude: string[]): string[]; - } - interface WriteFileCallback { - (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void; - } - class OperationCanceledException { - } - interface CancellationToken { - isCancellationRequested(): boolean; - /** @throws OperationCanceledException if isCancellationRequested is true */ - throwIfCancellationRequested(): void; - } - interface Program extends ScriptReferenceHost { - /** - * Get a list of root file names that were passed to a 'createProgram' - */ - getRootFileNames(): string[]; - /** - * Get a list of files in the program - */ - getSourceFiles(): SourceFile[]; - /** - * Emits the JavaScript and declaration files. If targetSourceFile is not specified, then - * the JavaScript and declaration files will be produced for all the files in this program. - * If targetSourceFile is specified, then only the JavaScript and declaration for that - * specific file will be generated. - * - * If writeFile is not specified then the writeFile callback from the compiler host will be - * used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter - * will be invoked when writing the JavaScript and declaration files. - */ - emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult; - getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; - getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; - getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - /** - * Gets a type checker that can be used to semantically analyze source fils in the program. - */ - getTypeChecker(): TypeChecker; - } - interface SourceMapSpan { - /** Line number in the .js file. */ - emittedLine: number; - /** Column number in the .js file. */ - emittedColumn: number; - /** Line number in the .ts file. */ - sourceLine: number; - /** Column number in the .ts file. */ - sourceColumn: number; - /** Optional name (index into names array) associated with this span. */ - nameIndex?: number; - /** .ts file (index into sources array) associated with this span */ - sourceIndex: number; - } - interface SourceMapData { - sourceMapFilePath: string; - jsSourceMappingURL: string; - sourceMapFile: string; - sourceMapSourceRoot: string; - sourceMapSources: string[]; - sourceMapSourcesContent?: string[]; - inputSourceFileNames: string[]; - sourceMapNames?: string[]; - sourceMapMappings: string; - sourceMapDecodedMappings: SourceMapSpan[]; - } - /** Return code used by getEmitOutput function to indicate status of the function */ - enum ExitStatus { - Success = 0, - DiagnosticsPresent_OutputsSkipped = 1, - DiagnosticsPresent_OutputsGenerated = 2, - } - interface EmitResult { - emitSkipped: boolean; - diagnostics: Diagnostic[]; - } - interface TypeChecker { - getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type; - getDeclaredTypeOfSymbol(symbol: Symbol): Type; - getPropertiesOfType(type: Type): Symbol[]; - getPropertyOfType(type: Type, propertyName: string): Symbol; - getSignaturesOfType(type: Type, kind: SignatureKind): Signature[]; - getIndexTypeOfType(type: Type, kind: IndexKind): Type; - getBaseTypes(type: InterfaceType): ObjectType[]; - getReturnTypeOfSignature(signature: Signature): Type; - getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; - getSymbolAtLocation(node: Node): Symbol; - getShorthandAssignmentValueSymbol(location: Node): Symbol; - getTypeAtLocation(node: Node): Type; - typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; - symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string; - getSymbolDisplayBuilder(): SymbolDisplayBuilder; - getFullyQualifiedName(symbol: Symbol): string; - getAugmentedPropertiesOfType(type: Type): Symbol[]; - getRootSymbols(symbol: Symbol): Symbol[]; - getContextualType(node: Expression): Type; - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature; - getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature; - isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; - isUndefinedSymbol(symbol: Symbol): boolean; - isArgumentsSymbol(symbol: Symbol): boolean; - getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; - isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; - getAliasedSymbol(symbol: Symbol): Symbol; - getExportsOfModule(moduleSymbol: Symbol): Symbol[]; - getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type; - getJsxIntrinsicTagNames(): Symbol[]; - isOptionalParameter(node: ParameterDeclaration): boolean; - } - interface SymbolDisplayBuilder { - buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags): void; - buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - } - interface SymbolWriter { - writeKeyword(text: string): void; - writeOperator(text: string): void; - writePunctuation(text: string): void; - writeSpace(text: string): void; - writeStringLiteral(text: string): void; - writeParameter(text: string): void; - writeSymbol(text: string, symbol: Symbol): void; - writeLine(): void; - increaseIndent(): void; - decreaseIndent(): void; - clear(): void; - trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; - } - const enum TypeFormatFlags { - None = 0, - WriteArrayAsGenericType = 1, - UseTypeOfFunction = 2, - NoTruncation = 4, - WriteArrowStyleSignature = 8, - WriteOwnNameForAnyLike = 16, - WriteTypeArgumentsOfSignature = 32, - InElementType = 64, - UseFullyQualifiedType = 128, - } - const enum SymbolFormatFlags { - None = 0, - WriteTypeParametersOrArguments = 1, - UseOnlyExternalAliasing = 2, - } - interface TypePredicate { - parameterName: string; - parameterIndex: number; - type: Type; - } - const enum SymbolFlags { - None = 0, - FunctionScopedVariable = 1, - BlockScopedVariable = 2, - Property = 4, - EnumMember = 8, - Function = 16, - Class = 32, - Interface = 64, - ConstEnum = 128, - RegularEnum = 256, - ValueModule = 512, - NamespaceModule = 1024, - TypeLiteral = 2048, - ObjectLiteral = 4096, - Method = 8192, - Constructor = 16384, - GetAccessor = 32768, - SetAccessor = 65536, - Signature = 131072, - TypeParameter = 262144, - TypeAlias = 524288, - ExportValue = 1048576, - ExportType = 2097152, - ExportNamespace = 4194304, - Alias = 8388608, - Instantiated = 16777216, - Merged = 33554432, - Transient = 67108864, - Prototype = 134217728, - SyntheticProperty = 268435456, - Optional = 536870912, - ExportStar = 1073741824, - Enum = 384, - Variable = 3, - Value = 107455, - Type = 793056, - Namespace = 1536, - Module = 1536, - Accessor = 98304, - FunctionScopedVariableExcludes = 107454, - BlockScopedVariableExcludes = 107455, - ParameterExcludes = 107455, - PropertyExcludes = 107455, - EnumMemberExcludes = 107455, - FunctionExcludes = 106927, - ClassExcludes = 899519, - InterfaceExcludes = 792960, - RegularEnumExcludes = 899327, - ConstEnumExcludes = 899967, - ValueModuleExcludes = 106639, - NamespaceModuleExcludes = 0, - MethodExcludes = 99263, - GetAccessorExcludes = 41919, - SetAccessorExcludes = 74687, - TypeParameterExcludes = 530912, - TypeAliasExcludes = 793056, - AliasExcludes = 8388608, - ModuleMember = 8914931, - ExportHasLocal = 944, - HasExports = 1952, - HasMembers = 6240, - BlockScoped = 418, - PropertyOrAccessor = 98308, - Export = 7340032, - } - interface Symbol { - flags: SymbolFlags; - name: string; - declarations?: Declaration[]; - valueDeclaration?: Declaration; - members?: SymbolTable; - exports?: SymbolTable; - } - interface SymbolTable { - [index: string]: Symbol; - } - const enum TypeFlags { - Any = 1, - String = 2, - Number = 4, - Boolean = 8, - Void = 16, - Undefined = 32, - Null = 64, - Enum = 128, - StringLiteral = 256, - TypeParameter = 512, - Class = 1024, - Interface = 2048, - Reference = 4096, - Tuple = 8192, - Union = 16384, - Intersection = 32768, - Anonymous = 65536, - Instantiated = 131072, - ObjectLiteral = 524288, - ESSymbol = 16777216, - StringLike = 258, - NumberLike = 132, - ObjectType = 80896, - UnionOrIntersection = 49152, - StructuredType = 130048, - } - interface Type { - flags: TypeFlags; - symbol?: Symbol; - } - interface StringLiteralType extends Type { - text: string; - } - interface ObjectType extends Type { - } - interface InterfaceType extends ObjectType { - typeParameters: TypeParameter[]; - outerTypeParameters: TypeParameter[]; - localTypeParameters: TypeParameter[]; - } - interface InterfaceTypeWithDeclaredMembers extends InterfaceType { - declaredProperties: Symbol[]; - declaredCallSignatures: Signature[]; - declaredConstructSignatures: Signature[]; - declaredStringIndexType: Type; - declaredNumberIndexType: Type; - } - interface TypeReference extends ObjectType { - target: GenericType; - typeArguments: Type[]; - } - interface GenericType extends InterfaceType, TypeReference { - } - interface TupleType extends ObjectType { - elementTypes: Type[]; - baseArrayType: TypeReference; - } - interface UnionOrIntersectionType extends Type { - types: Type[]; - } - interface UnionType extends UnionOrIntersectionType { - } - interface IntersectionType extends UnionOrIntersectionType { - } - interface TypeParameter extends Type { - constraint: Type; - } - const enum SignatureKind { - Call = 0, - Construct = 1, - } - interface Signature { - declaration: SignatureDeclaration; - typeParameters: TypeParameter[]; - parameters: Symbol[]; - typePredicate?: TypePredicate; - } - const enum IndexKind { - String = 0, - Number = 1, - } - interface DiagnosticMessage { - key: string; - category: DiagnosticCategory; - code: number; - } - /** - * A linked list of formatted diagnostic messages to be used as part of a multiline message. - * It is built from the bottom up, leaving the head to be the "main" diagnostic. - * While it seems that DiagnosticMessageChain is structurally similar to DiagnosticMessage, - * the difference is that messages are all preformatted in DMC. - */ - interface DiagnosticMessageChain { - messageText: string; - category: DiagnosticCategory; - code: number; - next?: DiagnosticMessageChain; - } - interface Diagnostic { - file: SourceFile; - start: number; - length: number; - messageText: string | DiagnosticMessageChain; - category: DiagnosticCategory; - code: number; - } - enum DiagnosticCategory { - Warning = 0, - Error = 1, - Message = 2, - } - const enum ModuleResolutionKind { - Classic = 1, - NodeJs = 2, - } - interface CompilerOptions { - allowNonTsExtensions?: boolean; - charset?: string; - declaration?: boolean; - diagnostics?: boolean; - emitBOM?: boolean; - help?: boolean; - init?: boolean; - inlineSourceMap?: boolean; - inlineSources?: boolean; - jsx?: JsxEmit; - listFiles?: boolean; - locale?: string; - mapRoot?: string; - module?: ModuleKind; - newLine?: NewLineKind; - noEmit?: boolean; - noEmitHelpers?: boolean; - noEmitOnError?: boolean; - noErrorTruncation?: boolean; - noImplicitAny?: boolean; - noLib?: boolean; - noResolve?: boolean; - out?: string; - outFile?: string; - outDir?: string; - preserveConstEnums?: boolean; - project?: string; - removeComments?: boolean; - rootDir?: string; - sourceMap?: boolean; - sourceRoot?: string; - suppressExcessPropertyErrors?: boolean; - suppressImplicitAnyIndexErrors?: boolean; - target?: ScriptTarget; - version?: boolean; - watch?: boolean; - isolatedModules?: boolean; - experimentalDecorators?: boolean; - experimentalAsyncFunctions?: boolean; - emitDecoratorMetadata?: boolean; - moduleResolution?: ModuleResolutionKind; - [option: string]: string | number | boolean; - } - const enum ModuleKind { - None = 0, - CommonJS = 1, - AMD = 2, - UMD = 3, - System = 4, - } - const enum JsxEmit { - None = 0, - Preserve = 1, - React = 2, - } - const enum NewLineKind { - CarriageReturnLineFeed = 0, - LineFeed = 1, - } - interface LineAndCharacter { - line: number; - character: number; - } - const enum ScriptTarget { - ES3 = 0, - ES5 = 1, - ES6 = 2, - Latest = 2, - } - const enum LanguageVariant { - Standard = 0, - JSX = 1, - } - interface ParsedCommandLine { - options: CompilerOptions; - fileNames: string[]; - errors: Diagnostic[]; - } - interface ModuleResolutionHost { - fileExists(fileName: string): boolean; - readFile(fileName: string): string; - } - interface ResolvedModule { - resolvedFileName: string; - isExternalLibraryImport?: boolean; - } - interface ResolvedModuleWithFailedLookupLocations { - resolvedModule: ResolvedModule; - failedLookupLocations: string[]; - } - interface CompilerHost extends ModuleResolutionHost { - getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile; - getCancellationToken?(): CancellationToken; - getDefaultLibFileName(options: CompilerOptions): string; - writeFile: WriteFileCallback; - getCurrentDirectory(): string; - getCanonicalFileName(fileName: string): string; - useCaseSensitiveFileNames(): boolean; - getNewLine(): string; - resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; - } - interface TextSpan { - start: number; - length: number; - } - interface TextChangeRange { - span: TextSpan; - newLength: number; - } -} -declare namespace ts { - interface System { - args: string[]; - newLine: string; - useCaseSensitiveFileNames: boolean; - write(s: string): void; - readFile(path: string, encoding?: string): string; - writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; - watchFile?(path: string, callback: (path: string) => void): FileWatcher; - resolvePath(path: string): string; - fileExists(path: string): boolean; - directoryExists(path: string): boolean; - createDirectory(path: string): void; - getExecutingFilePath(): string; - getCurrentDirectory(): string; - readDirectory(path: string, extension?: string, exclude?: string[]): string[]; - getMemoryUsage?(): number; - exit(exitCode?: number): void; - } - interface FileWatcher { - close(): void; - } - var sys: System; -} -declare namespace ts { - interface ErrorCallback { - (message: DiagnosticMessage, length: number): void; - } - interface Scanner { - getStartPos(): number; - getToken(): SyntaxKind; - getTextPos(): number; - getTokenPos(): number; - getTokenText(): string; - getTokenValue(): string; - hasExtendedUnicodeEscape(): boolean; - hasPrecedingLineBreak(): boolean; - isIdentifier(): boolean; - isReservedWord(): boolean; - isUnterminated(): boolean; - reScanGreaterToken(): SyntaxKind; - reScanSlashToken(): SyntaxKind; - reScanTemplateToken(): SyntaxKind; - scanJsxIdentifier(): SyntaxKind; - reScanJsxToken(): SyntaxKind; - scanJsxToken(): SyntaxKind; - scan(): SyntaxKind; - setText(text: string, start?: number, length?: number): void; - setOnError(onError: ErrorCallback): void; - setScriptTarget(scriptTarget: ScriptTarget): void; - setLanguageVariant(variant: LanguageVariant): void; - setTextPos(textPos: number): void; - lookAhead(callback: () => T): T; - tryScan(callback: () => T): T; - } - function tokenToString(t: SyntaxKind): string; - function getPositionOfLineAndCharacter(sourceFile: SourceFile, line: number, character: number): number; - function getLineAndCharacterOfPosition(sourceFile: SourceFile, position: number): LineAndCharacter; - function isWhiteSpace(ch: number): boolean; - function isLineBreak(ch: number): boolean; - function couldStartTrivia(text: string, pos: number): boolean; - function getLeadingCommentRanges(text: string, pos: number): CommentRange[]; - function getTrailingCommentRanges(text: string, pos: number): CommentRange[]; - /** Optionally, get the shebang */ - function getShebang(text: string): string; - function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; - function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; - function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; -} -declare namespace ts { - function getDefaultLibFileName(options: CompilerOptions): string; - function textSpanEnd(span: TextSpan): number; - function textSpanIsEmpty(span: TextSpan): boolean; - function textSpanContainsPosition(span: TextSpan, position: number): boolean; - function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean; - function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean; - function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan; - function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean; - function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean; - function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number): boolean; - function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean; - function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan; - function createTextSpan(start: number, length: number): TextSpan; - function createTextSpanFromBounds(start: number, end: number): TextSpan; - function textChangeRangeNewSpan(range: TextChangeRange): TextSpan; - function textChangeRangeIsUnchanged(range: TextChangeRange): boolean; - function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange; - let unchangedTextChangeRange: TextChangeRange; - /** - * Called to merge all the changes that occurred across several versions of a script snapshot - * into a single change. i.e. if a user keeps making successive edits to a script we will - * have a text change from V1 to V2, V2 to V3, ..., Vn. - * - * This function will then merge those changes into a single change range valid between V1 and - * Vn. - */ - function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; - function getTypeParameterOwner(d: Declaration): Declaration; -} -declare namespace ts { - function getNodeConstructor(kind: SyntaxKind): new () => Node; - function createNode(kind: SyntaxKind): Node; - function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; - function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean): SourceFile; - function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; -} -declare namespace ts { - const version: string; - function findConfigFile(searchPath: string): string; - function resolveTripleslashReference(moduleName: string, containingFile: string): string; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; - function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; - function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; -} -declare namespace ts { - function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine; - /** - * Read tsconfig.json file - * @param fileName The path to the config file - */ - function readConfigFile(fileName: string): { - config?: any; - error?: Diagnostic; - }; - /** - * Parse the text of the tsconfig.json file - * @param fileName The path to the config file - * @param jsonText The text of the config file - */ - function parseConfigFileText(fileName: string, jsonText: string): { - config?: any; - error?: Diagnostic; - }; - /** - * Parse the contents of a config file (tsconfig.json). - * @param json The contents of the config file to parse - * @param basePath A root directory to resolve relative path entries in the config - * file to. e.g. outDir - */ - function parseConfigFile(json: any, host: ParseConfigHost, basePath: string): ParsedCommandLine; -} -declare namespace ts { - /** The version of the language service API */ - let servicesVersion: string; - interface Node { - getSourceFile(): SourceFile; - getChildCount(sourceFile?: SourceFile): number; - getChildAt(index: number, sourceFile?: SourceFile): Node; - getChildren(sourceFile?: SourceFile): Node[]; - getStart(sourceFile?: SourceFile): number; - getFullStart(): number; - getEnd(): number; - getWidth(sourceFile?: SourceFile): number; - getFullWidth(): number; - getLeadingTriviaWidth(sourceFile?: SourceFile): number; - getFullText(sourceFile?: SourceFile): string; - getText(sourceFile?: SourceFile): string; - getFirstToken(sourceFile?: SourceFile): Node; - getLastToken(sourceFile?: SourceFile): Node; - } - interface Symbol { - getFlags(): SymbolFlags; - getName(): string; - getDeclarations(): Declaration[]; - getDocumentationComment(): SymbolDisplayPart[]; - } - interface Type { - getFlags(): TypeFlags; - getSymbol(): Symbol; - getProperties(): Symbol[]; - getProperty(propertyName: string): Symbol; - getApparentProperties(): Symbol[]; - getCallSignatures(): Signature[]; - getConstructSignatures(): Signature[]; - getStringIndexType(): Type; - getNumberIndexType(): Type; - getBaseTypes(): ObjectType[]; - } - interface Signature { - getDeclaration(): SignatureDeclaration; - getTypeParameters(): Type[]; - getParameters(): Symbol[]; - getReturnType(): Type; - getDocumentationComment(): SymbolDisplayPart[]; - } - interface SourceFile { - getLineAndCharacterOfPosition(pos: number): LineAndCharacter; - getLineStarts(): number[]; - getPositionOfLineAndCharacter(line: number, character: number): number; - update(newText: string, textChangeRange: TextChangeRange): SourceFile; - } - /** - * Represents an immutable snapshot of a script at a specified time.Once acquired, the - * snapshot is observably immutable. i.e. the same calls with the same parameters will return - * the same values. - */ - interface IScriptSnapshot { - /** Gets a portion of the script snapshot specified by [start, end). */ - getText(start: number, end: number): string; - /** Gets the length of this script snapshot. */ - getLength(): number; - /** - * Gets the TextChangeRange that describe how the text changed between this text and - * an older version. This information is used by the incremental parser to determine - * what sections of the script need to be re-parsed. 'undefined' can be returned if the - * change range cannot be determined. However, in that case, incremental parsing will - * not happen and the entire document will be re - parsed. - */ - getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange; - /** Releases all resources held by this script snapshot */ - dispose?(): void; - } - module ScriptSnapshot { - function fromString(text: string): IScriptSnapshot; - } - interface PreProcessedFileInfo { - referencedFiles: FileReference[]; - importedFiles: FileReference[]; - ambientExternalModules: string[]; - isLibFile: boolean; - } - interface HostCancellationToken { - isCancellationRequested(): boolean; - } - interface LanguageServiceHost { - getCompilationSettings(): CompilerOptions; - getNewLine?(): string; - getProjectVersion?(): string; - getScriptFileNames(): string[]; - getScriptVersion(fileName: string): string; - getScriptSnapshot(fileName: string): IScriptSnapshot; - getLocalizedDiagnosticMessages?(): any; - getCancellationToken?(): HostCancellationToken; - getCurrentDirectory(): string; - getDefaultLibFileName(options: CompilerOptions): string; - log?(s: string): void; - trace?(s: string): void; - error?(s: string): void; - useCaseSensitiveFileNames?(): boolean; - resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; - } - interface LanguageService { - cleanupSemanticCache(): void; - getSyntacticDiagnostics(fileName: string): Diagnostic[]; - getSemanticDiagnostics(fileName: string): Diagnostic[]; - getCompilerOptionsDiagnostics(): Diagnostic[]; - /** - * @deprecated Use getEncodedSyntacticClassifications instead. - */ - getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; - /** - * @deprecated Use getEncodedSemanticClassifications instead. - */ - getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; - getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; - getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; - getCompletionsAtPosition(fileName: string, position: number): CompletionInfo; - getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails; - getQuickInfoAtPosition(fileName: string, position: number): QuickInfo; - getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan; - getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan; - getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems; - getRenameInfo(fileName: string, position: number): RenameInfo; - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[]; - getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; - getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; - getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - findReferences(fileName: string, position: number): ReferencedSymbol[]; - getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; - /** @deprecated */ - getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - getNavigateToItems(searchValue: string, maxResultCount?: number): NavigateToItem[]; - getNavigationBarItems(fileName: string): NavigationBarItem[]; - getOutliningSpans(fileName: string): OutliningSpan[]; - getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; - getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; - getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number; - getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[]; - getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[]; - getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[]; - getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; - getEmitOutput(fileName: string): EmitOutput; - getProgram(): Program; - getSourceFile(fileName: string): SourceFile; - dispose(): void; - } - interface Classifications { - spans: number[]; - endOfLineState: EndOfLineState; - } - interface ClassifiedSpan { - textSpan: TextSpan; - classificationType: string; - } - interface NavigationBarItem { - text: string; - kind: string; - kindModifiers: string; - spans: TextSpan[]; - childItems: NavigationBarItem[]; - indent: number; - bolded: boolean; - grayed: boolean; - } - interface TodoCommentDescriptor { - text: string; - priority: number; - } - interface TodoComment { - descriptor: TodoCommentDescriptor; - message: string; - position: number; - } - class TextChange { - span: TextSpan; - newText: string; - } - interface TextInsertion { - newText: string; - /** The position in newText the caret should point to after the insertion. */ - caretOffset: number; - } - interface RenameLocation { - textSpan: TextSpan; - fileName: string; - } - interface ReferenceEntry { - textSpan: TextSpan; - fileName: string; - isWriteAccess: boolean; - } - interface DocumentHighlights { - fileName: string; - highlightSpans: HighlightSpan[]; - } - module HighlightSpanKind { - const none: string; - const definition: string; - const reference: string; - const writtenReference: string; - } - interface HighlightSpan { - fileName?: string; - textSpan: TextSpan; - kind: string; - } - interface NavigateToItem { - name: string; - kind: string; - kindModifiers: string; - matchKind: string; - isCaseSensitive: boolean; - fileName: string; - textSpan: TextSpan; - containerName: string; - containerKind: string; - } - interface EditorOptions { - IndentSize: number; - TabSize: number; - NewLineCharacter: string; - ConvertTabsToSpaces: boolean; - } - interface FormatCodeOptions extends EditorOptions { - InsertSpaceAfterCommaDelimiter: boolean; - InsertSpaceAfterSemicolonInForStatements: boolean; - InsertSpaceBeforeAndAfterBinaryOperators: boolean; - InsertSpaceAfterKeywordsInControlFlowStatements: boolean; - InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; - InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; - InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; - PlaceOpenBraceOnNewLineForFunctions: boolean; - PlaceOpenBraceOnNewLineForControlBlocks: boolean; - [s: string]: boolean | number | string; - } - interface DefinitionInfo { - fileName: string; - textSpan: TextSpan; - kind: string; - name: string; - containerKind: string; - containerName: string; - } - interface ReferencedSymbol { - definition: DefinitionInfo; - references: ReferenceEntry[]; - } - enum SymbolDisplayPartKind { - aliasName = 0, - className = 1, - enumName = 2, - fieldName = 3, - interfaceName = 4, - keyword = 5, - lineBreak = 6, - numericLiteral = 7, - stringLiteral = 8, - localName = 9, - methodName = 10, - moduleName = 11, - operator = 12, - parameterName = 13, - propertyName = 14, - punctuation = 15, - space = 16, - text = 17, - typeParameterName = 18, - enumMemberName = 19, - functionName = 20, - regularExpressionLiteral = 21, - } - interface SymbolDisplayPart { - text: string; - kind: string; - } - interface QuickInfo { - kind: string; - kindModifiers: string; - textSpan: TextSpan; - displayParts: SymbolDisplayPart[]; - documentation: SymbolDisplayPart[]; - } - interface RenameInfo { - canRename: boolean; - localizedErrorMessage: string; - displayName: string; - fullDisplayName: string; - kind: string; - kindModifiers: string; - triggerSpan: TextSpan; - } - interface SignatureHelpParameter { - name: string; - documentation: SymbolDisplayPart[]; - displayParts: SymbolDisplayPart[]; - isOptional: boolean; - } - /** - * Represents a single signature to show in signature help. - * The id is used for subsequent calls into the language service to ask questions about the - * signature help item in the context of any documents that have been updated. i.e. after - * an edit has happened, while signature help is still active, the host can ask important - * questions like 'what parameter is the user currently contained within?'. - */ - interface SignatureHelpItem { - isVariadic: boolean; - prefixDisplayParts: SymbolDisplayPart[]; - suffixDisplayParts: SymbolDisplayPart[]; - separatorDisplayParts: SymbolDisplayPart[]; - parameters: SignatureHelpParameter[]; - documentation: SymbolDisplayPart[]; - } - /** - * Represents a set of signature help items, and the preferred item that should be selected. - */ - interface SignatureHelpItems { - items: SignatureHelpItem[]; - applicableSpan: TextSpan; - selectedItemIndex: number; - argumentIndex: number; - argumentCount: number; - } - interface CompletionInfo { - isMemberCompletion: boolean; - isNewIdentifierLocation: boolean; - entries: CompletionEntry[]; - } - interface CompletionEntry { - name: string; - kind: string; - kindModifiers: string; - sortText: string; - } - interface CompletionEntryDetails { - name: string; - kind: string; - kindModifiers: string; - displayParts: SymbolDisplayPart[]; - documentation: SymbolDisplayPart[]; - } - interface OutliningSpan { - /** The span of the document to actually collapse. */ - textSpan: TextSpan; - /** The span of the document to display when the user hovers over the collapsed span. */ - hintSpan: TextSpan; - /** The text to display in the editor for the collapsed region. */ - bannerText: string; - /** - * Whether or not this region should be automatically collapsed when - * the 'Collapse to Definitions' command is invoked. - */ - autoCollapse: boolean; - } - interface EmitOutput { - outputFiles: OutputFile[]; - emitSkipped: boolean; - } - const enum OutputFileType { - JavaScript = 0, - SourceMap = 1, - Declaration = 2, - } - interface OutputFile { - name: string; - writeByteOrderMark: boolean; - text: string; - } - const enum EndOfLineState { - None = 0, - InMultiLineCommentTrivia = 1, - InSingleQuoteStringLiteral = 2, - InDoubleQuoteStringLiteral = 3, - InTemplateHeadOrNoSubstitutionTemplate = 4, - InTemplateMiddleOrTail = 5, - InTemplateSubstitutionPosition = 6, - } - enum TokenClass { - Punctuation = 0, - Keyword = 1, - Operator = 2, - Comment = 3, - Whitespace = 4, - Identifier = 5, - NumberLiteral = 6, - StringLiteral = 7, - RegExpLiteral = 8, - } - interface ClassificationResult { - finalLexState: EndOfLineState; - entries: ClassificationInfo[]; - } - interface ClassificationInfo { - length: number; - classification: TokenClass; - } - interface Classifier { - /** - * Gives lexical classifications of tokens on a line without any syntactic context. - * For instance, a token consisting of the text 'string' can be either an identifier - * named 'string' or the keyword 'string', however, because this classifier is not aware, - * it relies on certain heuristics to give acceptable results. For classifications where - * speed trumps accuracy, this function is preferable; however, for true accuracy, the - * syntactic classifier is ideal. In fact, in certain editing scenarios, combining the - * lexical, syntactic, and semantic classifiers may issue the best user experience. - * - * @param text The text of a line to classify. - * @param lexState The state of the lexical classifier at the end of the previous line. - * @param syntacticClassifierAbsent Whether the client is *not* using a syntactic classifier. - * If there is no syntactic classifier (syntacticClassifierAbsent=true), - * certain heuristics may be used in its place; however, if there is a - * syntactic classifier (syntacticClassifierAbsent=false), certain - * classifications which may be incorrectly categorized will be given - * back as Identifiers in order to allow the syntactic classifier to - * subsume the classification. - * @deprecated Use getLexicalClassifications instead. - */ - getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult; - getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; - } - /** - * The document registry represents a store of SourceFile objects that can be shared between - * multiple LanguageService instances. A LanguageService instance holds on the SourceFile (AST) - * of files in the context. - * SourceFile objects account for most of the memory usage by the language service. Sharing - * the same DocumentRegistry instance between different instances of LanguageService allow - * for more efficient memory utilization since all projects will share at least the library - * file (lib.d.ts). - * - * A more advanced use of the document registry is to serialize sourceFile objects to disk - * and re-hydrate them when needed. - * - * To create a default DocumentRegistry, use createDocumentRegistry to create one, and pass it - * to all subsequent createLanguageService calls. - */ - interface DocumentRegistry { - /** - * Request a stored SourceFile with a given fileName and compilationSettings. - * The first call to acquire will call createLanguageServiceSourceFile to generate - * the SourceFile if was not found in the registry. - * - * @param fileName The name of the file requested - * @param compilationSettings Some compilation settings like target affects the - * shape of a the resulting SourceFile. This allows the DocumentRegistry to store - * multiple copies of the same file for different compilation settings. - * @parm scriptSnapshot Text of the file. Only used if the file was not found - * in the registry and a new one was created. - * @parm version Current version of the file. Only used if the file was not found - * in the registry and a new one was created. - */ - acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile; - /** - * Request an updated version of an already existing SourceFile with a given fileName - * and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile - * to get an updated SourceFile. - * - * @param fileName The name of the file requested - * @param compilationSettings Some compilation settings like target affects the - * shape of a the resulting SourceFile. This allows the DocumentRegistry to store - * multiple copies of the same file for different compilation settings. - * @param scriptSnapshot Text of the file. - * @param version Current version of the file. - */ - updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile; - /** - * Informs the DocumentRegistry that a file is not needed any longer. - * - * Note: It is not allowed to call release on a SourceFile that was not acquired from - * this registry originally. - * - * @param fileName The name of the file to be released - * @param compilationSettings The compilation settings used to acquire the file - */ - releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; - reportStats(): string; - } - module ScriptElementKind { - const unknown: string; - const warning: string; - const keyword: string; - const scriptElement: string; - const moduleElement: string; - const classElement: string; - const localClassElement: string; - const interfaceElement: string; - const typeElement: string; - const enumElement: string; - const variableElement: string; - const localVariableElement: string; - const functionElement: string; - const localFunctionElement: string; - const memberFunctionElement: string; - const memberGetAccessorElement: string; - const memberSetAccessorElement: string; - const memberVariableElement: string; - const constructorImplementationElement: string; - const callSignatureElement: string; - const indexSignatureElement: string; - const constructSignatureElement: string; - const parameterElement: string; - const typeParameterElement: string; - const primitiveType: string; - const label: string; - const alias: string; - const constElement: string; - const letElement: string; - } - module ScriptElementKindModifier { - const none: string; - const publicMemberModifier: string; - const privateMemberModifier: string; - const protectedMemberModifier: string; - const exportedModifier: string; - const ambientModifier: string; - const staticModifier: string; - const abstractModifier: string; - } - class ClassificationTypeNames { - static comment: string; - static identifier: string; - static keyword: string; - static numericLiteral: string; - static operator: string; - static stringLiteral: string; - static whiteSpace: string; - static text: string; - static punctuation: string; - static className: string; - static enumName: string; - static interfaceName: string; - static moduleName: string; - static typeParameterName: string; - static typeAliasName: string; - static parameterName: string; - static docCommentTagName: string; - } - const enum ClassificationType { - comment = 1, - identifier = 2, - keyword = 3, - numericLiteral = 4, - operator = 5, - stringLiteral = 6, - regularExpressionLiteral = 7, - whiteSpace = 8, - text = 9, - punctuation = 10, - className = 11, - enumName = 12, - interfaceName = 13, - moduleName = 14, - typeParameterName = 15, - typeAliasName = 16, - parameterName = 17, - docCommentTagName = 18, - } - interface DisplayPartsSymbolWriter extends SymbolWriter { - displayParts(): SymbolDisplayPart[]; - } - function displayPartsToString(displayParts: SymbolDisplayPart[]): string; - function getDefaultCompilerOptions(): CompilerOptions; - interface TranspileOptions { - compilerOptions?: CompilerOptions; - fileName?: string; - reportDiagnostics?: boolean; - moduleName?: string; - renamedDependencies?: Map; - } - interface TranspileOutput { - outputText: string; - diagnostics?: Diagnostic[]; - sourceMapText?: string; - } - function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; - function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; - function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile; - let disableIncrementalParsing: boolean; - function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; - function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string; - function createDocumentRegistry(useCaseSensitiveFileNames?: boolean): DocumentRegistry; - function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo; - function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService; - function createClassifier(): Classifier; - /** - * Get the path of the default library files (lib.d.ts) as distributed with the typescript - * node package. - * The functionality is not supported if the ts module is consumed outside of a node module. - */ - function getDefaultLibFilePath(options: CompilerOptions): string; -} +// Type definitions for TypeScript API v0.4.0 +// Project: http://www.typescriptlang.org/ +// Definitions by: Microsoft TypeScript +// 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. +***************************************************************************** */ + +declare namespace ts { + interface Map { + [index: string]: T; + } + interface FileMap { + get(fileName: string): T; + set(fileName: string, value: T): void; + contains(fileName: string): boolean; + remove(fileName: string): void; + forEachValue(f: (v: T) => void): void; + clear(): void; + } + interface TextRange { + pos: number; + end: number; + } + const enum SyntaxKind { + Unknown = 0, + EndOfFileToken = 1, + SingleLineCommentTrivia = 2, + MultiLineCommentTrivia = 3, + NewLineTrivia = 4, + WhitespaceTrivia = 5, + ShebangTrivia = 6, + ConflictMarkerTrivia = 7, + NumericLiteral = 8, + StringLiteral = 9, + RegularExpressionLiteral = 10, + NoSubstitutionTemplateLiteral = 11, + TemplateHead = 12, + TemplateMiddle = 13, + TemplateTail = 14, + OpenBraceToken = 15, + CloseBraceToken = 16, + OpenParenToken = 17, + CloseParenToken = 18, + OpenBracketToken = 19, + CloseBracketToken = 20, + DotToken = 21, + DotDotDotToken = 22, + SemicolonToken = 23, + CommaToken = 24, + LessThanToken = 25, + LessThanSlashToken = 26, + GreaterThanToken = 27, + LessThanEqualsToken = 28, + GreaterThanEqualsToken = 29, + EqualsEqualsToken = 30, + ExclamationEqualsToken = 31, + EqualsEqualsEqualsToken = 32, + ExclamationEqualsEqualsToken = 33, + EqualsGreaterThanToken = 34, + PlusToken = 35, + MinusToken = 36, + AsteriskToken = 37, + SlashToken = 38, + PercentToken = 39, + PlusPlusToken = 40, + MinusMinusToken = 41, + LessThanLessThanToken = 42, + GreaterThanGreaterThanToken = 43, + GreaterThanGreaterThanGreaterThanToken = 44, + AmpersandToken = 45, + BarToken = 46, + CaretToken = 47, + ExclamationToken = 48, + TildeToken = 49, + AmpersandAmpersandToken = 50, + BarBarToken = 51, + QuestionToken = 52, + ColonToken = 53, + AtToken = 54, + EqualsToken = 55, + PlusEqualsToken = 56, + MinusEqualsToken = 57, + AsteriskEqualsToken = 58, + SlashEqualsToken = 59, + PercentEqualsToken = 60, + LessThanLessThanEqualsToken = 61, + GreaterThanGreaterThanEqualsToken = 62, + GreaterThanGreaterThanGreaterThanEqualsToken = 63, + AmpersandEqualsToken = 64, + BarEqualsToken = 65, + CaretEqualsToken = 66, + Identifier = 67, + BreakKeyword = 68, + CaseKeyword = 69, + CatchKeyword = 70, + ClassKeyword = 71, + ConstKeyword = 72, + ContinueKeyword = 73, + DebuggerKeyword = 74, + DefaultKeyword = 75, + DeleteKeyword = 76, + DoKeyword = 77, + ElseKeyword = 78, + EnumKeyword = 79, + ExportKeyword = 80, + ExtendsKeyword = 81, + FalseKeyword = 82, + FinallyKeyword = 83, + ForKeyword = 84, + FunctionKeyword = 85, + IfKeyword = 86, + ImportKeyword = 87, + InKeyword = 88, + InstanceOfKeyword = 89, + NewKeyword = 90, + NullKeyword = 91, + ReturnKeyword = 92, + SuperKeyword = 93, + SwitchKeyword = 94, + ThisKeyword = 95, + ThrowKeyword = 96, + TrueKeyword = 97, + TryKeyword = 98, + TypeOfKeyword = 99, + VarKeyword = 100, + VoidKeyword = 101, + WhileKeyword = 102, + WithKeyword = 103, + ImplementsKeyword = 104, + InterfaceKeyword = 105, + LetKeyword = 106, + PackageKeyword = 107, + PrivateKeyword = 108, + ProtectedKeyword = 109, + PublicKeyword = 110, + StaticKeyword = 111, + YieldKeyword = 112, + AbstractKeyword = 113, + AsKeyword = 114, + AnyKeyword = 115, + AsyncKeyword = 116, + AwaitKeyword = 117, + BooleanKeyword = 118, + ConstructorKeyword = 119, + DeclareKeyword = 120, + GetKeyword = 121, + IsKeyword = 122, + ModuleKeyword = 123, + NamespaceKeyword = 124, + RequireKeyword = 125, + NumberKeyword = 126, + SetKeyword = 127, + StringKeyword = 128, + SymbolKeyword = 129, + TypeKeyword = 130, + FromKeyword = 131, + OfKeyword = 132, + QualifiedName = 133, + ComputedPropertyName = 134, + TypeParameter = 135, + Parameter = 136, + Decorator = 137, + PropertySignature = 138, + PropertyDeclaration = 139, + MethodSignature = 140, + MethodDeclaration = 141, + Constructor = 142, + GetAccessor = 143, + SetAccessor = 144, + CallSignature = 145, + ConstructSignature = 146, + IndexSignature = 147, + TypePredicate = 148, + TypeReference = 149, + FunctionType = 150, + ConstructorType = 151, + TypeQuery = 152, + TypeLiteral = 153, + ArrayType = 154, + TupleType = 155, + UnionType = 156, + IntersectionType = 157, + ParenthesizedType = 158, + ObjectBindingPattern = 159, + ArrayBindingPattern = 160, + BindingElement = 161, + ArrayLiteralExpression = 162, + ObjectLiteralExpression = 163, + PropertyAccessExpression = 164, + ElementAccessExpression = 165, + CallExpression = 166, + NewExpression = 167, + TaggedTemplateExpression = 168, + TypeAssertionExpression = 169, + ParenthesizedExpression = 170, + FunctionExpression = 171, + ArrowFunction = 172, + DeleteExpression = 173, + TypeOfExpression = 174, + VoidExpression = 175, + AwaitExpression = 176, + PrefixUnaryExpression = 177, + PostfixUnaryExpression = 178, + BinaryExpression = 179, + ConditionalExpression = 180, + TemplateExpression = 181, + YieldExpression = 182, + SpreadElementExpression = 183, + ClassExpression = 184, + OmittedExpression = 185, + ExpressionWithTypeArguments = 186, + AsExpression = 187, + TemplateSpan = 188, + SemicolonClassElement = 189, + Block = 190, + VariableStatement = 191, + EmptyStatement = 192, + ExpressionStatement = 193, + IfStatement = 194, + DoStatement = 195, + WhileStatement = 196, + ForStatement = 197, + ForInStatement = 198, + ForOfStatement = 199, + ContinueStatement = 200, + BreakStatement = 201, + ReturnStatement = 202, + WithStatement = 203, + SwitchStatement = 204, + LabeledStatement = 205, + ThrowStatement = 206, + TryStatement = 207, + DebuggerStatement = 208, + VariableDeclaration = 209, + VariableDeclarationList = 210, + FunctionDeclaration = 211, + ClassDeclaration = 212, + InterfaceDeclaration = 213, + TypeAliasDeclaration = 214, + EnumDeclaration = 215, + ModuleDeclaration = 216, + ModuleBlock = 217, + CaseBlock = 218, + ImportEqualsDeclaration = 219, + ImportDeclaration = 220, + ImportClause = 221, + NamespaceImport = 222, + NamedImports = 223, + ImportSpecifier = 224, + ExportAssignment = 225, + ExportDeclaration = 226, + NamedExports = 227, + ExportSpecifier = 228, + MissingDeclaration = 229, + ExternalModuleReference = 230, + JsxElement = 231, + JsxSelfClosingElement = 232, + JsxOpeningElement = 233, + JsxText = 234, + JsxClosingElement = 235, + JsxAttribute = 236, + JsxSpreadAttribute = 237, + JsxExpression = 238, + CaseClause = 239, + DefaultClause = 240, + HeritageClause = 241, + CatchClause = 242, + PropertyAssignment = 243, + ShorthandPropertyAssignment = 244, + EnumMember = 245, + SourceFile = 246, + JSDocTypeExpression = 247, + JSDocAllType = 248, + JSDocUnknownType = 249, + JSDocArrayType = 250, + JSDocUnionType = 251, + JSDocTupleType = 252, + JSDocNullableType = 253, + JSDocNonNullableType = 254, + JSDocRecordType = 255, + JSDocRecordMember = 256, + JSDocTypeReference = 257, + JSDocOptionalType = 258, + JSDocFunctionType = 259, + JSDocVariadicType = 260, + JSDocConstructorType = 261, + JSDocThisType = 262, + JSDocComment = 263, + JSDocTag = 264, + JSDocParameterTag = 265, + JSDocReturnTag = 266, + JSDocTypeTag = 267, + JSDocTemplateTag = 268, + SyntaxList = 269, + Count = 270, + FirstAssignment = 55, + LastAssignment = 66, + FirstReservedWord = 68, + LastReservedWord = 103, + FirstKeyword = 68, + LastKeyword = 132, + FirstFutureReservedWord = 104, + LastFutureReservedWord = 112, + FirstTypeNode = 149, + LastTypeNode = 158, + FirstPunctuation = 15, + LastPunctuation = 66, + FirstToken = 0, + LastToken = 132, + FirstTriviaToken = 2, + LastTriviaToken = 7, + FirstLiteralToken = 8, + LastLiteralToken = 11, + FirstTemplateToken = 11, + LastTemplateToken = 14, + FirstBinaryOperator = 25, + LastBinaryOperator = 66, + FirstNode = 133, + } + const enum NodeFlags { + Export = 1, + Ambient = 2, + Public = 16, + Private = 32, + Protected = 64, + Static = 128, + Abstract = 256, + Async = 512, + Default = 1024, + MultiLine = 2048, + Synthetic = 4096, + DeclarationFile = 8192, + Let = 16384, + Const = 32768, + OctalLiteral = 65536, + Namespace = 131072, + ExportContext = 262144, + Modifier = 2035, + AccessibilityModifier = 112, + BlockScoped = 49152, + } + const enum JsxFlags { + None = 0, + IntrinsicNamedElement = 1, + IntrinsicIndexedElement = 2, + ClassElement = 4, + UnknownElement = 8, + IntrinsicElement = 3, + } + interface Node extends TextRange { + kind: SyntaxKind; + flags: NodeFlags; + decorators?: NodeArray; + modifiers?: ModifiersArray; + parent?: Node; + } + interface NodeArray extends Array, TextRange { + hasTrailingComma?: boolean; + } + interface ModifiersArray extends NodeArray { + flags: number; + } + interface Identifier extends PrimaryExpression { + text: string; + originalKeywordKind?: SyntaxKind; + } + interface QualifiedName extends Node { + left: EntityName; + right: Identifier; + } + type EntityName = Identifier | QualifiedName; + type DeclarationName = Identifier | LiteralExpression | ComputedPropertyName | BindingPattern; + interface Declaration extends Node { + _declarationBrand: any; + name?: DeclarationName; + } + interface ComputedPropertyName extends Node { + expression: Expression; + } + interface Decorator extends Node { + expression: LeftHandSideExpression; + } + interface TypeParameterDeclaration extends Declaration { + name: Identifier; + constraint?: TypeNode; + expression?: Expression; + } + interface SignatureDeclaration extends Declaration { + typeParameters?: NodeArray; + parameters: NodeArray; + type?: TypeNode; + } + interface VariableDeclaration extends Declaration { + parent?: VariableDeclarationList; + name: Identifier | BindingPattern; + type?: TypeNode; + initializer?: Expression; + } + interface VariableDeclarationList extends Node { + declarations: NodeArray; + } + interface ParameterDeclaration extends Declaration { + dotDotDotToken?: Node; + name: Identifier | BindingPattern; + questionToken?: Node; + type?: TypeNode; + initializer?: Expression; + } + interface BindingElement extends Declaration { + propertyName?: Identifier; + dotDotDotToken?: Node; + name: Identifier | BindingPattern; + initializer?: Expression; + } + interface PropertyDeclaration extends Declaration, ClassElement { + name: DeclarationName; + questionToken?: Node; + type?: TypeNode; + initializer?: Expression; + } + interface ObjectLiteralElement extends Declaration { + _objectLiteralBrandBrand: any; + } + interface PropertyAssignment extends ObjectLiteralElement { + _propertyAssignmentBrand: any; + name: DeclarationName; + questionToken?: Node; + initializer: Expression; + } + interface ShorthandPropertyAssignment extends ObjectLiteralElement { + name: Identifier; + questionToken?: Node; + } + interface VariableLikeDeclaration extends Declaration { + propertyName?: Identifier; + dotDotDotToken?: Node; + name: DeclarationName; + questionToken?: Node; + type?: TypeNode; + initializer?: Expression; + } + interface BindingPattern extends Node { + elements: NodeArray; + } + /** + * Several node kinds share function-like features such as a signature, + * a name, and a body. These nodes should extend FunctionLikeDeclaration. + * Examples: + * - FunctionDeclaration + * - MethodDeclaration + * - AccessorDeclaration + */ + interface FunctionLikeDeclaration extends SignatureDeclaration { + _functionLikeDeclarationBrand: any; + asteriskToken?: Node; + questionToken?: Node; + body?: Block | Expression; + } + interface FunctionDeclaration extends FunctionLikeDeclaration, Statement { + name?: Identifier; + body?: Block; + } + interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + body?: Block; + } + interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { + body?: Block; + } + interface SemicolonClassElement extends ClassElement { + _semicolonClassElementBrand: any; + } + interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + _accessorDeclarationBrand: any; + body: Block; + } + interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement { + _indexSignatureDeclarationBrand: any; + } + interface TypeNode extends Node { + _typeNodeBrand: any; + } + interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration { + _functionOrConstructorTypeNodeBrand: any; + } + interface TypeReferenceNode extends TypeNode { + typeName: EntityName; + typeArguments?: NodeArray; + } + interface TypePredicateNode extends TypeNode { + parameterName: Identifier; + type: TypeNode; + } + interface TypeQueryNode extends TypeNode { + exprName: EntityName; + } + interface TypeLiteralNode extends TypeNode, Declaration { + members: NodeArray; + } + interface ArrayTypeNode extends TypeNode { + elementType: TypeNode; + } + interface TupleTypeNode extends TypeNode { + elementTypes: NodeArray; + } + interface UnionOrIntersectionTypeNode extends TypeNode { + types: NodeArray; + } + interface UnionTypeNode extends UnionOrIntersectionTypeNode { + } + interface IntersectionTypeNode extends UnionOrIntersectionTypeNode { + } + interface ParenthesizedTypeNode extends TypeNode { + type: TypeNode; + } + interface StringLiteral extends LiteralExpression, TypeNode { + _stringLiteralBrand: any; + } + interface Expression extends Node { + _expressionBrand: any; + contextualType?: Type; + } + interface UnaryExpression extends Expression { + _unaryExpressionBrand: any; + } + interface PrefixUnaryExpression extends UnaryExpression { + operator: SyntaxKind; + operand: UnaryExpression; + } + interface PostfixUnaryExpression extends PostfixExpression { + operand: LeftHandSideExpression; + operator: SyntaxKind; + } + interface PostfixExpression extends UnaryExpression { + _postfixExpressionBrand: any; + } + interface LeftHandSideExpression extends PostfixExpression { + _leftHandSideExpressionBrand: any; + } + interface MemberExpression extends LeftHandSideExpression { + _memberExpressionBrand: any; + } + interface PrimaryExpression extends MemberExpression { + _primaryExpressionBrand: any; + } + interface DeleteExpression extends UnaryExpression { + expression: UnaryExpression; + } + interface TypeOfExpression extends UnaryExpression { + expression: UnaryExpression; + } + interface VoidExpression extends UnaryExpression { + expression: UnaryExpression; + } + interface AwaitExpression extends UnaryExpression { + expression: UnaryExpression; + } + interface YieldExpression extends Expression { + asteriskToken?: Node; + expression?: Expression; + } + interface BinaryExpression extends Expression { + left: Expression; + operatorToken: Node; + right: Expression; + } + interface ConditionalExpression extends Expression { + condition: Expression; + questionToken: Node; + whenTrue: Expression; + colonToken: Node; + whenFalse: Expression; + } + interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { + name?: Identifier; + body: Block | Expression; + } + interface ArrowFunction extends Expression, FunctionLikeDeclaration { + equalsGreaterThanToken: Node; + } + interface LiteralExpression extends PrimaryExpression { + text: string; + isUnterminated?: boolean; + hasExtendedUnicodeEscape?: boolean; + } + interface TemplateExpression extends PrimaryExpression { + head: LiteralExpression; + templateSpans: NodeArray; + } + interface TemplateSpan extends Node { + expression: Expression; + literal: LiteralExpression; + } + interface ParenthesizedExpression extends PrimaryExpression { + expression: Expression; + } + interface ArrayLiteralExpression extends PrimaryExpression { + elements: NodeArray; + } + interface SpreadElementExpression extends Expression { + expression: Expression; + } + interface ObjectLiteralExpression extends PrimaryExpression, Declaration { + properties: NodeArray; + } + interface PropertyAccessExpression extends MemberExpression { + expression: LeftHandSideExpression; + dotToken: Node; + name: Identifier; + } + interface ElementAccessExpression extends MemberExpression { + expression: LeftHandSideExpression; + argumentExpression?: Expression; + } + interface CallExpression extends LeftHandSideExpression { + expression: LeftHandSideExpression; + typeArguments?: NodeArray; + arguments: NodeArray; + } + interface ExpressionWithTypeArguments extends TypeNode { + expression: LeftHandSideExpression; + typeArguments?: NodeArray; + } + interface NewExpression extends CallExpression, PrimaryExpression { + } + interface TaggedTemplateExpression extends MemberExpression { + tag: LeftHandSideExpression; + template: LiteralExpression | TemplateExpression; + } + type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; + interface AsExpression extends Expression { + expression: Expression; + type: TypeNode; + } + interface TypeAssertion extends UnaryExpression { + type: TypeNode; + expression: UnaryExpression; + } + type AssertionExpression = TypeAssertion | AsExpression; + interface JsxElement extends PrimaryExpression { + openingElement: JsxOpeningElement; + children: NodeArray; + closingElement: JsxClosingElement; + } + interface JsxOpeningElement extends Expression { + _openingElementBrand?: any; + tagName: EntityName; + attributes: NodeArray; + } + interface JsxSelfClosingElement extends PrimaryExpression, JsxOpeningElement { + _selfClosingElementBrand?: any; + } + type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; + interface JsxAttribute extends Node { + name: Identifier; + initializer?: Expression; + } + interface JsxSpreadAttribute extends Node { + expression: Expression; + } + interface JsxClosingElement extends Node { + tagName: EntityName; + } + interface JsxExpression extends Expression { + expression?: Expression; + } + interface JsxText extends Node { + _jsxTextExpressionBrand: any; + } + type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement; + interface Statement extends Node { + _statementBrand: any; + } + interface Block extends Statement { + statements: NodeArray; + } + interface VariableStatement extends Statement { + declarationList: VariableDeclarationList; + } + interface ExpressionStatement extends Statement { + expression: Expression; + } + interface IfStatement extends Statement { + expression: Expression; + thenStatement: Statement; + elseStatement?: Statement; + } + interface IterationStatement extends Statement { + statement: Statement; + } + interface DoStatement extends IterationStatement { + expression: Expression; + } + interface WhileStatement extends IterationStatement { + expression: Expression; + } + interface ForStatement extends IterationStatement { + initializer?: VariableDeclarationList | Expression; + condition?: Expression; + incrementor?: Expression; + } + interface ForInStatement extends IterationStatement { + initializer: VariableDeclarationList | Expression; + expression: Expression; + } + interface ForOfStatement extends IterationStatement { + initializer: VariableDeclarationList | Expression; + expression: Expression; + } + interface BreakOrContinueStatement extends Statement { + label?: Identifier; + } + interface ReturnStatement extends Statement { + expression?: Expression; + } + interface WithStatement extends Statement { + expression: Expression; + statement: Statement; + } + interface SwitchStatement extends Statement { + expression: Expression; + caseBlock: CaseBlock; + } + interface CaseBlock extends Node { + clauses: NodeArray; + } + interface CaseClause extends Node { + expression?: Expression; + statements: NodeArray; + } + interface DefaultClause extends Node { + statements: NodeArray; + } + type CaseOrDefaultClause = CaseClause | DefaultClause; + interface LabeledStatement extends Statement { + label: Identifier; + statement: Statement; + } + interface ThrowStatement extends Statement { + expression: Expression; + } + interface TryStatement extends Statement { + tryBlock: Block; + catchClause?: CatchClause; + finallyBlock?: Block; + } + interface CatchClause extends Node { + variableDeclaration: VariableDeclaration; + block: Block; + } + interface ClassLikeDeclaration extends Declaration { + name?: Identifier; + typeParameters?: NodeArray; + heritageClauses?: NodeArray; + members: NodeArray; + } + interface ClassDeclaration extends ClassLikeDeclaration, Statement { + } + interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { + } + interface ClassElement extends Declaration { + _classElementBrand: any; + } + interface InterfaceDeclaration extends Declaration, Statement { + name: Identifier; + typeParameters?: NodeArray; + heritageClauses?: NodeArray; + members: NodeArray; + } + interface HeritageClause extends Node { + token: SyntaxKind; + types?: NodeArray; + } + interface TypeAliasDeclaration extends Declaration, Statement { + name: Identifier; + typeParameters?: NodeArray; + type: TypeNode; + } + interface EnumMember extends Declaration { + name: DeclarationName; + initializer?: Expression; + } + interface EnumDeclaration extends Declaration, Statement { + name: Identifier; + members: NodeArray; + } + interface ModuleDeclaration extends Declaration, Statement { + name: Identifier | LiteralExpression; + body: ModuleBlock | ModuleDeclaration; + } + interface ModuleBlock extends Node, Statement { + statements: NodeArray; + } + interface ImportEqualsDeclaration extends Declaration, Statement { + name: Identifier; + moduleReference: EntityName | ExternalModuleReference; + } + interface ExternalModuleReference extends Node { + expression?: Expression; + } + interface ImportDeclaration extends Statement { + importClause?: ImportClause; + moduleSpecifier: Expression; + } + interface ImportClause extends Declaration { + name?: Identifier; + namedBindings?: NamespaceImport | NamedImports; + } + interface NamespaceImport extends Declaration { + name: Identifier; + } + interface ExportDeclaration extends Declaration, Statement { + exportClause?: NamedExports; + moduleSpecifier?: Expression; + } + interface NamedImportsOrExports extends Node { + elements: NodeArray; + } + type NamedImports = NamedImportsOrExports; + type NamedExports = NamedImportsOrExports; + interface ImportOrExportSpecifier extends Declaration { + propertyName?: Identifier; + name: Identifier; + } + type ImportSpecifier = ImportOrExportSpecifier; + type ExportSpecifier = ImportOrExportSpecifier; + interface ExportAssignment extends Declaration, Statement { + isExportEquals?: boolean; + expression: Expression; + } + interface FileReference extends TextRange { + fileName: string; + } + interface CommentRange extends TextRange { + hasTrailingNewLine?: boolean; + kind: SyntaxKind; + } + interface JSDocTypeExpression extends Node { + type: JSDocType; + } + interface JSDocType extends TypeNode { + _jsDocTypeBrand: any; + } + interface JSDocAllType extends JSDocType { + _JSDocAllTypeBrand: any; + } + interface JSDocUnknownType extends JSDocType { + _JSDocUnknownTypeBrand: any; + } + interface JSDocArrayType extends JSDocType { + elementType: JSDocType; + } + interface JSDocUnionType extends JSDocType { + types: NodeArray; + } + interface JSDocTupleType extends JSDocType { + types: NodeArray; + } + interface JSDocNonNullableType extends JSDocType { + type: JSDocType; + } + interface JSDocNullableType extends JSDocType { + type: JSDocType; + } + interface JSDocRecordType extends JSDocType, TypeLiteralNode { + members: NodeArray; + } + interface JSDocTypeReference extends JSDocType { + name: EntityName; + typeArguments: NodeArray; + } + interface JSDocOptionalType extends JSDocType { + type: JSDocType; + } + interface JSDocFunctionType extends JSDocType, SignatureDeclaration { + parameters: NodeArray; + type: JSDocType; + } + interface JSDocVariadicType extends JSDocType { + type: JSDocType; + } + interface JSDocConstructorType extends JSDocType { + type: JSDocType; + } + interface JSDocThisType extends JSDocType { + type: JSDocType; + } + interface JSDocRecordMember extends PropertyDeclaration { + name: Identifier | LiteralExpression; + type?: JSDocType; + } + interface JSDocComment extends Node { + tags: NodeArray; + } + interface JSDocTag extends Node { + atToken: Node; + tagName: Identifier; + } + interface JSDocTemplateTag extends JSDocTag { + typeParameters: NodeArray; + } + interface JSDocReturnTag extends JSDocTag { + typeExpression: JSDocTypeExpression; + } + interface JSDocTypeTag extends JSDocTag { + typeExpression: JSDocTypeExpression; + } + interface JSDocParameterTag extends JSDocTag { + preParameterName?: Identifier; + typeExpression?: JSDocTypeExpression; + postParameterName?: Identifier; + isBracketed: boolean; + } + interface SourceFile extends Declaration { + statements: NodeArray; + endOfFileToken: Node; + fileName: string; + text: string; + amdDependencies: { + path: string; + name: string; + }[]; + moduleName: string; + referencedFiles: FileReference[]; + languageVariant: LanguageVariant; + /** + * lib.d.ts should have a reference comment like + * + * /// + * + * If any other file has this comment, it signals not to include lib.d.ts + * because this containing file is intended to act as a default library. + */ + hasNoDefaultLib: boolean; + languageVersion: ScriptTarget; + } + interface ScriptReferenceHost { + getCompilerOptions(): CompilerOptions; + getSourceFile(fileName: string): SourceFile; + getCurrentDirectory(): string; + } + interface ParseConfigHost extends ModuleResolutionHost { + readDirectory(rootDir: string, extension: string, exclude: string[]): string[]; + } + interface WriteFileCallback { + (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void; + } + class OperationCanceledException { + } + interface CancellationToken { + isCancellationRequested(): boolean; + /** @throws OperationCanceledException if isCancellationRequested is true */ + throwIfCancellationRequested(): void; + } + interface Program extends ScriptReferenceHost { + /** + * Get a list of root file names that were passed to a 'createProgram' + */ + getRootFileNames(): string[]; + /** + * Get a list of files in the program + */ + getSourceFiles(): SourceFile[]; + /** + * Emits the JavaScript and declaration files. If targetSourceFile is not specified, then + * the JavaScript and declaration files will be produced for all the files in this program. + * If targetSourceFile is specified, then only the JavaScript and declaration for that + * specific file will be generated. + * + * If writeFile is not specified then the writeFile callback from the compiler host will be + * used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter + * will be invoked when writing the JavaScript and declaration files. + */ + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult; + getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; + getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + /** + * Gets a type checker that can be used to semantically analyze source fils in the program. + */ + getTypeChecker(): TypeChecker; + } + interface SourceMapSpan { + /** Line number in the .js file. */ + emittedLine: number; + /** Column number in the .js file. */ + emittedColumn: number; + /** Line number in the .ts file. */ + sourceLine: number; + /** Column number in the .ts file. */ + sourceColumn: number; + /** Optional name (index into names array) associated with this span. */ + nameIndex?: number; + /** .ts file (index into sources array) associated with this span */ + sourceIndex: number; + } + interface SourceMapData { + sourceMapFilePath: string; + jsSourceMappingURL: string; + sourceMapFile: string; + sourceMapSourceRoot: string; + sourceMapSources: string[]; + sourceMapSourcesContent?: string[]; + inputSourceFileNames: string[]; + sourceMapNames?: string[]; + sourceMapMappings: string; + sourceMapDecodedMappings: SourceMapSpan[]; + } + /** Return code used by getEmitOutput function to indicate status of the function */ + enum ExitStatus { + Success = 0, + DiagnosticsPresent_OutputsSkipped = 1, + DiagnosticsPresent_OutputsGenerated = 2, + } + interface EmitResult { + emitSkipped: boolean; + diagnostics: Diagnostic[]; + } + interface TypeChecker { + getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type; + getDeclaredTypeOfSymbol(symbol: Symbol): Type; + getPropertiesOfType(type: Type): Symbol[]; + getPropertyOfType(type: Type, propertyName: string): Symbol; + getSignaturesOfType(type: Type, kind: SignatureKind): Signature[]; + getIndexTypeOfType(type: Type, kind: IndexKind): Type; + getBaseTypes(type: InterfaceType): ObjectType[]; + getReturnTypeOfSignature(signature: Signature): Type; + getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; + getSymbolAtLocation(node: Node): Symbol; + getShorthandAssignmentValueSymbol(location: Node): Symbol; + getTypeAtLocation(node: Node): Type; + typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; + symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string; + getSymbolDisplayBuilder(): SymbolDisplayBuilder; + getFullyQualifiedName(symbol: Symbol): string; + getAugmentedPropertiesOfType(type: Type): Symbol[]; + getRootSymbols(symbol: Symbol): Symbol[]; + getContextualType(node: Expression): Type; + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature; + getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature; + isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; + isUndefinedSymbol(symbol: Symbol): boolean; + isArgumentsSymbol(symbol: Symbol): boolean; + getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; + isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; + getAliasedSymbol(symbol: Symbol): Symbol; + getExportsOfModule(moduleSymbol: Symbol): Symbol[]; + getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type; + getJsxIntrinsicTagNames(): Symbol[]; + isOptionalParameter(node: ParameterDeclaration): boolean; + } + interface SymbolDisplayBuilder { + buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; + buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags): void; + buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + } + interface SymbolWriter { + writeKeyword(text: string): void; + writeOperator(text: string): void; + writePunctuation(text: string): void; + writeSpace(text: string): void; + writeStringLiteral(text: string): void; + writeParameter(text: string): void; + writeSymbol(text: string, symbol: Symbol): void; + writeLine(): void; + increaseIndent(): void; + decreaseIndent(): void; + clear(): void; + trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; + } + const enum TypeFormatFlags { + None = 0, + WriteArrayAsGenericType = 1, + UseTypeOfFunction = 2, + NoTruncation = 4, + WriteArrowStyleSignature = 8, + WriteOwnNameForAnyLike = 16, + WriteTypeArgumentsOfSignature = 32, + InElementType = 64, + UseFullyQualifiedType = 128, + } + const enum SymbolFormatFlags { + None = 0, + WriteTypeParametersOrArguments = 1, + UseOnlyExternalAliasing = 2, + } + interface TypePredicate { + parameterName: string; + parameterIndex: number; + type: Type; + } + const enum SymbolFlags { + None = 0, + FunctionScopedVariable = 1, + BlockScopedVariable = 2, + Property = 4, + EnumMember = 8, + Function = 16, + Class = 32, + Interface = 64, + ConstEnum = 128, + RegularEnum = 256, + ValueModule = 512, + NamespaceModule = 1024, + TypeLiteral = 2048, + ObjectLiteral = 4096, + Method = 8192, + Constructor = 16384, + GetAccessor = 32768, + SetAccessor = 65536, + Signature = 131072, + TypeParameter = 262144, + TypeAlias = 524288, + ExportValue = 1048576, + ExportType = 2097152, + ExportNamespace = 4194304, + Alias = 8388608, + Instantiated = 16777216, + Merged = 33554432, + Transient = 67108864, + Prototype = 134217728, + SyntheticProperty = 268435456, + Optional = 536870912, + ExportStar = 1073741824, + Enum = 384, + Variable = 3, + Value = 107455, + Type = 793056, + Namespace = 1536, + Module = 1536, + Accessor = 98304, + FunctionScopedVariableExcludes = 107454, + BlockScopedVariableExcludes = 107455, + ParameterExcludes = 107455, + PropertyExcludes = 107455, + EnumMemberExcludes = 107455, + FunctionExcludes = 106927, + ClassExcludes = 899519, + InterfaceExcludes = 792960, + RegularEnumExcludes = 899327, + ConstEnumExcludes = 899967, + ValueModuleExcludes = 106639, + NamespaceModuleExcludes = 0, + MethodExcludes = 99263, + GetAccessorExcludes = 41919, + SetAccessorExcludes = 74687, + TypeParameterExcludes = 530912, + TypeAliasExcludes = 793056, + AliasExcludes = 8388608, + ModuleMember = 8914931, + ExportHasLocal = 944, + HasExports = 1952, + HasMembers = 6240, + BlockScoped = 418, + PropertyOrAccessor = 98308, + Export = 7340032, + } + interface Symbol { + flags: SymbolFlags; + name: string; + declarations?: Declaration[]; + valueDeclaration?: Declaration; + members?: SymbolTable; + exports?: SymbolTable; + } + interface SymbolTable { + [index: string]: Symbol; + } + const enum TypeFlags { + Any = 1, + String = 2, + Number = 4, + Boolean = 8, + Void = 16, + Undefined = 32, + Null = 64, + Enum = 128, + StringLiteral = 256, + TypeParameter = 512, + Class = 1024, + Interface = 2048, + Reference = 4096, + Tuple = 8192, + Union = 16384, + Intersection = 32768, + Anonymous = 65536, + Instantiated = 131072, + ObjectLiteral = 524288, + ESSymbol = 16777216, + StringLike = 258, + NumberLike = 132, + ObjectType = 80896, + UnionOrIntersection = 49152, + StructuredType = 130048, + } + interface Type { + flags: TypeFlags; + symbol?: Symbol; + } + interface StringLiteralType extends Type { + text: string; + } + interface ObjectType extends Type { + } + interface InterfaceType extends ObjectType { + typeParameters: TypeParameter[]; + outerTypeParameters: TypeParameter[]; + localTypeParameters: TypeParameter[]; + } + interface InterfaceTypeWithDeclaredMembers extends InterfaceType { + declaredProperties: Symbol[]; + declaredCallSignatures: Signature[]; + declaredConstructSignatures: Signature[]; + declaredStringIndexType: Type; + declaredNumberIndexType: Type; + } + interface TypeReference extends ObjectType { + target: GenericType; + typeArguments: Type[]; + } + interface GenericType extends InterfaceType, TypeReference { + } + interface TupleType extends ObjectType { + elementTypes: Type[]; + baseArrayType: TypeReference; + } + interface UnionOrIntersectionType extends Type { + types: Type[]; + } + interface UnionType extends UnionOrIntersectionType { + } + interface IntersectionType extends UnionOrIntersectionType { + } + interface TypeParameter extends Type { + constraint: Type; + } + const enum SignatureKind { + Call = 0, + Construct = 1, + } + interface Signature { + declaration: SignatureDeclaration; + typeParameters: TypeParameter[]; + parameters: Symbol[]; + typePredicate?: TypePredicate; + } + const enum IndexKind { + String = 0, + Number = 1, + } + interface DiagnosticMessage { + key: string; + category: DiagnosticCategory; + code: number; + } + /** + * A linked list of formatted diagnostic messages to be used as part of a multiline message. + * It is built from the bottom up, leaving the head to be the "main" diagnostic. + * While it seems that DiagnosticMessageChain is structurally similar to DiagnosticMessage, + * the difference is that messages are all preformatted in DMC. + */ + interface DiagnosticMessageChain { + messageText: string; + category: DiagnosticCategory; + code: number; + next?: DiagnosticMessageChain; + } + interface Diagnostic { + file: SourceFile; + start: number; + length: number; + messageText: string | DiagnosticMessageChain; + category: DiagnosticCategory; + code: number; + } + enum DiagnosticCategory { + Warning = 0, + Error = 1, + Message = 2, + } + const enum ModuleResolutionKind { + Classic = 1, + NodeJs = 2, + } + interface CompilerOptions { + allowNonTsExtensions?: boolean; + charset?: string; + declaration?: boolean; + diagnostics?: boolean; + emitBOM?: boolean; + help?: boolean; + init?: boolean; + inlineSourceMap?: boolean; + inlineSources?: boolean; + jsx?: JsxEmit; + listFiles?: boolean; + locale?: string; + mapRoot?: string; + module?: ModuleKind; + newLine?: NewLineKind; + noEmit?: boolean; + noEmitHelpers?: boolean; + noEmitOnError?: boolean; + noErrorTruncation?: boolean; + noImplicitAny?: boolean; + noLib?: boolean; + noResolve?: boolean; + out?: string; + outFile?: string; + outDir?: string; + preserveConstEnums?: boolean; + project?: string; + removeComments?: boolean; + rootDir?: string; + sourceMap?: boolean; + sourceRoot?: string; + suppressExcessPropertyErrors?: boolean; + suppressImplicitAnyIndexErrors?: boolean; + target?: ScriptTarget; + version?: boolean; + watch?: boolean; + isolatedModules?: boolean; + experimentalDecorators?: boolean; + experimentalAsyncFunctions?: boolean; + emitDecoratorMetadata?: boolean; + moduleResolution?: ModuleResolutionKind; + [option: string]: string | number | boolean; + } + const enum ModuleKind { + None = 0, + CommonJS = 1, + AMD = 2, + UMD = 3, + System = 4, + } + const enum JsxEmit { + None = 0, + Preserve = 1, + React = 2, + } + const enum NewLineKind { + CarriageReturnLineFeed = 0, + LineFeed = 1, + } + interface LineAndCharacter { + line: number; + character: number; + } + const enum ScriptTarget { + ES3 = 0, + ES5 = 1, + ES6 = 2, + Latest = 2, + } + const enum LanguageVariant { + Standard = 0, + JSX = 1, + } + interface ParsedCommandLine { + options: CompilerOptions; + fileNames: string[]; + errors: Diagnostic[]; + } + interface ModuleResolutionHost { + fileExists(fileName: string): boolean; + readFile(fileName: string): string; + } + interface ResolvedModule { + resolvedFileName: string; + isExternalLibraryImport?: boolean; + } + interface ResolvedModuleWithFailedLookupLocations { + resolvedModule: ResolvedModule; + failedLookupLocations: string[]; + } + interface CompilerHost extends ModuleResolutionHost { + getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile; + getCancellationToken?(): CancellationToken; + getDefaultLibFileName(options: CompilerOptions): string; + writeFile: WriteFileCallback; + getCurrentDirectory(): string; + getCanonicalFileName(fileName: string): string; + useCaseSensitiveFileNames(): boolean; + getNewLine(): string; + resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; + } + interface TextSpan { + start: number; + length: number; + } + interface TextChangeRange { + span: TextSpan; + newLength: number; + } +} +declare namespace ts { + interface System { + args: string[]; + newLine: string; + useCaseSensitiveFileNames: boolean; + write(s: string): void; + readFile(path: string, encoding?: string): string; + writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; + watchFile?(path: string, callback: (path: string) => void): FileWatcher; + resolvePath(path: string): string; + fileExists(path: string): boolean; + directoryExists(path: string): boolean; + createDirectory(path: string): void; + getExecutingFilePath(): string; + getCurrentDirectory(): string; + readDirectory(path: string, extension?: string, exclude?: string[]): string[]; + getMemoryUsage?(): number; + exit(exitCode?: number): void; + } + interface FileWatcher { + close(): void; + } + var sys: System; +} +declare namespace ts { + interface ErrorCallback { + (message: DiagnosticMessage, length: number): void; + } + interface Scanner { + getStartPos(): number; + getToken(): SyntaxKind; + getTextPos(): number; + getTokenPos(): number; + getTokenText(): string; + getTokenValue(): string; + hasExtendedUnicodeEscape(): boolean; + hasPrecedingLineBreak(): boolean; + isIdentifier(): boolean; + isReservedWord(): boolean; + isUnterminated(): boolean; + reScanGreaterToken(): SyntaxKind; + reScanSlashToken(): SyntaxKind; + reScanTemplateToken(): SyntaxKind; + scanJsxIdentifier(): SyntaxKind; + reScanJsxToken(): SyntaxKind; + scanJsxToken(): SyntaxKind; + scan(): SyntaxKind; + setText(text: string, start?: number, length?: number): void; + setOnError(onError: ErrorCallback): void; + setScriptTarget(scriptTarget: ScriptTarget): void; + setLanguageVariant(variant: LanguageVariant): void; + setTextPos(textPos: number): void; + lookAhead(callback: () => T): T; + tryScan(callback: () => T): T; + } + function tokenToString(t: SyntaxKind): string; + function getPositionOfLineAndCharacter(sourceFile: SourceFile, line: number, character: number): number; + function getLineAndCharacterOfPosition(sourceFile: SourceFile, position: number): LineAndCharacter; + function isWhiteSpace(ch: number): boolean; + function isLineBreak(ch: number): boolean; + function couldStartTrivia(text: string, pos: number): boolean; + function getLeadingCommentRanges(text: string, pos: number): CommentRange[]; + function getTrailingCommentRanges(text: string, pos: number): CommentRange[]; + /** Optionally, get the shebang */ + function getShebang(text: string): string; + function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; + function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; + function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; +} +declare namespace ts { + function getDefaultLibFileName(options: CompilerOptions): string; + function textSpanEnd(span: TextSpan): number; + function textSpanIsEmpty(span: TextSpan): boolean; + function textSpanContainsPosition(span: TextSpan, position: number): boolean; + function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean; + function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean; + function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan; + function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean; + function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean; + function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number): boolean; + function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean; + function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan; + function createTextSpan(start: number, length: number): TextSpan; + function createTextSpanFromBounds(start: number, end: number): TextSpan; + function textChangeRangeNewSpan(range: TextChangeRange): TextSpan; + function textChangeRangeIsUnchanged(range: TextChangeRange): boolean; + function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange; + let unchangedTextChangeRange: TextChangeRange; + /** + * Called to merge all the changes that occurred across several versions of a script snapshot + * into a single change. i.e. if a user keeps making successive edits to a script we will + * have a text change from V1 to V2, V2 to V3, ..., Vn. + * + * This function will then merge those changes into a single change range valid between V1 and + * Vn. + */ + function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; + function getTypeParameterOwner(d: Declaration): Declaration; +} +declare namespace ts { + function getNodeConstructor(kind: SyntaxKind): new () => Node; + function createNode(kind: SyntaxKind): Node; + function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; + function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean): SourceFile; + function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; +} +declare namespace ts { + const version: string; + function findConfigFile(searchPath: string): string; + function resolveTripleslashReference(moduleName: string, containingFile: string): string; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; + function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; + function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; +} +declare namespace ts { + function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readConfigFile(fileName: string): { + config?: any; + error?: Diagnostic; + }; + /** + * Parse the text of the tsconfig.json file + * @param fileName The path to the config file + * @param jsonText The text of the config file + */ + function parseConfigFileText(fileName: string, jsonText: string): { + config?: any; + error?: Diagnostic; + }; + /** + * Parse the contents of a config file (tsconfig.json). + * @param json The contents of the config file to parse + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseConfigFile(json: any, host: ParseConfigHost, basePath: string): ParsedCommandLine; +} +declare namespace ts { + /** The version of the language service API */ + let servicesVersion: string; + interface Node { + getSourceFile(): SourceFile; + getChildCount(sourceFile?: SourceFile): number; + getChildAt(index: number, sourceFile?: SourceFile): Node; + getChildren(sourceFile?: SourceFile): Node[]; + getStart(sourceFile?: SourceFile): number; + getFullStart(): number; + getEnd(): number; + getWidth(sourceFile?: SourceFile): number; + getFullWidth(): number; + getLeadingTriviaWidth(sourceFile?: SourceFile): number; + getFullText(sourceFile?: SourceFile): string; + getText(sourceFile?: SourceFile): string; + getFirstToken(sourceFile?: SourceFile): Node; + getLastToken(sourceFile?: SourceFile): Node; + } + interface Symbol { + getFlags(): SymbolFlags; + getName(): string; + getDeclarations(): Declaration[]; + getDocumentationComment(): SymbolDisplayPart[]; + } + interface Type { + getFlags(): TypeFlags; + getSymbol(): Symbol; + getProperties(): Symbol[]; + getProperty(propertyName: string): Symbol; + getApparentProperties(): Symbol[]; + getCallSignatures(): Signature[]; + getConstructSignatures(): Signature[]; + getStringIndexType(): Type; + getNumberIndexType(): Type; + getBaseTypes(): ObjectType[]; + } + interface Signature { + getDeclaration(): SignatureDeclaration; + getTypeParameters(): Type[]; + getParameters(): Symbol[]; + getReturnType(): Type; + getDocumentationComment(): SymbolDisplayPart[]; + } + interface SourceFile { + getLineAndCharacterOfPosition(pos: number): LineAndCharacter; + getLineStarts(): number[]; + getPositionOfLineAndCharacter(line: number, character: number): number; + update(newText: string, textChangeRange: TextChangeRange): SourceFile; + } + /** + * Represents an immutable snapshot of a script at a specified time.Once acquired, the + * snapshot is observably immutable. i.e. the same calls with the same parameters will return + * the same values. + */ + interface IScriptSnapshot { + /** Gets a portion of the script snapshot specified by [start, end). */ + getText(start: number, end: number): string; + /** Gets the length of this script snapshot. */ + getLength(): number; + /** + * Gets the TextChangeRange that describe how the text changed between this text and + * an older version. This information is used by the incremental parser to determine + * what sections of the script need to be re-parsed. 'undefined' can be returned if the + * change range cannot be determined. However, in that case, incremental parsing will + * not happen and the entire document will be re - parsed. + */ + getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange; + /** Releases all resources held by this script snapshot */ + dispose?(): void; + } + module ScriptSnapshot { + function fromString(text: string): IScriptSnapshot; + } + interface PreProcessedFileInfo { + referencedFiles: FileReference[]; + importedFiles: FileReference[]; + ambientExternalModules: string[]; + isLibFile: boolean; + } + interface HostCancellationToken { + isCancellationRequested(): boolean; + } + interface LanguageServiceHost { + getCompilationSettings(): CompilerOptions; + getNewLine?(): string; + getProjectVersion?(): string; + getScriptFileNames(): string[]; + getScriptVersion(fileName: string): string; + getScriptSnapshot(fileName: string): IScriptSnapshot; + getLocalizedDiagnosticMessages?(): any; + getCancellationToken?(): HostCancellationToken; + getCurrentDirectory(): string; + getDefaultLibFileName(options: CompilerOptions): string; + log?(s: string): void; + trace?(s: string): void; + error?(s: string): void; + useCaseSensitiveFileNames?(): boolean; + resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; + } + interface LanguageService { + cleanupSemanticCache(): void; + getSyntacticDiagnostics(fileName: string): Diagnostic[]; + getSemanticDiagnostics(fileName: string): Diagnostic[]; + getCompilerOptionsDiagnostics(): Diagnostic[]; + /** + * @deprecated Use getEncodedSyntacticClassifications instead. + */ + getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; + /** + * @deprecated Use getEncodedSemanticClassifications instead. + */ + getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; + getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; + getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; + getCompletionsAtPosition(fileName: string, position: number): CompletionInfo; + getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails; + getQuickInfoAtPosition(fileName: string, position: number): QuickInfo; + getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan; + getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan; + getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems; + getRenameInfo(fileName: string, position: number): RenameInfo; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[]; + getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; + getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; + getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[]; + findReferences(fileName: string, position: number): ReferencedSymbol[]; + getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; + /** @deprecated */ + getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; + getNavigateToItems(searchValue: string, maxResultCount?: number): NavigateToItem[]; + getNavigationBarItems(fileName: string): NavigationBarItem[]; + getOutliningSpans(fileName: string): OutliningSpan[]; + getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; + getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; + getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number; + getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[]; + getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[]; + getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[]; + getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; + getEmitOutput(fileName: string): EmitOutput; + getProgram(): Program; + getSourceFile(fileName: string): SourceFile; + dispose(): void; + } + interface Classifications { + spans: number[]; + endOfLineState: EndOfLineState; + } + interface ClassifiedSpan { + textSpan: TextSpan; + classificationType: string; + } + interface NavigationBarItem { + text: string; + kind: string; + kindModifiers: string; + spans: TextSpan[]; + childItems: NavigationBarItem[]; + indent: number; + bolded: boolean; + grayed: boolean; + } + interface TodoCommentDescriptor { + text: string; + priority: number; + } + interface TodoComment { + descriptor: TodoCommentDescriptor; + message: string; + position: number; + } + class TextChange { + span: TextSpan; + newText: string; + } + interface TextInsertion { + newText: string; + /** The position in newText the caret should point to after the insertion. */ + caretOffset: number; + } + interface RenameLocation { + textSpan: TextSpan; + fileName: string; + } + interface ReferenceEntry { + textSpan: TextSpan; + fileName: string; + isWriteAccess: boolean; + } + interface DocumentHighlights { + fileName: string; + highlightSpans: HighlightSpan[]; + } + module HighlightSpanKind { + const none: string; + const definition: string; + const reference: string; + const writtenReference: string; + } + interface HighlightSpan { + fileName?: string; + textSpan: TextSpan; + kind: string; + } + interface NavigateToItem { + name: string; + kind: string; + kindModifiers: string; + matchKind: string; + isCaseSensitive: boolean; + fileName: string; + textSpan: TextSpan; + containerName: string; + containerKind: string; + } + interface EditorOptions { + IndentSize: number; + TabSize: number; + NewLineCharacter: string; + ConvertTabsToSpaces: boolean; + } + interface FormatCodeOptions extends EditorOptions { + InsertSpaceAfterCommaDelimiter: boolean; + InsertSpaceAfterSemicolonInForStatements: boolean; + InsertSpaceBeforeAndAfterBinaryOperators: boolean; + InsertSpaceAfterKeywordsInControlFlowStatements: boolean; + InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; + InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; + InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; + PlaceOpenBraceOnNewLineForFunctions: boolean; + PlaceOpenBraceOnNewLineForControlBlocks: boolean; + [s: string]: boolean | number | string; + } + interface DefinitionInfo { + fileName: string; + textSpan: TextSpan; + kind: string; + name: string; + containerKind: string; + containerName: string; + } + interface ReferencedSymbol { + definition: DefinitionInfo; + references: ReferenceEntry[]; + } + enum SymbolDisplayPartKind { + aliasName = 0, + className = 1, + enumName = 2, + fieldName = 3, + interfaceName = 4, + keyword = 5, + lineBreak = 6, + numericLiteral = 7, + stringLiteral = 8, + localName = 9, + methodName = 10, + moduleName = 11, + operator = 12, + parameterName = 13, + propertyName = 14, + punctuation = 15, + space = 16, + text = 17, + typeParameterName = 18, + enumMemberName = 19, + functionName = 20, + regularExpressionLiteral = 21, + } + interface SymbolDisplayPart { + text: string; + kind: string; + } + interface QuickInfo { + kind: string; + kindModifiers: string; + textSpan: TextSpan; + displayParts: SymbolDisplayPart[]; + documentation: SymbolDisplayPart[]; + } + interface RenameInfo { + canRename: boolean; + localizedErrorMessage: string; + displayName: string; + fullDisplayName: string; + kind: string; + kindModifiers: string; + triggerSpan: TextSpan; + } + interface SignatureHelpParameter { + name: string; + documentation: SymbolDisplayPart[]; + displayParts: SymbolDisplayPart[]; + isOptional: boolean; + } + /** + * Represents a single signature to show in signature help. + * The id is used for subsequent calls into the language service to ask questions about the + * signature help item in the context of any documents that have been updated. i.e. after + * an edit has happened, while signature help is still active, the host can ask important + * questions like 'what parameter is the user currently contained within?'. + */ + interface SignatureHelpItem { + isVariadic: boolean; + prefixDisplayParts: SymbolDisplayPart[]; + suffixDisplayParts: SymbolDisplayPart[]; + separatorDisplayParts: SymbolDisplayPart[]; + parameters: SignatureHelpParameter[]; + documentation: SymbolDisplayPart[]; + } + /** + * Represents a set of signature help items, and the preferred item that should be selected. + */ + interface SignatureHelpItems { + items: SignatureHelpItem[]; + applicableSpan: TextSpan; + selectedItemIndex: number; + argumentIndex: number; + argumentCount: number; + } + interface CompletionInfo { + isMemberCompletion: boolean; + isNewIdentifierLocation: boolean; + entries: CompletionEntry[]; + } + interface CompletionEntry { + name: string; + kind: string; + kindModifiers: string; + sortText: string; + } + interface CompletionEntryDetails { + name: string; + kind: string; + kindModifiers: string; + displayParts: SymbolDisplayPart[]; + documentation: SymbolDisplayPart[]; + } + interface OutliningSpan { + /** The span of the document to actually collapse. */ + textSpan: TextSpan; + /** The span of the document to display when the user hovers over the collapsed span. */ + hintSpan: TextSpan; + /** The text to display in the editor for the collapsed region. */ + bannerText: string; + /** + * Whether or not this region should be automatically collapsed when + * the 'Collapse to Definitions' command is invoked. + */ + autoCollapse: boolean; + } + interface EmitOutput { + outputFiles: OutputFile[]; + emitSkipped: boolean; + } + const enum OutputFileType { + JavaScript = 0, + SourceMap = 1, + Declaration = 2, + } + interface OutputFile { + name: string; + writeByteOrderMark: boolean; + text: string; + } + const enum EndOfLineState { + None = 0, + InMultiLineCommentTrivia = 1, + InSingleQuoteStringLiteral = 2, + InDoubleQuoteStringLiteral = 3, + InTemplateHeadOrNoSubstitutionTemplate = 4, + InTemplateMiddleOrTail = 5, + InTemplateSubstitutionPosition = 6, + } + enum TokenClass { + Punctuation = 0, + Keyword = 1, + Operator = 2, + Comment = 3, + Whitespace = 4, + Identifier = 5, + NumberLiteral = 6, + StringLiteral = 7, + RegExpLiteral = 8, + } + interface ClassificationResult { + finalLexState: EndOfLineState; + entries: ClassificationInfo[]; + } + interface ClassificationInfo { + length: number; + classification: TokenClass; + } + interface Classifier { + /** + * Gives lexical classifications of tokens on a line without any syntactic context. + * For instance, a token consisting of the text 'string' can be either an identifier + * named 'string' or the keyword 'string', however, because this classifier is not aware, + * it relies on certain heuristics to give acceptable results. For classifications where + * speed trumps accuracy, this function is preferable; however, for true accuracy, the + * syntactic classifier is ideal. In fact, in certain editing scenarios, combining the + * lexical, syntactic, and semantic classifiers may issue the best user experience. + * + * @param text The text of a line to classify. + * @param lexState The state of the lexical classifier at the end of the previous line. + * @param syntacticClassifierAbsent Whether the client is *not* using a syntactic classifier. + * If there is no syntactic classifier (syntacticClassifierAbsent=true), + * certain heuristics may be used in its place; however, if there is a + * syntactic classifier (syntacticClassifierAbsent=false), certain + * classifications which may be incorrectly categorized will be given + * back as Identifiers in order to allow the syntactic classifier to + * subsume the classification. + * @deprecated Use getLexicalClassifications instead. + */ + getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult; + getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; + } + /** + * The document registry represents a store of SourceFile objects that can be shared between + * multiple LanguageService instances. A LanguageService instance holds on the SourceFile (AST) + * of files in the context. + * SourceFile objects account for most of the memory usage by the language service. Sharing + * the same DocumentRegistry instance between different instances of LanguageService allow + * for more efficient memory utilization since all projects will share at least the library + * file (lib.d.ts). + * + * A more advanced use of the document registry is to serialize sourceFile objects to disk + * and re-hydrate them when needed. + * + * To create a default DocumentRegistry, use createDocumentRegistry to create one, and pass it + * to all subsequent createLanguageService calls. + */ + interface DocumentRegistry { + /** + * Request a stored SourceFile with a given fileName and compilationSettings. + * The first call to acquire will call createLanguageServiceSourceFile to generate + * the SourceFile if was not found in the registry. + * + * @param fileName The name of the file requested + * @param compilationSettings Some compilation settings like target affects the + * shape of a the resulting SourceFile. This allows the DocumentRegistry to store + * multiple copies of the same file for different compilation settings. + * @parm scriptSnapshot Text of the file. Only used if the file was not found + * in the registry and a new one was created. + * @parm version Current version of the file. Only used if the file was not found + * in the registry and a new one was created. + */ + acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile; + /** + * Request an updated version of an already existing SourceFile with a given fileName + * and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile + * to get an updated SourceFile. + * + * @param fileName The name of the file requested + * @param compilationSettings Some compilation settings like target affects the + * shape of a the resulting SourceFile. This allows the DocumentRegistry to store + * multiple copies of the same file for different compilation settings. + * @param scriptSnapshot Text of the file. + * @param version Current version of the file. + */ + updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile; + /** + * Informs the DocumentRegistry that a file is not needed any longer. + * + * Note: It is not allowed to call release on a SourceFile that was not acquired from + * this registry originally. + * + * @param fileName The name of the file to be released + * @param compilationSettings The compilation settings used to acquire the file + */ + releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; + reportStats(): string; + } + module ScriptElementKind { + const unknown: string; + const warning: string; + const keyword: string; + const scriptElement: string; + const moduleElement: string; + const classElement: string; + const localClassElement: string; + const interfaceElement: string; + const typeElement: string; + const enumElement: string; + const variableElement: string; + const localVariableElement: string; + const functionElement: string; + const localFunctionElement: string; + const memberFunctionElement: string; + const memberGetAccessorElement: string; + const memberSetAccessorElement: string; + const memberVariableElement: string; + const constructorImplementationElement: string; + const callSignatureElement: string; + const indexSignatureElement: string; + const constructSignatureElement: string; + const parameterElement: string; + const typeParameterElement: string; + const primitiveType: string; + const label: string; + const alias: string; + const constElement: string; + const letElement: string; + } + module ScriptElementKindModifier { + const none: string; + const publicMemberModifier: string; + const privateMemberModifier: string; + const protectedMemberModifier: string; + const exportedModifier: string; + const ambientModifier: string; + const staticModifier: string; + const abstractModifier: string; + } + class ClassificationTypeNames { + static comment: string; + static identifier: string; + static keyword: string; + static numericLiteral: string; + static operator: string; + static stringLiteral: string; + static whiteSpace: string; + static text: string; + static punctuation: string; + static className: string; + static enumName: string; + static interfaceName: string; + static moduleName: string; + static typeParameterName: string; + static typeAliasName: string; + static parameterName: string; + static docCommentTagName: string; + } + const enum ClassificationType { + comment = 1, + identifier = 2, + keyword = 3, + numericLiteral = 4, + operator = 5, + stringLiteral = 6, + regularExpressionLiteral = 7, + whiteSpace = 8, + text = 9, + punctuation = 10, + className = 11, + enumName = 12, + interfaceName = 13, + moduleName = 14, + typeParameterName = 15, + typeAliasName = 16, + parameterName = 17, + docCommentTagName = 18, + } + interface DisplayPartsSymbolWriter extends SymbolWriter { + displayParts(): SymbolDisplayPart[]; + } + function displayPartsToString(displayParts: SymbolDisplayPart[]): string; + function getDefaultCompilerOptions(): CompilerOptions; + interface TranspileOptions { + compilerOptions?: CompilerOptions; + fileName?: string; + reportDiagnostics?: boolean; + moduleName?: string; + renamedDependencies?: Map; + } + interface TranspileOutput { + outputText: string; + diagnostics?: Diagnostic[]; + sourceMapText?: string; + } + function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; + function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; + function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile; + let disableIncrementalParsing: boolean; + function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; + function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string; + function createDocumentRegistry(useCaseSensitiveFileNames?: boolean): DocumentRegistry; + function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo; + function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService; + function createClassifier(): Classifier; + /** + * Get the path of the default library files (lib.d.ts) as distributed with the typescript + * node package. + * The functionality is not supported if the ts module is consumed outside of a node module. + */ + function getDefaultLibFilePath(options: CompilerOptions): string; +} diff --git a/typescript/typescript.d.ts b/typescript/typescript.d.ts index 8078c6de2..59330b5dc 100644 --- a/typescript/typescript.d.ts +++ b/typescript/typescript.d.ts @@ -1,2148 +1,2148 @@ -// Type definitions for TypeScript API v0.4.0 -// Project: http://www.typescriptlang.org/ -// Definitions by: Microsoft TypeScript -// 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. -***************************************************************************** */ - -declare module "typescript" { - interface Map { - [index: string]: T; - } - interface FileMap { - get(fileName: string): T; - set(fileName: string, value: T): void; - contains(fileName: string): boolean; - remove(fileName: string): void; - forEachValue(f: (v: T) => void): void; - clear(): void; - } - interface TextRange { - pos: number; - end: number; - } - const enum SyntaxKind { - Unknown = 0, - EndOfFileToken = 1, - SingleLineCommentTrivia = 2, - MultiLineCommentTrivia = 3, - NewLineTrivia = 4, - WhitespaceTrivia = 5, - ShebangTrivia = 6, - ConflictMarkerTrivia = 7, - NumericLiteral = 8, - StringLiteral = 9, - RegularExpressionLiteral = 10, - NoSubstitutionTemplateLiteral = 11, - TemplateHead = 12, - TemplateMiddle = 13, - TemplateTail = 14, - OpenBraceToken = 15, - CloseBraceToken = 16, - OpenParenToken = 17, - CloseParenToken = 18, - OpenBracketToken = 19, - CloseBracketToken = 20, - DotToken = 21, - DotDotDotToken = 22, - SemicolonToken = 23, - CommaToken = 24, - LessThanToken = 25, - LessThanSlashToken = 26, - GreaterThanToken = 27, - LessThanEqualsToken = 28, - GreaterThanEqualsToken = 29, - EqualsEqualsToken = 30, - ExclamationEqualsToken = 31, - EqualsEqualsEqualsToken = 32, - ExclamationEqualsEqualsToken = 33, - EqualsGreaterThanToken = 34, - PlusToken = 35, - MinusToken = 36, - AsteriskToken = 37, - SlashToken = 38, - PercentToken = 39, - PlusPlusToken = 40, - MinusMinusToken = 41, - LessThanLessThanToken = 42, - GreaterThanGreaterThanToken = 43, - GreaterThanGreaterThanGreaterThanToken = 44, - AmpersandToken = 45, - BarToken = 46, - CaretToken = 47, - ExclamationToken = 48, - TildeToken = 49, - AmpersandAmpersandToken = 50, - BarBarToken = 51, - QuestionToken = 52, - ColonToken = 53, - AtToken = 54, - EqualsToken = 55, - PlusEqualsToken = 56, - MinusEqualsToken = 57, - AsteriskEqualsToken = 58, - SlashEqualsToken = 59, - PercentEqualsToken = 60, - LessThanLessThanEqualsToken = 61, - GreaterThanGreaterThanEqualsToken = 62, - GreaterThanGreaterThanGreaterThanEqualsToken = 63, - AmpersandEqualsToken = 64, - BarEqualsToken = 65, - CaretEqualsToken = 66, - Identifier = 67, - BreakKeyword = 68, - CaseKeyword = 69, - CatchKeyword = 70, - ClassKeyword = 71, - ConstKeyword = 72, - ContinueKeyword = 73, - DebuggerKeyword = 74, - DefaultKeyword = 75, - DeleteKeyword = 76, - DoKeyword = 77, - ElseKeyword = 78, - EnumKeyword = 79, - ExportKeyword = 80, - ExtendsKeyword = 81, - FalseKeyword = 82, - FinallyKeyword = 83, - ForKeyword = 84, - FunctionKeyword = 85, - IfKeyword = 86, - ImportKeyword = 87, - InKeyword = 88, - InstanceOfKeyword = 89, - NewKeyword = 90, - NullKeyword = 91, - ReturnKeyword = 92, - SuperKeyword = 93, - SwitchKeyword = 94, - ThisKeyword = 95, - ThrowKeyword = 96, - TrueKeyword = 97, - TryKeyword = 98, - TypeOfKeyword = 99, - VarKeyword = 100, - VoidKeyword = 101, - WhileKeyword = 102, - WithKeyword = 103, - ImplementsKeyword = 104, - InterfaceKeyword = 105, - LetKeyword = 106, - PackageKeyword = 107, - PrivateKeyword = 108, - ProtectedKeyword = 109, - PublicKeyword = 110, - StaticKeyword = 111, - YieldKeyword = 112, - AbstractKeyword = 113, - AsKeyword = 114, - AnyKeyword = 115, - AsyncKeyword = 116, - AwaitKeyword = 117, - BooleanKeyword = 118, - ConstructorKeyword = 119, - DeclareKeyword = 120, - GetKeyword = 121, - IsKeyword = 122, - ModuleKeyword = 123, - NamespaceKeyword = 124, - RequireKeyword = 125, - NumberKeyword = 126, - SetKeyword = 127, - StringKeyword = 128, - SymbolKeyword = 129, - TypeKeyword = 130, - FromKeyword = 131, - OfKeyword = 132, - QualifiedName = 133, - ComputedPropertyName = 134, - TypeParameter = 135, - Parameter = 136, - Decorator = 137, - PropertySignature = 138, - PropertyDeclaration = 139, - MethodSignature = 140, - MethodDeclaration = 141, - Constructor = 142, - GetAccessor = 143, - SetAccessor = 144, - CallSignature = 145, - ConstructSignature = 146, - IndexSignature = 147, - TypePredicate = 148, - TypeReference = 149, - FunctionType = 150, - ConstructorType = 151, - TypeQuery = 152, - TypeLiteral = 153, - ArrayType = 154, - TupleType = 155, - UnionType = 156, - IntersectionType = 157, - ParenthesizedType = 158, - ObjectBindingPattern = 159, - ArrayBindingPattern = 160, - BindingElement = 161, - ArrayLiteralExpression = 162, - ObjectLiteralExpression = 163, - PropertyAccessExpression = 164, - ElementAccessExpression = 165, - CallExpression = 166, - NewExpression = 167, - TaggedTemplateExpression = 168, - TypeAssertionExpression = 169, - ParenthesizedExpression = 170, - FunctionExpression = 171, - ArrowFunction = 172, - DeleteExpression = 173, - TypeOfExpression = 174, - VoidExpression = 175, - AwaitExpression = 176, - PrefixUnaryExpression = 177, - PostfixUnaryExpression = 178, - BinaryExpression = 179, - ConditionalExpression = 180, - TemplateExpression = 181, - YieldExpression = 182, - SpreadElementExpression = 183, - ClassExpression = 184, - OmittedExpression = 185, - ExpressionWithTypeArguments = 186, - AsExpression = 187, - TemplateSpan = 188, - SemicolonClassElement = 189, - Block = 190, - VariableStatement = 191, - EmptyStatement = 192, - ExpressionStatement = 193, - IfStatement = 194, - DoStatement = 195, - WhileStatement = 196, - ForStatement = 197, - ForInStatement = 198, - ForOfStatement = 199, - ContinueStatement = 200, - BreakStatement = 201, - ReturnStatement = 202, - WithStatement = 203, - SwitchStatement = 204, - LabeledStatement = 205, - ThrowStatement = 206, - TryStatement = 207, - DebuggerStatement = 208, - VariableDeclaration = 209, - VariableDeclarationList = 210, - FunctionDeclaration = 211, - ClassDeclaration = 212, - InterfaceDeclaration = 213, - TypeAliasDeclaration = 214, - EnumDeclaration = 215, - ModuleDeclaration = 216, - ModuleBlock = 217, - CaseBlock = 218, - ImportEqualsDeclaration = 219, - ImportDeclaration = 220, - ImportClause = 221, - NamespaceImport = 222, - NamedImports = 223, - ImportSpecifier = 224, - ExportAssignment = 225, - ExportDeclaration = 226, - NamedExports = 227, - ExportSpecifier = 228, - MissingDeclaration = 229, - ExternalModuleReference = 230, - JsxElement = 231, - JsxSelfClosingElement = 232, - JsxOpeningElement = 233, - JsxText = 234, - JsxClosingElement = 235, - JsxAttribute = 236, - JsxSpreadAttribute = 237, - JsxExpression = 238, - CaseClause = 239, - DefaultClause = 240, - HeritageClause = 241, - CatchClause = 242, - PropertyAssignment = 243, - ShorthandPropertyAssignment = 244, - EnumMember = 245, - SourceFile = 246, - JSDocTypeExpression = 247, - JSDocAllType = 248, - JSDocUnknownType = 249, - JSDocArrayType = 250, - JSDocUnionType = 251, - JSDocTupleType = 252, - JSDocNullableType = 253, - JSDocNonNullableType = 254, - JSDocRecordType = 255, - JSDocRecordMember = 256, - JSDocTypeReference = 257, - JSDocOptionalType = 258, - JSDocFunctionType = 259, - JSDocVariadicType = 260, - JSDocConstructorType = 261, - JSDocThisType = 262, - JSDocComment = 263, - JSDocTag = 264, - JSDocParameterTag = 265, - JSDocReturnTag = 266, - JSDocTypeTag = 267, - JSDocTemplateTag = 268, - SyntaxList = 269, - Count = 270, - FirstAssignment = 55, - LastAssignment = 66, - FirstReservedWord = 68, - LastReservedWord = 103, - FirstKeyword = 68, - LastKeyword = 132, - FirstFutureReservedWord = 104, - LastFutureReservedWord = 112, - FirstTypeNode = 149, - LastTypeNode = 158, - FirstPunctuation = 15, - LastPunctuation = 66, - FirstToken = 0, - LastToken = 132, - FirstTriviaToken = 2, - LastTriviaToken = 7, - FirstLiteralToken = 8, - LastLiteralToken = 11, - FirstTemplateToken = 11, - LastTemplateToken = 14, - FirstBinaryOperator = 25, - LastBinaryOperator = 66, - FirstNode = 133, - } - const enum NodeFlags { - Export = 1, - Ambient = 2, - Public = 16, - Private = 32, - Protected = 64, - Static = 128, - Abstract = 256, - Async = 512, - Default = 1024, - MultiLine = 2048, - Synthetic = 4096, - DeclarationFile = 8192, - Let = 16384, - Const = 32768, - OctalLiteral = 65536, - Namespace = 131072, - ExportContext = 262144, - Modifier = 2035, - AccessibilityModifier = 112, - BlockScoped = 49152, - } - const enum JsxFlags { - None = 0, - IntrinsicNamedElement = 1, - IntrinsicIndexedElement = 2, - ClassElement = 4, - UnknownElement = 8, - IntrinsicElement = 3, - } - interface Node extends TextRange { - kind: SyntaxKind; - flags: NodeFlags; - decorators?: NodeArray; - modifiers?: ModifiersArray; - parent?: Node; - } - interface NodeArray extends Array, TextRange { - hasTrailingComma?: boolean; - } - interface ModifiersArray extends NodeArray { - flags: number; - } - interface Identifier extends PrimaryExpression { - text: string; - originalKeywordKind?: SyntaxKind; - } - interface QualifiedName extends Node { - left: EntityName; - right: Identifier; - } - type EntityName = Identifier | QualifiedName; - type DeclarationName = Identifier | LiteralExpression | ComputedPropertyName | BindingPattern; - interface Declaration extends Node { - _declarationBrand: any; - name?: DeclarationName; - } - interface ComputedPropertyName extends Node { - expression: Expression; - } - interface Decorator extends Node { - expression: LeftHandSideExpression; - } - interface TypeParameterDeclaration extends Declaration { - name: Identifier; - constraint?: TypeNode; - expression?: Expression; - } - interface SignatureDeclaration extends Declaration { - typeParameters?: NodeArray; - parameters: NodeArray; - type?: TypeNode; - } - interface VariableDeclaration extends Declaration { - parent?: VariableDeclarationList; - name: Identifier | BindingPattern; - type?: TypeNode; - initializer?: Expression; - } - interface VariableDeclarationList extends Node { - declarations: NodeArray; - } - interface ParameterDeclaration extends Declaration { - dotDotDotToken?: Node; - name: Identifier | BindingPattern; - questionToken?: Node; - type?: TypeNode; - initializer?: Expression; - } - interface BindingElement extends Declaration { - propertyName?: Identifier; - dotDotDotToken?: Node; - name: Identifier | BindingPattern; - initializer?: Expression; - } - interface PropertyDeclaration extends Declaration, ClassElement { - name: DeclarationName; - questionToken?: Node; - type?: TypeNode; - initializer?: Expression; - } - interface ObjectLiteralElement extends Declaration { - _objectLiteralBrandBrand: any; - } - interface PropertyAssignment extends ObjectLiteralElement { - _propertyAssignmentBrand: any; - name: DeclarationName; - questionToken?: Node; - initializer: Expression; - } - interface ShorthandPropertyAssignment extends ObjectLiteralElement { - name: Identifier; - questionToken?: Node; - } - interface VariableLikeDeclaration extends Declaration { - propertyName?: Identifier; - dotDotDotToken?: Node; - name: DeclarationName; - questionToken?: Node; - type?: TypeNode; - initializer?: Expression; - } - interface BindingPattern extends Node { - elements: NodeArray; - } - /** - * Several node kinds share function-like features such as a signature, - * a name, and a body. These nodes should extend FunctionLikeDeclaration. - * Examples: - * - FunctionDeclaration - * - MethodDeclaration - * - AccessorDeclaration - */ - interface FunctionLikeDeclaration extends SignatureDeclaration { - _functionLikeDeclarationBrand: any; - asteriskToken?: Node; - questionToken?: Node; - body?: Block | Expression; - } - interface FunctionDeclaration extends FunctionLikeDeclaration, Statement { - name?: Identifier; - body?: Block; - } - interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { - body?: Block; - } - interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { - body?: Block; - } - interface SemicolonClassElement extends ClassElement { - _semicolonClassElementBrand: any; - } - interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { - _accessorDeclarationBrand: any; - body: Block; - } - interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement { - _indexSignatureDeclarationBrand: any; - } - interface TypeNode extends Node { - _typeNodeBrand: any; - } - interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration { - _functionOrConstructorTypeNodeBrand: any; - } - interface TypeReferenceNode extends TypeNode { - typeName: EntityName; - typeArguments?: NodeArray; - } - interface TypePredicateNode extends TypeNode { - parameterName: Identifier; - type: TypeNode; - } - interface TypeQueryNode extends TypeNode { - exprName: EntityName; - } - interface TypeLiteralNode extends TypeNode, Declaration { - members: NodeArray; - } - interface ArrayTypeNode extends TypeNode { - elementType: TypeNode; - } - interface TupleTypeNode extends TypeNode { - elementTypes: NodeArray; - } - interface UnionOrIntersectionTypeNode extends TypeNode { - types: NodeArray; - } - interface UnionTypeNode extends UnionOrIntersectionTypeNode { - } - interface IntersectionTypeNode extends UnionOrIntersectionTypeNode { - } - interface ParenthesizedTypeNode extends TypeNode { - type: TypeNode; - } - interface StringLiteral extends LiteralExpression, TypeNode { - _stringLiteralBrand: any; - } - interface Expression extends Node { - _expressionBrand: any; - contextualType?: Type; - } - interface UnaryExpression extends Expression { - _unaryExpressionBrand: any; - } - interface PrefixUnaryExpression extends UnaryExpression { - operator: SyntaxKind; - operand: UnaryExpression; - } - interface PostfixUnaryExpression extends PostfixExpression { - operand: LeftHandSideExpression; - operator: SyntaxKind; - } - interface PostfixExpression extends UnaryExpression { - _postfixExpressionBrand: any; - } - interface LeftHandSideExpression extends PostfixExpression { - _leftHandSideExpressionBrand: any; - } - interface MemberExpression extends LeftHandSideExpression { - _memberExpressionBrand: any; - } - interface PrimaryExpression extends MemberExpression { - _primaryExpressionBrand: any; - } - interface DeleteExpression extends UnaryExpression { - expression: UnaryExpression; - } - interface TypeOfExpression extends UnaryExpression { - expression: UnaryExpression; - } - interface VoidExpression extends UnaryExpression { - expression: UnaryExpression; - } - interface AwaitExpression extends UnaryExpression { - expression: UnaryExpression; - } - interface YieldExpression extends Expression { - asteriskToken?: Node; - expression?: Expression; - } - interface BinaryExpression extends Expression { - left: Expression; - operatorToken: Node; - right: Expression; - } - interface ConditionalExpression extends Expression { - condition: Expression; - questionToken: Node; - whenTrue: Expression; - colonToken: Node; - whenFalse: Expression; - } - interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { - name?: Identifier; - body: Block | Expression; - } - interface ArrowFunction extends Expression, FunctionLikeDeclaration { - equalsGreaterThanToken: Node; - } - interface LiteralExpression extends PrimaryExpression { - text: string; - isUnterminated?: boolean; - hasExtendedUnicodeEscape?: boolean; - } - interface TemplateExpression extends PrimaryExpression { - head: LiteralExpression; - templateSpans: NodeArray; - } - interface TemplateSpan extends Node { - expression: Expression; - literal: LiteralExpression; - } - interface ParenthesizedExpression extends PrimaryExpression { - expression: Expression; - } - interface ArrayLiteralExpression extends PrimaryExpression { - elements: NodeArray; - } - interface SpreadElementExpression extends Expression { - expression: Expression; - } - interface ObjectLiteralExpression extends PrimaryExpression, Declaration { - properties: NodeArray; - } - interface PropertyAccessExpression extends MemberExpression { - expression: LeftHandSideExpression; - dotToken: Node; - name: Identifier; - } - interface ElementAccessExpression extends MemberExpression { - expression: LeftHandSideExpression; - argumentExpression?: Expression; - } - interface CallExpression extends LeftHandSideExpression { - expression: LeftHandSideExpression; - typeArguments?: NodeArray; - arguments: NodeArray; - } - interface ExpressionWithTypeArguments extends TypeNode { - expression: LeftHandSideExpression; - typeArguments?: NodeArray; - } - interface NewExpression extends CallExpression, PrimaryExpression { - } - interface TaggedTemplateExpression extends MemberExpression { - tag: LeftHandSideExpression; - template: LiteralExpression | TemplateExpression; - } - type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; - interface AsExpression extends Expression { - expression: Expression; - type: TypeNode; - } - interface TypeAssertion extends UnaryExpression { - type: TypeNode; - expression: UnaryExpression; - } - type AssertionExpression = TypeAssertion | AsExpression; - interface JsxElement extends PrimaryExpression { - openingElement: JsxOpeningElement; - children: NodeArray; - closingElement: JsxClosingElement; - } - interface JsxOpeningElement extends Expression { - _openingElementBrand?: any; - tagName: EntityName; - attributes: NodeArray; - } - interface JsxSelfClosingElement extends PrimaryExpression, JsxOpeningElement { - _selfClosingElementBrand?: any; - } - type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; - interface JsxAttribute extends Node { - name: Identifier; - initializer?: Expression; - } - interface JsxSpreadAttribute extends Node { - expression: Expression; - } - interface JsxClosingElement extends Node { - tagName: EntityName; - } - interface JsxExpression extends Expression { - expression?: Expression; - } - interface JsxText extends Node { - _jsxTextExpressionBrand: any; - } - type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement; - interface Statement extends Node { - _statementBrand: any; - } - interface Block extends Statement { - statements: NodeArray; - } - interface VariableStatement extends Statement { - declarationList: VariableDeclarationList; - } - interface ExpressionStatement extends Statement { - expression: Expression; - } - interface IfStatement extends Statement { - expression: Expression; - thenStatement: Statement; - elseStatement?: Statement; - } - interface IterationStatement extends Statement { - statement: Statement; - } - interface DoStatement extends IterationStatement { - expression: Expression; - } - interface WhileStatement extends IterationStatement { - expression: Expression; - } - interface ForStatement extends IterationStatement { - initializer?: VariableDeclarationList | Expression; - condition?: Expression; - incrementor?: Expression; - } - interface ForInStatement extends IterationStatement { - initializer: VariableDeclarationList | Expression; - expression: Expression; - } - interface ForOfStatement extends IterationStatement { - initializer: VariableDeclarationList | Expression; - expression: Expression; - } - interface BreakOrContinueStatement extends Statement { - label?: Identifier; - } - interface ReturnStatement extends Statement { - expression?: Expression; - } - interface WithStatement extends Statement { - expression: Expression; - statement: Statement; - } - interface SwitchStatement extends Statement { - expression: Expression; - caseBlock: CaseBlock; - } - interface CaseBlock extends Node { - clauses: NodeArray; - } - interface CaseClause extends Node { - expression?: Expression; - statements: NodeArray; - } - interface DefaultClause extends Node { - statements: NodeArray; - } - type CaseOrDefaultClause = CaseClause | DefaultClause; - interface LabeledStatement extends Statement { - label: Identifier; - statement: Statement; - } - interface ThrowStatement extends Statement { - expression: Expression; - } - interface TryStatement extends Statement { - tryBlock: Block; - catchClause?: CatchClause; - finallyBlock?: Block; - } - interface CatchClause extends Node { - variableDeclaration: VariableDeclaration; - block: Block; - } - interface ClassLikeDeclaration extends Declaration { - name?: Identifier; - typeParameters?: NodeArray; - heritageClauses?: NodeArray; - members: NodeArray; - } - interface ClassDeclaration extends ClassLikeDeclaration, Statement { - } - interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { - } - interface ClassElement extends Declaration { - _classElementBrand: any; - } - interface InterfaceDeclaration extends Declaration, Statement { - name: Identifier; - typeParameters?: NodeArray; - heritageClauses?: NodeArray; - members: NodeArray; - } - interface HeritageClause extends Node { - token: SyntaxKind; - types?: NodeArray; - } - interface TypeAliasDeclaration extends Declaration, Statement { - name: Identifier; - typeParameters?: NodeArray; - type: TypeNode; - } - interface EnumMember extends Declaration { - name: DeclarationName; - initializer?: Expression; - } - interface EnumDeclaration extends Declaration, Statement { - name: Identifier; - members: NodeArray; - } - interface ModuleDeclaration extends Declaration, Statement { - name: Identifier | LiteralExpression; - body: ModuleBlock | ModuleDeclaration; - } - interface ModuleBlock extends Node, Statement { - statements: NodeArray; - } - interface ImportEqualsDeclaration extends Declaration, Statement { - name: Identifier; - moduleReference: EntityName | ExternalModuleReference; - } - interface ExternalModuleReference extends Node { - expression?: Expression; - } - interface ImportDeclaration extends Statement { - importClause?: ImportClause; - moduleSpecifier: Expression; - } - interface ImportClause extends Declaration { - name?: Identifier; - namedBindings?: NamespaceImport | NamedImports; - } - interface NamespaceImport extends Declaration { - name: Identifier; - } - interface ExportDeclaration extends Declaration, Statement { - exportClause?: NamedExports; - moduleSpecifier?: Expression; - } - interface NamedImportsOrExports extends Node { - elements: NodeArray; - } - type NamedImports = NamedImportsOrExports; - type NamedExports = NamedImportsOrExports; - interface ImportOrExportSpecifier extends Declaration { - propertyName?: Identifier; - name: Identifier; - } - type ImportSpecifier = ImportOrExportSpecifier; - type ExportSpecifier = ImportOrExportSpecifier; - interface ExportAssignment extends Declaration, Statement { - isExportEquals?: boolean; - expression: Expression; - } - interface FileReference extends TextRange { - fileName: string; - } - interface CommentRange extends TextRange { - hasTrailingNewLine?: boolean; - kind: SyntaxKind; - } - interface JSDocTypeExpression extends Node { - type: JSDocType; - } - interface JSDocType extends TypeNode { - _jsDocTypeBrand: any; - } - interface JSDocAllType extends JSDocType { - _JSDocAllTypeBrand: any; - } - interface JSDocUnknownType extends JSDocType { - _JSDocUnknownTypeBrand: any; - } - interface JSDocArrayType extends JSDocType { - elementType: JSDocType; - } - interface JSDocUnionType extends JSDocType { - types: NodeArray; - } - interface JSDocTupleType extends JSDocType { - types: NodeArray; - } - interface JSDocNonNullableType extends JSDocType { - type: JSDocType; - } - interface JSDocNullableType extends JSDocType { - type: JSDocType; - } - interface JSDocRecordType extends JSDocType, TypeLiteralNode { - members: NodeArray; - } - interface JSDocTypeReference extends JSDocType { - name: EntityName; - typeArguments: NodeArray; - } - interface JSDocOptionalType extends JSDocType { - type: JSDocType; - } - interface JSDocFunctionType extends JSDocType, SignatureDeclaration { - parameters: NodeArray; - type: JSDocType; - } - interface JSDocVariadicType extends JSDocType { - type: JSDocType; - } - interface JSDocConstructorType extends JSDocType { - type: JSDocType; - } - interface JSDocThisType extends JSDocType { - type: JSDocType; - } - interface JSDocRecordMember extends PropertyDeclaration { - name: Identifier | LiteralExpression; - type?: JSDocType; - } - interface JSDocComment extends Node { - tags: NodeArray; - } - interface JSDocTag extends Node { - atToken: Node; - tagName: Identifier; - } - interface JSDocTemplateTag extends JSDocTag { - typeParameters: NodeArray; - } - interface JSDocReturnTag extends JSDocTag { - typeExpression: JSDocTypeExpression; - } - interface JSDocTypeTag extends JSDocTag { - typeExpression: JSDocTypeExpression; - } - interface JSDocParameterTag extends JSDocTag { - preParameterName?: Identifier; - typeExpression?: JSDocTypeExpression; - postParameterName?: Identifier; - isBracketed: boolean; - } - interface SourceFile extends Declaration { - statements: NodeArray; - endOfFileToken: Node; - fileName: string; - text: string; - amdDependencies: { - path: string; - name: string; - }[]; - moduleName: string; - referencedFiles: FileReference[]; - languageVariant: LanguageVariant; - /** - * lib.d.ts should have a reference comment like - * - * /// - * - * If any other file has this comment, it signals not to include lib.d.ts - * because this containing file is intended to act as a default library. - */ - hasNoDefaultLib: boolean; - languageVersion: ScriptTarget; - } - interface ScriptReferenceHost { - getCompilerOptions(): CompilerOptions; - getSourceFile(fileName: string): SourceFile; - getCurrentDirectory(): string; - } - interface ParseConfigHost extends ModuleResolutionHost { - readDirectory(rootDir: string, extension: string, exclude: string[]): string[]; - } - interface WriteFileCallback { - (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void; - } - class OperationCanceledException { - } - interface CancellationToken { - isCancellationRequested(): boolean; - /** @throws OperationCanceledException if isCancellationRequested is true */ - throwIfCancellationRequested(): void; - } - interface Program extends ScriptReferenceHost { - /** - * Get a list of root file names that were passed to a 'createProgram' - */ - getRootFileNames(): string[]; - /** - * Get a list of files in the program - */ - getSourceFiles(): SourceFile[]; - /** - * Emits the JavaScript and declaration files. If targetSourceFile is not specified, then - * the JavaScript and declaration files will be produced for all the files in this program. - * If targetSourceFile is specified, then only the JavaScript and declaration for that - * specific file will be generated. - * - * If writeFile is not specified then the writeFile callback from the compiler host will be - * used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter - * will be invoked when writing the JavaScript and declaration files. - */ - emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult; - getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; - getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; - getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - /** - * Gets a type checker that can be used to semantically analyze source fils in the program. - */ - getTypeChecker(): TypeChecker; - } - interface SourceMapSpan { - /** Line number in the .js file. */ - emittedLine: number; - /** Column number in the .js file. */ - emittedColumn: number; - /** Line number in the .ts file. */ - sourceLine: number; - /** Column number in the .ts file. */ - sourceColumn: number; - /** Optional name (index into names array) associated with this span. */ - nameIndex?: number; - /** .ts file (index into sources array) associated with this span */ - sourceIndex: number; - } - interface SourceMapData { - sourceMapFilePath: string; - jsSourceMappingURL: string; - sourceMapFile: string; - sourceMapSourceRoot: string; - sourceMapSources: string[]; - sourceMapSourcesContent?: string[]; - inputSourceFileNames: string[]; - sourceMapNames?: string[]; - sourceMapMappings: string; - sourceMapDecodedMappings: SourceMapSpan[]; - } - /** Return code used by getEmitOutput function to indicate status of the function */ - enum ExitStatus { - Success = 0, - DiagnosticsPresent_OutputsSkipped = 1, - DiagnosticsPresent_OutputsGenerated = 2, - } - interface EmitResult { - emitSkipped: boolean; - diagnostics: Diagnostic[]; - } - interface TypeChecker { - getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type; - getDeclaredTypeOfSymbol(symbol: Symbol): Type; - getPropertiesOfType(type: Type): Symbol[]; - getPropertyOfType(type: Type, propertyName: string): Symbol; - getSignaturesOfType(type: Type, kind: SignatureKind): Signature[]; - getIndexTypeOfType(type: Type, kind: IndexKind): Type; - getBaseTypes(type: InterfaceType): ObjectType[]; - getReturnTypeOfSignature(signature: Signature): Type; - getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; - getSymbolAtLocation(node: Node): Symbol; - getShorthandAssignmentValueSymbol(location: Node): Symbol; - getTypeAtLocation(node: Node): Type; - typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; - symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string; - getSymbolDisplayBuilder(): SymbolDisplayBuilder; - getFullyQualifiedName(symbol: Symbol): string; - getAugmentedPropertiesOfType(type: Type): Symbol[]; - getRootSymbols(symbol: Symbol): Symbol[]; - getContextualType(node: Expression): Type; - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature; - getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature; - isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; - isUndefinedSymbol(symbol: Symbol): boolean; - isArgumentsSymbol(symbol: Symbol): boolean; - getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; - isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; - getAliasedSymbol(symbol: Symbol): Symbol; - getExportsOfModule(moduleSymbol: Symbol): Symbol[]; - getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type; - getJsxIntrinsicTagNames(): Symbol[]; - isOptionalParameter(node: ParameterDeclaration): boolean; - } - interface SymbolDisplayBuilder { - buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags): void; - buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - } - interface SymbolWriter { - writeKeyword(text: string): void; - writeOperator(text: string): void; - writePunctuation(text: string): void; - writeSpace(text: string): void; - writeStringLiteral(text: string): void; - writeParameter(text: string): void; - writeSymbol(text: string, symbol: Symbol): void; - writeLine(): void; - increaseIndent(): void; - decreaseIndent(): void; - clear(): void; - trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; - } - const enum TypeFormatFlags { - None = 0, - WriteArrayAsGenericType = 1, - UseTypeOfFunction = 2, - NoTruncation = 4, - WriteArrowStyleSignature = 8, - WriteOwnNameForAnyLike = 16, - WriteTypeArgumentsOfSignature = 32, - InElementType = 64, - UseFullyQualifiedType = 128, - } - const enum SymbolFormatFlags { - None = 0, - WriteTypeParametersOrArguments = 1, - UseOnlyExternalAliasing = 2, - } - interface TypePredicate { - parameterName: string; - parameterIndex: number; - type: Type; - } - const enum SymbolFlags { - None = 0, - FunctionScopedVariable = 1, - BlockScopedVariable = 2, - Property = 4, - EnumMember = 8, - Function = 16, - Class = 32, - Interface = 64, - ConstEnum = 128, - RegularEnum = 256, - ValueModule = 512, - NamespaceModule = 1024, - TypeLiteral = 2048, - ObjectLiteral = 4096, - Method = 8192, - Constructor = 16384, - GetAccessor = 32768, - SetAccessor = 65536, - Signature = 131072, - TypeParameter = 262144, - TypeAlias = 524288, - ExportValue = 1048576, - ExportType = 2097152, - ExportNamespace = 4194304, - Alias = 8388608, - Instantiated = 16777216, - Merged = 33554432, - Transient = 67108864, - Prototype = 134217728, - SyntheticProperty = 268435456, - Optional = 536870912, - ExportStar = 1073741824, - Enum = 384, - Variable = 3, - Value = 107455, - Type = 793056, - Namespace = 1536, - Module = 1536, - Accessor = 98304, - FunctionScopedVariableExcludes = 107454, - BlockScopedVariableExcludes = 107455, - ParameterExcludes = 107455, - PropertyExcludes = 107455, - EnumMemberExcludes = 107455, - FunctionExcludes = 106927, - ClassExcludes = 899519, - InterfaceExcludes = 792960, - RegularEnumExcludes = 899327, - ConstEnumExcludes = 899967, - ValueModuleExcludes = 106639, - NamespaceModuleExcludes = 0, - MethodExcludes = 99263, - GetAccessorExcludes = 41919, - SetAccessorExcludes = 74687, - TypeParameterExcludes = 530912, - TypeAliasExcludes = 793056, - AliasExcludes = 8388608, - ModuleMember = 8914931, - ExportHasLocal = 944, - HasExports = 1952, - HasMembers = 6240, - BlockScoped = 418, - PropertyOrAccessor = 98308, - Export = 7340032, - } - interface Symbol { - flags: SymbolFlags; - name: string; - declarations?: Declaration[]; - valueDeclaration?: Declaration; - members?: SymbolTable; - exports?: SymbolTable; - } - interface SymbolTable { - [index: string]: Symbol; - } - const enum TypeFlags { - Any = 1, - String = 2, - Number = 4, - Boolean = 8, - Void = 16, - Undefined = 32, - Null = 64, - Enum = 128, - StringLiteral = 256, - TypeParameter = 512, - Class = 1024, - Interface = 2048, - Reference = 4096, - Tuple = 8192, - Union = 16384, - Intersection = 32768, - Anonymous = 65536, - Instantiated = 131072, - ObjectLiteral = 524288, - ESSymbol = 16777216, - StringLike = 258, - NumberLike = 132, - ObjectType = 80896, - UnionOrIntersection = 49152, - StructuredType = 130048, - } - interface Type { - flags: TypeFlags; - symbol?: Symbol; - } - interface StringLiteralType extends Type { - text: string; - } - interface ObjectType extends Type { - } - interface InterfaceType extends ObjectType { - typeParameters: TypeParameter[]; - outerTypeParameters: TypeParameter[]; - localTypeParameters: TypeParameter[]; - } - interface InterfaceTypeWithDeclaredMembers extends InterfaceType { - declaredProperties: Symbol[]; - declaredCallSignatures: Signature[]; - declaredConstructSignatures: Signature[]; - declaredStringIndexType: Type; - declaredNumberIndexType: Type; - } - interface TypeReference extends ObjectType { - target: GenericType; - typeArguments: Type[]; - } - interface GenericType extends InterfaceType, TypeReference { - } - interface TupleType extends ObjectType { - elementTypes: Type[]; - baseArrayType: TypeReference; - } - interface UnionOrIntersectionType extends Type { - types: Type[]; - } - interface UnionType extends UnionOrIntersectionType { - } - interface IntersectionType extends UnionOrIntersectionType { - } - interface TypeParameter extends Type { - constraint: Type; - } - const enum SignatureKind { - Call = 0, - Construct = 1, - } - interface Signature { - declaration: SignatureDeclaration; - typeParameters: TypeParameter[]; - parameters: Symbol[]; - typePredicate?: TypePredicate; - } - const enum IndexKind { - String = 0, - Number = 1, - } - interface DiagnosticMessage { - key: string; - category: DiagnosticCategory; - code: number; - } - /** - * A linked list of formatted diagnostic messages to be used as part of a multiline message. - * It is built from the bottom up, leaving the head to be the "main" diagnostic. - * While it seems that DiagnosticMessageChain is structurally similar to DiagnosticMessage, - * the difference is that messages are all preformatted in DMC. - */ - interface DiagnosticMessageChain { - messageText: string; - category: DiagnosticCategory; - code: number; - next?: DiagnosticMessageChain; - } - interface Diagnostic { - file: SourceFile; - start: number; - length: number; - messageText: string | DiagnosticMessageChain; - category: DiagnosticCategory; - code: number; - } - enum DiagnosticCategory { - Warning = 0, - Error = 1, - Message = 2, - } - const enum ModuleResolutionKind { - Classic = 1, - NodeJs = 2, - } - interface CompilerOptions { - allowNonTsExtensions?: boolean; - charset?: string; - declaration?: boolean; - diagnostics?: boolean; - emitBOM?: boolean; - help?: boolean; - init?: boolean; - inlineSourceMap?: boolean; - inlineSources?: boolean; - jsx?: JsxEmit; - listFiles?: boolean; - locale?: string; - mapRoot?: string; - module?: ModuleKind; - newLine?: NewLineKind; - noEmit?: boolean; - noEmitHelpers?: boolean; - noEmitOnError?: boolean; - noErrorTruncation?: boolean; - noImplicitAny?: boolean; - noLib?: boolean; - noResolve?: boolean; - out?: string; - outFile?: string; - outDir?: string; - preserveConstEnums?: boolean; - project?: string; - removeComments?: boolean; - rootDir?: string; - sourceMap?: boolean; - sourceRoot?: string; - suppressExcessPropertyErrors?: boolean; - suppressImplicitAnyIndexErrors?: boolean; - target?: ScriptTarget; - version?: boolean; - watch?: boolean; - isolatedModules?: boolean; - experimentalDecorators?: boolean; - experimentalAsyncFunctions?: boolean; - emitDecoratorMetadata?: boolean; - moduleResolution?: ModuleResolutionKind; - [option: string]: string | number | boolean; - } - const enum ModuleKind { - None = 0, - CommonJS = 1, - AMD = 2, - UMD = 3, - System = 4, - } - const enum JsxEmit { - None = 0, - Preserve = 1, - React = 2, - } - const enum NewLineKind { - CarriageReturnLineFeed = 0, - LineFeed = 1, - } - interface LineAndCharacter { - line: number; - character: number; - } - const enum ScriptTarget { - ES3 = 0, - ES5 = 1, - ES6 = 2, - Latest = 2, - } - const enum LanguageVariant { - Standard = 0, - JSX = 1, - } - interface ParsedCommandLine { - options: CompilerOptions; - fileNames: string[]; - errors: Diagnostic[]; - } - interface ModuleResolutionHost { - fileExists(fileName: string): boolean; - readFile(fileName: string): string; - } - interface ResolvedModule { - resolvedFileName: string; - isExternalLibraryImport?: boolean; - } - interface ResolvedModuleWithFailedLookupLocations { - resolvedModule: ResolvedModule; - failedLookupLocations: string[]; - } - interface CompilerHost extends ModuleResolutionHost { - getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile; - getCancellationToken?(): CancellationToken; - getDefaultLibFileName(options: CompilerOptions): string; - writeFile: WriteFileCallback; - getCurrentDirectory(): string; - getCanonicalFileName(fileName: string): string; - useCaseSensitiveFileNames(): boolean; - getNewLine(): string; - resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; - } - interface TextSpan { - start: number; - length: number; - } - interface TextChangeRange { - span: TextSpan; - newLength: number; - } -} -declare module "typescript" { - interface System { - args: string[]; - newLine: string; - useCaseSensitiveFileNames: boolean; - write(s: string): void; - readFile(path: string, encoding?: string): string; - writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; - watchFile?(path: string, callback: (path: string) => void): FileWatcher; - resolvePath(path: string): string; - fileExists(path: string): boolean; - directoryExists(path: string): boolean; - createDirectory(path: string): void; - getExecutingFilePath(): string; - getCurrentDirectory(): string; - readDirectory(path: string, extension?: string, exclude?: string[]): string[]; - getMemoryUsage?(): number; - exit(exitCode?: number): void; - } - interface FileWatcher { - close(): void; - } - var sys: System; -} -declare module "typescript" { - interface ErrorCallback { - (message: DiagnosticMessage, length: number): void; - } - interface Scanner { - getStartPos(): number; - getToken(): SyntaxKind; - getTextPos(): number; - getTokenPos(): number; - getTokenText(): string; - getTokenValue(): string; - hasExtendedUnicodeEscape(): boolean; - hasPrecedingLineBreak(): boolean; - isIdentifier(): boolean; - isReservedWord(): boolean; - isUnterminated(): boolean; - reScanGreaterToken(): SyntaxKind; - reScanSlashToken(): SyntaxKind; - reScanTemplateToken(): SyntaxKind; - scanJsxIdentifier(): SyntaxKind; - reScanJsxToken(): SyntaxKind; - scanJsxToken(): SyntaxKind; - scan(): SyntaxKind; - setText(text: string, start?: number, length?: number): void; - setOnError(onError: ErrorCallback): void; - setScriptTarget(scriptTarget: ScriptTarget): void; - setLanguageVariant(variant: LanguageVariant): void; - setTextPos(textPos: number): void; - lookAhead(callback: () => T): T; - tryScan(callback: () => T): T; - } - function tokenToString(t: SyntaxKind): string; - function getPositionOfLineAndCharacter(sourceFile: SourceFile, line: number, character: number): number; - function getLineAndCharacterOfPosition(sourceFile: SourceFile, position: number): LineAndCharacter; - function isWhiteSpace(ch: number): boolean; - function isLineBreak(ch: number): boolean; - function couldStartTrivia(text: string, pos: number): boolean; - function getLeadingCommentRanges(text: string, pos: number): CommentRange[]; - function getTrailingCommentRanges(text: string, pos: number): CommentRange[]; - /** Optionally, get the shebang */ - function getShebang(text: string): string; - function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; - function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; - function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; -} -declare module "typescript" { - function getDefaultLibFileName(options: CompilerOptions): string; - function textSpanEnd(span: TextSpan): number; - function textSpanIsEmpty(span: TextSpan): boolean; - function textSpanContainsPosition(span: TextSpan, position: number): boolean; - function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean; - function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean; - function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan; - function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean; - function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean; - function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number): boolean; - function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean; - function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan; - function createTextSpan(start: number, length: number): TextSpan; - function createTextSpanFromBounds(start: number, end: number): TextSpan; - function textChangeRangeNewSpan(range: TextChangeRange): TextSpan; - function textChangeRangeIsUnchanged(range: TextChangeRange): boolean; - function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange; - let unchangedTextChangeRange: TextChangeRange; - /** - * Called to merge all the changes that occurred across several versions of a script snapshot - * into a single change. i.e. if a user keeps making successive edits to a script we will - * have a text change from V1 to V2, V2 to V3, ..., Vn. - * - * This function will then merge those changes into a single change range valid between V1 and - * Vn. - */ - function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; - function getTypeParameterOwner(d: Declaration): Declaration; -} -declare module "typescript" { - function getNodeConstructor(kind: SyntaxKind): new () => Node; - function createNode(kind: SyntaxKind): Node; - function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; - function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean): SourceFile; - function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; -} -declare module "typescript" { - const version: string; - function findConfigFile(searchPath: string): string; - function resolveTripleslashReference(moduleName: string, containingFile: string): string; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; - function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; - function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; -} -declare module "typescript" { - function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine; - /** - * Read tsconfig.json file - * @param fileName The path to the config file - */ - function readConfigFile(fileName: string): { - config?: any; - error?: Diagnostic; - }; - /** - * Parse the text of the tsconfig.json file - * @param fileName The path to the config file - * @param jsonText The text of the config file - */ - function parseConfigFileText(fileName: string, jsonText: string): { - config?: any; - error?: Diagnostic; - }; - /** - * Parse the contents of a config file (tsconfig.json). - * @param json The contents of the config file to parse - * @param basePath A root directory to resolve relative path entries in the config - * file to. e.g. outDir - */ - function parseConfigFile(json: any, host: ParseConfigHost, basePath: string): ParsedCommandLine; -} -declare module "typescript" { - /** The version of the language service API */ - let servicesVersion: string; - interface Node { - getSourceFile(): SourceFile; - getChildCount(sourceFile?: SourceFile): number; - getChildAt(index: number, sourceFile?: SourceFile): Node; - getChildren(sourceFile?: SourceFile): Node[]; - getStart(sourceFile?: SourceFile): number; - getFullStart(): number; - getEnd(): number; - getWidth(sourceFile?: SourceFile): number; - getFullWidth(): number; - getLeadingTriviaWidth(sourceFile?: SourceFile): number; - getFullText(sourceFile?: SourceFile): string; - getText(sourceFile?: SourceFile): string; - getFirstToken(sourceFile?: SourceFile): Node; - getLastToken(sourceFile?: SourceFile): Node; - } - interface Symbol { - getFlags(): SymbolFlags; - getName(): string; - getDeclarations(): Declaration[]; - getDocumentationComment(): SymbolDisplayPart[]; - } - interface Type { - getFlags(): TypeFlags; - getSymbol(): Symbol; - getProperties(): Symbol[]; - getProperty(propertyName: string): Symbol; - getApparentProperties(): Symbol[]; - getCallSignatures(): Signature[]; - getConstructSignatures(): Signature[]; - getStringIndexType(): Type; - getNumberIndexType(): Type; - getBaseTypes(): ObjectType[]; - } - interface Signature { - getDeclaration(): SignatureDeclaration; - getTypeParameters(): Type[]; - getParameters(): Symbol[]; - getReturnType(): Type; - getDocumentationComment(): SymbolDisplayPart[]; - } - interface SourceFile { - getLineAndCharacterOfPosition(pos: number): LineAndCharacter; - getLineStarts(): number[]; - getPositionOfLineAndCharacter(line: number, character: number): number; - update(newText: string, textChangeRange: TextChangeRange): SourceFile; - } - /** - * Represents an immutable snapshot of a script at a specified time.Once acquired, the - * snapshot is observably immutable. i.e. the same calls with the same parameters will return - * the same values. - */ - interface IScriptSnapshot { - /** Gets a portion of the script snapshot specified by [start, end). */ - getText(start: number, end: number): string; - /** Gets the length of this script snapshot. */ - getLength(): number; - /** - * Gets the TextChangeRange that describe how the text changed between this text and - * an older version. This information is used by the incremental parser to determine - * what sections of the script need to be re-parsed. 'undefined' can be returned if the - * change range cannot be determined. However, in that case, incremental parsing will - * not happen and the entire document will be re - parsed. - */ - getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange; - /** Releases all resources held by this script snapshot */ - dispose?(): void; - } - module ScriptSnapshot { - function fromString(text: string): IScriptSnapshot; - } - interface PreProcessedFileInfo { - referencedFiles: FileReference[]; - importedFiles: FileReference[]; - ambientExternalModules: string[]; - isLibFile: boolean; - } - interface HostCancellationToken { - isCancellationRequested(): boolean; - } - interface LanguageServiceHost { - getCompilationSettings(): CompilerOptions; - getNewLine?(): string; - getProjectVersion?(): string; - getScriptFileNames(): string[]; - getScriptVersion(fileName: string): string; - getScriptSnapshot(fileName: string): IScriptSnapshot; - getLocalizedDiagnosticMessages?(): any; - getCancellationToken?(): HostCancellationToken; - getCurrentDirectory(): string; - getDefaultLibFileName(options: CompilerOptions): string; - log?(s: string): void; - trace?(s: string): void; - error?(s: string): void; - useCaseSensitiveFileNames?(): boolean; - resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; - } - interface LanguageService { - cleanupSemanticCache(): void; - getSyntacticDiagnostics(fileName: string): Diagnostic[]; - getSemanticDiagnostics(fileName: string): Diagnostic[]; - getCompilerOptionsDiagnostics(): Diagnostic[]; - /** - * @deprecated Use getEncodedSyntacticClassifications instead. - */ - getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; - /** - * @deprecated Use getEncodedSemanticClassifications instead. - */ - getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; - getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; - getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; - getCompletionsAtPosition(fileName: string, position: number): CompletionInfo; - getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails; - getQuickInfoAtPosition(fileName: string, position: number): QuickInfo; - getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan; - getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan; - getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems; - getRenameInfo(fileName: string, position: number): RenameInfo; - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[]; - getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; - getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; - getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - findReferences(fileName: string, position: number): ReferencedSymbol[]; - getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; - /** @deprecated */ - getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - getNavigateToItems(searchValue: string, maxResultCount?: number): NavigateToItem[]; - getNavigationBarItems(fileName: string): NavigationBarItem[]; - getOutliningSpans(fileName: string): OutliningSpan[]; - getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; - getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; - getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number; - getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[]; - getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[]; - getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[]; - getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; - getEmitOutput(fileName: string): EmitOutput; - getProgram(): Program; - getSourceFile(fileName: string): SourceFile; - dispose(): void; - } - interface Classifications { - spans: number[]; - endOfLineState: EndOfLineState; - } - interface ClassifiedSpan { - textSpan: TextSpan; - classificationType: string; - } - interface NavigationBarItem { - text: string; - kind: string; - kindModifiers: string; - spans: TextSpan[]; - childItems: NavigationBarItem[]; - indent: number; - bolded: boolean; - grayed: boolean; - } - interface TodoCommentDescriptor { - text: string; - priority: number; - } - interface TodoComment { - descriptor: TodoCommentDescriptor; - message: string; - position: number; - } - class TextChange { - span: TextSpan; - newText: string; - } - interface TextInsertion { - newText: string; - /** The position in newText the caret should point to after the insertion. */ - caretOffset: number; - } - interface RenameLocation { - textSpan: TextSpan; - fileName: string; - } - interface ReferenceEntry { - textSpan: TextSpan; - fileName: string; - isWriteAccess: boolean; - } - interface DocumentHighlights { - fileName: string; - highlightSpans: HighlightSpan[]; - } - module HighlightSpanKind { - const none: string; - const definition: string; - const reference: string; - const writtenReference: string; - } - interface HighlightSpan { - fileName?: string; - textSpan: TextSpan; - kind: string; - } - interface NavigateToItem { - name: string; - kind: string; - kindModifiers: string; - matchKind: string; - isCaseSensitive: boolean; - fileName: string; - textSpan: TextSpan; - containerName: string; - containerKind: string; - } - interface EditorOptions { - IndentSize: number; - TabSize: number; - NewLineCharacter: string; - ConvertTabsToSpaces: boolean; - } - interface FormatCodeOptions extends EditorOptions { - InsertSpaceAfterCommaDelimiter: boolean; - InsertSpaceAfterSemicolonInForStatements: boolean; - InsertSpaceBeforeAndAfterBinaryOperators: boolean; - InsertSpaceAfterKeywordsInControlFlowStatements: boolean; - InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; - InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; - InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; - PlaceOpenBraceOnNewLineForFunctions: boolean; - PlaceOpenBraceOnNewLineForControlBlocks: boolean; - [s: string]: boolean | number | string; - } - interface DefinitionInfo { - fileName: string; - textSpan: TextSpan; - kind: string; - name: string; - containerKind: string; - containerName: string; - } - interface ReferencedSymbol { - definition: DefinitionInfo; - references: ReferenceEntry[]; - } - enum SymbolDisplayPartKind { - aliasName = 0, - className = 1, - enumName = 2, - fieldName = 3, - interfaceName = 4, - keyword = 5, - lineBreak = 6, - numericLiteral = 7, - stringLiteral = 8, - localName = 9, - methodName = 10, - moduleName = 11, - operator = 12, - parameterName = 13, - propertyName = 14, - punctuation = 15, - space = 16, - text = 17, - typeParameterName = 18, - enumMemberName = 19, - functionName = 20, - regularExpressionLiteral = 21, - } - interface SymbolDisplayPart { - text: string; - kind: string; - } - interface QuickInfo { - kind: string; - kindModifiers: string; - textSpan: TextSpan; - displayParts: SymbolDisplayPart[]; - documentation: SymbolDisplayPart[]; - } - interface RenameInfo { - canRename: boolean; - localizedErrorMessage: string; - displayName: string; - fullDisplayName: string; - kind: string; - kindModifiers: string; - triggerSpan: TextSpan; - } - interface SignatureHelpParameter { - name: string; - documentation: SymbolDisplayPart[]; - displayParts: SymbolDisplayPart[]; - isOptional: boolean; - } - /** - * Represents a single signature to show in signature help. - * The id is used for subsequent calls into the language service to ask questions about the - * signature help item in the context of any documents that have been updated. i.e. after - * an edit has happened, while signature help is still active, the host can ask important - * questions like 'what parameter is the user currently contained within?'. - */ - interface SignatureHelpItem { - isVariadic: boolean; - prefixDisplayParts: SymbolDisplayPart[]; - suffixDisplayParts: SymbolDisplayPart[]; - separatorDisplayParts: SymbolDisplayPart[]; - parameters: SignatureHelpParameter[]; - documentation: SymbolDisplayPart[]; - } - /** - * Represents a set of signature help items, and the preferred item that should be selected. - */ - interface SignatureHelpItems { - items: SignatureHelpItem[]; - applicableSpan: TextSpan; - selectedItemIndex: number; - argumentIndex: number; - argumentCount: number; - } - interface CompletionInfo { - isMemberCompletion: boolean; - isNewIdentifierLocation: boolean; - entries: CompletionEntry[]; - } - interface CompletionEntry { - name: string; - kind: string; - kindModifiers: string; - sortText: string; - } - interface CompletionEntryDetails { - name: string; - kind: string; - kindModifiers: string; - displayParts: SymbolDisplayPart[]; - documentation: SymbolDisplayPart[]; - } - interface OutliningSpan { - /** The span of the document to actually collapse. */ - textSpan: TextSpan; - /** The span of the document to display when the user hovers over the collapsed span. */ - hintSpan: TextSpan; - /** The text to display in the editor for the collapsed region. */ - bannerText: string; - /** - * Whether or not this region should be automatically collapsed when - * the 'Collapse to Definitions' command is invoked. - */ - autoCollapse: boolean; - } - interface EmitOutput { - outputFiles: OutputFile[]; - emitSkipped: boolean; - } - const enum OutputFileType { - JavaScript = 0, - SourceMap = 1, - Declaration = 2, - } - interface OutputFile { - name: string; - writeByteOrderMark: boolean; - text: string; - } - const enum EndOfLineState { - None = 0, - InMultiLineCommentTrivia = 1, - InSingleQuoteStringLiteral = 2, - InDoubleQuoteStringLiteral = 3, - InTemplateHeadOrNoSubstitutionTemplate = 4, - InTemplateMiddleOrTail = 5, - InTemplateSubstitutionPosition = 6, - } - enum TokenClass { - Punctuation = 0, - Keyword = 1, - Operator = 2, - Comment = 3, - Whitespace = 4, - Identifier = 5, - NumberLiteral = 6, - StringLiteral = 7, - RegExpLiteral = 8, - } - interface ClassificationResult { - finalLexState: EndOfLineState; - entries: ClassificationInfo[]; - } - interface ClassificationInfo { - length: number; - classification: TokenClass; - } - interface Classifier { - /** - * Gives lexical classifications of tokens on a line without any syntactic context. - * For instance, a token consisting of the text 'string' can be either an identifier - * named 'string' or the keyword 'string', however, because this classifier is not aware, - * it relies on certain heuristics to give acceptable results. For classifications where - * speed trumps accuracy, this function is preferable; however, for true accuracy, the - * syntactic classifier is ideal. In fact, in certain editing scenarios, combining the - * lexical, syntactic, and semantic classifiers may issue the best user experience. - * - * @param text The text of a line to classify. - * @param lexState The state of the lexical classifier at the end of the previous line. - * @param syntacticClassifierAbsent Whether the client is *not* using a syntactic classifier. - * If there is no syntactic classifier (syntacticClassifierAbsent=true), - * certain heuristics may be used in its place; however, if there is a - * syntactic classifier (syntacticClassifierAbsent=false), certain - * classifications which may be incorrectly categorized will be given - * back as Identifiers in order to allow the syntactic classifier to - * subsume the classification. - * @deprecated Use getLexicalClassifications instead. - */ - getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult; - getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; - } - /** - * The document registry represents a store of SourceFile objects that can be shared between - * multiple LanguageService instances. A LanguageService instance holds on the SourceFile (AST) - * of files in the context. - * SourceFile objects account for most of the memory usage by the language service. Sharing - * the same DocumentRegistry instance between different instances of LanguageService allow - * for more efficient memory utilization since all projects will share at least the library - * file (lib.d.ts). - * - * A more advanced use of the document registry is to serialize sourceFile objects to disk - * and re-hydrate them when needed. - * - * To create a default DocumentRegistry, use createDocumentRegistry to create one, and pass it - * to all subsequent createLanguageService calls. - */ - interface DocumentRegistry { - /** - * Request a stored SourceFile with a given fileName and compilationSettings. - * The first call to acquire will call createLanguageServiceSourceFile to generate - * the SourceFile if was not found in the registry. - * - * @param fileName The name of the file requested - * @param compilationSettings Some compilation settings like target affects the - * shape of a the resulting SourceFile. This allows the DocumentRegistry to store - * multiple copies of the same file for different compilation settings. - * @parm scriptSnapshot Text of the file. Only used if the file was not found - * in the registry and a new one was created. - * @parm version Current version of the file. Only used if the file was not found - * in the registry and a new one was created. - */ - acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile; - /** - * Request an updated version of an already existing SourceFile with a given fileName - * and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile - * to get an updated SourceFile. - * - * @param fileName The name of the file requested - * @param compilationSettings Some compilation settings like target affects the - * shape of a the resulting SourceFile. This allows the DocumentRegistry to store - * multiple copies of the same file for different compilation settings. - * @param scriptSnapshot Text of the file. - * @param version Current version of the file. - */ - updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile; - /** - * Informs the DocumentRegistry that a file is not needed any longer. - * - * Note: It is not allowed to call release on a SourceFile that was not acquired from - * this registry originally. - * - * @param fileName The name of the file to be released - * @param compilationSettings The compilation settings used to acquire the file - */ - releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; - reportStats(): string; - } - module ScriptElementKind { - const unknown: string; - const warning: string; - const keyword: string; - const scriptElement: string; - const moduleElement: string; - const classElement: string; - const localClassElement: string; - const interfaceElement: string; - const typeElement: string; - const enumElement: string; - const variableElement: string; - const localVariableElement: string; - const functionElement: string; - const localFunctionElement: string; - const memberFunctionElement: string; - const memberGetAccessorElement: string; - const memberSetAccessorElement: string; - const memberVariableElement: string; - const constructorImplementationElement: string; - const callSignatureElement: string; - const indexSignatureElement: string; - const constructSignatureElement: string; - const parameterElement: string; - const typeParameterElement: string; - const primitiveType: string; - const label: string; - const alias: string; - const constElement: string; - const letElement: string; - } - module ScriptElementKindModifier { - const none: string; - const publicMemberModifier: string; - const privateMemberModifier: string; - const protectedMemberModifier: string; - const exportedModifier: string; - const ambientModifier: string; - const staticModifier: string; - const abstractModifier: string; - } - class ClassificationTypeNames { - static comment: string; - static identifier: string; - static keyword: string; - static numericLiteral: string; - static operator: string; - static stringLiteral: string; - static whiteSpace: string; - static text: string; - static punctuation: string; - static className: string; - static enumName: string; - static interfaceName: string; - static moduleName: string; - static typeParameterName: string; - static typeAliasName: string; - static parameterName: string; - static docCommentTagName: string; - } - const enum ClassificationType { - comment = 1, - identifier = 2, - keyword = 3, - numericLiteral = 4, - operator = 5, - stringLiteral = 6, - regularExpressionLiteral = 7, - whiteSpace = 8, - text = 9, - punctuation = 10, - className = 11, - enumName = 12, - interfaceName = 13, - moduleName = 14, - typeParameterName = 15, - typeAliasName = 16, - parameterName = 17, - docCommentTagName = 18, - } - interface DisplayPartsSymbolWriter extends SymbolWriter { - displayParts(): SymbolDisplayPart[]; - } - function displayPartsToString(displayParts: SymbolDisplayPart[]): string; - function getDefaultCompilerOptions(): CompilerOptions; - interface TranspileOptions { - compilerOptions?: CompilerOptions; - fileName?: string; - reportDiagnostics?: boolean; - moduleName?: string; - renamedDependencies?: Map; - } - interface TranspileOutput { - outputText: string; - diagnostics?: Diagnostic[]; - sourceMapText?: string; - } - function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; - function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; - function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile; - let disableIncrementalParsing: boolean; - function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; - function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string; - function createDocumentRegistry(useCaseSensitiveFileNames?: boolean): DocumentRegistry; - function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo; - function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService; - function createClassifier(): Classifier; - /** - * Get the path of the default library files (lib.d.ts) as distributed with the typescript - * node package. - * The functionality is not supported if the ts module is consumed outside of a node module. - */ - function getDefaultLibFilePath(options: CompilerOptions): string; -} +// Type definitions for TypeScript API v0.4.0 +// Project: http://www.typescriptlang.org/ +// Definitions by: Microsoft TypeScript +// 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. +***************************************************************************** */ + +declare module "typescript" { + interface Map { + [index: string]: T; + } + interface FileMap { + get(fileName: string): T; + set(fileName: string, value: T): void; + contains(fileName: string): boolean; + remove(fileName: string): void; + forEachValue(f: (v: T) => void): void; + clear(): void; + } + interface TextRange { + pos: number; + end: number; + } + const enum SyntaxKind { + Unknown = 0, + EndOfFileToken = 1, + SingleLineCommentTrivia = 2, + MultiLineCommentTrivia = 3, + NewLineTrivia = 4, + WhitespaceTrivia = 5, + ShebangTrivia = 6, + ConflictMarkerTrivia = 7, + NumericLiteral = 8, + StringLiteral = 9, + RegularExpressionLiteral = 10, + NoSubstitutionTemplateLiteral = 11, + TemplateHead = 12, + TemplateMiddle = 13, + TemplateTail = 14, + OpenBraceToken = 15, + CloseBraceToken = 16, + OpenParenToken = 17, + CloseParenToken = 18, + OpenBracketToken = 19, + CloseBracketToken = 20, + DotToken = 21, + DotDotDotToken = 22, + SemicolonToken = 23, + CommaToken = 24, + LessThanToken = 25, + LessThanSlashToken = 26, + GreaterThanToken = 27, + LessThanEqualsToken = 28, + GreaterThanEqualsToken = 29, + EqualsEqualsToken = 30, + ExclamationEqualsToken = 31, + EqualsEqualsEqualsToken = 32, + ExclamationEqualsEqualsToken = 33, + EqualsGreaterThanToken = 34, + PlusToken = 35, + MinusToken = 36, + AsteriskToken = 37, + SlashToken = 38, + PercentToken = 39, + PlusPlusToken = 40, + MinusMinusToken = 41, + LessThanLessThanToken = 42, + GreaterThanGreaterThanToken = 43, + GreaterThanGreaterThanGreaterThanToken = 44, + AmpersandToken = 45, + BarToken = 46, + CaretToken = 47, + ExclamationToken = 48, + TildeToken = 49, + AmpersandAmpersandToken = 50, + BarBarToken = 51, + QuestionToken = 52, + ColonToken = 53, + AtToken = 54, + EqualsToken = 55, + PlusEqualsToken = 56, + MinusEqualsToken = 57, + AsteriskEqualsToken = 58, + SlashEqualsToken = 59, + PercentEqualsToken = 60, + LessThanLessThanEqualsToken = 61, + GreaterThanGreaterThanEqualsToken = 62, + GreaterThanGreaterThanGreaterThanEqualsToken = 63, + AmpersandEqualsToken = 64, + BarEqualsToken = 65, + CaretEqualsToken = 66, + Identifier = 67, + BreakKeyword = 68, + CaseKeyword = 69, + CatchKeyword = 70, + ClassKeyword = 71, + ConstKeyword = 72, + ContinueKeyword = 73, + DebuggerKeyword = 74, + DefaultKeyword = 75, + DeleteKeyword = 76, + DoKeyword = 77, + ElseKeyword = 78, + EnumKeyword = 79, + ExportKeyword = 80, + ExtendsKeyword = 81, + FalseKeyword = 82, + FinallyKeyword = 83, + ForKeyword = 84, + FunctionKeyword = 85, + IfKeyword = 86, + ImportKeyword = 87, + InKeyword = 88, + InstanceOfKeyword = 89, + NewKeyword = 90, + NullKeyword = 91, + ReturnKeyword = 92, + SuperKeyword = 93, + SwitchKeyword = 94, + ThisKeyword = 95, + ThrowKeyword = 96, + TrueKeyword = 97, + TryKeyword = 98, + TypeOfKeyword = 99, + VarKeyword = 100, + VoidKeyword = 101, + WhileKeyword = 102, + WithKeyword = 103, + ImplementsKeyword = 104, + InterfaceKeyword = 105, + LetKeyword = 106, + PackageKeyword = 107, + PrivateKeyword = 108, + ProtectedKeyword = 109, + PublicKeyword = 110, + StaticKeyword = 111, + YieldKeyword = 112, + AbstractKeyword = 113, + AsKeyword = 114, + AnyKeyword = 115, + AsyncKeyword = 116, + AwaitKeyword = 117, + BooleanKeyword = 118, + ConstructorKeyword = 119, + DeclareKeyword = 120, + GetKeyword = 121, + IsKeyword = 122, + ModuleKeyword = 123, + NamespaceKeyword = 124, + RequireKeyword = 125, + NumberKeyword = 126, + SetKeyword = 127, + StringKeyword = 128, + SymbolKeyword = 129, + TypeKeyword = 130, + FromKeyword = 131, + OfKeyword = 132, + QualifiedName = 133, + ComputedPropertyName = 134, + TypeParameter = 135, + Parameter = 136, + Decorator = 137, + PropertySignature = 138, + PropertyDeclaration = 139, + MethodSignature = 140, + MethodDeclaration = 141, + Constructor = 142, + GetAccessor = 143, + SetAccessor = 144, + CallSignature = 145, + ConstructSignature = 146, + IndexSignature = 147, + TypePredicate = 148, + TypeReference = 149, + FunctionType = 150, + ConstructorType = 151, + TypeQuery = 152, + TypeLiteral = 153, + ArrayType = 154, + TupleType = 155, + UnionType = 156, + IntersectionType = 157, + ParenthesizedType = 158, + ObjectBindingPattern = 159, + ArrayBindingPattern = 160, + BindingElement = 161, + ArrayLiteralExpression = 162, + ObjectLiteralExpression = 163, + PropertyAccessExpression = 164, + ElementAccessExpression = 165, + CallExpression = 166, + NewExpression = 167, + TaggedTemplateExpression = 168, + TypeAssertionExpression = 169, + ParenthesizedExpression = 170, + FunctionExpression = 171, + ArrowFunction = 172, + DeleteExpression = 173, + TypeOfExpression = 174, + VoidExpression = 175, + AwaitExpression = 176, + PrefixUnaryExpression = 177, + PostfixUnaryExpression = 178, + BinaryExpression = 179, + ConditionalExpression = 180, + TemplateExpression = 181, + YieldExpression = 182, + SpreadElementExpression = 183, + ClassExpression = 184, + OmittedExpression = 185, + ExpressionWithTypeArguments = 186, + AsExpression = 187, + TemplateSpan = 188, + SemicolonClassElement = 189, + Block = 190, + VariableStatement = 191, + EmptyStatement = 192, + ExpressionStatement = 193, + IfStatement = 194, + DoStatement = 195, + WhileStatement = 196, + ForStatement = 197, + ForInStatement = 198, + ForOfStatement = 199, + ContinueStatement = 200, + BreakStatement = 201, + ReturnStatement = 202, + WithStatement = 203, + SwitchStatement = 204, + LabeledStatement = 205, + ThrowStatement = 206, + TryStatement = 207, + DebuggerStatement = 208, + VariableDeclaration = 209, + VariableDeclarationList = 210, + FunctionDeclaration = 211, + ClassDeclaration = 212, + InterfaceDeclaration = 213, + TypeAliasDeclaration = 214, + EnumDeclaration = 215, + ModuleDeclaration = 216, + ModuleBlock = 217, + CaseBlock = 218, + ImportEqualsDeclaration = 219, + ImportDeclaration = 220, + ImportClause = 221, + NamespaceImport = 222, + NamedImports = 223, + ImportSpecifier = 224, + ExportAssignment = 225, + ExportDeclaration = 226, + NamedExports = 227, + ExportSpecifier = 228, + MissingDeclaration = 229, + ExternalModuleReference = 230, + JsxElement = 231, + JsxSelfClosingElement = 232, + JsxOpeningElement = 233, + JsxText = 234, + JsxClosingElement = 235, + JsxAttribute = 236, + JsxSpreadAttribute = 237, + JsxExpression = 238, + CaseClause = 239, + DefaultClause = 240, + HeritageClause = 241, + CatchClause = 242, + PropertyAssignment = 243, + ShorthandPropertyAssignment = 244, + EnumMember = 245, + SourceFile = 246, + JSDocTypeExpression = 247, + JSDocAllType = 248, + JSDocUnknownType = 249, + JSDocArrayType = 250, + JSDocUnionType = 251, + JSDocTupleType = 252, + JSDocNullableType = 253, + JSDocNonNullableType = 254, + JSDocRecordType = 255, + JSDocRecordMember = 256, + JSDocTypeReference = 257, + JSDocOptionalType = 258, + JSDocFunctionType = 259, + JSDocVariadicType = 260, + JSDocConstructorType = 261, + JSDocThisType = 262, + JSDocComment = 263, + JSDocTag = 264, + JSDocParameterTag = 265, + JSDocReturnTag = 266, + JSDocTypeTag = 267, + JSDocTemplateTag = 268, + SyntaxList = 269, + Count = 270, + FirstAssignment = 55, + LastAssignment = 66, + FirstReservedWord = 68, + LastReservedWord = 103, + FirstKeyword = 68, + LastKeyword = 132, + FirstFutureReservedWord = 104, + LastFutureReservedWord = 112, + FirstTypeNode = 149, + LastTypeNode = 158, + FirstPunctuation = 15, + LastPunctuation = 66, + FirstToken = 0, + LastToken = 132, + FirstTriviaToken = 2, + LastTriviaToken = 7, + FirstLiteralToken = 8, + LastLiteralToken = 11, + FirstTemplateToken = 11, + LastTemplateToken = 14, + FirstBinaryOperator = 25, + LastBinaryOperator = 66, + FirstNode = 133, + } + const enum NodeFlags { + Export = 1, + Ambient = 2, + Public = 16, + Private = 32, + Protected = 64, + Static = 128, + Abstract = 256, + Async = 512, + Default = 1024, + MultiLine = 2048, + Synthetic = 4096, + DeclarationFile = 8192, + Let = 16384, + Const = 32768, + OctalLiteral = 65536, + Namespace = 131072, + ExportContext = 262144, + Modifier = 2035, + AccessibilityModifier = 112, + BlockScoped = 49152, + } + const enum JsxFlags { + None = 0, + IntrinsicNamedElement = 1, + IntrinsicIndexedElement = 2, + ClassElement = 4, + UnknownElement = 8, + IntrinsicElement = 3, + } + interface Node extends TextRange { + kind: SyntaxKind; + flags: NodeFlags; + decorators?: NodeArray; + modifiers?: ModifiersArray; + parent?: Node; + } + interface NodeArray extends Array, TextRange { + hasTrailingComma?: boolean; + } + interface ModifiersArray extends NodeArray { + flags: number; + } + interface Identifier extends PrimaryExpression { + text: string; + originalKeywordKind?: SyntaxKind; + } + interface QualifiedName extends Node { + left: EntityName; + right: Identifier; + } + type EntityName = Identifier | QualifiedName; + type DeclarationName = Identifier | LiteralExpression | ComputedPropertyName | BindingPattern; + interface Declaration extends Node { + _declarationBrand: any; + name?: DeclarationName; + } + interface ComputedPropertyName extends Node { + expression: Expression; + } + interface Decorator extends Node { + expression: LeftHandSideExpression; + } + interface TypeParameterDeclaration extends Declaration { + name: Identifier; + constraint?: TypeNode; + expression?: Expression; + } + interface SignatureDeclaration extends Declaration { + typeParameters?: NodeArray; + parameters: NodeArray; + type?: TypeNode; + } + interface VariableDeclaration extends Declaration { + parent?: VariableDeclarationList; + name: Identifier | BindingPattern; + type?: TypeNode; + initializer?: Expression; + } + interface VariableDeclarationList extends Node { + declarations: NodeArray; + } + interface ParameterDeclaration extends Declaration { + dotDotDotToken?: Node; + name: Identifier | BindingPattern; + questionToken?: Node; + type?: TypeNode; + initializer?: Expression; + } + interface BindingElement extends Declaration { + propertyName?: Identifier; + dotDotDotToken?: Node; + name: Identifier | BindingPattern; + initializer?: Expression; + } + interface PropertyDeclaration extends Declaration, ClassElement { + name: DeclarationName; + questionToken?: Node; + type?: TypeNode; + initializer?: Expression; + } + interface ObjectLiteralElement extends Declaration { + _objectLiteralBrandBrand: any; + } + interface PropertyAssignment extends ObjectLiteralElement { + _propertyAssignmentBrand: any; + name: DeclarationName; + questionToken?: Node; + initializer: Expression; + } + interface ShorthandPropertyAssignment extends ObjectLiteralElement { + name: Identifier; + questionToken?: Node; + } + interface VariableLikeDeclaration extends Declaration { + propertyName?: Identifier; + dotDotDotToken?: Node; + name: DeclarationName; + questionToken?: Node; + type?: TypeNode; + initializer?: Expression; + } + interface BindingPattern extends Node { + elements: NodeArray; + } + /** + * Several node kinds share function-like features such as a signature, + * a name, and a body. These nodes should extend FunctionLikeDeclaration. + * Examples: + * - FunctionDeclaration + * - MethodDeclaration + * - AccessorDeclaration + */ + interface FunctionLikeDeclaration extends SignatureDeclaration { + _functionLikeDeclarationBrand: any; + asteriskToken?: Node; + questionToken?: Node; + body?: Block | Expression; + } + interface FunctionDeclaration extends FunctionLikeDeclaration, Statement { + name?: Identifier; + body?: Block; + } + interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + body?: Block; + } + interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { + body?: Block; + } + interface SemicolonClassElement extends ClassElement { + _semicolonClassElementBrand: any; + } + interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + _accessorDeclarationBrand: any; + body: Block; + } + interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement { + _indexSignatureDeclarationBrand: any; + } + interface TypeNode extends Node { + _typeNodeBrand: any; + } + interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration { + _functionOrConstructorTypeNodeBrand: any; + } + interface TypeReferenceNode extends TypeNode { + typeName: EntityName; + typeArguments?: NodeArray; + } + interface TypePredicateNode extends TypeNode { + parameterName: Identifier; + type: TypeNode; + } + interface TypeQueryNode extends TypeNode { + exprName: EntityName; + } + interface TypeLiteralNode extends TypeNode, Declaration { + members: NodeArray; + } + interface ArrayTypeNode extends TypeNode { + elementType: TypeNode; + } + interface TupleTypeNode extends TypeNode { + elementTypes: NodeArray; + } + interface UnionOrIntersectionTypeNode extends TypeNode { + types: NodeArray; + } + interface UnionTypeNode extends UnionOrIntersectionTypeNode { + } + interface IntersectionTypeNode extends UnionOrIntersectionTypeNode { + } + interface ParenthesizedTypeNode extends TypeNode { + type: TypeNode; + } + interface StringLiteral extends LiteralExpression, TypeNode { + _stringLiteralBrand: any; + } + interface Expression extends Node { + _expressionBrand: any; + contextualType?: Type; + } + interface UnaryExpression extends Expression { + _unaryExpressionBrand: any; + } + interface PrefixUnaryExpression extends UnaryExpression { + operator: SyntaxKind; + operand: UnaryExpression; + } + interface PostfixUnaryExpression extends PostfixExpression { + operand: LeftHandSideExpression; + operator: SyntaxKind; + } + interface PostfixExpression extends UnaryExpression { + _postfixExpressionBrand: any; + } + interface LeftHandSideExpression extends PostfixExpression { + _leftHandSideExpressionBrand: any; + } + interface MemberExpression extends LeftHandSideExpression { + _memberExpressionBrand: any; + } + interface PrimaryExpression extends MemberExpression { + _primaryExpressionBrand: any; + } + interface DeleteExpression extends UnaryExpression { + expression: UnaryExpression; + } + interface TypeOfExpression extends UnaryExpression { + expression: UnaryExpression; + } + interface VoidExpression extends UnaryExpression { + expression: UnaryExpression; + } + interface AwaitExpression extends UnaryExpression { + expression: UnaryExpression; + } + interface YieldExpression extends Expression { + asteriskToken?: Node; + expression?: Expression; + } + interface BinaryExpression extends Expression { + left: Expression; + operatorToken: Node; + right: Expression; + } + interface ConditionalExpression extends Expression { + condition: Expression; + questionToken: Node; + whenTrue: Expression; + colonToken: Node; + whenFalse: Expression; + } + interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { + name?: Identifier; + body: Block | Expression; + } + interface ArrowFunction extends Expression, FunctionLikeDeclaration { + equalsGreaterThanToken: Node; + } + interface LiteralExpression extends PrimaryExpression { + text: string; + isUnterminated?: boolean; + hasExtendedUnicodeEscape?: boolean; + } + interface TemplateExpression extends PrimaryExpression { + head: LiteralExpression; + templateSpans: NodeArray; + } + interface TemplateSpan extends Node { + expression: Expression; + literal: LiteralExpression; + } + interface ParenthesizedExpression extends PrimaryExpression { + expression: Expression; + } + interface ArrayLiteralExpression extends PrimaryExpression { + elements: NodeArray; + } + interface SpreadElementExpression extends Expression { + expression: Expression; + } + interface ObjectLiteralExpression extends PrimaryExpression, Declaration { + properties: NodeArray; + } + interface PropertyAccessExpression extends MemberExpression { + expression: LeftHandSideExpression; + dotToken: Node; + name: Identifier; + } + interface ElementAccessExpression extends MemberExpression { + expression: LeftHandSideExpression; + argumentExpression?: Expression; + } + interface CallExpression extends LeftHandSideExpression { + expression: LeftHandSideExpression; + typeArguments?: NodeArray; + arguments: NodeArray; + } + interface ExpressionWithTypeArguments extends TypeNode { + expression: LeftHandSideExpression; + typeArguments?: NodeArray; + } + interface NewExpression extends CallExpression, PrimaryExpression { + } + interface TaggedTemplateExpression extends MemberExpression { + tag: LeftHandSideExpression; + template: LiteralExpression | TemplateExpression; + } + type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; + interface AsExpression extends Expression { + expression: Expression; + type: TypeNode; + } + interface TypeAssertion extends UnaryExpression { + type: TypeNode; + expression: UnaryExpression; + } + type AssertionExpression = TypeAssertion | AsExpression; + interface JsxElement extends PrimaryExpression { + openingElement: JsxOpeningElement; + children: NodeArray; + closingElement: JsxClosingElement; + } + interface JsxOpeningElement extends Expression { + _openingElementBrand?: any; + tagName: EntityName; + attributes: NodeArray; + } + interface JsxSelfClosingElement extends PrimaryExpression, JsxOpeningElement { + _selfClosingElementBrand?: any; + } + type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; + interface JsxAttribute extends Node { + name: Identifier; + initializer?: Expression; + } + interface JsxSpreadAttribute extends Node { + expression: Expression; + } + interface JsxClosingElement extends Node { + tagName: EntityName; + } + interface JsxExpression extends Expression { + expression?: Expression; + } + interface JsxText extends Node { + _jsxTextExpressionBrand: any; + } + type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement; + interface Statement extends Node { + _statementBrand: any; + } + interface Block extends Statement { + statements: NodeArray; + } + interface VariableStatement extends Statement { + declarationList: VariableDeclarationList; + } + interface ExpressionStatement extends Statement { + expression: Expression; + } + interface IfStatement extends Statement { + expression: Expression; + thenStatement: Statement; + elseStatement?: Statement; + } + interface IterationStatement extends Statement { + statement: Statement; + } + interface DoStatement extends IterationStatement { + expression: Expression; + } + interface WhileStatement extends IterationStatement { + expression: Expression; + } + interface ForStatement extends IterationStatement { + initializer?: VariableDeclarationList | Expression; + condition?: Expression; + incrementor?: Expression; + } + interface ForInStatement extends IterationStatement { + initializer: VariableDeclarationList | Expression; + expression: Expression; + } + interface ForOfStatement extends IterationStatement { + initializer: VariableDeclarationList | Expression; + expression: Expression; + } + interface BreakOrContinueStatement extends Statement { + label?: Identifier; + } + interface ReturnStatement extends Statement { + expression?: Expression; + } + interface WithStatement extends Statement { + expression: Expression; + statement: Statement; + } + interface SwitchStatement extends Statement { + expression: Expression; + caseBlock: CaseBlock; + } + interface CaseBlock extends Node { + clauses: NodeArray; + } + interface CaseClause extends Node { + expression?: Expression; + statements: NodeArray; + } + interface DefaultClause extends Node { + statements: NodeArray; + } + type CaseOrDefaultClause = CaseClause | DefaultClause; + interface LabeledStatement extends Statement { + label: Identifier; + statement: Statement; + } + interface ThrowStatement extends Statement { + expression: Expression; + } + interface TryStatement extends Statement { + tryBlock: Block; + catchClause?: CatchClause; + finallyBlock?: Block; + } + interface CatchClause extends Node { + variableDeclaration: VariableDeclaration; + block: Block; + } + interface ClassLikeDeclaration extends Declaration { + name?: Identifier; + typeParameters?: NodeArray; + heritageClauses?: NodeArray; + members: NodeArray; + } + interface ClassDeclaration extends ClassLikeDeclaration, Statement { + } + interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { + } + interface ClassElement extends Declaration { + _classElementBrand: any; + } + interface InterfaceDeclaration extends Declaration, Statement { + name: Identifier; + typeParameters?: NodeArray; + heritageClauses?: NodeArray; + members: NodeArray; + } + interface HeritageClause extends Node { + token: SyntaxKind; + types?: NodeArray; + } + interface TypeAliasDeclaration extends Declaration, Statement { + name: Identifier; + typeParameters?: NodeArray; + type: TypeNode; + } + interface EnumMember extends Declaration { + name: DeclarationName; + initializer?: Expression; + } + interface EnumDeclaration extends Declaration, Statement { + name: Identifier; + members: NodeArray; + } + interface ModuleDeclaration extends Declaration, Statement { + name: Identifier | LiteralExpression; + body: ModuleBlock | ModuleDeclaration; + } + interface ModuleBlock extends Node, Statement { + statements: NodeArray; + } + interface ImportEqualsDeclaration extends Declaration, Statement { + name: Identifier; + moduleReference: EntityName | ExternalModuleReference; + } + interface ExternalModuleReference extends Node { + expression?: Expression; + } + interface ImportDeclaration extends Statement { + importClause?: ImportClause; + moduleSpecifier: Expression; + } + interface ImportClause extends Declaration { + name?: Identifier; + namedBindings?: NamespaceImport | NamedImports; + } + interface NamespaceImport extends Declaration { + name: Identifier; + } + interface ExportDeclaration extends Declaration, Statement { + exportClause?: NamedExports; + moduleSpecifier?: Expression; + } + interface NamedImportsOrExports extends Node { + elements: NodeArray; + } + type NamedImports = NamedImportsOrExports; + type NamedExports = NamedImportsOrExports; + interface ImportOrExportSpecifier extends Declaration { + propertyName?: Identifier; + name: Identifier; + } + type ImportSpecifier = ImportOrExportSpecifier; + type ExportSpecifier = ImportOrExportSpecifier; + interface ExportAssignment extends Declaration, Statement { + isExportEquals?: boolean; + expression: Expression; + } + interface FileReference extends TextRange { + fileName: string; + } + interface CommentRange extends TextRange { + hasTrailingNewLine?: boolean; + kind: SyntaxKind; + } + interface JSDocTypeExpression extends Node { + type: JSDocType; + } + interface JSDocType extends TypeNode { + _jsDocTypeBrand: any; + } + interface JSDocAllType extends JSDocType { + _JSDocAllTypeBrand: any; + } + interface JSDocUnknownType extends JSDocType { + _JSDocUnknownTypeBrand: any; + } + interface JSDocArrayType extends JSDocType { + elementType: JSDocType; + } + interface JSDocUnionType extends JSDocType { + types: NodeArray; + } + interface JSDocTupleType extends JSDocType { + types: NodeArray; + } + interface JSDocNonNullableType extends JSDocType { + type: JSDocType; + } + interface JSDocNullableType extends JSDocType { + type: JSDocType; + } + interface JSDocRecordType extends JSDocType, TypeLiteralNode { + members: NodeArray; + } + interface JSDocTypeReference extends JSDocType { + name: EntityName; + typeArguments: NodeArray; + } + interface JSDocOptionalType extends JSDocType { + type: JSDocType; + } + interface JSDocFunctionType extends JSDocType, SignatureDeclaration { + parameters: NodeArray; + type: JSDocType; + } + interface JSDocVariadicType extends JSDocType { + type: JSDocType; + } + interface JSDocConstructorType extends JSDocType { + type: JSDocType; + } + interface JSDocThisType extends JSDocType { + type: JSDocType; + } + interface JSDocRecordMember extends PropertyDeclaration { + name: Identifier | LiteralExpression; + type?: JSDocType; + } + interface JSDocComment extends Node { + tags: NodeArray; + } + interface JSDocTag extends Node { + atToken: Node; + tagName: Identifier; + } + interface JSDocTemplateTag extends JSDocTag { + typeParameters: NodeArray; + } + interface JSDocReturnTag extends JSDocTag { + typeExpression: JSDocTypeExpression; + } + interface JSDocTypeTag extends JSDocTag { + typeExpression: JSDocTypeExpression; + } + interface JSDocParameterTag extends JSDocTag { + preParameterName?: Identifier; + typeExpression?: JSDocTypeExpression; + postParameterName?: Identifier; + isBracketed: boolean; + } + interface SourceFile extends Declaration { + statements: NodeArray; + endOfFileToken: Node; + fileName: string; + text: string; + amdDependencies: { + path: string; + name: string; + }[]; + moduleName: string; + referencedFiles: FileReference[]; + languageVariant: LanguageVariant; + /** + * lib.d.ts should have a reference comment like + * + * /// + * + * If any other file has this comment, it signals not to include lib.d.ts + * because this containing file is intended to act as a default library. + */ + hasNoDefaultLib: boolean; + languageVersion: ScriptTarget; + } + interface ScriptReferenceHost { + getCompilerOptions(): CompilerOptions; + getSourceFile(fileName: string): SourceFile; + getCurrentDirectory(): string; + } + interface ParseConfigHost extends ModuleResolutionHost { + readDirectory(rootDir: string, extension: string, exclude: string[]): string[]; + } + interface WriteFileCallback { + (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void; + } + class OperationCanceledException { + } + interface CancellationToken { + isCancellationRequested(): boolean; + /** @throws OperationCanceledException if isCancellationRequested is true */ + throwIfCancellationRequested(): void; + } + interface Program extends ScriptReferenceHost { + /** + * Get a list of root file names that were passed to a 'createProgram' + */ + getRootFileNames(): string[]; + /** + * Get a list of files in the program + */ + getSourceFiles(): SourceFile[]; + /** + * Emits the JavaScript and declaration files. If targetSourceFile is not specified, then + * the JavaScript and declaration files will be produced for all the files in this program. + * If targetSourceFile is specified, then only the JavaScript and declaration for that + * specific file will be generated. + * + * If writeFile is not specified then the writeFile callback from the compiler host will be + * used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter + * will be invoked when writing the JavaScript and declaration files. + */ + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult; + getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; + getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + /** + * Gets a type checker that can be used to semantically analyze source fils in the program. + */ + getTypeChecker(): TypeChecker; + } + interface SourceMapSpan { + /** Line number in the .js file. */ + emittedLine: number; + /** Column number in the .js file. */ + emittedColumn: number; + /** Line number in the .ts file. */ + sourceLine: number; + /** Column number in the .ts file. */ + sourceColumn: number; + /** Optional name (index into names array) associated with this span. */ + nameIndex?: number; + /** .ts file (index into sources array) associated with this span */ + sourceIndex: number; + } + interface SourceMapData { + sourceMapFilePath: string; + jsSourceMappingURL: string; + sourceMapFile: string; + sourceMapSourceRoot: string; + sourceMapSources: string[]; + sourceMapSourcesContent?: string[]; + inputSourceFileNames: string[]; + sourceMapNames?: string[]; + sourceMapMappings: string; + sourceMapDecodedMappings: SourceMapSpan[]; + } + /** Return code used by getEmitOutput function to indicate status of the function */ + enum ExitStatus { + Success = 0, + DiagnosticsPresent_OutputsSkipped = 1, + DiagnosticsPresent_OutputsGenerated = 2, + } + interface EmitResult { + emitSkipped: boolean; + diagnostics: Diagnostic[]; + } + interface TypeChecker { + getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type; + getDeclaredTypeOfSymbol(symbol: Symbol): Type; + getPropertiesOfType(type: Type): Symbol[]; + getPropertyOfType(type: Type, propertyName: string): Symbol; + getSignaturesOfType(type: Type, kind: SignatureKind): Signature[]; + getIndexTypeOfType(type: Type, kind: IndexKind): Type; + getBaseTypes(type: InterfaceType): ObjectType[]; + getReturnTypeOfSignature(signature: Signature): Type; + getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; + getSymbolAtLocation(node: Node): Symbol; + getShorthandAssignmentValueSymbol(location: Node): Symbol; + getTypeAtLocation(node: Node): Type; + typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; + symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string; + getSymbolDisplayBuilder(): SymbolDisplayBuilder; + getFullyQualifiedName(symbol: Symbol): string; + getAugmentedPropertiesOfType(type: Type): Symbol[]; + getRootSymbols(symbol: Symbol): Symbol[]; + getContextualType(node: Expression): Type; + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature; + getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature; + isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; + isUndefinedSymbol(symbol: Symbol): boolean; + isArgumentsSymbol(symbol: Symbol): boolean; + getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; + isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; + getAliasedSymbol(symbol: Symbol): Symbol; + getExportsOfModule(moduleSymbol: Symbol): Symbol[]; + getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type; + getJsxIntrinsicTagNames(): Symbol[]; + isOptionalParameter(node: ParameterDeclaration): boolean; + } + interface SymbolDisplayBuilder { + buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; + buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags): void; + buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + } + interface SymbolWriter { + writeKeyword(text: string): void; + writeOperator(text: string): void; + writePunctuation(text: string): void; + writeSpace(text: string): void; + writeStringLiteral(text: string): void; + writeParameter(text: string): void; + writeSymbol(text: string, symbol: Symbol): void; + writeLine(): void; + increaseIndent(): void; + decreaseIndent(): void; + clear(): void; + trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; + } + const enum TypeFormatFlags { + None = 0, + WriteArrayAsGenericType = 1, + UseTypeOfFunction = 2, + NoTruncation = 4, + WriteArrowStyleSignature = 8, + WriteOwnNameForAnyLike = 16, + WriteTypeArgumentsOfSignature = 32, + InElementType = 64, + UseFullyQualifiedType = 128, + } + const enum SymbolFormatFlags { + None = 0, + WriteTypeParametersOrArguments = 1, + UseOnlyExternalAliasing = 2, + } + interface TypePredicate { + parameterName: string; + parameterIndex: number; + type: Type; + } + const enum SymbolFlags { + None = 0, + FunctionScopedVariable = 1, + BlockScopedVariable = 2, + Property = 4, + EnumMember = 8, + Function = 16, + Class = 32, + Interface = 64, + ConstEnum = 128, + RegularEnum = 256, + ValueModule = 512, + NamespaceModule = 1024, + TypeLiteral = 2048, + ObjectLiteral = 4096, + Method = 8192, + Constructor = 16384, + GetAccessor = 32768, + SetAccessor = 65536, + Signature = 131072, + TypeParameter = 262144, + TypeAlias = 524288, + ExportValue = 1048576, + ExportType = 2097152, + ExportNamespace = 4194304, + Alias = 8388608, + Instantiated = 16777216, + Merged = 33554432, + Transient = 67108864, + Prototype = 134217728, + SyntheticProperty = 268435456, + Optional = 536870912, + ExportStar = 1073741824, + Enum = 384, + Variable = 3, + Value = 107455, + Type = 793056, + Namespace = 1536, + Module = 1536, + Accessor = 98304, + FunctionScopedVariableExcludes = 107454, + BlockScopedVariableExcludes = 107455, + ParameterExcludes = 107455, + PropertyExcludes = 107455, + EnumMemberExcludes = 107455, + FunctionExcludes = 106927, + ClassExcludes = 899519, + InterfaceExcludes = 792960, + RegularEnumExcludes = 899327, + ConstEnumExcludes = 899967, + ValueModuleExcludes = 106639, + NamespaceModuleExcludes = 0, + MethodExcludes = 99263, + GetAccessorExcludes = 41919, + SetAccessorExcludes = 74687, + TypeParameterExcludes = 530912, + TypeAliasExcludes = 793056, + AliasExcludes = 8388608, + ModuleMember = 8914931, + ExportHasLocal = 944, + HasExports = 1952, + HasMembers = 6240, + BlockScoped = 418, + PropertyOrAccessor = 98308, + Export = 7340032, + } + interface Symbol { + flags: SymbolFlags; + name: string; + declarations?: Declaration[]; + valueDeclaration?: Declaration; + members?: SymbolTable; + exports?: SymbolTable; + } + interface SymbolTable { + [index: string]: Symbol; + } + const enum TypeFlags { + Any = 1, + String = 2, + Number = 4, + Boolean = 8, + Void = 16, + Undefined = 32, + Null = 64, + Enum = 128, + StringLiteral = 256, + TypeParameter = 512, + Class = 1024, + Interface = 2048, + Reference = 4096, + Tuple = 8192, + Union = 16384, + Intersection = 32768, + Anonymous = 65536, + Instantiated = 131072, + ObjectLiteral = 524288, + ESSymbol = 16777216, + StringLike = 258, + NumberLike = 132, + ObjectType = 80896, + UnionOrIntersection = 49152, + StructuredType = 130048, + } + interface Type { + flags: TypeFlags; + symbol?: Symbol; + } + interface StringLiteralType extends Type { + text: string; + } + interface ObjectType extends Type { + } + interface InterfaceType extends ObjectType { + typeParameters: TypeParameter[]; + outerTypeParameters: TypeParameter[]; + localTypeParameters: TypeParameter[]; + } + interface InterfaceTypeWithDeclaredMembers extends InterfaceType { + declaredProperties: Symbol[]; + declaredCallSignatures: Signature[]; + declaredConstructSignatures: Signature[]; + declaredStringIndexType: Type; + declaredNumberIndexType: Type; + } + interface TypeReference extends ObjectType { + target: GenericType; + typeArguments: Type[]; + } + interface GenericType extends InterfaceType, TypeReference { + } + interface TupleType extends ObjectType { + elementTypes: Type[]; + baseArrayType: TypeReference; + } + interface UnionOrIntersectionType extends Type { + types: Type[]; + } + interface UnionType extends UnionOrIntersectionType { + } + interface IntersectionType extends UnionOrIntersectionType { + } + interface TypeParameter extends Type { + constraint: Type; + } + const enum SignatureKind { + Call = 0, + Construct = 1, + } + interface Signature { + declaration: SignatureDeclaration; + typeParameters: TypeParameter[]; + parameters: Symbol[]; + typePredicate?: TypePredicate; + } + const enum IndexKind { + String = 0, + Number = 1, + } + interface DiagnosticMessage { + key: string; + category: DiagnosticCategory; + code: number; + } + /** + * A linked list of formatted diagnostic messages to be used as part of a multiline message. + * It is built from the bottom up, leaving the head to be the "main" diagnostic. + * While it seems that DiagnosticMessageChain is structurally similar to DiagnosticMessage, + * the difference is that messages are all preformatted in DMC. + */ + interface DiagnosticMessageChain { + messageText: string; + category: DiagnosticCategory; + code: number; + next?: DiagnosticMessageChain; + } + interface Diagnostic { + file: SourceFile; + start: number; + length: number; + messageText: string | DiagnosticMessageChain; + category: DiagnosticCategory; + code: number; + } + enum DiagnosticCategory { + Warning = 0, + Error = 1, + Message = 2, + } + const enum ModuleResolutionKind { + Classic = 1, + NodeJs = 2, + } + interface CompilerOptions { + allowNonTsExtensions?: boolean; + charset?: string; + declaration?: boolean; + diagnostics?: boolean; + emitBOM?: boolean; + help?: boolean; + init?: boolean; + inlineSourceMap?: boolean; + inlineSources?: boolean; + jsx?: JsxEmit; + listFiles?: boolean; + locale?: string; + mapRoot?: string; + module?: ModuleKind; + newLine?: NewLineKind; + noEmit?: boolean; + noEmitHelpers?: boolean; + noEmitOnError?: boolean; + noErrorTruncation?: boolean; + noImplicitAny?: boolean; + noLib?: boolean; + noResolve?: boolean; + out?: string; + outFile?: string; + outDir?: string; + preserveConstEnums?: boolean; + project?: string; + removeComments?: boolean; + rootDir?: string; + sourceMap?: boolean; + sourceRoot?: string; + suppressExcessPropertyErrors?: boolean; + suppressImplicitAnyIndexErrors?: boolean; + target?: ScriptTarget; + version?: boolean; + watch?: boolean; + isolatedModules?: boolean; + experimentalDecorators?: boolean; + experimentalAsyncFunctions?: boolean; + emitDecoratorMetadata?: boolean; + moduleResolution?: ModuleResolutionKind; + [option: string]: string | number | boolean; + } + const enum ModuleKind { + None = 0, + CommonJS = 1, + AMD = 2, + UMD = 3, + System = 4, + } + const enum JsxEmit { + None = 0, + Preserve = 1, + React = 2, + } + const enum NewLineKind { + CarriageReturnLineFeed = 0, + LineFeed = 1, + } + interface LineAndCharacter { + line: number; + character: number; + } + const enum ScriptTarget { + ES3 = 0, + ES5 = 1, + ES6 = 2, + Latest = 2, + } + const enum LanguageVariant { + Standard = 0, + JSX = 1, + } + interface ParsedCommandLine { + options: CompilerOptions; + fileNames: string[]; + errors: Diagnostic[]; + } + interface ModuleResolutionHost { + fileExists(fileName: string): boolean; + readFile(fileName: string): string; + } + interface ResolvedModule { + resolvedFileName: string; + isExternalLibraryImport?: boolean; + } + interface ResolvedModuleWithFailedLookupLocations { + resolvedModule: ResolvedModule; + failedLookupLocations: string[]; + } + interface CompilerHost extends ModuleResolutionHost { + getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile; + getCancellationToken?(): CancellationToken; + getDefaultLibFileName(options: CompilerOptions): string; + writeFile: WriteFileCallback; + getCurrentDirectory(): string; + getCanonicalFileName(fileName: string): string; + useCaseSensitiveFileNames(): boolean; + getNewLine(): string; + resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; + } + interface TextSpan { + start: number; + length: number; + } + interface TextChangeRange { + span: TextSpan; + newLength: number; + } +} +declare module "typescript" { + interface System { + args: string[]; + newLine: string; + useCaseSensitiveFileNames: boolean; + write(s: string): void; + readFile(path: string, encoding?: string): string; + writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; + watchFile?(path: string, callback: (path: string) => void): FileWatcher; + resolvePath(path: string): string; + fileExists(path: string): boolean; + directoryExists(path: string): boolean; + createDirectory(path: string): void; + getExecutingFilePath(): string; + getCurrentDirectory(): string; + readDirectory(path: string, extension?: string, exclude?: string[]): string[]; + getMemoryUsage?(): number; + exit(exitCode?: number): void; + } + interface FileWatcher { + close(): void; + } + var sys: System; +} +declare module "typescript" { + interface ErrorCallback { + (message: DiagnosticMessage, length: number): void; + } + interface Scanner { + getStartPos(): number; + getToken(): SyntaxKind; + getTextPos(): number; + getTokenPos(): number; + getTokenText(): string; + getTokenValue(): string; + hasExtendedUnicodeEscape(): boolean; + hasPrecedingLineBreak(): boolean; + isIdentifier(): boolean; + isReservedWord(): boolean; + isUnterminated(): boolean; + reScanGreaterToken(): SyntaxKind; + reScanSlashToken(): SyntaxKind; + reScanTemplateToken(): SyntaxKind; + scanJsxIdentifier(): SyntaxKind; + reScanJsxToken(): SyntaxKind; + scanJsxToken(): SyntaxKind; + scan(): SyntaxKind; + setText(text: string, start?: number, length?: number): void; + setOnError(onError: ErrorCallback): void; + setScriptTarget(scriptTarget: ScriptTarget): void; + setLanguageVariant(variant: LanguageVariant): void; + setTextPos(textPos: number): void; + lookAhead(callback: () => T): T; + tryScan(callback: () => T): T; + } + function tokenToString(t: SyntaxKind): string; + function getPositionOfLineAndCharacter(sourceFile: SourceFile, line: number, character: number): number; + function getLineAndCharacterOfPosition(sourceFile: SourceFile, position: number): LineAndCharacter; + function isWhiteSpace(ch: number): boolean; + function isLineBreak(ch: number): boolean; + function couldStartTrivia(text: string, pos: number): boolean; + function getLeadingCommentRanges(text: string, pos: number): CommentRange[]; + function getTrailingCommentRanges(text: string, pos: number): CommentRange[]; + /** Optionally, get the shebang */ + function getShebang(text: string): string; + function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; + function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; + function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; +} +declare module "typescript" { + function getDefaultLibFileName(options: CompilerOptions): string; + function textSpanEnd(span: TextSpan): number; + function textSpanIsEmpty(span: TextSpan): boolean; + function textSpanContainsPosition(span: TextSpan, position: number): boolean; + function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean; + function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean; + function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan; + function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean; + function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean; + function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number): boolean; + function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean; + function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan; + function createTextSpan(start: number, length: number): TextSpan; + function createTextSpanFromBounds(start: number, end: number): TextSpan; + function textChangeRangeNewSpan(range: TextChangeRange): TextSpan; + function textChangeRangeIsUnchanged(range: TextChangeRange): boolean; + function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange; + let unchangedTextChangeRange: TextChangeRange; + /** + * Called to merge all the changes that occurred across several versions of a script snapshot + * into a single change. i.e. if a user keeps making successive edits to a script we will + * have a text change from V1 to V2, V2 to V3, ..., Vn. + * + * This function will then merge those changes into a single change range valid between V1 and + * Vn. + */ + function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; + function getTypeParameterOwner(d: Declaration): Declaration; +} +declare module "typescript" { + function getNodeConstructor(kind: SyntaxKind): new () => Node; + function createNode(kind: SyntaxKind): Node; + function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; + function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean): SourceFile; + function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; +} +declare module "typescript" { + const version: string; + function findConfigFile(searchPath: string): string; + function resolveTripleslashReference(moduleName: string, containingFile: string): string; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; + function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; + function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; +} +declare module "typescript" { + function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readConfigFile(fileName: string): { + config?: any; + error?: Diagnostic; + }; + /** + * Parse the text of the tsconfig.json file + * @param fileName The path to the config file + * @param jsonText The text of the config file + */ + function parseConfigFileText(fileName: string, jsonText: string): { + config?: any; + error?: Diagnostic; + }; + /** + * Parse the contents of a config file (tsconfig.json). + * @param json The contents of the config file to parse + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseConfigFile(json: any, host: ParseConfigHost, basePath: string): ParsedCommandLine; +} +declare module "typescript" { + /** The version of the language service API */ + let servicesVersion: string; + interface Node { + getSourceFile(): SourceFile; + getChildCount(sourceFile?: SourceFile): number; + getChildAt(index: number, sourceFile?: SourceFile): Node; + getChildren(sourceFile?: SourceFile): Node[]; + getStart(sourceFile?: SourceFile): number; + getFullStart(): number; + getEnd(): number; + getWidth(sourceFile?: SourceFile): number; + getFullWidth(): number; + getLeadingTriviaWidth(sourceFile?: SourceFile): number; + getFullText(sourceFile?: SourceFile): string; + getText(sourceFile?: SourceFile): string; + getFirstToken(sourceFile?: SourceFile): Node; + getLastToken(sourceFile?: SourceFile): Node; + } + interface Symbol { + getFlags(): SymbolFlags; + getName(): string; + getDeclarations(): Declaration[]; + getDocumentationComment(): SymbolDisplayPart[]; + } + interface Type { + getFlags(): TypeFlags; + getSymbol(): Symbol; + getProperties(): Symbol[]; + getProperty(propertyName: string): Symbol; + getApparentProperties(): Symbol[]; + getCallSignatures(): Signature[]; + getConstructSignatures(): Signature[]; + getStringIndexType(): Type; + getNumberIndexType(): Type; + getBaseTypes(): ObjectType[]; + } + interface Signature { + getDeclaration(): SignatureDeclaration; + getTypeParameters(): Type[]; + getParameters(): Symbol[]; + getReturnType(): Type; + getDocumentationComment(): SymbolDisplayPart[]; + } + interface SourceFile { + getLineAndCharacterOfPosition(pos: number): LineAndCharacter; + getLineStarts(): number[]; + getPositionOfLineAndCharacter(line: number, character: number): number; + update(newText: string, textChangeRange: TextChangeRange): SourceFile; + } + /** + * Represents an immutable snapshot of a script at a specified time.Once acquired, the + * snapshot is observably immutable. i.e. the same calls with the same parameters will return + * the same values. + */ + interface IScriptSnapshot { + /** Gets a portion of the script snapshot specified by [start, end). */ + getText(start: number, end: number): string; + /** Gets the length of this script snapshot. */ + getLength(): number; + /** + * Gets the TextChangeRange that describe how the text changed between this text and + * an older version. This information is used by the incremental parser to determine + * what sections of the script need to be re-parsed. 'undefined' can be returned if the + * change range cannot be determined. However, in that case, incremental parsing will + * not happen and the entire document will be re - parsed. + */ + getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange; + /** Releases all resources held by this script snapshot */ + dispose?(): void; + } + module ScriptSnapshot { + function fromString(text: string): IScriptSnapshot; + } + interface PreProcessedFileInfo { + referencedFiles: FileReference[]; + importedFiles: FileReference[]; + ambientExternalModules: string[]; + isLibFile: boolean; + } + interface HostCancellationToken { + isCancellationRequested(): boolean; + } + interface LanguageServiceHost { + getCompilationSettings(): CompilerOptions; + getNewLine?(): string; + getProjectVersion?(): string; + getScriptFileNames(): string[]; + getScriptVersion(fileName: string): string; + getScriptSnapshot(fileName: string): IScriptSnapshot; + getLocalizedDiagnosticMessages?(): any; + getCancellationToken?(): HostCancellationToken; + getCurrentDirectory(): string; + getDefaultLibFileName(options: CompilerOptions): string; + log?(s: string): void; + trace?(s: string): void; + error?(s: string): void; + useCaseSensitiveFileNames?(): boolean; + resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; + } + interface LanguageService { + cleanupSemanticCache(): void; + getSyntacticDiagnostics(fileName: string): Diagnostic[]; + getSemanticDiagnostics(fileName: string): Diagnostic[]; + getCompilerOptionsDiagnostics(): Diagnostic[]; + /** + * @deprecated Use getEncodedSyntacticClassifications instead. + */ + getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; + /** + * @deprecated Use getEncodedSemanticClassifications instead. + */ + getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; + getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; + getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; + getCompletionsAtPosition(fileName: string, position: number): CompletionInfo; + getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails; + getQuickInfoAtPosition(fileName: string, position: number): QuickInfo; + getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan; + getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan; + getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems; + getRenameInfo(fileName: string, position: number): RenameInfo; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[]; + getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; + getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; + getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[]; + findReferences(fileName: string, position: number): ReferencedSymbol[]; + getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; + /** @deprecated */ + getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; + getNavigateToItems(searchValue: string, maxResultCount?: number): NavigateToItem[]; + getNavigationBarItems(fileName: string): NavigationBarItem[]; + getOutliningSpans(fileName: string): OutliningSpan[]; + getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; + getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; + getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number; + getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[]; + getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[]; + getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[]; + getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; + getEmitOutput(fileName: string): EmitOutput; + getProgram(): Program; + getSourceFile(fileName: string): SourceFile; + dispose(): void; + } + interface Classifications { + spans: number[]; + endOfLineState: EndOfLineState; + } + interface ClassifiedSpan { + textSpan: TextSpan; + classificationType: string; + } + interface NavigationBarItem { + text: string; + kind: string; + kindModifiers: string; + spans: TextSpan[]; + childItems: NavigationBarItem[]; + indent: number; + bolded: boolean; + grayed: boolean; + } + interface TodoCommentDescriptor { + text: string; + priority: number; + } + interface TodoComment { + descriptor: TodoCommentDescriptor; + message: string; + position: number; + } + class TextChange { + span: TextSpan; + newText: string; + } + interface TextInsertion { + newText: string; + /** The position in newText the caret should point to after the insertion. */ + caretOffset: number; + } + interface RenameLocation { + textSpan: TextSpan; + fileName: string; + } + interface ReferenceEntry { + textSpan: TextSpan; + fileName: string; + isWriteAccess: boolean; + } + interface DocumentHighlights { + fileName: string; + highlightSpans: HighlightSpan[]; + } + module HighlightSpanKind { + const none: string; + const definition: string; + const reference: string; + const writtenReference: string; + } + interface HighlightSpan { + fileName?: string; + textSpan: TextSpan; + kind: string; + } + interface NavigateToItem { + name: string; + kind: string; + kindModifiers: string; + matchKind: string; + isCaseSensitive: boolean; + fileName: string; + textSpan: TextSpan; + containerName: string; + containerKind: string; + } + interface EditorOptions { + IndentSize: number; + TabSize: number; + NewLineCharacter: string; + ConvertTabsToSpaces: boolean; + } + interface FormatCodeOptions extends EditorOptions { + InsertSpaceAfterCommaDelimiter: boolean; + InsertSpaceAfterSemicolonInForStatements: boolean; + InsertSpaceBeforeAndAfterBinaryOperators: boolean; + InsertSpaceAfterKeywordsInControlFlowStatements: boolean; + InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; + InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; + InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; + PlaceOpenBraceOnNewLineForFunctions: boolean; + PlaceOpenBraceOnNewLineForControlBlocks: boolean; + [s: string]: boolean | number | string; + } + interface DefinitionInfo { + fileName: string; + textSpan: TextSpan; + kind: string; + name: string; + containerKind: string; + containerName: string; + } + interface ReferencedSymbol { + definition: DefinitionInfo; + references: ReferenceEntry[]; + } + enum SymbolDisplayPartKind { + aliasName = 0, + className = 1, + enumName = 2, + fieldName = 3, + interfaceName = 4, + keyword = 5, + lineBreak = 6, + numericLiteral = 7, + stringLiteral = 8, + localName = 9, + methodName = 10, + moduleName = 11, + operator = 12, + parameterName = 13, + propertyName = 14, + punctuation = 15, + space = 16, + text = 17, + typeParameterName = 18, + enumMemberName = 19, + functionName = 20, + regularExpressionLiteral = 21, + } + interface SymbolDisplayPart { + text: string; + kind: string; + } + interface QuickInfo { + kind: string; + kindModifiers: string; + textSpan: TextSpan; + displayParts: SymbolDisplayPart[]; + documentation: SymbolDisplayPart[]; + } + interface RenameInfo { + canRename: boolean; + localizedErrorMessage: string; + displayName: string; + fullDisplayName: string; + kind: string; + kindModifiers: string; + triggerSpan: TextSpan; + } + interface SignatureHelpParameter { + name: string; + documentation: SymbolDisplayPart[]; + displayParts: SymbolDisplayPart[]; + isOptional: boolean; + } + /** + * Represents a single signature to show in signature help. + * The id is used for subsequent calls into the language service to ask questions about the + * signature help item in the context of any documents that have been updated. i.e. after + * an edit has happened, while signature help is still active, the host can ask important + * questions like 'what parameter is the user currently contained within?'. + */ + interface SignatureHelpItem { + isVariadic: boolean; + prefixDisplayParts: SymbolDisplayPart[]; + suffixDisplayParts: SymbolDisplayPart[]; + separatorDisplayParts: SymbolDisplayPart[]; + parameters: SignatureHelpParameter[]; + documentation: SymbolDisplayPart[]; + } + /** + * Represents a set of signature help items, and the preferred item that should be selected. + */ + interface SignatureHelpItems { + items: SignatureHelpItem[]; + applicableSpan: TextSpan; + selectedItemIndex: number; + argumentIndex: number; + argumentCount: number; + } + interface CompletionInfo { + isMemberCompletion: boolean; + isNewIdentifierLocation: boolean; + entries: CompletionEntry[]; + } + interface CompletionEntry { + name: string; + kind: string; + kindModifiers: string; + sortText: string; + } + interface CompletionEntryDetails { + name: string; + kind: string; + kindModifiers: string; + displayParts: SymbolDisplayPart[]; + documentation: SymbolDisplayPart[]; + } + interface OutliningSpan { + /** The span of the document to actually collapse. */ + textSpan: TextSpan; + /** The span of the document to display when the user hovers over the collapsed span. */ + hintSpan: TextSpan; + /** The text to display in the editor for the collapsed region. */ + bannerText: string; + /** + * Whether or not this region should be automatically collapsed when + * the 'Collapse to Definitions' command is invoked. + */ + autoCollapse: boolean; + } + interface EmitOutput { + outputFiles: OutputFile[]; + emitSkipped: boolean; + } + const enum OutputFileType { + JavaScript = 0, + SourceMap = 1, + Declaration = 2, + } + interface OutputFile { + name: string; + writeByteOrderMark: boolean; + text: string; + } + const enum EndOfLineState { + None = 0, + InMultiLineCommentTrivia = 1, + InSingleQuoteStringLiteral = 2, + InDoubleQuoteStringLiteral = 3, + InTemplateHeadOrNoSubstitutionTemplate = 4, + InTemplateMiddleOrTail = 5, + InTemplateSubstitutionPosition = 6, + } + enum TokenClass { + Punctuation = 0, + Keyword = 1, + Operator = 2, + Comment = 3, + Whitespace = 4, + Identifier = 5, + NumberLiteral = 6, + StringLiteral = 7, + RegExpLiteral = 8, + } + interface ClassificationResult { + finalLexState: EndOfLineState; + entries: ClassificationInfo[]; + } + interface ClassificationInfo { + length: number; + classification: TokenClass; + } + interface Classifier { + /** + * Gives lexical classifications of tokens on a line without any syntactic context. + * For instance, a token consisting of the text 'string' can be either an identifier + * named 'string' or the keyword 'string', however, because this classifier is not aware, + * it relies on certain heuristics to give acceptable results. For classifications where + * speed trumps accuracy, this function is preferable; however, for true accuracy, the + * syntactic classifier is ideal. In fact, in certain editing scenarios, combining the + * lexical, syntactic, and semantic classifiers may issue the best user experience. + * + * @param text The text of a line to classify. + * @param lexState The state of the lexical classifier at the end of the previous line. + * @param syntacticClassifierAbsent Whether the client is *not* using a syntactic classifier. + * If there is no syntactic classifier (syntacticClassifierAbsent=true), + * certain heuristics may be used in its place; however, if there is a + * syntactic classifier (syntacticClassifierAbsent=false), certain + * classifications which may be incorrectly categorized will be given + * back as Identifiers in order to allow the syntactic classifier to + * subsume the classification. + * @deprecated Use getLexicalClassifications instead. + */ + getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult; + getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; + } + /** + * The document registry represents a store of SourceFile objects that can be shared between + * multiple LanguageService instances. A LanguageService instance holds on the SourceFile (AST) + * of files in the context. + * SourceFile objects account for most of the memory usage by the language service. Sharing + * the same DocumentRegistry instance between different instances of LanguageService allow + * for more efficient memory utilization since all projects will share at least the library + * file (lib.d.ts). + * + * A more advanced use of the document registry is to serialize sourceFile objects to disk + * and re-hydrate them when needed. + * + * To create a default DocumentRegistry, use createDocumentRegistry to create one, and pass it + * to all subsequent createLanguageService calls. + */ + interface DocumentRegistry { + /** + * Request a stored SourceFile with a given fileName and compilationSettings. + * The first call to acquire will call createLanguageServiceSourceFile to generate + * the SourceFile if was not found in the registry. + * + * @param fileName The name of the file requested + * @param compilationSettings Some compilation settings like target affects the + * shape of a the resulting SourceFile. This allows the DocumentRegistry to store + * multiple copies of the same file for different compilation settings. + * @parm scriptSnapshot Text of the file. Only used if the file was not found + * in the registry and a new one was created. + * @parm version Current version of the file. Only used if the file was not found + * in the registry and a new one was created. + */ + acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile; + /** + * Request an updated version of an already existing SourceFile with a given fileName + * and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile + * to get an updated SourceFile. + * + * @param fileName The name of the file requested + * @param compilationSettings Some compilation settings like target affects the + * shape of a the resulting SourceFile. This allows the DocumentRegistry to store + * multiple copies of the same file for different compilation settings. + * @param scriptSnapshot Text of the file. + * @param version Current version of the file. + */ + updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile; + /** + * Informs the DocumentRegistry that a file is not needed any longer. + * + * Note: It is not allowed to call release on a SourceFile that was not acquired from + * this registry originally. + * + * @param fileName The name of the file to be released + * @param compilationSettings The compilation settings used to acquire the file + */ + releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; + reportStats(): string; + } + module ScriptElementKind { + const unknown: string; + const warning: string; + const keyword: string; + const scriptElement: string; + const moduleElement: string; + const classElement: string; + const localClassElement: string; + const interfaceElement: string; + const typeElement: string; + const enumElement: string; + const variableElement: string; + const localVariableElement: string; + const functionElement: string; + const localFunctionElement: string; + const memberFunctionElement: string; + const memberGetAccessorElement: string; + const memberSetAccessorElement: string; + const memberVariableElement: string; + const constructorImplementationElement: string; + const callSignatureElement: string; + const indexSignatureElement: string; + const constructSignatureElement: string; + const parameterElement: string; + const typeParameterElement: string; + const primitiveType: string; + const label: string; + const alias: string; + const constElement: string; + const letElement: string; + } + module ScriptElementKindModifier { + const none: string; + const publicMemberModifier: string; + const privateMemberModifier: string; + const protectedMemberModifier: string; + const exportedModifier: string; + const ambientModifier: string; + const staticModifier: string; + const abstractModifier: string; + } + class ClassificationTypeNames { + static comment: string; + static identifier: string; + static keyword: string; + static numericLiteral: string; + static operator: string; + static stringLiteral: string; + static whiteSpace: string; + static text: string; + static punctuation: string; + static className: string; + static enumName: string; + static interfaceName: string; + static moduleName: string; + static typeParameterName: string; + static typeAliasName: string; + static parameterName: string; + static docCommentTagName: string; + } + const enum ClassificationType { + comment = 1, + identifier = 2, + keyword = 3, + numericLiteral = 4, + operator = 5, + stringLiteral = 6, + regularExpressionLiteral = 7, + whiteSpace = 8, + text = 9, + punctuation = 10, + className = 11, + enumName = 12, + interfaceName = 13, + moduleName = 14, + typeParameterName = 15, + typeAliasName = 16, + parameterName = 17, + docCommentTagName = 18, + } + interface DisplayPartsSymbolWriter extends SymbolWriter { + displayParts(): SymbolDisplayPart[]; + } + function displayPartsToString(displayParts: SymbolDisplayPart[]): string; + function getDefaultCompilerOptions(): CompilerOptions; + interface TranspileOptions { + compilerOptions?: CompilerOptions; + fileName?: string; + reportDiagnostics?: boolean; + moduleName?: string; + renamedDependencies?: Map; + } + interface TranspileOutput { + outputText: string; + diagnostics?: Diagnostic[]; + sourceMapText?: string; + } + function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; + function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; + function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile; + let disableIncrementalParsing: boolean; + function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; + function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string; + function createDocumentRegistry(useCaseSensitiveFileNames?: boolean): DocumentRegistry; + function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo; + function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService; + function createClassifier(): Classifier; + /** + * Get the path of the default library files (lib.d.ts) as distributed with the typescript + * node package. + * The functionality is not supported if the ts module is consumed outside of a node module. + */ + function getDefaultLibFilePath(options: CompilerOptions): string; +} diff --git a/underscore/underscore-tests.ts b/underscore/underscore-tests.ts index e14bac94e..4fb680885 100644 --- a/underscore/underscore-tests.ts +++ b/underscore/underscore-tests.ts @@ -1,508 +1,508 @@ -/// - -declare var $: any; - -_.each([1, 2, 3], (num) => alert(num.toString())); -_.each({ one: 1, two: 2, three: 3 }, (value, key) => alert(value.toString())); - -_.map([1, 2, 3], (num) => num * 3); -_.map({ one: 1, two: 2, three: 3 }, (value, key) => value * 3); - -//var sum = _.reduce([1, 2, 3], (memo, num) => memo + num, 0); // https://typescript.codeplex.com/workitem/1960 -var sum = _.reduce([1, 2, 3], (memo, num) => memo + num, 0); -sum = _.reduce([1, 2, 3], (memo, num) => memo + num); // memo is optional #issue 5 github -sum = _.reduce({'a':'1', 'b':'2', 'c':'3'}, (memo, numstr) => memo + (+numstr)); - -var list = [[0, 1], [2, 3], [4, 5]]; -//var flat = _.reduceRight(list, (a, b) => a.concat(b), []); // https://typescript.codeplex.com/workitem/1960 -var flat = _.reduceRight(list, (a, b) => a.concat(b), []); - -module TestFind { - let array: {a: string}[] = [{a: 'a'}, {a: 'b'}]; - let list: _.List<{a: string}> = {0: {a: 'a'}, 1: {a: 'b'}, length: 2}; - let dict: _.Dictionary<{a: string}> = {a: {a: 'a'}, b: {a: 'b'}}; - let context = {}; - - { - let iterator = (value: {a: string}, index: number, list: _.List<{a: string}>) => value.a === 'b'; - let result: {a: string}; - - result = _.find<{a: string}>(array, iterator); - result = _.find<{a: string}>(array, iterator, context); - result = _.find<{a: string}, {a: string}>(array, {a: 'b'}); - result = _.find<{a: string}>(array, 'a'); - - result = _(array).find<{a: string}>(iterator); - result = _(array).find<{a: string}>(iterator, context); - result = _(array).find<{a: string}, {a: string}>({a: 'b'}); - result = _(array).find<{a: string}>('a'); - - result = _(array).chain().find<{a: string}>(iterator).value(); - result = _(array).chain().find<{a: string}>(iterator, context).value(); - result = _(array).chain().find<{a: string}, {a: string}>({a: 'b'}).value(); - result = _(array).chain().find<{a: string}>('a').value(); - - result = _.find<{a: string}>(list, iterator); - result = _.find<{a: string}>(list, iterator, context); - result = _.find<{a: string}, {a: string}>(list, {a: 'b'}); - result = _.find<{a: string}>(list, 'a'); - - result = _(list).find<{a: string}>(iterator); - result = _(list).find<{a: string}>(iterator, context); - result = _(list).find<{a: string}, {a: string}>({a: 'b'}); - result = _(list).find<{a: string}>('a'); - - result = _(list).chain().find<{a: string}>(iterator).value(); - result = _(list).chain().find<{a: string}>(iterator, context).value(); - result = _(list).chain().find<{a: string}, {a: string}>({a: 'b'}).value(); - result = _(list).chain().find<{a: string}>('a').value(); - - result = _.detect<{a: string}>(array, iterator); - result = _.detect<{a: string}>(array, iterator, context); - result = _.detect<{a: string}, {a: string}>(array, {a: 'b'}); - result = _.detect<{a: string}>(array, 'a'); - - result = _(array).detect<{a: string}>(iterator); - result = _(array).detect<{a: string}>(iterator, context); - result = _(array).detect<{a: string}, {a: string}>({a: 'b'}); - result = _(array).detect<{a: string}>('a'); - - result = _(array).chain().detect<{a: string}>(iterator).value(); - result = _(array).chain().detect<{a: string}>(iterator, context).value(); - result = _(array).chain().detect<{a: string}, {a: string}>({a: 'b'}).value(); - result = _(array).chain().detect<{a: string}>('a').value(); - - result = _.detect<{a: string}>(list, iterator); - result = _.detect<{a: string}>(list, iterator, context); - result = _.detect<{a: string}, {a: string}>(list, {a: 'b'}); - result = _.detect<{a: string}>(list, 'a'); - - result = _(list).detect<{a: string}>(iterator); - result = _(list).detect<{a: string}>(iterator, context); - result = _(list).detect<{a: string}, {a: string}>({a: 'b'}); - result = _(list).detect<{a: string}>('a'); - - result = _(list).chain().detect<{a: string}>(iterator).value(); - result = _(list).chain().detect<{a: string}>(iterator, context).value(); - result = _(list).chain().detect<{a: string}, {a: string}>({a: 'b'}).value(); - result = _(list).chain().detect<{a: string}>('a').value(); - } - - { - let iterator = (element: {a: string}, key: string, list: _.Dictionary<{a: string}>) => element.a === 'b'; - let result: {a: string}; - - result = _.find<{a: string}>(dict, iterator); - result = _.find<{a: string}>(dict, iterator, context); - result = _.find<{a: string}, {a: string}>(dict, {a: 'b'}); - result = _.find<{a: string}>(dict, 'a'); - - result = _(dict).find<{a: string}>(iterator); - result = _(dict).find<{a: string}>(iterator, context); - result = _(dict).find<{a: string}, {a: string}>({a: 'b'}); - result = _(dict).find<{a: string}>('a'); - - result = _(dict).chain().find<{a: string}>(iterator).value(); - result = _(dict).chain().find<{a: string}>(iterator, context).value(); - result = _(dict).chain().find<{a: string}, {a: string}>({a: 'b'}).value(); - result = _(dict).chain().find<{a: string}>('a').value(); - - result = _.detect<{a: string}>(dict, iterator); - result = _.detect<{a: string}>(dict, iterator, context); - result = _.detect<{a: string}, {a: string}>(dict, {a: 'b'}); - result = _.detect<{a: string}>(dict, 'a'); - - result = _(dict).detect<{a: string}>(iterator); - result = _(dict).detect<{a: string}>(iterator, context); - result = _(dict).detect<{a: string}, {a: string}>({a: 'b'}); - result = _(dict).detect<{a: string}>('a'); - - result = _(dict).chain().detect<{a: string}>(iterator).value(); - result = _(dict).chain().detect<{a: string}>(iterator, context).value(); - result = _(dict).chain().detect<{a: string}, {a: string}>({a: 'b'}).value(); - result = _(dict).chain().detect<{a: string}>('a').value(); - } - - { - let iterator = (value: string, index: number, list: _.List) => value === 'b'; - let result: string; - - result = _.find('abc', iterator); - result = _.find('abc', iterator, context); - - result = _('abc').find(iterator); - result = _('abc').find(iterator, context); - - result = _('abc').chain().find(iterator).value(); - result = _('abc').chain().find(iterator, context).value(); - - result = _.detect('abc', iterator); - result = _.detect('abc', iterator, context); - - result = _('abc').detect(iterator); - result = _('abc').detect(iterator, context); - - result = _('abc').chain().detect(iterator).value(); - result = _('abc').chain().detect(iterator, context).value(); - } -} - -var evens = _.filter([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0); - -var capitalLetters = _.filter({ a: 'a', b: 'B', c: 'C', d: 'd' }, l => l === l.toUpperCase()); - -var listOfPlays = [{ title: "Cymbeline", author: "Shakespeare", year: 1611 }, { title: "The Tempest", author: "Shakespeare", year: 1611 }, { title: "Other", author: "Not Shakespeare", year: 2012 }]; -_.where(listOfPlays, { author: "Shakespeare", year: 1611 }); - -var odds = _.reject([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0); - -_.every([true, 1, null, 'yes'], _.identity); - -_.any([null, 0, 'yes', false]); - -_.some([1, 2, 3, 4], l => l % 3 === 0); - -_.some({ a: 'a', b: 'B', c: 'C', d: 'd' }, l => l === l.toUpperCase()); - -_.contains([1, 2, 3], 3); - -_.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); - -var stooges = [{ name: 'moe', age: 40 }, { name: 'larry', age: 50 }, { name: 'curly', age: 60 }]; -_.pluck(stooges, 'name'); - -_.max(stooges, (stooge) => stooge.age); -_.min(stooges, (stooge) => stooge.age); - -var numbers = [10, 5, 100, 2, 1000]; -_.max(numbers); -_.min(numbers); - -_.sortBy([1, 2, 3, 4, 5, 6], (num) => Math.sin(num)); - - -_([1.3, 2.1, 2.4]).groupBy((e) => Math.floor(e)); -_.groupBy([1.3, 2.1, 2.4], (num) => Math.floor(num).toString()); -_.groupBy(['one', 'two', 'three'], 'length'); - -_.indexBy(stooges, 'age')['40'].age; -_(stooges).indexBy('age')['40'].name; -_(stooges) - .chain() - .indexBy('age') - .value()['40'].age; - -_.countBy([1, 2, 3, 4, 5], (num) => (num % 2 == 0) ? 'even' : 'odd'); - -_.shuffle([1, 2, 3, 4, 5, 6]); - -(function (a, b, c, d) { return _.toArray(arguments).slice(1); })(1, 2, 3, 4); - -_.size({ one: 1, two: 2, three: 3 }); - -_.partition([0, 1, 2, 3, 4, 5], (num) => {return num % 2 == 0 }); - -interface Family { - name: string; - relation: string; -} -var isUncleMoe = _.matches({ name: 'moe', relation: 'uncle' }); -_.filter([{ name: 'larry', relation: 'father' }, { name: 'moe', relation: 'uncle' }], isUncleMoe); - - - -/////////////////////////////////////////////////////////////////////////////////////// - -_.first([5, 4, 3, 2, 1]); -_.initial([5, 4, 3, 2, 1]); -_.last([5, 4, 3, 2, 1]); -_.rest([5, 4, 3, 2, 1]); -_.compact([0, 1, false, 2, '', 3]); - -_.flatten([1, 2, 3, 4]); -_.flatten([1, [2]]); - -// typescript doesn't like the elements being different -_.flatten([1, [2], [3, [[4]]]]); -_.flatten([1, [2], [3, [[4]]]], true); -_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); -_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); -_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); -_.difference([1, 2, 3, 4, 5], [5, 2, 10]); -_.uniq([1, 2, 1, 3, 1, 4]); -_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]); -var r = _.object(['moe', 'larry', 'curly'], [30, 40, 50]); -_.object([['moe', 30], ['larry', 40], ['curly', 50]]); -_.indexOf([1, 2, 3], 2); -_.lastIndexOf([1, 2, 3, 1, 2, 3], 2); -_.sortedIndex([10, 20, 30, 40, 50], 35); -_.range(10); -_.range(1, 11); -_.range(0, 30, 5); -_.range(0, 30, 5); -_.range(0); - -/////////////////////////////////////////////////////////////////////////////////////// - -var func = function (greeting) { return greeting + ': ' + this.name }; -// need a second var otherwise typescript thinks func signature is the above func type, -// instead of the newly returned _bind => func type. -var func2 = _.bind(func, { name: 'moe' }, 'hi'); -func2(); - -var buttonView = { - label: 'underscore', - onClick: function () { alert('clicked: ' + this.label); }, - onHover: function () { console.log('hovering: ' + this.label); } -}; -_.bindAll(buttonView); -$('#underscore_button').bind('click', buttonView.onClick); - -var fibonacci = _.memoize(function (n) { - return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); -}); - -var log = _.bind(console.log, console); -_.delay(log, 1000, 'logged later'); - -_.defer(function () { alert('deferred'); }); - -var updatePosition = (param:string) => alert('updating position... Param: ' + param); -var throttled = _.throttle(updatePosition, 100); -$(window).scroll(throttled); - -var calculateLayout = (param:string) => alert('calculating layout... Param: ' + param); -var lazyLayout = _.debounce(calculateLayout, 300); -$(window).resize(lazyLayout); - -var createApplication = (param:string) => alert('creating application... Param: ' + param); -var initialize = _.once(createApplication); -initialize("me"); -initialize("me"); - -var notes: any[]; -var render = () => alert("rendering..."); -var renderNotes = _.after(notes.length, render); -_.each(notes, (note) => note.asyncSave({ success: renderNotes })); - -var hello = function (name) { return "hello: " + name; }; -// can't use the same "hello" var otherwise typescript fails -var hello2 = _.wrap(hello, (func) => { return "before, " + func("moe") + ", after"; }); -hello2(); - -var greet = function (name) { return "hi: " + name; }; -var exclaim = function (statement) { return statement + "!"; }; -var welcome = _.compose(exclaim, greet); -welcome('moe'); - -var partialApplicationTestFunction = (a: string, b: number, c: boolean, d: string, e: number, f: string) => { } -var partialApplicationResult = _.partial(partialApplicationTestFunction, "", 1); -var parametersCanBeStubbed = _.partial(partialApplicationResult, _, _, _, ""); - -/////////////////////////////////////////////////////////////////////////////////////// - -_.keys({ one: 1, two: 2, three: 3 }); -_.values({ one: 1, two: 2, three: 3 }); -_.pairs({ one: 1, two: 2, three: 3 }); -_.invert({ Moe: "Moses", Larry: "Louis", Curly: "Jerome" }); -_.functions(_); -_.extend({ name: 'moe' }, { age: 50 }); -_.extendOwn({ name: 'moe'}, { age: 50 }); -_.assign({ name: 'moe'}, { age: 50 }); -_.pick({ name: 'moe', age: 50, userid: 'moe1' }, 'name', 'age'); -_.omit({ name: 'moe', age: 50, userid: 'moe1' }, 'name'); -_.omit({ name: 'moe', age: 50, userid: 'moe1' }, 'name', 'age'); -_.omit({ name: 'moe', age: 50, userid: 'moe1' }, ['name', 'age']); - -_.mapObject({ a: 1, b: 2 }, val => val * 2) === _.mapObject({ a: 2, b: 4 }, _.identity); -_.mapObject({ a: 1, b: 2 }, (val, key, o) => o[key] * 2) === _.mapObject({ a: 2, b: 4}, _.identity); -_.mapObject({ x: "string 1", y: "string 2" }, 'length') === _.mapObject({ x: "string 1", y: "string 2"}, _.property('length')); - -var iceCream = { flavor: "chocolate" }; -_.defaults(iceCream, { flavor: "vanilla", sprinkles: "lots" }); - -_.clone({ name: 'moe' }); -_.clone(['i', 'am', 'an', 'object!']); - -_([1, 2, 3, 4]) - .chain() - .filter((num) => { return num % 2 == 0; }) - .tap(alert) - .map((num) => { return num * num; }) - .value(); - -_.chain([1, 2, 3, 200]) - .filter((num) => { return num % 2 == 0; }) - .tap(alert) - .map((num) => { return num * num; }) - .value(); - -_.has({ a: 1, b: 2, c: 3 }, "b"); - -var moe = { name: 'moe', luckyNumbers: [13, 27, 34] }; -var clone = { name: 'moe', luckyNumbers: [13, 27, 34] }; -moe == clone; -_.isEqual(moe, clone); - -_.isEmpty([1, 2, 3]); -_.isEmpty({}); - -_.isElement($('body')[0]); - -(function () { return _.isArray(arguments); })(); -_.isArray([1, 2, 3]); - -_.isObject({}); -_.isObject(1); - -_.property('name')(moe); - - -// (() => { return _.isArguments(arguments); })(1, 2, 3); -_.isArguments([1, 2, 3]); - -_.isFunction(alert); - -_.isString("moe"); - -_.isNumber(8.4 * 5); - -_.isFinite(-101); - -_.isFinite(-Infinity); - -_.isBoolean(null); - -_.isDate(new Date()); - -_.isRegExp(/moe/); - -_.isNaN(NaN); -isNaN(undefined); -_.isNaN(undefined); - -_.isNull(null); -_.isNull(undefined); - -_.isUndefined((window).missingVariable); - -/////////////////////////////////////////////////////////////////////////////////////// - -var UncleMoe = { name: 'moe' }; -_.constant(UncleMoe)(); - -typeof _.now() === "number"; - -var underscore = _.noConflict(); - -var moe2 = { name: 'moe' }; -moe2 === _.identity(moe); - -var genie; -var r2 = _.times(3, (n) => { return n * n }); -_(3).times(function (n) { genie.grantWishNumber(n); }); - -_.random(0, 100); - -_.mixin({ - capitalize: function (string) { - return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase(); - } -}); -(_("fabio")).capitalize(); - -_.uniqueId('contact_'); - -_.escape('Curly, Larry & Moe'); - -var object = { cheese: 'crumpets', stuff: function () { return 'nonsense'; } }; -_.result(object, 'cheese'); - -_.result(object, 'stuff'); - -var compiled = _.template("hello: <%= name %>"); -compiled({ name: 'moe' }); -var list2 = "<% _.each(people, function(name) { %>
  • <%= name %>
  • <% }); %>"; -_.template(list2)({ people: ['moe', 'curly', 'larry'] }); -var template = _.template("<%- value %>"); -template({ value: '