diff --git a/.travis.yml b/.travis.yml index c8c468a417..07914721a9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: node_js node_js: - - 6.9.2 + - node sudo: false diff --git a/3d-bin-packing/3d-bin-packing-tests.ts b/3d-bin-packing/3d-bin-packing-tests.ts index 319624d597..8e394e46bb 100644 --- a/3d-bin-packing/3d-bin-packing-tests.ts +++ b/3d-bin-packing/3d-bin-packing-tests.ts @@ -1,5 +1,5 @@ import packer = require("3d-bin-packing"); -import samchon = require("samchon-framework"); +import samchon = require("samchon"); function main(): void { diff --git a/3d-bin-packing/index.d.ts b/3d-bin-packing/index.d.ts index 14228f3141..8165ea513e 100644 --- a/3d-bin-packing/index.d.ts +++ b/3d-bin-packing/index.d.ts @@ -1,20 +1,22 @@ -// Type definitions for 3d-bin-packing +// Type definitions for 3d-bin-packing v1.1.2 // Project: https://github.com/betterwaysystems/packer // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 -/// -/// -/// -/// -/// +/// declare module "3d-bin-packing" { - export = bws.packer; + export = bws.packer; +} + +/// +/// +declare namespace bws.packer { + export import library = samchon.library; + export import protocol = samchon.protocol; + function _Test(): void; } -declare var ReactDataGrid: typeof AdazzleReactDataGrid.ReactDataGrid; declare namespace boxologic { /** *

An abstract instance of boxologic.

@@ -62,122 +64,6 @@ declare namespace boxologic { constructor(width: number, height: number, length: number); } } -declare namespace bws.packer { - /** - * @brief Packer, a solver of 3d bin packing with multiple wrappers. - * - * @details - *

Packer is a facade class supporting packing operations in user side. You can solve a packing problem - * by constructing Packer class with {@link WrapperArray wrappers} and {@link InstanceArray instances} to - * pack and executing {@link optimize Packer.optimize()} method.

- * - *

In background side, deducting packing solution, those algorithms are used.

- * - * - * @author Jeongho Nam - */ - class Packer extends samchon.protocol.Entity { - /** - * Candidate wrappers who can contain instances. - */ - protected wrapperArray: WrapperArray; - /** - * Instances trying to pack into the wrapper. - */ - protected instanceArray: InstanceArray; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from members. - * - * @param wrapperArray Candidate wrappers who can contain instances. - * @param instanceArray Instances to be packed into some wrappers. - */ - constructor(wrapperArray: WrapperArray, instanceArray: InstanceArray); - /** - * @inheritdoc - */ - construct(xml: samchon.library.XML): void; - /** - * Get wrapperArray. - */ - getWrapperArray(): WrapperArray; - /** - * Get instanceArray. - */ - getInstanceArray(): InstanceArray; - /** - *

Deduct - * - */ - optimize(): WrapperArray; - /** - * @brief Initialize sequence list (gene_array). - * - * @details - *

Deducts initial sequence list by such assumption:

- * - *
    - *
  • Cost of larger wrapper is less than smaller one, within framework of price per volume unit.
  • - *
      - *
    • Wrapper Larger: (price: $1,000, volume: 100cm^3 -> price per volume unit: $10 / cm^3)
    • - *
    • Wrapper Smaller: (price: $700, volume: 50cm^3 -> price per volume unit: $14 / cm^3)
    • - *
    • Larger's cost is less than Smaller, within framework of price per volume unit
    • - *
    - *
- * - *

Method {@link initGenes initGenes()} constructs {@link WrapperGroup WrapperGroups} corresponding - * with the {@link wrapperArray} and allocates {@link instanceArray instances} to a {@link WrapperGroup}, - * has the smallest cost between containbles.

- * - *

After executing packing solution by {@link WrapperGroup.optimize WrapperGroup.optimize()}, trying to - * {@link repack re-pack} each {@link WrapperGroup} to another type of {@link Wrapper}, deducts the best - * solution between them. It's the initial sequence list of genetic algorithm.

- * - * @return Initial sequence list. - */ - protected initGenes(): GAWrapperArray; - /** - * Try to repack each wrappers to another type. - * - * @param $wrappers Wrappers to repack. - * @return Re-packed wrappers. - */ - protected repack($wrappers: WrapperArray): WrapperArray; - /** - * @inheritdoc - */ - TAG(): string; - /** - * @inheritdoc - */ - toXML(): samchon.library.XML; - } -} -declare namespace flex { - class TabNavigator extends React.Component { - render(): JSX.Element; - private handle_change(index, event); - } - class NavigatorContent extends React.Component { - render(): JSX.Element; - } - interface TabNavigatorProps extends React.Props { - selectedIndex?: number; - style?: React.CSSProperties; - } - interface NavigatorContentProps extends React.Props { - label: string; - } -} declare namespace boxologic { /** * A box, trying to pack into a {@link Pallet}. @@ -589,7 +475,7 @@ declare namespace bws.packer { * * @author Jeongho Nam */ - class PackerForm extends samchon.protocol.Entity { + class PackerForm extends protocol.Entity { /** * Form of Instances to pack. */ @@ -609,12 +495,12 @@ declare namespace bws.packer { * @param wrapperArray Type of Wrappers to be used. */ constructor(instanceFormArray: InstanceFormArray, wrapperArray: WrapperArray); - construct(xml: samchon.library.XML): void; + construct(xml: library.XML): void; optimize(): WrapperArray; getInstanceFormArray(): InstanceFormArray; getWrapperArray(): WrapperArray; TAG(): string; - toXML(): samchon.library.XML; + toXML(): library.XML; toPacker(): Packer; } /** @@ -622,12 +508,12 @@ declare namespace bws.packer { * * @author Jeongho Nam */ - class InstanceFormArray extends samchon.protocol.EntityArrayCollection { + class InstanceFormArray extends protocol.EntityArrayCollection { /** * Default Constructor. */ constructor(); - createChild(xml: samchon.library.XML): InstanceForm; + createChild(xml: library.XML): InstanceForm; TAG(): string; CHILD_TAG(): string; /** @@ -645,7 +531,7 @@ declare namespace bws.packer { * * @author Jeongho Nam */ - class InstanceForm extends samchon.protocol.Entity { + class InstanceForm extends protocol.Entity { /** * A duplicated Instance. */ @@ -661,7 +547,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - construct(xml: samchon.library.XML): void; + construct(xml: library.XML): void; private createInstance(xml); key(): any; getInstance(): Instance; @@ -679,7 +565,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - toXML(): samchon.library.XML; + toXML(): library.XML; /** *

Repeated {@link instance} to {@link InstanceArray}. * @@ -694,7 +580,7 @@ declare namespace bws.packer { } } declare namespace bws.packer { - class WrapperArray extends samchon.protocol.EntityArrayCollection { + class WrapperArray extends protocol.EntityArrayCollection { /** * Default Constructor. */ @@ -702,7 +588,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - createChild(xml: samchon.library.XML): Wrapper; + createChild(xml: library.XML): Wrapper; /** * Get (calculate) price. */ @@ -756,7 +642,7 @@ declare namespace bws.packer { * * @author Jeongho Nam */ - interface Instance extends samchon.protocol.IEntity { + interface Instance extends protocol.IEntity { /** * Get name. */ @@ -813,7 +699,7 @@ declare namespace bws.packer { * * @author Jeongho Nam */ - class InstanceArray extends samchon.protocol.EntityArray { + class InstanceArray extends protocol.EntityArray { /** * Default Constructor. */ @@ -821,7 +707,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - createChild(xml: samchon.library.XML): Instance; + createChild(xml: library.XML): Instance; /** * @inheritdoc */ @@ -832,13 +718,113 @@ declare namespace bws.packer { CHILD_TAG(): string; } } +declare namespace bws.packer { + /** + * @brief Packer, a solver of 3d bin packing with multiple wrappers. + * + * @details + *

Packer is a facade class supporting packing operations in user side. You can solve a packing problem + * by constructing Packer class with {@link WrapperArray wrappers} and {@link InstanceArray instances} to + * pack and executing {@link optimize Packer.optimize()} method.

+ * + *

In background side, deducting packing solution, those algorithms are used.

+ * + * + * @author Jeongho Nam + */ + class Packer extends protocol.Entity { + /** + * Candidate wrappers who can contain instances. + */ + protected wrapperArray: WrapperArray; + /** + * Instances trying to pack into the wrapper. + */ + protected instanceArray: InstanceArray; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from members. + * + * @param wrapperArray Candidate wrappers who can contain instances. + * @param instanceArray Instances to be packed into some wrappers. + */ + constructor(wrapperArray: WrapperArray, instanceArray: InstanceArray); + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * Get wrapperArray. + */ + getWrapperArray(): WrapperArray; + /** + * Get instanceArray. + */ + getInstanceArray(): InstanceArray; + /** + *

Deduct + * + */ + optimize(): WrapperArray; + /** + * @brief Initialize sequence list (gene_array). + * + * @details + *

Deducts initial sequence list by such assumption:

+ * + *
    + *
  • Cost of larger wrapper is less than smaller one, within framework of price per volume unit.
  • + *
      + *
    • Wrapper Larger: (price: $1,000, volume: 100cm^3 -> price per volume unit: $10 / cm^3)
    • + *
    • Wrapper Smaller: (price: $700, volume: 50cm^3 -> price per volume unit: $14 / cm^3)
    • + *
    • Larger's cost is less than Smaller, within framework of price per volume unit
    • + *
    + *
+ * + *

Method {@link initGenes initGenes()} constructs {@link WrapperGroup WrapperGroups} corresponding + * with the {@link wrapperArray} and allocates {@link instanceArray instances} to a {@link WrapperGroup}, + * has the smallest cost between containbles.

+ * + *

After executing packing solution by {@link WrapperGroup.optimize WrapperGroup.optimize()}, trying to + * {@link repack re-pack} each {@link WrapperGroup} to another type of {@link Wrapper}, deducts the best + * solution between them. It's the initial sequence list of genetic algorithm.

+ * + * @return Initial sequence list. + */ + protected initGenes(): GAWrapperArray; + /** + * Try to repack each wrappers to another type. + * + * @param $wrappers Wrappers to repack. + * @return Re-packed wrappers. + */ + protected repack($wrappers: WrapperArray): WrapperArray; + /** + * @inheritdoc + */ + TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} declare namespace bws.packer { /** * A product. * * @author Jeongho Nam */ - class Product extends samchon.protocol.Entity implements Instance { + class Product extends protocol.Entity implements Instance { /** *

Name, key of the Product.

* @@ -921,7 +907,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - toXML(): samchon.library.XML; + toXML(): library.XML; } } declare namespace bws.packer { @@ -937,7 +923,7 @@ declare namespace bws.packer { * * @author Jeongho Nam */ - class Wrap extends samchon.protocol.Entity { + class Wrap extends protocol.Entity { /** * A wrapper wrapping the {@link instance}. */ @@ -962,10 +948,6 @@ declare namespace bws.packer { * Placement orientation of wrapped {@link instance}. */ protected orientation: number; - /** - * - */ - protected color: number; /** * Construct from a Wrapper. * @@ -996,7 +978,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - construct(xml: samchon.library.XML): void; + construct(xml: library.XML): void; /** * Factory method of wrapped Instance. * @@ -1058,11 +1040,11 @@ declare namespace bws.packer { /** * Get width. */ - getWidth(): number; + getLayoutWidth(): number; /** * Get height. */ - getHeight(): number; + getLayoutHeight(): number; /** * Get length. */ @@ -1071,9 +1053,9 @@ declare namespace bws.packer { * Get volume. */ getVolume(): number; - $instanceName: string; - $layoutScale: string; - $position: string; + readonly $instanceName: string; + readonly $layoutScale: string; + readonly $position: string; /** * @inheritdoc */ @@ -1081,19 +1063,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - toXML(): samchon.library.XML; - /** - * Thickness of boundary lines of a shape represents the {@link instance}. - */ - private static BOUNDARY_THICKNESS; - /** - * - * - * @param geometry - * - * @return A shape and its boundary lines as 3D-objects. - */ - toDisplayObjects(geometry: THREE.Geometry): std.Vector; + toXML(): library.XML; } } declare namespace bws.packer { @@ -1102,7 +1072,7 @@ declare namespace bws.packer { * * @author Jeongho Nam */ - class Wrapper extends samchon.protocol.EntityDeque implements Instance { + class Wrapper extends protocol.EntityDeque implements Instance { /** *

Name, key of the Wrapper.

* @@ -1151,11 +1121,10 @@ declare namespace bws.packer { * @param thickness A thickness causes shrinkness on containable volume. */ constructor(name: string, price: number, width: number, height: number, length: number, thickness: number); - construct(xml: samchon.library.XML): void; /** * @inheritdoc */ - createChild(xml: samchon.library.XML): Wrap; + createChild(xml: library.XML): Wrap; /** * Key of a Wrapper is its name. */ @@ -1232,7 +1201,7 @@ declare namespace bws.packer { * @return utilization ratio. */ getUtilization(): number; - equal_to(obj: Wrapper): boolean; + equals(obj: Wrapper): boolean; /** *

Wrapper is enough greater?

* @@ -1272,8 +1241,8 @@ declare namespace bws.packer { $height: string; $length: string; $thickness: string; - $scale: string; - $spaceUtilization: string; + readonly $scale: string; + readonly $spaceUtilization: string; /** * @inheritdoc */ @@ -1289,25 +1258,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - toXML(): samchon.library.XML; - private static scene; - private static renderer; - private static camera; - private static trackball; - private static mouse; - private static BOUNDARY_THICKNESS; - /** - *

Convert to a canvas containing 3D elements.

- * - * @param endIndex - * - * @return A 3D-canvans printing the Wrapper and its children {@link Wrap wrapped} - * {@link Instance instances} with those boundary lines. - */ - toCanvas(endIndex?: number): HTMLCanvasElement; - private static handleMouseMove(event); - private static animate(); - private static render(); + toXML(): library.XML; } } declare namespace bws.packer { @@ -1430,72 +1381,3 @@ declare namespace bws.packer { TAG(): string; } } -declare namespace bws.packer { - abstract class Editor extends React.Component<{ - dataProvider: samchon.protocol.EntityArrayCollection; - }, {}> { - private columns; - private selected_index; - /** - * Default Constructor. - */ - constructor(); - protected abstract createColumns(): AdazzleReactDataGrid.Column[]; - private get_row(index); - private insert_instance(event); - private erase_instances(event); - private handle_data_change(event); - private handle_row_change(event); - private handle_select(event); - render(): JSX.Element; - } -} -declare namespace bws.packer { - interface ItemEditorProps extends React.Props { - application: PackerApplication; - instances: InstanceFormArray; - wrappers: WrapperArray; - } - class ItemEditor extends React.Component { - private clear(event); - private open(event); - private save(event); - private pack(event); - render(): JSX.Element; - } - class InstanceEditor extends Editor { - protected createColumns(): AdazzleReactDataGrid.Column[]; - } - class WrapperEditor extends Editor { - protected createColumns(): AdazzleReactDataGrid.Column[]; - } -} -declare namespace bws.packer { - class PackerApplication extends React.Component<{}, {}> { - private instances; - private wrappers; - private result; - /** - * Default Constructor. - */ - constructor(); - pack(): void; - drawWrapper(wrapper: Wrapper, index?: number): void; - render(): JSX.Element; - static main(): void; - } -} -declare namespace bws.packer { - class ResultViewer extends React.Component { - drawWrapper(wrapper: Wrapper, index?: number): void; - private clear(event); - private open(event); - private save(event); - refresh(): void; - render(): JSX.Element; - } - interface WrapperViewerProps extends React.Props { - application: PackerApplication; - wrappers: WrapperArray; - } -} diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 6e2c883f3a..c3218efb0a 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -811,8 +811,8 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](jquery.cookie/jquery.cookie.d.ts) [jQuery Cookie Plugin](https://github.com/carhartl/jquery-cookie) by [Roy Goode](https://github.com/RoyGoode), [Ben Lorantfy](https://github.com/BenLorantfy) * [:link:](jquery-cropbox/jquery-cropbox.d.ts) [jQuery cropbox](https://github.com/acornejo/jquery-cropbox) by [Per Kastman](https://github.com/PerKastman) * [:link:](jquery.cycle2/jquery.cycle2.d.ts) [jQuery Cycle2 version (build 20140216)](http://jquery.malsup.com/cycle2) by [Donny Nadolny](https://github.com/dnadolny) -* [:link:](jquery.dataTables/jquery.dataTables.d.ts) [JQuery DataTables](http://www.datatables.net) by [Kiarash Ghiaseddin](https://github.com/Silver-Connection/DefinitelyTyped), [Omid Rad](https://github.com/omidkrad), [Armin Sander](https://github.com/pragmatrix) -* [:link:](datatables-buttons/datatables-buttons.d.ts) [JQuery DataTables Buttons extension](http://datatables.net/extensions/buttons) by [Sam Germano](https://github.com/SammyG4Free) +* [:link:](datatables.net/index.d.ts) [JQuery DataTables](http://www.datatables.net) by [Kiarash Ghiaseddin](https://github.com/Silver-Connection/DefinitelyTyped), [Omid Rad](https://github.com/omidkrad), [Armin Sander](https://github.com/pragmatrix) +* [:link:](datatables.net-buttons/index.d.ts) [JQuery DataTables Buttons extension](http://datatables.net/extensions/buttons) by [Sam Germano](https://github.com/SammyG4Free) * [:link:](jquery.fileupload/jquery.fileupload.d.ts) [jQuery File Upload Plugin](https://github.com/blueimp/jQuery-File-Upload) by [Rob Alarcon](https://github.com/rob-alarcon) * [:link:](jquery.joyride/jquery.joyride.d.ts) [jQuery JoyRide Plugin](https://github.com/zurb/joyride) by [Vincent Bortone](https://github.com/vbortone) * [:link:](jqgrid/jqgrid.d.ts) [jQuery jqgrid Plugin](https://github.com/tonytomov/jqGrid) by [Lokesh Peta](https://github.com/lokeshpeta) diff --git a/acorn/acorn-tests.ts b/acorn/acorn-tests.ts index fb79d23718..72ca71d2f6 100644 --- a/acorn/acorn-tests.ts +++ b/acorn/acorn-tests.ts @@ -1,5 +1,3 @@ -/// - import acorn = require('acorn'); import * as ESTree from 'estree'; @@ -67,3 +65,6 @@ acorn.getLineInfo('string', 56); acorn.plugins['test'] = function (p: acorn.Parser, config: any) { } + +acorn.tokenizer('console.log("hello world)', {locations: true}).getToken(); +acorn.tokenizer('console.log("hello world)', {locations: true})[Symbol.iterator]().next(); diff --git a/acorn/index.d.ts b/acorn/index.d.ts index 1944abc257..441deb29c3 100644 --- a/acorn/index.d.ts +++ b/acorn/index.d.ts @@ -238,9 +238,12 @@ declare namespace acorn { function parseExpressionAt(input: string, pos?: number, options?: Options): ESTree.Expression; - // todo: here the tokenizer function returns a Parser instance, that is targeting the detail of - // Parser prototype. Someone need this please reade README.md first. - // function tokenizer(options: Options, input: string): Parser; + interface ITokenizer { + getToken() : Token, + [Symbol.iterator](): Iterator + } + + function tokenizer(input: string, options: Options): ITokenizer; let parse_dammit: IParse | undefined; let LooseParser: ILooseParserClass | undefined; diff --git a/amplify/amplify-tests.ts b/amplify/amplify-tests.ts index edf2988122..b4f98ccd5b 100644 --- a/amplify/amplify-tests.ts +++ b/amplify/amplify-tests.ts @@ -1,6 +1,3 @@ - -/// - import amplify = require("amplify"); // Copied examples directly from AmplifyJs site diff --git a/angular-bootstrap-calendar/angular-bootstrap-calendar-tests.ts b/angular-bootstrap-calendar/angular-bootstrap-calendar-tests.ts index 4ff5b4cf19..1efc5d0391 100644 --- a/angular-bootstrap-calendar/angular-bootstrap-calendar-tests.ts +++ b/angular-bootstrap-calendar/angular-bootstrap-calendar-tests.ts @@ -1,6 +1,3 @@ -/// -/// - var myApp = angular.module('testModule'); interface MyAppScope extends ng.IScope { diff --git a/angular-dynamic-locale/angular-dynamic-locale-tests.ts b/angular-dynamic-locale/angular-dynamic-locale-tests.ts index fd88de0d25..1e30aafd94 100644 --- a/angular-dynamic-locale/angular-dynamic-locale-tests.ts +++ b/angular-dynamic-locale/angular-dynamic-locale-tests.ts @@ -15,6 +15,9 @@ class LocaleTestController { var newLocale = "mt" tmhDynamicLocaleService.set(newLocale); + + newLocale = "en"; + tmhDynamicLocaleService.set(newLocale).then((value) => {}); } } diff --git a/angular-dynamic-locale/index.d.ts b/angular-dynamic-locale/index.d.ts index 788c3ad87b..4ee0e6eb89 100644 --- a/angular-dynamic-locale/index.d.ts +++ b/angular-dynamic-locale/index.d.ts @@ -11,7 +11,7 @@ declare module 'angular' { export namespace dynamicLocale { interface tmhDynamicLocaleService { - set(locale: string): void; + set(locale: string): angular.IPromise; get(): string; } diff --git a/angular-feature-flags/angular-feature-flags-tests.ts b/angular-feature-flags/angular-feature-flags-tests.ts index 8ca17e4962..ac956dd657 100644 --- a/angular-feature-flags/angular-feature-flags-tests.ts +++ b/angular-feature-flags/angular-feature-flags-tests.ts @@ -1,5 +1,3 @@ -/// - import * as angular from "angular"; let myApp = angular.module('myApp', ['feature-flags']); diff --git a/angular-hotkeys/angular-hotkeys-tests.ts b/angular-hotkeys/angular-hotkeys-tests.ts index 1f87ecefdf..c0bd9b974d 100644 --- a/angular-hotkeys/angular-hotkeys-tests.ts +++ b/angular-hotkeys/angular-hotkeys-tests.ts @@ -1,5 +1,3 @@ -/// - var scope: ng.IScope; var hotkeyProvider: ng.hotkeys.HotkeysProvider; var hotkeyObj: ng.hotkeys.Hotkey; diff --git a/angular-jwt/angular-jwt-tests.ts b/angular-jwt/angular-jwt-tests.ts index b20b2eea9d..88b177ba74 100644 --- a/angular-jwt/angular-jwt-tests.ts +++ b/angular-jwt/angular-jwt-tests.ts @@ -1,5 +1,3 @@ -/// - var app = angular.module("angular-jwt-tests", ["angular-jwt"]); var $jwtHelper: ng.jwt.IJwtHelper; diff --git a/angular-modal/angular-modal-tests.ts b/angular-modal/angular-modal-tests.ts index 5be313840b..edb4d7e6ef 100644 --- a/angular-modal/angular-modal-tests.ts +++ b/angular-modal/angular-modal-tests.ts @@ -1,5 +1,3 @@ -/// - var btfModal: angularModal.AngularModalFactory; // Using template URL diff --git a/angular-oauth2/angular-oauth2-tests.ts b/angular-oauth2/angular-oauth2-tests.ts new file mode 100644 index 0000000000..042fe537aa --- /dev/null +++ b/angular-oauth2/angular-oauth2-tests.ts @@ -0,0 +1,10 @@ +import * as angular from 'angular'; + +angular.module('angular-oauth2-test', ['angular-oauth2']) + .config(['OAuthProvider', (OAuthProvider: angular.oauth2.OAuthProvider) => { + OAuthProvider.configure({ + baseUrl: 'https://api.website.com', + clientId: 'CLIENT_ID', + clientSecret: 'CLIENT_SECRET' // optional + }); + }]); \ No newline at end of file diff --git a/angular-oauth2/index.d.ts b/angular-oauth2/index.d.ts new file mode 100644 index 0000000000..e6b9592874 --- /dev/null +++ b/angular-oauth2/index.d.ts @@ -0,0 +1,49 @@ +// Type definitions for angular-oauth2 4.1 +// Project: https://github.com/oauthjs/angular-oauth2 +// Definitions by: Antério Vieira +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as angular from 'angular'; + +declare module 'angular' { + export namespace oauth2 { + interface OAuthConfig { + baseUrl: string; + clientId: string; + clientSecret?: string; + grantPath?: string; + revokePath?: string; + } + + interface OAuthProvider { + configure(params: OAuthConfig): OAuthConfig; + } + + interface Data { + username: string; + password: string; + } + + interface OAuth { + isAuthenticated(): boolean; + getAccessToken(data: Data, options?: any): angular.IPromise; + getRefreshToken(data?: Data, options?: any): angular.IPromise; + revokeToken(data?: Data, options?: any): angular.IPromise; + } + + interface OAuthTokenConfig { + name: string; + options: any; + } + + interface OAuthTokenOptions { + secure: boolean; + } + + interface OAuthTokenProvider { + configure(params: OAuthTokenConfig): OAuthTokenConfig; + } + + } +} + diff --git a/angular-oauth2/tsconfig.json b/angular-oauth2/tsconfig.json new file mode 100644 index 0000000000..e8a5250748 --- /dev/null +++ b/angular-oauth2/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "angular-oauth2-tests.ts" + ] +} diff --git a/fine-uploader/tslint.json b/angular-oauth2/tslint.json similarity index 100% rename from fine-uploader/tslint.json rename to angular-oauth2/tslint.json diff --git a/angular/angular-tests.ts b/angular/angular-tests.ts index 4e1f33ce47..b4e394aa37 100644 --- a/angular/angular-tests.ts +++ b/angular/angular-tests.ts @@ -587,7 +587,8 @@ namespace TestPromise { function test_angular_forEach() { const values: { [key: string]: string } = { name: 'misko', gender: 'male' }; const log: string[] = []; - angular.forEach(values, (value, key) => { + angular.forEach(values, (value, key, obj) => { + obj[key] = value; this.push(key + ': ' + value); }, log); // expect(log).toEqual(['name: misko', 'gender: male']); diff --git a/angular/index.d.ts b/angular/index.d.ts index bbbbdb021a..5d47751844 100644 --- a/angular/index.d.ts +++ b/angular/index.d.ts @@ -97,7 +97,7 @@ declare namespace angular { * @param iterator Iterator function. * @param context Object to become context (this) for the iterator function. */ - forEach(obj: T[], iterator: (value: T, key: number) => any, context?: any): any; + forEach(obj: T[], iterator: (value: T, key: number, obj: T[]) => void, context?: any): T[]; /** * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. * @@ -107,7 +107,7 @@ declare namespace angular { * @param iterator Iterator function. * @param context Object to become context (this) for the iterator function. */ - forEach(obj: { [index: string]: T; }, iterator: (value: T, key: string) => any, context?: any): any; + forEach(obj: { [index: string]: T; }, iterator: (value: T, key: string, obj: { [index: string]: T; }) => void, context?: any): { [index: string]: T; }; /** * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. * @@ -117,7 +117,7 @@ declare namespace angular { * @param iterator Iterator function. * @param context Object to become context (this) for the iterator function. */ - forEach(obj: any, iterator: (value: any, key: any) => any, context?: any): any; + forEach(obj: any, iterator: (value: any, key: any, obj: any) => void, context?: any): any; fromJson(json: string): any; identity(arg?: T): T; @@ -1332,9 +1332,19 @@ declare namespace angular { // see http://docs.angularjs.org/api/ng.$controller // see http://docs.angularjs.org/api/ng.$controllerProvider /////////////////////////////////////////////////////////////////////////// + + /** + * The minimal local definitions required by $controller(ctrl, locals) calls. + */ + interface IControllerLocals { + $scope: ng.IScope; + $element: JQuery; + } + interface IControllerService { // Although the documentation doesn't state this, locals are optional (controllerConstructor: new (...args: any[]) => T, locals?: any, later?: boolean, ident?: string): T; + (controllerConstructor: Function, locals?: IControllerLocals, later?: boolean, ident?: string): T; (controllerConstructor: Function, locals?: any, later?: boolean, ident?: string): T; (controllerName: string, locals?: any, later?: boolean, ident?: string): T; } diff --git a/antd/antd-tests.tsx b/antd/antd-tests.tsx deleted file mode 100644 index 1319455e91..0000000000 --- a/antd/antd-tests.tsx +++ /dev/null @@ -1,483 +0,0 @@ -/// - -/*import { - Affix, - Button, - Alert, - Badge, - Breadcrumb, - Calendar, - Carousel, - Cascader, - Checkbox, - Collapse, - DatePicker, - Dropdown, - Icon, - Form, - Input, - InputNumber, - Row, - Col, - Menu, - message, - Modal, - notification, - Pagination, - Popconfirm, - Popover, - Progress, - QueueAnim, - Radio, - Select, - Slider, - Spin, - Steps, - Switch, - Table, - Tabs, - Tag, - TimePicker, - Timeline, - Tooltip, - Transfer, - Tree, - TreeSelect, - Upload, - - - -} from 'antd';*/ - -import * as React from 'react' -import Affix from 'antd/lib/Affix' -import Button from 'antd/lib/Button' -import Alert from 'antd/lib/Alert' -import Badge from 'antd/lib/Badge' -import Breadcrumb from 'antd/lib/Breadcrumb' -import Calendar from 'antd/lib/Calendar' -import Carousel from 'antd/lib/Carousel' -import Cascader from 'antd/lib/Cascader' -import Checkbox from 'antd/lib/Checkbox' -import Collapse from 'antd/lib/Collapse' -import DatePicker from 'antd/lib/DatePicker' -import Dropdown from 'antd/lib/Dropdown' -import Icon from 'antd/lib/Icon' -import Form from 'antd/lib/Form' -import Input from 'antd/lib/Input' -import InputNumber from 'antd/lib/InputNumber' -import Row from 'antd/lib/Row' -import Col from 'antd/lib/Col' -import Menu from 'antd/lib/Menu' -import message from 'antd/lib/message' -import Modal from 'antd/lib/Modal' -import notification from 'antd/lib/notification' -import Pagination from 'antd/lib/Pagination' -import Popconfirm from 'antd/lib/Popconfirm' -import Popover from 'antd/lib/Popover' -import Progress from 'antd/lib/Progress' -import QueueAnim from 'antd/lib/QueueAnim' -import Radio from 'antd/lib/Radio' -import Select from 'antd/lib/Select' -import Slider from 'antd/lib/Slider' -import Spin from 'antd/lib/Spin' -import Steps from 'antd/lib/Steps' -import Switch from 'antd/lib/Switch' -import Table from 'antd/lib/Table' -import Tabs from 'antd/lib/Tabs' -import Tag from 'antd/lib/Tag' -import TimePicker from 'antd/lib/TimePicker' -import Timeline from 'antd/lib/Timeline' -import Tooltip from 'antd/lib/Tooltip' -import Transfer from 'antd/lib/Transfer' -import Tree from 'antd/lib/Tree' -import TreeSelect from 'antd/lib/TreeSelect' -import Upload from 'antd/lib/Upload' - -const ButtonGroup = Button.Group; -const CheckboxGroup = Checkbox.Group; -const Panel = Collapse.Panel; -const RangePicker = DatePicker.RangePicker; -const MonthPicker = DatePicker.MonthPicker; -const DropdownButton = Dropdown.Button; -const SubMenu = Menu.SubMenu; -const MenuItemGroup = Menu.ItemGroup; -const ProgressCircle = Progress.Circle; -const ProgressLine = Progress.Line; -const RadioGroup = Radio.Group; -const Option = Select.Option; -const OptGroup = Select.OptGroup; -const Step = Steps.Step; -const FormItem = Form.Item; -const TabPane = Tabs.TabPane; -const TreeNode = Tree.TreeNode; -const TreeSelectTreeNode = TreeSelect.TreeNode; - -const onChange = () => { } - -const options = [{ - value: 'zhejiang', - label: '浙江', - children: [{ - value: 'hangzhou', - label: '杭州', - children: [{ - value: 'xihu', - label: '西湖', - }], - }], -}, { - value: 'jiangsu', - label: '江苏', - children: [{ - value: 'nanjing', - label: '南京', - children: [{ - value: 'zhonghuamen', - label: '中华门', - }], - }], - }]; - -const columns = [{ - title: '姓名', - dataIndex: 'name', - key: 'name', - render(text: any) { - return {text}; - } -}, { - title: '年龄', - dataIndex: 'age', - key: 'age', - }, { - title: '住址', - dataIndex: 'address', - key: 'address', - }, { - title: '操作', - key: 'operation', - render(text: any, record: any) { - return ( - - 操作一{record.name} - - 操作二 - - - 更多 - - - ); - } - }]; -const data = [{ - key: '1', - name: '胡彦斌', - age: 32, - address: '西湖区湖底公园1号' -}, { - key: '2', - name: '胡彦祖', - age: 42, - address: '西湖区湖底公园1号' - }, { - key: '3', - name: '李大嘴', - age: 32, - address: '西湖区湖底公园1号' - }]; - -// tests -class AccountForm extends React.Component{ - render() { - const { getFieldProps } = this.props.form; - return ( -
- - - - - - - - - - -
- ); - } -} - -var Account = Form.create()(AccountForm); - -// app -class App extends React.Component{ - render() { - message.success('success') - message.config({ top: 100 }) - message.destroy() - message.info('info', 1000) - message.error('error', 3500) - - Modal.info({ title: 'hello' }); - Modal.success({ cancelText: 'No' }) - notification.success({ - message: 'hello', - description: 'test' - }) - const props = { - name: 'file', - action: '/upload.do', - onChange(info: any) { - if (info.file.status !== 'uploading') { - console.log(info.file, info.fileList); - } - if (info.file.status === 'done') { - message.success(`${info.file.name} 上传成功。`); - } else if (info.file.status === 'error') { - message.error(`${info.file.name} 上传失败。`); - } - } - }; - return
- Affix - - - test - - - - - - - - - - - - 首页 - 应用中心 - 应用列表 - 某应用 - - - - - -

1

-

2

-

3

-

4

-
- - - - - - -

test1

-
- -

test2

-
- -

test3

-
-
- - - - Hello Dp
}> - - 触发链接 - - - dpb

} type="primary"> - 某功能按钮 -
- - - - - - - 导航一 - - - 导航 - 子菜单}> - - 选项1 - 选项2 - - - 选项3 - 选项4 - - - - - - - - - - , - - - remove - - Overlay} title="title"> - - - - - - - - - - - - - - - - - - -
demo1
-
demo2
-
demo3
-
demo4
-
- - - A - B - C - D - - - - - - - - - - - - - - - - - - - - , - - - - 选项卡一内容 - 选项卡二内容 - 选项卡三内容 - - - 标签一 - 标签二 - { } }>标签三 - 标签四(链接) - - - - - - 创建服务现场 2015-09-01 - 初步排除网络异常 2015-09-01 - 技术测试异常 2015-09-01 - 网络异常正在修复 2015-09-01 - - - - - 鼠标移上来就会出现提示 - - - - - - - - - - - - - - - sss} key="0-0-1-0" /> - - - - - - - - - - - - - - - - - - - sss} key="random3" /> - - - - - - } -} diff --git a/antd/index.d.ts b/antd/index.d.ts deleted file mode 100644 index f262eda45f..0000000000 --- a/antd/index.d.ts +++ /dev/null @@ -1,2083 +0,0 @@ -// Type definitions for Antd v0.12.10 -// Project: http://ant.design -// Definitions by: bang88 , Bruce Mitchener -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 - -/// - -declare namespace Antd { - // Affix - interface AffixProps { - /** - * 达到指定偏移量后触发 - */ - offset?: number - } - /** - * # Affix - * 将页面元素钉在可视范围。 - * ## 何时使用 - * 当内容区域比较长,需要滚动页面时,这部分内容对应的操作或者导航需要在滚动范围内始终展现。常用于侧边菜单和按钮组合。 - * 页面可视范围过小时,慎用此功能以免遮挡页面内容。 - */ - export class Affix extends React.Component { - render(): JSX.Element - } - - - // Alert - interface AlertProps { - /** - * 必选参数,指定警告提示的样式,有四种选择`success`、`info`、`warn`、`error` - */ - type: string, - /**可选参数,默认不显示关闭按钮 */ - closable?: boolean, - /**可选参数,自定义关闭按钮 */ - closeText?: React.ReactNode, - /**必选参数,警告提示内容 */ - message: React.ReactNode, - /**可选参数,警告提示的辅助性文字介绍 */ - description?: React.ReactNode, - /**可选参数,关闭时触发的回调函数 */ - onClose?: Function, - /**可选参数,是否显示辅助图标 */ - showIcon?: boolean - } - - - /** - * # Alert - * 警告提示,展现需要关注的信息。 - - * ## 何时使用 - - * - 当某个页面需要向用户显示警告的信息时。 - * - 非浮层的静态展现形式,始终展现,不会自动消失,用户可以点击关闭。 - * */ - export class Alert extends React.Component { - render(): JSX.Element - } - - - // Badge - /** - * #Badge - * - * 图标右上角的圆形徽标数字。 - - * ## 何时使用 - - * 一般出现在通知图标或头像的右上角,用于显示需要处理的消息条数,通过醒目视觉形式吸引用户处理。 - * - */ - export class Badge extends React.Component { - render(): JSX.Element - } - interface BadgeProps { - /** 展示的数字,大于 overflowCount 时显示为 `${overflowCount}+`,为 0 时隐藏*/ - count: number, - /** 展示封顶的数字值*/ - overflowCount?: number, - /** 不展示数字,只有一个小红点*/ - dot?: boolean - } - - - // Button - interface ButtonProps { - /** 设置按钮类型,可选值为 `primary` `ghost` 或者不设 */ - type?: ButtonType | string, - /** 设置按钮形状,可选值为 `circle` `circle-outline` 或者不设*/ - shape?: string, - /** 设置按钮大小,可选值为 `small` `large` 或者不设*/ - size?: string, - /** 设置 `button` 原生的 `type` 值,可选值请参考 HTML标准*/ - htmlType?: string, - /** `click` 事件的 handler*/ - onClick?: Function, - /** 设置按钮载入状态*/ - loading?: boolean, - /** 样式名*/ - className?: string, - } - - - enum ButtonType { - primary, - ghost, - dashed - } - - interface ButtonGroupProps { - /** 设置按钮大小,可选值为 `small` `large` 或者不设*/ - size?: string - - } - - /** - 可以将多个 `Button` 放入 `Button.Group` 的容器中。 - - 通过设置 `size` 为 `large` `small` 分别把按钮组合设为大、小尺寸。若不设置 `size`,则尺寸为中。*/ - class ButtonGroup extends React.Component { - render(): JSX.Element - } - - /** - * #Button - 按钮用于开始一个即时操作。 - - ## 何时使用 - - 标记了一个(或封装一组)操作命令,响应用户点击行为,触发相应的业务逻辑。*/ - export class Button extends React.Component { - static Group: typeof ButtonGroup - render(): JSX.Element - } - - - - // Breadcrumb - - interface BreadcrumbItemProps { - /** 链接,如不传则不可点击 */ - href?: string - } - export class BreadcrumbItem extends React.Component { - render(): JSX.Element - } - - interface BreadcrumbProps { - /** router 的路由栈信息 */ - routes?: Array, - /** 路由的参数*/ - params?: Object, - /** 分隔符自定义*/ - separator?: string | React.ReactNode - } - /** - * #Breadcrumb - 显示当前页面在系统层级结构中的位置,并能向上返回。 - - ## 何时使用 - - - 当系统拥有超过两级以上的层级结构时; - - 当需要告知用户“你在哪里”时; - - 当需要向上导航的功能时。*/ - export class Breadcrumb extends React.Component { - static Item: typeof BreadcrumbItem - render(): JSX.Element - } - - - // Calendar - interface CalendarProps { - /** 自定义渲染月单元格*/ - monthCellRender?: Function, - /** 自定义渲染日期单元格*/ - dateCellRender?: Function, - /** 是否全屏显示*/ - fullscreen?: boolean, - /** 国际化配置*/ - locale?: Object, - prefixCls?: string, - className?: string, - style?: Object, - /** 日期面板变化回调*/ - onPanelChange?: Function, - /** 展示日期*/ - value?: Date, - /** 默认展示日期*/ - defaultValue?: Date, - /** 初始模式,`month/year`*/ - mode?: string - } - /** - * #Calendar - 按照日历形式展示数据的容器。 - - ## 何时使用 - - 当数据是日期或按照日期划分时,例如日程、课表、价格日历等,农历等。目前支持年/月切换。 - */ - export class Calendar extends React.Component { - render(): JSX.Element - } - - - // Carousel - interface CarouselProps { - /** 动画效果函数,可取 scrollx, fade*/ - effect?: string, - /** 是否显示面板指示点*/ - dots?: boolean, - /** 垂直显示*/ - vertical?: boolean, - /** 是否自动切换*/ - autoplay?: boolean, - /** 动画效果*/ - easing?: string, - /** 切换面板的回调*/ - beforeChange?: Function, - /** 切换面板的回调*/ - afterChange?: Function - } - /** - * #Carousel - 旋转木马,一组轮播的区域。 - - ## 何时使用 - - - 当有一组平级的内容。 - - 当内容空间不足时,可以用走马灯的形式进行收纳,进行轮播展现。 - - 常用于一组图片或卡片轮播。 - */ - export class Carousel extends React.Component { - render(): JSX.Element - } - - - - // Cascader - interface CascaderProps { - /** 可选项数据源*/ - options: Object, - /** 默认的选中项*/ - defaultValue?: Array, - /** 指定选中项*/ - value?: Array, - /** 选择完成后的回调*/ - onChange?: Function, - /** 选择后展示的渲染函数*/ - displayRender?: Function, - /** 自定义样式*/ - style?: Object, - /** 自定义类名*/ - className?: string, - /** 自定义浮层类名*/ - popupClassName?: string, - /** 浮层预设位置:`bottomLeft` `bottomRight` `topLeft` `topRight` */ - popupPlacement?: string, - /** 输入框占位文本*/ - placeholder?: string, - /** 输入框大小,可选 `large` `default` `small` */ - size?: string, - /** 禁用*/ - disabled?: boolean, - /** 是否支持清除*/ - allowClear?: boolean - - } - /** - * #Cascader - 级联选择框。 - - - ## 何时使用 - - - 需要从一组相关联的数据集合进行选择,例如省市区,公司层级,事物分类等。 - - 从一个较大的数据集合中进行选择时,用多级分类进行分隔,方便选择。 - - 比起 Select 组件,可以在同一个浮层中完成选择,有较好的体验。*/ - export class Cascader extends React.Component { - render(): JSX.Element - } - - - - - // Checkbox - interface CheckboxProps { - /** 指定当前是否选中*/ - checked?: boolean, - /** 初始是否选中*/ - defaultChecked?: boolean, - /** 变化时回调函数*/ - onChange?: Function - } - - interface CheckboxGroupProps { - /** 默认选中的选项*/ - defaultValue?: Array, - /** 指定选中的选项*/ - value?: Array, - /** 指定可选项*/ - options?: Array, - /** 变化时回调函数*/ - onChange?: Function - } - /** Checkbox 组*/ - class CheckboxGroup extends React.Component { - render(): JSX.Element - } - /** - * #Checkbox - 多选框。 - - ## 何时使用 - - - 在一组可选项中进行多项选择时; - - 单独使用可以表示两种状态之间的切换,和 `switch` 类似。区别在于切换 `switch` 会直接触发状态改变,而 `checkbox` 一般用于状态标记,需要和提交操作配合。 - */ - export class Checkbox extends React.Component { - static Group: typeof CheckboxGroup - render(): JSX.Element - } - - - - // Collapse - - interface CollapseProps { - /** 当前激活 tab 面板的 key*/ - activeKey?: Array | string, - /** 初始化选中面板的key */ - defaultActiveKey?: Array, - /** 切换面板的回调*/ - onChange?: Function - - } - class CollapsePanel extends React.Component<{ - /** 对应 activeKey */ - key: string, - /** 面板头内容*/ - header: React.ReactNode | string - }, {}> { - render(): JSX.Element - } - /** - * #Collapse - 可以折叠/展开的内容区域。 - - ## 何时使用 - - - 对复杂区域进行分组和隐藏,保持页面的整洁。 - - `手风琴` 是一种特殊的折叠面板,只允许单个内容区域展开。*/ - export class Collapse extends React.Component { - static Panel: typeof CollapsePanel - render(): JSX.Element - } - - - - // DatePicker - interface DatePickerProps { - - value?: string | Date, - defaultValue?: string | Date, - /** 展示的日期格式,配置参考 [GregorianCalendarFormat](https://github.com/yiminghe/gregorian-calendar-format)*/ - format?: string, - /** 不可选择的日期*/ - disabledDate?: Function, - /** 时间发生变化的回调,发生在用户选择时间时*/ - onChange?: Function, - /** 禁用*/ - disabled?: boolean, - style?: Object, - /** 格外的弹出日历样式*/ - popupStyle?: Object, - /** 输入框大小,`large` 高度为 32px,`small` 为 22px,默认是 28px*/ - size?: string, - /** 国际化配置*/ - locale?: Object, - /** 增加时间选择功能*/ - showTime?: boolean, - /** 点击确定按钮的回调*/ - onOk?: Function, - /** 定义浮层的容器,默认为 body 上新建 div*/ - getCalendarContainer?: Function - - } - interface RangePickProps extends DatePickerProps { - - } - class RangePicker extends React.Component { - render(): JSX.Element - } - class MonthPicker extends React.Component { - render(): JSX.Element - } - /** - * #DatePicker - 输入或选择日期的控件。 - - ## 何时使用 - - 当用户需要输入一个日期,可以点击标准输入框,弹出日期面板进行选择。*/ - export class DatePicker extends React.Component, {}> { - static RangePicker: typeof RangePicker - static MonthPicker: typeof MonthPicker - render(): JSX.Element - } - - - - - // Dropdown - - interface DropdownProps { - /** 触发下拉的行为 ['click'] or ['hover']*/ - trigger?: Array, - /** 菜单节点*/ - overlay: React.ReactNode - - } - - class DropdownButton extends React.Component<{ - /** 按钮类型*/ - type?: string, - /** 点击左侧按钮的回调*/ - onClick?: Function, - /** 触发下拉的行为*/ - trigger?: string, - /** 菜单节点*/ - overlay: React.ReactNode - }, {}> { - render(): JSX.Element - } - /** - * #Dropdown - 向下弹出的列表。 - - ## 何时使用 - - 当页面上的操作命令过多时,用此组件可以收纳操作元素。点击或移入触点,会出现一个下拉菜单。可在列表中进行选择,并执行相应的命令。 - */ - export class Dropdown extends React.Component { - static Button: typeof DropdownButton - render(): JSX.Element - } - - - - // Form - - interface FormItemProps { - prefixCls?: string, - /** label 标签的文本*/ - label?: React.ReactNode, - /** label 标签布局,通 `` 组件,设置 `span` `offset` 值,如 `{span: 3, offset: 12}`*/ - labelCol?: Object, - /** 提示信息,如不设置,则会根据校验规则自动生成 */ - help?: React.ReactNode | boolean, - /** 额外的提示信息,和 help 类似,当需要错误信息和提示文案同时出现时,可以使用这个。*/ - extra?: string, - /** 是否必填,如不设置,则会根据校验规则自动生成 */ - validateStatus?: string, - /** 配合 validateStatus 属性使用,是否展示校验状态图标 */ - hasFeedback?: boolean, - /** 需要为输入控件设置布局样式时,使用该属性,用法同 labelCol*/ - wrapperCol?: Object, - className?: string, - required?: boolean, - id?: string - } - /** - 表单一定会包含表单域,表单域可以是输入控件,标准表单域,标签,下拉菜单,文本域等。 - - 这里我们分别封装了表单域 `` 和输入控件 ``。*/ - export class FormItem extends React.Component { - render(): JSX.Element - } - interface FormComponentProps { - form: CreateFormOptions - } - export class FormComponent extends React.Component { - render(): JSX.Element - } - - // function create - type CreateFormOptions = { - /** 获取一组输入控件的值,如不传入参数,则获取全部组件的值*/ - getFieldsValue(): (fieldNames?: Array) => any - /** 获取一个输入控件的值*/ - getFieldValue(): (fieldName: string) => any - /** 设置一组输入控件的值*/ - setFieldsValue(): (obj: Object) => void - /** 设置一组输入控件的值*/ - setFields(): (obj: Object) => void - /** 校验并获取一组输入域的值与 Error*/ - validateFields(): (fieldNames?: Array, options?: Object, callback?: (erros: any, values: any) => void) => any - /** 与 `validateFields` 相似,但校验完后,如果校验不通过的菜单域不在可见范围内,则自动滚动进可见范围 */ - validateFieldsAndScroll(): (fieldNames?: Array, options?: Object, callback?: (erros: any, values: any) => void) => any - /** 获取某个输入控件的 Error */ - getFieldError(): (name: string) => Object - /** 判断一个输入控件是否在校验状态*/ - isFieldValidating(): (name: string) => Object - /**重置一组输入控件的值与状态,如不传入参数,则重置所有组件*/ - resetFields(): (names?: Array) => void - - getFieldsValue(): (id: string, options: { - /** 子节点的值的属性,如 Checkbox 的是 'checked'*/ - valuePropName?: string, - /** 子节点的初始值,类型、可选值均由子节点决定*/ - initialValue?: any, - /** 收集子节点的值的时机*/ - trigger?: string, - /** 校验子节点值的时机*/ - validateTrigger?: string, - /** 校验规则,参见 [async-validator](https://github.com/yiminghe/async-validator) */ - rules?: Array, - /** 必填输入控件唯一标志*/ - id?: string - }) => Array - - - } - - interface ComponentDecorator { - (component: T): T; - } - interface FormProps { - prefixCls?: string, - /** 水平排列布局*/ - horizontal?: boolean, - /** 行内排列布局*/ - inline?: boolean, - /** 经 `Form.create()` 包装过的组件会自带 `this.props.form` 属性,直接传给 Form 即可*/ - form?: Object, - /** 数据验证成功后回调事件*/ - onSubmit?: (e: React.FormEvent
) => void, - } - /** - * #Form - 具有数据收集、校验和提交功能的表单,包含复选框、单选框、输入框、下拉选择框等元素。 - - ## 表单 - - 我们为 `form` 提供了以下两种排列方式: - - - 水平排列:可以实现 `label` 标签和表单控件的水平排列; - - 行内排列:使其表现为 `inline-block` 级别的控件。 - */ - export class Form extends React.Component { - static Item: typeof FormItem - static create(options?: { - /** - * 当 `Form.Item` 子节点的值发生改变时触发,可以把对应的值转存到 Redux store - */ - onFieldsChange?: (props: Object, fields: Array) => void, - /** 把 props 转为对应的值,可用于把 Redux store 中的值读出 */ - mapPropsToFields?: (props: Object) => void - }): ComponentDecorator - render(): JSX.Element - } - - - - - - // Icon - interface IconProps { - /** 图标类型*/ - type: string - } - /** - * #Icon - 有含义的矢量图形,每一个图标打倒一个敌人。 - - ## 图标的命名规范 - - 我们为每个图标赋予了语义化的命名,命名规则如下: - - - 实心和描线图标保持同名,用 `-o` 来区分,比如 `question-circle`(实心) 和 `question-circle-o`(描线); - - - 命名顺序:`[icon名]-[形状可选]-[描线与否]-[方向可选]`。 - - ## 如何使用 - - 使用 `` 标签声明组件,指定图标对应的 type 属性,示例代码如下: - - ```html - - ``` - - 最终会渲染为: - - ```html - - ```*/ - export class Icon extends React.Component { - render(): JSX.Element - } - - - - - // Input - interface InputProps { - /** 【必须】声明 input 类型,同原生 input 标签的 type 属性*/ - type?: string, - id: string | number, - /** 控件大小,默认值为 default 。注:标准表单内的输入框大小限制为 large。 {'large','default','small'}*/ - size?: string, - /** 是否禁用状态,默认为 false*/ - disabled?: boolean, - value?: any, - /** 设置初始默认值*/ - defaultValue?: any, - className?: string, - /** 带标签的 input,设置前置标签*/ - addonBefore?: React.ReactNode, - /** 带标签的 input,设置后置标签*/ - addonAfter?: React.ReactNode, - prefixCls?: string, - placeholder?: string - } - export class Input extends React.Component { - render(): JSX.Element - } - - - - - // InputNumber - interface InputNumberProps { - /** 最小值*/ - min: number, - /** 最大值*/ - max: number, - /** 当前值*/ - value?: number, - /** 每次改变步数*/ - step?: number, - /** 初始值*/ - defaultValue?: number, - /** 变化回调*/ - onChange?: Function, - /** 禁用*/ - disabled?: boolean, - /** 输入框大小*/ - size?: string - - } - /** - * #InputNumber - 通过鼠标或键盘,输入范围内的数值。 - - ## 何时使用 - - 当需要获取标准数值时。*/ - export class InputNumber extends React.Component { - render(): JSX.Element - } - - - // Layout - // Row - interface RowProps { - type?: string, - align?: string, - justify?: string, - className?: string - } - export class Row extends React.Component { - render(): JSX.Element - } - - // Col - interface ColProps { - span?: string, - order?: string, - offset?: string, - push?: string, - pull?: string, - className?: string - } - /** - 在多数业务情况下,Ant Design需要在设计区域内解决大量信息收纳的问题,因此在12栅格系统的基础上,我们将整个设计建议区域按照24等分的原则进行划分。 - - 划分之后的信息区块我们称之为“盒子”。建议横向排列的盒子数量最多四个,最少一个。“盒子”在整个屏幕上占比见上图。设计部分基于盒子的单位定制盒子内部的排版规则,以保证视觉层面的舒适感。 - - ## 概述 - - 布局的栅格化系统,我们是基于行(row)和列(col)来定义信息区块的外部框架,以保证页面的每个区域能够稳健地排布起来。下面简单介绍一下它的工作原理: - - * 通过`row`在水平方向建立一组`column`(简写col) - * 你的内容应当放置于`col`内,并且,只有`col`可以作为`row`的直接元素 - * 栅格系统中的列是指1到24的值来表示其跨越的范围。例如,三个等宽的列可以使用`.col-8`来创建 - * 如果一个`row`中的`col`总和超过24,那么多余的`col`会作为一个整体另起一行排列 - - ## Flex 布局 - - 我们的栅格化系统支持 Flex 布局,允许子元素在父节点内的水平对齐方式 - 居左、居中、居右、等宽排列、分散排列。子元素与子元素之间,支持顶部对齐、垂直居中对齐、底部对齐的方式。同时,支持使用 order 来定义元素的排列顺序。 - - Flex 布局是基于 24 栅格来定义每一个“盒子”的宽度,但排版则不拘泥于栅格。*/ - export class Col extends React.Component { - render(): JSX.Element - } - - - - - // Menu - interface MenuItemProps { - /** - * (是否禁用) - * - * @type {boolean} - */ - disabled?: boolean, - key: string - } - export class MenuItem extends React.Component { - render(): JSX.Element - } - - interface MenuSubMenuProps { - /** - * (子菜单项值) - * - * @type {(string | React.ReactNode)} - */ - title: string | React.ReactNode, - /** - * (子菜单的菜单项) - * - * @type {(MenuItem | MenuSubMenu)} - */ - children?: JSX.Element[] - } - export class MenuSubMenu extends React.Component { - render(): JSX.Element - } - - interface MenuItemGroupProps { - /** - * (分组标题) - * - * @type {(string | React.ReactNode)} - */ - title: string | React.ReactNode, - /** - * (分组的菜单项) - * - * @type {MenuItem} - */ - children?: JSX.Element[] - } - export class MenuItemGroup extends React.Component { - render(): JSX.Element - } - - - // enum - enum MenuTheme { - light, - dark - } - enum MenuMode { - vertical, - horizontal, - inline - } - interface MenuProps { - /** 主题颜色*/ - theme?: MenuTheme | string, - /** 菜单类型 enum: `vertical` `horizontal` `inline`*/ - mode?: MenuMode | string, - /** 当前选中的菜单项 key 数组*/ - selectedKeys?: Array, - /** 初始选中的菜单项 key 数组*/ - defaultSelectedKeys?: Array, - /** 当前展开的菜单项 key 数组*/ - openKeys?: Array, - /** 初始展开的菜单项 key 数组*/ - defaultOpenKeys?: Array, - /** - * 被选中时调用 - * - * @type {(item: any, key: string, selectedKeys: Array) => void} - */ - onSelect?: (item: any, key: string, selectedKeys: Array) => void, - /** 取消选中时调用*/ - onDeselect?: (item: any, key: string, selectedKeys: Array) => void, - /** 点击 menuitem 调用此函数*/ - onClick?: (item: any, key: string) => void, - /** 根节点样式*/ - style?: Object - } - /** - # Menu - 为页面和功能提供导航的菜单列表。 - - ## 何时使用 - - 导航菜单是一个网站的灵魂,用户依赖导航在各个页面中进行跳转。一般分为顶部导航和侧边导航,顶部导航提供全局性的类目和功能,侧边导航提供多级结构来收纳和排列网站架构。 - - 更多布局和导航的范例可以参考:[常用布局](/spec/layout)。*/ - export class Menu extends React.Component { - static Item: typeof MenuItem - static SubMenu: typeof MenuSubMenu - static ItemGroup: typeof MenuItemGroup - static Divider: typeof React.Component - render(): JSX.Element - } - - - - // Message - type MessageFunc = ( - /** 提示内容*/ - content: string, - /** 自动关闭的延时*/ - duration?: number - ) => void - /** - * #Message - 全局展示操作反馈信息。 - - ## 何时使用 - - - 可提供成功、警告和错误等反馈信息。 - - 顶部居中显示并自动消失,是一种不打断用户操作的轻量级提示方式。*/ - export const message: { - - success: MessageFunc - error: MessageFunc - info: MessageFunc - loading: MessageFunc - config: (options: { - /** - * 消息距离顶部的位置 - * - * @type {number} - */ - top: number - }) => void - destroy: () => void - } - - // Modal - type ModalFunc = (options: { - visible?: boolean, - title?: React.ReactNode | string, - onOk?: Function, - onCancel?: Function, - width?: string | number, - iconClassName?: string, - okText?: string, - cancelText?: string - }) => void - - interface ModalProps { - /** 对话框是否可见*/ - visible?: boolean, - /** 确定按钮 loading*/ - confirmLoading?: boolean, - /** 标题*/ - title?: React.ReactNode | string, - /** 是否显示右上角的关闭按钮*/ - closable?: boolean, - /** 点击确定回调*/ - onOk?: Function, - /** 点击遮罩层或右上角叉或取消按钮的回调*/ - onCancel?: Function, - /** 宽度*/ - width?: string | number, - /** 底部内容*/ - footer?: React.ReactNode | string, - /** 确认按钮文字*/ - okText?: string, - /** 取消按钮文字*/ - cancelText?: string, - /** 点击蒙层是否允许关闭*/ - maskClosable?: boolean - } - - /** - # Modal - 模态对话框。 - - ## 何时使用 - - 需要用户处理事务,又不希望跳转页面以致打断工作流程时,可以使用 `Modal` 在当前页面正中打开一个浮层,承载相应的操作。 - - 另外当需要一个简洁的确认框询问用户时,可以使用精心封装好的 `ant.Modal.confirm()` 等方法。*/ - export class Modal extends React.Component { - static info: ModalFunc - static success: ModalFunc - static error: ModalFunc - static confirm: ModalFunc - render(): JSX.Element - } - - - - - // Notification - type NotificationFunc = ( - config: { - /** 通知提醒标题,必选 */ - message: React.ReactNode | string, - /** 通知提醒内容,必选*/ - description: React.ReactNode | string, - /** 自定义关闭按钮*/ - btn?: React.ReactNode | string, - /** 当前通知唯一标志*/ - key?: string, - /** 点击默认关闭按钮时触发的回调函数*/ - onClose?: Function, - /** 默认 4.5 秒后自动关闭,配置为 null 则不自动关闭*/ - duration?: number - }) => void - /** - * #notification - 全局展示通知提醒信息。 - - ## 何时使用 - - 在系统右上角显示通知提醒信息。经常用于以下情况: - - - 较为复杂的通知内容。 - - 带有交互的通知,给出用户下一步的行动点。 - - 系统主动推送。*/ - export const notification: { - success: NotificationFunc - error: NotificationFunc - info: NotificationFunc - warn: NotificationFunc - close: (key: string) => void - destroy: () => void - config: (options: { - /** 消息距离顶部的位置*/ - top: number - }) => void - - } - - - - - // Pagination - interface PaginationProps { - /** 当前页数*/ - current?: number, - /** 默认的当前页数*/ - defaultCurrent?: number, - /** 数据总数*/ - total: number, - /** 初始的每页条数*/ - defaultPageSize?: number, - /** 每页条数*/ - pageSize?: number, - /** 页码改变的回调,参数是改变后的页码*/ - onChange?: Function, - /** 是否可以改变 pageSize */ - showSizeChanger?: boolean, - /** 指定每页可以显示多少条*/ - pageSizeOptions?: Array - /** pageSize 变化的回调 */ - onShowSizeChange?: Function, - /** 是否可以快速跳转至某页*/ - showQuickJumper?: boolean, - /** 当为「small」时,是小尺寸分页 */ - size?: string, - /** 当添加该属性时,显示为简单分页*/ - simple?: Object, - /** 用于显示总共有多少条数据*/ - showTotal?: Function - } - /** - * #Pagination - 采用分页的形式分隔长列表,每次只加载一个页面。 - - ## 何时使用 - - - 当加载/渲染所有数据将花费很多时间时; - - 可切换页码浏览数据。*/ - export class Pagination extends React.Component { - render(): JSX.Element - } - - - - - // Popconfirm - enum Placement { - top, left, right, bottom - } - interface PopconfirmProps { - /** - * 气泡框位置,可选 `top/left/right/bottom` - * - * @type {(Placement | string)} - */ - placement?: Placement | string, - /** 确认框的描述*/ - title?: string, - /** 点击确认的回调*/ - onConfirm?: Function, - onCancel?: Function, - /** 显示隐藏的回调*/ - onVisibleChange?: (visible: boolean) => void, - /** 确认按钮文字*/ - okText?: string, - /** 取消按钮文字*/ - cancelText?: string - } - /** - * #Popconfirm - 点击元素,弹出气泡式的确认框。 - - ## 何时使用 - - 目标元素的操作需要用户进一步的确认时,在目标元素附近弹出浮层提示,询问用户。 - - 和 `confirm` 弹出的全屏居中模态对话框相比,交互形式更轻量。 - */ - export class Popconfirm extends React.Component { - render(): JSX.Element - } - - - - - // Popover - enum Trigger { - hover, focus, click - } - enum PopoverPlacement { - top, - left, right, bottom, - topLeft, topRight, bottomLeft, bottomRight, - leftTop, leftBottom, rightTop, rightBottom - } - interface PopoverProps { - /** 触发行为,可选 `hover/focus/click` */ - trigger?: Trigger | string, - /** 气泡框位置,可选 `top/left/right/bottom` `topLeft/topRight/bottomLeft/bottomRight` `leftTop/leftBottom/rightTop/rightBottom`*/ - placement?: PopoverPlacement | string, - /** 卡片标题*/ - title?: React.ReactNode | string, - /** 卡片内容*/ - overlay?: React.ReactNode | string, - prefixCls?: string, - /** 用于手动控制浮层显隐*/ - visible?: boolean, - /** 显示隐藏改变的回调*/ - onVisibleChange?: Function - } - /** - * #Popover - 点击/鼠标移入元素,弹出气泡式的卡片浮层。 - - ## 何时使用 - - 当目标元素有进一步的描述和相关操作时,可以收纳到卡片中,根据用户的操作行为进行展现。 - - 和 `Tooltip` 的区别是,用户可以对浮层上的元素进行操作,因此它可以承载更复杂的内容,比如链接或按钮等。 - */ - export class Popover extends React.Component { - render(): JSX.Element - } - - - - - // Progress - enum ProgressStatus { - normal, - exception, - active - } - - interface LineProps { - /** 百分比*/ - percent: number, - /** 内容的模板函数*/ - format?: (percent: any) => void, - /** 状态,可选:normal、exception、active*/ - status?: ProgressStatus | string, - /** 进度条线的宽度,单位是px*/ - strokeWidth?: number, - /** 是否显示进度数值和状态图标*/ - showInfo?: boolean - } - export class Line extends React.Component { - render(): JSX.Element - } - - interface CircleProps { - /** 百分比*/ - percent: number, - /** 内容的模板函数*/ - format?: (percent: any) => void, - /** 状态,可选:normal、exception*/ - status?: ProgressStatus | string, - /** 进度条线的宽度,单位是进度条画布宽度的百分比*/ - strokeWidth?: number, - /** 必填,进度条画布宽度,单位px。这里没有提供height属性设置,Line型高度就是strokeWidth,Circle型高度等于width*/ - width?: number - } - export class Circle extends React.Component { - render(): JSX.Element - } - /** - * #Progress - 展示操作的当前进度。 - - ## 何时使用 - - 在操作需要较长时间才能完成时,为用户显示该操作的当前进度和状态。 - - * 当一个操作会打断当前界面,或者需要在后台运行,且耗时可能超过2秒时; - * 当需要显示一个操作完成的百分比时。*/ - export const Progress: { - Line: typeof Line, - Circle: typeof Circle - } - - - // QueueAnim - interface QueueAnimProps { - /** 动画内置参数 `left` `right` `top` `bottom` `scale` `scaleBig` `scaleX` `scaleY`*/ - type?: string | Array, - /** 配置动画参数 如 `{opacity:[1, 0],translateY:[0, -30]}` 具体参考 [velocity](http://julian.com/research/velocity) 的写法*/ - animConfig?: Object | Array, - /** 整个动画的延时,以毫秒为单位*/ - delay?: number | Array, - /** 每个动画的时间,以毫秒为单位*/ - duration?: number | Array, - /** 每个动画的间隔时间,以毫秒为单位*/ - interval?: number | Array, - /** 出场时是否倒放,从最后一个 dom 开始往上播放 */ - leaveReverse?: boolean, - /** 动画的缓动函数,[查看详细](http://julian.com/research/velocity/#easing)*/ - ease?: string | Array, - /** 进出场动画进行中的类名*/ - animatingClassName?: Array, - /** QueueAnim 替换的标签名*/ - component?: string - } - /** - * #QueueAnim - 通过简单的配置对一组元素添加串行的进场动画效果。 - - ## 何时使用 - - - 从内容A到内容B的转变过程时能有效的吸引用户注意力,突出视觉中心,提高整体视觉效果。 - - - 小的信息元素排布或块状较多的情况下,根据一定的路径层次依次进场,区分维度层级,来凸显量级,使页面转场更加流畅和舒适,提高整体视觉效果和产品的质感。 - - - 特别适合首页和需要视觉展示效果的宣传页,以及单页应用的切换页面动效。 - */ - export class QueueAnim extends React.Component { - render(): JSX.Element - } - - - - - // Radio - enum RadioGroupSize { - large, - default, - small - } - interface RadioGroupProps { - /** 选项变化时的回调函数*/ - onChange?: (e: Event) => void, - /** 用于设置当前选中的值*/ - value?: string, - /** 默认选中的值*/ - defaultValue?: string, - /** 大小,只对按钮样式生效*/ - size?: RadioGroupSize | string - } - export class RadioGroup extends React.Component { - render(): JSX.Element - } - - - interface RadioProps { - /** 指定当前是否选中*/ - checked?: boolean, - /** 初始是否选中*/ - defaultChecked?: boolean, - /** 根据 value 进行比较,判断是否选中 */ - value?: any - } - /** - * #Radio - 单选框。 - - ## 何时使用 - - - 用于在多个备选项中选中单个状态。 - - 和 Select 的区别是,Radio 所有选项默认可见,方便用户在比较中选择,因此选项不宜过多。 - */ - export class Radio extends React.Component { - static Group: typeof RadioGroup - static Button: typeof Button - render(): JSX.Element - } - - - - // Select - interface SelectOptionProps { - /** 是否禁用*/ - disabled?: boolean, - /** 如果 react 需要你设置此项,此项值与 value 的值相同,然后可以省略 value 设置*/ - key?: string, - /** 默认根据此属性值进行筛选*/ - value: string - } - export class SelectOption extends React.Component { - render(): JSX.Element - } - - interface SelectOptGroupProps { - /** 组名*/ - label: string | React.ReactNode, - key?: string - } - export class SelectOptGroup extends React.Component { - render(): JSX.Element - } - - interface SelectProps { - /** 指定当前选中的条目*/ - value?: string | Array, - /** 指定默认选中的条目*/ - defaultValue?: string | Array, - /** 支持多选*/ - multiple?: boolean, - /** 支持清除, 单选模式有效*/ - allowClear?: boolean, - /** 是否根据输入项进行筛选,可为一个函数,返回满足要求的 option 即可*/ - filterOption?: boolean | Function, - /** 可以把随意输入的条目作为 tag,输入项不需要与下拉选项匹配*/ - tags?: boolean, - /** 被选中时调用,参数为选中项的 value 值 */ - onSelect?: (value: any, option: any) => void, - /** 取消选中时调用,参数为选中项的 option value 值,仅在 multiple 或 tags 模式下生效*/ - onDeselect?: (value: any, option: any) => void, - /** 选中option,或input的value变化(combobox 模式下)时,调用此函数*/ - onChange?: (value: any, label: any) => void, - /** 文本框值变化时回调*/ - onSearch?: (value: string) => void, - /** 选择框默认文字*/ - placeholder?: string, - /** 搜索框默认文字*/ - searchPlaceholder?: string, - /** 当下拉列表为空时显示的内容*/ - notFoundContent?: string, - /** 下拉菜单和选择器同宽*/ - dropdownMatchSelectWidth?: boolean, - /** 搜索时过滤对应的 option 属性,如设置为 children 表示对内嵌内容进行搜索*/ - optionFilterProp?: string, - /** 输入框自动提示模式*/ - combobox?: SVGSymbolElement, - /** 选择框大小,可选 `large` `small` */ - size?: string, - /** 在下拉中显示搜索框*/ - showSearch?: boolean, - /** 是否禁用*/ - disabled?: boolean, - style?: Object - } - /** - * #Select - 类似 Select2 的选择器。 - - ## 何时使用 - - 弹出一个下拉菜单给用户选择操作,用于代替原生的选择器,或者需要一个更优雅的多选器时。*/ - export class Select extends React.Component { - static Option: typeof SelectOption - static OptGroup: typeof SelectOptGroup - render(): JSX.Element - } - - - - // Slider - interface SliderProps { - /** 最小值*/ - min?: number, - /** 最大值*/ - max?: number, - /** 步长,取值必须大于 0,并且可被 (max - min) 整除。当 `marks` 不为空对象时,可以设置 `step` 为 `null`,此时 Slider 的可选值仅有 marks 标出来的部分。*/ - step?: number, - /** 分段标记,key 的类型必须为 `Number` 且取值在闭区间 [min, max] 内*/ - marks?: { key: number, value: any }, - /** 设置当前取值。当 `range` 为 `false` 时,使用 `Number`,否则用 `[Number, Number]`*/ - value?: number | Array, - /** 设置当前取值。当 `range` 为 `false` 时,使用 `Number`,否则用 `[Number, Number]`*/ - defaultValue?: number | Array, - /** `marks` 不为空对象时有效,值为 true 时表示值为包含关系,false 表示并列*/ - included?: boolean, - /** 值为 `true` 时,滑块为禁用状态*/ - disabled?: boolean, - /** 当 `range` 为 `true` 时,该属性可以设置是否允许两个滑块交换位置。*/ - allowCross?: boolean, - /** 当 Slider 的值发生改变时,会触发 onChange 事件,并把改变后的值作为参数传入。*/ - onChange?: Function, - /** 与 `onmouseup` 触发时机一致,把当前值作为参数传入。*/ - onAfterChange?: Function, - /** Slider 会把当前值传给 `tipFormatter`,并在 Tooltip 中显示 `tipFormatter` 的返回值,若为 null,则隐藏 Tooltip。*/ - tipFormatter?: Function | any, - range?: boolean - } - /** - * #Slider - 滑动型输入器,展示当前值和可选范围。 - - ## 何时使用 - - 当用户需要在数值区间/自定义区间内进行选择时,可为连续或离散值。*/ - export class Slider extends React.Component { - render(): JSX.Element - } - - - - - // Spin - interface SpinProps { - /** spin组件中点的大小,可选值为 small default large*/ - size?: string, - /** 用于内嵌其他组件的模式,可以关闭 loading 效果*/ - spining?: boolean - } - /** - * #Spin - 用于页面和区块的加载中状态。 - - ## 何时使用 - - 页面局部处于等待异步数据或正在渲染过程时,合适的加载动效会有效缓解用户的焦虑。 - */ - export class Spin extends React.Component { - render(): JSX.Element - } - - - - - // Steps - enum StepStatus { - wait, process, finish - } - interface StepProps { - /** 可选参数,指定状态。当不配置该属性时,会使用父Steps元素的current来自动指定状态。*/ - status?: StepStatus | string, - /** 必要参数,标题。*/ - title: string | React.ReactNode, - /** 可选参数,步骤的详情描述。*/ - description?: string | React.ReactNode, - /** 可选参数,步骤的Icon。如果不指定,则使用默认的样式。*/ - icon?: string | React.ReactNode - } - export class Step extends React.Component { - render(): JSX.Element - } - - interface StepsProps { - /** 可选参数,指定当前处理正在执行状态的步骤,从0开始记数。在子Step元素中,可以通过status属性覆盖状态。*/ - current?: number, - /** 可选参数,指定大小(目前只支持普通和迷你两种大小)。 small, default */ - size?: string, - /** 可选参数,指定步骤条方向(目前支持水平和竖直两种方向,默认水平方向)。*/ - direction?: string, - /** 可选参数,指定步骤的详细描述文字的最大宽度。*/ - maxDescriptionWidth?: number - - } - /** - * #Steps - 引导用户按照流程完成任务的导航条。 - - ## 何时使用 - - 当任务复杂或者存在先后关系时,将其分解成一系列步骤,从而简化任务。*/ - export class Steps extends React.Component { - static Step: typeof Step - render(): JSX.Element - } - - - - // Switch - interface SwitchProps { - /** 指定当前是否选中*/ - checked?: boolean, - /** 初始是否选中*/ - defaultChecked?: boolean, - /** 变化时回调函数*/ - onChange?: (checked: boolean) => void, - /** 选中时的内容*/ - checkedChildren?: React.ReactNode, - /** 非选中时的内容*/ - unCheckedChildren?: React.ReactNode, - /** 开关大小*/ - size?: string - } - /** - * #Switch - 开关选择器。 - - ## 何时使用 - - - 需要表示开关状态/两种状态之间的切换时; - - 和 `checkbox `的区别是,切换 `switch` 会直接触发状态改变,而 `checkbox` 一般用于状态标记,需要和提交操作配合。 - */ - export class Switch extends React.Component { - render(): JSX.Element - } - - - - - // Table - enum RowSelectionType { - checkbox, - radio - } - type SelectedRowKeys = Array - interface RowSelection { - type?: RowSelectionType | string, - selectedRowKeys?: SelectedRowKeys, - onChange?: (selectedRowKeys: SelectedRowKeys, selectedRows: any) => void, - getCheckboxProps?: (record: any) => void, - onSelect?: (record: any, selected: any, selectedRows: any) => void, - onSelectAll?: (rselectedecord: any, selectedRows: any, changeRows: any) => void - } - interface Columns { - /** React 需要的 key,建议设置*/ - key?: string, - /** 列头显示文字*/ - title?: string | React.ReactNode, - /** 列数据在数据项中对应的 key*/ - dataIndex?: string, - /** 生成复杂数据的渲染函数,参数分别为当前列的值,当前列数据,列索引,@return里面可以设置表格[行/列合并](#demo-colspan-rowspan)*/ - render?: (text?: any, record?: any, index?: number) => React.ReactNode, - /** 表头的筛选菜单项*/ - filters?: Array, - /** 本地模式下,确定筛选的运行函数*/ - onFilter?: Function, - /** 是否多选*/ - filterMultiple?: boolean, - /** 排序函数,本地排序使用一个函数,需要服务端排序可设为 true */ - sorter?: boolean | Function, - /** 表头列合并,设置为 0 时,不渲染*/ - colSpan?: number, - /** 列宽度*/ - width?: string | number, - /** 列的 className*/ - className?: string - } - interface TableProps { - /** 列表项是否可选择*/ - rowSelection?: RowSelection, - /** 分页器*/ - pagination?: Object, - /** 正常或迷你类型 : `default` or `small` */ - size?: string, - /** 数据数组*/ - dataSource: Array, - /** 表格列的配置描述*/ - columns: Columns, - /** 表格行 key 的取值*/ - rowKey?: (record: any, index: number) => string, - /** 额外的展开行*/ - expandedRowRender?: Function, - /** 默认展开的行*/ - defaultExpandedRowKeys?: Array, - /** 分页、排序、筛选变化时触发*/ - onChange?: (pagination: Object, filters: any, sorter: any) => void, - /** 页面是否加载中*/ - loading?: boolean, - /** 默认文案设置,目前包括排序、过滤、空数据文案: `{ filterConfirm: '确定', filterReset: '重置', emptyText: '暂无数据' }` */ - locale?: Object, - /** 展示树形数据时,每层缩进的宽度,以 px 为单位*/ - indentSize?: number, - /** 处理行点击事件*/ - onRowClick?: (record: any, index: number) => void, - /** 是否固定表头*/ - useFixedHeader?: boolean, - /** 是否展示外边框和列边框*/ - bordered?: boolean, - /** 是否显示表头*/ - showHeader?: boolean, - /** 表格底部自定义渲染函数*/ - footer?: (currentPageData: Object) => void - - } - /** - * #Table - 展示行列数据。 - - ## 何时使用 - - - 当有大量结构化的数据需要展现时; - - 当需要对数据进行排序、搜索、分页、自定义操作等复杂行为时。*/ - export class Table extends React.Component { - render(): JSX.Element - } - - - - // Tabs - interface TabPaneProps { - /** 选项卡头显示文字*/ - tab: React.ReactNode | string - } - export class TabPane extends React.Component { - render(): JSX.Element - } - - enum TabsType { - line, card, 'editable-card' - } - enum TabsPosition { - top, - right, - bottom, - left - } - interface TabsProps { - /** 当前激活 tab 面板的 key */ - activeKey?: string, - /** 初始化选中面板的 key,如果没有设置 activeKey*/ - defaultActiveKey?: string, - /** 切换面板的回调*/ - onChange?: Function, - /** tab 被点击的回调 */ - onTabClick?: Function, - /** tab bar 上额外的元素 */ - tabBarExtraContent?: React.ReactNode, - /** 页签的基本样式,可选 `line`、`card` `editable-card` 类型*/ - type?: TabsType | string, - /** 页签位置,可选值有 `top` `right` `bottom` `left`*/ - tabPosition?: TabsPosition | string, - /** 新增和删除页签的回调,在 `type="editable-card"` 时有效*/ - onEdit?: (targetKey: string, action: any) => void - } - /** - * #Tabs - 选项卡切换组件。 - - ## 何时使用 - - 提供平级的区域将大块内容进行收纳和展现,保持界面整洁。 - - Ant Design 依次提供了三级选项卡,分别用于不同的场景。 - - - 卡片式的页签,提供可关闭的样式,常用于容器顶部。 - - 标准线条式页签,用于容器内部的主功能切换,这是最常用的 Tabs。 - - [RadioButton](/components/radio/#demo-radiobutton) 可作为更次级的页签来使用。*/ - export class Tabs extends React.Component { - static TabPane: typeof TabPane - render(): JSX.Element - } - - - - - // Tag - interface TagProps { - /** 标签是否可以关闭*/ - closable?: boolean, - /** 关闭时的回调*/ - onClose?: Function, - /** 动画关闭后的回调*/ - afterClose?: Function, - /** 标签的色彩*/ - color?: string - } - /** - * #Tag - 进行标记和分类的小标签。 - - ## 何时使用 - - - 用于标记事物的属性和维度。 - - 进行分类。*/ - export class Tag extends React.Component { - render(): JSX.Element - } - - - - - - - // TimePicker - interface TimePickerProps { - /** 默认时间*/ - value?: string | Date, - /** 初始默认时间*/ - defaultValue?: string | Date, - /** 展示的时间格式 : "HH:mm:ss"、"HH:mm"、"mm:ss" */ - format?: string, - /** 时间发生变化的回调*/ - onChange?: (Date: Date) => void, - /** 禁用全部操作*/ - disabled?: boolean, - /** 没有值的时候显示的内容*/ - placeholder?: string, - /** 国际化配置*/ - locale?: Object, - /** 隐藏禁止选择的选项*/ - hideDisabledOptions?: boolean, - /** 禁止选择部分小时选项*/ - disabledHours?: Function, - /** 禁止选择部分分钟选项*/ - disabledMinutes?: Function, - /** 禁止选择部分秒选项*/ - disabledSeconds?: Function - - } - /** - * #TimePicker - 输入或选择时间的控件。 - - 何时使用 - -------- - - 当用户需要输入一个时间,可以点击标准输入框,弹出时间面板进行选择。 - */ - export class TimePicker extends React.Component { - render(): JSX.Element - } - - - - - // Timeline - interface TimeLineItemProps { - /** 指定圆圈颜色。*/ - color?: string - } - export class TimeLineItem extends React.Component { - render(): JSX.Element - } - - interface TimelineProps { - /** 指定最后一个幽灵节点是否存在或内容*/ - pending?: boolean | React.ReactNode - } - /** - * #Timeline - 垂直展示的时间流信息。 - - ## 何时使用 - - - 当有一系列信息需要从上至下按时间排列时; - - 需要有一条时间轴进行视觉上的串联时;*/ - export class Timeline extends React.Component { - static Item: typeof TimeLineItem - render(): JSX.Element - } - - - - // Tooltip - - interface TooltipProps { - /** 气泡框位置,可选 `top` `left` `right` `bottom` `topLeft` `topRight` `bottomLeft` `bottomRight` `leftTop` `leftBottom` `rightTop` `rightBottom`*/ - placement?: PopoverPlacement | string, - /** 提示文字*/ - title?: string | React.ReactNode - } - /** - * #Tooltip - 简单的文字提示气泡框。 - - ## 何时使用 - - 鼠标移入则显示提示,移出消失,气泡浮层不承载复杂文本和操作。 - - 可用来代替系统默认的 `title` 提示,提供一个`按钮/文字/操作`的文案解释。*/ - export class Tooltip extends React.Component { - render(): JSX.Element - } - - - - - - // Transfer - interface TransferProps { - /** 数据源*/ - dataSource: Array, - /** 每行数据渲染函数*/ - render?: (record: Object) => any, - /** 显示在右侧框数据的key集合*/ - targetKeys: Array, - /** 变化时回调函数*/ - onChange?: (targetKeys: any, direction: string, moveKeys: any) => void, - /** 两个穿梭框的自定义样式*/ - listStyle?: Object, - /** 自定义类*/ - className?: string, - /** 标题集合,顺序从左至右*/ - titles?: Array, - /** 操作文案集合,顺序从上至下*/ - operations?: Array, - /** 是否显示搜索框*/ - showSearch?: boolean, - /** 搜索框的默认值*/ - searchPlaceholder?: string, - /** 当列表为空时显示的内容*/ - notFoundContent?: React.ReactNode | string - /** 底部渲染函数*/ - footer?: (props: any) => any - } - /** - * #Transfer - 双栏穿梭选择框。 - - ## 何时使用 - - 用直观的方式在两栏中移动元素,完成选择行为。 - */ - export class Transfer extends React.Component { - render(): JSX.Element - } - - - - - - // Tree - interface TreeNodeProps { - disabled?: boolean, - disableCheckbox?: boolean, - title?: string | React.ReactNode, - key?: string, - isLeaf?: boolean - } - export class TreeNode extends React.Component { - render(): JSX.Element - } - - interface TreeProps { - showLine?: boolean, - className?: string, - /** 是否支持多选*/ - multiple?: boolean, - /** 是否支持选中*/ - checkable?: boolean, - /** 默认展开所有树节点*/ - defaultExpandAll?: boolean, - /** 默认展开指定的树节点*/ - defaultExpandedKeys?: Array, - /** (受控)展开指定的树节点*/ - expandedKeys?: Array, - /** (受控)选中复选框的树节点*/ - checkedKeys?: Array, - /** 默认选中复选框的树节点*/ - defaultCheckedKeys?: Array, - /** (受控)设置选中的树节点*/ - selectedKeys?: Array, - /** 默认选中的树节点*/ - defaultSelectedKeys?: Array, - /** 展开/收起节点时触发 */ - onExpand?: (node: any, expanded: any, expandedKeys: any) => void, - /** 点击复选框触发*/ - onCheck?: (checkedKeys: any, e: { checked: boolean, checkedNodes: any, node: any, event: Event }) => void, - /** 点击树节点触发*/ - onSelect?: (selectedKeys: any, e: { selected: boolean, selectedNodes: any, node: any, event: Event }) => void, - /** filter some treeNodes as you need. it should return true */ - filterTreeNode?: (node: any) => boolean, - /** 异步加载数据*/ - loadData?: (node: any) => void, - /** 响应右键点击*/ - onRightClick?: (options: { event: Event, node: any }) => void, - /** 设置节点可拖拽(IE>8)*/ - draggable?: boolean, - /** 开始拖拽时调用*/ - onDragStart?: (options: { event: Event, node: any }) => void, - /** dragenter 触发时调用*/ - onDragEnter?: (options: { event: Event, node: any, expandedKeys: any }) => void, - /** dragover 触发时调用 */ - onDragOver?: (options: { event: Event, node: any }) => void, - /** dragleave 触发时调用*/ - onDragLeave?: (options: { event: Event, node: any }) => void, - /** drop 触发时调用*/ - onDrop?: (options: { event: Event, node: any, dragNode: any, dragNodesKeys: any }) => void, - } - /** - * #Tree - * 文件夹、组织架构、生物分类、国家地区等等,世间万物的大多数结构都是树形结构。使用`树控件`可以完整展现其中的层级关系,并具有展开收起选择等交互功能。 - */ - export class Tree extends React.Component { - static TreeNode: typeof TreeNode - render(): JSX.Element - } - - - - - - // TreeSelect - interface TreeSelectTreeNodeProps { - disabled?: boolean, - /** 此项必须设置(其值在整个树范围内唯一)*/ - key: string, - /** 默认根据此属性值进行筛选*/ - value?: string, - /** 树节点显示的内容*/ - title?: React.ReactNode | string, - /** 是否是叶子节点*/ - isLeaf?: boolean - } - export class TreeSelectTreeNode extends React.Component { - render(): JSX.Element - } - - type TreeData = Array<{ value: any, label: string, children: TreeData }> - interface TreeSelectProps { - style?: Object, - /** 指定当前选中的条目*/ - value?: string | Array, - /** 指定默认选中的条目*/ - defaultValue?: string | Array, - /** 支持多选*/ - multiple?: boolean, - /** 可以把随意输入的条目作为 tag,输入项不需要与下拉选项匹配*/ - tags?: boolean, - /** 被选中时调用,参数为选中项的 value 值*/ - onSelect?: (value: any) => void, - /** 选中option,或input的value变化(combobox 模式下)时,调用此函数*/ - onChange?: (value: any, label: any) => void, - /** 显示清除按钮*/ - allowClear?: boolean, - /** 文本框值变化时回调*/ - onSearch?: (value: any) => void, - /** 选择框默认文字*/ - placeholder?: string, - /** 搜索框默认文字*/ - searchPlaceholder?: string, - /** 下拉菜单的样式*/ - dropdownStyle?: Object, - /** 下拉菜单和选择器同宽*/ - dropdownMatchSelectWidth?: boolean, - /** 输入框自动提示模式*/ - combobox?: boolean, - /** 选择框大小,可选 `large` `small`*/ - size?: string, - /** 在下拉中显示搜索框*/ - showSearch?: boolean, - /** 是否禁用*/ - disabled?: boolean, - /** 默认展开所有树节点*/ - treeDefaultExpandAll?: boolean, - /** 显示checkbox*/ - treeCheckable?: boolean, - /** 是否根据输入项进行筛选,返回值true*/ - filterTreeNode?: (treeNode: any) => boolean, - /** 输入项过滤对应的 treeNode 属性*/ - treeNodeFilterProp?: string, - /** 作为显示的prop设置*/ - treeNodeLabelProp?: string, - /** treeNodes数据,如果设置则不需要手动构造TreeNode节点(如果value在整个树范围内不唯一,需要设置`key`其值为整个树范围内的唯一id*/ - treeData?: TreeData, - /** 异步加载数据*/ - loadData?: (node: any) => void - } - /** - * #TreeSelect - 树型选择控件。 - - ## 何时使用 - - 类似 Select 的选择控件,可选择的数据结构是一个树形结构时,可以使用 TreeSelect,例如公司层级、学科系统、分类目录等等。 - */ - export class TreeSelect extends React.Component { - static TreeNode: typeof TreeSelectTreeNode - render(): JSX.Element - } - - - - - - - // Upload - interface UploadProps { - /** 可选参数, 上传的文件 */ - name?: string, - /** 必选参数, 上传的地址 */ - action: string, - /** 可选参数, 上传所需参数 */ - data?: Object, - /** 可选参数, 设置上传的请求头部,IE10 以上有效*/ - headers?: Object, - /** 可选参数, 是否展示 uploadList, 默认开启 */ - showUploadList?: boolean, - /** 可选参数, 是否支持多选文件,`ie10+` 支持。开启后按住 ctrl 可选择多个文件。*/ - multiple?: boolean, - /** 可选参数, 接受上传的文件类型, 详见 input accept Attribute */ - accept?: string, - /** 可选参数, 上传文件之前的钩子,参数为上传的文件,若返回 `false` 或者 Promise 则停止上传。**注意:该方法不支持老 IE**。*/ - beforeUpload?: Function, - /** 可选参数, 上传文件改变时的状态,详见 onChange */ - onChange?: (info: Object) => void, - /** 上传列表的内建样式,支持两种基本样式 `text` or `picture` */ - listType?: string, - /** 自定义类名*/ - className?: string - - } - /** - * #Upload - 文件选择上传和拖拽上传控件。 - - ## 何时使用 - - 上传是将信息(网页、文字、图片、视频等)通过网页或者上传工具发布到远程服务器上的过程。 - - - 当需要上传一个或一些文件时。 - - 当需要展现上传的进度时。 - - 当需要使用拖拽交互时。*/ - export class Upload extends React.Component { - render(): JSX.Element - } - - - - - - -} - - -// export all antd -declare module 'antd' { - export = Antd -} -// single export point -declare module 'antd/lib/Affix' { - export default Antd.Affix -} -declare module 'antd/lib/Button' { - export default Antd.Button -} -declare module 'antd/lib/Alert' { - export default Antd.Alert -} -declare module 'antd/lib/Badge' { - export default Antd.Badge -} -declare module 'antd/lib/Breadcrumb' { - export default Antd.Breadcrumb -} -declare module 'antd/lib/Calendar' { - export default Antd.Calendar -} -declare module 'antd/lib/Carousel' { - export default Antd.Carousel -} -declare module 'antd/lib/Cascader' { - export default Antd.Cascader -} -declare module 'antd/lib/Checkbox' { - export default Antd.Checkbox -} -declare module 'antd/lib/Collapse' { - export default Antd.Collapse -} -declare module 'antd/lib/DatePicker' { - export default Antd.DatePicker -} -declare module 'antd/lib/Dropdown' { - export default Antd.Dropdown -} -declare module 'antd/lib/Icon' { - export default Antd.Icon -} -declare module 'antd/lib/Form' { - export default Antd.Form -} -declare module 'antd/lib/Input' { - export default Antd.Input -} -declare module 'antd/lib/InputNumber' { - export default Antd.InputNumber -} -declare module 'antd/lib/Row' { - export default Antd.Row -} -declare module 'antd/lib/Col' { - export default Antd.Col -} -declare module 'antd/lib/Menu' { - export default Antd.Menu -} -declare module 'antd/lib/message' { - export default Antd.message -} -declare module 'antd/lib/Modal' { - export default Antd.Modal -} -declare module 'antd/lib/notification' { - export default Antd.notification -} -declare module 'antd/lib/Pagination' { - export default Antd.Pagination -} -declare module 'antd/lib/Popconfirm' { - export default Antd.Popconfirm -} -declare module 'antd/lib/Popover' { - export default Antd.Popover -} -declare module 'antd/lib/Progress' { - export default Antd.Progress -} -declare module 'antd/lib/QueueAnim' { - export default Antd.QueueAnim -} -declare module 'antd/lib/Radio' { - export default Antd.Radio -} -declare module 'antd/lib/Select' { - export default Antd.Select -} -declare module 'antd/lib/Slider' { - export default Antd.Slider -} -declare module 'antd/lib/Spin' { - export default Antd.Spin -} -declare module 'antd/lib/Steps' { - export default Antd.Steps -} -declare module 'antd/lib/Switch' { - export default Antd.Switch -} -declare module 'antd/lib/Table' { - export default Antd.Table -} -declare module 'antd/lib/Tabs' { - export default Antd.Tabs -} -declare module 'antd/lib/Tag' { - export default Antd.Tag -} -declare module 'antd/lib/TimePicker' { - export default Antd.TimePicker -} -declare module 'antd/lib/Timeline' { - export default Antd.Timeline -} -declare module 'antd/lib/Tooltip' { - export default Antd.Tooltip -} -declare module 'antd/lib/Transfer' { - export default Antd.Transfer -} -declare module 'antd/lib/Tree' { - export default Antd.Tree -} -declare module 'antd/lib/TreeSelect' { - export default Antd.TreeSelect -} -declare module 'antd/lib/Upload' { - export default Antd.Upload -} diff --git a/applicationinsights-js/applicationinsights-js-tests.ts b/applicationinsights-js/applicationinsights-js-tests.ts index f77bab2b0a..06a7d06bc5 100644 --- a/applicationinsights-js/applicationinsights-js-tests.ts +++ b/applicationinsights-js/applicationinsights-js-tests.ts @@ -1,4 +1,3 @@ - // More samples on: https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md var config: Microsoft.ApplicationInsights.IConfig = { @@ -24,7 +23,11 @@ var config: Microsoft.ApplicationInsights.IConfig = { disableCorrelationHeaders: true, disableFlushOnBeforeUnload: false, enableSessionStorageBuffer: false, - cookieDomain: "" + cookieDomain: "", + isCookieUseDisabled: true, + isRetryDisabled: true, + isPerfAnalyzerEnabled: true, + isStorageUseDisabled: true }; var appInsights: Microsoft.ApplicationInsights.IAppInsights = { @@ -35,17 +38,17 @@ var appInsights: Microsoft.ApplicationInsights.IAppInsights = { startTrackPage(name?: string) { return null; }, stopTrackPage(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; }, trackPageView(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, duration?: number) { return null; }, - startTrackEvent(name: string) { return null }, - stopTrackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null }, - trackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null }, - trackAjax(id: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, method?: string) { return null }, - trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: AI.SeverityLevel) { return null }, - trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; }) { return null }, - trackTrace(message: string, properties?: { [name: string]: string; }) { return null }, - flush() { return null }, - setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string) { return null }, - clearAuthenticatedUserContext() { return null }, - _onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error) { return null } + startTrackEvent(name: string) { return null; }, + stopTrackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; }, + trackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; }, + trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number) { return null; }, + trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: AI.SeverityLevel) { return null; }, + trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; }) { return null; }, + trackTrace(message: string, properties?: { [name: string]: string; }) { return null; }, + flush() { return null; }, + setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string) { return null; }, + clearAuthenticatedUserContext() { return null; }, + _onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error) { return null; } }; // trackPageView @@ -75,6 +78,9 @@ appInsights.trackException(new Error("sample error"), "handledAt", null, null); appInsights.trackTrace("message"); appInsights.trackTrace("message", null); +// trackDependency +appInsights.trackDependency("id", "POST", "http://example.com/test/abc", "/test/abc", null, true, null); + // flush appInsights.flush(); diff --git a/applicationinsights-js/index.d.ts b/applicationinsights-js/index.d.ts index ba154e5fe6..c032919618 100644 --- a/applicationinsights-js/index.d.ts +++ b/applicationinsights-js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ApplicationInsights-JS v0.23.2 +// Type definitions for ApplicationInsights-JS 1.0 // Project: https://github.com/Microsoft/ApplicationInsights-JS // Definitions by: Kamil Szostak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -323,7 +323,7 @@ declare module Microsoft.ApplicationInsights.Telemetry { /** * Constructs a new instance of the EventTelemetry object */ - constructor(name: string, properties?: Object, measurements?: Object); + constructor(name: string, properties?: any, measurements?: any); } class Exception implements Microsoft.ApplicationInsights.ISerializable { @@ -348,7 +348,7 @@ declare module Microsoft.ApplicationInsights.Telemetry { /** * Constructs a new isntance of the ExceptionTelemetry object */ - constructor(exception: Error, handledAt?: string, properties?: Object, measurements?: Object, severityLevel?: AI.SeverityLevel); + constructor(exception: Error, handledAt?: string, properties?: any, measurements?: any, severityLevel?: AI.SeverityLevel); /** * Creates a simple exception with 1 stack frame. Useful for manual constracting of exception. */ @@ -369,7 +369,7 @@ declare module Microsoft.ApplicationInsights.Telemetry { /** * Constructs a new instance of the MetricTelemetry object */ - constructor(name: string, value: number, count?: number, min?: number, max?: number, properties?: Object); + constructor(name: string, value: number, count?: number, min?: number, max?: number, properties?: any); } class PageView extends AI.PageViewData implements Microsoft.ApplicationInsights.ISerializable { @@ -477,7 +477,7 @@ declare module Microsoft.ApplicationInsights.Telemetry { /** * Constructs a new instance of the MetricTelemetry object */ - constructor(message: string, properties?: Object); + constructor(message: string, properties?: any); } } @@ -567,8 +567,12 @@ declare module Microsoft.ApplicationInsights { disableCorrelationHeaders?: boolean; disableFlushOnBeforeUnload?: boolean; enableSessionStorageBuffer?: boolean; + isCookieUseDisabled?: boolean; cookieDomain?: string; + isRetryDisabled?: boolean; + isPerfAnalyzerEnabled?: boolean; url?: string; + isStorageUseDisabled?: boolean; } /** @@ -657,7 +661,7 @@ declare module Microsoft.ApplicationInsights { interface IAppInsights { config: IConfig; context: ITelemetryContext; - queue: (() => void)[]; + queue: Array<() => void>; /** * Starts timing how long the user views a page or other item. Call this when the page opens. * This method doesn't send any telemetry. Call {@link stopTrackTelemetry} to log the page when it closes. @@ -717,16 +721,16 @@ declare module Microsoft.ApplicationInsights { [name: string]: number; }): any; /** - * Log an AJAX request - * @param id Event id - * @param absoluteUrl Full url - * @param pathName Leave this parameter blank - * @param totalTime Total time it took for AJAX request to complete - * @param success Whether AJAX request succeeded or failed - * @param resultCode Result code returned from AJAX call - * @param method HTTP verb that was used (GET, POST) - */ - trackAjax(id: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, method?: string): any; + * Log a dependency call + * @param id unique id, this is used by the backend o correlate server requests. Use Util.newId() to generate a unique Id. + * @param method represents request verb (GET, POST, etc.) + * @param absoluteUrl absolute url used to make the dependency request + * @param pathName the path part of the absolute url + * @param totalTime total request time + * @param success indicates if the request was sessessful + * @param resultCode response code returned by the dependency request + */ + trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number): any; /** * Log an exception you have caught. * @param exception An Error from a catch clause, or the string error message. @@ -755,7 +759,7 @@ declare module Microsoft.ApplicationInsights { /** * Log a diagnostic message. * @param message A message string - * @param properties map[string, string] - additional data used to filter traces in the portal. Defaults to empty. + * @param properties map[string, string] - additional data used to filter traces in the portal. Defaults to empty. */ trackTrace(message: string, properties?: { [name: string]: string; @@ -776,7 +780,7 @@ declare module Microsoft.ApplicationInsights { * Clears the authenticated user id and the account id from the user context. */ clearAuthenticatedUserContext(): any; - downloadAndSetup?(config: Microsoft.ApplicationInsights.IConfig): void; + downloadAndSetup?(config: Microsoft.ApplicationInsights.IConfig): any; /** * The custom error handler for Application Insights * @param {string} message - The error message diff --git a/applicationinsights-js/tslint.json b/applicationinsights-js/tslint.json new file mode 100644 index 0000000000..119a5839d0 --- /dev/null +++ b/applicationinsights-js/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "../tslint.json", + "rules": { + "interface-name": [ false ], + "no-internal-module": false, + "no-single-declare-module": false + } +} \ No newline at end of file diff --git a/arcgis-js-api/index.d.ts b/arcgis-js-api/index.d.ts index 87df41a8d8..293c5190e9 100644 --- a/arcgis-js-api/index.d.ts +++ b/arcgis-js-api/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ArcGIS API for JavaScript 4.2 +// Type definitions for ArcGIS API for JavaScript 4.3 // Project: http://js.arcgis.com // Definitions by: Esri // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -32,14 +32,19 @@ declare namespace JSX { declare namespace __esri { export class Accessor { + constructor(obj?: any); + destroyed: boolean; initialized: boolean; declaredClass: string; destroy(): void; + get(propertyName: string): T; get(propertyName: string): any; set(propertyName: string, value: T): this; set(props: HashMap): this; + watch(path: string | string[], callback: WatchCallback, sync?: boolean): WatchHandle; + protected notifyChange(propertyName: string): void; protected _get(propertyName: string): any; protected _get(propertyName: string): T; @@ -69,18 +74,521 @@ declare namespace __esri { remove(): void; } + export interface EachAlwaysResult { + promise: IPromise; + value: any; + error: any; + } + export interface PausableWatchHandle { remove(): void; pause(): void; resume(): void; } + export interface FeatureEditResult { + objectId: number; + error: any; + } + export interface AttributeParamValue { attributeName: string; parameterName: string; value: string; } + export interface DataWorkspace { + id: string; + name: string; + } + + export interface GroupMembership { + id: number; + name: string; + } + + export interface HoldType { + description: string; + id: number; + name: string; + } + + export interface JobPriority { + description: string; + name: string; + value: number; + } + + export interface JobQuery { + id: number; + name: string; + } + + export interface JobStatus { + caption: string; + description: string; + id: number; + name: string; + } + + export interface JobQueryContainer { + containers: JobQueryContainer[]; + id: number; + name: string; + queries: JobQuery[]; + } + + export interface JobQueryDetails { + aliases: string[]; + fields: string[]; + id: number; + name: string; + orderBy: string; + tables: string[]; + where: string; + } + + export interface Privilege { + description: string; + id: number; + name: string; + } + + export interface UserDetails { + lastName: string; + address: string; + faxNumber: string; + firstName: string; + fullName: string; + groups: GroupMembership[]; + email: string; + phoneNumber: string; + privileges: Privilege[]; + roomNumber: string; + userName: string; + userQueries: JobQueryContainer[]; + zipCode: string; + } + + export interface VersionInfo { + access: string; + name: string; + parent: string; + } + + export interface WorkflowManagerServiceInfo { + jobPriorities: JobPriority[]; + activityTypes: ActivityType[]; + currentVersion: number; + dataWorkspaces: DataWorkspace[]; + holdTypes: HoldType[]; + configProperties: any; + jobStatuses: JobStatus[]; + jobTypes: JobType[]; + notificationTypes: NotificationType[]; + privileges: Privilege[]; + publicQueries: JobQueryContainer[]; + } + + export interface JobType { + category: string; + description: string; + id: string; + name: string; + state: string; + } + + export interface JobTypeDetails { + defaultParentVersionName: string; + autoExecuteCreatedJobs: boolean; + category: string; + defaultAssignedTo: string; + defaultAssignedType: string; + defaultDataWorkspaceId: string; + defaultDescription: string; + defaultDueDate: string; + defaultJobDuration: number; + canDataWorkspaceChange: boolean; + defaultPriority: string; + defaultStartDate: Date; + description: string; + id: string; + jobNamingScheme: string; + jobVersionNamingScheme: string; + mxdNamingScheme: string; + name: string; + state: string; + } + + export interface TableRelationship { + cardinality: string; + linkField: string; + tableAlias: string; + tableName: string; + } + + export interface JobCreationParameters { + loi: Geometry; + assignedTo: string; + autoCommitWorkflow: boolean; + autoExecute: boolean; + dataWorkspaceId: string; + description: string; + dueDate: Date; + jobTypeId: number; + assignedType: string; + name: string; + numJobs: string; + ownedBy: string; + parentJobId: number; + parentVersion: string; + priority: number; + startDate: Date; + user: string; + } + + export interface JobQueryParameters { + aliases: string; + fields: string; + orderBy: string; + tables: string; + where: string; + user: string; + } + + export interface JobUpdateParameters { + ownedBy: string; + assignedTo: string; + dataWorkspaceId: string; + description: string; + dueDate: Date; + loi: Geometry; + jobId: number; + name: string; + assignedType: string; + parentJobId: number; + parentVersion: string; + percent: number; + priority: number; + startDate: Date; + status: number; + versionName: string; + user: string; + } + + export interface AuxRecordDescription { + properties: any; + recordId: number; + tableName: string; + } + + export interface ActivityType { + desription: string; + id: number; + message: string; + name: string; + } + + export interface AuxRecordContainer { + records: AuxRecord; + relationshipType: string; + tableAlias: string; + tableName: string; + } + + export interface JobTaskJobInfo { + name: string; + assignedTo: string; + childJobIds: number[]; + createdBy: string; + createdDate: Date; + dataWorkspaceId: string; + description: string; + dueDate: Date; + endDate: Date; + id: number; + jobTypeId: number; + loi: Geometry; + assignedType: string; + ownedBy: string; + parentJobId: number; + parentVersion: string; + pendingDays: number; + percentageComplete: number; + priority: number; + stage: string; + startDate: Date; + status: number; + versionExists: boolean; + versionInfo: JobVersionInfo; + versionName: string; + } + + export interface QueryResult { + fields: QueryFieldInfo[]; + rows: string[]; + } + + export interface AuxRecord { + displayProperty: any; + id: number; + recordvalues: AuxRecordValue; + } + + export interface AuxRecordValue { + filter: string; + alias: string; + data: any; + dataType: string; + displayOrder: number; + displayType: string; + domain: string; + canUpdate: boolean; + length: number; + name: string; + required: boolean; + tableListClass: string; + tableListDisplayField: string; + tableListStoreField: string; + userVisible: boolean; + } + + export interface FieldValue { + description: string; + value: any; + } + + export interface JobVersionInfo { + dataWorkspaceId: string; + name: string; + parent: string; + created: boolean; + owner: string; + } + + export interface QueryFieldInfo { + alias: string; + length: string; + name: string; + type: string; + } + + export interface JobAttachment { + filename: string; + folder: string; + id: number; + storageType: string; + } + + export interface JobDependency { + depJobId: number; + depOnType: string; + depOnValue: string; + heldOnValue: number; + holdOnType: string; + id: number; + jobID: string; + } + + export interface ChangeRule { + description: string; + evaluators: any[]; + id: number; + name: string; + notifier: any; + summarize: boolean; + } + + export interface DataSetEvaluator { + dataSetConfigurations: DatasetConfiguration[]; + name: string; + type: string; + } + + export interface AOIEvaluator { + aoi: Polygon; + inverse: boolean; + name: string; + relation: string; + type: string; + useJobAOI: boolean; + } + + export interface DatasetConfiguration { + changeCondition: number; + changeFields: string; + dataset: string; + dataWorkspaceId: string; + name: string; + whereConditions: WhereCondition[]; + } + + export interface EmailNotifier { + attachJobAttachments: boolean; + message: string; + name: string; + senderEmail: string; + senderName: string; + subject: string; + subscribers: string[]; + type: string; + } + + export interface WhereCondition { + compareValue: any; + field: string; + operator: string; + } + + export interface NotificationType { + attachJobAttachments: boolean; + id: number; + message: string; + senderEmail: string; + senderName: string; + subject: string; + subscribers: string[]; + type: string; + } + + export interface ChangeRuleMatch { + changeTime: Date; + changeType: string; + dataset: string; + dataWorkspaceId: string; + id: string; + jobID: string; + ruleID: string; + } + + export interface ReportDataGroup { + aggregateLabel: string; + aggregateValue: string; + row: string[]; + value: string; + } + + export interface ReportData { + columns: string[]; + description: string; + groups: ReportDataGroup[]; + title: string; + } + + export interface Report { + description: string; + hierarchy: string; + id: number; + name: string; + title: string; + } + + export interface ExecuteInfo { + conflicts: WorkflowConflicts; + errorCode: number; + errorDescription: string; + executionResult: string; + hasConflicts: boolean; + hasReturnCode: boolean; + jobID: number; + returnCode: number; + stepID: number; + threwError: boolean; + } + + export interface Step { + hasBeenExecuted: boolean; + assignedTo: string; + async: boolean; + autoRun: boolean; + canSkip: boolean; + canSpawnConcurrency: boolean; + commonId: number; + defaultPercentComplete: number; + assignedType: string; + hasBeenStarted: boolean; + id: number; + name: string; + selfCheck: boolean; + statusId: number; + stepPercentComplete: number; + notificationType: string; + stepType: StepType; + } + + export interface StepType { + program: string; + arguments: string; + executionType: string; + id: number; + name: string; + description: string; + stepDescriptionLink: string; + stepDescriptionType: string; + stepIndicatorType: string; + supportedPlatform: string; + visible: boolean; + } + + export interface WorkflowDisplayDetails { + annotations: WorkflowAnnotationDisplayDetails[]; + paths: WorkflowPathDisplayDetails[]; + steps: WorkflowStepDisplayDetails[]; + } + + export interface WorkflowOption { + returnCode: number; + steps: WorkflowStepInfo[]; + } + + export interface WorkflowStepInfo { + id: number; + name: string; + } + + export interface WorkflowAnnotationDisplayDetails { + centerX: number; + centerY: number; + fillColor: any; + height: number; + label: string; + labelColor: any; + OutlineColor: any; + width: number; + } + + export interface WorkflowConflicts { + jobID: number; + options: WorkflowOption[]; + spawnsConcurrency: boolean; + stepId: number; + } + + export interface WorkflowPathDisplayDetails { + destStepId: number; + sourceStepID: number; + label: string; + labelColor: any; + labelX: number; + labelY: number; + lineColor: any; + pathObject: any; + } + + export interface WorkflowStepDisplayDetails { + labelColor: any; + centerX: number; + fillColor: any; + height: number; + label: string; + centerY: number; + OutlineColor: any; + shape: string; + stepId: number; + stepType: string; + width: number; + } + export interface ExternalRenderer { setup(): void; render(): void; @@ -139,26 +647,6 @@ declare namespace __esri { suggestionTemplate: string; } - export interface SearchViewModelLocatorSource { - categories: string[]; - countryCode: string; - localSearchOptions: any; - locationToAddressDistance: number; - searchTemplate: string; - locator: Locator; - singleLineFieldName: string; - } - - export interface SearchViewModelFeatureLayerSource { - displayField: string; - exactMatch: boolean; - featureLayer: FeatureLayer; - searchFields: string[]; - searchQueryParams: any; - suggestQueryParams: any; - suggestionTemplate: string; - } - export type GetHeader = (headerName: string) => string; export type WatchCallback = (newValue: any, oldValue: any, propertyName: string, target: Accessor) => void; @@ -282,11 +770,33 @@ declare namespace __esri { offset?: number; } + export interface FeatureLayerApplyEditsEdits { + addFeatures?: Graphic[]; + updateFeatures?: Graphic[]; + deleteFeatures?: Graphic[] | any[]; + } + + export interface FeatureLayerCapabilities { + operations: FeatureLayerCapabilitiesOperations; + } + + export interface FeatureLayerCapabilitiesOperations { + supportsAdd: boolean; + supportsDelete: boolean; + supportsUpdate: boolean; + supportsEditing: boolean; + supportsQuery: boolean; + } + export interface FeatureLayerElevationInfo { mode: string; offset?: number; } + export interface FeatureLayerGetFieldDomainOptions { + feature: Graphic; + } + export interface GraphicsLayerElevationInfo { mode: string; offset?: number; @@ -306,6 +816,21 @@ declare namespace __esri { offset?: number; } + export interface StreamLayerFilter { + geometry: Extent; + where: string; + } + + export interface StreamLayerPurgeOptions { + displayCount: number; + age: number; + } + + export interface StreamLayerUpdateFilterFilterChanges { + geometry: Extent; + where: string; + } + export interface VectorTileLayerCurrentStyleInfo { serviceUrl: string; styleUrl: string; @@ -382,6 +907,14 @@ declare namespace __esri { label: string; } + export interface PointCloudRendererPointSizeAlgorithm { + type: string; + useRealWorldSymbolSizes: boolean; + size: number; + scaleFactor: number; + minSize: number; + } + export interface PointCloudClassBreaksRendererColorClassBreakInfos { minValue: number; maxValue: number; @@ -422,8 +955,8 @@ declare namespace __esri { } export interface Symbol3DStyleOrigin { - styleName: string; - styleUrl: string; + styleName?: string; + styleUrl?: string; name: string; } @@ -508,6 +1041,294 @@ declare namespace __esri { tolerance: number; } + export interface ConfigurationTaskGetDataWorkspaceDetailsParams { + dataWorkspaceId: string; + user: string; + } + + export interface ConfigurationTaskGetUserJobQueryDetailsParams { + queryId: number; + user: string; + } + + export interface JobTaskAddEmbeddedAttachmentParams { + jobId: number; + form: any; + user: string; + } + + export interface JobTaskAddLinkedAttachmentParams { + jobId: number; + attachmentType: number; + path: string; + user: string; + } + + export interface JobTaskAddLinkedRecordParams { + jobId: number; + tableName: string; + user: string; + } + + export interface JobTaskAssignJobsParams { + jobIds: number[]; + assignedType: string; + assignedTo: string; + user: string; + } + + export interface JobTaskCloseJobsParams { + jobIds: number[]; + user: string; + } + + export interface JobTaskCreateDependencyParams { + jobId: number; + heldOnType: string; + heldOnValue: number; + depJobId: number; + depOnType: string; + depOnValue: number; + user: string; + } + + export interface JobTaskCreateHoldParams { + jobId: number; + holdTypeId: number; + comments: string; + user: string; + } + + export interface JobTaskCreateJobVersionParams { + jobId: number; + name: string; + parent: string; + user: string; + } + + export interface JobTaskDeleteAttachmentParams { + jobId: number; + attachmentId: number; + user: string; + } + + export interface JobTaskDeleteDependencyParams { + jobId: number; + dependencyId: number; + user: string; + } + + export interface JobTaskDeleteJobsParams { + jobIds: number[]; + deleteHistory?: boolean; + user: string; + } + + export interface JobTaskDeleteLinkedRecordParams { + jobId: number; + tableName: string; + recordId: number; + user: string; + } + + export interface JobTaskGetAttachmentContentUrlParams { + jobId: number; + attachmentId: number; + } + + export interface JobTaskListFieldValuesParams { + jobId: number; + tableName: string; + field: string; + user: string; + } + + export interface JobTaskListMultiLevelFieldValuesParams { + field: string; + previousSelectedValues: string[]; + user: string; + } + + export interface JobTaskLogActionParams { + jobId: number; + activityTypeId: number; + comments: string; + user: string; + } + + export interface JobTaskQueryJobsParams { + queryId: number; + user: string; + } + + export interface JobTaskQueryMultiLevelSelectedValuesParams { + field: string; + user: string; + } + + export interface JobTaskReleaseHoldParams { + jobId: number; + holdId: number; + } + + export interface JobTaskReopenClosedJobsParams { + jobIds: number[]; + user: string; + } + + export interface JobTaskSearchJobsParams { + text: string; + user: string; + } + + export interface JobTaskUnassignJobsParams { + jobIds: number[]; + user: string; + } + + export interface JobTaskUpdateNotesParams { + jobId: number; + notes: string; + user: string; + } + + export interface JobTaskUpdateRecordParams { + jobId: number; + record: AuxRecordDescription; + user: string; + } + + export interface NotificationTaskAddChangeRuleParams { + rule: ChangeRule; + user: string; + } + + export interface NotificationTaskDeleteChangeRuleParams { + ruleId: string; + user: string; + } + + export interface NotificationTaskNotifySessionParams { + sessionid: string; + deleteAfter: boolean; + user: string; + } + + export interface NotificationTaskQueryChangeRulesParams { + name: string; + description: string; + searchType: string; + user: string; + } + + export interface NotificationTaskRunSpatialNotificationOnHistoryParams { + dataWorkspaceId: string; + from: Date; + to: Date; + logMatches: boolean; + send: boolean; + user: string; + } + + export interface NotificationTaskSendNotificationParams { + jobId: number; + notificationType: string; + user: string; + } + + export interface NotificationTaskSubscribeToNotificationParams { + notificationTypeId: number; + email: string; + user: string; + } + + export interface NotificationTaskUnsubscribeFromNotificationParams { + notificationTypeId: number; + email: string; + user: string; + } + + export interface ReportTaskGenerateReportParams { + reportId: number; + user: string; + } + + export interface ReportTaskGetReportContentUrlParams { + reportId: number; + user: number; + } + + export interface ReportTaskGetReportDataParams { + reportId: number; + user: string; + } + + export interface TokenTaskParseTokensParams { + jobId: any; + stringToParse: string; + user: string; + } + + export interface WorkflowTaskCanRunStepParams { + jobId: number; + stepId: number; + user: string; + } + + export interface WorkflowTaskExecuteStepsParams { + jobId: number; + stepIds: number[]; + auto: boolean; + user: string; + } + + export interface WorkflowTaskGetStepDescriptionParams { + jobId: number; + stepId: number; + } + + export interface WorkflowTaskGetStepFileUrlParams { + jobId: number; + stepId: number; + } + + export interface WorkflowTaskGetStepParams { + jobId: number; + stepId: number; + } + + export interface WorkflowTaskMarkStepsAsDoneParams { + jobId: number; + stepIds: number[]; + user: string; + } + + export interface WorkflowTaskMoveToNextStepParams { + jobId: number; + stepId: number; + returnCode: number; + user: string; + } + + export interface WorkflowTaskRecreateWorkflowParams { + jobId: number; + user: string; + } + + export interface WorkflowTaskResolveConflictParams { + jobId: number; + stepId: number; + optionReturnCode: number; + optionStepIds: number[]; + user: string; + } + + export interface WorkflowTaskSetCurrentStepParams { + jobId: number; + stepId: number; + user: string; + } + export interface MapViewConstraints { lods?: LOD[]; minScale?: number; @@ -804,6 +1625,17 @@ declare namespace __esri { urlPrefix: string; } + export interface configWorkers { + loaderConfig: configWorkersLoaderConfig; + } + + export interface configWorkersLoaderConfig { + has: any; + paths: any; + map: any; + packages: any[]; + } + export interface requestEsriRequestOptions { callbackParamName?: string; query?: any; @@ -827,6 +1659,7 @@ declare namespace __esri { cast?: Function; readOnly?: boolean; aliasOf?: string; + value?: any; } export interface colorCreateContinuousRendererParams { @@ -895,21 +1728,22 @@ declare namespace __esri { title: string; } - export interface sizeCreateVisualVariableParams { + export interface sizeCreateVisualVariablesParams { layer: FeatureLayer | SceneLayer; field: string; normalizationField?: string; basemap?: string | Basemap; sizeScheme?: any | any | any; - legendOptions?: sizeCreateVisualVariableParamsLegendOptions; + legendOptions?: sizeCreateVisualVariablesParamsLegendOptions; statistics?: any; minValue?: number; maxValue?: number; view?: SceneView; worldScale?: boolean; + axis?: boolean; } - export interface sizeCreateVisualVariableParamsLegendOptions { + export interface sizeCreateVisualVariablesParamsLegendOptions { title: string; } @@ -972,6 +1806,7 @@ declare namespace __esri { } export interface univariateColorSizeCreateVisualVariablesParamsSizeOptions { + axis?: boolean; sizeScheme?: any | any | any; legendOptions?: univariateColorSizeCreateVisualVariablesParamsSizeOptionsLegendOptions; } @@ -1433,6 +2268,7 @@ declare namespace __esri { expand(factor: number): Extent; intersection(extent: Extent): Extent; intersects(geometry: Geometry): boolean; + normalize(): Extent[]; offset(dx: number, dy: number, dz: number): Extent; union(extent: Extent): Extent; } @@ -1519,6 +2355,7 @@ declare namespace __esri { copy(other: Point): void; distance(other: Point): number; equals(point: Point): boolean; + normalize(): Point; } interface PointConstructor { @@ -1556,6 +2393,9 @@ declare namespace __esri { interface PolygonConstructor { new(properties?: PolygonProperties): Polygon; + + fromExtent(extent: Extent): Polygon; + fromJSON(json: any): Polygon; } @@ -1873,6 +2713,7 @@ declare namespace __esri { } interface FeatureLayer extends Layer, PortalLayer, ScaleRangeLayer { + capabilities: FeatureLayerCapabilities; copyright: string; definitionExpression: string; elevationInfo: FeatureLayerElevationInfo; @@ -1898,7 +2739,9 @@ declare namespace __esri { url: string; version: number; + applyEdits(edits: FeatureLayerApplyEditsEdits): IPromise; createQuery(): Query; + getFieldDomain(fieldName: string, options?: FeatureLayerGetFieldDomainOptions): Domain; queryExtent(params?: Query): IPromise; queryFeatureCount(params?: Query): IPromise; queryFeatures(params?: Query): IPromise; @@ -1914,6 +2757,7 @@ declare namespace __esri { export const FeatureLayer: FeatureLayerConstructor; interface FeatureLayerProperties extends LayerProperties, PortalLayerProperties, ScaleRangeLayerProperties { + capabilities?: FeatureLayerCapabilities; copyright?: string; definitionExpression?: string; elevationInfo?: FeatureLayerElevationInfo; @@ -1940,6 +2784,26 @@ declare namespace __esri { version?: number; } + interface GeoRSSLayer extends Layer { + lineSymbol: SimpleLineSymbol; + pointSymbol: PictureMarkerSymbol; + polygonSymbol: SimpleFillSymbol; + url: string; + } + + interface GeoRSSLayerConstructor { + new(properties?: GeoRSSLayerProperties): GeoRSSLayer; + } + + export const GeoRSSLayer: GeoRSSLayerConstructor; + + interface GeoRSSLayerProperties extends LayerProperties { + lineSymbol?: SimpleLineSymbolProperties; + pointSymbol?: PictureMarkerSymbolProperties; + polygonSymbol?: SimpleFillSymbolProperties; + url?: string; + } + interface GraphicsLayer extends Layer, ScaleRangeLayer { elevationInfo: GraphicsLayerElevationInfo; graphics: Collection; @@ -2061,6 +2925,7 @@ declare namespace __esri { } interface SceneLayer extends Layer, SceneService, PortalLayer { + definitionExpression: string; elevationInfo: SceneLayerElevationInfo; fields: Field[]; geometryType: string; @@ -2072,6 +2937,7 @@ declare namespace __esri { popupTemplate: PopupTemplate; renderer: Renderer; + createQuery(): Query; getFieldUsageInfo(fieldName: string): any; queryExtent(params?: Query): IPromise; queryFeatureCount(params?: Query): IPromise; @@ -2088,6 +2954,7 @@ declare namespace __esri { export const SceneLayer: SceneLayerConstructor; interface SceneLayerProperties extends LayerProperties, SceneServiceProperties, PortalLayerProperties { + definitionExpression?: string; elevationInfo?: SceneLayerElevationInfo; fields?: FieldProperties[]; geometryType?: string; @@ -2101,9 +2968,12 @@ declare namespace __esri { } interface StreamLayer extends FeatureLayer { + filter: StreamLayerFilter; geometryDefinition: Extent; maximumTrackPoints: number; - purgeOptions: any; + purgeOptions: StreamLayerPurgeOptions; + + updateFilter(filterChanges: StreamLayerUpdateFilterFilterChanges): IPromise; } interface StreamLayerConstructor { @@ -2115,9 +2985,10 @@ declare namespace __esri { export const StreamLayer: StreamLayerConstructor; interface StreamLayerProperties extends FeatureLayerProperties { + filter?: StreamLayerFilter; geometryDefinition?: ExtentProperties; maximumTrackPoints?: number; - purgeOptions?: any; + purgeOptions?: StreamLayerPurgeOptions; } interface UnknownLayer extends Layer { @@ -2199,13 +3070,20 @@ declare namespace __esri { } interface CodedValueDomainConstructor { - new(properties?: any): CodedValueDomain; + new(properties?: CodedValueDomainProperties): CodedValueDomain; + getName(code: string | number): string; + + fromJSON(json: any): CodedValueDomain; } export const CodedValueDomain: CodedValueDomainConstructor; + interface CodedValueDomainProperties extends DomainProperties { + codedValues?: CodedValueDomainCodedValues[]; + } + interface DimensionalDefinition { dimensionName: string; isSlice: boolean; @@ -2221,20 +3099,25 @@ declare namespace __esri { export const DimensionalDefinition: DimensionalDefinitionConstructor; - interface Domain { + interface Domain extends Accessor, JSONSupport { name: string; type: string; - - toJSON(): any; } interface DomainConstructor { - new(): Domain; + new(properties?: DomainProperties): Domain; + + fromJSON(json: any): Domain; } export const Domain: DomainConstructor; - interface Field extends JSONSupport { + interface DomainProperties { + name?: string; + type?: string; + } + + interface Field extends Accessor, JSONSupport { alias: string; domain: Domain; editable: boolean; @@ -2254,7 +3137,7 @@ declare namespace __esri { interface FieldProperties { alias?: string; - domain?: Domain; + domain?: DomainProperties; editable?: boolean; length?: number; name?: string; @@ -2262,7 +3145,7 @@ declare namespace __esri { type?: string; } - interface ImageParameters { + interface ImageParameters extends Accessor { dpi: number; extent: Extent; format: string; @@ -2278,20 +3161,39 @@ declare namespace __esri { } interface ImageParametersConstructor { - new(properties?: any): ImageParameters; + new(properties?: ImageParametersProperties): ImageParameters; } export const ImageParameters: ImageParametersConstructor; + interface ImageParametersProperties { + dpi?: number; + extent?: ExtentProperties; + format?: string; + height?: number; + imageSpatialReference?: SpatialReferenceProperties; + layerDefinitions?: string[]; + layerIds?: number[]; + layerOption?: string; + transparent?: boolean; + width?: number; + } + interface InheritedDomain extends Domain { } interface InheritedDomainConstructor { - new(): InheritedDomain; + new(properties?: InheritedDomainProperties): InheritedDomain; + + fromJSON(json: any): InheritedDomain; } export const InheritedDomain: InheritedDomainConstructor; + interface InheritedDomainProperties extends DomainProperties { + + } + interface LabelClass extends Accessor, JSONSupport { labelExpression: string; labelExpressionInfo: LabelClassLabelExpressionInfo; @@ -2301,6 +3203,8 @@ declare namespace __esri { symbol: TextSymbol | LabelSymbol3D; useCodedValues: boolean; where: string; + + clone(): LabelClass; } interface LabelClassConstructor { @@ -2372,7 +3276,7 @@ declare namespace __esri { width?: number; } - interface MosaicRule extends JSONSupport { + interface MosaicRule extends Accessor, JSONSupport { ascending: boolean; lockRasterIds: number[]; method: string; @@ -2406,7 +3310,7 @@ declare namespace __esri { where?: string; } - interface PixelBlock { + interface PixelBlock extends Accessor { height: number; mask: number[]; pixels: number[][]; @@ -2421,23 +3325,39 @@ declare namespace __esri { } interface PixelBlockConstructor { - new(properties?: any): PixelBlock; + new(properties?: PixelBlockProperties): PixelBlock; } export const PixelBlock: PixelBlockConstructor; + interface PixelBlockProperties { + height?: number; + mask?: number[]; + pixels?: number[][]; + pixelType?: string; + statistics?: PixelBlockStatistics[]; + width?: number; + } + interface RangeDomain extends Domain { maxValue: number; minValue: number; } interface RangeDomainConstructor { - new(): RangeDomain; + new(properties?: RangeDomainProperties): RangeDomain; + + fromJSON(json: any): RangeDomain; } export const RangeDomain: RangeDomainConstructor; - interface RasterFunction extends JSONSupport { + interface RangeDomainProperties extends DomainProperties { + maxValue?: number; + minValue?: number; + } + + interface RasterFunction extends Accessor, JSONSupport { functionArguments: any; functionName: string; outputPixelType: string; @@ -2875,6 +3795,7 @@ declare namespace __esri { role: string; roleId: string; thumbnailUrl: string; + units: string; userContentUrl: string; username: string; @@ -2907,6 +3828,7 @@ declare namespace __esri { role?: string; roleId?: string; thumbnailUrl?: string; + units?: string; userContentUrl?: string; username?: string; } @@ -3005,7 +3927,7 @@ declare namespace __esri { valueExpression: string; valueExpressionTitle: string; - addUniqueValueInfo(valueOrInfo: string | any, symbol: Symbol): void; + addUniqueValueInfo(valueOrInfo: string | any, symbol?: Symbol): void; clone(): UniqueValueRenderer; getUniqueValueInfo(graphic: Graphic): any; removeUniqueValueInfo(value: string): void; @@ -3034,6 +3956,7 @@ declare namespace __esri { } interface PointCloudRenderer extends Accessor, JSONSupport { + pointSizeAlgorithm: PointCloudRendererPointSizeAlgorithm; pointsPerInch: number; } @@ -3046,6 +3969,7 @@ declare namespace __esri { export const PointCloudRenderer: PointCloudRendererConstructor; interface PointCloudRendererProperties { + pointSizeAlgorithm?: PointCloudRendererPointSizeAlgorithm; pointsPerInch?: number; } @@ -3133,6 +4057,30 @@ declare namespace __esri { type?: string; } + interface Action extends Accessor { + className: string; + id: string; + image: string; + title: string; + visible: boolean; + + clone(): Action; + } + + interface ActionConstructor { + new(properties?: ActionProperties): Action; + } + + export const Action: ActionConstructor; + + interface ActionProperties { + className?: string; + id?: string; + image?: string; + title?: string; + visible?: boolean; + } + interface ExtrudeSymbol3DLayer extends Symbol3DLayer { size: number; @@ -3817,8 +4765,6 @@ declare namespace __esri { } interface QueryTask extends Task { - gdbVersion: string; - execute(params: Query, requestOptions?: any): IPromise; executeForCount(params: Query, requestOptions?: any): IPromise; executeForExtent(params: Query, requestOptions?: any): IPromise; @@ -3833,7 +4779,7 @@ declare namespace __esri { export const QueryTask: QueryTaskConstructor; interface QueryTaskProperties extends TaskProperties { - gdbVersion?: string; + } interface PrintTask extends Task { @@ -4276,6 +5222,7 @@ declare namespace __esri { foundFieldName: string; layerId: number; layerName: string; + value: void; } interface FindResultConstructor { @@ -4292,6 +5239,7 @@ declare namespace __esri { foundFieldName?: string; layerId?: number; layerName?: string; + value?: void; } interface GeneralizeParameters extends Accessor { @@ -5042,6 +5990,173 @@ declare namespace __esri { trimExtendTo?: PolylineProperties; } + interface ConfigurationTask extends Task { + url: string; + + getAllGroups(requestOptions?: any): IPromise; + getAllUsers(requestOptions?: any): IPromise; + getDataWorkspaceDetails(params: ConfigurationTaskGetDataWorkspaceDetailsParams, requestOptions?: any): IPromise; + getGroup(groupId: number, requestOptions?: any): IPromise; + getJobTypeDetails(jobTypeId: number, requestOptions?: any): IPromise; + getPublicJobQueryDetails(queryId: number, requestOptions?: any): IPromise; + getServiceInfo(requestOptions?: any): IPromise; + getTableRelationshipsDetails(requestOptions?: any): IPromise; + getUser(user: string, requestOptions?: any): IPromise; + getUserJobQueryDetails(params: ConfigurationTaskGetUserJobQueryDetailsParams, requestOptions?: any): IPromise; + getVisibleJobTypes(user: string, requestOptions?: any): IPromise; + } + + interface ConfigurationTaskConstructor { + new(properties?: ConfigurationTaskProperties): ConfigurationTask; + } + + export const ConfigurationTask: ConfigurationTaskConstructor; + + interface ConfigurationTaskProperties extends TaskProperties { + url?: string; + } + + interface JobTask extends Task { + url: string; + + addEmbeddedAttachment(params: JobTaskAddEmbeddedAttachmentParams, requestOptions?: any): IPromise; + addLinkedAttachment(params: JobTaskAddLinkedAttachmentParams, requestOptions?: any): IPromise; + addLinkedRecord(params: JobTaskAddLinkedRecordParams, requestOptions?: any): IPromise; + assignJobs(params: JobTaskAssignJobsParams, requestOptions?: any): IPromise; + closeJobs(params: JobTaskCloseJobsParams, requestOptions?: any): IPromise; + createDependency(params: JobTaskCreateDependencyParams, requestOptions?: any): IPromise; + createHold(params: JobTaskCreateHoldParams, requestOptions?: any): IPromise; + createJobs(params: JobCreationParameters, requestOptions?: any): IPromise; + createJobVersion(params: JobTaskCreateJobVersionParams, requestOptions?: any): IPromise; + deleteAttachment(params: JobTaskDeleteAttachmentParams, requestOptions?: any): IPromise; + deleteDependency(params: JobTaskDeleteDependencyParams, requestOptions?: any): IPromise; + deleteJobs(params: JobTaskDeleteJobsParams, requestOptions?: any): IPromise; + deleteLinkedRecord(params: JobTaskDeleteLinkedRecordParams, requestOptions?: any): IPromise; + getActivityLog(jobId: number, requestOptions?: any): IPromise; + getAttachmentContentUrl(params: JobTaskGetAttachmentContentUrlParams): string; + getAttachments(jobId: number, requestOptions?: any): IPromise; + getDependencies(jobId: number, requestOptions?: any): IPromise; + getExtendedProperties(jobId: number, requestOptions?: any): IPromise; + getHolds(jobId: number, requestOptions?: any): IPromise; + getJob(jobId: number, requestOptions?: any): IPromise; + getJobIds(requestOptions?: any): IPromise; + getNotes(jobId: number, requestOptions?: any): IPromise; + listFieldValues(params: JobTaskListFieldValuesParams, requestOptions?: any): IPromise; + listMultiLevelFieldValues(params: JobTaskListMultiLevelFieldValuesParams, requestOptions?: any): IPromise; + logAction(params: JobTaskLogActionParams, requestOptions?: any): IPromise; + queryJobs(params: JobTaskQueryJobsParams, requestOptions?: any): IPromise; + queryJobsAdHoc(params: JobQueryParameters, requestOptions?: any): IPromise; + queryMultiLevelSelectedValues(params: JobTaskQueryMultiLevelSelectedValuesParams, requestOptions?: any): IPromise; + releaseHold(params: JobTaskReleaseHoldParams, requestOptions?: any): IPromise; + reopenClosedJobs(params: JobTaskReopenClosedJobsParams, requestOptions?: any): IPromise; + searchJobs(params: JobTaskSearchJobsParams, requestOptions?: any): IPromise; + unassignJobs(params: JobTaskUnassignJobsParams, requestOptions?: any): IPromise; + updateJob(params: JobUpdateParameters, requestOptions?: any): IPromise; + updateNotes(params: JobTaskUpdateNotesParams, requestOptions?: any): IPromise; + updateRecord(params: JobTaskUpdateRecordParams, requestOptions?: any): IPromise; + } + + interface JobTaskConstructor { + new(properties?: JobTaskProperties): JobTask; + } + + export const JobTask: JobTaskConstructor; + + interface JobTaskProperties extends TaskProperties { + url?: string; + } + + interface NotificationTask extends Task { + url: string; + + addChangeRule(params: NotificationTaskAddChangeRuleParams, requestOptions?: any): IPromise; + deleteChangeRule(params: NotificationTaskDeleteChangeRuleParams, requestOptions?: any): IPromise; + getAllChangeRules(requestOptions?: any): IPromise; + getChangeRule(ruleId: string, requestOptions?: any): IPromise; + getChangeRuleMatch(matchId: string, requestOptions?: any): IPromise; + getDatabaseTime(dataWorkspaceId: string, requestOptions?: any): IPromise; + getSessionMatches(sessionId: string, requestOptions?: any): IPromise; + notifySession(params: NotificationTaskNotifySessionParams, requestOptions?: any): IPromise; + queryChangeRules(params: NotificationTaskQueryChangeRulesParams, requestOptions?: any): IPromise; + runSpatialNotificationOnHistory(params: NotificationTaskRunSpatialNotificationOnHistoryParams, requestOptions?: any): IPromise; + sendNotification(params: NotificationTaskSendNotificationParams, requestOptions?: any): IPromise; + subscribeToNotification(params: NotificationTaskSubscribeToNotificationParams, requestOptions?: any): IPromise; + unsubscribeFromNotification(params: NotificationTaskUnsubscribeFromNotificationParams, requestOptions?: any): IPromise; + } + + interface NotificationTaskConstructor { + new(properties?: NotificationTaskProperties): NotificationTask; + } + + export const NotificationTask: NotificationTaskConstructor; + + interface NotificationTaskProperties extends TaskProperties { + url?: string; + } + + interface ReportTask extends Task { + url: string; + + generateReport(params: ReportTaskGenerateReportParams, requestOptions?: any): IPromise; + getAllReports(requestOptions?: any): IPromise; + getReportContentUrl(params: ReportTaskGetReportContentUrlParams): string; + getReportData(params: ReportTaskGetReportDataParams, requestOptions?: any): IPromise; + getReportStylesheet(reportId: number, requestOptions?: any): IPromise; + } + + interface ReportTaskConstructor { + new(properties?: ReportTaskProperties): ReportTask; + } + + export const ReportTask: ReportTaskConstructor; + + interface ReportTaskProperties extends TaskProperties { + url?: string; + } + + interface TokenTask extends Task { + parseTokens(params: TokenTaskParseTokensParams, requestOptions?: any): IPromise; + } + + interface TokenTaskConstructor { + new(properties?: TokenTaskProperties): TokenTask; + } + + export const TokenTask: TokenTaskConstructor; + + interface TokenTaskProperties extends TaskProperties { + + } + + interface WorkflowTask extends Task { + url: string; + + canRunStep(params: WorkflowTaskCanRunStepParams, requestOptions?: any): IPromise; + executeSteps(params: WorkflowTaskExecuteStepsParams, requestOptions?: any): IPromise; + getAllSteps(jobId: number, requestOptions?: any): IPromise; + getCurrentSteps(jobId: number, requestOptions?: any): IPromise; + getStep(params: WorkflowTaskGetStepParams, requestOptions?: any): IPromise; + getStepDescription(params: WorkflowTaskGetStepDescriptionParams, requestOptions?: any): IPromise; + getStepFileUrl(params: WorkflowTaskGetStepFileUrlParams): string; + getWorkflowDisplayDetails(jobId: number, requestOptions?: any): IPromise; + getWorkflowImageUrl(jobId: number): string; + markStepsAsDone(params: WorkflowTaskMarkStepsAsDoneParams, requestOptions?: any): IPromise; + moveToNextStep(params: WorkflowTaskMoveToNextStepParams, requestOptions?: any): IPromise; + recreateWorkflow(params: WorkflowTaskRecreateWorkflowParams, requestOptions?: any): IPromise; + resolveConflict(params: WorkflowTaskResolveConflictParams, requestOptions?: any): IPromise; + setCurrentStep(params: WorkflowTaskSetCurrentStepParams, requestOptions?: any): IPromise; + } + + interface WorkflowTaskConstructor { + new(properties?: WorkflowTaskProperties): WorkflowTask; + } + + export const WorkflowTask: WorkflowTaskConstructor; + + interface WorkflowTaskProperties extends TaskProperties { + url?: string; + } + interface MapView extends View { center: Point; constraints: MapViewConstraints; @@ -5053,6 +6168,7 @@ declare namespace __esri { zoom: number; goTo(target: number[] | Geometry | Geometry[] | Graphic | Graphic[] | Viewpoint | any, options?: MapViewGoToOptions): IPromise; + hasEventListener(type: string): boolean; hitTest(screenPoint: MapViewHitTestScreenPoint): IPromise; on(type: string | string[], modifiersOrHandler: string[] | Function, handler?: Function): any; toMap(screenPoint: ScreenPoint, mapPoint?: Point): Point; @@ -5090,6 +6206,7 @@ declare namespace __esri { zoom: number; goTo(target: number[] | Geometry | Geometry[] | Graphic | Graphic[] | Viewpoint | Camera | any, options?: SceneViewGoToOptions): IPromise; + hasEventListener(type: string): boolean; hitTest(screenPoint: SceneViewHitTestScreenPoint): IPromise; on(type: string | string[], modifiersOrHandler: string[] | Function, handler?: Function): any; toMap(screenPoint: ScreenPoint, mapPoint?: Point): Point; @@ -5116,7 +6233,7 @@ declare namespace __esri { zoom?: number; } - interface View extends Accessor, corePromise, Evented, BreakpointsOwner, DOMContainer { + interface View extends Accessor, corePromise, BreakpointsOwner, DOMContainer { allLayerViews: Collection; animation: ViewAnimation; graphics: Collection; @@ -5238,16 +6355,33 @@ declare namespace __esri { pixelData?: ImageryLayerViewPixelData; } + interface SceneLayerView extends LayerView { + queryExtent(params?: Query): IPromise; + queryFeatureCount(params?: Query): IPromise; + queryFeatures(params?: Query): IPromise; + queryObjectIds(params?: Query): IPromise; + } + + interface SceneLayerViewConstructor { + new(properties?: SceneLayerViewProperties): SceneLayerView; + } + + export const SceneLayerView: SceneLayerViewConstructor; + + interface SceneLayerViewProperties extends LayerViewProperties { + + } + interface UI extends Accessor { container: any; height: number; padding: any; - view: SceneView | MapView; + view: MapView | SceneView; width: number; - add(component: any | any[], position?: string | any): void; + add(component: Widget | any | string | any | any, position?: string | any): void; empty(position?: string): void; - move(component: any | any[], position?: string): void; + move(component: Widget | any | string | any | any, position?: string): void; remove(component: any | any[]): void; } @@ -5261,7 +6395,7 @@ declare namespace __esri { container?: any; height?: number; padding?: any | number; - view?: SceneView | MapView; + view?: MapView | SceneView; width?: number; } @@ -5406,9 +6540,11 @@ declare namespace __esri { visibleLayers?: SlideVisibleLayers; } - interface Attribution extends Accessor { - view: SceneView | MapView; + interface Attribution extends Widget { + view: MapView | SceneView; viewModel: AttributionViewModel; + + render(): any; } interface AttributionConstructor { @@ -5417,18 +6553,41 @@ declare namespace __esri { export const Attribution: AttributionConstructor; - interface AttributionProperties { - view?: SceneView | MapView; + interface AttributionProperties extends WidgetProperties { + view?: MapView | SceneView; viewModel?: AttributionViewModel; } - interface BasemapToggle extends Accessor, Evented { + interface BasemapGallery extends Widget { + activeBasemap: Basemap; + source: LocalBasemapsSource | PortalBasemapsSource; + view: MapView | SceneView; + viewModel: BasemapGalleryViewModel; + + render(): any; + } + + interface BasemapGalleryConstructor { + new(properties?: BasemapGalleryProperties): BasemapGallery; + } + + export const BasemapGallery: BasemapGalleryConstructor; + + interface BasemapGalleryProperties extends WidgetProperties { + activeBasemap?: BasemapProperties; + source?: LocalBasemapsSource | PortalBasemapsSource; + view?: MapView | SceneView; + viewModel?: BasemapGalleryViewModelProperties; + } + + interface BasemapToggle extends Widget { activeBasemap: Basemap; nextBasemap: Basemap; titleVisible: boolean; - view: SceneView | MapView; + view: MapView | SceneView; viewModel: BasemapToggleViewModel; + render(): any; toggle(): void; } @@ -5438,15 +6597,15 @@ declare namespace __esri { export const BasemapToggle: BasemapToggleConstructor; - interface BasemapToggleProperties { + interface BasemapToggleProperties extends WidgetProperties { activeBasemap?: BasemapProperties; nextBasemap?: Basemap | string; titleVisible?: boolean; - view?: SceneView | MapView; + view?: MapView | SceneView; viewModel?: BasemapToggleViewModelProperties; } - interface ColorSlider extends Accessor { + interface ColorSlider extends Accessor, Widgette { handlesVisible: boolean; histogram: any; histogramVisible: boolean; @@ -5469,7 +6628,7 @@ declare namespace __esri { export const ColorSlider: ColorSliderConstructor; - interface ColorSliderProperties { + interface ColorSliderProperties extends WidgetteProperties { handlesVisible?: boolean; histogram?: any; histogramVisible?: boolean; @@ -5486,10 +6645,11 @@ declare namespace __esri { visualVariable?: any; } - interface Compass extends Accessor { - view: SceneView | MapView; + interface Compass extends Widget { + view: MapView | SceneView; viewModel: CompassViewModel; + render(): any; reset(): void; } @@ -5499,17 +6659,51 @@ declare namespace __esri { export const Compass: CompassConstructor; - interface CompassProperties { - view?: SceneView | MapView; + interface CompassProperties extends WidgetProperties { + view?: MapView | SceneView; viewModel?: CompassViewModelProperties; } - interface Home extends Accessor, Evented { + interface Expand extends Widget { + collapseTooltip: string; + content: any; + expanded: boolean; + expandIconClass: string; + expandTooltip: string; + iconNumber: string; + view: MapView | SceneView; + viewModel: ExpandViewModel; + + collapse(): void; + expand(): void; + render(): any; + toggle(): void; + } + + interface ExpandConstructor { + new(properties?: ExpandProperties): Expand; + } + + export const Expand: ExpandConstructor; + + interface ExpandProperties extends WidgetProperties { + collapseTooltip?: string; + content?: any | any | string | Widget; + expanded?: boolean; + expandIconClass?: string; + expandTooltip?: string; + iconNumber?: string; + view?: MapView | SceneView; + viewModel?: ExpandViewModelProperties; + } + + interface Home extends Widget { view: MapView | SceneView; viewModel: HomeViewModel; viewpoint: Viewpoint; go(): void; + render(): any; } interface HomeConstructor { @@ -5518,7 +6712,7 @@ declare namespace __esri { export const Home: HomeConstructor; - interface HomeProperties { + interface HomeProperties extends WidgetProperties { view?: MapView | SceneView; viewModel?: HomeViewModelProperties; viewpoint?: ViewpointProperties; @@ -5526,10 +6720,12 @@ declare namespace __esri { interface LayerList extends Widget { createActionsFunction: Function; - view: SceneView | MapView; + operationalItems: Collection; + view: MapView | SceneView; viewModel: LayerListViewModel; render(): any; + triggerAction(action: Action, item: ListItem): void; } interface LayerListConstructor { @@ -5540,13 +6736,14 @@ declare namespace __esri { interface LayerListProperties extends WidgetProperties { createActionsFunction?: Function; - view?: SceneView | MapView; + operationalItems?: Collection; + view?: MapView | SceneView; viewModel?: LayerListViewModelProperties; } - interface Legend extends Accessor { + interface Legend extends Accessor, Widgette { layerInfos: LegendLayerInfos[]; - view: SceneView | MapView; + view: MapView | SceneView; } interface LegendConstructor { @@ -5555,12 +6752,12 @@ declare namespace __esri { export const Legend: LegendConstructor; - interface LegendProperties { + interface LegendProperties extends WidgetteProperties { layerInfos?: LegendLayerInfos[]; - view?: SceneView | MapView; + view?: MapView | SceneView; } - interface Locate extends Accessor, Evented { + interface Locate extends Widget { geolocationOptions: any; goToLocationEnabled: boolean; graphic: Graphic; @@ -5568,6 +6765,7 @@ declare namespace __esri { viewModel: LocateViewModel; locate(): IPromise; + render(): any; } interface LocateConstructor { @@ -5576,7 +6774,7 @@ declare namespace __esri { export const Locate: LocateConstructor; - interface LocateProperties { + interface LocateProperties extends WidgetProperties { geolocationOptions?: any; goToLocationEnabled?: boolean; graphic?: GraphicProperties; @@ -5584,11 +6782,12 @@ declare namespace __esri { viewModel?: LocateViewModelProperties; } - interface NavigationToggle extends Accessor { + interface NavigationToggle extends Widget { layout: string; view: SceneView; viewModel: NavigationToggleViewModel; + render(): any; toggle(): void; } @@ -5598,13 +6797,13 @@ declare namespace __esri { export const NavigationToggle: NavigationToggleConstructor; - interface NavigationToggleProperties { + interface NavigationToggleProperties extends WidgetProperties { layout?: string; view?: SceneViewProperties; viewModel?: NavigationToggleViewModelProperties; } - interface Popup extends Accessor, Evented { + interface Popup extends Accessor, Widgette, Evented { actions: Collection; content: string; currentDockPosition: string; @@ -5636,7 +6835,7 @@ declare namespace __esri { export const Popup: PopupConstructor; - interface PopupProperties { + interface PopupProperties extends WidgetteProperties { actions?: Collection; content?: string | any; currentDockPosition?: string; @@ -5674,12 +6873,34 @@ declare namespace __esri { viewModel?: PrintViewModelProperties; } - interface Search extends Accessor, Evented { + interface ScaleBar extends Widget { + style: string; + unit: string; + view: MapView; + viewModel: ScaleBarViewModel; + + render(): any; + } + + interface ScaleBarConstructor { + new(properties?: ScaleBarProperties): ScaleBar; + } + + export const ScaleBar: ScaleBarConstructor; + + interface ScaleBarProperties extends WidgetProperties { + style?: string; + unit?: string; + view?: MapViewProperties; + viewModel?: ScaleBarViewModelProperties; + } + + interface Search extends Widget { activeSource: FeatureLayer | Locator; activeSourceIndex: number; allPlaceholder: string; autoSelect: boolean; - defaultSource: any; + defaultSource: any | any; maxResults: number; maxSuggestions: number; minSuggestCharacters: number; @@ -5690,6 +6911,7 @@ declare namespace __esri { resultGraphicEnabled: boolean; results: any[]; searchAllEnabled: boolean; + searching: boolean; searchTerm: string; selectedResult: any; sources: SearchSources; @@ -5699,6 +6921,7 @@ declare namespace __esri { viewModel: SearchViewModel; clear(): void; + render(): any; search(searchTerm?: string | Geometry | any | number[][]): IPromise; suggest(value?: string): IPromise; } @@ -5709,12 +6932,12 @@ declare namespace __esri { export const Search: SearchConstructor; - interface SearchProperties { + interface SearchProperties extends WidgetProperties { activeSource?: FeatureLayer | Locator; activeSourceIndex?: number; allPlaceholder?: string; autoSelect?: boolean; - defaultSource?: any; + defaultSource?: any | any; maxResults?: number; maxSuggestions?: number; minSuggestCharacters?: number; @@ -5725,6 +6948,7 @@ declare namespace __esri { resultGraphicEnabled?: boolean; results?: any[]; searchAllEnabled?: boolean; + searching?: boolean; searchTerm?: string; selectedResult?: any; sources?: SearchSources; @@ -5734,7 +6958,7 @@ declare namespace __esri { viewModel?: SearchViewModelProperties; } - interface SizeSlider extends Accessor { + interface SizeSlider extends Accessor, Widgette { handlesVisible: boolean; histogram: any; histogramVisible: boolean; @@ -5757,7 +6981,7 @@ declare namespace __esri { export const SizeSlider: SizeSliderConstructor; - interface SizeSliderProperties { + interface SizeSliderProperties extends WidgetteProperties { handlesVisible?: boolean; histogram?: any; histogramVisible?: boolean; @@ -5774,7 +6998,7 @@ declare namespace __esri { visualVariable?: any; } - interface Track extends Accessor { + interface Track extends Widget { geolocationOptions: any; goToLocationEnabled: boolean; graphic: Graphic; @@ -5782,6 +7006,7 @@ declare namespace __esri { view: MapView | SceneView; viewModel: TrackViewModel; + render(): any; start(): void; stop(): void; } @@ -5792,7 +7017,7 @@ declare namespace __esri { export const Track: TrackConstructor; - interface TrackProperties { + interface TrackProperties extends WidgetProperties { geolocationOptions?: any; goToLocationEnabled?: boolean; graphic?: GraphicProperties; @@ -5801,7 +7026,7 @@ declare namespace __esri { viewModel?: TrackViewModelProperties; } - interface UnivariateColorSizeSlider extends Accessor { + interface UnivariateColorSizeSlider extends Accessor, Widgette { handlesVisible: boolean; histogram: any; histogramVisible: boolean; @@ -5824,7 +7049,7 @@ declare namespace __esri { export const UnivariateColorSizeSlider: UnivariateColorSizeSliderConstructor; - interface UnivariateColorSizeSliderProperties { + interface UnivariateColorSizeSliderProperties extends WidgetteProperties { handlesVisible?: boolean; histogram?: any; histogramVisible?: boolean; @@ -5847,7 +7072,9 @@ declare namespace __esri { id: string; destroy(): void; + own(handles: any[]): void; postInitialize(): void; + renderNow(): void; scheduleRender(): void; startup(): void; } @@ -5859,15 +7086,16 @@ declare namespace __esri { export const Widget: WidgetConstructor; interface WidgetProperties { - container?: string; + container?: string | any; destroyed?: boolean; id?: string; } - interface Zoom extends Accessor { - view: SceneView | MapView; + interface Zoom extends Widget { + view: MapView | SceneView; viewModel: ZoomViewModel; + render(): any; zoomIn(): void; zoomOut(): void; } @@ -5878,8 +7106,8 @@ declare namespace __esri { export const Zoom: ZoomConstructor; - interface ZoomProperties { - view?: SceneView | MapView; + interface ZoomProperties extends WidgetProperties { + view?: MapView | SceneView; viewModel?: ZoomViewModelProperties; } @@ -5887,7 +7115,7 @@ declare namespace __esri { attributionText: string; itemDelimiter: string; state: string; - view: SceneView | MapView; + view: MapView | SceneView; } interface AttributionViewModelConstructor { @@ -5896,11 +7124,35 @@ declare namespace __esri { export const AttributionViewModel: AttributionViewModelConstructor; + interface BasemapGalleryViewModel extends Accessor { + activeBasemap: Basemap; + items: Collection; + source: LocalBasemapsSource | PortalBasemapsSource; + state: string; + view: MapView | SceneView; + + basemapEquals(basemap1: Basemap, basemap2: Basemap): boolean; + } + + interface BasemapGalleryViewModelConstructor { + new(properties?: BasemapGalleryViewModelProperties): BasemapGalleryViewModel; + } + + export const BasemapGalleryViewModel: BasemapGalleryViewModelConstructor; + + interface BasemapGalleryViewModelProperties { + activeBasemap?: BasemapProperties; + items?: Collection; + source?: LocalBasemapsSource | PortalBasemapsSource; + state?: string; + view?: MapView | SceneView; + } + interface BasemapToggleViewModel extends Accessor, Evented { activeBasemap: Basemap; nextBasemap: Basemap; state: string; - view: SceneView | MapView; + view: MapView | SceneView; toggle(): void; } @@ -5915,12 +7167,13 @@ declare namespace __esri { activeBasemap?: BasemapProperties; nextBasemap?: Basemap | string; state?: string; - view?: SceneView | MapView; + view?: MapView | SceneView; } interface CompassViewModel extends Accessor { + orientation: any; state: string; - view: SceneView | MapView; + view: MapView | SceneView; reset(): void; } @@ -5932,8 +7185,27 @@ declare namespace __esri { export const CompassViewModel: CompassViewModelConstructor; interface CompassViewModelProperties { + orientation?: any; state?: string; - view?: SceneView | MapView; + view?: MapView | SceneView; + } + + interface ExpandViewModel extends Accessor { + expanded: boolean; + state: string; + view: MapView | SceneView; + } + + interface ExpandViewModelConstructor { + new(properties?: ExpandViewModelProperties): ExpandViewModel; + } + + export const ExpandViewModel: ExpandViewModelConstructor; + + interface ExpandViewModelProperties { + expanded?: boolean; + state?: string; + view?: MapView | SceneView; } interface HomeViewModel extends Accessor, Evented { @@ -5960,9 +7232,9 @@ declare namespace __esri { createActionsFunction: Function; operationalItems: Collection; state: string; - view: SceneView | MapView; + view: MapView | SceneView; - triggerAction(actionIndex: number): void; + triggerAction(action: Action, item: ListItem): void; } interface LayerListViewModelConstructor { @@ -5975,9 +7247,32 @@ declare namespace __esri { createActionsFunction?: Function; operationalItems?: Collection; state?: string; - view?: SceneView | MapView; + view?: MapView | SceneView; } + interface ListItem { + actionsOpen: boolean; + actionsSections: Collection; + children: Collection; + error: Error; + layer: Layer; + open: boolean; + title: string; + updating: boolean; + view: MapView | SceneView; + visibilityMode: string; + visible: boolean; + visibleAtCurrentScale: boolean; + + clone(): ListItem; + } + + interface ListItemConstructor { + new(): ListItem; + } + + export const ListItem: ListItemConstructor; + interface LocateViewModel extends Accessor, Evented, GeolocationPositioning { state: string; @@ -6075,6 +7370,20 @@ declare namespace __esri { view?: MapView | SceneView; } + interface ScaleBarViewModel extends Accessor { + view: MapView; + } + + interface ScaleBarViewModelConstructor { + new(properties?: ScaleBarViewModelProperties): ScaleBarViewModel; + } + + export const ScaleBarViewModel: ScaleBarViewModelConstructor; + + interface ScaleBarViewModelProperties { + view?: MapViewProperties; + } + interface SearchViewModel extends Accessor, Evented { activeSource: FeatureLayer | Locator; activeSourceIndex: number; @@ -6163,7 +7472,7 @@ declare namespace __esri { canZoomIn: boolean; canZoomOut: boolean; state: string; - view: SceneView | MapView; + view: MapView | SceneView; zoomIn(): void; zoomOut(): void; @@ -6179,7 +7488,7 @@ declare namespace __esri { canZoomIn?: boolean; canZoomOut?: boolean; state?: string; - view?: SceneView | MapView; + view?: MapView | SceneView; } interface JSONSupport { @@ -6301,6 +7610,8 @@ declare namespace __esri { dpi: number; gdbVersion: string; imageFormat: string; + imageMaxHeight: number; + imageMaxWidth: number; imageTransparency: boolean; sublayers: Collection; @@ -6320,6 +7631,8 @@ declare namespace __esri { dpi?: number; gdbVersion?: string; imageFormat?: string; + imageMaxHeight?: number; + imageMaxWidth?: number; imageTransparency?: boolean; sublayers?: Collection; } @@ -6547,6 +7860,24 @@ declare namespace __esri { width?: number; } + interface Widgette { + container: string | any; + visible: boolean; + + destroy(): void; + } + + interface WidgetteConstructor { + new(): Widgette; + } + + export const Widgette: WidgetteConstructor; + + interface WidgetteProperties { + container?: string | any; + visible?: boolean; + } + interface GeolocationPositioning { geolocationOptions: any; goToLocationEnabled: boolean; @@ -6569,8 +7900,10 @@ declare namespace __esri { interface config { geometryServiceUrl: string; + geoRSSServiceUrl: string; portalUrl: string; request: configRequest; + workers: configWorkers; } export const config: config; @@ -6596,13 +7929,19 @@ declare namespace __esri { export const lang: lang; interface promiseUtils { - eachAlways(promises: IPromise[]): IPromise[]; - reject(error?: any): IPromise; - resolve(value?: any): IPromise; + eachAlways(promises: IPromise[] | any): IPromise | any; + reject(error?: any): IPromise; + resolve(value?: T): IPromise; } export const promiseUtils: promiseUtils; + interface requireUtils { + when(moduleRequire: any, moduleNames: string[] | string): IPromise; + } + + export const requireUtils: requireUtils; + interface urlUtils { addProxyRule(rule: urlUtilsAddProxyRuleRule): number; getProxyRule(url: string): any; @@ -6636,7 +7975,7 @@ declare namespace __esri { interface decorators { aliasOf(propertyName: string): Function; cast(propertyName: string): Function; - cast(classFunction: Function): void; + cast(classFunction: Function): Function; declared(baseClass: T, ...mixinClasses: any[]): T; property(propertyMetadata?: decoratorsPropertyPropertyMetadata): Function; subclass(declaredClass?: string): Function; @@ -6739,6 +8078,12 @@ declare namespace __esri { export const jsonUtils: jsonUtils; + interface normalizeUtils { + normalizeCentralMeridian(geometries: Geometry[], geometryService?: GeometryService): IPromise; + } + + export const normalizeUtils: normalizeUtils; + interface webMercatorUtils { canProject(source: SpatialReference | any, target: SpatialReference | any): boolean; geographicToWebMercator(geometry: Geometry): Geometry; @@ -6765,7 +8110,7 @@ declare namespace __esri { interface size { createContinuousRenderer(params: sizeCreateContinuousRendererParams): IPromise; - createVisualVariable(params: sizeCreateVisualVariableParams): IPromise; + createVisualVariables(params: sizeCreateVisualVariablesParams): IPromise; } export const size: size; @@ -6787,13 +8132,17 @@ declare namespace __esri { histogram(params: histogramHistogramParams): IPromise; } - export const histogram: histogram; + const __histogramMapped: histogram; + export const histogram: typeof __histogramMapped.histogram; + interface summaryStatistics { summaryStatistics(params: summaryStatisticsSummaryStatisticsParams): IPromise; } - export const summaryStatistics: summaryStatistics; + const __summaryStatisticsMapped: summaryStatistics; + export const summaryStatistics: typeof __summaryStatisticsMapped.summaryStatistics; + interface symbologyColor { cloneScheme(scheme: any): any; @@ -6824,16 +8173,6 @@ declare namespace __esri { export const supportJsonUtils: supportJsonUtils; - interface Action { - className: string; - id: string; - image: string; - title: string; - visible: boolean; - } - - export const Action: Action; - interface symbolsSupportJsonUtils { fromJSON(json: any): Symbol; } @@ -6861,20 +8200,30 @@ declare namespace __esri { export const widget: widget; - interface ListItem { - actionsOpen: boolean; - actionsSections: Collection; - children: Collection; + interface BasemapGalleryItem { + basemap: Basemap; error: Error; - open: boolean; - title: string; - updating: boolean; - visibilityMode: string; - visible: boolean; - visibleAtCurrentScale: boolean; + state: string; + view: MapView | SceneView; } - export const ListItem: ListItem; + export const BasemapGalleryItem: BasemapGalleryItem; + + interface LocalBasemapsSource { + basemaps: Collection; + state: string; + } + + export const LocalBasemapsSource: LocalBasemapsSource; + + interface PortalBasemapsSource { + basemaps: Collection; + filterFunction: Function; + portal: Portal; + state: string; + } + + export const PortalBasemapsSource: PortalBasemapsSource; } declare module "esri" { @@ -6888,10 +8237,116 @@ declare module "esri" { export import WatchHandle = __esri.WatchHandle; + export import EachAlwaysResult = __esri.EachAlwaysResult; + export import PausableWatchHandle = __esri.PausableWatchHandle; + export import FeatureEditResult = __esri.FeatureEditResult; + export import AttributeParamValue = __esri.AttributeParamValue; + export import DataWorkspace = __esri.DataWorkspace; + + export import GroupMembership = __esri.GroupMembership; + + export import HoldType = __esri.HoldType; + + export import JobPriority = __esri.JobPriority; + + export import JobQuery = __esri.JobQuery; + + export import JobStatus = __esri.JobStatus; + + export import JobQueryContainer = __esri.JobQueryContainer; + + export import JobQueryDetails = __esri.JobQueryDetails; + + export import Privilege = __esri.Privilege; + + export import UserDetails = __esri.UserDetails; + + export import VersionInfo = __esri.VersionInfo; + + export import WorkflowManagerServiceInfo = __esri.WorkflowManagerServiceInfo; + + export import JobType = __esri.JobType; + + export import JobTypeDetails = __esri.JobTypeDetails; + + export import TableRelationship = __esri.TableRelationship; + + export import JobCreationParameters = __esri.JobCreationParameters; + + export import JobQueryParameters = __esri.JobQueryParameters; + + export import JobUpdateParameters = __esri.JobUpdateParameters; + + export import AuxRecordDescription = __esri.AuxRecordDescription; + + export import ActivityType = __esri.ActivityType; + + export import AuxRecordContainer = __esri.AuxRecordContainer; + + export import JobTaskJobInfo = __esri.JobTaskJobInfo; + + export import QueryResult = __esri.QueryResult; + + export import AuxRecord = __esri.AuxRecord; + + export import AuxRecordValue = __esri.AuxRecordValue; + + export import FieldValue = __esri.FieldValue; + + export import JobVersionInfo = __esri.JobVersionInfo; + + export import QueryFieldInfo = __esri.QueryFieldInfo; + + export import JobAttachment = __esri.JobAttachment; + + export import JobDependency = __esri.JobDependency; + + export import ChangeRule = __esri.ChangeRule; + + export import DataSetEvaluator = __esri.DataSetEvaluator; + + export import AOIEvaluator = __esri.AOIEvaluator; + + export import DatasetConfiguration = __esri.DatasetConfiguration; + + export import EmailNotifier = __esri.EmailNotifier; + + export import WhereCondition = __esri.WhereCondition; + + export import NotificationType = __esri.NotificationType; + + export import ChangeRuleMatch = __esri.ChangeRuleMatch; + + export import ReportDataGroup = __esri.ReportDataGroup; + + export import ReportData = __esri.ReportData; + + export import Report = __esri.Report; + + export import ExecuteInfo = __esri.ExecuteInfo; + + export import Step = __esri.Step; + + export import StepType = __esri.StepType; + + export import WorkflowDisplayDetails = __esri.WorkflowDisplayDetails; + + export import WorkflowOption = __esri.WorkflowOption; + + export import WorkflowStepInfo = __esri.WorkflowStepInfo; + + export import WorkflowAnnotationDisplayDetails = __esri.WorkflowAnnotationDisplayDetails; + + export import WorkflowConflicts = __esri.WorkflowConflicts; + + export import WorkflowPathDisplayDetails = __esri.WorkflowPathDisplayDetails; + + export import WorkflowStepDisplayDetails = __esri.WorkflowStepDisplayDetails; + export import ExternalRenderer = __esri.ExternalRenderer; export import RenderContext = __esri.RenderContext; @@ -6906,10 +8361,6 @@ declare module "esri" { export import FeatureLayerSource = __esri.FeatureLayerSource; - export import SearchViewModelLocatorSource = __esri.SearchViewModelLocatorSource; - - export import SearchViewModelFeatureLayerSource = __esri.SearchViewModelFeatureLayerSource; - export import GetHeader = __esri.GetHeader; export import WatchCallback = __esri.WatchCallback; @@ -6966,8 +8417,16 @@ declare module "esri" { export import CSVLayerElevationInfo = __esri.CSVLayerElevationInfo; + export import FeatureLayerApplyEditsEdits = __esri.FeatureLayerApplyEditsEdits; + + export import FeatureLayerCapabilities = __esri.FeatureLayerCapabilities; + + export import FeatureLayerCapabilitiesOperations = __esri.FeatureLayerCapabilitiesOperations; + export import FeatureLayerElevationInfo = __esri.FeatureLayerElevationInfo; + export import FeatureLayerGetFieldDomainOptions = __esri.FeatureLayerGetFieldDomainOptions; + export import GraphicsLayerElevationInfo = __esri.GraphicsLayerElevationInfo; export import LayerFromArcGISServerUrlParams = __esri.LayerFromArcGISServerUrlParams; @@ -6976,6 +8435,12 @@ declare module "esri" { export import SceneLayerElevationInfo = __esri.SceneLayerElevationInfo; + export import StreamLayerFilter = __esri.StreamLayerFilter; + + export import StreamLayerPurgeOptions = __esri.StreamLayerPurgeOptions; + + export import StreamLayerUpdateFilterFilterChanges = __esri.StreamLayerUpdateFilterFilterChanges; + export import VectorTileLayerCurrentStyleInfo = __esri.VectorTileLayerCurrentStyleInfo; export import CodedValueDomainCodedValues = __esri.CodedValueDomainCodedValues; @@ -7004,6 +8469,8 @@ declare module "esri" { export import UniqueValueRendererUniqueValueInfos = __esri.UniqueValueRendererUniqueValueInfos; + export import PointCloudRendererPointSizeAlgorithm = __esri.PointCloudRendererPointSizeAlgorithm; + export import PointCloudClassBreaksRendererColorClassBreakInfos = __esri.PointCloudClassBreaksRendererColorClassBreakInfos; export import PointCloudStretchRendererStops = __esri.PointCloudStretchRendererStops; @@ -7042,6 +8509,102 @@ declare module "esri" { export import QueryQuantizationParameters = __esri.QueryQuantizationParameters; + export import ConfigurationTaskGetDataWorkspaceDetailsParams = __esri.ConfigurationTaskGetDataWorkspaceDetailsParams; + + export import ConfigurationTaskGetUserJobQueryDetailsParams = __esri.ConfigurationTaskGetUserJobQueryDetailsParams; + + export import JobTaskAddEmbeddedAttachmentParams = __esri.JobTaskAddEmbeddedAttachmentParams; + + export import JobTaskAddLinkedAttachmentParams = __esri.JobTaskAddLinkedAttachmentParams; + + export import JobTaskAddLinkedRecordParams = __esri.JobTaskAddLinkedRecordParams; + + export import JobTaskAssignJobsParams = __esri.JobTaskAssignJobsParams; + + export import JobTaskCloseJobsParams = __esri.JobTaskCloseJobsParams; + + export import JobTaskCreateDependencyParams = __esri.JobTaskCreateDependencyParams; + + export import JobTaskCreateHoldParams = __esri.JobTaskCreateHoldParams; + + export import JobTaskCreateJobVersionParams = __esri.JobTaskCreateJobVersionParams; + + export import JobTaskDeleteAttachmentParams = __esri.JobTaskDeleteAttachmentParams; + + export import JobTaskDeleteDependencyParams = __esri.JobTaskDeleteDependencyParams; + + export import JobTaskDeleteJobsParams = __esri.JobTaskDeleteJobsParams; + + export import JobTaskDeleteLinkedRecordParams = __esri.JobTaskDeleteLinkedRecordParams; + + export import JobTaskGetAttachmentContentUrlParams = __esri.JobTaskGetAttachmentContentUrlParams; + + export import JobTaskListFieldValuesParams = __esri.JobTaskListFieldValuesParams; + + export import JobTaskListMultiLevelFieldValuesParams = __esri.JobTaskListMultiLevelFieldValuesParams; + + export import JobTaskLogActionParams = __esri.JobTaskLogActionParams; + + export import JobTaskQueryJobsParams = __esri.JobTaskQueryJobsParams; + + export import JobTaskQueryMultiLevelSelectedValuesParams = __esri.JobTaskQueryMultiLevelSelectedValuesParams; + + export import JobTaskReleaseHoldParams = __esri.JobTaskReleaseHoldParams; + + export import JobTaskReopenClosedJobsParams = __esri.JobTaskReopenClosedJobsParams; + + export import JobTaskSearchJobsParams = __esri.JobTaskSearchJobsParams; + + export import JobTaskUnassignJobsParams = __esri.JobTaskUnassignJobsParams; + + export import JobTaskUpdateNotesParams = __esri.JobTaskUpdateNotesParams; + + export import JobTaskUpdateRecordParams = __esri.JobTaskUpdateRecordParams; + + export import NotificationTaskAddChangeRuleParams = __esri.NotificationTaskAddChangeRuleParams; + + export import NotificationTaskDeleteChangeRuleParams = __esri.NotificationTaskDeleteChangeRuleParams; + + export import NotificationTaskNotifySessionParams = __esri.NotificationTaskNotifySessionParams; + + export import NotificationTaskQueryChangeRulesParams = __esri.NotificationTaskQueryChangeRulesParams; + + export import NotificationTaskRunSpatialNotificationOnHistoryParams = __esri.NotificationTaskRunSpatialNotificationOnHistoryParams; + + export import NotificationTaskSendNotificationParams = __esri.NotificationTaskSendNotificationParams; + + export import NotificationTaskSubscribeToNotificationParams = __esri.NotificationTaskSubscribeToNotificationParams; + + export import NotificationTaskUnsubscribeFromNotificationParams = __esri.NotificationTaskUnsubscribeFromNotificationParams; + + export import ReportTaskGenerateReportParams = __esri.ReportTaskGenerateReportParams; + + export import ReportTaskGetReportContentUrlParams = __esri.ReportTaskGetReportContentUrlParams; + + export import ReportTaskGetReportDataParams = __esri.ReportTaskGetReportDataParams; + + export import TokenTaskParseTokensParams = __esri.TokenTaskParseTokensParams; + + export import WorkflowTaskCanRunStepParams = __esri.WorkflowTaskCanRunStepParams; + + export import WorkflowTaskExecuteStepsParams = __esri.WorkflowTaskExecuteStepsParams; + + export import WorkflowTaskGetStepDescriptionParams = __esri.WorkflowTaskGetStepDescriptionParams; + + export import WorkflowTaskGetStepFileUrlParams = __esri.WorkflowTaskGetStepFileUrlParams; + + export import WorkflowTaskGetStepParams = __esri.WorkflowTaskGetStepParams; + + export import WorkflowTaskMarkStepsAsDoneParams = __esri.WorkflowTaskMarkStepsAsDoneParams; + + export import WorkflowTaskMoveToNextStepParams = __esri.WorkflowTaskMoveToNextStepParams; + + export import WorkflowTaskRecreateWorkflowParams = __esri.WorkflowTaskRecreateWorkflowParams; + + export import WorkflowTaskResolveConflictParams = __esri.WorkflowTaskResolveConflictParams; + + export import WorkflowTaskSetCurrentStepParams = __esri.WorkflowTaskSetCurrentStepParams; + export import MapViewConstraints = __esri.MapViewConstraints; export import MapViewGoToOptions = __esri.MapViewGoToOptions; @@ -7124,6 +8687,10 @@ declare module "esri" { export import configRequestProxyRules = __esri.configRequestProxyRules; + export import configWorkers = __esri.configWorkers; + + export import configWorkersLoaderConfig = __esri.configWorkersLoaderConfig; + export import requestEsriRequestOptions = __esri.requestEsriRequestOptions; export import urlUtilsAddProxyRuleRule = __esri.urlUtilsAddProxyRuleRule; @@ -7144,9 +8711,9 @@ declare module "esri" { export import sizeCreateContinuousRendererParamsLegendOptions = __esri.sizeCreateContinuousRendererParamsLegendOptions; - export import sizeCreateVisualVariableParams = __esri.sizeCreateVisualVariableParams; + export import sizeCreateVisualVariablesParams = __esri.sizeCreateVisualVariablesParams; - export import sizeCreateVisualVariableParamsLegendOptions = __esri.sizeCreateVisualVariableParamsLegendOptions; + export import sizeCreateVisualVariablesParamsLegendOptions = __esri.sizeCreateVisualVariablesParamsLegendOptions; export import univariateColorSizeCreateContinuousRendererParams = __esri.univariateColorSizeCreateContinuousRendererParams; @@ -7351,6 +8918,11 @@ declare module "esri/layers/FeatureLayer" { export = FeatureLayer; } +declare module "esri/layers/GeoRSSLayer" { + import GeoRSSLayer = __esri.GeoRSSLayer; + export = GeoRSSLayer; +} + declare module "esri/layers/GraphicsLayer" { import GraphicsLayer = __esri.GraphicsLayer; export = GraphicsLayer; @@ -7571,6 +9143,11 @@ declare module "esri/renderers/PointCloudUniqueValueRenderer" { export = PointCloudUniqueValueRenderer; } +declare module "esri/support/Action" { + import Action = __esri.Action; + export = Action; +} + declare module "esri/symbols/ExtrudeSymbol3DLayer" { import ExtrudeSymbol3DLayer = __esri.ExtrudeSymbol3DLayer; export = ExtrudeSymbol3DLayer; @@ -7961,6 +9538,36 @@ declare module "esri/tasks/support/TrimExtendParameters" { export = TrimExtendParameters; } +declare module "esri/tasks/workflow/ConfigurationTask" { + import ConfigurationTask = __esri.ConfigurationTask; + export = ConfigurationTask; +} + +declare module "esri/tasks/workflow/JobTask" { + import JobTask = __esri.JobTask; + export = JobTask; +} + +declare module "esri/tasks/workflow/NotificationTask" { + import NotificationTask = __esri.NotificationTask; + export = NotificationTask; +} + +declare module "esri/tasks/workflow/ReportTask" { + import ReportTask = __esri.ReportTask; + export = ReportTask; +} + +declare module "esri/tasks/workflow/TokenTask" { + import TokenTask = __esri.TokenTask; + export = TokenTask; +} + +declare module "esri/tasks/workflow/WorkflowTask" { + import WorkflowTask = __esri.WorkflowTask; + export = WorkflowTask; +} + declare module "esri/views/MapView" { import MapView = __esri.MapView; export = MapView; @@ -8001,6 +9608,11 @@ declare module "esri/views/layers/ImageryLayerView" { export = ImageryLayerView; } +declare module "esri/views/layers/SceneLayerView" { + import SceneLayerView = __esri.SceneLayerView; + export = SceneLayerView; +} + declare module "esri/views/ui/UI" { import UI = __esri.UI; export = UI; @@ -8046,6 +9658,11 @@ declare module "esri/widgets/Attribution" { export = Attribution; } +declare module "esri/widgets/BasemapGallery" { + import BasemapGallery = __esri.BasemapGallery; + export = BasemapGallery; +} + declare module "esri/widgets/BasemapToggle" { import BasemapToggle = __esri.BasemapToggle; export = BasemapToggle; @@ -8061,6 +9678,11 @@ declare module "esri/widgets/Compass" { export = Compass; } +declare module "esri/widgets/Expand" { + import Expand = __esri.Expand; + export = Expand; +} + declare module "esri/widgets/Home" { import Home = __esri.Home; export = Home; @@ -8096,6 +9718,11 @@ declare module "esri/widgets/Print" { export = Print; } +declare module "esri/widgets/ScaleBar" { + import ScaleBar = __esri.ScaleBar; + export = ScaleBar; +} + declare module "esri/widgets/Search" { import Search = __esri.Search; export = Search; @@ -8131,6 +9758,11 @@ declare module "esri/widgets/Attribution/AttributionViewModel" { export = AttributionViewModel; } +declare module "esri/widgets/BasemapGallery/BasemapGalleryViewModel" { + import BasemapGalleryViewModel = __esri.BasemapGalleryViewModel; + export = BasemapGalleryViewModel; +} + declare module "esri/widgets/BasemapToggle/BasemapToggleViewModel" { import BasemapToggleViewModel = __esri.BasemapToggleViewModel; export = BasemapToggleViewModel; @@ -8141,6 +9773,11 @@ declare module "esri/widgets/Compass/CompassViewModel" { export = CompassViewModel; } +declare module "esri/widgets/Expand/ExpandViewModel" { + import ExpandViewModel = __esri.ExpandViewModel; + export = ExpandViewModel; +} + declare module "esri/widgets/Home/HomeViewModel" { import HomeViewModel = __esri.HomeViewModel; export = HomeViewModel; @@ -8151,6 +9788,11 @@ declare module "esri/widgets/LayerList/LayerListViewModel" { export = LayerListViewModel; } +declare module "esri/widgets/LayerList/ListItem" { + import ListItem = __esri.ListItem; + export = ListItem; +} + declare module "esri/widgets/Locate/LocateViewModel" { import LocateViewModel = __esri.LocateViewModel; export = LocateViewModel; @@ -8171,6 +9813,11 @@ declare module "esri/widgets/Popup/PopupViewModel" { export = PopupViewModel; } +declare module "esri/widgets/ScaleBar/ScaleBarViewModel" { + import ScaleBarViewModel = __esri.ScaleBarViewModel; + export = ScaleBarViewModel; +} + declare module "esri/widgets/Search/SearchViewModel" { import SearchViewModel = __esri.SearchViewModel; export = SearchViewModel; @@ -8266,6 +9913,11 @@ declare module "esri/views/DOMContainer" { export = DOMContainer; } +declare module "esri/widgets/Widgette" { + import Widgette = __esri.Widgette; + export = Widgette; +} + declare module "esri/widgets/support/GeolocationPositioning" { import GeolocationPositioning = __esri.GeolocationPositioning; export = GeolocationPositioning; @@ -8296,6 +9948,11 @@ declare module "esri/core/promiseUtils" { export = promiseUtils; } +declare module "esri/core/requireUtils" { + import requireUtils = __esri.requireUtils; + export = requireUtils; +} + declare module "esri/core/urlUtils" { import urlUtils = __esri.urlUtils; export = urlUtils; @@ -8331,6 +9988,11 @@ declare module "esri/geometry/support/jsonUtils" { export = jsonUtils; } +declare module "esri/geometry/support/normalizeUtils" { + import normalizeUtils = __esri.normalizeUtils; + export = normalizeUtils; +} + declare module "esri/geometry/support/webMercatorUtils" { import webMercatorUtils = __esri.webMercatorUtils; export = webMercatorUtils; @@ -8391,11 +10053,6 @@ declare module "esri/renderers/support/jsonUtils" { export = supportJsonUtils; } -declare module "esri/support/Action" { - import Action = __esri.Action; - export = Action; -} - declare module "esri/symbols/support/jsonUtils" { import symbolsSupportJsonUtils = __esri.symbolsSupportJsonUtils; export = symbolsSupportJsonUtils; @@ -8411,7 +10068,17 @@ declare module "esri/widgets/support/widget" { export = widget; } -declare module "esri/widgets/LayerList/ListItem" { - import ListItem = __esri.ListItem; - export = ListItem; +declare module "esri/widgets/BasemapGallery/BasemapGalleryItem" { + import BasemapGalleryItem = __esri.BasemapGalleryItem; + export = BasemapGalleryItem; } + +declare module "esri/widgets/BasemapGallery/support/LocalBasemapsSource" { + import LocalBasemapsSource = __esri.LocalBasemapsSource; + export = LocalBasemapsSource; +} + +declare module "esri/widgets/BasemapGallery/support/PortalBasemapsSource" { + import PortalBasemapsSource = __esri.PortalBasemapsSource; + export = PortalBasemapsSource; +} \ No newline at end of file diff --git a/arcgis-js-api/v3/index.d.ts b/arcgis-js-api/v3/index.d.ts index c32749eb26..40875ddd48 100644 --- a/arcgis-js-api/v3/index.d.ts +++ b/arcgis-js-api/v3/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ArcGIS API for JavaScript 3.19 +// Type definitions for ArcGIS API for JavaScript 3.20 // Project: https://developers.arcgis.com/javascript/3/ // Definitions by: Esri // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -21,7 +21,6 @@ declare module "esri" { import Color = require("esri/Color"); import LocationProviderBase = require("esri/tasks/locationproviders/LocationProviderBase"); import PictureMarkerSymbol = require("esri/symbols/PictureMarkerSymbol"); - import RouteParameters = require("esri/tasks/RouteParameters"); import SimpleLineSymbol = require("esri/symbols/SimpleLineSymbol"); import Font = require("esri/symbols/Font"); import ArcGISDynamicMapServiceLayer = require("esri/layers/ArcGISDynamicMapServiceLayer"); @@ -263,6 +262,12 @@ declare module "esri" { /** The symbol in which the BlendRenderer is applied. */ symbol: Symbol; } + export interface BookmarkItemOptions { + /** The extent for the specified bookmark item. */ + extent?: Extent; + /** The name for the bookmark item. */ + name?: string; + } export interface BookmarksOptions { /** An array of BookmarkItem objects or a json object with the BookmarkItem format to initially display in the bookmark widget. */ bookmarks?: BookmarkItem[]; @@ -282,8 +287,14 @@ declare module "esri" { latitudeFieldName?: string; /** The longitude field name. */ longitudeFieldName?: string; + /** Opacity or transparency of layer. */ + opacity?: number; /** An array of strings which correspond to fields to include in the CSVLayer. */ outFields?: string[]; + /** Refresh interval of the layer in minutes. */ + refreshInterval?: number; + /** Visibility of the layer. */ + visible?: boolean; } export interface ChooseBestFacilitiesOptions { /** The URL to the analysis service, for example "http://analysis.arcgis.com/arcgis/rest/services/tasks/GPServer". */ @@ -624,8 +635,8 @@ declare module "esri" { canModifyStops?: boolean; /** Center the map at the start of the selected route segment. */ centerAtSegmentStart?: boolean; - /** The returned directions object from the routing solve result. */ - directions?: any; + /** The locale used for the directions. */ + directionsLanguage?: string; /** Length units. */ directionsLengthUnits?: string; /** Enable the dragging of stop locations on the map. */ @@ -658,8 +669,6 @@ declare module "esri" { printTemplate?: string; /** When true, the route will return to start point. */ returnToStart?: boolean; - /** Specify the input parameters for the route task. */ - routeParams?: RouteParameters; /** Define the symbol used to draw the route on the map. */ routeSymbol?: SimpleLineSymbol; /** Specify the service that will be used to calculate directions. */ @@ -672,6 +681,8 @@ declare module "esri" { segmentSymbol?: SimpleLineSymbol; /** Defines whether the Directions widget will show the map-click-active toggle button. */ showActivateButton?: boolean; + /** Indicates whether to expose barriers when using the widget. */ + showBarriersButton?: boolean; /** If true, the Clear button is shown. */ showClearButton?: boolean; /** If true, the toggle button group allowing user to choose between Miles and Kilometers is shown. */ @@ -1076,6 +1087,8 @@ declare module "esri" { export interface GeoRSSLayerOptions { /** The template used to display popup window for identify operation. */ infoTemplate?: InfoTemplate; + /** Opacity or transparency of layer. */ + opacity?: number; /** The output spatial reference for the GeoRSSLayer. */ outSpatialReference?: SpatialReference; /** The default symbol use to display point features. */ @@ -1084,6 +1097,8 @@ declare module "esri" { polygonSymbol?: Symbol; /** The default symbol used to display polyline features. */ polylineSymbol?: Symbol; + /** Refresh interval of the layer in minutes. */ + refreshInterval?: number; } export interface GeocoderOptions { /** By default, the Geocoder widget uses the Esri World Locator to find search locations. */ @@ -3235,7 +3250,7 @@ declare module "esri/arcgis/Portal" { tags: string[]; /** The url to the thumbnail image for the user. */ thumbnailUrl: string; - /** The url for the user content. */ + /** The URL for the user content. */ userContentUrl: string; /** The username for the user. */ username: string; @@ -3554,16 +3569,15 @@ declare module "esri/dijit/BasemapToggle" { } declare module "esri/dijit/BookmarkItem" { - import Extent = require("esri/geometry/Extent"); + import esri = require("esri"); /** Defines a bookmark for use in the Bookmark widget. */ class BookmarkItem { /** * Creates a new BookmarkItem. - * @param name The name for the bookmark item. - * @param extent The extent for the specified bookmark item. + * @param params See options list for parameters. */ - constructor(name: string, extent: Extent); + constructor(params?: esri.BookmarkItemOptions); } export = BookmarkItem; } @@ -3815,7 +3829,6 @@ declare module "esri/dijit/Directions" { import esri = require("esri"); import DirectionsFeatureSet = require("esri/tasks/DirectionsFeatureSet"); import Graphic = require("esri/graphic"); - import RouteParameters = require("esri/tasks/RouteParameters"); import RouteTask = require("esri/tasks/RouteTask"); import Point = require("esri/geometry/Point"); import RouteResult = require("esri/tasks/RouteResult"); @@ -3832,14 +3845,14 @@ declare module "esri/dijit/Directions" { mergedRouteGraphic: Graphic; /** If specified, this specifies the portal where the produced route layers are going to be stored and accessed. */ portalUrl: string; - /** Routing parameters for the widget. */ - routeParams: RouteParameters; /** Routing task for the widget. */ routeTask: RouteTask; /** Read-only: The Service Description object returned by the Route REST Endpoint. */ serviceDescription: any; /** Indicates whether the Directions widget will display the map-click-active toggle button. */ showActivateButton: boolean; + /** Indicates whether to expose barriers when using the widget. */ + showBarriersButton: boolean; /** If true, the Clear button is shown. */ showClearButton: boolean; /** If true, the toggle button group allowing user to choose between Miles and Kilometers is shown. */ @@ -9230,8 +9243,14 @@ declare module "esri/layers/CSVLayer" { latitudeFieldName: string; /** The longitude field name. */ longitudeFieldName: string; + /** Opacity or transparency of layer. */ + opacity: number; + /** Refresh interval of the layer in minutes. */ + refreshInterval: number; /** The url to a CSV resource. */ url: string; + /** Visibility of the layer. */ + visible: boolean; /** * Creates a CSV layer. * @param url URL to a CSV resource. @@ -9938,6 +9957,10 @@ declare module "esri/layers/GeoRSSLayer" { items: Graphic[]; /** The name of the layer. */ name: string; + /** Opacity or transparency of layer. */ + opacity: number; + /** Refresh interval of the layer in minutes. */ + refreshInterval: number; /** The publicly accessible URL to a GeoRSS file. */ url: string; /** @@ -11703,6 +11726,7 @@ declare module "esri/layers/pixelfilters/StretchFilter" { declare module "esri/map" { import esri = require("esri"); import Attribution = require("esri/dijit/Attribution"); + import Color = require("esri/Color"); import Extent = require("esri/geometry/Extent"); import GraphicsLayer = require("esri/layers/GraphicsLayer"); import InfoWindowBase = require("esri/InfoWindowBase"); @@ -11721,6 +11745,8 @@ declare module "esri/map" { attribution: Attribution; /** Value is true when the map automatically resizes if the browser window or ContentPane widget enclosing the map is resized. */ autoResize: boolean; + /** The background color "behind" the map. */ + backgroundColor: Color; /** An array of IDs corresponding to the layers that make up the map's current basemap. */ basemapLayerIds: string[]; /** The current extent of the map in map units. */ @@ -11924,6 +11950,11 @@ declare module "esri/map" { * @param immediate By default, the actual resize logic is delayed internally in order to throttle spurious resize events dispatched by some browsers. */ resize(immediate?: boolean): void; + /** + * Change the background color of the map. + * @param color Color specified using either a named string (e.g. + */ + setBackgroundColor(color: Color | string): void; /** * Change the map's current basemap. * @param basemap A valid basemap name. diff --git a/archiver/archiver-tests.ts b/archiver/archiver-tests.ts index d79b29f079..f186fb9bcb 100644 --- a/archiver/archiver-tests.ts +++ b/archiver/archiver-tests.ts @@ -1,6 +1,3 @@ - -/// - import Archiver = require('archiver'); import FS = require('fs'); diff --git a/atom/atom-tests.ts b/atom/atom-tests.ts index 37b2fb314c..1b141fb492 100644 --- a/atom/atom-tests.ts +++ b/atom/atom-tests.ts @@ -1,5 +1,4 @@ /// -/// import path = require("path"); import _atom = require("atom"); diff --git a/aurelia-knockout/aurelia-knockout-tests.ts b/aurelia-knockout/aurelia-knockout-tests.ts new file mode 100644 index 0000000000..6944ab5889 --- /dev/null +++ b/aurelia-knockout/aurelia-knockout-tests.ts @@ -0,0 +1,11 @@ + +export class ViewModel { + + constructor(private knockoutBindable: KnockoutBindable) { + } + + activate(settings: any): void { + this.knockoutBindable.applyBindableValues(settings, this); + this.knockoutBindable.applyBindableValues(settings, this, true); + } +} diff --git a/aurelia-knockout/index.d.ts b/aurelia-knockout/index.d.ts new file mode 100644 index 0000000000..2ccec60b46 --- /dev/null +++ b/aurelia-knockout/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for aurelia-knockout 2.0 +// Project: https://github.com/code-chris/aurelia-knockout +// Definitions by: Christian Kotzbauer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare interface KnockoutBindable { + + /** + * Applys all values from a data object (usually the activation data) to the corresponding instance fields + * in the current view model if they are marked as @bindable. By default all matching values from the data object + * are applied. To only apply observable values set the last parameter to `true`. Subscriptions are created + * for all Knockout observables in the data object to update the view-model values respectively. + * + * @param data - the data object + * @param target - the target view model + * @param applyOnlyObservables - `true` if only observable values should be applied, false by default. + */ + applyBindableValues(data: any, target: any, applyOnlyObservables?: boolean): void; +} diff --git a/aurelia-knockout/tsconfig.json b/aurelia-knockout/tsconfig.json new file mode 100644 index 0000000000..aa45dc1157 --- /dev/null +++ b/aurelia-knockout/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "aurelia-knockout-tests.ts" + ] +} diff --git a/aurelia-knockout/tslint.json b/aurelia-knockout/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/aurelia-knockout/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/auth0-js/auth0-js-tests.ts b/auth0-js/auth0-js-tests.ts index 7c910d1765..cd7789c62d 100644 --- a/auth0-js/auth0-js-tests.ts +++ b/auth0-js/auth0-js-tests.ts @@ -1,4 +1,4 @@ -import 'auth0-js'; +import * as auth0 from 'auth0-js'; let webAuth = new auth0.WebAuth({ domain: 'mine.auth0.com', @@ -61,10 +61,8 @@ webAuth.signupAndAuthorize({ }); - - webAuth.client.login({ - ealm: 'Username-Password-Authentication', //connection name or HRD domain + realm: 'Username-Password-Authentication', //connection name or HRD domain username: 'info@auth0.com', password: 'areallystrongpassword', audience: 'https://mystore.com/api/v2', @@ -73,6 +71,26 @@ webAuth.client.login({ // Auth tokens in the result or an error }); +webAuth.popup.buildPopupHandler(); +webAuth.popup.preload({}); +webAuth.popup.authorize({}, (err, data) => { + if (err) /* handle error */ return; + // do something with data +}); +webAuth.popup.loginWithCredentials({}, (err, data) => { + if (err) /* handle error */ return; + // do something with data +}); +webAuth.popup.passwordlessVerify({}, (err, data) => { + if (err) /* handle error */ return; + // do something with data +}); +webAuth.popup.signupAndLogin({}, (err, data) => { + if (err) /* handle error */ return; + // do something with data +}); + + let authentication = new auth0.Authentication({ domain: 'me.auth0.com', clientID: '...', @@ -101,7 +119,9 @@ authentication.delegation({ refresh_token: 'your_refresh_token', api_type: 'app' }, (err, data) => { - + if (!err) { + localStorage.setItem('token', data.idToken) + } }); authentication.loginWithDefaultDirectory({ @@ -146,6 +166,8 @@ let management = new auth0.Management({ management.getUser('asd', (err, user) => {}); -management.patchUserMetadata('asd', {role: 'admin'}, (err, user) => {}); +management.patchUserMetadata('asd', {role: 'admin'}, (err, user) => { + if (!err && user.email_verified) return; // do something +}); management.linkUser('asd', 'eqwe', (err, user) => {}); diff --git a/auth0-js/index.d.ts b/auth0-js/index.d.ts index 11cf16a3ed..d8d1e6f392 100644 --- a/auth0-js/index.d.ts +++ b/auth0-js/index.d.ts @@ -1,456 +1,516 @@ -// Type definitions for Auth0.js 8.1 +// Type definitions for Auth0.js 8.3 // Project: https://github.com/auth0/auth0.js // Definitions by: Adrian Chia // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace auth0 { +export as namespace auth0; - export class Authentication { - constructor(options: AuthOptions); - passwordless: PasswordlessAuthentication; - dbConnection: DBConnection; +export class Authentication { + constructor(options: AuthOptions); - /** - * Builds and returns the `/authorize` url in order to initialize a new authN/authZ transaction - * - * @method buildAuthorizeUrl - * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db - */ - buildAuthorizeUrl(options: any): string; + passwordless: PasswordlessAuthentication; + dbConnection: DBConnection; - /** - * Builds and returns the Logout url in order to initialize a new authN/authZ transaction - * - * @method buildLogoutUrl - * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout - */ - buildLogoutUrl(options?: any): string; + /** + * Builds and returns the `/authorize` url in order to initialize a new authN/authZ transaction + * + * @method buildAuthorizeUrl + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + */ + buildAuthorizeUrl(options: any): string; - /** - * Makes a call to the `oauth/token` endpoint with `password` grant type - * - * @method loginWithDefaultDirectory - * @param {Object} options: https://auth0.com/docs/api-auth/grant/password - * @param {Function} callback - */ - loginWithDefaultDirectory(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Builds and returns the Logout url in order to initialize a new authN/authZ transaction + * + * @method buildLogoutUrl + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout + */ + buildLogoutUrl(options?: any): string; - /** - * Makes a call to the `/ro` endpoint - * @param {any} options - * @param {Function} callback - * @deprecated `loginWithResourceOwner` will be soon deprecated, user `login` instead. - */ - loginWithResourceOwner(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Makes a call to the `oauth/token` endpoint with `password` grant type + * + * @method loginWithDefaultDirectory + * @param {Object} options: https://auth0.com/docs/api-auth/grant/password + * @param {Function} callback + */ + loginWithDefaultDirectory(options: any, callback: Auth0Callback): void; - /** - * Makes a call to the `oauth/token` endpoint with `password-realm` grant type - * @param {any} options - * @param {Function} callback - */ - login(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Makes a call to the `/ro` endpoint + * @param {any} options + * @param {Function} callback + * @deprecated `loginWithResourceOwner` will be soon deprecated, user `login` instead. + */ + loginWithResourceOwner(options: any, callback: Auth0Callback): void; - /** - * Makes a call to the `oauth/token` endpoint - * @param {any} options - * @param {Function} callback - */ - oauthToken(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Makes a call to the `oauth/token` endpoint with `password-realm` grant type + * @param {any} options + * @param {Function} callback + */ + login(options: any, callback: Auth0Callback): void; - /** - * Makes a call to the `/ssodata` endpoint - * - * @method getSSOData - * @param {Boolean} withActiveDirectories - * @param {Function} callback - * @deprecated `getSSOData` will be soon deprecated. - */ - getSSOData(callback?: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Makes a call to the `oauth/token` endpoint + * @param {any} options + * @param {Function} callback + */ + oauthToken(options: any, callback: Auth0Callback): void; - /** - * Makes a call to the `/ssodata` endpoint - * - * @method getSSOData - * @param {Boolean} withActiveDirectories - * @param {Function} callback - * @deprecated `getSSOData` will be soon deprecated. - */ - getSSOData(withActiveDirectories: boolean, callback?: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Makes a call to the `/ssodata` endpoint + * + * @method getSSOData + * @param {Function} callback + */ + getSSOData(callback?: Auth0Callback): void; - /** - * Makes a call to the `/userinfo` endpoint and returns the user profile - * - * @method userInfo - * @param {String} accessToken - * @param {Function} callback - */ - userInfo(token: string, callback: (error?: Auth0Error, user?: any) => any): void; + /** + * Makes a call to the `/ssodata` endpoint + * + * @method getSSOData + * @param {Boolean} withActiveDirectories + * @param {Function} callback + */ + getSSOData(withActiveDirectories: boolean, callback?: Auth0Callback): void; - /** - * Makes a call to the `/delegation` endpoint - * - * @method delegation - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--delegation - * @param {Function} callback - * @deprecated `delegation` will be soon deprecated. - */ - delegation(options: any, callback: (error?: Auth0Error, authResult?: Auth0DelegationToken) => any): any; + /** + * Makes a call to the `/userinfo` endpoint and returns the user profile + * + * @method userInfo + * @param {String} accessToken + * @param {Function} callback + */ + userInfo(token: string, callback: Auth0Callback): void; - /** - * Fetches the user country based on the ip. - * - * @method getUserCountry - * @param {Function} callback - */ - getUserCountry(callback: (error?: Auth0Error, result?: any) => any): void; - } - - export class PasswordlessAuthentication { - constructor(request: any, option: any); - - /** - * Builds and returns the passwordless TOTP verify url in order to initialize a new authN/authZ transaction - * - * @method buildVerifyUrl - * @param {Object} options - * @param {Function} callback - */ - buildVerifyUrl(options: any): string; - - /** - * Initializes a new passwordless authN/authZ transaction - * - * @method start - * @param {Object} options: https://auth0.com/docs/api/authentication#passwordless - * @param {Function} callback - */ - start(options: PasswordlessStartOptions, callback: any): void; - - /** - * Verifies the passwordless TOTP and returns an error if any. - * - * @method buildVerifyUrl - * @param {Object} options - * @param {Function} callback - */ - verify(options: any, callback: any): void; - } - - export class DBConnection { - constructor(request: any, option: any); - - /** - * Signup a new user - * - * @method signup - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup - * @param {Function} calback - */ - signup(options: any, callback: any): void; - - /** - * Initializes the change password flow - * - * @method signup - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password - * @param {Function} callback - */ - changePassword(options: ChangePasswordOptions, callback: any): void; - } - - export class Management { - constructor(options: ManagementOptions); - - /** - * Returns the user profile. https://auth0.com/docs/api/management/v2#!/Users/get_users_by_id - * - * @method getUser - * @param {String} userId - * @param {Function} callback - */ - getUser(userId: string, callback: (error?: Auth0Error, user?: any) => any): void; - - /** - * Updates the user metdata. It will patch the user metdata with the attributes sent. - * https://auth0.com/docs/api/management/v2#!/Users/patch_users_by_id - * - * @method patchUserMetadata - * @param {String} userId - * @param {Object} userMetadata - * @param {Function} callback - */ - patchUserMetadata(userId: string, userMetadata: any, callback: (error?: Auth0Error, user?: any) => any): void; - - /** - * Link two users. https://auth0.com/docs/api/management/v2#!/Users/post_identities - * - * @method linkUser - * @param {String} userId - * @param {String} secondaryUserToken - * @param {Function} callback - */ - linkUser(userId: string, secondaryUserToken: string, callback: (error?: Auth0Error, user?: any) => any): void; - } - - export class WebAuth { - constructor(options: AuthOptions); - client: Authentication; - popup: Popup; - redirect: Redirect; - - /** - * Redirects to the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction - * - * @method authorize - * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db - */ - authorize(options: any): void; - - /** - * Parse the url hash and extract the returned tokens depending on the transaction. - * - * Only validates id_tokens signed by Auth0 using the RS256 algorithm using the public key exposed - * by the `/.well-known/jwks.json` endpoint. Id tokens signed with other algorithms will not be - * accepted. - * - * @method parseHash - * @param {Object} options: - * @param {String} options.state [OPTIONAL] to verify the response - * @param {String} options.nonce [OPTIONAL] to verify the id_token - * @param {String} options.hash [OPTIONAL] the url hash. If not provided it will extract from window.location.hash - * @param {Function} callback: any(err, token_payload) - */ - parseHash(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - - /** - * Decodes the id_token and verifies the nonce. - * - * @method validateToken - * @param {String} token - * @param {String} state - * @param {String} nonce - * @param {Function} callback: function(err, {payload, transaction}) - */ - validateToken(token: string, state: string, nonce: string, callback: any): void; - - /** - * Executes a silent authentication transaction under the hood in order to fetch a new token. - * - * @method renewAuth - * @param {Object} options: any valid oauth2 parameter to be sent to the `/authorize` endpoint - * @param {Function} callback - */ - renewAuth(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - - /** - * Initialices a change password transaction - * - * @method changePassword - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password - * @param {Function} callback - */ - changePassword(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - - /** - * Signs up a new user - * - * @method signup - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup - * @param {Function} callback - */ - signup(options: any, callback: any): void; - - /** - * Signs up a new user, automatically logs the user in after the signup and returns the user token. - * The login will be done using /oauth/token with password-realm grant type. - * - * @method signupAndAuthorize - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup - * @param {Function} callback - */ - signupAndAuthorize(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - - /** - * Redirects to the auth0 logout page - * - * @method logout - * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout - */ - logout(options: any): void; - - passwordlessStart(options: PasswordlessStartOptions, callback: (error?: Auth0Error, data?: any) => any): void; - - /** - * Verifies the passwordless TOTP and redirects to finish the passwordless transaction - * - * @method passwordlessVerify - * @param {Object} options: - * @param {Object} options.type: `sms` or `email` - * @param {Object} options.phoneNumber: only if type = sms - * @param {Object} options.email: only if type = email - * @param {Object} options.connection: the connection name - * @param {Object} options.verificationCode: the TOTP code - * @param {Function} callback - */ - passwordlessVerify(options: any, callback: any): void; - } - - export class Redirect { - constructor(client: any, options: any); - - /** - * Initializes the legacy Lock login flow in a popup - * - * @method loginWithCredentials - * @param {Object} options - * @param {Function} callback - * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. - */ - loginWithCredentials(options: any, callback: any): void; - - /** - * Signs up a new user and automatically logs the user in after the signup. - * - * @method signupAndLogin - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup - * @param {Function} callback - */ - signupAndLogin(options: any, callback: any): void; - } - - export class Popup { - constructor(client: any, options: any); - - /** - * Initializes the popup window and returns the instance to be used later in order to avoid being blocked by the browser. - * - * @method preload - * @param {Object} options: receives the window height and width and any other window feature to be sent to window.open - */ - preload(options: any): any; - - /** - * Internal use. - * - * @method getPopupHandler - */ - getPopupHandler(options: any, preload: boolean): any; - /** - * Opens in a popup the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction - * - * @method authorize - * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db - * @param {Function} callback - */ - authorize(options: any, callback: any): void; - - /** - * Initializes the legacy Lock login flow in a popup - * - * @method loginWithCredentials - * @param {Object} options - * @param {Function} callback - * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. - */ - loginWithCredentials(options: any, callback: any): void; - - /** - * Verifies the passwordless TOTP and returns the requested token - * - * @method passwordlessVerify - * @param {Object} options: - * @param {Object} options.type: `sms` or `email` - * @param {Object} options.phoneNumber: only if type = sms - * @param {Object} options.email: only if type = email - * @param {Object} options.connection: the connection name - * @param {Object} options.verificationCode: the TOTP code - * @param {Function} callback - */ - passwordlessVerify(options: any, callback: any): void; - - /** - * Signs up a new user and automatically logs the user in after the signup. - * - * @method signupAndLogin - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup - * @param {Function} callback - */ - signupAndLogin(options: any, callback: any): void; - } - - interface ManagementOptions { - domain: string; - token: string; - _sendTelemetry?: boolean; - _telemetryInfo?: any; - } - - interface AuthOptions { - domain: string; - clientID: string; - responseType?: string; - responseMode?: string; - redirectUri?: string; - scope?: string; - audience?: string; - leeway?: number; - _disableDeprecationWarnings?: boolean; - _sendTelemetry?: boolean; - _telemetryInfo?: any; - } - - interface PasswordlessAuthOptions { - connection: string; - verificationCode: string; - phoneNumber: string; - email: string; - } - - interface Auth0Error { - error: any; - errorDescription: string; - } - - interface Auth0DecodedHash { - accessToken?: string; - idToken?: string; - idTokenPayload?: any; - refreshToken?: string; - state?: string; - expiresIn?: number; - tokenType?: string; - } - - /** Represents the response from an API Token Delegation request. */ - interface Auth0DelegationToken { - /** The length of time in seconds the token is valid for. */ - ExpiresIn: number; - /** The JWT for delegated access. */ - idToken: string; - /** The type of token being returned. Possible values: "Bearer" */ - tokenType: string; - } - - interface ChangePasswordOptions { - connection: string; - email: string; - password?: string; - } - - interface PasswordlessStartOptions { - connection: string; - send: string; - phoneNumber?: string; - email?: string; - authParams?: any; - } - - interface PasswordlessVerifyOptions { - connection: string; - verificationCode: string; - phoneNumber?: string; - email?: string; - } + /** + * Makes a call to the `/delegation` endpoint + * + * @method delegation + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--delegation + * @param {Function} callback + */ + delegation(options: any, callback: Auth0Callback): any; + /** + * Fetches the user country based on the ip. + * + * @method getUserCountry + * @param {Function} callback + */ + getUserCountry(callback: Auth0Callback<{ countryCode: string }>): void; +} + +export class PasswordlessAuthentication { + constructor(request: any, option: any); + + /** + * Builds and returns the passwordless TOTP verify url in order to initialize a new authN/authZ transaction + * + * @method buildVerifyUrl + * @param {Object} options + * @param {Function} callback + */ + buildVerifyUrl(options: any): string; + + /** + * Initializes a new passwordless authN/authZ transaction + * + * @method start + * @param {Object} options: https://auth0.com/docs/api/authentication#passwordless + * @param {Function} callback + */ + start(options: PasswordlessStartOptions, callback: Auth0Callback): void; + + /** + * Verifies the passwordless TOTP and returns an error if any. + * + * @method buildVerifyUrl + * @param {Object} options + * @param {Function} callback + */ + verify(options: any, callback: Auth0Callback): void; +} + +export class DBConnection { + constructor(request: any, option: any); + + /** + * Signup a new user + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} calback + */ + signup(options: any, callback: Auth0Callback): void; + + /** + * Initializes the change password flow + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password + * @param {Function} callback + */ + changePassword(options: ChangePasswordOptions, callback: Auth0Callback): void; +} + +export class Management { + constructor(options: ManagementOptions); + + /** + * Returns the user profile. https://auth0.com/docs/api/management/v2#!/Users/get_users_by_id + * + * @method getUser + * @param {String} userId + * @param {Function} callback + */ + getUser(userId: string, callback: Auth0Callback): void; + + /** + * Updates the user metdata. It will patch the user metdata with the attributes sent. + * https://auth0.com/docs/api/management/v2#!/Users/patch_users_by_id + * + * @method patchUserMetadata + * @param {String} userId + * @param {Object} userMetadata + * @param {Function} callback + */ + patchUserMetadata(userId: string, userMetadata: any, callback: Auth0Callback): void; + + /** + * Link two users. https://auth0.com/docs/api/management/v2#!/Users/post_identities + * + * @method linkUser + * @param {String} userId + * @param {String} secondaryUserToken + * @param {Function} callback + */ + linkUser(userId: string, secondaryUserToken: string, callback: Auth0Callback): void; +} + +export class WebAuth { + constructor(options: AuthOptions); + client: Authentication; + popup: Popup; + redirect: Redirect; + + /** + * Redirects to the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction + * + * @method authorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + */ + authorize(options: any): void; + + /** + * Parse the url hash and extract the returned tokens depending on the transaction. + * + * Only validates id_tokens signed by Auth0 using the RS256 algorithm using the public key exposed + * by the `/.well-known/jwks.json` endpoint. Id tokens signed with other algorithms will not be + * accepted. + * + * @method parseHash + * @param {Object} options: + * @param {String} options._idTokenVerification [OPTIONAL] Default: true + * @param {String} options.state [OPTIONAL] to verify the response + * @param {String} options.nonce [OPTIONAL] to verify the id_token + * @param {String} options.hash [OPTIONAL] the url hash. If not provided it will extract from window.location.hash + * @param {Function} callback: any(err, token_payload) + */ + parseHash(options: any, callback: Auth0Callback): void; + + /** + * Decodes the id_token and verifies the nonce. + * + * @method validateToken + * @param {String} token + * @param {String} state + * @param {String} nonce + * @param {Function} callback: function(err, {payload, transaction}) + */ + validateToken(token: string, state: string, nonce: string, callback: Auth0Callback): void; + + /** + * Executes a silent authentication transaction under the hood in order to fetch a new token. + * + * @method renewAuth + * @param {Object} options: any valid oauth2 parameter to be sent to the `/authorize` endpoint + * @param {Function} callback + */ + renewAuth(options: any, callback: Auth0Callback): void; + + /** + * Initialices a change password transaction + * + * @method changePassword + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password + * @param {Function} callback + */ + changePassword(options: any, callback: Auth0Callback): void; + + /** + * Signs up a new user + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signup(options: any, callback: Auth0Callback): void; + + /** + * Signs up a new user, automatically logs the user in after the signup and returns the user token. + * The login will be done using /oauth/token with password-realm grant type. + * + * @method signupAndAuthorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndAuthorize(options: any, callback: Auth0Callback): void; + + /** + * Redirects to the auth0 logout page + * + * @method logout + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout + */ + logout(options: any): void; + + /** + * Initialices a passwordless authentication transaction + * + * @method passwordlessStart + * @param {Object} options: https://auth0.com/docs/api/authentication#passwordless + * @param {Object} options.send: `link` or `code` + * @param {Object} options.phoneNumber: send should be code and email not set + * @param {Object} options.email: phoneNumber should be ignored + * @param {Object} options.connection + * @param {Object} options.authParams + * @param {Function} callback + */ + passwordlessStart(options: PasswordlessStartOptions, callback: Auth0Callback): void; + + /** + * Verifies the passwordless TOTP and redirects to finish the passwordless transaction + * + * @method passwordlessVerify + * @param {Object} options: + * @param {Object} options.type: `sms` or `email` + * @param {Object} options.phoneNumber: only if type = sms + * @param {Object} options.email: only if type = email + * @param {Object} options.connection: the connection name + * @param {Object} options.verificationCode: the TOTP code + * @param {Function} callback + */ + passwordlessVerify(options: any, callback: Auth0Callback): void; +} + +export class Redirect { + constructor(client: any, options: any); + + /** + * Initializes the legacy Lock login flow in a popup + * + * @method loginWithCredentials + * @param {Object} options + * @param {Function} callback + * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. + */ + loginWithCredentials(options: any, callback: Auth0Callback): void; + + /** + * Signs up a new user and automatically logs the user in after the signup. + * + * @method signupAndLogin + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndLogin(options: any, callback: Auth0Callback): void; +} + +export class Popup { + constructor(client: any, options: any); + + /** + * Returns a new instance of the popup handler + * + * @method buildPopupHandler + */ + buildPopupHandler(): any; + + /** + * Initializes the popup window and returns the instance to be used later in order to avoid being blocked by the browser. + * + * @method preload + * @param {Object} options: receives the window height and width and any other window feature to be sent to window.open + */ + preload(options: any): any; + + /** + * Opens in a popup the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction + * + * @method authorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + * @param {Function} callback + */ + authorize(options: any, callback: Auth0Callback): void; + + /** + * Initializes the legacy Lock login flow in a popup + * + * @method loginWithCredentials + * @param {Object} options + * @param {Function} callback + * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. + */ + loginWithCredentials(options: any, callback: Auth0Callback): void; + + /** + * Verifies the passwordless TOTP and returns the requested token + * + * @method passwordlessVerify + * @param {Object} options: + * @param {Object} options.type: `sms` or `email` + * @param {Object} options.phoneNumber: only if type = sms + * @param {Object} options.email: only if type = email + * @param {Object} options.connection: the connection name + * @param {Object} options.verificationCode: the TOTP code + * @param {Function} callback + */ + passwordlessVerify(options: any, callback: Auth0Callback): void; + + /** + * Signs up a new user and automatically logs the user in after the signup. + * + * @method signupAndLogin + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndLogin(options: any, callback: Auth0Callback): void; +} + +type Auth0Callback = (error: null | Auth0Error, result: T) => void; + +interface ManagementOptions { + domain: string; + token: string; + _sendTelemetry?: boolean; + _telemetryInfo?: any; +} + +interface AuthOptions { + domain: string; + clientID: string; + responseType?: string; + responseMode?: string; + redirectUri?: string; + scope?: string; + audience?: string; + leeway?: number; + plugins?: any[]; + _disableDeprecationWarnings?: boolean; + _sendTelemetry?: boolean; + _telemetryInfo?: any; +} + +interface PasswordlessAuthOptions { + connection: string; + verificationCode: string; + phoneNumber: string; + email: string; +} + +interface Auth0Error { + error?: any; + errorDescription?: string; + code?: string; + description?: string; + name?: string; + policy?: string; + original?: any; + statusCode?: number; + statusText?: string; +} + +interface Auth0DecodedHash { + accessToken?: string; + idToken?: string; + idTokenPayload?: any; + refreshToken?: string; + state?: string; + expiresIn?: number; + tokenType?: string; +} + +/** Represents the response from an API Token Delegation request. */ +interface Auth0DelegationToken { + /** The length of time in seconds the token is valid for. */ + expiresIn: number; + /** The JWT for delegated access. */ + idToken: string; + /** The type of token being returned. Possible values: "Bearer" */ + tokenType: string; +} + +interface ChangePasswordOptions { + connection: string; + email: string; + password?: string; +} + +interface PasswordlessStartOptions { + connection: string; + send: string; + phoneNumber?: string; + email?: string; + authParams?: any; +} + +interface PasswordlessVerifyOptions { + connection: string; + verificationCode: string; + phoneNumber?: string; + email?: string; +} + +interface Auth0UserProfile { + name: string; + nickname: string; + picture: string; + user_id: string; + username?: string; + given_name?: string; + family_name?: string; + email?: string; + email_verified?: string; + clientID: string; + gender?: string; + locale?: string; + identities: Auth0Identity[]; + created_at: string; + updated_at: string; + sub: string; + user_metadata?: any; + app_metadata?: any; +} + +interface MicrosoftUserProfile extends Auth0UserProfile { + emails?: string[]; //optional depending on whether email addresses permission is granted +} + +interface Office365UserProfile extends Auth0UserProfile { + tenantid: string; + upn: string; +} + +interface AdfsUserProfile extends Auth0UserProfile { + issuer?: string; +} + +interface Auth0Identity { + connection: string; + isSocial: boolean; + provider: string; + user_id: string; } diff --git a/auth0-lock/auth0-lock-tests.ts b/auth0-lock/auth0-lock-tests.ts index 8045386586..a241eb6d0c 100644 --- a/auth0-lock/auth0-lock-tests.ts +++ b/auth0-lock/auth0-lock-tests.ts @@ -1,4 +1,4 @@ -import 'auth0-js/v7'; +import * as auth0 from 'auth0-js'; import Auth0Lock from 'auth0-lock'; const CLIENT_ID = "YOUR_AUTH0_APP_CLIENTID"; @@ -38,7 +38,7 @@ lock.show(showOptions); // "on" event-driven example lock.on("authenticated", function(authResult : any) { - lock.getProfile(authResult.idToken, function(error, profile) { + lock.getProfile(authResult.idToken, function(error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) { if (error) { // Handle error return; diff --git a/auth0-lock/index.d.ts b/auth0-lock/index.d.ts index 09c3f4fedd..285ad25288 100644 --- a/auth0-lock/index.d.ts +++ b/auth0-lock/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for auth0-lock 10.9 +// Type definitions for auth0-lock 10.10 // Project: http://auth0.com // Definitions by: Brian Caruso // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface Auth0LockAdditionalSignUpFieldOption { value: string; @@ -11,13 +11,13 @@ interface Auth0LockAdditionalSignUpFieldOption { } type Auth0LockAdditionalSignUpFieldOptionsCallback = - (error: Auth0Error, options: Auth0LockAdditionalSignUpFieldOption[]) => void; + (error: auth0.Auth0Error, options: Auth0LockAdditionalSignUpFieldOption[]) => void; type Auth0LockAdditionalSignUpFieldOptionsFunction = (callback: Auth0LockAdditionalSignUpFieldOptionsCallback) => void; type Auth0LockAdditionalSignUpFieldPrefillCallback = - (error: Auth0Error, prefill: string) => void; + (error: auth0.Auth0Error, prefill: string) => void; type Auth0LockAdditionalSignUpFieldPrefillFunction = (callback: Auth0LockAdditionalSignUpFieldPrefillCallback) => void; @@ -32,8 +32,8 @@ interface Auth0LockAdditionalSignUpField { validator?: (input: string) => { valid: boolean; hint?: string }; } -type Auth0LockAvatarUrlCallback = (error: Auth0Error, url: string) => void; -type Auth0LockAvatarDisplayNameCallback = (error: Auth0Error, displayName: string) => void; +type Auth0LockAvatarUrlCallback = (error: auth0.Auth0Error, url: string) => void; +type Auth0LockAvatarDisplayNameCallback = (error: auth0.Auth0Error, displayName: string) => void; interface Auth0LockAvatarOptions { url: (email: string, callback: Auth0LockAvatarUrlCallback) => void; @@ -63,6 +63,7 @@ interface Auth0LockAuthOptions { redirectUrl?: string; responseType?: string; sso?: boolean; + audience?: string; } interface Auth0LockPopupOptions { @@ -101,6 +102,7 @@ interface Auth0LockConstructorOptions { socialButtonStyle?: "big" | "small"; theme?: Auth0LockThemeOptions; usernameStyle?: string; + oidcConformant?: boolean; } interface Auth0LockFlashMessageOptions { @@ -123,15 +125,16 @@ interface Auth0LockStatic { new (clientId: string, domain: string, options?: Auth0LockConstructorOptions): Auth0LockStatic; // deprecated - getProfile(token: string, callback: (error: Auth0Error, profile: Auth0UserProfile) => void): void; - getUserInfo(token: string, callback: (error: Auth0Error, profile: Auth0UserProfile) => void): void; - + getProfile(token: string, callback: (error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) => void): void; + getUserInfo(token: string, callback: (error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) => void): void; + // https://github.com/auth0/lock#resumeauthhash-callback + resumeAuth( hash: string, callback: (error: auth0.Auth0Error, authResult: any) => void): void; show(options?: Auth0LockShowOptions): void; hide(): void; logout(query: any): void; on(event: "show" | "hide", callback: () => void): void; - on(event: "unrecoverable_error" | "authorization_error", callback: (error: Auth0Error) => void): void; + on(event: "unrecoverable_error" | "authorization_error", callback: (error: auth0.Auth0Error) => void): void; on(event: "authenticated", callback: (authResult: any) => void): void; on(event: string, callback: (...args: any[]) => void): void; } diff --git a/auth0/auth0-tests.ts b/auth0/auth0-tests.ts index 502a72eec1..24a4aad87d 100644 --- a/auth0/auth0-tests.ts +++ b/auth0/auth0-tests.ts @@ -1,5 +1,3 @@ -/// - import * as auth0 from 'auth0'; const management = new auth0.ManagementClient({ diff --git a/autoprefixer/autoprefixer-tests.ts b/autoprefixer/autoprefixer-tests.ts new file mode 100644 index 0000000000..47ef1cbc08 --- /dev/null +++ b/autoprefixer/autoprefixer-tests.ts @@ -0,0 +1,17 @@ +import * as autopref from 'autoprefixer'; + +const ap: autopref.Transformer = autopref({ + browsers: ['> 5%', 'last 2 versions'], + env: '', + cascade: true, + add: true, + remove: true, + supports: true, + flexbox: true, + grid: true, + stats: {}, +}); +const ap2: autopref.Transformer = autopref({ + flexbox: 'no-2009', +}); +const info: string = ap.info(); diff --git a/autoprefixer/index.d.ts b/autoprefixer/index.d.ts new file mode 100644 index 0000000000..0a01c34d9a --- /dev/null +++ b/autoprefixer/index.d.ts @@ -0,0 +1,32 @@ +// Type definitions for autoprefixer 6.7 +// Project: https://github.com/postcss/autoprefixer +// Definitions by: Armando Meziat +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Plugin, Transformer as PostcssTransformer } from 'postcss'; + +declare namespace autoprefixer { + + export interface Options { + browsers?: string[]; + env?: string; + cascade?: boolean; + add?: boolean; + remove?: boolean; + supports?: boolean; + flexbox?: boolean | 'no-2009'; + grid?: boolean; + stats?: any; + } + + export interface Transformer extends PostcssTransformer { + info(): string; + } + + export interface Autoprefixer extends Plugin { + (opts?: Options): Transformer; + } +} + +declare const autoprefixer: autoprefixer.Autoprefixer; +export = autoprefixer; diff --git a/autoprefixer/package.json b/autoprefixer/package.json new file mode 100644 index 0000000000..aa284a6db8 --- /dev/null +++ b/autoprefixer/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "postcss": "^5.2.15" + } +} diff --git a/autoprefixer/tsconfig.json b/autoprefixer/tsconfig.json new file mode 100644 index 0000000000..244c865adf --- /dev/null +++ b/autoprefixer/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "autoprefixer-tests.ts" + ] +} diff --git a/autoprefixer/tslint.json b/autoprefixer/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/autoprefixer/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/autosize/autosize-tests.ts b/autosize/autosize-tests.ts index a7eea57a62..fa0988be24 100644 --- a/autosize/autosize-tests.ts +++ b/autosize/autosize-tests.ts @@ -1,5 +1,3 @@ -/// - // from a NodeList autosize(document.querySelectorAll('textarea')); diff --git a/awesomplete/awesomplete-tests.ts b/awesomplete/awesomplete-tests.ts index 11abfdcba0..7998dc49e3 100644 --- a/awesomplete/awesomplete-tests.ts +++ b/awesomplete/awesomplete-tests.ts @@ -1,3 +1,5 @@ +import * as Awesomplete from 'awesomplete'; + var input = document.getElementById("myinput"); new Awesomplete(input, {list: "#mylist"}); @@ -11,45 +13,48 @@ var awesomplete = new Awesomplete(input); awesomplete.list = ["Ada", "Java", "JavaScript", "LOLCODE", "Node.js", "Ruby on Rails"]; new Awesomplete(input, { - list: [ - { label: "Belarus", value: "BY" }, - { label: "China", value: "CN" }, - { label: "United States", value: "US" } - ] + list: [ + { label: "Belarus", value: "BY" }, + { label: "China", value: "CN" }, + { label: "United States", value: "US" } + ] }); // Same with arrays: new Awesomplete(input, { - list: [ - [ "Belarus", "BY" ], - [ "China", "CN" ], - [ "United States", "US" ] - ] + list: [ + [ "Belarus", "BY" ], + [ "China", "CN" ], + [ "United States", "US" ] + ] }); new Awesomplete('input[type="email"]', { - list: ["aol.com", "att.net", "comcast.net", "facebook.com", "gmail.com", "gmx.com", "googlemail.com", "google.com", "hotmail.com", "hotmail.co.uk", "mac.com", "me.com", "mail.com", "msn.com", "live.com", "sbcglobal.net", "verizon.net", "yahoo.com", "yahoo.co.uk"], - data: function (text: string, input: any) { - return input.slice(0, input.indexOf("@")) + "@" + text; - }, - filter: Awesomplete.FILTER_STARTSWITH + list: ["aol.com", "att.net", "comcast.net", "facebook.com", "gmail.com", + "gmx.com", "googlemail.com", "google.com", "hotmail.com", + "hotmail.co.uk", "mac.com", "me.com", "mail.com", "msn.com", + "live.com", "sbcglobal.net", "verizon.net", "yahoo.com", "yahoo.co.uk"], + data: (text: string, input: string) => { + return input.slice(0, input.indexOf("@")) + "@" + text; + }, + filter: Awesomplete.FILTER_STARTSWITH }); new Awesomplete('input[data-multiple]', { - filter: function(text: string, input: any) { - return Awesomplete.FILTER_CONTAINS(text, input.match(/[^,]*$/)[0]); - }, + filter: (text: string, input: any) => { + return Awesomplete.FILTER_CONTAINS(text, input.match(/[^,]*$/)[0]); + }, - replace: function(text: string) { - var before = this.input.value.match(/^.+,\s*|/)[0]; - this.input.value = before + text + ", "; - } + replace: (text: string) => { + var before = this.input.value.match(/^.+,\s*|/)[0]; + this.input.value = before + text + ", "; + } }); var ajax = new XMLHttpRequest(); ajax.open("GET", "https://restcountries.eu/rest/v1/lang/fr", true); -ajax.onload = function() { - var list = JSON.parse(ajax.responseText).map(function(i: any) { return i.name; }); - new Awesomplete(document.querySelector("#ajax-example input"),{ list: list }); +ajax.onload = () => { + var list = JSON.parse(ajax.responseText).map((i: any) => { return i.name; }); + new Awesomplete(document.querySelector("#ajax-example input"), { list: list }); }; -ajax.send(); \ No newline at end of file +ajax.send(); diff --git a/awesomplete/index.d.ts b/awesomplete/index.d.ts index d39389f008..9b8976cfd1 100644 --- a/awesomplete/index.d.ts +++ b/awesomplete/index.d.ts @@ -1,49 +1,57 @@ -// Type definitions for Awesomplete v1.1.0 +// Type definitions for Awesomplete 1.1 // Project: https://leaverou.github.io/awesomplete/ -// Definitions by: webbiesdk , Ben Dixon +// Definitions by: webbiesdk , Ben Dixon , Trevor Bekolay // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare class Awesomplete { - constructor(input: Element | HTMLElement | string, o?: AwesompleteOptions); - static all: Array; - static $$: (expr: string | NodeSelector, con?: any) => NodeList; - static ITEM: (text: string, input: string) => HTMLElement; - static $: { - (expr: string|Element, con?: NodeSelector): string | Element; - regExpEscape: (s: { replace: (arg0: RegExp, arg1: string) => void }) => any; - create: (tag: string, o: any) => HTMLElement; - fire: (target: EventTarget, type: string, properties: any) => any; - siblingIndex: (el: Element) => number; - }; - static FILTER_STARTSWITH: (text: string, input: string) => boolean; - static FILTER_CONTAINS: (text: string, input: string) => boolean; - static SORT_BYLENGTH: (a: number | any[], b: number | any[]) => number; - static REPLACE: (text: any) => void; - next: () => void; - container: HTMLElement; - select: (selected?: HTMLElement, originalTarget?: HTMLElement) => void; - previous: () => void; - index: number; - opened: number; - list: string | string[] | Element | { label: string, value: any }[] | [string, string][]; - input: HTMLElement | string; - goto: (i: number) => void; - ul: HTMLElement; - close: () => void; - evaluate: () => void; - selected: boolean; - open: () => void; - status: HTMLElement; + constructor(input: Element | HTMLElement | string, o?: Awesomplete.Options); + static all: any[]; + static $$: (expr: string | NodeSelector, con?: any) => NodeList; + static ITEM: (text: string, input: string) => HTMLElement; + static $: { + (expr: string|Element, con?: NodeSelector): string | Element; + regExpEscape: (s: { replace: (arg0: RegExp, arg1: string) => void }) => any; + create: (tag: string, o: any) => HTMLElement; + fire: (target: EventTarget, type: string, properties: any) => any; + siblingIndex: (el: Element) => number; + }; + static FILTER_STARTSWITH: (text: string, input: string) => boolean; + static FILTER_CONTAINS: (text: string, input: string) => boolean; + static SORT_BYLENGTH: (left: number | any[], right: number | any[]) => number; + static REPLACE: (text: string) => void; + static DATA: (item: Awesomplete.Suggestion) => Awesomplete.Suggestion; + next: () => void; + container: HTMLElement; + select: (selected?: HTMLElement, originalTarget?: HTMLElement) => void; + previous: () => void; + index: number; + opened: number; + list: string | Element | Awesomplete.Suggestion[]; + input: HTMLElement | string; + goto: (i: number) => void; + ul: HTMLElement; + close: () => void; + evaluate: () => void; + selected: boolean; + open: () => void; + status: HTMLElement; } -interface AwesompleteOptions { - list?: string | string[] | Element | { label: string, value: any }[] | [string, string][]; - minChars?: Number; - maxItems?: Number; - autoFirst?: boolean; - data?: Function; - filter?: Function; - sort?: Function; - item?: Function; - replace?: Function; +declare namespace Awesomplete { + type Suggestion = string | {label: string | any, value: string | any} | [string, string]; + + interface Options { + list?: string | string[] | Element | { label: string, value: any }[] | [string, string][]; + minChars?: number; + maxItems?: number; + autoFirst?: boolean; + data?: (item: Suggestion, input: string) => string; + filter?: (text: string, input: string) => boolean; + sort?: (left: number | any[], right: number | any[]) => number; + item?: (text: string, input: string) => HTMLElement; + replace?: (text: string) => void; + } } + +export = Awesomplete; +export as namespace Awesomplete; diff --git a/awesomplete/tslint.json b/awesomplete/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/awesomplete/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/aws-lambda/aws-lambda-tests.ts b/aws-lambda/aws-lambda-tests.ts index fb09beda8a..1ffdb2980b 100644 --- a/aws-lambda/aws-lambda-tests.ts +++ b/aws-lambda/aws-lambda-tests.ts @@ -1,5 +1,3 @@ -/// - var str: string = "any string"; var date: Date = new Date(); var anyObj: any = { abc: 123 }; @@ -13,6 +11,12 @@ var clientContextClient: AWSLambda.ClientContextClient; var context: AWSLambda.Context; var identity: AWSLambda.CognitoIdentity; var proxyResult: AWSLambda.ProxyResult; +var snsEvt: AWSLambda.SNSEvent; +var snsEvtRecs: Array; +var snsEvtRec: AWSLambda.SNSEventRecord; +var snsMsg: AWSLambda.SNSMessage; +var snsMsgAttr: AWSLambda.SNSMessageAttribute; +var snsMsgAttrs: AWSLambda.SNSMessageAttributes; /* API Gateway Event */ str = apiGwEvt.body; @@ -44,9 +48,36 @@ str = apiGwEvt.requestContext.resourceId; str = apiGwEvt.requestContext.resourcePath; str = apiGwEvt.resource; +/* SNS Event */ +snsEvtRecs = snsEvt.Records; + +str = snsEvtRec.EventSource; +str = snsEvtRec.EventSubscriptionArn; +str = snsEvtRec.EventVersion; +snsMsg = snsEvtRec.Sns; + +str = snsMsg.SignatureVersion; +str = snsMsg.Timestamp; +str = snsMsg.Signature; +str = snsMsg.SigningCertUrl; +str = snsMsg.MessageId; +str = snsMsg.Message; +snsMsgAttrs = snsMsg.MessageAttributes; +str = snsMsg.Type; +str = snsMsg.UnsubscribeUrl; +str = snsMsg.TopicArn; +str = snsMsg.Subject; + +snsMsgAttrs["example"] = snsMsgAttr; + +str = snsMsgAttr.Type; +str = snsMsgAttr.Value; + /* Lambda Proxy Result */ num = proxyResult.statusCode; -str = proxyResult.headers["example"]; +proxyResult.headers["example"] = str; +proxyResult.headers["example"] = b; +proxyResult.headers["example"] = num; str = proxyResult.body /* Context */ diff --git a/aws-lambda/index.d.ts b/aws-lambda/index.d.ts index e8b70db7bd..83579b4d0d 100644 --- a/aws-lambda/index.d.ts +++ b/aws-lambda/index.d.ts @@ -39,6 +39,41 @@ interface APIGatewayEvent { resource: string; } +// SNS "event" +interface SNSMessageAttribute { + Type: string; + Value: string; +} + +interface SNSMessageAttributes { + [name: string]: SNSMessageAttribute; +} + +interface SNSMessage { + SignatureVersion: string; + Timestamp: string; + Signature: string; + SigningCertUrl: string; + MessageId: string; + Message: string; + MessageAttributes: SNSMessageAttributes; + Type: string; + UnsubscribeUrl: string; + TopicArn: string; + Subject: string; +} + +interface SNSEventRecord { + EventVersion: string; + EventSubscriptionArn: string; + EventSource: string; + Sns: SNSMessage; +} + +interface SNSEvent { + Records: Array; +} + // Context // http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html interface Context { @@ -97,7 +132,7 @@ interface ClientContextEnv { interface ProxyResult { statusCode: number; headers?: { - [header: string]: string; + [header: string]: boolean | number | string; }, body: string; } @@ -110,8 +145,8 @@ interface ProxyResult { * @param context – runtime information of the Lambda function that is executing. * @param callback – optional callback to return information to the caller, otherwise return value is null. */ -export type Handler = (event: any, context: Context, callback?: Callback) => void; -export type ProxyHandler = (event: APIGatewayEvent, context: Context, callback?: ProxyCallback) => void; +export type Handler = (event: any, context: Context, callback?: Callback) => void; +export type ProxyHandler = (event: APIGatewayEvent, context: Context, callback?: ProxyCallback) => void; /** * Optional callback parameter. diff --git a/aws-serverless-express/aws-serverless-express-tests.ts b/aws-serverless-express/aws-serverless-express-tests.ts index c46056ed25..97d236e043 100644 --- a/aws-serverless-express/aws-serverless-express-tests.ts +++ b/aws-serverless-express/aws-serverless-express-tests.ts @@ -1,9 +1,10 @@ -/// - import * as awsServerlessExpress from 'aws-serverless-express'; import * as express from 'express'; +import { eventContext } from 'aws-serverless-express/middleware'; const app = express(); +app.use(eventContext()); + const server = awsServerlessExpress.createServer(app, () => {}); const mockEvent = { diff --git a/aws-serverless-express/index.d.ts b/aws-serverless-express/index.d.ts index e4601e6ccd..db49e6ca6b 100644 --- a/aws-serverless-express/index.d.ts +++ b/aws-serverless-express/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for aws-serverless-express +// Type definitions for aws-serverless-express 2.1 // Project: https://github.com/awslabs/aws-serverless-express -// Definitions by: Ben Speakman +// Definitions by: Ben Speakman , Josh Caffey // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -16,4 +16,4 @@ export function proxy( server: http.Server, event: any, context: lambda.Context -): void; \ No newline at end of file +): void; diff --git a/aws-serverless-express/middleware.d.ts b/aws-serverless-express/middleware.d.ts new file mode 100644 index 0000000000..ff33b4c6ea --- /dev/null +++ b/aws-serverless-express/middleware.d.ts @@ -0,0 +1,8 @@ +import { RequestHandler } from 'express'; + +export interface Options { + reqPropKey?: string; + deleteHeaders?: boolean; +} + +export function eventContext(options?: Options): RequestHandler; diff --git a/aws-serverless-express/tsconfig.json b/aws-serverless-express/tsconfig.json index a62cead1a1..62885fcda3 100644 --- a/aws-serverless-express/tsconfig.json +++ b/aws-serverless-express/tsconfig.json @@ -17,6 +17,7 @@ }, "files": [ "index.d.ts", + "middleware.d.ts", "aws-serverless-express-tests.ts" ] -} \ No newline at end of file +} diff --git a/aws-serverless-express/tslint.json b/aws-serverless-express/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/aws-serverless-express/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/b_/b_-tests.ts b/b_/b_-tests.ts new file mode 100644 index 0000000000..c0a92a4c7d --- /dev/null +++ b/b_/b_-tests.ts @@ -0,0 +1,52 @@ +import b_ = require("b_"); + +const blockClass: string = b_("block"); +const blockWithModsClass: string = b_("block", {stringMod: "string", boolMod: true, numberMod: 5}); +const elemClass: string = b_("block", "elem"); +const elemWithModsClass: string = b_("block", "elem", {stringMod: "string", boolMod: true, numberMod: 5}); + +const withBlock = b_.with("block"); +const withBlockClass: string = withBlock(); +const withBlockWithModsClass: string = withBlock({stringMod: "string", boolMod: true, numberMod: 5}); +const withBlockElemClass: string = withBlock("elem"); +const withBlockElemWithModsClass: string = withBlock("elem", {stringMod: "string", boolMod: true, numberMod: 5}); + +const lockBlock = b_.lock("block"); +const lockBlockClass: string = lockBlock(); +const lockBlockWithModsClass: string = lockBlock({stringMod: "string", boolMod: true, numberMod: 5}); +const lockBlockElemClass: string = lockBlock("elem"); +const lockBlockElemWithModsClass: string = lockBlock("elem", {stringMod: "string", boolMod: true, numberMod: 5}); + +const withElem = b_.with("block", "elem"); +const withElemClass: string = withElem(); +const withElemWithModsClass: string = withElem({stringMod: "string", boolMod: true, numberMod: 5}); + +const parameterizedB_ = b_.B({ + tailSpace: " ", + elementSeparator: "-", + modSeparator: "_", + modValueSeparator: "-", + classSeparator: " ", + isFullModifier: true +}); + +const parameterizedBlockClass: string = parameterizedB_("block"); +const parameterizedBlockWithModsClass: string = parameterizedB_("block", {stringMod: "string", boolMod: true, numberMod: 5}); +const parameterizedElemClass: string = parameterizedB_("block", "elem"); +const parameterizedElemWithModsClass: string = parameterizedB_("block", "elem", {stringMod: "string", boolMod: true, numberMod: 5}); + +const parameterizedWithBlock = parameterizedB_.with("block"); +const parameterizedWithBlockClass: string = parameterizedWithBlock(); +const parameterizedWithBlockWithModsClass: string = parameterizedWithBlock({stringMod: "string", boolMod: true, numberMod: 5}); +const parameterizedWithBlockElemClass: string = parameterizedWithBlock("elem"); +const parameterizedWithBlockElemWithModsClass: string = parameterizedWithBlock("elem", {stringMod: "string", boolMod: true, numberMod: 5}); + +const parameterizedLockBlock = parameterizedB_.lock("block"); +const parameterizedLockBlockClass: string = parameterizedLockBlock(); +const parameterizedLockBlockWithModsClass: string = parameterizedLockBlock({stringMod: "string", boolMod: true, numberMod: 5}); +const parameterizedLockBlockElemClass: string = parameterizedLockBlock("elem"); +const parameterizedLockBlockElemWithModsClass: string = parameterizedLockBlock("elem", {stringMod: "string", boolMod: true, numberMod: 5}); + +const parameterizedWithElem = parameterizedB_.with("block", "elem"); +const parameterizedWithElemClass: string = parameterizedWithElem(); +const parameterizedWithElemWithModsClass: string = parameterizedWithElem({stringMod: "string", boolMod: true, numberMod: 5}); diff --git a/b_/index.d.ts b/b_/index.d.ts new file mode 100644 index 0000000000..fe59f2d72e --- /dev/null +++ b/b_/index.d.ts @@ -0,0 +1,40 @@ +// Type definitions for b_ 1.3 +// Project: https://github.com/azproduction/b_ +// Definitions by: Vasya Aksyonov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Options { + tailSpace?: string; + elementSeparator?: string; + modSeparator?: string; + modValueSeparator?: string; + classSeparator?: string; + isFullModifier?: boolean; +} + +interface Mods { + [name: string]: any; +} + +interface Formatter { + (block: string, mods?: Mods): string; + (block: string, elem: string, mods?: Mods): string; + + with(block: string): BlockFormatter; + with(block: string, elem: string): ElemFormatter; + + lock(block: string): BlockFormatter; + lock(block: string, elem: string): ElemFormatter; + + B(options: Options): Formatter; +} + +interface BlockFormatter { + (mods?: Mods): string; + (elem: string, mods?: Mods): string; +} + +type ElemFormatter = (mods?: Mods) => string; + +declare const formatter: Formatter; +export = formatter; diff --git a/b_/tsconfig.json b/b_/tsconfig.json new file mode 100644 index 0000000000..5271d3aeeb --- /dev/null +++ b/b_/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "b_-tests.ts" + ] +} diff --git a/b_/tslint.json b/b_/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/b_/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/babel-template/babel-template-tests.ts b/babel-template/babel-template-tests.ts index b5d4547188..31e3bd44d9 100644 --- a/babel-template/babel-template-tests.ts +++ b/babel-template/babel-template-tests.ts @@ -1,7 +1,4 @@ - /// -/// - // Example from https://github.com/babel/babel/tree/master/packages/babel-template import template = require('babel-template'); diff --git a/babel-traverse/babel-traverse-tests.ts b/babel-traverse/babel-traverse-tests.ts index 3779852c5f..98afbbc0a7 100644 --- a/babel-traverse/babel-traverse-tests.ts +++ b/babel-traverse/babel-traverse-tests.ts @@ -1,5 +1,3 @@ - -/// /// diff --git a/babylon/babylon-tests.ts b/babylon/babylon-tests.ts index bb95625935..769d635e89 100644 --- a/babylon/babylon-tests.ts +++ b/babylon/babylon-tests.ts @@ -1,8 +1,3 @@ - -/// -/// - - // Example from https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babylon import * as babylon from "babylon"; declare function assert(expr: boolean): void; diff --git a/babylon/index.d.ts b/babylon/index.d.ts index 45b929264d..4400a8f1a0 100644 --- a/babylon/index.d.ts +++ b/babylon/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for babylon v6.7 +// Type definitions for babylon v6.16.1 // Project: https://github.com/babel/babylon // Definitions by: Troy Gerwien // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -41,7 +41,17 @@ export interface BabylonOptions { plugins?: PluginName[]; } -export type PluginName = 'jsx' | 'flow' | 'asyncFunctions' | 'classConstructorCall' | 'doExpressions' - | 'trailingFunctionCommas' | 'objectRestSpread' | 'decorators' | 'classProperties' | 'exportExtensions' - | 'exponentiationOperator' | 'asyncGenerators' | 'functionBind' | 'functionSent' | '*'; - +export type PluginName = + 'estree' | + 'jsx' | + 'flow' | + 'classConstructorCall' | + 'doExpressions' | + 'objectRestSpread' | + 'decorators' | + 'classProperties' | + 'exportExtensions' | + 'asyncGenerators' | + 'functionBind' | + 'functionSent' | + 'dynamicImport'; diff --git a/backbone.layoutmanager/backbone.layoutmanager-tests.ts b/backbone.layoutmanager/backbone.layoutmanager-tests.ts index fe11ce9b18..edddb8352b 100644 --- a/backbone.layoutmanager/backbone.layoutmanager-tests.ts +++ b/backbone.layoutmanager/backbone.layoutmanager-tests.ts @@ -1,5 +1,3 @@ -/// - import * as Backbone from 'backbone'; // Example code. @@ -26,7 +24,7 @@ class View extends Backbone.Layout { "mouseleave": "removeElement" } } - + wrapElement(): void { this.$el.wrap(""); } diff --git a/backbone/backbone-tests.ts b/backbone/backbone-tests.ts index accdb93979..c074ac57e5 100644 --- a/backbone/backbone-tests.ts +++ b/backbone/backbone-tests.ts @@ -1,5 +1,3 @@ -/// - function test_events() { var object = new Backbone.Events(); diff --git a/bardjs/bardjs-tests.ts b/bardjs/bardjs-tests.ts index 2d312634ca..91172b7255 100644 --- a/bardjs/bardjs-tests.ts +++ b/bardjs/bardjs-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as angular from 'angular'; import 'angular-mocks'; diff --git a/batch-stream/batch-stream-tests.ts b/batch-stream/batch-stream-tests.ts index d3195466e8..4554530072 100644 --- a/batch-stream/batch-stream-tests.ts +++ b/batch-stream/batch-stream-tests.ts @@ -1,5 +1,3 @@ -/// - import fs = require('fs'); import BatchStream = require('batch-stream'); diff --git a/bazinga-translator/bazinga-translator-tests.ts b/bazinga-translator/bazinga-translator-tests.ts index 8c5d1dafa8..3856ff22a1 100644 --- a/bazinga-translator/bazinga-translator-tests.ts +++ b/bazinga-translator/bazinga-translator-tests.ts @@ -1,5 +1,3 @@ -/// - Translator.fallback = 'en'; Translator.defaultDomain = 'messages'; diff --git a/bezier-js/bezier-js-tests.ts b/bezier-js/bezier-js-tests.ts index f5fba4d947..003b6e1c45 100644 --- a/bezier-js/bezier-js-tests.ts +++ b/bezier-js/bezier-js-tests.ts @@ -1,5 +1,3 @@ -/// - function test() { var bezierjs: typeof BezierJs; diff --git a/big-integer/big-integer-tests.ts b/big-integer/big-integer-tests.ts index 2ab3c1fad5..62f234b371 100644 --- a/big-integer/big-integer-tests.ts +++ b/big-integer/big-integer-tests.ts @@ -113,5 +113,6 @@ isBigInteger = x.times( "100" ); isNumber = x.toJSNumber(); isString = x.toString(); +isString = x.toString(36); isNumber = x.valueOf(); diff --git a/big-integer/index.d.ts b/big-integer/index.d.ts index 452593e950..f8ca2b488c 100644 --- a/big-integer/index.d.ts +++ b/big-integer/index.d.ts @@ -195,7 +195,7 @@ interface BigInteger { toJSNumber(): number; /** Converts a bigInt to a string. */ - toString(): string; + toString( radix?: number ): string; /** Converts a bigInt to a native Javascript number. This override allows you to use native arithmetic operators without explicit conversion. */ valueOf(): number; diff --git a/bignumber.js/bignumber.js-tests.ts b/bignumber.js/bignumber.js-tests.ts new file mode 100644 index 0000000000..a375fc60cd --- /dev/null +++ b/bignumber.js/bignumber.js-tests.ts @@ -0,0 +1,445 @@ +var x: BigNumber.BigNumber = new BigNumber(9) +var y = new BigNumber(x) + +BigNumber(435.345) + +new BigNumber('5032485723458348569331745.33434346346912144534543') +new BigNumber('4.321e+4') +new BigNumber('-735.0918e-430') +new BigNumber(Infinity) +new BigNumber(NaN) +new BigNumber('.5') +new BigNumber('+2') +new BigNumber(-10110100.1, 2) +new BigNumber(-0b10110100) +new BigNumber('123412421.234324', 5) +new BigNumber('ff.8', 16) +new BigNumber('0xff.8') + +new BigNumber(9, 2) + +new BigNumber(96517860459076817.4395) + +new BigNumber('blurgh') + +BigNumber.config({ DECIMAL_PLACES: 5 }) +new BigNumber(1.23456789) +new BigNumber(1.23456789, 10) + +BigNumber.config({ DECIMAL_PLACES: 5 }) +var BN = BigNumber.another({ DECIMAL_PLACES: 9 }) + +x = new BigNumber(1) +y = new BN(1) + +x.div(3) +y.div(3) + +BN = BigNumber.another() +BN.config({ DECIMAL_PLACES: 9 }) + +BigNumber.config({ DECIMAL_PLACES: 5 }) +BigNumber.set({ DECIMAL_PLACES: 5 }) +BigNumber.config(5) + +BigNumber.config({ ROUNDING_MODE: 0 }) +BigNumber.config(undefined, BigNumber.ROUND_UP) + +BigNumber.config({ EXPONENTIAL_AT: 2 }) +new BigNumber(12.3) +new BigNumber(123) +new BigNumber(0.123) +new BigNumber(0.0123) + +BigNumber.config({ EXPONENTIAL_AT: [-7, 20] }) +new BigNumber(123456789) +new BigNumber(0.000000123) + +BigNumber.config({ EXPONENTIAL_AT: 1e+9 }) + +BigNumber.config({ EXPONENTIAL_AT: 0 }) + +BigNumber.config({ RANGE: 500 }) +BigNumber.config().RANGE +new BigNumber('9.999e499') +new BigNumber('1e500') +new BigNumber('1e-499') +new BigNumber('1e-500') + +BigNumber.config({ RANGE: [-3, 4] }) +new BigNumber(99999) +new BigNumber(100000) +new BigNumber(0.001) +new BigNumber(0.0001) + +BigNumber.config({ ERRORS: false }) + +BigNumber.config({ CRYPTO: true }) +BigNumber.config().CRYPTO +BigNumber.random() + +BigNumber.config({ MODULO_MODE: BigNumber.EUCLID }) +BigNumber.config({ MODULO_MODE: 9 }) + +BigNumber.config({ POW_PRECISION: 100 }) + +BigNumber.config({ + FORMAT: { + decimalSeparator: '.', + groupSeparator: ',', + groupSize: 3, + secondaryGroupSize: 0, + fractionGroupSeparator: ' ', + fractionGroupSize: 0 + } +}); + +BigNumber.config({ + DECIMAL_PLACES: 40, + ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL, + EXPONENTIAL_AT: [-10, 20], + RANGE: [-500, 500], + ERRORS: true, + CRYPTO: true, + MODULO_MODE: BigNumber.ROUND_FLOOR, + POW_PRECISION: 80, + FORMAT: { + groupSize: 3, + groupSeparator: ' ', + decimalSeparator: ',' + } +}); + +BigNumber.config(40, 7, [-10, 20], 500, 1, 1, 3, 80) + +var obj = BigNumber.config(); +obj.ERRORS +obj.RANGE + +x = new BigNumber('3257869345.0378653') +BigNumber.max(4e9, x, '123456789.9') + +var arr = [12, '13', new BigNumber(14)] +BigNumber.max(arr) + +x = new BigNumber('3257869345.0378653') +BigNumber.min(4e9, x, '123456789.9') + +arr = [2, new BigNumber(-14), '-15.9999', -12] +BigNumber.min(arr) + +BigNumber.config({ DECIMAL_PLACES: 10 }) +BigNumber.random() +BigNumber.random(20) + +BigNumber.config({ ROUNDING_MODE: BigNumber.ROUND_CEIL }) +BigNumber.config({ ROUNDING_MODE: 2 }) + +x = new BigNumber(-0.8) +y = x.absoluteValue() +var z = y.abs() + +x = new BigNumber(1.3) +x.ceil() +y = new BigNumber(-1.8) +y.ceil() + +x = new BigNumber(Infinity) +y = new BigNumber(5) +x.comparedTo(y) +x.comparedTo(x.minus(1)) +y.cmp(NaN) +y.cmp('110', 2) + +x = new BigNumber(123.45) +x.decimalPlaces() +y = new BigNumber('9.9e-101') +y.dp() + +x = new BigNumber(355) +y = new BigNumber(113) +x.dividedBy(y) +x.div(5) +x.div(47, 16) + +x = new BigNumber(5) +y = new BigNumber(3) +x.dividedToIntegerBy(y) +x.divToInt(0.7) +x.divToInt('0.f', 16) + +0 === 1e-324 +x = new BigNumber(0) +x.equals('1e-324') +BigNumber(-0).eq(x) +BigNumber(255).eq('ff', 16) + +y = new BigNumber(NaN) +y.equals(NaN) + +x = new BigNumber(1.8) +x.floor() +y = new BigNumber(-1.3) +y.floor() + +0.1 > (0.3 - 0.2) +x = new BigNumber(0.1) +x.greaterThan(BigNumber(0.3).minus(0.2)) +BigNumber(0).gt(x) +BigNumber(11, 3).gt(11.1, 2) + +x = new BigNumber(0.3).minus(0.2) +x.greaterThanOrEqualTo(0.1) +BigNumber(1).gte(x) +BigNumber(10, 18).gte('i', 36) + +x = new BigNumber(1) +x.isFinite() +y = new BigNumber(Infinity) +y.isFinite() + +x = new BigNumber(1) +x.isInteger() +y = new BigNumber(123.456) +y.isInt() + +x = new BigNumber(NaN) +x.isNaN() +y = new BigNumber('Infinity') +y.isNaN() + +x = new BigNumber(-0) +x.isNegative() +y = new BigNumber(2) +y.isNeg() + +x = new BigNumber(-0) +x.isZero() && x.isNeg() +y = new BigNumber(Infinity) +y.isZero() + +x = new BigNumber(0.3).minus(0.2) +x.lessThan(0.1) +BigNumber(0).lt(x) +BigNumber(11.1, 2).lt(11, 3) + +x = new BigNumber(0.1) +x.lessThanOrEqualTo(BigNumber(0.3).minus(0.2)) +BigNumber(-1).lte(x) +BigNumber(10, 18).lte('i', 36) + +x = new BigNumber(0.3) +x.minus(0.1) +x.sub(0.6, 20) + +x = new BigNumber(1) +x.modulo(0.9) +y = new BigNumber(33) +y.mod('a', 33) + +x = new BigNumber(1.8) +x.negated() +y = new BigNumber(-1.3) +y.neg() + +x = new BigNumber(0.1) +y = x.plus(0.2) +BigNumber(0.7).plus(x).add(y) +x.plus('0.1', 8) + +x = new BigNumber(1.234) +x.precision() +y = new BigNumber(987000) +y.sd() +y.sd(true) + +y = new BigNumber(x) +y.round() +y.round(1) +y.round(2) +y.round(10) +y.round(0, 1) +y.round(0, 6) +y.round(1, 1) +y.round(1, BigNumber.ROUND_HALF_EVEN) +y + +x = new BigNumber(1.23) +x.shift(3) +x.shift(-3) + +x = new BigNumber(16) +x.squareRoot() +y = new BigNumber(3) +y.sqrt() + +x = new BigNumber(0.6) +y = x.times(3) +BigNumber('7e+500').times(y) +x.times('-a', 16) + +BigNumber.config({ DECIMAL_PLACES: 5, ROUNDING_MODE: 4 }) +x = new BigNumber(9876.54321) + +x.toDigits() +x.toDigits(6) +x.toDigits(6, BigNumber.ROUND_UP) +x.toDigits(2) +x.toDigits(2, 1) +x + +y = new BigNumber(45.6) +y.toExponential() +y.toExponential(0) +y.toExponential(1) +y.toExponential(1, 1) +y.toExponential(3) + +y = new BigNumber(3.456) +y.toFixed() +y.toFixed(0) +y.toFixed(2) +y.toFixed(2, 1) +y.toFixed(5) + +var format = { + decimalSeparator: '.', + groupSeparator: ',', + groupSize: 3, + secondaryGroupSize: 0, + fractionGroupSeparator: ' ', + fractionGroupSize: 0 +} +BigNumber.config({ FORMAT: format }) + +x = new BigNumber('123456789.123456789') +x.toFormat() +x.toFormat(1) + +format.groupSeparator = ' ' +format.fractionGroupSize = 5 +x.toFormat() + +BigNumber.config({ + FORMAT: { + decimalSeparator: ',', + groupSeparator: '.', + groupSize: 3, + secondaryGroupSize: 2 + } +}) + +x.toFormat(6) + +x = new BigNumber(1.75) +x.toFraction() + +var pi = new BigNumber('3.14159265358') +pi.toFraction() +pi.toFraction(100000) +pi.toFraction(10000) +pi.toFraction(100) +pi.toFraction(10) +pi.toFraction(1) + +x = new BigNumber('177.7e+457') +y = new BigNumber(235.4325) +z = new BigNumber('0.0098074') + +var str = JSON.stringify([x, y, z]) + +JSON.parse(str, (key, val) => key === '' ? val : new BigNumber(val)) + +x = new BigNumber(456.789) +x.toNumber() +{ +x } + +y = new BigNumber('45987349857634085409857349856430985') +y.toNumber() + +z = new BigNumber(-0) +1 / +z +1 / z.toNumber() + +x = new BigNumber(0.7) +x.toPower(2) +BigNumber(3).pow(-2) + +y = new BigNumber(45.6) +x.toPrecision() +y.toPrecision() +x.toPrecision(1) +y.toPrecision(1) +y.toPrecision(2, 0) +y.toPrecision(2, 1) +x.toPrecision(5) +y.toPrecision(5) + +x = new BigNumber(750000) +x.toString() +BigNumber.config({ EXPONENTIAL_AT: 5 }) +x.toString() + +y = new BigNumber(362.875) +y.toString(2) +y.toString(9) +y.toString(32) + +BigNumber.config({ DECIMAL_PLACES: 4 }); +z = new BigNumber('1.23456789') +z.toString() +z.toString(10) + +x = new BigNumber(123.456) +x.truncated() +y = new BigNumber(-12.3) +y.trunc() + +x = new BigNumber('-0') +x.toString() +x.valueOf() +y = new BigNumber('1.777e+457') +y.valueOf() + +x = new BigNumber(0.123) +x.toExponential() +x.c +x.e +x.s + +z = new BigNumber('-123.4567000e+2') +z.toExponential() +z.c +z.e +z.s + +x = new BigNumber(3) +x instanceof BigNumber +x.isBigNumber + +BN = BigNumber.another(); + +y = new BN(3) +y instanceof BigNumber +y.isBigNumber + +y = new BigNumber(-0) +y.c +y.e +y.s + +try { + // ... +} catch (e) { + if (e instanceof Error && e.name == 'BigNumber Error') { + // ... + } +} + +x = new BigNumber("1.0") +y = new BigNumber("1.1000") +z = x.add(y) + +x = new BigNumber("1.20") +y = new BigNumber("3.45000") +z = x.mul(y) diff --git a/bignumber.js/index.d.ts b/bignumber.js/index.d.ts new file mode 100644 index 0000000000..d94be507c7 --- /dev/null +++ b/bignumber.js/index.d.ts @@ -0,0 +1,681 @@ +// Type definitions for bignumber.js 4.0 +// Project: https://github.com/MikeMcl/bignumber.js/ +// Definitions by: Viktor Smirnov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +declare var BigNumber: BigNumber.BigNumberStatic; + +export as namespace BigNumber; +export = BigNumber; + +declare namespace BigNumber { + + interface FormatConfig { + + /** + * The decimal separator. + */ + decimalSeparator: string; + + /** + * The grouping separator of the integer part. + */ + groupSeparator: string; + + /** + * The primary grouping size of the integer part. + */ + groupSize: number; + + /** + * The secondary grouping size of the integer part. + */ + secondaryGroupSize: number; + + /** + * The grouping separator of the fraction part. + */ + fractionGroupSeparator: string; + + /** + * The grouping size of the fraction part. + */ + fractionGroupSize: number; + } + + interface BigNumberConfig { + + /** + * The maximum number of decimal places of the results of operations involving division, + * i.e. division, square root and base conversion operations, and power operations with negative exponents. + */ + DECIMAL_PLACES: number; + + /** + * The rounding mode used in the above operations and the default rounding mode of round, `toExponential`, `toFixed`, `toFormat` and `toPrecision`. + */ + ROUNDING_MODE: RoundingMode; + + /** + * The exponent value(s) at which `toString` returns exponential notation. + * + * If a single number is assigned, the value is the exponent magnitude. + * + * If an array of two numbers is assigned then the first number is the negative exponent value at and beneath which exponential notation is used, + * and the second number is the positive exponent value at and above which the same. + */ + EXPONENTIAL_AT: number | number[]; + + /** + * The exponent value(s) beyond which overflow to `Infinity` and underflow to zero occurs. + * + * If a single number is assigned, it is the maximum exponent magnitude: + * values wth a positive exponent of greater magnitude become `Infinity` + * and those with a negative exponent of greater magnitude become zero. + * + * If an array of two numbers is assigned then the first number is the negative exponent limit and the second number is the positive exponent limit. + */ + RANGE: number | number[]; + + /** + * The value that determines whether BigNumber Errors are thrown. + * + * If `ERRORS` is false, no errors will be thrown. + */ + ERRORS: boolean | 0 | 1; + + /** + * The value that determines whether cryptographically-secure pseudo-random number generation is used. + * + * If `CRYPTO` is set to `true` then the `random` method will generate random digits using `crypto.getRandomValues` in browsers that support it, + * or `crypto.randomBytes` if using a version of Node.js that supports it. + * + * If neither function is supported by the host environment then attempting to set `CRYPTO` to `true` will fail, and if `ERRORS` is `true` an exception will be thrown. + * + * If `CRYPTO` is `false` then the source of randomness used will be `Math.random` (which is assumed to generate at least `30` bits of randomness). + */ + CRYPTO: boolean | 0 | 1; + + /** + * The modulo mode used when calculating the modulus: `a mod n`. + * + * The quotient, `q = a / n`, is calculated according to the `ROUNDING_MODE` that corresponds to the chosen `MODULO_MODE`. + * + * The remainder, `r`, is calculated as: `r = a - n * q`. + */ + MODULO_MODE: ModuloMode; + + /** + * The maximum number of significant digits of the result of the power operation (unless a modulus is specified). + * + * If set to `0`, the number of signifcant digits will not be limited. + */ + POW_PRECISION: number; + + /** + * The `FORMAT` object configures the format of the string returned by the toFormat method. + */ + FORMAT: Partial + } + + type NumberLike = number | string | BigNumber; + type RoundingMode = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 + type ModuloMode = RoundingMode | 9 + + interface BigNumberStatic { + + /** + * Returns a new instance of a BigNumber object. + */ + (value: NumberLike, base?: number): BigNumber; + + /** + * Returns a new instance of a BigNumber object. + */ + new (value: NumberLike, base?: number): BigNumber; + + /** + * Returns a new independent BigNumber constructor with configuration as described by obj, or with the default configuration if obj is null or undefined. + */ + another(obj?: Partial): BigNumberStatic; + + /** + * Configures the settings for this particular BigNumber constructor. + * + */ + config(obj?: Partial): BigNumberConfig; + + /** + * Configures the settings for this particular BigNumber constructor. + */ + config( + DECIMAL_PLACES?: number, + ROUNDING_MODE?: RoundingMode, + EXPONENTIAL_AT?: number | number[], + RANGE?: number | number[], + ERRORS?: boolean | 0 | 1, + CRYPTO?: boolean | 0 | 1, + MODULO_MODE?: ModuloMode, + POW_PRECISION?: number + ): BigNumberConfig; + + /** + * Configures the settings for this particular BigNumber constructor. + */ + set(obj?: Partial): BigNumberConfig; + + /** + * Configures the settings for this particular BigNumber constructor. + */ + set( + DECIMAL_PLACES?: number, + ROUNDING_MODE?: RoundingMode, + EXPONENTIAL_AT?: number | number[], + RANGE?: number | number[], + ERRORS?: boolean | 0 | 1, + CRYPTO?: boolean | 0 | 1, + MODULO_MODE?: ModuloMode, + POW_PRECISION?: number + ): BigNumberConfig; + + /** + * Returns a BigNumber whose value is the maximum of `args`. + */ + max(...args: NumberLike[]): BigNumber; + + /** + * Returns a BigNumber whose value is the maximum of `args`. + */ + max(args: NumberLike[]): BigNumber; + + /** + * Returns a BigNumber whose value is the minimum of `args`. + */ + min(...args: NumberLike[]): BigNumber; + + /** + * Returns a BigNumber whose value is the minimum of `args`. + */ + min(args: NumberLike[]): BigNumber; + + /** + * Returns a new BigNumber with a pseudo-random value equal to or greater than `0` and less than `1`. + * + * The return value will have `dp` decimal places (or less if trailing zeros are produced). + * If `dp` is omitted then the number of decimal places will default to the current `DECIMAL_PLACES` setting. + * + * Depending on the value of this BigNumber constructor's `CRYPTO` setting and the support for the `crypto` object in the host environment, + * the random digits of the return value are generated by either + * `Math.random` (fastest), + * `crypto.getRandomValues` (Web Cryptography API in recent browsers) + * or `crypto.randomBytes` (Node.js). + * + * If `CRYPTO` is `true`, i.e. one of the `crypto` methods is to be used, + * the value of a returned BigNumber should be cryptographically-secure and statistically indistinguishable from a random value. + */ + random(dp?: number): BigNumber; + + /** + * Rounds away from zero + */ + ROUND_UP: 0; + + /** + * Rounds towards zero + */ + ROUND_DOWN: 1; + + /** + * Rounds towards `Infinity` + */ + ROUND_CEIL: 2; + + /** + * Rounds towards `-Infinity` + */ + ROUND_FLOOR: 3; + + /** + * Rounds towards nearest neighbour. + * If equidistant, rounds away from zero. + */ + ROUND_HALF_UP: 4; + + /** + * Rounds towards nearest neighbour. + * If equidistant, rounds towards zero. + */ + ROUND_HALF_DOWN: 5; + + /** + * Rounds towards nearest neighbour. + * If equidistant, rounds towards even neighbour. + */ + ROUND_HALF_EVEN: 6; + + /** + * Rounds towards nearest neighbour. + * If equidistant, rounds towards `Infinity`. + */ + ROUND_HALF_CEIL: 7; + + /** + * Rounds towards nearest neighbour. + * If equidistant, rounds towards `-Infinity`. + */ + ROUND_HALF_FLOOR: 8; + + /** + * The remainder is always positive. + * + * Euclidian division: `q = sign(n) * floor(a / abs(n))` + */ + EUCLID: 9; + } + + interface BigNumber { + + /** + * Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of this BigNumber. + */ + absoluteValue(): BigNumber; + + /** + * Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of this BigNumber. + */ + abs(): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded to a whole number in the direction of positive Infinity. + */ + ceil(): BigNumber; + + /** + * Returns + * + * `1` if the value of this BigNumber is greater than the value of `n` + * + * `-1` if the value of this BigNumber is less than the value of `n` + * + * `0` if this BigNumber and `n` have the same value + * + * `null` if the value of either this BigNumber or `n` is `NaN` + */ + comparedTo(n: NumberLike, base?: number): 1 | -1 | 0 | null; + + /** + * Returns + * + * `1` if the value of this BigNumber is greater than the value of `n` + * + * `-1` if the value of this BigNumber is less than the value of `n` + * + * `0` if this BigNumber and `n` have the same value + * + * `null` if the value of either this BigNumber or `n` is `NaN` + */ + cmp(n: NumberLike, base?: number): 1 | -1 | 0 | null; + + /** + * Return the number of decimal places of the value of this BigNumber, or `null` if the value of this BigNumber is `±Infinity` or `NaN`. + */ + decimalPlaces(): number; + + /** + * Return the number of decimal places of the value of this BigNumber, or `null` if the value of this BigNumber is `±Infinity` or `NaN`. + */ + dp(): number; + + /** + * Returns a BigNumber whose value is the value of this BigNumber divided by `n`, rounded according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` configuration. + */ + dividedBy(n: NumberLike, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber divided by `n`, rounded according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` configuration. + */ + div(n: NumberLike, base?: number): BigNumber; + + /** + * Return a BigNumber whose value is the integer part of dividing the value of this BigNumber by `n`. + */ + dividedToIntegerBy(n: NumberLike, base?: number): BigNumber; + + /** + * Return a BigNumber whose value is the integer part of dividing the value of this BigNumber by `n`. + */ + divToInt(n: NumberLike, base?: number): BigNumber; + + /** + * Returns `true` if the value of this BigNumber equals the value of `n`, otherwise returns `false`. + * + * As with JavaScript, `NaN` does not equal `NaN`. + */ + equals(n: NumberLike, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber equals the value of `n`, otherwise returns `false`. + * + * As with JavaScript, `NaN` does not equal `NaN`. + */ + eq(n: NumberLike, base?: number): boolean; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded to a whole number in the direction of negative `Infinity`. + */ + floor(): BigNumber; + + /** + * Returns `true` if the value of this BigNumber is greater than the value of `n`, otherwise returns `false`. + */ + greaterThan(n: NumberLike, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than the value of `n`, otherwise returns `false`. + */ + gt(n: NumberLike, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than or equal to the value of `n`, otherwise returns `false`. + */ + greaterThanOrEqualTo(n: NumberLike, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than or equal to the value of `n`, otherwise returns `false`. + */ + gte(n: NumberLike, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is a finite number, otherwise returns `false`. + * + * The only possible non-finite values of a BigNumber are `NaN`, `Infinity` and `-Infinity`. + */ + isFinite(): boolean; + + /** + * Returns `true` if the value of this BigNumber is a whole number, otherwise returns `false`. + */ + isInteger(): boolean; + + /** + * Returns `true` if the value of this BigNumber is a whole number, otherwise returns `false`. + */ + isInt(): boolean; + + /** + * Returns `true` if the value of this BigNumber is NaN, otherwise returns `false`. + */ + isNaN(): boolean; + + /** + * Returns `true` if the value of this BigNumber is negative, otherwise returns `false`. + */ + isNegative(): boolean; + + /** + * Returns `true` if the value of this BigNumber is negative, otherwise returns `false`. + */ + isNeg(): boolean; + + /** + * Returns `true` if the value of this BigNumber is zero or minus zero, otherwise returns `false`. + */ + isZero(): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than the value of `n`, otherwise returns `false`. + */ + lessThan(n: NumberLike, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than the value of `n`, otherwise returns `false`. + */ + lt(n: NumberLike, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than or equal to the value of `n`, otherwise returns + */ + lessThanOrEqualTo(n: NumberLike, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than or equal to the value of `n`, otherwise returns + */ + lte(n: NumberLike, base?: number): boolean; + + /** + * Returns a BigNumber whose value is the value of this BigNumber minus `n`. + */ + minus(n: NumberLike, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber minus `n`. + */ + sub(n: NumberLike, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber modulo `n`, i.e. the integer remainder of dividing this BigNumber by `n`. + * + * The value returned, and in particular its sign, is dependent on the value of the `MODULO_MODE` setting of this BigNumber constructor. + * If it is `1` (default value), the result will have the same sign as this BigNumber, + * and it will match that of Javascript's `%` operator (within the limits of double precision) and BigDecimal's `remainder` method. + */ + modulo(n: NumberLike, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber modulo `n`, i.e. the integer remainder of dividing this BigNumber by `n`. + * + * The value returned, and in particular its sign, is dependent on the value of the `MODULO_MODE` setting of this BigNumber constructor. + * If it is `1` (default value), the result will have the same sign as this BigNumber, + * and it will match that of Javascript's `%` operator (within the limits of double precision) and BigDecimal's `remainder` method. + */ + mod(n: NumberLike, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber negated, i.e. multiplied by `-1`. + */ + negated(): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber negated, i.e. multiplied by `-1`. + */ + neg(): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber plus `n`. + */ + plus(n: NumberLike, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber plus `n`. + */ + add(n: NumberLike, base?: number): BigNumber; + + /** + * Returns the number of significant digits of the value of this BigNumber. + * + * If `z` is `true` or `1` then any trailing zeros of the integer part of a number are counted as significant digits, otherwise they are not. + */ + precision(z?: boolean | 0 | 1): number; + + /** + * Returns the number of significant digits of the value of this BigNumber. + * + * If `z` is `true` or `1` then any trailing zeros of the integer part of a number are counted as significant digits, otherwise they are not. + */ + sd(z?: boolean | 0 | 1): number; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded by rounding mode `rm` to a maximum of `dp` decimal places. + * + * If `dp` is omitted, or is `null` or `undefined`, the return value is `n` rounded to a whole number. + * + * If `rm` is omitted, or is `null` or `undefined`, `ROUNDING_MODE` is used. + */ + round(dp?: number, rm?: RoundingMode): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber shifted `n` places. + * + * The shift is of the decimal point, i.e. of powers of ten, and is to the left if `n` is negative or to the right if `n` is positive. + */ + shift(n: number): BigNumber; + + /** + * Returns a BigNumber whose value is the square root of the value of this BigNumber, rounded according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` configuration. + * + * The return value will be correctly rounded, i.e. rounded as if the result was first calculated to an infinite number of correct digits before rounding. + */ + squareRoot(): BigNumber; + + /** + * Returns a BigNumber whose value is the square root of the value of this BigNumber, rounded according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` configuration. + * + * The return value will be correctly rounded, i.e. rounded as if the result was first calculated to an infinite number of correct digits before rounding. + */ + sqrt(): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber times `n`. + */ + times(n: NumberLike, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber times `n`. + */ + mul(n: NumberLike, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded to `sd` significant digits using rounding mode `rm`. + * + * If `sd` is omitted or is `null` or `undefined`, the return value will not be rounded. + * + * If `rm` is omitted or is `null` or `undefined`, ROUNDING_MODE will be used. + */ + toDigits(sd?: number, rm?: RoundingMode): BigNumber; + + /** + * Returns a string representing the value of this BigNumber in exponential notation rounded using rounding mode `rm` to `dp` decimal places, + * i.e with one digit before the decimal point and `dp` digits after it. + * + * If the value of this BigNumber in exponential notation has fewer than `dp` fraction digits, the return value will be appended with zeros accordingly. + * + * If `dp` is omitted, or is `null` or `undefined`, the number of digits after the decimal point defaults to the minimum number of digits necessary to represent the value exactly. + * + * If `rm` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + */ + toExponential(dp?: number, rm?: RoundingMode): string; + + /** + * Returns a string representing the value of this BigNumber in normal (fixed-point) notation rounded to `dp` decimal places using rounding mode `rm`. + * + * If the value of this BigNumber in normal notation has fewer than `dp` fraction digits, the return value will be appended with zeros accordingly. + * + * Unlike `Number.prototype.toFixed`, which returns exponential notation if a number is greater or equal to `10e21`, this method will always return normal notation. + * + * If `dp` is omitted or is `null` or `undefined`, the return value will be unrounded and in normal notation. + * This is also unlike `Number.prototype.toFixed`, which returns the value to zero decimal places. + * It is useful when fixed-point notation is required and the current `EXPONENTIAL_AT` setting causes `toString` to return exponential notation. + * + * If `rm` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + */ + toFixed(dp?: number, rm?: RoundingMode): string; + + /** + * Returns a string representing the value of this BigNumber in normal (fixed-point) notation rounded to `dp` decimal places using rounding mode `rm`, + * and formatted according to the properties of the `FORMAT` object. + * + * If `dp` is omitted or is `null` or `undefined`, then the return value is not rounded to a fixed number of decimal places. + * + * If `rm` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + */ + toFormat(dp?: number, rm?: RoundingMode): string; + + /** + * Returns a string array representing the value of this BigNumber as a simple fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to `max`. + * + * If a maximum denominator, `max`, is not specified, or is `null` or `undefined`, the denominator will be the lowest value necessary to represent the number exactly. + */ + toFraction(max?: NumberLike): [string, string]; + + /** + * As `valueOf`. + */ + toJSON(): string; + + /** + * Returns the value of this BigNumber as a JavaScript number primitive. + * + * Type coercion with, for example, the unary plus operator will also work, except that a BigNumber with the value minus zero will be converted to positive zero. + */ + toNumber(): number; + + /** + * Returns a BigNumber whose value is the value of this BigNumber raised to the power `n`, and optionally modulo a modulus `m`. + * + * If `n` is negative the result is rounded according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` configuration. + */ + toPower(n: number, m?: NumberLike): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber raised to the power `n`, and optionally modulo a modulus `m`. + * + * If `n` is negative the result is rounded according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` configuration. + */ + pow(n: number, m?: NumberLike): BigNumber; + + /** + * Returns a string representing the value of this BigNumber rounded to `sd` significant digits using rounding mode `rm`. + * + * If `sd` is less than the number of digits necessary to represent the integer part of the value in normal (fixed-point) notation, then exponential notation is used. + * + * If `sd` is omitted, or is `null` or `undefined`, then the return value is the same as `n.toString()`. + * + * If `rm` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + */ + toPrecision(sd?: number, rm?: RoundingMode): string; + + /** + * Returns a string representing the value of this BigNumber in the specified base, or base `10` if `base` is omitted or is `null` or `undefined`. + */ + toString(base?: number): string; + + /** + * Returns a BigNumber whose value is the value of this BigNumber truncated to a whole number. + */ + truncated(): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber truncated to a whole number. + */ + trunc(): BigNumber; + + /** + * As `toString`, but does not accept a base argument and includes the minus sign for negative zero. + */ + valueOf(): string; + + /** + * coefficient + * @description Array of base 1e14 numbers + */ + c: number[] | null; + + /** + * exponent + * @description Integer, -1000000000 to 1000000000 inclusive + */ + e: number | null; + + /** + * sign + */ + s: -1 | 1 | null; + + /** + * type identifier + */ + isBigNumber: true; + } +} \ No newline at end of file diff --git a/bignumber.js/tsconfig.json b/bignumber.js/tsconfig.json new file mode 100644 index 0000000000..485dace353 --- /dev/null +++ b/bignumber.js/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bignumber.js-tests.ts" + ] +} \ No newline at end of file diff --git a/bignumber.js/tslint.json b/bignumber.js/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/bignumber.js/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/bingmaps/bingmaps-tests.ts b/bingmaps/bingmaps-tests.ts index 239e33094a..e83ff89aba 100644 --- a/bingmaps/bingmaps-tests.ts +++ b/bingmaps/bingmaps-tests.ts @@ -1,10 +1,3 @@ -/// -/// -/// -/// -/// -/// - namespace BingMapsTests { // An interactive set of Bing Maps AJAX control usages can be found at http://www.bingmapsportal.com/isdk/ajaxv7 diff --git a/bit-array/bit-array-tests.ts b/bit-array/bit-array-tests.ts index 7c1ff57b1b..7d50de143c 100644 --- a/bit-array/bit-array-tests.ts +++ b/bit-array/bit-array-tests.ts @@ -1,5 +1,3 @@ -/// - import BitArray = require("bit-array"); const a = new BitArray(32); diff --git a/bittorrent-protocol/index.d.ts b/bittorrent-protocol/index.d.ts index 688527e71f..be1a60b179 100644 --- a/bittorrent-protocol/index.d.ts +++ b/bittorrent-protocol/index.d.ts @@ -16,6 +16,7 @@ declare namespace BittorrentProtocol { } export interface Extension { + //tslint:disable-next-line:no-misused-new - could use class instead of interface but class is not extendible constructor(wire: Wire): this; onHandshake?: () => void; onExtendedHandshake?: () => void; @@ -24,6 +25,7 @@ declare namespace BittorrentProtocol { } export interface Request { + //tslint:disable-next-line:no-misused-new - could use class instead of interface but class is not extendible constructor(piece: number, offset: number, length: number, callback: () => void): this; piece: number; offset: number; diff --git a/bittorrent-protocol/tsconfig.json b/bittorrent-protocol/tsconfig.json index 9258205ba7..1bc778df1b 100644 --- a/bittorrent-protocol/tsconfig.json +++ b/bittorrent-protocol/tsconfig.json @@ -19,4 +19,4 @@ "index.d.ts", "bittorrent-protocol-tests.ts" ] -} \ No newline at end of file +} diff --git a/blob-stream/blob-stream-tests.ts b/blob-stream/blob-stream-tests.ts index b9174859f9..40f9888788 100644 --- a/blob-stream/blob-stream-tests.ts +++ b/blob-stream/blob-stream-tests.ts @@ -1,6 +1,3 @@ - -/// - var bl = require('blob-stream'); var blob = bl.toBlob(); diff --git a/blue-tape/blue-tape-tests.ts b/blue-tape/blue-tape-tests.ts index 92b2641115..c34bc6e32c 100644 --- a/blue-tape/blue-tape-tests.ts +++ b/blue-tape/blue-tape-tests.ts @@ -1,4 +1,3 @@ -/// /// import tape = require('blue-tape'); diff --git a/bluebird-global/index.d.ts b/bluebird-global/index.d.ts index caf873510d..e4c4920501 100644 --- a/bluebird-global/index.d.ts +++ b/bluebird-global/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for bluebird 3.0 +// Type definitions for bluebird 3.5 // Project: https://github.com/petkaantonov/bluebird // Definitions by: d-ph // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -76,6 +76,7 @@ declare global { spread: typeof Bluebird.prototype.spread; suppressUnhandledRejections: typeof Bluebird.prototype.suppressUnhandledRejections; tap: typeof Bluebird.prototype.tap; + tapCatch: typeof Bluebird.prototype.tapCatch; // then: typeof Bluebird.prototype.then; thenReturn: typeof Bluebird.prototype.thenReturn; thenThrow: typeof Bluebird.prototype.thenThrow; diff --git a/bluebird-retry/bluebird-retry-tests.ts b/bluebird-retry/bluebird-retry-tests.ts index b63b360160..eb3260a007 100644 --- a/bluebird-retry/bluebird-retry-tests.ts +++ b/bluebird-retry/bluebird-retry-tests.ts @@ -1,5 +1,3 @@ - -/// import Promise = require('bluebird'); import retry = require('bluebird-retry'); diff --git a/bluebird-retry/index.d.ts b/bluebird-retry/index.d.ts index 22c7b1c95e..63adc1476d 100644 --- a/bluebird-retry/index.d.ts +++ b/bluebird-retry/index.d.ts @@ -17,6 +17,9 @@ declare namespace retry { timeout?: number; max_tries?: number; predicate?: any; + throw_original?: boolean; + context?: any; + args?: any; } } diff --git a/bluebird/bluebird-tests.ts b/bluebird/bluebird-tests.ts index ea1ea69882..c08a7bdc6b 100644 --- a/bluebird/bluebird-tests.ts +++ b/bluebird/bluebird-tests.ts @@ -151,6 +151,10 @@ var BlueBird: typeof Promise; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +var version: string = Promise.version; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + var nodeCallbackFunc = (callback: (err: any, result: string) => void) => {} var nodeCallbackFuncErrorOnly = (callback: (err: any) => void) => {} @@ -336,14 +340,12 @@ fooOrBarProm = fooProm.caught(Promise.CancellationError, (reason: any) => { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -{ - class CustomError extends Error { - public customField: number; - } - fooProm = fooProm.catch(CustomError, reason => { - let a: number = reason.customField - }) +class CustomError extends Error { + public customField: number; } +fooProm = fooProm.catch(CustomError, reason => { + let a: number = reason.customField +}) { class CustomErrorWithConstructor extends Error { @@ -433,6 +435,24 @@ fooProm = fooProm.tap(() => { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +fooProm = fooProm.tapCatch((err) => { + return "foo"; +}); + +fooProm = fooProm.tapCatch(err => { + return Promise.resolve("foo"); +}); + +fooProm.tapCatch(CustomError, (err: CustomError) => { + return err.customField; +}); + +fooProm.tapCatch((e: any) => e instanceof CustomError, (err: CustomError) => { + return err.customField; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + fooProm = fooProm.delay(num); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/bluebird/index.d.ts b/bluebird/index.d.ts index 2faa74e285..ecacedfd0d 100644 --- a/bluebird/index.d.ts +++ b/bluebird/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for bluebird 3.0.0 +// Type definitions for bluebird 3.5.0 // Project: https://github.com/petkaantonov/bluebird // Definitions by: Leonard Hecker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -68,19 +68,19 @@ declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection boolean, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; caught(predicate: (error: any) => boolean, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; - + catch(predicate: (error: any) => boolean, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; caught(predicate: (error: any) => boolean, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; - + catch(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; caught(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; catch(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => U | Bluebird.Thenable): Bluebird; caught(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => U | Bluebird.Thenable): Bluebird; - + catch(predicate: Object, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; caught(predicate: Object, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; - + catch(predicate: Object, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; caught(predicate: Object, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; @@ -114,6 +114,14 @@ declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection(onFulFill: (value: R) => Bluebird.Thenable): Bluebird; tap(onFulfill: (value: R) => U): Bluebird; + /** + * Like `.catch()` but rethrows the error + */ + tapCatch(onReject: (error?: any) => U | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + tapCatch(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => U | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + tapCatch(predicate: (error?: any) => boolean, onReject: (error?: any) => U | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + + /** * Same as calling `Promise.delay(ms, this)`. */ @@ -321,7 +329,7 @@ declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection implements Bluebird.Thenable, Bluebird.Inspection { + console.log(req.body); + res.json(req.body); +}); + +app.listen(8080); diff --git a/body-parser/index.d.ts b/body-parser/index.d.ts index 4627c2c5b3..c0ce775bb0 100644 --- a/body-parser/index.d.ts +++ b/body-parser/index.d.ts @@ -1,202 +1,48 @@ -// Type definitions for body-parser -// Project: http://expressjs.com -// Definitions by: Santi Albo , VILIC VANE , Jonathan Häberle , Gevik Babakhani +// Type definitions for body-parser 1.16 +// Project: https://github.com/expressjs/body-parser +// Definitions by: Santi Albo , Vilic Vane , Jonathan Häberle , Gevik Babakhani , Tomasz Łaziuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// +import { Request, RequestHandler, Response } from 'express'; +// for docs go to https://github.com/expressjs/body-parser/tree/1.16.0#body-parser -import * as express from "express"; - -/** - * bodyParser: use individual json/urlencoded middlewares - * @deprecated - */ - -declare function bodyParser(options?: { - /** - * if deflated bodies will be inflated. (default: true) - */ - inflate?: boolean; - /** - * maximum request body size. (default: '100kb') - */ - limit?: any; - /** - * function to verify body content, the parsing can be aborted by throwing an error. - */ - verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; - /** - * only parse objects and arrays. (default: true) - */ - strict?: boolean; - /** - * passed to JSON.parse(). - */ - reviver?: (key: string, value: any) => any; - /** - * parse extended syntax with the qs module. (default: true) - */ - extended?: boolean; -}): express.RequestHandler; +// @deprecated +declare function bodyParser(options?: bodyParser.OptionsJson & bodyParser.OptionsText & bodyParser.OptionsUrlencoded): RequestHandler; declare namespace bodyParser { - /** - * Interface for defining the options for the json() middleware - * - * @export - * @interface JsonOptions - */ - export interface JsonOptions { - /** - * if deflated bodies will be inflated. (default: true) - */ + export interface Options { inflate?: boolean; - /** - * maximum request body size. (default: '100kb') - */ - limit?: any; - /** - * request content-type to parse, passed directly to the type-is library. (default: 'json') - */ - type?: any; - /** - * function to verify body content, the parsing can be aborted by throwing an error. - */ - verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; - /** - * only parse objects and arrays. (default: true) - */ + limit?: number | string; + type?: string | ((req: Request) => any); + verify?: (req: Request, res: Response, buf: Buffer, encoding: string) => void; + } + + export interface OptionsJson extends Options { + reviever?: (key: string, value: any) => any; strict?: boolean; - /** - * passed to JSON.parse(). - */ - reviver?: (key: string, value: any) => any; } - /** - * Interface for defining the options the raw() middleware - * - * @export - * @interface RawOptions - */ - export interface RawOptions { - /** - * if deflated bodies will be inflated. (default: true) - */ - inflate?: boolean; - /** - * maximum request body size. (default: '100kb') - */ - limit?: any; - /** - * request content-type to parse, passed directly to the type-is library. (default: 'application/octet-stream') - */ - type?: any; - /** - * function to verify body content, the parsing can be aborted by throwing an error. - */ - verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; - } - - /** - * Interface for defining the options for the text() middleware - * - * @export - * @interface TextOptions - */ - export interface TextOptions { - /** - * if deflated bodies will be inflated. (default: true) - */ - inflate?: boolean; - /** - * maximum request body size. (default: '100kb') - */ - limit?: any; - /** - * request content-type to parse, passed directly to the type-is library. (default: 'text/plain') - */ - type?: any; - /** - * function to verify body content, the parsing can be aborted by throwing an error. - */ - verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; - /** - * the default charset to parse as, if not specified in content-type. (default: 'utf-8') - */ + export interface OptionsText extends Options { defaultCharset?: string; } - /** - * Interface for defining the options for the urlencoded() middleware - * - * @export - * @interface UrlEncodedOptions - */ - export interface UrlEncodedOptions { - /** - * if deflated bodies will be inflated. (default: true) - */ - inflate?: boolean; - /** - * maximum request body size. (default: '100kb') - */ - limit?: any; - /** - * request content-type to parse, passed directly to the type-is library. (default: 'urlencoded') - */ - type?: any; - /** - * function to verify body content, the parsing can be aborted by throwing an error. - */ - verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; - /** - * parse extended syntax with the qs module. - */ - extended: boolean; + export interface OptionsUrlencoded extends Options { + extended?: boolean; + parameterLimit?: number; } - /** - * Returns middleware that only parses json. This parser accepts any Unicode encoding - * of the body and supports automatic inflation of gzip and deflate encodings. - * - * @export - * @param {JsonOptions} [options] - * @returns {express.RequestHandler} - */ - export function json(options?: JsonOptions): express.RequestHandler; + export function json(options?: OptionsJson): RequestHandler; - /** - * Returns middleware that parses all bodies as a Buffer. This parser supports automatic - * inflation of gzip and deflate encodings. - * - * @export - * @param {RawOptions} [options] - * @returns {express.RequestHandler} - */ - export function raw(options?: RawOptions): express.RequestHandler; + export function raw(options?: Options): RequestHandler; - /** - * Returns middleware that parses all bodies as a string. This parser supports - * automatic inflation of gzip and deflate encodings. - * - * @export - * @param {TextOptions} [options] - * @returns {express.RequestHandler} - */ - export function text(options?: TextOptions): express.RequestHandler; + export function text(options?: OptionsText): RequestHandler; + + export function urlencoded(options?: OptionsUrlencoded): RequestHandler; - /** - * Returns middleware that only parses urlencoded bodies. This parser accepts only - * UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings. - * - * @export - * @param {UrlEncodedOptions} [options] - * @returns {express.RequestHandler} - */ - export function urlencoded(options?: UrlEncodedOptions): express.RequestHandler; } export = bodyParser; diff --git a/body-parser/tsconfig.json b/body-parser/tsconfig.json index 27e01ecd7b..e798cd97d3 100644 --- a/body-parser/tsconfig.json +++ b/body-parser/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, @@ -16,6 +17,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "index.d.ts" + "index.d.ts", + "body-parser-tests.ts" ] -} \ No newline at end of file +} diff --git a/body-parser/tslint.json b/body-parser/tslint.json new file mode 100644 index 0000000000..9311f348d9 --- /dev/null +++ b/body-parser/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "max-line-length": false + } +} diff --git a/bookshelf/bookshelf-tests.ts b/bookshelf/bookshelf-tests.ts index 5b743bef71..98fd0f4599 100644 --- a/bookshelf/bookshelf-tests.ts +++ b/bookshelf/bookshelf-tests.ts @@ -1330,3 +1330,50 @@ new User({name: 'John'}).fetchAll({require: true}) /* events.trigger(), see http://bookshelfjs.org/#Events-instance-trigger */ /* events.triggerThen(), see http://bookshelfjs.org/#Events-instance-triggerThen */ + + +/* model - foreignKey and foreignKeyTarget, see http://bookshelfjs.org/#Model-instance-hasOne */ + +{ + class Capital extends bookshelf.Model { + get tableName() { return 'capitals'; } + } + + class City extends bookshelf.Model { + get tableName() { return 'cities'; } + + country(): Country { + return this.belongsTo(Country, 'key1', 'key2'); + } + } + + class Language extends bookshelf.Model { + get tableName() { return 'languages'; } + + countries(): Bookshelf.Collection { + return this.belongsToMany(Country, 'languages_countries', 'lang_id', 'country_id'); + } + } + + class Country extends bookshelf.Model { + get tableName() { return 'countries'; } + capital(): Capital { + return this.hasOne(Capital, 'id', 'capital_id'); + } + + cities(): Bookshelf.Collection { + return this.hasMany(City, 'key2', 'key1'); + } + } + + // select * from `health_records` where `patient_id` = 1; + const capital = new Country({id: 1}).related('capital'); + capital.fetch().then(model => { + // ... + }); + + // alternatively, if you don't need the relation loaded on the patient's relations hash: + new Country({id: 1}).capital().fetch().then(model => { + // ... + }); +} \ No newline at end of file diff --git a/bookshelf/index.d.ts b/bookshelf/index.d.ts index 56472a3213..4aa6fd38b5 100644 --- a/bookshelf/index.d.ts +++ b/bookshelf/index.d.ts @@ -92,14 +92,14 @@ declare namespace Bookshelf { static where(properties: { [key: string]: any }): T; static where(key: string, operatorOrValue: string | number | boolean, valueIfOperator?: string | number | boolean): T; - belongsTo>(target: { new (...args: any[]): R }, foreignKey?: string): R; + belongsTo>(target: { new (...args: any[]): R }, foreignKey?: string, foreignKeyTarget?: string): R; belongsToMany>(target: { new (...args: any[]): R }, table?: string, foreignKey?: string, otherKey?: string): Collection; count(column?: string, options?: SyncOptions): BlueBird; destroy(options?: DestroyOptions): BlueBird; fetch(options?: FetchOptions): BlueBird; fetchAll(options?: FetchAllOptions): BlueBird>; - hasMany>(target: { new (...args: any[]): R }, foreignKey?: string): Collection; - hasOne>(target: { new (...args: any[]): R }, foreignKey?: string): R; + hasMany>(target: { new (...args: any[]): R }, foreignKey?: string, foreignKeyTarget?: string): Collection; + hasOne>(target: { new (...args: any[]): R }, foreignKey?: string, foreignKeyTarget?: string): R; load(relations: string | string[], options?: LoadOptions): BlueBird; morphMany>(target: { new (...args: any[]): R }, name?: string, columnNames?: string[], morphValue?: string): Collection; morphOne>(target: { new (...args: any[]): R }, name?: string, columnNames?: string[], morphValue?: string): R; diff --git a/bootbox/bootbox-tests.ts b/bootbox/bootbox-tests.ts index 92a079f456..b5f32931ae 100644 --- a/bootbox/bootbox-tests.ts +++ b/bootbox/bootbox-tests.ts @@ -6,7 +6,7 @@ bootbox.alert("Are we ok with callback?", function () { console.log("Callback called!"); }); bootbox.alert({ - size: "medium", + size: "small", message: "Are we ok with callback and custom button?", callback: function () { console.log("Callback called!"); diff --git a/bootbox/index.d.ts b/bootbox/index.d.ts index 40494d5ca5..d5ceb5ef62 100644 --- a/bootbox/index.d.ts +++ b/bootbox/index.d.ts @@ -15,7 +15,8 @@ interface BootboxBaseOptions { closeButton?: boolean; animate?: boolean; className?: string; - size?: string; + /** All other values result in medium */ + size?: "small" | "large"; buttons?: BootboxButtonMap; // complex object where each key is of type BootboxButton } @@ -40,7 +41,7 @@ interface BootboxConfirmOptions extends BootboxDialogOptions { interface BootboxPromptOptions extends BootboxBaseOptions { title: string; value?: string; - inputType?: string; + inputType?: "text" | "textarea" | "email" | "select" | "checkbox" | "date" | "time" | "number" | "password"; callback: (result: string) => any; buttons?: BootboxConfirmPromptButtonMap; } diff --git a/bootpag/bootpag-tests.ts b/bootpag/bootpag-tests.ts index 6a5503f9f8..a0a2a78cc3 100644 --- a/bootpag/bootpag-tests.ts +++ b/bootpag/bootpag-tests.ts @@ -1,5 +1,3 @@ -/// - var pagerSelector = ".bootpager"; var $pager = $(pagerSelector); diff --git a/bootstrap-datepicker/bootstrap-datepicker-tests.ts b/bootstrap-datepicker/bootstrap-datepicker-tests.ts index cedc28c93c..372967ec21 100644 --- a/bootstrap-datepicker/bootstrap-datepicker-tests.ts +++ b/bootstrap-datepicker/bootstrap-datepicker-tests.ts @@ -1,4 +1,3 @@ -/// function tests_simple() { $('#datepicker').datepicker(); $('#datepicker').datepicker({ diff --git a/bootstrap-maxlength/bootstrap-maxlength-tests.ts b/bootstrap-maxlength/bootstrap-maxlength-tests.ts index 32255bc66b..92c3f1b57e 100644 --- a/bootstrap-maxlength/bootstrap-maxlength-tests.ts +++ b/bootstrap-maxlength/bootstrap-maxlength-tests.ts @@ -1,5 +1,3 @@ -/// - // Examples from the projects github page $('input[maxlength]').maxlength(); diff --git a/bootstrap-notify/bootstrap-notify-tests.ts b/bootstrap-notify/bootstrap-notify-tests.ts index 5ae4f2ffc1..2977d39abf 100644 --- a/bootstrap-notify/bootstrap-notify-tests.ts +++ b/bootstrap-notify/bootstrap-notify-tests.ts @@ -1,6 +1,3 @@ - -/// - //Test for bootstrap-notify v3.1.3 //Copied example directly from Bootstrap-notify site diff --git a/bootstrap-select/bootstrap-select-tests.ts b/bootstrap-select/bootstrap-select-tests.ts index e2e8c88560..55900b3ab7 100644 --- a/bootstrap-select/bootstrap-select-tests.ts +++ b/bootstrap-select/bootstrap-select-tests.ts @@ -1,5 +1,3 @@ -/// - $(".selectpicker").selectpicker({ actionsBox: true, container: "body", diff --git a/bootstrap-slider/bootstrap-slider-tests.ts b/bootstrap-slider/bootstrap-slider-tests.ts index 98701cedc3..df143d4c72 100644 --- a/bootstrap-slider/bootstrap-slider-tests.ts +++ b/bootstrap-slider/bootstrap-slider-tests.ts @@ -1,6 +1,3 @@ -/// - - $(function() { // examples from http://seiyria.github.io/bootstrap-slider/ diff --git a/bootstrap-switch/bootstrap-switch-tests.ts b/bootstrap-switch/bootstrap-switch-tests.ts index 539399a78e..65fafff2e9 100644 --- a/bootstrap-switch/bootstrap-switch-tests.ts +++ b/bootstrap-switch/bootstrap-switch-tests.ts @@ -1,9 +1,6 @@ -/// - - function test_cases() { $('#switch').bootstrapSwitch(); - + $('#switch').bootstrapSwitch({ state: false }); @@ -15,7 +12,7 @@ function test_cases() { //var mySwitch = $('#switch').get(0); //mySwitch.toggleAnimate(); - + $('#switch').bootstrapSwitch('state', true, true); $('#switch').bootstrapSwitch('state') === true; diff --git a/bootstrap-touchspin/bootstrap-touchspin-tests.ts b/bootstrap-touchspin/bootstrap-touchspin-tests.ts index c8a6a713f9..7d1ea73437 100644 --- a/bootstrap-touchspin/bootstrap-touchspin-tests.ts +++ b/bootstrap-touchspin/bootstrap-touchspin-tests.ts @@ -1,6 +1,3 @@ -/// - - $(function () { // Example 1 from http://www.virtuosoft.eu/code/bootstrap-touchspin/ $("input[name='demo1']").TouchSpin({ @@ -26,7 +23,7 @@ $(function () { $("input[name='demo_vertical']").TouchSpin({ verticalbuttons: true }); - + // Example 4 from http://www.virtuosoft.eu/code/bootstrap-touchspin/ $("input[name='demo_vertical2']").TouchSpin({ verticalbuttons: true, diff --git a/bootstrap-validator/bootstrap-validator-tests.ts b/bootstrap-validator/bootstrap-validator-tests.ts index 07d4753ed1..e43a094184 100644 --- a/bootstrap-validator/bootstrap-validator-tests.ts +++ b/bootstrap-validator/bootstrap-validator-tests.ts @@ -1,5 +1,3 @@ -/// - $('#myForm').validator(); $('#myForm').validator('update'); $('#myForm').validator('validate'); diff --git a/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-tests.ts b/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-tests.ts index 4306bf97c7..575f72b7cb 100644 --- a/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-tests.ts +++ b/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-tests.ts @@ -1,26 +1,175 @@ -/// +import * as moment from "moment"; -import * as moment from 'moment'; +const dp = $("#picker").datetimepicker().data("DateTimePicker"); function test_cases() { - $('#datetimepicker').datetimepicker(); - $('#datetimepicker').datetimepicker({ - minDate: '2012-12-31' + $("#datetimepicker").datetimepicker(); + $("#datetimepicker").datetimepicker({ + minDate: "2012-12-31" }); - $('#datetimepicker').data("DateTimePicker").maxDate('2012-12-31'); + $("#datetimepicker").data("DateTimePicker").maxDate("2012-12-31"); - var startDate = moment(new Date(2012, 1, 20)); - var endDate = moment(new Date(2012, 1, 25)); - $('#datetimepicker2') + let startDate = moment(new Date(2012, 1, 20)); + const endDate = moment(new Date(2012, 1, 25)); + + $("#datetimepicker2") .datetimepicker() - .on("dp.change", function (ev) { + .on("dp.change", ev => { if (ev.date.valueOf() > endDate.valueOf()) { - $('#alert').show().find('strong').text('The start date must be before the end date.'); + $("#alert").show().find("strong").text("The start date must be before the end date."); } else { - $('#alert').hide(); + $("#alert").hide(); startDate = ev.date; - $('#date-start-display').text($('#date-start').data('date')); + $("#date-start-display").text($("#date-start").data("date")); } + }) + .on("dp.error", ev => { + console.log(`Error: ${ev.date.format("YYYY-MM-DD")}`); + }) + .on("dp.update", ev => { + console.log(`Change: ${ev.change}, ${ev.viewDate.format("YYYY-MM-DD")}`); }); -} \ No newline at end of file +} + +function test_date() { + let momentObj = moment("20111031", "YYYYMMDD"); + + dp.date(null); + dp.date("1969-07-21"); + dp.date(new Date()); + dp.date(momentObj); + + momentObj = dp.date(); +} + +function test_format() { + let boolFormat = false; + let strFormat = "YYYY-MM-DD"; + let momentFormat = moment.ISO_8601; + + $("#picker").datetimepicker({ + format: boolFormat + }); + + $("#picker").datetimepicker({ + format: strFormat + }); + + $("#picker").datetimepicker({ + format: momentFormat + }); + + dp.format(boolFormat); + boolFormat = dp.format() as boolean; + + dp.format(strFormat); + strFormat = dp.format() as string; + + dp.format(momentFormat); + momentFormat = dp.format() as moment.MomentBuiltinFormat; +} + +function test_extraFormats() { + let boolFormat = false; + let strFormats = ["YYYYMMDD", "YYYY/MM/DD"]; + let mixFormats = ["YYYYMMDD", moment.ISO_8601]; + + $("#picker").datetimepicker({ + extraFormats: boolFormat + }); + + $("#picker").datetimepicker({ + extraFormats: strFormats + }); + + $("#picker").datetimepicker({ + extraFormats: mixFormats + }); + + dp.extraFormats(boolFormat); + boolFormat = dp.extraFormats() as boolean; + + dp.extraFormats(strFormats); + strFormats = dp.extraFormats() as string[]; + + dp.extraFormats(mixFormats); + mixFormats = dp.extraFormats() as Array<(string | moment.MomentBuiltinFormat)>; +} + +function test_timeZone() { + let nullTz = null; + let strFormats = "Africa/Abidjan"; + + $("#picker").datetimepicker({ + timeZone: nullTz + }); + + $("#picker").datetimepicker({ + timeZone: strFormats + }); + + dp.timeZone(nullTz); + nullTz = dp.timeZone() as null; + + dp.timeZone(strFormats); + strFormats = dp.timeZone() as string; +} + + +function test_widgetParent() { + let nullW: null = null; + let str: string = "myId"; + let jquery = $("#element"); + + $("#picker").datetimepicker({ + widgetParent: nullW + }); + + $("#picker").datetimepicker({ + widgetParent: str + }); + + $("#picker").datetimepicker({ + widgetParent: jquery + }); + + dp.widgetParent(nullW); + nullW = dp.widgetParent() as null; + + dp.widgetParent(str); + str = dp.widgetParent() as string; + + dp.widgetParent(jquery); + jquery = dp.widgetParent() as JQuery; +} + +function inputParser(inputDate: string | Date | moment.Moment) { + const relativeDatePattern = /[0-9]+\s+(days ago)/; + + if (moment.isMoment(inputDate) || inputDate instanceof Date) { + return moment(inputDate); + } else { + const relativeDate = inputDate.match(relativeDatePattern); + if (relativeDate !== null) { + const subDays = +relativeDate[0].replace("days ago", "").trim(); + return moment().subtract(subDays, "day"); + } else { + return moment(); + } + } +}; + +function test_parseInputDate() { + let undef: undefined; + let parser: BootstrapV3DatetimePicker.InputParser; + + $("#picker").datetimepicker(); + + $("#picker").datetimepicker({ + parseInputDate: inputParser + }); + + undef = dp.parseInputDate() as undefined; + parser = dp.parseInputDate() as BootstrapV3DatetimePicker.InputParser; +} diff --git a/bootstrap.v3.datetimepicker/index.d.ts b/bootstrap.v3.datetimepicker/index.d.ts index 565ad9a356..d8ec008dca 100644 --- a/bootstrap.v3.datetimepicker/index.d.ts +++ b/bootstrap.v3.datetimepicker/index.d.ts @@ -1,21 +1,23 @@ -// Type definitions for Bootstrap 3 Datepicker v4.17.37 +// Type definitions for Bootstrap 3 Datepicker 4.17 // Project: http://eonasdan.github.io/bootstrap-datetimepicker // Definitions by: Katona Péter // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // based on the previous version created by Jesica N. Fera /** - * bootstrap-datetimepicker.js 4.17.37 Copyright (c) 2015 Jonathan Peterson + * bootstrap-datetimepicker.js 4.17.45 Copyright (c) 2015 Jonathan Peterson * Available via the MIT license. * see: http://eonasdan.github.io/bootstrap-datetimepicker or https://github.com/Eonasdan/bootstrap-datetimepicker for details. */ /// -import * as moment from 'moment'; +import * as moment from "moment"; export as namespace BootstrapV3DatetimePicker; +type InputParser = (input: string | Date | moment.Moment) => moment.Moment; + export interface Datetimepicker { /**Clears the datepicker by setting the value to null */ clear(): void; @@ -30,7 +32,7 @@ export interface Datetimepicker { * Emits: * - dp.change - In case newDate is different from current moment */ - date(date: moment.Moment | Date | string): void; + date(date: moment.Moment | Date | string | null): void; /**Destroys the widget and removes all attached event listeners */ destroy(): void; /**Disables the input element, the component is attached to, by adding a disabled="true" attribute to it. If the widget was visible before that call it is hidden. @@ -149,21 +151,23 @@ export interface Datetimepicker { * Like en/disabledDates, the en/disabledHours options are mutually exclusive and will reset one of the options back to false. */ enabledHours(value: boolean | Array): void; /**Returns a boolean or array with the options.extraFormats option configuration */ - extraFormats(): boolean | Array; + extraFormats(): boolean | Array; /**Takes an array of valid input moment format options, or boolean:false */ - extraFormats(formats: boolean | Array): void; + extraFormats(formats: boolean | Array): void; /**Returns the options.focusOnShow option. */ focusOnShow(): boolean; /**If false, the textbox will not be given focus when the picker is shown */ focusOnShow(value: boolean): void; /**Returns the component's options.format string */ - format(): boolean | string; + format(): boolean | string | moment.MomentBuiltinFormat; /**Takes a moment.js format string and sets the components options.format. * This is used for displaying and also for parsing input strings either from the input element the component is attached to or the date() function. * The parameter can also be a boolean:false in which case the format is set to the locale's L LT. * Note: this is also used to determine if the TimePicker sub component will display the hours in 12 or 24 format. (if "a" or "h" exists in the passed string then a 12 hour mode is set) + * Throws: + * - TypeError - if format is boolean:true */ - format(format: boolean | string): void; + format(format: boolean | string | moment.MomentBuiltinFormat): void; /**Returns options.icons */ icons(): Icons; /**Takes an Object of strings. @@ -224,11 +228,11 @@ export interface Datetimepicker { */ minDate(date: moment.Moment | Date | string | boolean): void; /**Returns the options.parseInputDate option */ - parseInputDate(): Function; + parseInputDate(): InputParser | undefined; /**Allows custom input formatting For example: the user can enter "yesterday"" or "30 days ago". * {@link http://eonasdan.github.io/bootstrap-datetimepicker/Functions/#parseinputdate} */ - parseInputDate(value: (input: string) => moment.Moment): void; + parseInputDate(value: InputParser): void; /**Returns the options.showClear option. */ showClear(): boolean; /**Set if the clear date button will appear on the widget */ @@ -249,12 +253,19 @@ export interface Datetimepicker { stepping(): number; /**This will be the amount the up/down arrows move the minute value with a time picker. */ stepping(step: number): void; + /** Returns a string of options.timeZone */ + timeZone(): string | null; + /** Takes a null or a string of a valid timezone. + * Throws: + * - TypeError - if tooltips parameter is not a string or null + */ + timeZone(timeZone: string | null): void; /**Returns the options.toolbarplacement option. */ toolbarPlacement(): string; /**Changes the placement of the toolbar where the today, clear, component switch icon are located. * See valid values at DatetimepickerOptions.toolbarplacement * Throws: - * - TypeError if the parameter is not a valid value + * - TypeError - if the parameter is not a valid value */ toolbarPlacement(value: string): void; /**Returns the options.tooltips option */ @@ -267,10 +278,12 @@ export interface Datetimepicker { /**Returns the options.useCurrent option configuration */ useCurrent(): boolean | string; /**Takes a boolean or string. - * If a boolean true is passed and the components model moment is not set (either through setDate or through a valid value on the input element the component is attached to) then the first time the user opens the datetimepicker widget the value is initialized to the current moment of the action. + * If a boolean true is passed and the components model moment is not set (either through setDate or through a valid value on the input element the component is attached to) + * then the first time the user opens the datetimepicker widget the value is initialized to the current moment of the action. * If a false boolean is passed then no initialization happens on the input element. * You can select the granularity on the initialized moment by passing one of the following strings ("year", "month", "day", "hour", "minute") in the variable. - * If for example you pass "day" to the useCurrent function and the input field is empty the first time the user opens the datetimepicker widget the input text will be initialized to the current datetime with day granularity (ie if currentTime = 2014-08-10 13:32:33 the input value will be initialized to 2014-08-10 00:00:00) + * If for example you pass "day" to the useCurrent function and the input field is empty the first time the user opens the datetimepicker widget the input text will be + * initialized to the current datetime with day granularity (ie if currentTime = 2014-08-10 13:32:33 the input value will be initialized to 2014-08-10 00:00:00) * Note: If the options.defaultDate is set or the input element the component is attached to has already a value that takes precedence and the functionality of useCurrent is not triggered! */ useCurrent(value: boolean | string): void; @@ -289,6 +302,10 @@ export interface Datetimepicker { * - TypeError - if the parameter is not a string or not a valid value */ viewMode(value: string): void; + /**Returns a $(element) variable with the currently set options.widgetParent option. */ + widgetParent(): string | JQuery | null + /**Takes a string or $(element) value. */ + widgetParent(widgetParent: string | JQuery | null): void; /**Returns the options.widgetPositioning object */ widgetPositioning(): WidgetPositioningOptions; /**WidgetPositioning defines where the dropdown with the widget will appear relative to the input element the component is attached to. @@ -364,7 +381,7 @@ export interface DatetimepickerOptions { /**Allows for several input formats to be valid. See: https://github.com/Eonasdan/bootstrap-datetimepicker/pull/666 * @default: false */ - extraFormats?: boolean | Array; + extraFormats?: boolean | Array; /**If false, the textbox will not be given focus when the picker is shown * @default: true */ @@ -372,7 +389,7 @@ export interface DatetimepickerOptions { /**See momentjs' docs for valid formats. Format also dictates what components are shown, e.g. MM/dd/YYYY will not display the time picker. * @default: false */ - format?: boolean | string; + format?: boolean | string | moment.MomentBuiltinFormat; /**Change the default icons for the pickers functions. */ icons?: Icons; /**Allow date picker show event to fire even when the associated input element has the readonly="readonly"property. @@ -416,7 +433,7 @@ export interface DatetimepickerOptions { /**Allows custom input formatting For example: the user can enter "yesterday"" or "30 days ago". * {@link http://eonasdan.github.io/bootstrap-datetimepicker/Functions/#parseinputdate} */ - parseInputDate?: (input: string) => moment.Moment; + parseInputDate?: InputParser; /**Show the "Clear" button in the icon toolbar. * Clicking the "Clear" button will set the calendar to null. * @default: false @@ -440,6 +457,11 @@ export interface DatetimepickerOptions { * @default: 1 */ stepping?: number; + /** + * Timezone to use, if moment-timezone is loaded. If null or empty string, ignore timezones. + * @default: "" + */ + timeZone?: string | null; /**Changes the placement of the icon toolbar. * @default: "default" */ @@ -466,7 +488,7 @@ export interface DatetimepickerOptions { /**On picker show, places the widget at the identifier (string) or jQuery object if the element has css position: "relative" * @default: null */ - widgetParent?: string | JQuery; + widgetParent?: string | JQuery | null; widgetPositioning?: WidgetPositioningOptions; } @@ -540,12 +562,12 @@ export interface UpdateEvent extends JQueryEventObject { viewDate: moment.Moment; } +type EventName = "dp.show" | "dp.hide" | "dp.error"; declare global { interface JQuery { - datetimepicker(): JQuery; - datetimepicker(options: DatetimepickerOptions): JQuery; + datetimepicker(options?: DatetimepickerOptions): JQuery; data(key: "DateTimePicker"): Datetimepicker; @@ -556,36 +578,18 @@ declare global { off(events: "dp.change", handler: (eventobject: ChangeEvent) => any): JQuery; off(events: "dp.change", selector?: string, handler?: (eventobject: ChangeEvent) => any): JQuery; + on(events: EventName , handler: (eventObject: Event) => any): JQuery; + on(events: EventName, selector: string, handler: (eventobject: Event) => any): JQuery; + on(events: EventName, selector: string, data: any, handler?: (eventobject: Event) => any): JQuery; - on(events: "dp.show", handler: (eventObject: Event) => any): JQuery; - on(events: "dp.show", selector: string, handler: (eventobject: Event) => any): JQuery; - on(events: "dp.show", selector: string, data: any, handler?: (eventobject: Event) => any): JQuery; - - off(events: "dp.show", handler: (eventobject: Event) => any): JQuery; - off(events: "dp.show", selector?: string, handler?: (eventobject: Event) => any): JQuery; - - - on(events: "dp.hide", handler: (eventObject: Event) => any): JQuery; - on(events: "dp.hide", selector: string, handler: (eventobject: Event) => any): JQuery; - on(events: "dp.hide", selector: string, data: any, handler?: (eventobject: Event) => any): JQuery; - - off(events: "dp.hide", handler: (eventobject: Event) => any): JQuery; - off(events: "dp.hide", selector?: string, handler?: (eventobject: Event) => any): JQuery; - - - on(events: "dp.error", handler: (eventObject: Event) => any): JQuery; - on(events: "dp.error", selector: string, handler: (eventobject: Event) => any): JQuery; - on(events: "dp.error", selector: string, data: any, handler?: (eventobject: Event) => any): JQuery; - - off(events: "dp.error", handler: (eventobject: Event) => any): JQuery; - off(events: "dp.error", selector?: string, handler?: (eventobject: Event) => any): JQuery; - + off(events: EventName, handler: (eventobject: Event) => any): JQuery; + off(events: EventName, selector?: string, handler?: (eventobject: Event) => any): JQuery; on(events: "dp.update", handler: (eventObject: UpdateEvent) => any): JQuery; on(events: "dp.update", selector: string, handler: (eventobject: UpdateEvent) => any): JQuery; on(events: "dp.update", selector: string, data: any, handler?: (eventobject: UpdateEvent) => any): JQuery; - off(events: "dp.update", handler: (eventobject: Event) => any): JQuery; + off(events: "dp.update", handler: (eventobject: UpdateEvent) => any): JQuery; off(events: "dp.update", selector?: string, handler?: (eventobject: UpdateEvent) => any): JQuery; } } diff --git a/bootstrap.v3.datetimepicker/tsconfig.json b/bootstrap.v3.datetimepicker/tsconfig.json index 27ff9874c6..a405cd85dc 100644 --- a/bootstrap.v3.datetimepicker/tsconfig.json +++ b/bootstrap.v3.datetimepicker/tsconfig.json @@ -11,7 +11,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/bootstrap.v3.datetimepicker/tslint.json b/bootstrap.v3.datetimepicker/tslint.json new file mode 100644 index 0000000000..341858d283 --- /dev/null +++ b/bootstrap.v3.datetimepicker/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "quotemark": [true, "double", "avoid-escape"] + } +} \ No newline at end of file diff --git a/bootstrap/bootstrap-tests.ts b/bootstrap/bootstrap-tests.ts index cef85d5d42..cd786b41a7 100644 --- a/bootstrap/bootstrap-tests.ts +++ b/bootstrap/bootstrap-tests.ts @@ -1,6 +1,3 @@ -/// - - $('body').off('.data-api'); $('body').off('.alert.data-api'); diff --git a/browser-resolve/browser-resolve-tests.ts b/browser-resolve/browser-resolve-tests.ts index 2225f7754c..7d08de726f 100644 --- a/browser-resolve/browser-resolve-tests.ts +++ b/browser-resolve/browser-resolve-tests.ts @@ -1,5 +1,3 @@ -/// - import * as browserResolve from 'browser-resolve'; function basic_test_async(callback: (err?: Error, resolved?: string) => void) { diff --git a/bull/bull-tests.tsx b/bull/bull-tests.tsx index 1d307fd31e..fcf339b3c3 100644 --- a/bull/bull-tests.tsx +++ b/bull/bull-tests.tsx @@ -98,3 +98,18 @@ videoQueue.process( ( job: VideoJob ) => { // don't forget to remove the done ca // If the job throws an unhandled exception it is also handled correctly throw new Error( 'some unexpected error' ); } ); + + +var addVideo1Job = videoQueue.add( { video: 'http://example.com/video1.mov' } ); + +addVideo1Job.then((video1Job) => { + // When job has successfully be placed in the queue the job is returned + // then wait for completion + return video1Job.finished(); +}) +.then(() => { + // video1Job completed successfully +}) +.catch((err) => { + // error +}); diff --git a/bull/index.d.ts b/bull/index.d.ts index c604fe25d6..3c89655101 100644 --- a/bull/index.d.ts +++ b/bull/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for bull 1.0.0 +// Type definitions for bull 2.1.2 // Project: https://github.com/OptimalBits/bull -// Definitions by: Bruno Grieder +// Definitions by: Bruno Grieder , Cameron Crothers // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -47,6 +47,13 @@ declare module "bull" { * @returns {Promise} A promise that resolves when the job is scheduled for retry. */ retry(): Promise; + + /** + * Returns a promise the resolves when the job has been finished. + * TODO: Add a watchdog to check if the job has finished periodically. + * since pubsub does not give any guarantees. + */ + finished(): Promise; } export interface Backoff { diff --git a/bunyan-blackhole/bunyan-blackhole-tests.ts b/bunyan-blackhole/bunyan-blackhole-tests.ts new file mode 100644 index 0000000000..ef2096a4c8 --- /dev/null +++ b/bunyan-blackhole/bunyan-blackhole-tests.ts @@ -0,0 +1,26 @@ +import blackhole = require("bunyan-blackhole"); + + + +var logsLaboursLost = blackhole("lost"); + +const rotten = new Error("Something is rotten in the state of Denmark"); + +logsLaboursLost.info(rotten, "Play %s", "Hamlet"); +logsLaboursLost.debug(rotten, "Play %s", "King Lear"); +logsLaboursLost.trace(rotten, "Play %s", "Much Ado About Nothing"); +logsLaboursLost.warn(rotten, "Play %s", "All's Well That Ends Well"); +logsLaboursLost.error(rotten, "Play %s", "Romeo and Juliet"); + +logsLaboursLost.error("Something is rotten in the state of Denmark"); + +logsLaboursLost.debug({character: "Marcellus", play: "King Lear"}, "Friends of my soul, you twain"); +logsLaboursLost.trace({play: "All's Well That Ends Well"}, "Love all, trust a few, do wrong to none"); +logsLaboursLost.info({play: "Much Ado About Nothing"}, "Let me be that I am and seek not to alter me."); +logsLaboursLost.warn({play: "All's Well That Ends Well"}, "Love all, trust a few, do wrong to none"); +logsLaboursLost.error({play: "All's Well That Ends Well"}, "Love all, trust a few, do wrong to none"); + +var hamlet = logsLaboursLost.child({play: "Hamlet"}); +hamlet.info({character: "Polonius"}, "Though this be madness, yet there is method in't"); + + diff --git a/bunyan-blackhole/index.d.ts b/bunyan-blackhole/index.d.ts new file mode 100644 index 0000000000..f8be6fc730 --- /dev/null +++ b/bunyan-blackhole/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for bunyan-blackhole 0.2 +// Project: https://github.com/Floby/node-bunyan-blackhole +// Definitions by: Olivier Chevet +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as Logger from "bunyan"; + +/** + * Constructor. + * @param {string} [name] name of the blackhole Logger + * @return {Logger} A bunyan logger . + */ +declare function bunyanBlackHole(name: string): Logger; +export = bunyanBlackHole; diff --git a/greensock/tsconfig.json b/bunyan-blackhole/tsconfig.json similarity index 87% rename from greensock/tsconfig.json rename to bunyan-blackhole/tsconfig.json index 27e01ecd7b..cddd529d29 100644 --- a/greensock/tsconfig.json +++ b/bunyan-blackhole/tsconfig.json @@ -16,6 +16,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "index.d.ts" + "index.d.ts", + "bunyan-blackhole-tests.ts" ] } \ No newline at end of file diff --git a/bunyan-blackhole/tslint.json b/bunyan-blackhole/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/bunyan-blackhole/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/bunyan/bunyan-tests.ts b/bunyan/bunyan-tests.ts index 91b45765d1..acf382c7c2 100644 --- a/bunyan/bunyan-tests.ts +++ b/bunyan/bunyan-tests.ts @@ -86,26 +86,32 @@ var object = { test: 123 }; +log.trace(); log.trace(buffer); log.trace(error); log.trace(object); log.trace('Hello, %s', 'world!'); +log.debug(); log.debug(buffer); log.debug(error); log.debug(object); log.debug('Hello, %s', 'world!'); +log.info(); log.info(buffer); log.info(error); log.info(object); log.info('Hello, %s', 'world!'); +log.warn(); log.warn(buffer); log.warn(error); log.warn(object); log.warn('Hello, %s', 'world!'); +log.error(); log.error(buffer); log.error(error); log.error(object); log.error('Hello, %s', 'world!'); +log.fatal(); log.fatal(buffer); log.fatal(error); log.fatal(object); diff --git a/bunyan/index.d.ts b/bunyan/index.d.ts index 787a0225f1..060fa8eaa3 100644 --- a/bunyan/index.d.ts +++ b/bunyan/index.d.ts @@ -22,30 +22,191 @@ declare class Logger extends EventEmitter { fields: any; src: boolean; + /** + * Returns a boolean: is the `trace` level enabled? + * + * This is equivalent to `log.isTraceEnabled()` or `log.isEnabledFor(TRACE)` in log4j. + */ + trace(): boolean; + + /** + * Special case to log an `Error` instance to the record. + * This adds an `err` field with exception details + * (including the stack) and sets `msg` to the exception + * message or you can specify the `msg`. + */ trace(error: Error, format?: any, ...params: any[]): void; + trace(buffer: Buffer, format?: any, ...params: any[]): void; + + /** + * Uses `util.format` for msg formatting. + */ + trace(format: string | number, ...params: any[]): void; + + /** + * The first field can optionally be a "fields" object, which + * is merged into the log record. + * + * To pass in an Error *and* other fields, use the `err` + * field name for the Error instance. + */ trace(obj: Object, format?: any, ...params: any[]): void; - trace(format: string, ...params: any[]): void; + + /** + * Returns a boolean: is the `debug` level enabled? + * + * This is equivalent to `log.isDebugEnabled()` or `log.isEnabledFor(DEBUG)` in log4j. + */ + debug(): boolean; + + /** + * Special case to log an `Error` instance to the record. + * This adds an `err` field with exception details + * (including the stack) and sets `msg` to the exception + * message or you can specify the `msg`. + */ debug(error: Error, format?: any, ...params: any[]): void; + debug(buffer: Buffer, format?: any, ...params: any[]): void; + + /** + * Uses `util.format` for msg formatting. + */ + debug(format: string | number, ...params: any[]): void; + + /** + * The first field can optionally be a "fields" object, which + * is merged into the log record. + * + * To pass in an Error *and* other fields, use the `err` + * field name for the Error instance. + */ debug(obj: Object, format?: any, ...params: any[]): void; - debug(format: string, ...params: any[]): void; + + /** + * Returns a boolean: is the `info` level enabled? + * + * This is equivalent to `log.isInfoEnabled()` or `log.isEnabledFor(INFO)` in log4j. + */ + info(): boolean; + + /** + * Special case to log an `Error` instance to the record. + * This adds an `err` field with exception details + * (including the stack) and sets `msg` to the exception + * message or you can specify the `msg`. + */ info(error: Error, format?: any, ...params: any[]): void; + info(buffer: Buffer, format?: any, ...params: any[]): void; + + /** + * Uses `util.format` for msg formatting. + */ + info(format: string | number, ...params: any[]): void; + + /** + * The first field can optionally be a "fields" object, which + * is merged into the log record. + * + * To pass in an Error *and* other fields, use the `err` + * field name for the Error instance. + */ info(obj: Object, format?: any, ...params: any[]): void; - info(format: string, ...params: any[]): void; + + /** + * Returns a boolean: is the `warn` level enabled? + * + * This is equivalent to `log.isWarnEnabled()` or `log.isEnabledFor(WARN)` in log4j. + */ + warn(): boolean; + + /** + * Special case to log an `Error` instance to the record. + * This adds an `err` field with exception details + * (including the stack) and sets `msg` to the exception + * message or you can specify the `msg`. + */ warn(error: Error, format?: any, ...params: any[]): void; + warn(buffer: Buffer, format?: any, ...params: any[]): void; + + /** + * Uses `util.format` for msg formatting. + */ + warn(format: string | number, ...params: any[]): void; + + /** + * The first field can optionally be a "fields" object, which + * is merged into the log record. + * + * To pass in an Error *and* other fields, use the `err` + * field name for the Error instance. + */ warn(obj: Object, format?: any, ...params: any[]): void; - warn(format: string, ...params: any[]): void; + + /** + * Returns a boolean: is the `error` level enabled? + * + * This is equivalent to `log.isErrorEnabled()` or `log.isEnabledFor(ERROR)` in log4j. + */ + error(): boolean; + + /** + * Special case to log an `Error` instance to the record. + * This adds an `err` field with exception details + * (including the stack) and sets `msg` to the exception + * message or you can specify the `msg`. + */ error(error: Error, format?: any, ...params: any[]): void; + error(buffer: Buffer, format?: any, ...params: any[]): void; + + /** + * Uses `util.format` for msg formatting. + */ + error(format: string | number, ...params: any[]): void; + + /** + * The first field can optionally be a "fields" object, which + * is merged into the log record. + * + * To pass in an Error *and* other fields, use the `err` + * field name for the Error instance. + */ error(obj: Object, format?: any, ...params: any[]): void; - error(format: string, ...params: any[]): void; + + /** + * Returns a boolean: is the `fatal` level enabled? + * + * This is equivalent to `log.isFatalEnabled()` or `log.isEnabledFor(FATAL)` in log4j. + */ + fatal(): boolean; + + /** + * Special case to log an `Error` instance to the record. + * This adds an `err` field with exception details + * (including the stack) and sets `msg` to the exception + * message or you can specify the `msg`. + */ fatal(error: Error, format?: any, ...params: any[]): void; + fatal(buffer: Buffer, format?: any, ...params: any[]): void; + + /** + * Uses `util.format` for msg formatting. + */ + fatal(format: string | number, ...params: any[]): void; + + /** + * The first field can optionally be a "fields" object, which + * is merged into the log record. + * + * To pass in an Error *and* other fields, use the `err` + * field name for the Error instance. + */ fatal(obj: Object, format?: any, ...params: any[]): void; - fatal(format: string, ...params: any[]): void; } declare namespace Logger { diff --git a/business-rules-engine/business-rules-engine-tests.ts b/business-rules-engine/business-rules-engine-tests.ts index 3ffbe2948c..4ae31155f2 100644 --- a/business-rules-engine/business-rules-engine-tests.ts +++ b/business-rules-engine/business-rules-engine-tests.ts @@ -1,4 +1,3 @@ -/// import * as Validators from 'business-rules-engine/node-validators'; import Validation = require("business-rules-engine"); diff --git a/cachefactory/cachefactory-tests.ts b/cachefactory/cachefactory-tests.ts index 73397dd8bf..32eeb63257 100644 --- a/cachefactory/cachefactory-tests.ts +++ b/cachefactory/cachefactory-tests.ts @@ -1,5 +1,3 @@ -/// - CacheFactory.get('test'); CacheFactory.createCache('test', { diff --git a/cal-heatmap/cal-heatmap-tests.ts b/cal-heatmap/cal-heatmap-tests.ts index 47020b811c..ff0e3c0d06 100644 --- a/cal-heatmap/cal-heatmap-tests.ts +++ b/cal-heatmap/cal-heatmap-tests.ts @@ -1,6 +1,4 @@ - /// -/// var cal = new CalHeatMap(); cal.init(); diff --git a/cassandra-driver/cassandra-driver-tests.ts b/cassandra-driver/cassandra-driver-tests.ts index 9feee249ac..e5d8f2ab60 100644 --- a/cassandra-driver/cassandra-driver-tests.ts +++ b/cassandra-driver/cassandra-driver-tests.ts @@ -1,5 +1,3 @@ -/// - import * as cassandra from 'cassandra-driver'; import * as util from 'util'; diff --git a/cbor/cbor-tests.ts b/cbor/cbor-tests.ts index e1a7abb9cf..eb84201b97 100644 --- a/cbor/cbor-tests.ts +++ b/cbor/cbor-tests.ts @@ -1,5 +1,3 @@ -/// - import cbor = require('cbor'); import assert = require('assert'); import fs = require('fs'); diff --git a/chai-as-promised/chai-as-promised-tests.ts b/chai-as-promised/chai-as-promised-tests.ts index 0fde03dfa3..d9f681769b 100644 --- a/chai-as-promised/chai-as-promised-tests.ts +++ b/chai-as-promised/chai-as-promised-tests.ts @@ -1,7 +1,3 @@ - -/// -/// - import chai = require('chai'); import chaiAsPromised = require('chai-as-promised'); import Q = require('q'); @@ -12,7 +8,7 @@ class TestClass {} // ReSharper disable WrongExpressionStatement // BDD API (expect) -var thenableNum: PromisesAPlus.Thenable; +var thenableNum: PromiseLike; thenableNum = chai.expect(thenableNum).to.eventually.equal(3); thenableNum = chai.expect(thenableNum).to.eventually.have.property('foo'); thenableNum = chai.expect(thenableNum).to.become(3); @@ -56,7 +52,7 @@ Q.all([ ]).should.notify(() => console.log('done')); // Assert API -var thenableVoid: PromisesAPlus.Thenable; +var thenableVoid: PromiseLike; thenableVoid = chai.assert.eventually.equal(thenableNum, 4, 'Message'); thenableVoid = chai.assert.isFulfilled(thenableNum, "optional message"); thenableVoid = chai.assert.becomes(thenableNum, "foo", "optional message"); diff --git a/chai-as-promised/index.d.ts b/chai-as-promised/index.d.ts index b4f3ca405d..4c36eccb61 100644 --- a/chai-as-promised/index.d.ts +++ b/chai-as-promised/index.d.ts @@ -4,7 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -/// declare module 'chai-as-promised' { function chaiAsPromised(chai: any, utils: any): void; @@ -27,7 +26,7 @@ declare namespace Chai { // Eventually does not have .then(), but PromisedAssertion have. interface Eventually extends PromisedLanguageChains, PromisedNumericComparison, PromisedTypeComparison { // From chai-as-promised - become(expected: PromisesAPlus.Thenable): PromisedAssertion; + become(expected: PromiseLike): PromisedAssertion; fulfilled: PromisedAssertion; rejected: PromisedAssertion; rejectedWith(expected: any, message?: string | RegExp): PromisedAssertion; @@ -74,7 +73,7 @@ declare namespace Chai { members: PromisedMembers; } - interface PromisedAssertion extends Eventually, PromisesAPlus.Thenable { + interface PromisedAssertion extends Eventually, PromiseLike { } interface PromisedLanguageChains { @@ -181,111 +180,111 @@ declare namespace Chai { // For Assert API interface Assert { eventually: PromisedAssert; - isFulfilled(promise: PromisesAPlus.Thenable, message?: string): PromisesAPlus.Thenable; - becomes(promise: PromisesAPlus.Thenable, expected: any, message?: string): PromisesAPlus.Thenable; - doesNotBecome(promise: PromisesAPlus.Thenable, expected: any, message?: string): PromisesAPlus.Thenable; - isRejected(promise: PromisesAPlus.Thenable, message?: string): PromisesAPlus.Thenable; - isRejected(promise: PromisesAPlus.Thenable, expected: any, message?: string): PromisesAPlus.Thenable; - isRejected(promise: PromisesAPlus.Thenable, match: RegExp, message?: string): PromisesAPlus.Thenable; - notify(fn: Function): PromisesAPlus.Thenable; + isFulfilled(promise: PromiseLike, message?: string): PromiseLike; + becomes(promise: PromiseLike, expected: any, message?: string): PromiseLike; + doesNotBecome(promise: PromiseLike, expected: any, message?: string): PromiseLike; + isRejected(promise: PromiseLike, message?: string): PromiseLike; + isRejected(promise: PromiseLike, expected: any, message?: string): PromiseLike; + isRejected(promise: PromiseLike, match: RegExp, message?: string): PromiseLike; + notify(fn: Function): PromiseLike; } export interface PromisedAssert { - fail(actual?: any, expected?: any, msg?: string, operator?: string): PromisesAPlus.Thenable; + fail(actual?: any, expected?: any, msg?: string, operator?: string): PromiseLike; - ok(val: any, msg?: string): PromisesAPlus.Thenable; - notOk(val: any, msg?: string): PromisesAPlus.Thenable; + ok(val: any, msg?: string): PromiseLike; + notOk(val: any, msg?: string): PromiseLike; - equal(act: any, exp: any, msg?: string): PromisesAPlus.Thenable; - notEqual(act: any, exp: any, msg?: string): PromisesAPlus.Thenable; + equal(act: any, exp: any, msg?: string): PromiseLike; + notEqual(act: any, exp: any, msg?: string): PromiseLike; - strictEqual(act: any, exp: any, msg?: string): PromisesAPlus.Thenable; - notStrictEqual(act: any, exp: any, msg?: string): PromisesAPlus.Thenable; + strictEqual(act: any, exp: any, msg?: string): PromiseLike; + notStrictEqual(act: any, exp: any, msg?: string): PromiseLike; - deepEqual(act: any, exp: any, msg?: string): PromisesAPlus.Thenable; - notDeepEqual(act: any, exp: any, msg?: string): PromisesAPlus.Thenable; + deepEqual(act: any, exp: any, msg?: string): PromiseLike; + notDeepEqual(act: any, exp: any, msg?: string): PromiseLike; - isTrue(val: any, msg?: string): PromisesAPlus.Thenable; - isFalse(val: any, msg?: string): PromisesAPlus.Thenable; + isTrue(val: any, msg?: string): PromiseLike; + isFalse(val: any, msg?: string): PromiseLike; - isNull(val: any, msg?: string): PromisesAPlus.Thenable; - isNotNull(val: any, msg?: string): PromisesAPlus.Thenable; + isNull(val: any, msg?: string): PromiseLike; + isNotNull(val: any, msg?: string): PromiseLike; - isUndefined(val: any, msg?: string): PromisesAPlus.Thenable; - isDefined(val: any, msg?: string): PromisesAPlus.Thenable; + isUndefined(val: any, msg?: string): PromiseLike; + isDefined(val: any, msg?: string): PromiseLike; - isFunction(val: any, msg?: string): PromisesAPlus.Thenable; - isNotFunction(val: any, msg?: string): PromisesAPlus.Thenable; + isFunction(val: any, msg?: string): PromiseLike; + isNotFunction(val: any, msg?: string): PromiseLike; - isObject(val: any, msg?: string): PromisesAPlus.Thenable; - isNotObject(val: any, msg?: string): PromisesAPlus.Thenable; + isObject(val: any, msg?: string): PromiseLike; + isNotObject(val: any, msg?: string): PromiseLike; - isArray(val: any, msg?: string): PromisesAPlus.Thenable; - isNotArray(val: any, msg?: string): PromisesAPlus.Thenable; + isArray(val: any, msg?: string): PromiseLike; + isNotArray(val: any, msg?: string): PromiseLike; - isString(val: any, msg?: string): PromisesAPlus.Thenable; - isNotString(val: any, msg?: string): PromisesAPlus.Thenable; + isString(val: any, msg?: string): PromiseLike; + isNotString(val: any, msg?: string): PromiseLike; - isNumber(val: any, msg?: string): PromisesAPlus.Thenable; - isNotNumber(val: any, msg?: string): PromisesAPlus.Thenable; + isNumber(val: any, msg?: string): PromiseLike; + isNotNumber(val: any, msg?: string): PromiseLike; - isBoolean(val: any, msg?: string): PromisesAPlus.Thenable; - isNotBoolean(val: any, msg?: string): PromisesAPlus.Thenable; + isBoolean(val: any, msg?: string): PromiseLike; + isNotBoolean(val: any, msg?: string): PromiseLike; - typeOf(val: any, type: string, msg?: string): PromisesAPlus.Thenable; - notTypeOf(val: any, type: string, msg?: string): PromisesAPlus.Thenable; + typeOf(val: any, type: string, msg?: string): PromiseLike; + notTypeOf(val: any, type: string, msg?: string): PromiseLike; - instanceOf(val: any, type: Function, msg?: string): PromisesAPlus.Thenable; - notInstanceOf(val: any, type: Function, msg?: string): PromisesAPlus.Thenable; + instanceOf(val: any, type: Function, msg?: string): PromiseLike; + notInstanceOf(val: any, type: Function, msg?: string): PromiseLike; - include(exp: string, inc: any, msg?: string): PromisesAPlus.Thenable; - include(exp: any[], inc: any, msg?: string): PromisesAPlus.Thenable; + include(exp: string, inc: any, msg?: string): PromiseLike; + include(exp: any[], inc: any, msg?: string): PromiseLike; - notInclude(exp: string, inc: any, msg?: string): PromisesAPlus.Thenable; - notInclude(exp: any[], inc: any, msg?: string): PromisesAPlus.Thenable; + notInclude(exp: string, inc: any, msg?: string): PromiseLike; + notInclude(exp: any[], inc: any, msg?: string): PromiseLike; - match(exp: any, re: RegExp, msg?: string): PromisesAPlus.Thenable; - notMatch(exp: any, re: RegExp, msg?: string): PromisesAPlus.Thenable; + match(exp: any, re: RegExp, msg?: string): PromiseLike; + notMatch(exp: any, re: RegExp, msg?: string): PromiseLike; - property(obj: Object, prop: string, msg?: string): PromisesAPlus.Thenable; - notProperty(obj: Object, prop: string, msg?: string): PromisesAPlus.Thenable; - deepProperty(obj: Object, prop: string, msg?: string): PromisesAPlus.Thenable; - notDeepProperty(obj: Object, prop: string, msg?: string): PromisesAPlus.Thenable; + property(obj: Object, prop: string, msg?: string): PromiseLike; + notProperty(obj: Object, prop: string, msg?: string): PromiseLike; + deepProperty(obj: Object, prop: string, msg?: string): PromiseLike; + notDeepProperty(obj: Object, prop: string, msg?: string): PromiseLike; - propertyVal(obj: Object, prop: string, val: any, msg?: string): PromisesAPlus.Thenable; - propertyNotVal(obj: Object, prop: string, val: any, msg?: string): PromisesAPlus.Thenable; + propertyVal(obj: Object, prop: string, val: any, msg?: string): PromiseLike; + propertyNotVal(obj: Object, prop: string, val: any, msg?: string): PromiseLike; - deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): PromisesAPlus.Thenable; - deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): PromisesAPlus.Thenable; + deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): PromiseLike; + deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): PromiseLike; - lengthOf(exp: any, len: number, msg?: string): PromisesAPlus.Thenable; + lengthOf(exp: any, len: number, msg?: string): PromiseLike; //alias frenzy - throw(fn: Function, msg?: string): PromisesAPlus.Thenable; - throw(fn: Function, regExp: RegExp): PromisesAPlus.Thenable; - throw(fn: Function, errType: Function, msg?: string): PromisesAPlus.Thenable; - throw(fn: Function, errType: Function, regExp: RegExp): PromisesAPlus.Thenable; + throw(fn: Function, msg?: string): PromiseLike; + throw(fn: Function, regExp: RegExp): PromiseLike; + throw(fn: Function, errType: Function, msg?: string): PromiseLike; + throw(fn: Function, errType: Function, regExp: RegExp): PromiseLike; - throws(fn: Function, msg?: string): PromisesAPlus.Thenable; - throws(fn: Function, regExp: RegExp): PromisesAPlus.Thenable; - throws(fn: Function, errType: Function, msg?: string): PromisesAPlus.Thenable; - throws(fn: Function, errType: Function, regExp: RegExp): PromisesAPlus.Thenable; + throws(fn: Function, msg?: string): PromiseLike; + throws(fn: Function, regExp: RegExp): PromiseLike; + throws(fn: Function, errType: Function, msg?: string): PromiseLike; + throws(fn: Function, errType: Function, regExp: RegExp): PromiseLike; - Throw(fn: Function, msg?: string): PromisesAPlus.Thenable; - Throw(fn: Function, regExp: RegExp): PromisesAPlus.Thenable; - Throw(fn: Function, errType: Function, msg?: string): PromisesAPlus.Thenable; - Throw(fn: Function, errType: Function, regExp: RegExp): PromisesAPlus.Thenable; + Throw(fn: Function, msg?: string): PromiseLike; + Throw(fn: Function, regExp: RegExp): PromiseLike; + Throw(fn: Function, errType: Function, msg?: string): PromiseLike; + Throw(fn: Function, errType: Function, regExp: RegExp): PromiseLike; - doesNotThrow(fn: Function, msg?: string): PromisesAPlus.Thenable; - doesNotThrow(fn: Function, regExp: RegExp): PromisesAPlus.Thenable; - doesNotThrow(fn: Function, errType: Function, msg?: string): PromisesAPlus.Thenable; - doesNotThrow(fn: Function, errType: Function, regExp: RegExp): PromisesAPlus.Thenable; + doesNotThrow(fn: Function, msg?: string): PromiseLike; + doesNotThrow(fn: Function, regExp: RegExp): PromiseLike; + doesNotThrow(fn: Function, errType: Function, msg?: string): PromiseLike; + doesNotThrow(fn: Function, errType: Function, regExp: RegExp): PromiseLike; - operator(val: any, operator: string, val2: any, msg?: string): PromisesAPlus.Thenable; - closeTo(act: number, exp: number, delta: number, msg?: string): PromisesAPlus.Thenable; + operator(val: any, operator: string, val2: any, msg?: string): PromiseLike; + closeTo(act: number, exp: number, delta: number, msg?: string): PromiseLike; - sameMembers(set1: any[], set2: any[], msg?: string): PromisesAPlus.Thenable; - includeMembers(set1: any[], set2: any[], msg?: string): PromisesAPlus.Thenable; + sameMembers(set1: any[], set2: any[], msg?: string): PromiseLike; + includeMembers(set1: any[], set2: any[], msg?: string): PromiseLike; - ifError(val: any, msg?: string): PromisesAPlus.Thenable; + ifError(val: any, msg?: string): PromiseLike; } } diff --git a/chai-enzyme/chai-enzyme-tests.tsx b/chai-enzyme/chai-enzyme-tests.tsx index a70f7e7f96..8fc64e2711 100644 --- a/chai-enzyme/chai-enzyme-tests.tsx +++ b/chai-enzyme/chai-enzyme-tests.tsx @@ -1,7 +1,3 @@ -/// -/// -/// - import * as React from "react"; import * as chaiEnzyme from "chai-enzyme"; import { expect } from "chai"; @@ -34,11 +30,15 @@ expect(wrapper).to.have.ref("test"); expect(wrapper).to.be.selected(); expect(wrapper).to.have.tagName("div"); expect(wrapper).to.have.text(""); +expect(wrapper).to.have.type(Test); expect(wrapper).to.have.value("test"); expect(wrapper).to.have.attr("test", "test"); expect(wrapper).to.have.data("test", "Test"); expect(wrapper).to.have.style("background", "green"); expect(wrapper).to.have.state("test", "test"); expect(wrapper).to.have.prop("test", 5); +expect(wrapper).to.have.props(["test1", "test2"]); +expect(wrapper).to.have.props({ test: 5 }); expect(wrapper).to.contain(); +expect(wrapper).to.containMatchingElement(); expect(wrapper).to.match(); diff --git a/chai-enzyme/index.d.ts b/chai-enzyme/index.d.ts index 6997abd5fe..92c5817504 100644 --- a/chai-enzyme/index.d.ts +++ b/chai-enzyme/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for chai-enzyme 0.5.0 +// Type definitions for chai-enzyme 0.6.1 // Project: https://github.com/producthunt/chai-enzyme // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -39,6 +39,12 @@ declare namespace Chai { */ className(name: string): Assertion; + /** + * Assert that the wrapper contains a certain element: + * @param selector + */ + containMatchingElement(selector: EnzymeSelector): Assertion; + /** * Assert that the wrapper contains a descendant matching the given selector: * @param selector @@ -100,6 +106,12 @@ declare namespace Chai { */ text(str?: string): Assertion; + /** + * Assert that the given wrapper has a given type: + * @param func + */ + type(func: EnzymeSelector): Assertion; + /** * Assert that the given wrapper has given value: * @param str @@ -140,6 +152,18 @@ declare namespace Chai { * @param val */ prop(key: string, val?: any): Assertion; + + /** + * Assert that the wrapper has given props [with values]: + * @param keys + */ + props(keys: string[]): Assertion; + + /** + * Assert that the wrapper has given props [with values]: + * @param props + */ + props(props: EnzymeSelector): Assertion; } } diff --git a/chai-spies/chai-spies-tests.ts b/chai-spies/chai-spies-tests.ts index 7ac0610e4d..326b1e0137 100644 --- a/chai-spies/chai-spies-tests.ts +++ b/chai-spies/chai-spies-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as chai from 'chai'; import * as spies from 'chai-spies'; import * as Mocha from 'mocha'; diff --git a/chance/index.d.ts b/chance/index.d.ts index 7ce79b431f..10538b747c 100644 --- a/chance/index.d.ts +++ b/chance/index.d.ts @@ -129,7 +129,7 @@ declare namespace Chance { * @deprecated Use pickset */ pick(arr: T[], count: number): T[]; - pickset(arr: T[], count: number): T[]; + pickset(arr: T[], count?: number): T[]; set: Setter; shuffle(arr: T[]): T[]; diff --git a/chart.js/index.d.ts b/chart.js/index.d.ts index 08781f4463..43192689c1 100644 --- a/chart.js/index.d.ts +++ b/chart.js/index.d.ts @@ -1,11 +1,16 @@ -// Type definitions for Chart.js +// Type definitions for Chart.js 2.4.0 // Project: https://github.com/nnnick/Chart.js // Definitions by: Alberto Nuti // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + declare class Chart { static readonly Chart: typeof Chart; - constructor(context: CanvasRenderingContext2D | HTMLCanvasElement, options: Chart.ChartConfiguration); + constructor( + context: string | JQuery | CanvasRenderingContext2D | HTMLCanvasElement | string[] | CanvasRenderingContext2D[] | HTMLCanvasElement[], + options: Chart.ChartConfiguration + ); config: Chart.ChartConfiguration; data: Chart.ChartData; destroy: () => {}; @@ -20,7 +25,7 @@ declare class Chart { getElementsAtEvent: (e: any) => {}[]; getDatasetAtEvent: (e: any) => {}[]; - defaults: { + static defaults: { global: Chart.ChartOptions; } } @@ -32,6 +37,8 @@ declare namespace Chart { export type ScaleType = 'category' | 'linear' | 'logarithmic' | 'time' | 'radialLinear'; + export type PositionType = 'left' | 'right' | 'top' | 'bottom'; + export interface ChartLegendItem { text?: string; fillStyle?: string; @@ -342,7 +349,7 @@ declare namespace Chart { export interface ChartScales { type?: ScaleType | string; display?: boolean; - position?: string; + position?: PositionType | string; beforeUpdate?: (scale?: any) => void; beforeSetDimension?: (scale?: any) => void; beforeDataLimits?: (scale?: any) => void; @@ -364,29 +371,25 @@ declare namespace Chart { yAxes?: ChartYAxe[]; } - export interface ChartXAxe { + export interface CommonAxe { type?: ScaleType | string; display?: boolean; id?: string; stacked?: boolean; - categoryPercentage?: number; - barPercentage?: number; - barThickness?: number; - gridLines?: GridLineOptions; position?: string; ticks?: TickOptions; - time?: TimeScale; + gridLines?: GridLineOptions; + barThickness?: number; scaleLabel?: ScaleTitleOptions; } - export interface ChartYAxe { - type?: ScaleType | string; - display?: boolean; - id?: string; - stacked?: boolean; - position?: string; - ticks?: TickOptions; - scaleLabel?: ScaleTitleOptions; + export interface ChartXAxe extends CommonAxe { + categoryPercentage?: number; + barPercentage?: number; + time?: TimeScale; + } + + export interface ChartYAxe extends CommonAxe { } export interface LinearScale extends ChartScales { diff --git a/cheerio/cheerio-tests.ts b/cheerio/cheerio-tests.ts index 5b1f6511ec..1c0848eef7 100644 --- a/cheerio/cheerio-tests.ts +++ b/cheerio/cheerio-tests.ts @@ -55,6 +55,10 @@ var $multiEl = $('selector', 'selector', 'selector'); $el.attr('id'); $el.attr('id', 'favorite').html(); +// props +$el.prop('style') +$el.prop('style', 'none').html() + // data $el.data(); $el.data('apple-color'); @@ -86,6 +90,7 @@ $el.is(() => { */ // serializeArray $('').serializeArray(); +$('
').serialize(); /** * Traversing @@ -217,6 +222,9 @@ $el.eq(0).addBack('.class').length * Manipulation */ +$('
  • Plum
  • ').appendTo($el) +$el.prependTo($('
  • Plum
  • ')) + // .append( content, [content, ...] ) $el.append('
  • Plum
  • ').html(); $el.append('
  • Plum
  • ', '
  • Plum
  • ').html(); diff --git a/cheerio/index.d.ts b/cheerio/index.d.ts index e94eb1a68c..f3615674f5 100644 --- a/cheerio/index.d.ts +++ b/cheerio/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Cheerio v0.17.0 +// Type definitions for Cheerio v0.22.0 // Project: https://github.com/cheeriojs/cheerio -// Definitions by: Bret Little , VILIC VANE , Wayne Maurer +// Definitions by: Bret Little , VILIC VANE , Wayne Maurer , Umar Nizamani // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Cheerio { @@ -47,10 +47,11 @@ interface Cheerio { is(func: (index: number, element: CheerioElement) => boolean): boolean; // Form + serialize(): string; serializeArray(): {name: string, value: string}[]; // Traversing - + find(selector: string): Cheerio; find(element: Cheerio): Cheerio; @@ -60,6 +61,9 @@ interface Cheerio { parentsUntil(element: CheerioElement, filter?: string): Cheerio; parentsUntil(element: Cheerio, filter?: string): Cheerio; + prop(name: string): any; + prop(name: string, value: any): Cheerio; + closest(): Cheerio; closest(selector: string): Cheerio; @@ -126,6 +130,8 @@ interface Cheerio { addBack(filter: string):Cheerio; // Manipulation + appendTo(target: Cheerio) : Cheerio + prependTo(target: Cheerio) : Cheerio append(content: string, ...contents: any[]): Cheerio; append(content: Document, ...contents: any[]): Cheerio; @@ -266,4 +272,4 @@ declare var cheerio:CheerioAPI; declare module "cheerio" { export = cheerio; -} +} \ No newline at end of file diff --git a/chocolatechipjs/chocolatechipjs-tests.ts b/chocolatechipjs/chocolatechipjs-tests.ts index 465ea2b0a9..7036358aed 100644 --- a/chocolatechipjs/chocolatechipjs-tests.ts +++ b/chocolatechipjs/chocolatechipjs-tests.ts @@ -1,4 +1,3 @@ -/// // ChocolateChipStatic -- DOM creation, etc. $(function() { alert('Ready to do stuff!'); @@ -282,7 +281,7 @@ fetch('../controllers/php-post.php', { }, body: formData }) -.then($.json) +.then($.json) .then(function(data: any): any { if(data.email_check == "valid"){ $("#message_ajax").html("
    " + data.email + " is a valid e-mail address. Thank you, " + data.name + ".
    "); @@ -300,12 +299,12 @@ interface putData { var putData = $('#fileText').val(); fetch('../controllers/php-put.php', { method: 'put', - headers: { - "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" + headers: { + "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" }, body: putData }) -.then($.json) +.then($.json) .then(function(data:any): any { console.dir(data.base); $("#message_ajax").append('

    ' + data.result + '

    '); @@ -324,12 +323,12 @@ interface deleteData { var file = $('#fileName').val(); fetch('../controllers/php-delete.php', { method: 'delete', - headers: { - "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" + headers: { + "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" }, body: file }) -.then($.json) +.then($.json) .then(function(data: any): any { $("#message_ajax").html("
    DELETE was sent to the server successfully.
    "); $("#message_ajax").append('

    ' + data.result + '

    '); diff --git a/chrome/index.d.ts b/chrome/index.d.ts index 211375a3fe..b7b6de0076 100644 --- a/chrome/index.d.ts +++ b/chrome/index.d.ts @@ -1831,7 +1831,7 @@ declare namespace chrome.devtools.panels { * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ - setObject(jsonObject: string, rootTitle?: string, callback?: () => void): void; + setObject(jsonObject: Object, rootTitle?: string, callback?: () => void): void; /** * Sets a JSON-compliant object to be displayed in the sidebar pane. * @param jsonObject An object to be displayed in context of the inspected page. Evaluated in the context of the caller (API client). @@ -1839,7 +1839,7 @@ declare namespace chrome.devtools.panels { * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ - setObject(jsonObject: string, callback?: () => void): void; + setObject(jsonObject: Object, callback?: () => void): void; /** * Sets an HTML page to be displayed in the sidebar pane. * @param path Relative path of an extension page to display within the sidebar. @@ -4854,7 +4854,7 @@ declare namespace chrome.proxy { */ declare namespace chrome.runtime { /** This will be defined during an API method callback if there was an error */ - var lastError: LastError; + var lastError: LastError | undefined; /** The ID of the extension/app. */ var id: string; diff --git a/cliff/cliff-tests.ts b/cliff/cliff-tests.ts index 9217d9a38a..e69de29bb2 100644 --- a/cliff/cliff-tests.ts +++ b/cliff/cliff-tests.ts @@ -1 +0,0 @@ -/// \ No newline at end of file diff --git a/co-body/co-body-tests.ts b/co-body/co-body-tests.ts index 6011632399..944cadd394 100644 --- a/co-body/co-body-tests.ts +++ b/co-body/co-body-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as koa from 'koa'; import * as parse from 'co-body'; diff --git a/coinstring/coinstring-tests.ts b/coinstring/coinstring-tests.ts index ab11a44fb7..1cc3fb9a42 100644 --- a/coinstring/coinstring-tests.ts +++ b/coinstring/coinstring-tests.ts @@ -1,8 +1,5 @@ -/// - import cs = require('coinstring'); - var privateKeyHex = "1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd"; var privateKeyHexBuf = new Buffer(privateKeyHex, 'hex'); var version = 0x80; // Bitcoin private key diff --git a/combined-stream/combined-stream-tests.ts b/combined-stream/combined-stream-tests.ts new file mode 100644 index 0000000000..776e530e63 --- /dev/null +++ b/combined-stream/combined-stream-tests.ts @@ -0,0 +1,30 @@ +import * as CombinedStream from "combined-stream"; +import { createReadStream, createWriteStream } from "fs"; + +const stream1 = new CombinedStream(); + +stream1.append(createReadStream("tsconfig.json")); +stream1.append(createReadStream("tslint.json")); +stream1.append(createReadStream("index.d.ts")); + +stream1.pipe(createWriteStream("combined.txt")); + +const stream2 = CombinedStream.create({ + maxDataSize: 1 << 32, + pauseStreams: false, +}); + +stream1.destroy(); + +// should log true +console.log(CombinedStream.isStreamLike(stream2)); + +stream2.on("data", (data) => { + console.log(data); +}); + +stream2.pipe(createWriteStream("combined.txt")); + +stream2.write(CombinedStream.name); + +stream2.destroy(); diff --git a/combined-stream/index.d.ts b/combined-stream/index.d.ts new file mode 100644 index 0000000000..cada758701 --- /dev/null +++ b/combined-stream/index.d.ts @@ -0,0 +1,56 @@ +// Type definitions for combined-stream 1.0 +// Project: https://github.com/felixge/node-combined-stream +// Definitions by: Felix Geisendörfer , Tomek Łaziuk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Stream } from "stream"; + +declare class CombinedStream extends Stream implements CombinedStream.Options { + readonly writable: boolean; + readonly readable: boolean; + readonly dataSize: number; + maxDataSize: number; + pauseStreams: boolean; + append(stream: NodeJS.ReadableStream | NodeJS.WritableStream | Buffer | string): this; + write(data: any): void; + pause(): void; + resume(): void; + end(): void; + destroy(): void; + + // private properties + _released: boolean; + // @TODO it should be a type of Array<'delayed-stream' instance | Buffer | string> + _streams: Array; + _currentStream: Stream | Buffer | string | null; + _getNext(): void; + _pipeNext(): void; + _handleErrors(stream: NodeJS.EventEmitter): void; + _reset(): void; + _checkDataSize(): void; + _updateDataSize(): void; + _emitError(error: Error): void; + + // events + on(event: "close" | "end" | "resume" | "pause", cb: () => void): this; + on(event: "error", cb: (err: Error) => void): this; + on(event: "data", cb: (data: any) => void): this; + once(event: "close" | "end" | "resume" | "pause", cb: () => void): this; + once(event: "error", cb: (err: Error) => void): this; + once(event: "data", cb: (data: any) => void): this; +} + +declare namespace CombinedStream { + export interface Options { + maxDataSize?: number; + pauseStreams?: boolean; + } + + export function create(options?: Options): CombinedStream; + + export function isStreamLike(stream: any): stream is Stream; +} + +export = CombinedStream; diff --git a/combined-stream/tsconfig.json b/combined-stream/tsconfig.json new file mode 100644 index 0000000000..e1986a21be --- /dev/null +++ b/combined-stream/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "combined-stream-tests.ts" + ] +} diff --git a/combined-stream/tslint.json b/combined-stream/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/combined-stream/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/connect-redis/connect-redis-tests.ts b/connect-redis/connect-redis-tests.ts index ed21f3b4be..3c50074117 100644 --- a/connect-redis/connect-redis-tests.ts +++ b/connect-redis/connect-redis-tests.ts @@ -1,5 +1,3 @@ -/// - import * as connectRedis from "connect-redis"; import * as session from "express-session"; diff --git a/cookie/cookie-tests.ts b/cookie/cookie-tests.ts index 2581a5c372..dd5be0f850 100644 --- a/cookie/cookie-tests.ts +++ b/cookie/cookie-tests.ts @@ -17,7 +17,7 @@ function test_parse(): void { } function test_options(): void { - var serializeOptions: CookieSerializeOptions = { + var serializeOptions: cookie.CookieSerializeOptions = { encode: (x: string) => x, path: '/', expires: new Date(), @@ -27,7 +27,7 @@ function test_options(): void { httpOnly: false }; - var parseOptios: CookieParseOptions = { + var parseOptios: cookie.CookieParseOptions = { decode: (x: string) => x }; } diff --git a/cookie/index.d.ts b/cookie/index.d.ts index 950796fa22..507eaee01d 100644 --- a/cookie/index.d.ts +++ b/cookie/index.d.ts @@ -1,28 +1,118 @@ -// Type definitions for cookie v0.1.2 +// Type definitions for cookie v0.3.0 // Project: https://github.com/jshttp/cookie // Definitions by: Pine Mizune // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface CookieSerializeOptions { - encode?: (val: string) => string; - path?: string; - expires?: Date; - maxAge?: number; + /** + * Specifies the value for the Domain Set-Cookie attribute. By default, no + * domain is set, and most clients will consider the cookie to apply to only + * the current domain. + */ domain?: string; - secure?: boolean; + /** + * Specifies a function that will be used to encode a cookie's value. Since + * value of a cookie has a limited character set (and must be a simple + * string), this function can be used to encode a value into a string suited + * for a cookie's value. + * + * The default function is the global `encodeURIComponent`, which will + * encode a JavaScript string into UTF-8 byte sequences and then URL-encode + * any that fall outside of the cookie range. + */ + encode?: (val: string) => string; + /** + * Specifies the `Date` object to be the value for the `Expires` + * `Set-Cookie` attribute. By default, no expiration is set, and most + * clients will consider this a "non-persistent cookie" and will delete it + * on a condition like exiting a web browser application. + * + * *Note* the cookie storage model specification states that if both + * `expires` and `maxAge` are set, then `maxAge` takes precedence, but it is + * possible not all clients by obey this, so if both are set, they should + * point to the same date and time. + */ + expires?: Date; + /** + * Specifies the boolean value for the `HttpOnly` `Set-Cookie` attribute. + * When truthy, the `HttpOnly` attribute is set, otherwise it is not. By + * default, the `HttpOnly` attribute is not set. + * + * *Note* be careful when setting this to true, as compliant clients will + * not allow client-side JavaScript to see the cookie in `document.cookie`. + */ httpOnly?: boolean; + /** + * Specifies the number (in seconds) to be the value for the `Max-Age` + * `Set-Cookie` attribute. The given number will be converted to an integer + * by rounding down. By default, no maximum age is set. + * + * *Note* the cookie storage model specification states that if both + * `expires` and `maxAge` are set, then `maxAge` takes precedence, but it is + * possible not all clients by obey this, so if both are set, they should + * point to the same date and time. + */ + maxAge?: number; + /** + * Specifies the value for the `Path` `Set-Cookie` attribute. By default, + * the path is considered the "default path". + */ + path?: string; + /** + * Specifies the boolean or string to be the value for the `SameSite` + * `Set-Cookie` attribute. + * + * - `true` will set the `SameSite` attribute to `Strict` for strict same + * site enforcement. + * - `false` will not set the `SameSite` attribute. + * - `'lax'` will set the `SameSite` attribute to Lax for lax same site + * enforcement. + * - `'strict'` will set the `SameSite` attribute to Strict for strict same + * site enforcement. + */ + sameSite?: boolean | 'lax' | 'strict'; + /** + * Specifies the boolean value for the `Secure` `Set-Cookie` attribute. When + * truthy, the `Secure` attribute is set, otherwise it is not. By default, + * the `Secure` attribute is not set. + * + * *Note* be careful when setting this to `true`, as compliant clients will + * not send the cookie back to the server in the future if the browser does + * not have an HTTPS connection. + */ + secure?: boolean; } interface CookieParseOptions { + /** + * Specifies a function that will be used to decode a cookie's value. Since + * the value of a cookie has a limited character set (and must be a simple + * string), this function can be used to decode a previously-encoded cookie + * value into a JavaScript string or other object. + * + * The default function is the global `decodeURIComponent`, which will decode + * any URL-encoded sequences into their byte representations. + * + * *Note* if an error is thrown from this function, the original, non-decoded + * cookie value will be returned as the cookie's value. + */ decode?: (val: string) => string; } -interface CookieStatic { - serialize(name: string, val: string, options?: CookieSerializeOptions): string; - parse(str: string, options?: CookieParseOptions): { [key: string]: string }; -} +/** + * Parse an HTTP Cookie header string and returning an object of all cookie + * name-value pairs. + * + * @param str the string representing a `Cookie` header value + * @param options object containing parsing options + */ +export function parse(str: string, options?: CookieParseOptions): { [key: string]: string }; -declare module "cookie" { - var cookie: CookieStatic; - export = cookie; -} +/** + * Serialize a cookie name-value pair into a `Set-Cookie` header string. + * + * @param name the name for the cookie + * @param val value to set the cookie to + * @param options object containing serialization options + */ +export function serialize(name: string, val: string, options?: CookieSerializeOptions): string; diff --git a/cookies/cookies-tests.ts b/cookies/cookies-tests.ts index 30e07d3000..5a2ad1e4a7 100644 --- a/cookies/cookies-tests.ts +++ b/cookies/cookies-tests.ts @@ -1,5 +1,3 @@ -/// - import * as Cookies from 'cookies'; import * as http from 'http'; diff --git a/cordova-plugin-battery-status/cordova-plugin-battery-status-tests.ts b/cordova-plugin-battery-status/cordova-plugin-battery-status-tests.ts index 4dafa2e966..1c62521293 100644 --- a/cordova-plugin-battery-status/cordova-plugin-battery-status-tests.ts +++ b/cordova-plugin-battery-status/cordova-plugin-battery-status-tests.ts @@ -1,5 +1,3 @@ -/// - window.addEventListener('batterystatus', (ev: BatteryStatusEvent) => { console.log('Battery level is ' + ev.level); }); diff --git a/cordova-plugin-camera/cordova-plugin-camera-tests.ts b/cordova-plugin-camera/cordova-plugin-camera-tests.ts index 00edf02b0a..2f1b661775 100644 --- a/cordova-plugin-camera/cordova-plugin-camera-tests.ts +++ b/cordova-plugin-camera/cordova-plugin-camera-tests.ts @@ -1,5 +1,3 @@ -/// - navigator.camera.getPicture( (data: string) => { alert('Got photo!'); }, (message: string)=> { alert('Failed!: ' + message); }, diff --git a/cordova-plugin-contacts/cordova-plugin-contacts-tests.ts b/cordova-plugin-contacts/cordova-plugin-contacts-tests.ts index c50912c3ba..26243ab43a 100644 --- a/cordova-plugin-contacts/cordova-plugin-contacts-tests.ts +++ b/cordova-plugin-contacts/cordova-plugin-contacts-tests.ts @@ -1,5 +1,3 @@ -/// - var contact: Contact = navigator.contacts.create({ nickname: 'John Smith', displayName: 'John Smith', diff --git a/cordova-plugin-device-motion/cordova-plugin-device-motion-tests.ts b/cordova-plugin-device-motion/cordova-plugin-device-motion-tests.ts index 17b1e49930..1b335beaf7 100644 --- a/cordova-plugin-device-motion/cordova-plugin-device-motion-tests.ts +++ b/cordova-plugin-device-motion/cordova-plugin-device-motion-tests.ts @@ -1,5 +1,3 @@ -/// - navigator.accelerometer.getCurrentAcceleration( (acc: Acceleration) => { console.log('X: ' + acc.x + 'Y: ' + acc.y + 'Z: ' + acc.z); }, () => { alert('Error!'); }); diff --git a/cordova-plugin-device-orientation/cordova-plugin-device-orientation-tests.ts b/cordova-plugin-device-orientation/cordova-plugin-device-orientation-tests.ts index 097a66e99e..ab025d5fbf 100644 --- a/cordova-plugin-device-orientation/cordova-plugin-device-orientation-tests.ts +++ b/cordova-plugin-device-orientation/cordova-plugin-device-orientation-tests.ts @@ -1,5 +1,3 @@ -/// - navigator.compass.getCurrentHeading( (heading: CompassHeading)=> { console.log('Got heading to ' + heading.magneticHeading); }, (error: CompassError)=> { alert('Error! ' + error.code); }, diff --git a/cordova-plugin-device/cordova-plugin-device-tests.ts b/cordova-plugin-device/cordova-plugin-device-tests.ts index 450eadb1f0..cb894785c2 100644 --- a/cordova-plugin-device/cordova-plugin-device-tests.ts +++ b/cordova-plugin-device/cordova-plugin-device-tests.ts @@ -1,3 +1 @@ -/// - console.log(JSON.stringify(device)); \ No newline at end of file diff --git a/cordova-plugin-dialogs/cordova-plugin-dialogs-tests.ts b/cordova-plugin-dialogs/cordova-plugin-dialogs-tests.ts index dd9396f36f..498d7d1000 100644 --- a/cordova-plugin-dialogs/cordova-plugin-dialogs-tests.ts +++ b/cordova-plugin-dialogs/cordova-plugin-dialogs-tests.ts @@ -1,4 +1,2 @@ -/// - navigator.notification.alert('Alert!', () => { alert('You\'re alerted'); }, 'Alert', 'Ok'); navigator.notification.confirm('Are you ok?', (choice: number) => { alert('Your choice is ' + choice); }); diff --git a/cordova-plugin-file-transfer/cordova-plugin-file-transfer-tests.ts b/cordova-plugin-file-transfer/cordova-plugin-file-transfer-tests.ts index 4050b2c4aa..eec24db2e0 100644 --- a/cordova-plugin-file-transfer/cordova-plugin-file-transfer-tests.ts +++ b/cordova-plugin-file-transfer/cordova-plugin-file-transfer-tests.ts @@ -1,5 +1,3 @@ -/// - var file = new FileTransfer(); file.onprogress = (ev: ProgressEvent) => { diff --git a/cordova-plugin-file/cordova-plugin-file-tests.ts b/cordova-plugin-file/cordova-plugin-file-tests.ts index bd9d7de672..37538434e3 100644 --- a/cordova-plugin-file/cordova-plugin-file-tests.ts +++ b/cordova-plugin-file/cordova-plugin-file-tests.ts @@ -1,5 +1,4 @@ /// -/// function fsaccessor(fs: FileSystem) { console.log('FS root is: ' + fs.root.name); diff --git a/cordova-plugin-globalization/cordova-plugin-globalization-tests.ts b/cordova-plugin-globalization/cordova-plugin-globalization-tests.ts index 0a58703a32..4b80f2ff72 100644 --- a/cordova-plugin-globalization/cordova-plugin-globalization-tests.ts +++ b/cordova-plugin-globalization/cordova-plugin-globalization-tests.ts @@ -1,5 +1,3 @@ -/// - navigator.globalization.dateToString(new Date(), (date) => { console.log(JSON.stringify(date)); }, (error) => { alert(error.message); }, diff --git a/cordova-plugin-inappbrowser/cordova-plugin-inappbrowser-tests.ts b/cordova-plugin-inappbrowser/cordova-plugin-inappbrowser-tests.ts index 43b0d28153..cef288c921 100644 --- a/cordova-plugin-inappbrowser/cordova-plugin-inappbrowser-tests.ts +++ b/cordova-plugin-inappbrowser/cordova-plugin-inappbrowser-tests.ts @@ -1,5 +1,3 @@ -/// - // InAppBrowser plugin //---------------------------------------------------------------------- diff --git a/cordova-plugin-keyboard/cordova-plugin-keyboard-tests.ts b/cordova-plugin-keyboard/cordova-plugin-keyboard-tests.ts index 3dce2776bf..767eaa6ed2 100644 --- a/cordova-plugin-keyboard/cordova-plugin-keyboard-tests.ts +++ b/cordova-plugin-keyboard/cordova-plugin-keyboard-tests.ts @@ -1,5 +1,3 @@ -/// - Keyboard.shrinkView(true); Keyboard.shrinkView(false); Keyboard.hideFormAccessoryBar(true); diff --git a/cordova-plugin-media-capture/cordova-plugin-media-capture-tests.ts b/cordova-plugin-media-capture/cordova-plugin-media-capture-tests.ts index 8bd56c714f..91fdefa74f 100644 --- a/cordova-plugin-media-capture/cordova-plugin-media-capture-tests.ts +++ b/cordova-plugin-media-capture/cordova-plugin-media-capture-tests.ts @@ -1,5 +1,3 @@ -/// - console.log('Supported audio modes are: ' + JSON.stringify(navigator.device.capture.supportedAudioModes)); navigator.device.capture.captureAudio( diff --git a/cordova-plugin-media/cordova-plugin-media-tests.ts b/cordova-plugin-media/cordova-plugin-media-tests.ts index 76e39c8d7b..1c00c850e5 100644 --- a/cordova-plugin-media/cordova-plugin-media-tests.ts +++ b/cordova-plugin-media/cordova-plugin-media-tests.ts @@ -1,5 +1,3 @@ -/// - // Media and Media Capture //---------------------------------------------------------------------- diff --git a/cordova-plugin-network-information/cordova-plugin-network-information-tests.ts b/cordova-plugin-network-information/cordova-plugin-network-information-tests.ts index 702aeb5714..0c4bfd7a2d 100644 --- a/cordova-plugin-network-information/cordova-plugin-network-information-tests.ts +++ b/cordova-plugin-network-information/cordova-plugin-network-information-tests.ts @@ -1,5 +1,3 @@ -/// - var connType = navigator.connection.type; if (connType == Connection.WIFI) { console.log('Congratulations, you\'re with fast Internet!'); diff --git a/cordova-plugin-splashscreen/cordova-plugin-splashscreen-tests.ts b/cordova-plugin-splashscreen/cordova-plugin-splashscreen-tests.ts index d24720eb1d..5938396ad4 100644 --- a/cordova-plugin-splashscreen/cordova-plugin-splashscreen-tests.ts +++ b/cordova-plugin-splashscreen/cordova-plugin-splashscreen-tests.ts @@ -1,4 +1,2 @@ -/// - navigator.splashscreen.show(); navigator.splashscreen.hide(); \ No newline at end of file diff --git a/cordova-plugin-statusbar/cordova-plugin-statusbar-tests.ts b/cordova-plugin-statusbar/cordova-plugin-statusbar-tests.ts index 9d22ca912c..623211d6c6 100644 --- a/cordova-plugin-statusbar/cordova-plugin-statusbar-tests.ts +++ b/cordova-plugin-statusbar/cordova-plugin-statusbar-tests.ts @@ -1,6 +1,3 @@ -/// - - var statusBar: StatusBar = window.StatusBar; statusBar.overlaysWebView(true); statusBar.overlaysWebView(false); diff --git a/cordova-plugin-vibration/cordova-plugin-vibration-tests.ts b/cordova-plugin-vibration/cordova-plugin-vibration-tests.ts index b34cd23675..33cdb43436 100644 --- a/cordova-plugin-vibration/cordova-plugin-vibration-tests.ts +++ b/cordova-plugin-vibration/cordova-plugin-vibration-tests.ts @@ -1,5 +1,3 @@ -/// - var notification: Notification; notification.vibrate(100); diff --git a/cordova-plugin-websql/cordova-plugin-websql-tests.ts b/cordova-plugin-websql/cordova-plugin-websql-tests.ts index 8679b3d5c3..c6299a489c 100644 --- a/cordova-plugin-websql/cordova-plugin-websql-tests.ts +++ b/cordova-plugin-websql/cordova-plugin-websql-tests.ts @@ -1,6 +1,3 @@ -/// - - var db = window.openDatabase('Test', '0.1', 'test', 1024 * 1024 * 5); db.transaction( (tx: SqlTransaction) => { diff --git a/core-js/core-js-tests.ts b/core-js/core-js-tests.ts index 42cd770b86..0614b117b9 100644 --- a/core-js/core-js-tests.ts +++ b/core-js/core-js-tests.ts @@ -8,7 +8,7 @@ let s: string; let i: number; let b: boolean; let f: () => void; -let o: Object; +let o: {}; let r: RegExp; let sym: symbol; let e: Error; @@ -21,7 +21,7 @@ let arrayOfPoint3D: Point3D[]; let arrayOfSymbol: symbol[]; let arrayOfPropertyKey: PropertyKey[]; let arrayOfAny: any[]; -let arrayOfStringAny: [string, any][]; +let arrayOfStringAny: Array<[string, any]>; let arrayLikeOfAny: ArrayLike; let iterableOfPoint: Iterable; let iterableOfStringPoint: Iterable<[string, Point]>; @@ -57,7 +57,7 @@ let dictOfAny: Dict; // ############################################################################################# // ECMAScript 6: Object & Function -// Modules: es6.object.assign, es6.object.is, es6.object.set-prototype-of, +// Modules: es6.object.assign, es6.object.is, es6.object.set-prototype-of, // es6.object.to-string, es6.function.name and es6.function.has-instance. // ############################################################################################# @@ -88,8 +88,8 @@ arrayOfPoint = Array.of(point, point); // ############################################################################################# // ECMAScript 6: String & RegExp -// Modules: es6.string.from-code-point, es6.string.raw, es6.string.code-point-at, -// es6.string.ends-with, es6.string.includes, es6.string.repeat, +// Modules: es6.string.from-code-point, es6.string.raw, es6.string.code-point-at, +// es6.string.ends-with, es6.string.includes, es6.string.repeat, // es6.string.starts-with, and es6.regexp // ############################################################################################# diff --git a/core-js/index.d.ts b/core-js/index.d.ts index 7dda59aab3..4191cd11aa 100644 --- a/core-js/index.d.ts +++ b/core-js/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for core-js v0.9.7 +// Type definitions for core-js 0.9 // Project: https://github.com/zloirock/core-js/ // Definitions by: Ron Buckton // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /* ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. @@ -18,539 +19,12 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ -declare type PropertyKey = string | number | symbol; - -// ############################################################################################# -// ECMAScript 6: Object & Function -// Modules: es6.object.assign, es6.object.is, es6.object.set-prototype-of, -// es6.object.to-string, es6.function.name and es6.function.has-instance. -// ############################################################################################# - -interface ObjectConstructor { - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param source The source object from which to copy properties. - */ - assign(target: T, source: U): T & U; - - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param source1 The first source object from which to copy properties. - * @param source2 The second source object from which to copy properties. - */ - assign(target: T, source1: U, source2: V): T & U & V; - - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param source1 The first source object from which to copy properties. - * @param source2 The second source object from which to copy properties. - * @param source3 The third source object from which to copy properties. - */ - assign(target: T, source1: U, source2: V, source3: W): T & U & V & W; - - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param sources One or more source objects from which to copy properties - */ - assign(target: any, ...sources: any[]): any; - - /** - * Returns true if the values are the same value, false otherwise. - * @param value1 The first value. - * @param value2 The second value. - */ - is(value1: any, value2: any): boolean; - - /** - * Sets the prototype of a specified object o to object proto or null. Returns the object o. - * @param o The object to change its prototype. - * @param proto The value of the new prototype or null. - * @remarks Requires `__proto__` support. - */ - setPrototypeOf(o: any, proto: any): any; -} - -interface Function { - /** - * Returns the name of the function. Function names are read-only and can not be changed. - */ - name: string; - - /** - * Determines if a constructor object recognizes an object as one of the - * constructor’s instances. - * @param value The object to test. - */ - [Symbol.hasInstance](value: any): boolean; -} - -// ############################################################################################# -// ECMAScript 6: Array -// Modules: es6.array.from, es6.array.of, es6.array.copy-within, es6.array.fill, es6.array.find, -// and es6.array.find-index -// ############################################################################################# - -interface Array { - /** - * Returns the value of the first element in the array where predicate is true, and undefined - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, find - * immediately returns that element value. Otherwise, find returns undefined. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - find(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): T; - - /** - * Returns the index of the first element in the array where predicate is true, and undefined - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, find - * immediately returns that element value. Otherwise, find returns undefined. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - findIndex(predicate: (value: T) => boolean, thisArg?: any): number; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: T, start?: number, end?: number): T[]; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): T[]; - - [Symbol.unscopables]: any; -} - -interface ArrayConstructor { - /** - * Creates an array from an array-like object. - * @param arrayLike An array-like object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): Array; - - /** - * Creates an array from an iterable object. - * @param iterable An iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(iterable: Iterable, mapfn: (v: T, k: number) => U, thisArg?: any): Array; - - /** - * Creates an array from an array-like object. - * @param arrayLike An array-like object to convert to an array. - */ - from(arrayLike: ArrayLike): Array; - - /** - * Creates an array from an iterable object. - * @param iterable An iterable object to convert to an array. - */ - from(iterable: Iterable): Array; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: T[]): Array; -} - -// ############################################################################################# -// ECMAScript 6: String & RegExp -// Modules: es6.string.from-code-point, es6.string.raw, es6.string.code-point-at, -// es6.string.ends-with, es6.string.includes, es6.string.repeat, -// es6.string.starts-with, and es6.regexp -// ############################################################################################# - -interface String { - /** - * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point - * value of the UTF-16 encoded code point starting at the string element at position pos in - * the String resulting from converting this object to a String. - * If there is no element at that position, the result is undefined. - * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. - */ - codePointAt(pos: number): number; - - /** - * Returns true if searchString appears as a substring of the result of converting this - * object to a String, at one or more positions that are - * greater than or equal to position; otherwise, returns false. - * @param searchString search string - * @param position If position is undefined, 0 is assumed, so as to search all of the String. - */ - includes(searchString: string, position?: number): boolean; - - /** - * Returns true if the sequence of elements of searchString converted to a String is the - * same as the corresponding elements of this object (converted to a String) starting at - * endPosition – length(this). Otherwise returns false. - */ - endsWith(searchString: string, endPosition?: number): boolean; - - /** - * Returns a String value that is made from count copies appended together. If count is 0, - * T is the empty String is returned. - * @param count number of copies to append - */ - repeat(count: number): string; - - /** - * Returns true if the sequence of elements of searchString converted to a String is the - * same as the corresponding elements of this object (converted to a String) starting at - * position. Otherwise returns false. - */ - startsWith(searchString: string, position?: number): boolean; -} - -interface StringConstructor { - /** - * Return the String value whose elements are, in order, the elements in the List elements. - * If length is 0, the empty string is returned. - */ - fromCodePoint(...codePoints: number[]): string; - - /** - * String.raw is intended for use as a tag function of a Tagged Template String. When called - * as such the first argument will be a well formed template call site object and the rest - * parameter will contain the substitution values. - * @param template A well-formed template string call site representation. - * @param substitutions A set of substitution values. - */ - raw(template: TemplateStringsArray, ...substitutions: any[]): string; -} - -interface RegExp { - /** - * Returns a string indicating the flags of the regular expression in question. This field is read-only. - * The characters in this string are sequenced and concatenated in the following order: - * - * - "g" for global - * - "i" for ignoreCase - * - "m" for multiline - * - "u" for unicode - * - "y" for sticky - * - * If no flags are set, the value is the empty string. - */ - flags: string; -} - -// ############################################################################################# -// ECMAScript 6: Number & Math -// Modules: es6.number.constructor, es6.number.statics, and es6.math -// ############################################################################################# - -interface NumberConstructor { - /** - * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 - * that is representable as a Number value, which is approximately: - * 2.2204460492503130808472633361816 x 10‍−‍16. - */ - EPSILON: number; - - /** - * Returns true if passed value is finite. - * Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a - * number. Only finite values of the type number, result in true. - * @param number A numeric value. - */ - isFinite(number: number): boolean; - - /** - * Returns true if the value passed is an integer, false otherwise. - * @param number A numeric value. - */ - isInteger(number: number): boolean; - - /** - * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a - * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter - * to a number. Only values of the type number, that are also NaN, result in true. - * @param number A numeric value. - */ - isNaN(number: number): boolean; - - /** - * Returns true if the value passed is a safe integer. - * @param number A numeric value. - */ - isSafeInteger(number: number): boolean; - - /** - * The value of the largest integer n such that n and n + 1 are both exactly representable as - * a Number value. - * The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 − 1. - */ - MAX_SAFE_INTEGER: number; - - /** - * The value of the smallest integer n such that n and n − 1 are both exactly representable as - * a Number value. - * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)). - */ - MIN_SAFE_INTEGER: number; - - /** - * Converts a string to a floating-point number. - * @param string A string that contains a floating-point number. - */ - parseFloat(string: string): number; - - /** - * Converts A string to an integer. - * @param s A string to convert into a number. - * @param radix A value between 2 and 36 that specifies the base of the number in numString. - * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. - * All other strings are considered decimal. - */ - parseInt(string: string, radix?: number): number; -} - -interface Math { - /** - * Returns the number of leading zero bits in the 32-bit binary representation of a number. - * @param x A numeric expression. - */ - clz32(x: number): number; - - /** - * Returns the result of 32-bit multiplication of two numbers. - * @param x First number - * @param y Second number - */ - imul(x: number, y: number): number; - - /** - * Returns the sign of the x, indicating whether x is positive, negative or zero. - * @param x The numeric expression to test - */ - sign(x: number): number; - - /** - * Returns the base 10 logarithm of a number. - * @param x A numeric expression. - */ - log10(x: number): number; - - /** - * Returns the base 2 logarithm of a number. - * @param x A numeric expression. - */ - log2(x: number): number; - - /** - * Returns the natural logarithm of 1 + x. - * @param x A numeric expression. - */ - log1p(x: number): number; - - /** - * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of - * the natural logarithms). - * @param x A numeric expression. - */ - expm1(x: number): number; - - /** - * Returns the hyperbolic cosine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - cosh(x: number): number; - - /** - * Returns the hyperbolic sine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - sinh(x: number): number; - - /** - * Returns the hyperbolic tangent of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - tanh(x: number): number; - - /** - * Returns the inverse hyperbolic cosine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - acosh(x: number): number; - - /** - * Returns the inverse hyperbolic sine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - asinh(x: number): number; - - /** - * Returns the inverse hyperbolic tangent of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - atanh(x: number): number; - - /** - * Returns the square root of the sum of squares of its arguments. - * @param values Values to compute the square root for. - * If no arguments are passed, the result is +0. - * If there is only one argument, the result is the absolute value. - * If any argument is +Infinity or -Infinity, the result is +Infinity. - * If any argument is NaN, the result is NaN. - * If all arguments are either +0 or −0, the result is +0. - */ - hypot(...values: number[]): number; - - /** - * Returns the integral part of the a numeric expression, x, removing any fractional digits. - * If x is already an integer, the result is x. - * @param x A numeric expression. - */ - trunc(x: number): number; - - /** - * Returns the nearest single precision float representation of a number. - * @param x A numeric expression. - */ - fround(x: number): number; - - /** - * Returns an implementation-dependent approximation to the cube root of number. - * @param x A numeric expression. - */ - cbrt(x: number): number; -} - // ############################################################################################# // ECMAScript 6: Symbols // Modules: es6.symbol // ############################################################################################# -interface Symbol { - /** Returns a string representation of an object. */ - toString(): string; - - [Symbol.toStringTag]: string; -} - interface SymbolConstructor { - /** - * A reference to the prototype. - */ - prototype: Symbol; - - /** - * Returns a new unique Symbol value. - * @param description Description of the new Symbol object. - */ - (description?: string|number): symbol; - - /** - * Returns a Symbol object from the global symbol registry matching the given key if found. - * Otherwise, returns a new symbol with this key. - * @param key key to search for. - */ - for(key: string): symbol; - - /** - * Returns a key from the global symbol registry matching the given Symbol if found. - * Otherwise, returns a undefined. - * @param sym Symbol to find the key for. - */ - keyFor(sym: symbol): string; - - // Well-known Symbols - - /** - * A method that determines if a constructor object recognizes an object as one of the - * constructor’s instances. Called by the semantics of the instanceof operator. - */ - hasInstance: symbol; - - /** - * A Boolean value that if true indicates that an object should flatten to its array elements - * by Array.prototype.concat. - */ - isConcatSpreadable: symbol; - - /** - * A method that returns the default iterator for an object. Called by the semantics of the - * for-of statement. - */ - iterator: symbol; - - /** - * A regular expression method that matches the regular expression against a string. Called - * by the String.prototype.match method. - */ - match: symbol; - - /** - * A regular expression method that replaces matched substrings of a string. Called by the - * String.prototype.replace method. - */ - replace: symbol; - - /** - * A regular expression method that returns the index within a string that matches the - * regular expression. Called by the String.prototype.search method. - */ - search: symbol; - - /** - * A function valued property that is the constructor function that is used to create - * derived objects. - */ - species: symbol; - - /** - * A regular expression method that splits a string at the indices that match the regular - * expression. Called by the String.prototype.split method. - */ - split: symbol; - - /** - * A method that converts an object to a corresponding primitive value.Called by the ToPrimitive - * abstract operation. - */ - toPrimitive: symbol; - - /** - * A String value that is used in the creation of the default string description of an object. - * Called by the built-in method Object.prototype.toString. - */ - toStringTag: symbol; - - /** - * An Object whose own property names are property names that are excluded from the with - * environment bindings of the associated objects. - */ - unscopables: symbol; - /** * Non-standard. Use simple mode for core-js symbols. See https://github.com/zloirock/core-js/#caveats-when-using-symbol-polyfill */ @@ -562,193 +36,6 @@ interface SymbolConstructor { userSetter(): void; } -declare var Symbol: SymbolConstructor; - -interface Object { - /** - * Determines whether an object has a property with the specified name. - * @param v A property name. - */ - hasOwnProperty(v: PropertyKey): boolean; - - /** - * Determines whether a specified property is enumerable. - * @param v A property name. - */ - propertyIsEnumerable(v: PropertyKey): boolean; -} - -interface ObjectConstructor { - /** - * Returns an array of all symbol properties found directly on object o. - * @param o Object to retrieve the symbols from. - */ - getOwnPropertySymbols(o: any): symbol[]; - - /** - * Gets the own property descriptor of the specified object. - * An own property descriptor is one that is defined directly on the object and is not - * inherited from the object's prototype. - * @param o Object that contains the property. - * @param p Name of the property. - */ - getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor; - - /** - * Adds a property to an object, or modifies attributes of an existing property. - * @param o Object on which to add or modify the property. This can be a native JavaScript - * object (that is, a user-defined object or a built in object) or a DOM object. - * @param p The property name. - * @param attributes Descriptor for the property. It can be for a data property or an accessor - * property. - */ - defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; -} - -interface Math { - [Symbol.toStringTag]: string; -} - -interface JSON { - [Symbol.toStringTag]: string; -} - -// ############################################################################################# -// ECMAScript 6: Collections -// Modules: es6.map, es6.set, es6.weak-map, and es6.weak-set -// ############################################################################################# - -interface Map { - clear(): void; - delete(key: K): boolean; - forEach(callbackfn: (value: V, index: K, map: Map) => void, thisArg?: any): void; - get(key: K): V; - has(key: K): boolean; - set(key: K, value?: V): Map; - size: number; -} - -interface MapConstructor { - new (): Map; - new (iterable: Iterable<[K, V]>): Map; - prototype: Map; -} - -declare var Map: MapConstructor; - -interface Set { - add(value: T): Set; - clear(): void; - delete(value: T): boolean; - forEach(callbackfn: (value: T, index: T, set: Set) => void, thisArg?: any): void; - has(value: T): boolean; - size: number; -} - -interface SetConstructor { - new (): Set; - new (iterable: Iterable): Set; - prototype: Set; -} - -declare var Set: SetConstructor; - -interface WeakMap { - delete(key: K): boolean; - get(key: K): V; - has(key: K): boolean; - set(key: K, value?: V): WeakMap; -} - -interface WeakMapConstructor { - new (): WeakMap; - new (iterable: Iterable<[K, V]>): WeakMap; - prototype: WeakMap; -} - -declare var WeakMap: WeakMapConstructor; - -interface WeakSet { - add(value: T): WeakSet; - delete(value: T): boolean; - has(value: T): boolean; -} - -interface WeakSetConstructor { - new (): WeakSet; - new (iterable: Iterable): WeakSet; - prototype: WeakSet; -} - -declare var WeakSet: WeakSetConstructor; - -// ############################################################################################# -// ECMAScript 6: Iterators -// Modules: es6.string.iterator, es6.array.iterator, es6.map, es6.set, web.dom.iterable -// ############################################################################################# - -interface IteratorResult { - done: boolean; - value?: T; -} - -interface Iterator { - next(value?: any): IteratorResult; - return?(value?: any): IteratorResult; - throw?(e?: any): IteratorResult; -} - -interface Iterable { - [Symbol.iterator](): Iterator; -} - -interface IterableIterator extends Iterator { - [Symbol.iterator](): IterableIterator; -} - -interface String { - /** Iterator */ - [Symbol.iterator](): IterableIterator; -} - -interface Array { - /** Iterator */ - [Symbol.iterator](): IterableIterator; - - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, T]>; - - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; - - /** - * Returns an list of values in the array - */ - values(): IterableIterator; -} - -interface Map { - entries(): IterableIterator<[K, V]>; - keys(): IterableIterator; - values(): IterableIterator; - [Symbol.iterator](): IterableIterator<[K, V]>; -} - -interface Set { - entries(): IterableIterator<[T, T]>; - keys(): IterableIterator; - values(): IterableIterator; - [Symbol.iterator](): IterableIterator; -} - -interface NodeList { - [Symbol.iterator](): IterableIterator; -} - interface $for extends IterableIterator { of(callbackfn: (value: T, key: any) => void, thisArg?: any): void; array(): T[]; @@ -759,135 +46,6 @@ interface $for extends IterableIterator { declare function $for(iterable: Iterable): $for; -// ############################################################################################# -// ECMAScript 6: Promises -// Modules: es6.promise -// ############################################################################################# - -interface PromiseLike { - /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of which ever callback is executed. - */ - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): PromiseLike; - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): PromiseLike; -} - -/** - * Represents the completion of an asynchronous operation - */ -interface Promise { - /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of which ever callback is executed. - */ - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; - - /** - * Attaches a callback for only the rejection of the Promise. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of the callback. - */ - catch(onrejected?: (reason: any) => T | PromiseLike): Promise; - catch(onrejected?: (reason: any) => void): Promise; -} - -interface PromiseConstructor { - /** - * A reference to the prototype. - */ - prototype: Promise; - - /** - * Creates a new Promise. - * @param executor A callback used to initialize the promise. This callback is passed two arguments: - * a resolve callback used resolve the promise with a value or the result of another promise, - * and a reject callback used to reject the promise with a provided reason or error. - */ - new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>; - all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; - all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; - all(values: Iterable>): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: Iterable>): Promise; - - /** - * Creates a new rejected promise for the provided reason. - * @param reason The reason the promise was rejected. - * @returns A new rejected Promise. - */ - reject(reason: any): Promise; - - /** - * Creates a new rejected promise for the provided reason. - * @param reason The reason the promise was rejected. - * @returns A new rejected Promise. - */ - reject(reason: any): Promise; - - /** - * Creates a new resolved promise for the provided value. - * @param value A promise. - * @returns A promise whose internal state matches the provided promise. - */ - resolve(value: T | PromiseLike): Promise; - - /** - * Creates a new resolved promise . - * @returns A resolved promise. - */ - resolve(): Promise; -} - -declare var Promise: PromiseConstructor; - -// ############################################################################################# -// ECMAScript 6: Reflect -// Modules: es6.reflect -// ############################################################################################# - -declare namespace Reflect { - function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; - function construct(target: Function, argumentsList: ArrayLike, newTarget?: any): any; - function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; - function deleteProperty(target: any, propertyKey: PropertyKey): boolean; - function enumerate(target: any): IterableIterator; - function get(target: any, propertyKey: PropertyKey, receiver?: any): any; - function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; - function getPrototypeOf(target: any): any; - function has(target: any, propertyKey: PropertyKey): boolean; - function isExtensible(target: any): boolean; - function ownKeys(target: any): Array; - function preventExtensions(target: any): boolean; - function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; - function setPrototypeOf(target: any, proto: any): boolean; -} - // ############################################################################################# // ECMAScript 7 // Modules: es7.array.includes, es7.string.at, es7.string.pad-start, es7.string.pad-end, @@ -895,19 +53,11 @@ declare namespace Reflect { // es7.map.to-json, and es7.set.to-json // ############################################################################################# -interface Array { - includes(value: T, fromIndex?: number): boolean; -} - interface String { at(index: number): string; - padStart(length: number, fillStr?: string): string; - padEnd(length: number, fillStr?: string): string; } -interface ObjectConstructor { - values(object: any): any[]; - entries(object: any): [string, any][]; +interface Object { getOwnPropertyDescriptors(object: any): PropertyDescriptorMap; } @@ -942,7 +92,7 @@ interface ArrayConstructor { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(array: ArrayLike, ...items: (T[]| T)[]): T[]; + concat(array: ArrayLike, ...items: Array): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. @@ -969,19 +119,13 @@ interface ArrayConstructor { */ sort(array: ArrayLike, compareFn?: (a: T, b: T) => number): T[]; - /** - * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. - * @param start The zero-based location in the array from which to start removing elements. - */ - splice(array: ArrayLike, start: number): T[]; - /** * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. * @param start The zero-based location in the array from which to start removing elements. * @param deleteCount The number of elements to remove. * @param items Elements to insert into the array in place of the deleted elements. */ - splice(array: ArrayLike, start: number, deleteCount: number, ...items: T[]): T[]; + splice(array: ArrayLike, start: number, deleteCount?: number, ...items: T[]): T[]; /** * Inserts new elements at the start of an array. @@ -1005,14 +149,16 @@ interface ArrayConstructor { /** * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. + * @param callbackfn A function that accepts up to three arguments. + * The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ every(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; /** * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. + * @param callbackfn A function that accepts up to three arguments. + * The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ some(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; @@ -1039,30 +185,38 @@ interface ArrayConstructor { filter(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[]; /** - * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * Calls the specified callback function for all the elements in an array. + * The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. + * The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduce(array: ArrayLike, callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; /** - * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * Calls the specified callback function for all the elements in an array. + * The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. + * The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduce(array: ArrayLike, callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; /** - * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. + * The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduceRight(array: ArrayLike, callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; /** - * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. + * The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduceRight(array: ArrayLike, callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; @@ -1090,7 +244,7 @@ interface ArrayConstructor { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(array: ArrayLike, predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): T; + find(array: ArrayLike, predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): T; /** * Returns the index of the first element in the array where predicate is true, and undefined @@ -1125,8 +279,8 @@ interface ArrayConstructor { copyWithin(array: ArrayLike, target: number, start: number, end?: number): T[]; includes(array: ArrayLike, value: T, fromIndex?: number): boolean; - turn(array: ArrayLike, callbackfn: (memo: U, value: T, index: number, array: Array) => void, memo?: U): U; - turn(array: ArrayLike, callbackfn: (memo: Array, value: T, index: number, array: Array) => void, memo?: Array): Array; + turn(array: ArrayLike, callbackfn: (memo: U, value: T, index: number, array: T[]) => void, memo?: U): U; + turn(array: ArrayLike, callbackfn: (memo: T[], value: T, index: number, array: T[]) => void, memo?: T[]): T[]; } // ############################################################################################# @@ -1180,7 +334,7 @@ declare var log: Log; interface Dict { [key: string]: T; [key: number]: T; - //[key: symbol]: T; + // [key: symbol]: T; } interface DictConstructor { @@ -1257,12 +411,12 @@ interface Array { /** * Non-standard. */ - turn(callbackfn: (memo: U, value: T, index: number, array: Array) => void, memo?: U): U; + turn(callbackfn: (memo: U, value: T, index: number, array: T[]) => void, memo?: U): U; /** * Non-standard. */ - turn(callbackfn: (memo: Array, value: T, index: number, array: Array) => void, memo?: Array): Array; + turn(callbackfn: (memo: T[], value: T, index: number, array: T[]) => void, memo?: T[]): T[]; } // ############################################################################################# @@ -1313,10 +467,9 @@ declare namespace core { function get(target: any, propertyKey: PropertyKey, receiver?: any): any; function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; function getPrototypeOf(target: any): any; - function has(target: any, propertyKey: string): boolean; - function has(target: any, propertyKey: symbol): boolean; + function has(target: any, propertyKey: string | symbol): boolean; function isExtensible(target: any): boolean; - function ownKeys(target: any): Array; + function ownKeys(target: any): PropertyKey[]; function preventExtensions(target: any): boolean; function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; function setPrototypeOf(target: any, proto: any): boolean; @@ -1324,10 +477,8 @@ declare namespace core { var Object: { getPrototypeOf(o: any): any; - getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor; getOwnPropertyNames(o: any): string[]; create(o: any, properties?: PropertyDescriptorMap): any; - defineProperty(o: any, p: string, attributes: PropertyDescriptor): any; defineProperties(o: any, properties: PropertyDescriptorMap): any; seal(o: T): T; freeze(o: T): T; @@ -1357,21 +508,18 @@ declare namespace core { }; var Array: { - from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): Array; - from(iterable: Iterable, mapfn: (v: T, k: number) => U, thisArg?: any): Array; - from(arrayLike: ArrayLike): Array; - from(iterable: Iterable): Array; - of(...items: T[]): Array; + from(arrayLike: ArrayLike | Iterable, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; + from(arrayLike: ArrayLike | Iterable): T[]; + of(...items: T[]): T[]; push(array: ArrayLike, ...items: T[]): number; pop(array: ArrayLike): T; - concat(array: ArrayLike, ...items: (T[]| T)[]): T[]; + concat(array: ArrayLike, ...items: Array): T[]; join(array: ArrayLike, separator?: string): string; reverse(array: ArrayLike): T[]; shift(array: ArrayLike): T; slice(array: ArrayLike, start?: number, end?: number): T[]; sort(array: ArrayLike, compareFn?: (a: T, b: T) => number): T[]; - splice(array: ArrayLike, start: number): T[]; - splice(array: ArrayLike, start: number, deleteCount: number, ...items: T[]): T[]; + splice(array: ArrayLike, start: number, deleteCount?: number, ...items: T[]): T[]; unshift(array: ArrayLike, ...items: T[]): number; indexOf(array: ArrayLike, searchElement: T, fromIndex?: number): number; lastIndexOf(array: ArrayLike, earchElement: T, fromIndex?: number): number; @@ -1387,13 +535,13 @@ declare namespace core { entries(array: ArrayLike): IterableIterator<[number, T]>; keys(array: ArrayLike): IterableIterator; values(array: ArrayLike): IterableIterator; - find(array: ArrayLike, predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): T; + find(array: ArrayLike, predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): T; findIndex(array: ArrayLike, predicate: (value: T) => boolean, thisArg?: any): number; fill(array: ArrayLike, value: T, start?: number, end?: number): T[]; copyWithin(array: ArrayLike, target: number, start: number, end?: number): T[]; includes(array: ArrayLike, value: T, fromIndex?: number): boolean; - turn(array: ArrayLike, callbackfn: (memo: Array, value: T, index: number, array: Array) => void, memo?: Array): Array; - turn(array: ArrayLike, callbackfn: (memo: U, value: T, index: number, array: Array) => void, memo?: U): U; + turn(array: ArrayLike, callbackfn: (memo: T[], value: T, index: number, array: T[]) => void, memo?: T[]): T[]; + turn(array: ArrayLike, callbackfn: (memo: U, value: T, index: number, array: T[]) => void, memo?: U): U; }; var String: { @@ -1782,8 +930,7 @@ declare module "core-js/fn/function/has-instance" { var hasInstance: (value: any) => boolean; export = hasInstance; } -declare module "core-js/fn/function/name" -{ +declare module "core-js/fn/function/name" { } declare module "core-js/fn/function/part" { var part: typeof core.Function.part; diff --git a/core-js/tsconfig.json b/core-js/tsconfig.json index b37502a626..8c7007b563 100644 --- a/core-js/tsconfig.json +++ b/core-js/tsconfig.json @@ -2,8 +2,9 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es5", - "dom" + "es2017", + "dom", + "dom.iterable" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/mobservable/tslint.json b/core-js/tslint.json similarity index 97% rename from mobservable/tslint.json rename to core-js/tslint.json index f05741c59b..0f47deabb4 100644 --- a/mobservable/tslint.json +++ b/core-js/tslint.json @@ -3,4 +3,4 @@ "rules": { "forbidden-types": false } -} +} \ No newline at end of file diff --git a/cors/index.d.ts b/cors/index.d.ts index ecad80d187..6c1fc3e4c3 100644 --- a/cors/index.d.ts +++ b/cors/index.d.ts @@ -10,7 +10,7 @@ import express = require('express'); type CustomOrigin = ( requestOrigin: string, - callback: (err: Error, allow?: boolean) => void + callback: (err: Error | null, allow?: boolean) => void ) => void; declare namespace e { diff --git a/cryptojs/test/md5-tests.ts b/cryptojs/test/md5-tests.ts index d44496aae5..4063750d7d 100644 --- a/cryptojs/test/md5-tests.ts +++ b/cryptojs/test/md5-tests.ts @@ -1,6 +1,3 @@ -/// - - YUI.add('algo-md5-test', function (Y) { var C = CryptoJS; diff --git a/css-modules-require-hook/css-modules-require-hook-tests.ts b/css-modules-require-hook/css-modules-require-hook-tests.ts index 0e2e366f96..ea80474dc5 100644 --- a/css-modules-require-hook/css-modules-require-hook-tests.ts +++ b/css-modules-require-hook/css-modules-require-hook-tests.ts @@ -1,4 +1,3 @@ -/// /// import * as hook from 'css-modules-require-hook'; diff --git a/csv-parse/csv-parse-tests.ts b/csv-parse/csv-parse-tests.ts index 21df979d82..b0f13121fe 100644 --- a/csv-parse/csv-parse-tests.ts +++ b/csv-parse/csv-parse-tests.ts @@ -2,27 +2,27 @@ import parse = require('csv-parse'); function callbackAPITest() { var input = '#Welcome\n"1","2","3","4"\n"a","b","c","d"'; - parse(input, {comment: '#'}, function(err, output){ - output.should.eql([ [ '1', '2', '3', '4' ], [ 'a', 'b', 'c', 'd' ] ]); + parse(input, {comment: '#'}, (err, output) => { + output.should.eql([ [ '1', '2', '3', '4' ], [ 'a', 'b', 'c', 'd' ] ]); }); } function streamAPITest() { - let output:string[][] = []; + let output: string[][] = []; // Create the parser var parser = parse({delimiter: ':'}); let record: string[]; // Use the writable stream api - parser.on('readable', function(){ - while(record = parser.read()){ + parser.on('readable', () => { + while (record = parser.read()) { output.push(record); } }); // Catch any error - parser.on('error', function(err: any){ + parser.on('error', (err: any) => { console.log(err.message); }); - parser.on('finish', function(){ + parser.on('finish', () => { console.log(output); }); // Now that setup is done, write data to the stream @@ -37,12 +37,12 @@ import fs = require('fs'); function pipeFunctionTest() { var transform = require('stream-transform'); - var output:any = []; + var output: any = []; var parser = parse({delimiter: ':'}) var input = fs.createReadStream('/etc/passwd'); - var transformer = transform(function(record: any[], callback: any){ - setTimeout(function(){ - callback(null, record.join(' ')+'\n'); + var transformer = transform((record: any[], callback: any) => { + setTimeout(() => { + callback(null, record.join(' ') + '\n'); }, 500); }, {parallel: 10}); input.pipe(parser).pipe(transformer).pipe(process.stdout); diff --git a/csv-parse/index.d.ts b/csv-parse/index.d.ts index 5cdfe164ef..e780bac27d 100644 --- a/csv-parse/index.d.ts +++ b/csv-parse/index.d.ts @@ -1,136 +1,120 @@ -// Type definitions for csv-parse 1.1.0 +// Type definitions for csv-parse 1.1 // Project: https://github.com/wdavidw/node-csv-parse // Definitions by: David Muller // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -declare module "csv-parse/types" { - interface callbackFn { - (err: any, output: any): void - } +import * as stream from "stream"; - interface nameCallback { - (line1: any[]): boolean | string[] - } +export = parse; - interface options { - /*** - * Set the field delimiter. One character only, defaults to comma. - */ - delimiter?: string; +declare function parse(input: string, options?: parse.Options, callback?: parse.Callback): any; +declare function parse(options?: parse.Options, callback?: parse.Callback): any; +declare function parse(callback?: parse.Callback): any; +declare namespace parse { + type Callback = (err: any, output: any) => void; - /*** - * String used to delimit record rows or a special value; special constants are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified). - */ - rowDelimiter?: string; - /*** - * Optional character surrounding a field, one character only, defaults to double quotes. - */ - quote?: string - - /*** - * Set the escape character, one character only, defaults to double quotes. - */ - escape?: string - - /*** - * List of fields as an array, a user defined callback accepting the first line and returning the column names or true if autodiscovered in the first CSV line, default to null, affect the result data set in the sense that records will be objects instead of arrays. - */ - columns?: any[]|boolean|nameCallback; - - /*** - * Treat all the characters after this one as a comment, default to '' (disabled). - */ - comment?: string - - /*** - * Name of header-record title to name objects by. - */ - objname?: string - - /*** - * Preserve quotes inside unquoted field. - */ - relax?: boolean - - /*** - * Discard inconsistent columns count, default to false. - */ - relax_column_count?: boolean - - /*** - * Dont generate empty values for empty lines. - */ - skip_empty_lines?: boolean - - /*** - * Maximum numer of characters to be contained in the field and line buffers before an exception is raised, used to guard against a wrong delimiter or rowDelimiter, default to 128000 characters. - */ - max_limit_on_data_read?: number - - /*** - * If true, ignore whitespace immediately around the delimiter, defaults to false. Does not remove whitespace in a quoted field. - */ - trim?: boolean - - /*** - * If true, ignore whitespace immediately following the delimiter (i.e. left-trim all fields), defaults to false. Does not remove whitespace in a quoted field. - */ - ltrim?: boolean - - /*** - * If true, ignore whitespace immediately preceding the delimiter (i.e. right-trim all fields), defaults to false. Does not remove whitespace in a quoted field. - */ - rtrim?: boolean - - /*** - * If true, the parser will attempt to convert read data types to native types. - */ - auto_parse?: boolean - - /*** - * If true, the parser will attempt to convert read data types to dates. It requires the "auto_parse" option. - */ - auto_parse_date?: boolean - } - - import * as stream from "stream"; - - interface Parser extends stream.Transform { + interface Parser extends stream.Transform {} + class Parser { + constructor(options: Options); __push(line: any): any ; __write(chars: any, end: any, callback: any): any; } - interface ParserConstructor { - new (options: options): Parser; + interface Options { + /** + * Set the field delimiter. One character only, defaults to comma. + */ + delimiter?: string; + + /** + * String used to delimit record rows or a special value; + * special constants are 'auto', 'unix', 'mac', 'windows', 'unicode'; + * defaults to 'auto' (discovered in source or 'unix' if no source is specified). + */ + rowDelimiter?: string; + /** + * Optional character surrounding a field, one character only, defaults to double quotes. + */ + quote?: string + + /** + * Set the escape character, one character only, defaults to double quotes. + */ + escape?: string + + /** + * List of fields as an array, + * a user defined callback accepting the first line and returning the column names or true if autodiscovered in the first CSV line, + * default to null, + * affect the result data set in the sense that records will be objects instead of arrays. + */ + columns?: any[] | boolean | ((line1: any[]) => boolean | string[]); + + /** + * Treat all the characters after this one as a comment, default to '' (disabled). + */ + comment?: string + + /** + * Name of header-record title to name objects by. + */ + objname?: string + + /** + * Preserve quotes inside unquoted field. + */ + relax?: boolean + + /** + * Discard inconsistent columns count, default to false. + */ + relax_column_count?: boolean + + /** + * Dont generate empty values for empty lines. + */ + skip_empty_lines?: boolean + + /** + * Maximum numer of characters to be contained in the field and line buffers before an exception is raised, + * used to guard against a wrong delimiter or rowDelimiter, + * default to 128000 characters. + */ + max_limit_on_data_read?: number + + /** + * If true, ignore whitespace immediately around the delimiter, defaults to false. + * Does not remove whitespace in a quoted field. + */ + trim?: boolean + + /** + * If true, ignore whitespace immediately following the delimiter (i.e. left-trim all fields), defaults to false. + * Does not remove whitespace in a quoted field. + */ + ltrim?: boolean + + /** + * If true, ignore whitespace immediately preceding the delimiter (i.e. right-trim all fields), defaults to false. + * Does not remove whitespace in a quoted field. + */ + rtrim?: boolean + + /** + * If true, the parser will attempt to convert read data types to native types. + */ + auto_parse?: boolean + + /** + * If true, the parser will attempt to convert read data types to dates. It requires the "auto_parse" option. + */ + auto_parse_date?: boolean } + // TODO: what is this for? interface ParserStream extends NodeJS.ReadWriteStream { read(size?: number): any & string[]; } - - interface parse { - (input: string, options?: options, callback?: callbackFn): any; - (options: options, callback: callbackFn): any; - (callback: callbackFn): any; - (options?: options): ParserStream; - Parser: ParserConstructor; - } } - -declare module "csv-parse" { - import { parse as parseIntf } from "csv-parse/types"; - - let parse: parseIntf; - - export = parse; -} - -declare module "csv-parse/lib/sync" { - import { options } from "csv-parse/types"; - - function parse (input: string, options?: options): any; - - export = parse; -} \ No newline at end of file diff --git a/csv-parse/lib/sync.d.ts b/csv-parse/lib/sync.d.ts new file mode 100644 index 0000000000..5a025f6dab --- /dev/null +++ b/csv-parse/lib/sync.d.ts @@ -0,0 +1,4 @@ +import { Options } from "csv-parse"; + +declare function parse(input: string, options?: Options): any; +export = parse; diff --git a/csv-parse/tsconfig.json b/csv-parse/tsconfig.json index 36611c4d1d..b721ff4fe6 100644 --- a/csv-parse/tsconfig.json +++ b/csv-parse/tsconfig.json @@ -17,6 +17,7 @@ }, "files": [ "index.d.ts", + "lib/sync.d.ts", "csv-parse-tests.ts" ] } \ No newline at end of file diff --git a/csv-parse/tslint.json b/csv-parse/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/csv-parse/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/csv-stringify/csv-stringify-tests.ts b/csv-stringify/csv-stringify-tests.ts index bd6873affb..a05f35d368 100644 --- a/csv-stringify/csv-stringify-tests.ts +++ b/csv-stringify/csv-stringify-tests.ts @@ -1,5 +1,3 @@ -/// - import stringify = require("csv-stringify"); let stream: stringify.Stringifier; diff --git a/csvtojson/csvtojson-tests.ts b/csvtojson/csvtojson-tests.ts new file mode 100644 index 0000000000..4368d00494 --- /dev/null +++ b/csvtojson/csvtojson-tests.ts @@ -0,0 +1,114 @@ +import csv = require('csvtojson'); +import fs = require('fs'); + +// From documentation on project home page -> https://github.com/Keyang/node-csvtojson + +///////////////////////////// +// From CSV String +const csvStr: string = `1,2,3 +4,5,6 +7,8,9`; + +// event emitter version using factory function +csv({ noheader: true }) + .fromString(csvStr) + .on('csv', (csvRow: string[]) => { // this func will be called 3 times + console.log(csvRow); // => [1,2,3] , [4,5,6] , [7,8,9] + }) + .on('done', () => { + //parsing finished + }); + +// event emitter version using Converter class +new csv.Converter({ noheader: true }) + .fromString(csvStr) + .on('csv', (csvRow: string[]) => { // this func will be called 3 times + console.log(csvRow); // => [1,2,3] , [4,5,6] , [7,8,9] + }) + .on('done', () => { + //parsing finished + }); + +// callback version using Converter class +new csv.Converter({ noheader: true }) + .fromString(csvStr, (err, result) => { + console.log(JSON.stringify(result)); + }); + +// callback version using factory function +csv({ noheader: true }) + .fromString(csvStr, (err, result) => { + console.log(JSON.stringify(result)); + }); + +///////////////////////////// +// From CSV File +const filePath = './test.csv'; + +// event emitter version using factory function +csv() + .fromFile(filePath) + .on('json', (jsonObj: any) => { + console.log(JSON.stringify(jsonObj)); + }) + .on('done', (error: any) => { + console.log('end'); + }); + +// event emitter version using Converter class +new csv.Converter() + .fromFile(filePath) + .on('json', (jsonObj: any) => { + console.log(JSON.stringify(jsonObj)); + }) + .on('done', (error: any) => { + console.log('end'); + }); + +// callback version using factory function +csv() + .fromFile(filePath, (err, result) => { + console.log(JSON.stringify(result)); + }); + +// callback version using Converter class +new csv.Converter() + .fromFile(filePath, (err, result) => { + console.log(JSON.stringify(result)); + }); + +///////////////////////////// +// From CSV Stream + +const stream = fs.createReadStream(filePath); + +// event emitter version using factory function +csv().fromStream(stream) + .on('json', (jsonObj: any) => { + console.log(JSON.stringify(jsonObj)); + }) + .on('done', (error: any) => { + console.log('end'); + }); + +// event emitter version using Converter class +new csv.Converter() + .fromStream(stream) + .on('json', (jsonObj: any) => { + console.log(JSON.stringify(jsonObj)); + }) + .on('done', (error: any) => { + console.log('end'); + }); + +// callback version using factory function +csv() + .fromStream(stream, (err, result) => { + console.log(JSON.stringify(result)); + }); + +// callback version using Converter class +new csv.Converter() + .fromStream(stream, (err, result) => { + console.log(JSON.stringify(result)); + }); diff --git a/csvtojson/index.d.ts b/csvtojson/index.d.ts new file mode 100644 index 0000000000..9ba01212c7 --- /dev/null +++ b/csvtojson/index.d.ts @@ -0,0 +1,276 @@ +// Type definitions for csvtojson 1.1 +// Project: https://github.com/Keyang/node-csvtojson +// Definitions by: Eric Byers , Wayne Carson +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as stream from 'stream'; + +declare namespace csvtojson { + + /** + * Stream options + */ + type StreamOptions = stream.TransformOptions; + + /** + * Converter options + */ + interface ConverterOptions { + + /** + * Delimiter used for seperating columns. Use "auto" if delimiter is unknown in advance, + * in this case, delimiter will be auto-detected (by best attempt). Use an array to give + * a list of potential delimiters e.g. [",","|","$"]. (default: ",") + */ + delimiter?: string | string[]; + + /** + * If a column contains delimiter, it is able to use quote character to surround the column + * content. e.g. "hello, world" wont be split into two columns while parsing. Set to "off" + * will ignore all quotes. (default: " (double quote)) + */ + quote?: string; + + /** + * Indicate if parser trim off spaces surrounding column content. e.g. " content " will be + * trimmed to "content". (default: true) + */ + trim?: boolean; + + /** + * This parameter turns on and off whether check field type. (default: true) + */ + checkType?: boolean; + + /** + * Stringify the stream output to JSON array. This is useful when pipe output to a file + * which expects stringified JSON array. (default: false and only stringified JSON (without []) + * will be pushed to downstream) + */ + toArrayString?: boolean; + + /** + * Ignore the empty value in CSV columns. If a column value is not giving, set this to true to + * skip them. (default: false) + */ + ignoreEmpty?: boolean; + + /** + * Number of worker processes. The worker process will use multi-cores to help process CSV data. + * Set to number of cores to improve the performance of processing large CSV file. Keep 1 for + * small csv files. (default: 1) + */ + workerNum?: number; + + /** + * Indicating CSV data has no header row and first row is data row. (default: false) + */ + noheader?: boolean; + + /** + * An array to specify the headers of CSV data. If noheader is false, this value will override + * CSV header row. Example: ["my field","name"] (default: null) + */ + headers?: string[]; + + /** + * Don't interpret dots (.) and square brackets in header fields as nested object or array identifiers + * at all (treat them like regular characters for JSON field identifiers). (default: false) + */ + flatKeys?: boolean; + + /** + * The max character a CSV row could have. 0 means infinite. If max number exceeded, parser will emit + * "error" of "row_exceed". if a possibly corrupted CSV data provided, give it a number like 65535 + * so the parser wont consume memory. (default: 0) + */ + maxRowLength?: number; + + /** + * Whether or not to check if the column number of a row is the same as headers. If column number + * mismatched headers number, an error of "mismatched_column" will be emitted. (default: false) + */ + checkColumn?: boolean; + + /** + * End of line character. If omitted, parser will attempt retrieve it from first chunk of CSV data. + * If no valid eol found, then operation system eol will be used. + */ + eol?: string; + + /** + * Escape character used in quoted column. Default is double quote (") according to RFC4108. Change + * to back slash (\) or other chars for your own case. (default: " (double quote)) + */ + escape?: string; + + /** + * This parameter instructs the parser to include only those columns as specified by an array of + * column indexes. Example: [0,2,3] will parse and include only columns 0, 2, and 3 in the JSON output. + */ + includeColumns?: number[]; + + /** + * This parameter instructs the parser to ignore columns as specified by an array of column indexes. + * Example: [1,3,5] will ignore columns 1, 3, and 5 and will not return them in the JSON output. + */ + ignoreColumns?: number[]; + + /** + * Deprecated. Use workerNum instead. + */ + fork?: number; + } + + /** + * Callback function for handling result of parse. + */ + type ParseResultHandler = (err: any, result: any) => void; + + /** + * Event handler for "json" events. + */ + type JsonEventHandler = (jsonObj: any, rowNumber: number) => void; + + /** + * Event handler for "csv" events. + */ + type CsvEventHandler = (csvRow: string[], rowNumber: number) => void; + + /** + * Event handler for "data" events. + */ + type DataEventHandler = (data: any) => void; + + /** + * Event handler for "error" events. + */ + type ErrorEventHandler = (err: any) => void; + + /** + * Event handler for "record_parsed" events. + */ + type RecordParsedEventHandler = (jsonObj: any, csvRoe: string[], rowNumber: number) => void; + + /** + * Event handler for "end" events. + */ + type EndEventHandler = () => void; + + /** + * Event handler for "end_parsed" events. + */ + type EndParsedEventHandler = (jsonObjArray: any[]) => void; + + /** + * Event handler for "done" events. + */ + type DoneEventHandler = (err: any) => void; + + /** + * Converts provided CSV input to a JSON object. + */ + class Converter extends stream.Transform { + + /** + * Initializes a new instance of a Converter + * @param {ConverterOptions} options converter options + * @param {StreamOptions} streamOptions stream options + */ + constructor(options?: ConverterOptions, streamOptions?: StreamOptions); + + /** + * Reads in a CSV from a string. + * @param {string} str the string to convert + * @return {Converter} returns this object for chaining + */ + fromString(str: string): this + + /** + * Reads in a CSV from a string. + * @param {string} str the string to convert + * @param {ParseResultHandler} callback callback function to handle result or error + */ + fromString(str: string, callback: ParseResultHandler): void; + + /** + * Reads in a CSV from a file. + * @param {string} filePath the path to the CSV file + * @return {Converter} returns this object for chaining + */ + fromFile(filePath: string): this + + /** + * Reads in a CSV from a file. + * @param {string} filePath the path to the CSV file + * @param {ParseResultHandler} callback callback function to handle result or error + */ + fromFile(filePath: string, callback: ParseResultHandler): void; + + /** + * Reads in a CSV from a stream. + * @param {Stream} stream the stream + * @return {Converter} returns this object for chaining + */ + fromStream(stream: NodeJS.ReadableStream): this + + /** + * Reads in a CSV from a stream. + * @param {Stream} stream the stream + * @param {ParseResultHandler} callback callback function to handle result or error + */ + fromStream(stream: stream.Stream, callback: ParseResultHandler): void; + + /** + * Adds a listener function to the end of the listeners array for an event. + * Available events: + * - json + * - csv + * - data + * - error + * - record_parsed + * - end + * - end_parsed + * - done + * @param {Event} event name of event + * @param {Function} listener listener function + * @return {this} returns this object for chaining + */ + // tslint:disable-next-line:forbidden-types + on(event: string, listener: Function | JsonEventHandler | CsvEventHandler | DataEventHandler | ErrorEventHandler + | RecordParsedEventHandler | EndEventHandler | EndParsedEventHandler | DoneEventHandler): this; + + /** + * Transform objects after CSV parsing but before result being emitted or pushed downstream. + * @param {Function} callback transform function + * @return {this} returns this object for chaining + */ + transf(callback: (jsonObj: any, csvRow: string[], rowNumber: number) => void): this; + + /** + * The function in preRawData will be called directly with the string from upper stream. + * @param {Function} callback callback function + * @return {this} returns this object for chaining + */ + preRawData(callback: (csvRawData: string, cb: (newData: any) => void) => void): this; + + /** + * The function is called each time a file line being found in csv stream. + * @param {Function} callback callback function + * @return {this} returns this object for chaining + */ + preFileLine(callback: (line: string, rowNumber: number) => string): this; + } +} + +/** + * Factory function which creates an instance of a Converter object. + * @param {ConverterOptions} options converter options + * @param {StreamOptions} streamOptions stream options + * @return {csvtojson.Converter} Converter object + */ +declare function csvtojson(options?: csvtojson.ConverterOptions, streamOptions?: csvtojson.StreamOptions): csvtojson.Converter; + +export = csvtojson; diff --git a/csvtojson/tsconfig.json b/csvtojson/tsconfig.json new file mode 100644 index 0000000000..81ec6a66a2 --- /dev/null +++ b/csvtojson/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "csvtojson-tests.ts" + ] +} diff --git a/csvtojson/tslint.json b/csvtojson/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/csvtojson/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/cucumber/cucumber-tests.ts b/cucumber/cucumber-tests.ts index 87089671ae..3eb86b223f 100644 --- a/cucumber/cucumber-tests.ts +++ b/cucumber/cucumber-tests.ts @@ -97,6 +97,24 @@ function StepSample() { } ) }); + cucumber.defineSupportCode(function(hook: cucumber.Hooks){ + hook.addTransform({ + captureGroupRegexps: ['red|blue|green'], + transformer: (arg: string) => arg, + typeName: 'color' + }); + }); + + cucumber.defineSupportCode(function({After, Given}) { + Given( /^a variable set to (\d+)$/, (x:string) => { + console.log("the number is: " + x); + }); + After((scenario: HookScenario, callback?: Callback) => { + console.log("After"); + callback(); + }); + }); + let fns : cucumber.SupportCodeConsumer[] = cucumber.getSupportCodeFns() cucumber.clearSupportCodeFns(); diff --git a/cucumber/index.d.ts b/cucumber/index.d.ts index a8b85539ce..99f31c5372 100644 --- a/cucumber/index.d.ts +++ b/cucumber/index.d.ts @@ -64,6 +64,12 @@ declare namespace cucumber { (scenario: HookScenario, runScenario?: (error:string, callback?:Function)=>void): void; } + interface Transform { + captureGroupRegexps: Array; + transformer: (arg: string) => any; + typeName: string; + } + export interface Hooks { Before(code: HookCode): void; After(code: HookCode): void; @@ -72,6 +78,7 @@ declare namespace cucumber { setWorldConstructor(world: () => void): void; registerHandler(handlerOption:string, code:(event:any, callback:CallbackStepDefinition) =>void): void; registerListener(listener: EventListener): void; + addTransform(transform: Transform): void; } export class EventListener { diff --git a/cybozulabs-md5/cybozulabs-md5-tests.ts b/cybozulabs-md5/cybozulabs-md5-tests.ts index 7572ed9124..2163b6e8c9 100644 --- a/cybozulabs-md5/cybozulabs-md5-tests.ts +++ b/cybozulabs-md5/cybozulabs-md5-tests.ts @@ -1,5 +1,3 @@ -/// - var hash: string; hash = CybozuLabs.MD5.calc("abc"); hash = CybozuLabs.MD5.calc("abc", CybozuLabs.MD5.BY_ASCII); diff --git a/d3-array/d3-array-tests.ts b/d3-array/d3-array-tests.ts index 74b749bea3..7dbe08bad0 100644 --- a/d3-array/d3-array-tests.ts +++ b/d3-array/d3-array-tests.ts @@ -44,13 +44,13 @@ let num: number; let date: Date; let numOrUndefined: number | undefined; -let strOrUndefined: string | undefined; -let numericOrUndefined: NumCoercible | undefined; -let dateOrUndefined: Date | undefined; +let strOrUndefined: string |  undefined; +let numericOrUndefined: NumCoercible |  undefined; +let dateOrUndefined: Date |  undefined; let numOrUndefinedExtent: [number, number] | [undefined, undefined]; let strOrUndefinedExtent: [string, string] | [undefined, undefined]; let numericOrUndefinedExtent: [NumCoercible, NumCoercible] | [undefined, undefined]; -let dateMixedOrUndefined: [Date , Date] | [undefined, undefined]; +let dateMixedOrUndefined: [Date, Date] | [undefined, undefined]; let mixedOrUndefinedExtent: [d3Array.Primitive | NumCoercible, d3Array.Primitive | NumCoercible] | [undefined, undefined]; let dateOrUndefinedExtent: [Date, Date] | [undefined, undefined]; @@ -330,12 +330,34 @@ mergedArray = d3Array.merge(testArrays); // inferred type mergedArray = d3Array.merge(testArrays); // explicit type // mergedArray = d3Array.merge([[10, 40, 30], [15, 30]]); // fails, type mismatch +// cross() --------------------------------------------------------------------- + +let crossed: Array<[string, number]>; + +crossed = d3Array.cross(['x', 'y'], [1, 2]); +crossed = d3Array.cross(['x', 'y'], [1, 2]); + +let strArray: string[] = d3Array.cross([2, 3], [5, 6], (a, b) => (a + b) + 'px'); +strArray = d3Array.cross([2, 3], [5, 6], (a, b) => { + let aa: number = a; + let bb: number = b; + return (aa + bb) + 'px'; +}); + + // pairs() --------------------------------------------------------------------- let pairs: Array<[MixedObject, MixedObject]>; pairs = d3Array.pairs(mergedArray); +numbersArray = d3Array.pairs(mergedArray, (a, b) => b.num - a.num); +numbersArray = d3Array.pairs(mergedArray, (a, b) => { + let aa: MixedObject = a; + let bb: MixedObject = b; + return bb.num - aa.num; +}); + // permute() ------------------------------------------------------------------- // getting a permutation of array elements diff --git a/d3-array/index.d.ts b/d3-array/index.d.ts index 336eb2bc83..d938a8c032 100644 --- a/d3-array/index.d.ts +++ b/d3-array/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for D3JS d3-array module 1.0 +// Type definitions for D3JS d3-array module 1.1 // Project: https://github.com/d3/d3-array // Definitions by: Alex Ford , Boris Yankov , Tom Wanzek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.0.2 +// Last module patch version validated against: 1.1.0 // -------------------------------------------------------------------------- // Shared Types and Interfaces @@ -181,6 +181,26 @@ export function descending(a: Primitive | undefined, b: Primitive | undefined): // Transforming Arrays // -------------------------------------------------------------------------------------- +/** + * Returns the Cartesian product of the two arrays a and b. + * For each element i in the specified array a and each element j in the specified array b, in order, + * it creates a two-element array for each pair. + * + * @param a First input array. + * @param b Second input array. + */ +export function cross(a: S[], b: T[]): Array<[S, T]>; + +/** + * Returns the Cartesian product of the two arrays a and b. + * For each element i in the specified array a and each element j in the specified array b, in order, + * invokes the specified reducer function passing the element i and element j. + * + * @param a First input array. + * @param b Second input array. + * @param reducer A reducer function taking as input an element from "a" and "b" and returning a reduced value. + */ +export function cross(a: S[], b: T[], reducer: (a: S, b: T) => U): U[]; /** * Merges the specified arrays into a single array. @@ -190,8 +210,19 @@ export function merge(arrays: T[][]): T[]; /** * For each adjacent pair of elements in the specified array, returns a new array of tuples of elements i and i - 1. * Returns the empty array if the input array has fewer than two elements. + * + * @param array Array of input elements */ export function pairs(array: T[]): Array<[T, T]>; +/** + * For each adjacent pair of elements in the specified array, in order, invokes the specified reducer function passing the element i and element i - 1. + * Returns the resulting array of pair-wise reduced elements. + * Returns the empty array if the input array has fewer than two elements. + * + * @param array Array of input elements + * @param reducer A reducer function taking as input to adjecent elements of the input array and returning a reduced value. + */ +export function pairs(array: T[], reducer: (a: T, b: T) => U): U[]; /** * Given the specified array, return an array corresponding to the list of indices in 'keys'. diff --git a/d3-format/d3-format-tests.ts b/d3-format/d3-format-tests.ts index 3fd5742997..57a98e26c6 100644 --- a/d3-format/d3-format-tests.ts +++ b/d3-format/d3-format-tests.ts @@ -63,11 +63,6 @@ num = d3Format.precisionRound(0.0005, 3000); // Test Locale Definition // ---------------------------------------------------------------------- -let decimal: '.' | ',' = localeDef.decimal; -let thousands: '.' | ',' | '\u00a0' | "'" = localeDef.thousands; -let grouping: Array = localeDef.grouping; -let currency: [string, string] = localeDef.currency; - localeDef = { decimal: ',', thousands: '.', @@ -75,6 +70,20 @@ localeDef = { currency: ['EUR', ''] }; +localeDef = { + decimal: "\u066b", + thousands: "\u066c", + grouping: [3], + currency: ["", ""], + numerals : ["\u0660", "\u0661", "\u0662", "\u0663", "\u0664", "\u0665", "\u0666", "\u0667", "\u0668", "\u0669"] +} + +let decimal: string = localeDef.decimal; +let thousands: string = localeDef.thousands; +let grouping: Array = localeDef.grouping; +let currency: [string, string] = localeDef.currency; +let numerals: string[] | undefined = localeDef.numerals; + localeObj = d3Format.formatLocale(localeDef); localeObj = d3Format.formatDefaultLocale(localeDef); diff --git a/d3-format/index.d.ts b/d3-format/index.d.ts index 92197f6ab8..be6c2b9a99 100644 --- a/d3-format/index.d.ts +++ b/d3-format/index.d.ts @@ -1,8 +1,10 @@ -// Type definitions for D3JS d3-format module v1.0.2 +// Type definitions for D3JS d3-format module 1.1 // Project: https://github.com/d3/d3-format/ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Last module patch version validated against: 1.1.0 + /** * Specification of locale to use when creating a new FormatLocaleObject */ @@ -10,12 +12,12 @@ export interface FormatLocaleDefinition { /** * The decimal point (e.g., ".") */ - decimal: '.' | ','; + decimal: string; /** * The group separator (e.g., ","). Note that the thousands property is a misnomer, as\ * the grouping definition allows groups other than thousands. */ - thousands: '.' | ',' | '\u00a0' | "'"; + thousands: string; /** * The array of group sizes (e.g., [3]), cycled as needed. */ @@ -24,6 +26,10 @@ export interface FormatLocaleDefinition { * The currency prefix and suffix (e.g., ["$", ""]) */ currency: [string, string]; + /** + * An array of ten strings to replace the numerals 0-9. + */ + numerals?: string[]; } /** diff --git a/d3-geo/d3-geo-tests.ts b/d3-geo/d3-geo-tests.ts index 3d28bb610f..a29dce0e8b 100644 --- a/d3-geo/d3-geo-tests.ts +++ b/d3-geo/d3-geo-tests.ts @@ -130,6 +130,18 @@ centroid = d3Geo.geoCentroid(sampleExtendedFeature2); centroid = d3Geo.geoCentroid(sampleFeatureCollection); centroid = d3Geo.geoCentroid(sampleExtendedFeatureCollection); +// geoContains(...) ======================================================= + +let contained: boolean = d3Geo.geoContains(samplePolygon, [0, 0]); +contained = d3Geo.geoContains(sampleSphere, [0, 0]); +contained = d3Geo.geoContains(sampleGeometryCollection, [0, 0]); +contained = d3Geo.geoContains(sampleExtendedGeometryCollection, [0, 0]); +contained = d3Geo.geoContains(sampleFeature, [0, 0]); +contained = d3Geo.geoContains(sampleExtendedFeature1, [0, 0]); +contained = d3Geo.geoContains(sampleExtendedFeature2, [0, 0]); +contained = d3Geo.geoContains(sampleFeatureCollection, [0, 0]); +contained = d3Geo.geoContains(sampleExtendedFeatureCollection, [0, 0]); + // geoDistance(...) ======================================================= let distance: number = d3Geo.geoDistance([54, 2], [53, 1]); @@ -198,7 +210,7 @@ class Circulator { private p: number; private circleGenerator: d3Geo.GeoCircleGenerator; - public getCirclePolygon(center?: [number, number]): GeoJSON.Polygon { + getCirclePolygon(center?: [number, number]): GeoJSON.Polygon { if (center && center.length === 2 && typeof center[0] === 'number' && typeof center[1] === 'number') { return this.circleGenerator(center); } else { @@ -489,7 +501,8 @@ geoPathSVG = geoPathSVG.pointRadius(function (datum) { }); let geoPathSVGPointRadiusAccessor: number | ((this: SVGPathElement, d: d3Geo.ExtendedFeature, ...args: any[]) => number) = geoPathSVG.pointRadius(); -// let geoPathSVGPointRadiusAccessorWrong1: number | ((this: SVGCircleElement, d: d3Geo.ExtendedFeature, ...args: any[]) => number) = geoPathSVG.pointRadius(); // fails, mismatch in this context +// let geoPathSVGPointRadiusAccessorWrong1: number | ((this: SVGCircleElement, d: d3Geo.ExtendedFeature, ...args: any[]) => number) +// = geoPathSVG.pointRadius(); // fails, mismatch in this context // let geoPathSVGPointRadiusAccessorWrong2: number | ((this: SVGPathElement, d: d3Geo.GeoGeometryObjects, ...args: any[]) => number) = geoPathSVG.pointRadius(); // fails, mismatch in object datum type // Use geoPath Generator ================================================ @@ -537,6 +550,19 @@ geoPathCentroid = geoPathCanvas.centroid(sampleExtendedFeatureCollection); // geoPathCentroid = geoPathSVG.centroid(sampleExtendedFeatureCollection); // fails, wrong data object type + +// measure(...) ------------------------------------------------------ + +let geoPathMeasure: number = geoPathCanvas.measure(samplePolygon); +geoPathMeasure = geoPathCanvas.measure(sampleSphere); +geoPathMeasure = geoPathCanvas.measure(sampleGeometryCollection); +geoPathMeasure = geoPathCanvas.measure(sampleExtendedGeometryCollection); +geoPathMeasure = geoPathCanvas.measure(sampleFeature); +geoPathMeasure = geoPathCanvas.measure(sampleExtendedFeature1); +geoPathMeasure = geoPathCanvas.measure(sampleExtendedFeature2); +geoPathMeasure = geoPathCanvas.measure(sampleFeatureCollection); +geoPathMeasure = geoPathCanvas.measure(sampleExtendedFeatureCollection); + // render path to context of get path string---------------------------- // render to GeoContext/Canvas diff --git a/d3-geo/index.d.ts b/d3-geo/index.d.ts index 9ab3ae74cd..dfc58a5f9e 100644 --- a/d3-geo/index.d.ts +++ b/d3-geo/index.d.ts @@ -1,10 +1,12 @@ -// Type definitions for D3JS d3-geo module v1.4.0 +// Type definitions for D3JS d3-geo module 1.6 // Project: https://github.com/d3/d3-geo/ // Definitions by: Hugues Stefanski , Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +// Last module patch version validated against: 1.6.1 + // ---------------------------------------------------------------------- // Shared Interfaces and Types // ---------------------------------------------------------------------- @@ -59,7 +61,8 @@ export interface ExtendedFeatureCollection | ExtendedFeature | ExtendedFeatureCollection>; +export type GeoPermissibleObjects = GeoGeometryObjects | ExtendedGeometryCollection + | ExtendedFeature | ExtendedFeatureCollection>; // ---------------------------------------------------------------------- // Spherical Math @@ -67,94 +70,135 @@ export type GeoPermissibleObjects = GeoGeometryObjects | ExtendedGeometryCollect /** * Returns the spherical area of the specified feature in steradians. - * (See also path.area, which computes the projected planar area.) + * This is the spherical equivalent of path.area. * - * @param feature A geographic feature supported by d3-geo (An extension of GeoJSON feature). + * @param object A geographic feature supported by d3-geo (An extension of GeoJSON feature). */ -export function geoArea(feature: ExtendedFeature): number; +export function geoArea(object: ExtendedFeature): number; /** * Returns the spherical area of the specified feature collection in steradians. - * (See also path.area, which computes the projected planar area.) + * This is the spherical equivalent of path.area. * - * @param feature A geographic feature collection supported by d3-geo (An extension of GeoJSON feature). + * @param object A geographic feature collection supported by d3-geo (An extension of GeoJSON feature). */ -export function geoArea(feature: ExtendedFeatureCollection>): number; +export function geoArea(object: ExtendedFeatureCollection>): number; /** * Returns the spherical area of the specified GeoJson Geometry Object or GeoSphere object in steradians. - * (See also path.area, which computes the projected planar area.) + * This is the spherical equivalent of path.area. * - * @param feature A GeoJson Geometry Object or GeoSphere object supported by d3-geo (An extension of GeoJSON). + * @param object A GeoJson Geometry Object or GeoSphere object supported by d3-geo (An extension of GeoJSON). */ -export function geoArea(feature: GeoGeometryObjects): number; +export function geoArea(object: GeoGeometryObjects): number; /** * Returns the spherical area of the specified geographic geometry collection in steradians. - * (See also path.area, which computes the projected planar area.) + * This is the spherical equivalent of path.area. * - * @param feature A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). + * @param object A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). */ -export function geoArea(feature: ExtendedGeometryCollection): number; +export function geoArea(object: ExtendedGeometryCollection): number; /** * Returns the spherical bounding box for the specified feature. The bounding box is represented by a two-dimensional array: [[left, bottom], [right, top]], * where left is the minimum longitude, bottom is the minimum latitude, right is maximum longitude, and top is the maximum latitude. All coordinates are given in degrees. * (Note that in projected planar coordinates, the minimum latitude is typically the maximum y-value, and the maximum latitude is typically the minimum y-value.) + * This is the spherical equivalent of path.bounds. * - * @param feature A geographic feature supported by d3-geo (An extension of GeoJSON feature). + * @param object A geographic feature supported by d3-geo (An extension of GeoJSON feature). */ -export function geoBounds(feature: ExtendedFeature): [[number, number], [number, number]]; +export function geoBounds(object: ExtendedFeature): [[number, number], [number, number]]; /** * Returns the spherical bounding box for the specified feature collection. The bounding box is represented by a two-dimensional array: [[left, bottom], [right, top]], * where left is the minimum longitude, bottom is the minimum latitude, right is maximum longitude, and top is the maximum latitude. All coordinates are given in degrees. * (Note that in projected planar coordinates, the minimum latitude is typically the maximum y-value, and the maximum latitude is typically the minimum y-value.) + * This is the spherical equivalent of path.bounds. * - * @param feature A geographic feature collection supported by d3-geo (An extension of GeoJSON feature). + * @param object A geographic feature collection supported by d3-geo (An extension of GeoJSON feature). */ -export function geoBounds(feature: ExtendedFeatureCollection>): [[number, number], [number, number]]; +export function geoBounds(object: ExtendedFeatureCollection>): [[number, number], [number, number]]; /** * Returns the spherical bounding box for the specified GeoJson Geometry Object or GeoSphere object. The bounding box is represented by a two-dimensional array: [[left, bottom], [right, top]], * where left is the minimum longitude, bottom is the minimum latitude, right is maximum longitude, and top is the maximum latitude. All coordinates are given in degrees. * (Note that in projected planar coordinates, the minimum latitude is typically the maximum y-value, and the maximum latitude is typically the minimum y-value.) + * This is the spherical equivalent of path.bounds. * - * @param feature A GeoJson Geometry Object or GeoSphere object supported by d3-geo (An extension of GeoJSON). + * @param object A GeoJson Geometry Object or GeoSphere object supported by d3-geo (An extension of GeoJSON). */ -export function geoBounds(feature: GeoGeometryObjects): [[number, number], [number, number]]; +export function geoBounds(object: GeoGeometryObjects): [[number, number], [number, number]]; /** * Returns the spherical bounding box for the specified geometry collection. The bounding box is represented by a two-dimensional array: [[left, bottom], [right, top]], * where left is the minimum longitude, bottom is the minimum latitude, right is maximum longitude, and top is the maximum latitude. All coordinates are given in degrees. * (Note that in projected planar coordinates, the minimum latitude is typically the maximum y-value, and the maximum latitude is typically the minimum y-value.) + * This is the spherical equivalent of path.bounds. * - * @param feature A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). + * @param object A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). */ -export function geoBounds(feature: ExtendedGeometryCollection): [[number, number], [number, number]]; +export function geoBounds(object: ExtendedGeometryCollection): [[number, number], [number, number]]; /** * Returns the spherical centroid of the specified feature in steradians. - * (See also path.centroid, which computes the projected planar centroid.) + * This is the spherical equivalent of path.centroid. * - * @param feature A geographic feature supported by d3-geo (An extension of GeoJSON feature). + * @param object A geographic feature supported by d3-geo (An extension of GeoJSON feature). */ -export function geoCentroid(feature: ExtendedFeature): [number, number]; +export function geoCentroid(object: ExtendedFeature): [number, number]; /** * Returns the spherical centroid of the specified feature collection in steradians. - * (See also path.centroid, which computes the projected planar centroid.) + * This is the spherical equivalent of path.centroid. * - * @param feature A geographic feature collection supported by d3-geo (An extension of GeoJSON feature). + * @param object A geographic feature collection supported by d3-geo (An extension of GeoJSON feature). */ -export function geoCentroid(feature: ExtendedFeatureCollection>): [number, number]; +export function geoCentroid(object: ExtendedFeatureCollection>): [number, number]; /** * Returns the spherical centroid of the specified GeoJson Geometry Object or GeoSphere object in steradians. - * (See also path.centroid, which computes the projected planar centroid.) + * This is the spherical equivalent of path.centroid. * - * @param feature A GeoJson Geometry Object or GeoSphere object supported by d3-geo (An extension of GeoJSON). + * @param object A GeoJson Geometry Object or GeoSphere object supported by d3-geo (An extension of GeoJSON). */ -export function geoCentroid(feature: GeoGeometryObjects): [number, number]; +export function geoCentroid(object: GeoGeometryObjects): [number, number]; /** * Returns the spherical centroid of the specified geographic geometry collection in steradians. - * (See also path.centroid, which computes the projected planar centroid.) + * This is the spherical equivalent of path.centroid. * - * @param feature A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). + * @param object A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). */ -export function geoCentroid(feature: ExtendedGeometryCollection): [number, number]; +export function geoCentroid(object: ExtendedGeometryCollection): [number, number]; + +/** + * Returns true if and only if the specified GeoJSON object contains the specified point, or false if the object does not contain the point. + * The point must be specified as a two-element array [longitude, latitude] in degrees. For Point and MultiPoint geometries, an exact test is used; + * for a Sphere, true is always returned; for other geometries, an epsilon threshold is applied. + * + * @param object A geographic feature supported by d3-geo (An extension of GeoJSON feature). + * @param point Point specified as a two-element array [longitude, latitude] in degrees. + */ +export function geoContains(object: ExtendedFeature, point: [number, number]): boolean; +/** + * Returns true if and only if the specified GeoJSON object contains the specified point, or false if the object does not contain the point. + * The point must be specified as a two-element array [longitude, latitude] in degrees. For Point and MultiPoint geometries, an exact test is used; + * for a Sphere, true is always returned; for other geometries, an epsilon threshold is applied. + * + * @param object A geographic feature collection supported by d3-geo (An extension of GeoJSON feature). + * @param point Point specified as a two-element array [longitude, latitude] in degrees. + */ +export function geoContains(object: ExtendedFeatureCollection>, point: [number, number]): boolean; +/** + * Returns true if and only if the specified GeoJSON object contains the specified point, or false if the object does not contain the point. + * The point must be specified as a two-element array [longitude, latitude] in degrees. For Point and MultiPoint geometries, an exact test is used; + * for a Sphere, true is always returned; for other geometries, an epsilon threshold is applied. + * + * @param object A GeoJson Geometry Object or GeoSphere object supported by d3-geo (An extension of GeoJSON). + * @param point Point specified as a two-element array [longitude, latitude] in degrees. + */ +export function geoContains(object: GeoGeometryObjects, point: [number, number]): boolean; +/** + * Returns true if and only if the specified GeoJSON object contains the specified point, or false if the object does not contain the point. + * The point must be specified as a two-element array [longitude, latitude] in degrees. For Point and MultiPoint geometries, an exact test is used; + * for a Sphere, true is always returned; for other geometries, an epsilon threshold is applied. + * + * @param object A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). + * @param point Point specified as a two-element array [longitude, latitude] in degrees. + */ +export function geoContains(object: ExtendedGeometryCollection, point: [number, number]): boolean; /** * Returns the great-arc distance in radians between the two points a and b. @@ -166,29 +210,33 @@ export function geoCentroid(feature: ExtendedGeometryCollection): number; +export function geoLength(object: ExtendedFeature): number; /** - * Returns the great-arc length of the specified feature collection in radians. + * Returns the great-arc length of the specified feature collection in radians. For polygons, returns the perimeter of the exterior ring plus that of any interior rings. + * This is the spherical equivalent of path.measure. * - * @param feature A geographic feature collection supported by d3-geo (An extension of GeoJSON feature). + * @param object A geographic feature collection supported by d3-geo (An extension of GeoJSON feature). */ -export function geoLength(feature: ExtendedFeatureCollection>): number; +export function geoLength(object: ExtendedFeatureCollection>): number; /** - * Returns the great-arc length of the specified GeoJson Geometry Object or GeoSphere object in radians. + * Returns the great-arc length of the specified GeoJson Geometry Object or GeoSphere object in radians. For polygons, returns the perimeter of the exterior ring plus that of any interior rings. + * This is the spherical equivalent of path.measure. * -* @param feature A GeoJson Geometry Object or GeoSphere object supported by d3-geo (An extension of GeoJSON). + * @param object A GeoJson Geometry Object or GeoSphere object supported by d3-geo (An extension of GeoJSON). */ -export function geoLength(feature: GeoGeometryObjects): number; +export function geoLength(object: GeoGeometryObjects): number; /** - * Returns the great-arc length of the specified geographic geometry collection in radians. + * Returns the great-arc length of the specified geographic geometry collection in radians For polygons, returns the perimeter of the exterior ring plus that of any interior rings. + * This is the spherical equivalent of path.measure.. * - * @param feature A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). + * @param object A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). */ -export function geoLength(feature: ExtendedGeometryCollection): number; +export function geoLength(object: ExtendedGeometryCollection): number; /** * Returns an interpolator function given two points a and b. @@ -658,15 +706,15 @@ export interface GeoProjection extends GeoStreamWrapper { * @param object A geographic feature supported by d3-geo (An extension of GeoJSON feature). */ fitExtent(extent: [[number, number], [number, number]], object: ExtendedFeature): this; - /** - * Sets the projection’s scale and translate to fit the specified geographic feature collection in the center of the given extent. - * Returns the projection. - * - * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. - * - * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. - * @param object A geographic feature collection supported by d3-geo (An extension of GeoJSON feature collection). - */ + /** + * Sets the projection’s scale and translate to fit the specified geographic feature collection in the center of the given extent. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. + * @param object A geographic feature collection supported by d3-geo (An extension of GeoJSON feature collection). + */ fitExtent(extent: [[number, number], [number, number]], object: ExtendedFeatureCollection>): this; /** * Sets the projection’s scale and translate to fit the specified geographic geometry object in the center of the given extent. @@ -678,15 +726,15 @@ export interface GeoProjection extends GeoStreamWrapper { * @param object A GeoJson Geometry Object or GeoSphere object supported by d3-geo (An extension of GeoJSON). */ fitExtent(extent: [[number, number], [number, number]], object: GeoGeometryObjects): this; - /** - * Sets the projection’s scale and translate to fit the specified geographic geometry collection in the center of the given extent. - * Returns the projection. - * - * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. - * - * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. - * @param object A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). - */ + /** + * Sets the projection’s scale and translate to fit the specified geographic geometry collection in the center of the given extent. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. + * @param object A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). + */ fitExtent(extent: [[number, number], [number, number]], object: ExtendedGeometryCollection): this; @@ -867,7 +915,8 @@ export interface GeoContext { /** * A Geo Path generator * - * The first generic corresponds to the "this"-context within which the geo path generator will be invoked. This could be e.g. the DOMElement bound to "this" when using selection.attr("d", ...) with the path generator. + * The first generic corresponds to the "this"-context within which the geo path generator will be invoked. + * This could be e.g. the DOMElement bound to "this" when using selection.attr("d", ...) with the path generator. * * The second generic corresponds to the type of the DatumObject which will be passed into the geo path generator for rendering. */ @@ -904,11 +953,11 @@ export interface GeoPath { /** * Returns the projected planar area (typically in square pixels) for the specified GeoJSON object. - * Point, MultiPoint, LineString and MultiLineString features have zero area. For Polygon and MultiPolygon features, + * Point, MultiPoint, LineString and MultiLineString geometries have zero area. For Polygon and MultiPolygon geometries, * this method first computes the area of the exterior ring, and then subtracts the area of any interior holes. - * This method observes any clipping performed by the projection; see projection.clipAngle and projection.clipExtent. + * This method observes any clipping performed by the projection; see projection.clipAngle and projection.clipExtent. This is the planar equivalent of d3.geoArea. * - * @param An object for which the area is to be calculated. + * @param object An object for which the area is to be calculated. */ area(object: DatumObject): number; @@ -919,9 +968,9 @@ export interface GeoPath { * * This is handy for, say, zooming in to a particular feature. (Note that in projected planar coordinates, * the minimum latitude is typically the maximum y-value, and the maximum latitude is typically the minimum y-value.) - * This method observes any clipping performed by the projection; see projection.clipAngle and projection.clipExtent. + * This method observes any clipping performed by the projection; see projection.clipAngle and projection.clipExtent. This is the planar equivalent of d3.geoBounds. * - * @param An object for which the bounds are to be calculated. + * @param object An object for which the bounds are to be calculated. */ bounds(object: DatumObject): [[number, number], [number, number]]; @@ -929,12 +978,22 @@ export interface GeoPath { * Returns the projected planar centroid (typically in pixels) for the specified GeoJSON object. * This is handy for, say, labeling state or county boundaries, or displaying a symbol map. * For example, a noncontiguous cartogram might scale each state around its centroid. - * This method observes any clipping performed by the projection; see projection.clipAngle and projection.clipExtent. + * This method observes any clipping performed by the projection; see projection.clipAngle and projection.clipExtent. This is the planar equivalent of d3.geoCentroid. * - * @param An object for which the centroid is to be calculated. + * @param object An object for which the centroid is to be calculated. */ centroid(object: DatumObject): [number, number]; + /** + * Returns the projected planar length (typically in pixels) for the specified GeoJSON object. + * Point and MultiPoint geometries have zero length. For Polygon and MultiPolygon geometries, this method computes the summed length of all rings. + * + * This method observes any clipping performed by the projection; see projection.clipAngle and projection.clipExtent. This is the planar equivalent of d3.geoLength. + * + * @param object An object for which the measure is to be calculated. + */ + measure(object: DatumObject): number; + /** * Returns the current render context which defaults to null. * @@ -1000,27 +1059,28 @@ export interface GeoPath { projection(projection: GeoStreamWrapper): this; /** - * Returns the current radius or radius accessor used to determine the radius for the display of Point and MultiPoint features. + * Returns the current radius or radius accessor used to determine the radius for the display of Point and MultiPoint geometries. * The default is a constant radius of 4.5. */ pointRadius(): ((this: This, object: DatumObject, ...args: any[]) => number) | number; /** - * Sets the radius used to display Point and MultiPoint features to the specified number and return the geo path generator. + * Sets the radius used to display Point and MultiPoint geometries to the specified number and return the geo path generator. * * @param value Fixed radius value. */ pointRadius(value: number): this; /** - * Sets the radius used to display Point and MultiPoint features to use the specified radius accessor function. + * Sets the radius used to display Point and MultiPoint geometries to use the specified radius accessor function. * * While the radius is commonly specified as a number constant, it may also be specified as a function which is computed per feature, * being passed the any arguments passed to the path generator. For example, if your GeoJSON data has additional properties, * you might access those properties inside the radius function to vary the point size; * alternatively, you could d3.symbol and a projection for greater flexibility. * - * @param value A value accessor function for the radius which is evaluated for each path to be rendered. The value accessor function is invoked within the "this" context in which the path generator is used. + * @param value A value accessor function for the radius which is evaluated for each path to be rendered. + * The value accessor function is invoked within the "this" context in which the path generator is used. * It is passed the object to be rendered, and any additional arguments which have been passed into the call to the render function of the path generator. */ pointRadius(value: (this: This, object: DatumObject, ...args: any[]) => number): this; @@ -1070,7 +1130,8 @@ export function geoPath(projection?: * * The default context is null, which implies that the path generator will return an SVG path string. * - * The first generic corresponds to the "this"-context within which the geo path generator will be invoked. This could be e.g. the DOMElement bound to "this" when using selection.attr("d", ...) with the path generator. + * The first generic corresponds to the "this"-context within which the geo path generator will be invoked. + * This could be e.g. the DOMElement bound to "this" when using selection.attr("d", ...) with the path generator. * * The second generic corresponds to the type of the DatumObject which will be passed into the geo path generator for rendering. * @@ -1339,15 +1400,15 @@ export interface GeoIdentityTranform extends GeoStreamWrapper { * @param object A geographic feature supported by d3-geo (An extension of GeoJSON feature). */ fitExtent(extent: [[number, number], [number, number]], object: ExtendedFeature): this; - /** - * Sets the projection’s scale and translate to fit the specified geographic feature collection in the center of the given extent. - * Returns the projection. - * - * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. - * - * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. - * @param object A geographic feature collection supported by d3-geo (An extension of GeoJSON feature collection). - */ + /** + * Sets the projection’s scale and translate to fit the specified geographic feature collection in the center of the given extent. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. + * @param object A geographic feature collection supported by d3-geo (An extension of GeoJSON feature collection). + */ fitExtent(extent: [[number, number], [number, number]], object: ExtendedFeatureCollection>): this; /** * Sets the projection’s scale and translate to fit the specified geographic geometry object in the center of the given extent. @@ -1359,15 +1420,15 @@ export interface GeoIdentityTranform extends GeoStreamWrapper { * @param object A GeoJson Geometry Object or GeoSphere object supported by d3-geo (An extension of GeoJSON). */ fitExtent(extent: [[number, number], [number, number]], object: GeoGeometryObjects): this; - /** - * Sets the projection’s scale and translate to fit the specified geographic geometry collection in the center of the given extent. - * Returns the projection. - * - * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. - * - * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. - * @param object A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). - */ + /** + * Sets the projection’s scale and translate to fit the specified geographic geometry collection in the center of the given extent. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. + * @param object A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). + */ fitExtent(extent: [[number, number], [number, number]], object: ExtendedGeometryCollection): this; diff --git a/d3-geo/tslint.json b/d3-geo/tslint.json new file mode 100644 index 0000000000..6a00563639 --- /dev/null +++ b/d3-geo/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "../tslint.json", + "rules": { + "unified-signatures": false, + "max-line-length": [false, 200] + } +} diff --git a/d3.cloud.layout/d3.cloud.layout-tests.ts b/d3.cloud.layout/d3.cloud.layout-tests.ts index b2e0349cd4..862b7f0d82 100644 --- a/d3.cloud.layout/d3.cloud.layout-tests.ts +++ b/d3.cloud.layout/d3.cloud.layout-tests.ts @@ -1,42 +1,40 @@ -/// +interface ICompTextSize{ + text:string; + size:number; + x?:number; + y?:number; + rotate?:number; +} - interface ICompTextSize{ - text:string; - size:number; - x?:number; - y?:number; - rotate?:number; - } +var fill = d3.scale.category20(); +d3.layout.cloud().size([300, 300]) + .words([ + "Hello", "world", "normally", "you", "want", "more", "words", + "than", "this"].map(function(d:string) { + return {text: d, size: 10 + Math.random() * 90}; + })) + .padding(5) + .rotate(function() { return ~~(Math.random() * 2) * 90; }) + .font("Impact") + .fontSize(function(d:ICompTextSize) { return d.size; }) + .on("end", draw) + .start(); - - var fill = d3.scale.category20(); - d3.layout.cloud().size([300, 300]) - .words([ - "Hello", "world", "normally", "you", "want", "more", "words", - "than", "this"].map(function(d:string) { - return {text: d, size: 10 + Math.random() * 90}; - })) - .padding(5) - .rotate(function() { return ~~(Math.random() * 2) * 90; }) - .font("Impact") - .fontSize(function(d:ICompTextSize) { return d.size; }) - .on("end", draw) - .start(); - function draw(words:ICompTextSize[]) { - d3.select("body").append("svg") - .attr("width", 300) - .attr("height", 300) - .append("g") - .attr("transform", "translate(150,150)") - .selectAll("text") - .data(words) - .enter().append("text") - .style("font-size", function(d:ICompTextSize) { return d.size + "px"; }) - .style("font-family", "Impact") - .style("fill", function(d:ICompTextSize, i:number) { return fill(i); }) - .attr("text-anchor", "middle") - .attr("transform", function(d:ICompTextSize) { - return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")"; - }) - .text(function(d:ICompTextSize) { return d.text; }); - } +function draw(words:ICompTextSize[]) { + d3.select("body").append("svg") + .attr("width", 300) + .attr("height", 300) + .append("g") + .attr("transform", "translate(150,150)") + .selectAll("text") + .data(words) + .enter().append("text") + .style("font-size", function(d:ICompTextSize) { return d.size + "px"; }) + .style("font-family", "Impact") + .style("fill", function(d:ICompTextSize, i:number) { return fill(i); }) + .attr("text-anchor", "middle") + .attr("transform", function(d:ICompTextSize) { + return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")"; + }) + .text(function(d:ICompTextSize) { return d.text; }); +} diff --git a/d3/index.d.ts b/d3/index.d.ts index bf7fa8e6b6..525c4dbfd3 100644 --- a/d3/index.d.ts +++ b/d3/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for D3JS d3 standard bundle 4.5 +// Type definitions for D3JS d3 standard bundle 4.7 // Project: https://github.com/d3/d3 // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/d3kit/d3kit-tests.ts b/d3kit/d3kit-tests.ts index c8a447ecda..e1a92d41b9 100644 --- a/d3kit/d3kit-tests.ts +++ b/d3kit/d3kit-tests.ts @@ -1,5 +1,3 @@ -/// - function test_abstract_chart() { let el: Element, chart: d3kit.AbstractChart, @@ -86,8 +84,8 @@ function test_svgchart() { options: d3kit.ChartOptions, margins: d3kit.ChartMargin, offsets: [number, number], - svg: d3.Selection, - rootg: d3.Selection, + svg: d3.Selection, + rootg: d3.Selection, layers: d3kit.LayerOrganizer; // create a div, append to body, return Node as type Element diff --git a/d3kit/v1/d3kit-tests.ts b/d3kit/v1/d3kit-tests.ts index d49891822b..9ffb7ca2ba 100644 --- a/d3kit/v1/d3kit-tests.ts +++ b/d3kit/v1/d3kit-tests.ts @@ -1,9 +1,6 @@ -/// /// /// -/* jshint expr: true */ - var expect = chai.expect; describe('Skeleton', function(){ var element: Element, $element: d3.Selection, $svg: d3.Selection, skeleton: d3kit.Skeleton; diff --git a/datatables-buttons/datatables-buttons-tests.ts b/datatables.net-buttons/datatables.net-buttons-tests.ts similarity index 91% rename from datatables-buttons/datatables-buttons-tests.ts rename to datatables.net-buttons/datatables.net-buttons-tests.ts index 52a21db894..6acbbeaf8a 100644 --- a/datatables-buttons/datatables-buttons-tests.ts +++ b/datatables.net-buttons/datatables.net-buttons-tests.ts @@ -1,7 +1,3 @@ -/// -/// - - $(document).ready(function () { var config: DataTables.Settings = diff --git a/datatables-buttons/index.d.ts b/datatables.net-buttons/index.d.ts similarity index 98% rename from datatables-buttons/index.d.ts rename to datatables.net-buttons/index.d.ts index 2ce52d8483..b4ed4b0eb5 100644 --- a/datatables-buttons/index.d.ts +++ b/datatables.net-buttons/index.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -/// +/// declare namespace DataTables { export interface Settings { diff --git a/antd/tsconfig.json b/datatables.net-buttons/tsconfig.json similarity index 90% rename from antd/tsconfig.json rename to datatables.net-buttons/tsconfig.json index 6b7785ac6c..5e407ab2d8 100644 --- a/antd/tsconfig.json +++ b/datatables.net-buttons/tsconfig.json @@ -9,7 +9,6 @@ "noImplicitThis": true, "strictNullChecks": false, "baseUrl": "../", - "jsx": "react", "typeRoots": [ "../" ], @@ -19,6 +18,6 @@ }, "files": [ "index.d.ts", - "antd-tests.tsx" + "datatables.net-buttons-tests.ts" ] } \ No newline at end of file diff --git a/datatables.net-fixedheader/index.d.ts b/datatables.net-fixedheader/index.d.ts index e72360f933..caf3987d35 100644 --- a/datatables.net-fixedheader/index.d.ts +++ b/datatables.net-fixedheader/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Jared Szechy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -/// +/// declare namespace DataTables { export interface Settings { diff --git a/datatables.net-select/index.d.ts b/datatables.net-select/index.d.ts index 1365ab991e..96529a10c1 100644 --- a/datatables.net-select/index.d.ts +++ b/datatables.net-select/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Jared Szechy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -/// +/// declare namespace DataTables { export interface Settings { diff --git a/jquery.datatables/jquery.datatables-tests.ts b/datatables.net/datatables.net-tests.ts similarity index 99% rename from jquery.datatables/jquery.datatables-tests.ts rename to datatables.net/datatables.net-tests.ts index 3bcc931a5f..c4a8fcaf3e 100644 --- a/jquery.datatables/jquery.datatables-tests.ts +++ b/datatables.net/datatables.net-tests.ts @@ -1,6 +1,3 @@ -/// - - $(document).ready(function () { //#region "Language" @@ -908,7 +905,7 @@ $(document).ready(function () { //#region "Methods-Static" - // Variable is a stand-in for $.fn.dataTable. See extension of JQueryStatic at the top of jquery.dataTables.d.ts. + // Variable is a stand-in for $.fn.dataTable. See extension of JQueryStatic at the top of index.d.ts. var staticFn: DataTables.StaticFunctions; // With boolean parameter type, always returns DataTables.DataTable[]. diff --git a/jquery.datatables/index.d.ts b/datatables.net/index.d.ts similarity index 100% rename from jquery.datatables/index.d.ts rename to datatables.net/index.d.ts diff --git a/jquery.datatables/tsconfig.json b/datatables.net/tsconfig.json similarity index 92% rename from jquery.datatables/tsconfig.json rename to datatables.net/tsconfig.json index 0831b7cc76..b48881c33b 100644 --- a/jquery.datatables/tsconfig.json +++ b/datatables.net/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "jquery.datatables-tests.ts" + "datatables.net-tests.ts" ] } \ No newline at end of file diff --git a/daterangepicker/index.d.ts b/daterangepicker/index.d.ts index 7929474994..d78e06dd97 100644 --- a/daterangepicker/index.d.ts +++ b/daterangepicker/index.d.ts @@ -140,6 +140,14 @@ declare namespace daterangepicker { * Text for apply label. */ applyLabel?: string; + /** + * Text for fromLabel label. + */ + fromLabel?: string; + /** + * Text for toLabel label. + */ + toLabel?: string; /** * Format of the date string. example: 'YYYY-MM-DD' */ diff --git a/dc/dc-tests.ts b/dc/dc-tests.ts index 9d2688fdf0..643594276d 100644 --- a/dc/dc-tests.ts +++ b/dc/dc-tests.ts @@ -180,6 +180,8 @@ d3.json("data/yelp_test_set_business.json", (yelp_data:IYelpData[]) => { .xAxis() .tickFormat((v: string) => v); + lineChart.legend(dc.legend().x(200).y(10).itemHeight(13).gap(5)); + rowChart .width(340) .height(850) diff --git a/dc/index.d.ts b/dc/index.d.ts index e7be4f86aa..9f9d7d3a57 100644 --- a/dc/index.d.ts +++ b/dc/index.d.ts @@ -111,14 +111,14 @@ declare namespace dc { } export interface Legend { - x: IGetSet; - y: IGetSet; - gap: IGetSet; - itemHeight: IGetSet; - horizontal: IGetSet; - legendWidth: IGetSet; - itemWidth: IGetSet; - autoItemWidth: IGetSet; + x: IGetSet; + y: IGetSet; + gap: IGetSet; + itemHeight: IGetSet; + horizontal: IGetSet; + legendWidth: IGetSet; + itemWidth: IGetSet; + autoItemWidth: IGetSet; render: () => void; } diff --git a/deep-equal/deep-equal-tests.ts b/deep-equal/deep-equal-tests.ts index 2f4f238a4f..ed23a35838 100644 --- a/deep-equal/deep-equal-tests.ts +++ b/deep-equal/deep-equal-tests.ts @@ -1,8 +1,11 @@ -import * as deepEqual from "deep-equal"; +import deepEqual = require("deep-equal"); -let isDeepEqual1: boolean = deepEqual({}, {}); -let isDeepEqual2: boolean = deepEqual({}, {}, { strict: true }); -let isDeepEqual3: boolean = deepEqual({}, {}, { strict: false }); +const isDeepEqual1: boolean = deepEqual({}, {}); +const isDeepEqual2: boolean = deepEqual({}, {}, { strict: true }); +const isDeepEqual3: boolean = deepEqual({}, {}, { strict: false }); +const isDeepEqual4: boolean = deepEqual(undefined, undefined); +const isDeepEqual5: boolean = deepEqual(3, false); +const isDeepEqual6: boolean = deepEqual("a-string", null); -console.log(isDeepEqual1, isDeepEqual2, isDeepEqual3); +console.log(isDeepEqual1, isDeepEqual2, isDeepEqual3, isDeepEqual4, isDeepEqual5, isDeepEqual6); diff --git a/deep-equal/index.d.ts b/deep-equal/index.d.ts index eef762a4ea..d9c4b5f6cf 100644 --- a/deep-equal/index.d.ts +++ b/deep-equal/index.d.ts @@ -1,17 +1,15 @@ -// Type definitions for deep-equal +// Type definitions for deep-equal 1.0 // Project: https://github.com/substack/node-deep-equal -// Definitions by: remojansen +// Definitions by: remojansen , Jay Anslow // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - interface DeepEqualOptions { strict: boolean; } -declare let deepEqual: ( - actual: Object, - expected: Object, - opts?: DeepEqualOptions) => boolean; +declare function deepEqual( + actual: any, + expected: any, + opts?: DeepEqualOptions): boolean; export = deepEqual; diff --git a/deep-equal/tsconfig.json b/deep-equal/tsconfig.json index b192443e3f..6d21a4a7e6 100644 --- a/deep-equal/tsconfig.json +++ b/deep-equal/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/deep-equal/tslint.json b/deep-equal/tslint.json new file mode 100644 index 0000000000..f9e30021f4 --- /dev/null +++ b/deep-equal/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} diff --git a/dockerode/index.d.ts b/dockerode/index.d.ts index c317d5d32e..968199436a 100644 --- a/dockerode/index.d.ts +++ b/dockerode/index.d.ts @@ -184,6 +184,7 @@ declare namespace Dockerode { Created: number; Ports: Port[]; Labels: { [label: string]: string }; + State: string; Status: string; HostConfig: { NetworkMode: string; diff --git a/draft-js/index.d.ts b/draft-js/index.d.ts index 1805a17ab0..a79de31e70 100644 --- a/draft-js/index.d.ts +++ b/draft-js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Draft.js v0.9.0 +// Type definitions for Draft.js v0.10.0 // Project: https://facebook.github.io/draft-js/ // Definitions by: Dmitry Rogozhny , Eelco Lempsink // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -357,7 +357,7 @@ declare namespace Draft { * - "props": Props to be passed into the React component that will be used. */ interface DraftDecorator { - strategy: (block: ContentBlock, callback: (start: number, end: number) => void) => void; + strategy: (block: ContentBlock, callback: (start: number, end: number) => void, contentState: ContentState) => void; component: Function; props?: Object; } @@ -564,6 +564,9 @@ declare namespace Draft { import DraftBlockType = Draft.Model.Constants.DraftBlockType; import DraftDecoratorType = Draft.Model.Decorators.DraftDecoratorType; + import DraftEntityType = Draft.Model.Entity.DraftEntityType; + import DraftEntityMutability = Draft.Model.Entity.DraftEntityMutability; + type DraftInlineStyle = Immutable.OrderedSet; type BlockMap = Immutable.OrderedMap; @@ -701,6 +704,10 @@ declare namespace Draft { static createFromBlockArray(blocks: Array): ContentState; static createFromText(text: string, delimiter?: string): ContentState; + createEntity(type: DraftEntityType, mutability: DraftEntityMutability, data?: Object): ContentState; + getEntity(key: string): EntityInstance; + getLastCreatedEntityKey(): string; + getBlockMap(): BlockMap; getSelectionBefore(): SelectionState; getSelectionAfter(): SelectionState; diff --git a/dw-bxslider-4/dw-bxslider-4-tests.ts b/dw-bxslider-4/dw-bxslider-4-tests.ts index e20f748a5d..57092d642f 100644 --- a/dw-bxslider-4/dw-bxslider-4-tests.ts +++ b/dw-bxslider-4/dw-bxslider-4-tests.ts @@ -1,6 +1,3 @@ -/// - - // examples from http://bxslider.com/examples $(document).ready(function() { diff --git a/dynatable/dynatable-tests.ts b/dynatable/dynatable-tests.ts index acba41092a..e727c209c1 100644 --- a/dynatable/dynatable-tests.ts +++ b/dynatable/dynatable-tests.ts @@ -1,5 +1,3 @@ -/// - // Using the global setup option // ============================= $.dynatableSetup({ features: { pushState: false }, dataset: { perPageDefault: 5, perPageOptions: [2, 5, 10] } }); diff --git a/ecurve/ecurve-tests.ts b/ecurve/ecurve-tests.ts index c2214c6905..ced84ef8aa 100644 --- a/ecurve/ecurve-tests.ts +++ b/ecurve/ecurve-tests.ts @@ -1,5 +1,3 @@ -/// - import ecurve = require('ecurve'); import crypto = require('crypto'); diff --git a/ej.web.all/ej.web.all-tests.ts b/ej.web.all/ej.web.all-tests.ts index faf5a48e0f..50b4c117e4 100644 --- a/ej.web.all/ej.web.all-tests.ts +++ b/ej.web.all/ej.web.all-tests.ts @@ -1,8 +1,5 @@ -/// -/// +/* tslint:disable */ - - module AccordionComponent { $(function () { var sample = new ej.Accordion($("#basicAccordion"), { @@ -15,8 +12,6 @@ module AccordionComponent { events: "click", expandSpeed: 500, headerSize: "40px", - height: "500px", - heightAdjustMode: ej.Accordion.HeightAdjustMode.Auto, htmlAttributes: { title: "Demo" }, selectedItemIndex: 1, showCloseButton: true, @@ -25,7 +20,7 @@ module AccordionComponent { }); } - + module AutocompleteComponent{ var carList = [ @@ -49,15 +44,15 @@ module AutocompleteComponent{ "Triumph Spitfire", "Toyota 2000GT", "Volvo P1800", "Volkswagen Shirako" ]; - $(function () { - var autocompleteInstance =new ej.Autocomplete($("#selectCar"), { + $(function () { + var autocompleteInstance =new ej.Autocomplete($("#selectCar"), { width: "100%", watermarkText: "Select a car", dataSource: carList, enableAutoFill: true, showPopupButton: true, multiSelectMode: "delimiter" - }); + }); }); } @@ -155,7 +150,7 @@ module ButtonComponent { }); }); } - + @@ -171,7 +166,7 @@ module ChartComponent { range: { min: 25, max: 50, interval: 5 }, labelFormat: "{value}%", title: { text: "Efficiency" }, - + }, commonSeriesOptions: { @@ -186,28 +181,28 @@ module ChartComponent { }, visible: true }, - border : {width: 2} - }, - series: + border : {width: 2} + }, + series: [ { - points: [{ x: 2005, y: 28 }, { x: 2006, y: 25 },{ x: 2007, y: 26 }, { x: 2008, y: 27 }, - { x: 2009, y: 32 }, { x: 2010, y: 35 }, { x: 2011, y: 30 }], + points: [{ x: 2005, y: 28 }, { x: 2006, y: 25 },{ x: 2007, y: 26 }, { x: 2008, y: 27 }, + { x: 2009, y: 32 }, { x: 2010, y: 35 }, { x: 2011, y: 30 }], name: 'India' - }, + }, { - points: [{ x: 2005, y: 31 }, { x: 2006, y: 28 },{ x: 2007, y: 30 }, { x: 2008, y: 36 }, - { x: 2009, y: 36 }, { x: 2010, y: 39 }, { x: 2011, y: 37 }], + points: [{ x: 2005, y: 31 }, { x: 2006, y: 28 },{ x: 2007, y: 30 }, { x: 2008, y: 36 }, + { x: 2009, y: 36 }, { x: 2010, y: 39 }, { x: 2011, y: 37 }], name: 'Germany' }, { - points: [{ x: 2005, y: 36 }, { x: 2006, y: 32 },{ x: 2007, y: 34 }, { x: 2008, y: 41 }, - { x: 2009, y: 42 }, { x: 2010, y: 42 }, { x: 2011, y: 43 }], + points: [{ x: 2005, y: 36 }, { x: 2006, y: 32 },{ x: 2007, y: 34 }, { x: 2008, y: 41 }, + { x: 2009, y: 42 }, { x: 2010, y: 42 }, { x: 2011, y: 43 }], name: 'England' - }, + }, { - points: [{ x: 2005, y: 39 }, { x: 2006, y: 36 },{ x: 2007, y: 40 }, { x: 2008, y: 44 }, - { x: 2009, y: 45 }, { x: 2010, y: 48 }, { x: 2011, y: 46 }], + points: [{ x: 2005, y: 39 }, { x: 2006, y: 36 },{ x: 2007, y: 40 }, { x: 2008, y: 44 }, + { x: 2009, y: 45 }, { x: 2010, y: 48 }, { x: 2011, y: 46 }], name: 'France' } ], @@ -247,6 +242,62 @@ module ChartComponent { + + +module circulargaugecomponent { + $(function () { + var circularsample = new ej.datavisualization.CircularGauge($("#CircularGauge"), { + enableAnimation: false, + isResponsive: true, + backgroundColor: "transparent", width: 500, + scales: [{ + showRanges: true, + startAngle: 122, sweepAngle: 296, radius: 130, showScaleBar: true, size: 1, maximum: 120, majorIntervalValue: 20, minorIntervalValue: 10, + border: { + width: 0.5, + }, + pointers: [{ + value: 60, + showBackNeedle: true, + backNeedleLength: 20, + length: 95, + width: 7 + }], + ticks: [{ + type: "major", + distanceFromScale: 2, + height: 16, + width: 1, color: "#8c8c8c" + }, { type: "minor", height: 8, width: 1, distanceFromScale: 2, color: "#8c8c8c" }], + labels: [{ + color: "#8c8c8c" + }], + ranges: [{ + distanceFromScale: -30, + startValue: 0, + endValue: 70 + }, { + distanceFromScale: -30, + startValue: 70, + endValue: 110, + backgroundColor: "#fc0606", + border: { color: "#fc0606" } + }, + { + distanceFromScale: -30, + startValue: 110, + endValue: 120, + backgroundColor: "#f5b43f", + border: { color: "#f5b43f" } + }] + }] + }); + }); +} + + + + module ColorPickerComponent { $(function () { var colorSample = new ej.ColorPicker($("#colorpick"), { @@ -304,14 +355,18 @@ $(function () { snapConstraints: ej.datavisualization.Diagram.SnapConstraints.ShowLines }, nodes: [ - createNode({ name: "NewIdea", width: 150, height: 60, offsetX: 300, offsetY: 60, labels: [createLabel({ "text": "New idea identified" })], type: "flow", shape: "terminator" }), - createNode({ name: "Meeting", width: 150, height: 60, offsetX: 300, offsetY: 155, labels: [createLabel({ "text": "Meeting with board" })], type: "flow", shape: "process" }), - createNode({ name: "BoardDecision", width: 150, height: 110, offsetX: 300, offsetY: 280, labels: [createLabel({ text: "Board decides \nwhether \nto proceed", wrapText: "true", "margin": { left: 20, top: 0, right: 20, bottom: 0 } })], type: "flow", shape: "decision" }), - createNode({ name: "Project", width: 150, height: 100, offsetX: 300, offsetY: 430, labels: [createLabel({ "text": "Find Project \nmanager" })], type: "flow", shape: "decision" }), - createNode({ name: "End", width: 150, height: 60, offsetX: 300, offsetY: 555, labels: [createLabel({ "text": "Implement and Deliver" })], type: "flow", shape: "process" }), - createNode({ name: "Decision", width: 250, height: 60, offsetX: 550, offsetY: 60, labels: [createLabel({ "text": "Decision Process for new software ideas" })], type: "flow", shape: "card", fillColor: "#858585", borderColor: "#858585" }), - createNode({ name: "Reject", width: 150, height: 60, offsetX: 550, offsetY: 285, labels: [createLabel({ "text": "Reject and write report" })], type: "flow", shape: "process" }), - createNode({ name: "Resources", width: 150, height: 60, offsetX: 550, offsetY: 430, labels: [createLabel({ "text": "Hire new resources" })], type: "flow", shape: "process" }) + createNode({ name: "NewIdea", width: 150, height: 60, offsetX: 300, offsetY: 60, labels: [createLabel({ "text": "New idea identified" })], type: "flow", shape: ej.datavisualization.Diagram.FlowShapes.Terminator }), + createNode({ name: "Meeting", width: 150, height: 60, offsetX: 300, offsetY: 155, labels: [createLabel({ "text": "Meeting with board" })], type: "flow", shape: ej.datavisualization.Diagram.FlowShapes.Process }), + createNode({ + name: "BoardDecision", width: 150, height: 110, offsetX: 300, offsetY: 280, labels: [createLabel({ text: "Board decides \nwhether \nto proceed", wrapText: "true", "margin": { left: 20, top: 0, right: 20, bottom: 0 } })], + type: "flow", shape: ej.datavisualization.Diagram.FlowShapes.Decision + }), + createNode({ name: "Project", width: 150, height: 100, offsetX: 300, offsetY: 430, labels: [createLabel({ "text": "Find Project \nmanager" })], type: "flow", shape: ej.datavisualization.Diagram.FlowShapes.Decision }), + createNode({ + name: "End", width: 150, height: 60, offsetX: 300, offsetY: 555, labels: [createLabel({ "text": "Implement and Deliver" })], type: "flow", shape: ej.datavisualization.Diagram.FlowShapes.Process }), + createNode({ name: "Decision", width: 250, height: 60, offsetX: 550, offsetY: 60, labels: [createLabel({ "text": "Decision Process for new software ideas" })], type: "flow", shape: ej.datavisualization.Diagram.FlowShapes.Card, fillColor: "#858585", borderColor: "#858585" }), + createNode({ name: "Reject", width: 150, height: 60, offsetX: 550, offsetY: 285, labels: [createLabel({ "text": "Reject and write report" })], type: "flow", shape: ej.datavisualization.Diagram.FlowShapes.Process }), + createNode({ name: "Resources", width: 150, height: 60, offsetX: 550, offsetY: 430, labels: [createLabel({ "text": "Hire new resources" })], type: "flow", shape: ej.datavisualization.Diagram.FlowShapes.Process }) ], connectors: [ createConnector({ name: "connector1", sourceNode: "NewIdea", targetNode: "Meeting" }), @@ -322,7 +377,7 @@ $(function () { createConnector({ name: "connector6", sourceNode: "Project", targetNode: "Resources", labels: [createLabel({ "text": "No" })] }) ] }); - + }); function createNode(option: ej.datavisualization.Diagram.Node) { @@ -347,7 +402,7 @@ function createLabel(options : any) { return options; } - + module DialogComponent { $(function () { @@ -356,11 +411,14 @@ module DialogComponent { minWidth: 310, minHeight: 215, target:".control", - close:()=>{this.onDialogClose()} + close:()=>{ + $("#btnOpen").show();} }); var btnInstance = new ej.Button($("#btnOpen"), { size: "medium", - click: ()=>{this.onOpen()}, + click: ()=>{ + $("#btnOpen").hide(); + $("#basicDialog").ejDialog("open");}, type: "button", height: 30, width: 150 @@ -368,13 +426,6 @@ module DialogComponent { }); } -function onDialogClose(args:any) { - $("#btnOpen").show(); -} -function onOpen() { - $("#btnOpen").hide(); - $("#basicDialog").ejDialog("open"); -} @@ -401,7 +452,7 @@ module digitalgaugecomponent { } - + @@ -421,16 +472,14 @@ module DropDownListComponent { enableFilterSearch: true, caseSensitiveSearch: true, enableIncrementalSearch: true, - enablePopupResize: true, + enablePopupResize: true, delimiterChar: ";", multiSelectMode: ej.MultiSelectMode.Delimiter, maxPopupHeight: "300px", - minPopupHeight: "150px", - maxPopupWidth: "500px", + minPopupHeight: "150px", + maxPopupWidth: "500px", minPopupWidth: "350px", - selectedIndex: 1, showCheckbox: true, - showPopupOnLoad: true, showRoundedCorner: true }); }); @@ -445,12 +494,12 @@ module DropDownListComponent { module ExplorerComponent { $(function () { var file = new ej.FileExplorer($("#fileExplorer"), { - path: (window).baseurl + "webapi/FileExplorer/FileBrowser/", + path: (window).baseurl + "Content/FileBrowser/", width: "100%", minWidth: "150px", layout: "tile", isResponsive: true, - ajaxAction: (window).baseurl + "api/fileoperation/doJSONAction" + ajaxAction: (window).baseurl + "api/FileExplorer/FileOperations" }); }); } @@ -464,7 +513,7 @@ module GanttComponent { dataSource: (window).projectData, allowColumnResize: true, allowSorting: true, - allowSelection: true, + allowSelection: true, enableContextMenu: true, taskIdMapping: "taskID", allowDragAndDrop: true, @@ -505,7 +554,7 @@ module GanttComponent { treeColumnIndex: 1, isResponsive: true, }); -}); +}); } @@ -547,7 +596,7 @@ module GridComponent { -var columns = ["Vegie-spread", "Tofuaa", "Alice Mutton", "Konbu", "Fløtemysost"] +var columns = ["Vegie-spread", "Tofuaa", "Alice Mutton", "Konbu", "Fløtemysost"] var itemSource: any[] = []; for (var i = 0; i < columns.length; i++) { for (var j = 0; j < 6; j++) { @@ -621,7 +670,7 @@ module KanbanComponent { }); } - + module lineargaugecomponent { @@ -647,14 +696,14 @@ module lineargaugecomponent { backgroundColor: "#E94649", border: { color: "#E94649" }, startWidth: 4, endWidth: 4 }] - }] + }] }); }); } - - + + module ListBoxComponent { $(function () { @@ -664,12 +713,12 @@ module ListBoxComponent { }); } - + module ListviewComponent { $(function () { var listviewInstance = new ej.ListView($("#defaultlistview"), { - enableCheckMark: true, + enableCheckMark: true, width: 400 }); }); @@ -711,7 +760,7 @@ var world_map= { "type": "Feature", "properties": { "admin": "Switzerland", "name": "Switzerland", "continent": "Europe" }, "geometry": { "type": "Polygon", "coordinates": [[[9.594226108446346, 47.525058091820256], [9.632931756232974, 47.347601223329974], [9.479969516649019, 47.102809963563367], [9.932448357796657, 46.920728054382948], [10.442701450246627, 46.893546250997424], [10.36337812667861, 46.483571275409851], [9.922836541390378, 46.314899400409182], [9.182881707403054, 46.440214748716976], [8.966305779667804, 46.036931871111186], [8.489952426801322, 46.005150865251672], [8.316629672894377, 46.163642483090847], [7.755992058959832, 45.824490057959302], [7.273850945676655, 45.776947740250769], [6.843592970414504, 45.991146552100595], [6.500099724970424, 46.429672756529428], [6.022609490593537, 46.272989813820466], [6.037388950229, 46.725778713561859], [6.768713820023605, 47.287708238303686], [6.736571079138058, 47.541801255882838], [7.192202182655505, 47.449765529971003], [7.466759067422228, 47.620581976911794], [8.31730146651415, 47.613579820336255], [8.522611932009765, 47.830827541691285], [9.594226108446346, 47.525058091820256]]] } }, { "type": "Feature", "properties": { "admin": "Chile", "name": "Chile", "continent": "South America" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-68.634010227583147, -52.636370458874353], [-68.633349999999879, -54.8695], [-67.56244, -54.87001], [-66.95992, -54.89681], [-67.291029999999878, -55.30124], [-68.148629999999841, -55.61183], [-68.639990810811796, -55.580017999086877], [-69.2321, -55.49906], [-69.95809, -55.19843], [-71.00568, -55.05383], [-72.2639, -54.49514], [-73.2852, -53.957519999999874], [-74.66253, -52.83749], [-73.8381, -53.04743], [-72.43418, -53.7154], [-71.10773, -54.07433], [-70.591779999999787, -53.61583], [-70.26748, -52.93123], [-69.345649999999878, -52.5183], [-68.634010227583147, -52.636370458874353]]], [[[-68.219913092711224, -21.49434661223183], [-67.828179897722634, -22.872918796482178], [-67.106673550063604, -22.735924574476392], [-66.985233934177629, -22.986348565362825], [-67.328442959244128, -24.025303236590908], [-68.417652960876111, -24.518554782816874], [-68.386001146097342, -26.185016371365229], [-68.594799770772667, -26.50690886811126], [-68.295541551370391, -26.899339694935787], [-69.001234910748266, -27.521213881136127], [-69.656130337183143, -28.459141127233686], [-70.013550381129861, -29.367922865518544], [-69.919008348251921, -30.336339206668306], [-70.535068935819439, -31.365010267870279], [-70.074399380153622, -33.09120981214803], [-69.814776984319209, -33.273886000299839], [-69.817309129501453, -34.193571465798279], [-70.388049485949082, -35.169687595359441], [-70.364769253201658, -36.005088799789931], [-71.121880662709771, -36.65812387466233], [-71.118625047475419, -37.576827487947192], [-70.814664272734703, -38.552995293940732], [-71.413516608349042, -38.916022230791107], [-71.680761277946445, -39.808164157878061], [-71.915734015577542, -40.832339369470716], [-71.746803758415453, -42.051386407235988], [-72.148898078078517, -42.254888197601375], [-71.915423956983901, -43.408564548517404], [-71.464056159130493, -43.787611179378324], [-71.793622606071935, -44.207172133156099], [-71.329800788036195, -44.407521661151677], [-71.222778896759721, -44.784242852559409], [-71.659315558545316, -44.973688653341434], [-71.552009446891233, -45.560732924177117], [-71.917258470330196, -46.884838148791786], [-72.44735531278026, -47.738532810253517], [-72.331160854771937, -48.244238376661819], [-72.648247443314929, -48.878618259476774], [-73.415435757120022, -49.318436374712952], [-73.328050910114456, -50.378785088909865], [-72.975746832964617, -50.741450290734299], [-72.309973517532342, -50.677009779666342], [-72.329403856074023, -51.425956312872394], [-71.914803839796321, -52.009022305865912], [-69.498362189396076, -52.142760912637236], [-68.571545376241332, -52.299443855346247], [-69.461284349226617, -52.291950772663924], [-69.94277950710611, -52.537930590373243], [-70.8451016913545, -52.899200528525711], [-71.006332160105217, -53.833252042201345], [-71.429794684520928, -53.856454760300373], [-72.557942877884855, -53.531410001184447], [-73.702756720662862, -52.835069268607249], [-73.702756720662862, -52.835070076051487], [-74.946763475225154, -52.262753588419017], [-75.260026007778507, -51.62935475037321], [-74.976632453089806, -51.043395684615675], [-75.47975419788348, -50.378371677451547], [-75.608015102831942, -48.673772881871784], [-75.182769741502128, -47.711919447623153], [-74.126580980104677, -46.939253431995084], [-75.644395311165439, -46.647643324572016], [-74.69215369332305, -45.76397633238097], [-74.351709357384252, -44.10304412208788], [-73.240356004515192, -44.454960625995611], [-72.717803921179765, -42.383355808278985], [-73.388899909138232, -42.117532240569567], [-73.701335618774834, -43.365776462579738], [-74.33194312203257, -43.224958184584395], [-74.017957119427152, -41.794812920906828], [-73.677099372029943, -39.942212823243111], [-73.217592536090663, -39.258688653318508], [-73.505559455037044, -38.282882582351064], [-73.588060879191076, -37.156284681956016], [-73.166717088499283, -37.123780206044351], [-72.553136969681717, -35.508840020491022], [-71.861732143832555, -33.909092706031522], [-71.438450486929895, -32.418899428030819], [-71.668720669222424, -30.920644626592516], [-71.370082567007714, -30.095682061484997], [-71.48989437527645, -28.861442152625909], [-70.905123867461569, -27.640379734001193], [-70.724953986275963, -25.705924167587209], [-70.403965827095035, -23.628996677344542], [-70.091245897080668, -21.393319187101223], [-70.164419725205974, -19.756468194256183], [-70.372572394477714, -18.347975355708879], [-69.858443569605797, -18.092693780187027], [-69.590423753523979, -17.580011895419286], [-69.100246955019401, -18.260125420812653], [-68.966818406841824, -18.981683444904089], [-68.442225104430918, -19.405068454671419], [-68.757167121033703, -20.37265797290447], [-68.219913092711224, -21.49434661223183]]]] } }, { "type": "Feature", "properties": { "admin": "China", "name": "China", "continent": "Asia" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[110.339187860151526, 18.678395087147603], [109.475209588663702, 18.19770091396861], [108.655207961056135, 18.507681993071397], [108.626217482540426, 19.367887885001974], [109.119055617308007, 19.821038519769385], [110.211598748822837, 20.101253973872073], [110.786550734502228, 20.077534491450077], [111.01005130416462, 19.695929877190732], [110.570646600386794, 19.255879218009305], [110.339187860151526, 18.678395087147603]]], [[[127.657407261262378, 49.760270494172929], [129.397817824420429, 49.440600084015429], [130.58229332898236, 48.729687404976112], [130.987281528853828, 47.790132351261391], [132.506671991099495, 47.788969631534876], [133.373595819228001, 48.183441677434914], [135.026311476786702, 48.478229885443902], [134.500813836810607, 47.578439846377833], [134.112362095272601, 47.212467352886719], [133.76964399631288, 46.116926988299056], [133.097126906466428, 45.14406647397216], [131.883454217659562, 45.32116160743643], [131.025212030156069, 44.967953192721573], [131.288555129115537, 44.111519680348252], [131.144687941614848, 42.929989732426932], [130.633866408409801, 42.903014634770543], [130.640015903852429, 42.39500946712527], [129.994267205933227, 42.985386867843793], [129.596668735879462, 42.424981797854592], [128.05221520397231, 41.994284572917984], [128.208433058790717, 41.466771552082534], [127.343782993683021, 41.503151760415953], [126.869083286649854, 41.816569322266155], [126.18204511932943, 41.107336127276362], [125.079941847840587, 40.569823716792449], [124.265624627785314, 39.928493353834135], [122.86757042856101, 39.637787583976255], [122.131387974130917, 39.170451768544623], [121.054554478032856, 38.89747101496291], [121.585994907722466, 39.360853583324136], [121.376757033372641, 39.750261338859524], [122.168595005381007, 40.422442531896046], [121.640358514493528, 40.946389878903304], [120.768628778161954, 40.593388169917596], [119.639602085449056, 39.898055935214209], [119.023463983233015, 39.252333075511096], [118.042748651197897, 39.204273993479674], [117.532702264477052, 38.73763580988409], [118.05969852098967, 38.061475531561051], [118.878149855628351, 37.897325344385898], [118.911636183753501, 37.448463853498723], [119.702802362142037, 37.156388658185072], [120.823457472823648, 37.870427761377968], [121.711258579597938, 37.481123358707165], [122.357937453298462, 37.454484157860684], [122.519994744965814, 36.930614325501828], [121.104163853033029, 36.651329047180432], [120.63700890511457, 36.111439520811125], [119.66456180224607, 35.609790554337728], [119.151208123858567, 34.909859117160458], [120.227524855633717, 34.360331936168613], [120.620369093916565, 33.37672272392512], [121.229014113450219, 32.460318711877186], [121.908145786630044, 31.692174384074683], [121.891919386890336, 30.949351508095098], [121.264257440273298, 30.676267401648712], [121.503519321784722, 30.14291494396425], [122.092113885589086, 29.832520453403156], [121.93842817595305, 29.018022365834803], [121.684438511238469, 28.225512600206677], [121.125661248866436, 28.135673122667178], [120.395473260582307, 27.053206895449385], [119.585496860839555, 25.740780544532605], [118.656871372554519, 24.547390855400234], [117.281606479970833, 23.624501451099714], [115.890735304835118, 22.782873236578094], [114.763827345846209, 22.668074042241663], [114.152546828265656, 22.223760077396204], [113.806779819800752, 22.548339748621423], [113.241077915501592, 22.051367499270462], [111.843592157032447, 21.550493679281512], [110.78546552942413, 21.39714386645533], [110.444039341271662, 20.34103261970639], [109.88986128137357, 20.282457383703441], [109.627655063924635, 21.008227037026725], [109.864488153118316, 21.395050970947516], [108.522812941524421, 21.715212307211821], [108.050180291782979, 21.552379869060101], [107.043420037872636, 21.8118989120299], [106.567273390735352, 22.21820486092474], [106.725403273548466, 22.794267889898375], [105.811247186305209, 22.976892401617899], [105.329209425886631, 23.352063300056976], [104.476858351664475, 22.819150092046918], [103.504514601660503, 22.703756618739217], [102.706992222100155, 22.708795070887696], [102.170435825613552, 22.464753119389336], [101.652017856861576, 22.318198757409554], [101.803119744882906, 21.174366766845051], [101.27002566936001, 21.201651923095167], [101.180005324307558, 21.436572984294052], [101.150032993578236, 21.849984442629015], [100.416537713627349, 21.558839423096654], [99.983489211021549, 21.742936713136451], [99.240898878987196, 22.118314317304559], [99.53199222208741, 22.949038804612591], [98.898749220782804, 23.142722072842581], [98.66026248575578, 24.063286037690002], [97.604719679762027, 23.897404690033049], [97.724609002679131, 25.083637193293036], [98.671838006589212, 25.91870250091349], [98.712093947344556, 26.743535874940243], [98.682690057370507, 27.508812160750658], [98.246230910233351, 27.747221381129172], [97.91198774616943, 28.335945136014367], [97.327113885490007, 28.261582749946339], [96.248833449287829, 28.411030992134467], [96.586590610747521, 28.830979519154361], [96.117678664131006, 29.452802028922513], [95.404802280664626, 29.031716620392157], [94.565990431702929, 29.27743805593996], [93.413347609432662, 28.640629380807233], [92.503118931043616, 27.896876329046442], [91.696656528696693, 27.771741848251615], [91.258853794319876, 28.040614325466343], [90.730513950567797, 28.064953925075738], [90.015828891971182, 28.296438503527177], [89.475810174521158, 28.042758897406365], [88.814248488320573, 27.299315904239389], [88.730325962278528, 28.086864732367552], [88.120440708369941, 27.876541652939572], [86.954517043000635, 27.974261786403524], [85.823319940131526, 28.203575954698742], [85.011638218123053, 28.642773952747369], [84.23457970575015, 28.839893703724691], [83.89899295444674, 29.320226141877633], [83.337115106137176, 29.463731594352193], [82.327512648450877, 30.115268052688204], [81.525804477874786, 30.422716986608659], [81.111256138029276, 30.183480943313402], [79.721366815107118, 30.882714748654728], [78.738894484374001, 31.515906073527045], [78.458446486326025, 32.61816437431272], [79.176128777995544, 32.483779812137747], [79.208891636068543, 32.994394639613738], [78.811086460285722, 33.506198025032397], [78.912268914713209, 34.321936346975768], [77.83745079947461, 35.494009507787794], [76.192848341785705, 35.89840342868785], [75.896897414050173, 36.666806138651872], [75.158027785140987, 37.133030910789152], [74.980002475895404, 37.419990139305888], [74.829985792952144, 37.990007025701445], [74.864815708316783, 38.378846340481587], [74.25751427602269, 38.606506862943476], [73.928852166646394, 38.505815334622717], [73.675379266254836, 39.431236884105566], [73.960013055318427, 39.660008449861714], [73.822243686828315, 39.893973497063136], [74.776862420556043, 40.366425279291619], [75.467827996730719, 40.56207225194867], [76.526368035797432, 40.427946071935132], [76.90448449087711, 41.066485907549648], [78.187196893226044, 41.185315863604799], [78.543660923175253, 41.582242540038713], [80.119430373051401, 42.12394074153822], [80.259990268885318, 42.34999929459908], [80.180150180994374, 42.920067857426844], [80.866206496101213, 43.180362046881008], [79.966106398441426, 44.917516994804622], [81.947070753918084, 45.317027492853143], [82.458925815769035, 45.539649563166499], [83.180483839860543, 47.330031236350735], [85.164290399113213, 47.000955715516099], [85.720483839870667, 47.452969468773077], [85.76823286330837, 48.455750637396896], [86.59877648310335, 48.549181626980605], [87.359970330762692, 49.214980780629148], [87.751264276076668, 49.297197984405464], [88.013832228551678, 48.599462795600594], [88.854297723346747, 48.069081732773007], [90.280825636763893, 47.693549099307901], [90.970809360724957, 46.88814606382293], [90.585768263718307, 45.719716091487491], [90.945539585334316, 45.286073309910243], [92.133890822318222, 45.115075995456429], [93.480733677141316, 44.97547211362], [94.688928664125356, 44.352331854828456], [95.306875441471504, 44.241330878265458], [95.762454868556688, 43.319449164394619], [96.349395786527808, 42.725635280928643], [97.451757440177971, 42.74888967546007], [99.515817498779995, 42.524691473961688], [100.845865513108279, 42.663804429691417], [101.833040399179936, 42.51487295182627], [103.312278273534787, 41.907468166667613], [104.522281935649005, 41.90834666601662], [104.964993931093431, 41.597409572916334], [106.129315627061658, 42.134327704428891], [107.744772576937976, 42.481515814781908], [109.243595819131428, 42.519446316084149], [110.412103306115299, 42.871233628911014], [111.129682244920218, 43.406834011400171], [111.82958784388137, 43.743118394539486], [111.667737257943202, 44.073175767587706], [111.348376906379428, 44.457441718110047], [111.87330610560025, 45.102079372735112], [112.436062453258842, 45.01164561622425], [113.463906691544196, 44.808893134127111], [114.46033165899604, 45.339816799493875], [115.985096470200133, 45.727235012386004], [116.717868280098855, 46.38820241961524], [117.421701287914246, 46.67273285581421], [118.874325799638711, 46.805412095723646], [119.663269891438745, 46.692679958678944], [119.772823927897562, 47.048058783550132], [118.866574334794947, 47.747060044946195], [118.064142694166719, 48.06673045510373], [117.295507440257438, 47.697709052107385], [116.308952671373234, 47.853410142602812], [115.742837355615734, 47.726544501326273], [115.485282017073018, 48.135382595403442], [116.191802199367601, 49.134598090199056], [116.67880089728618, 49.888531399121398], [117.879244419426371, 49.510983384796944], [119.288460728025839, 50.142882798862033], [119.279365675942358, 50.582907619827282], [120.182049595216924, 51.64356639261802], [120.738191359541972, 51.964115302124547], [120.725789015791975, 52.516226304730814], [120.177088657716865, 52.753886216841195], [121.003084751470226, 53.251401068731226], [122.245747918792858, 53.431725979213681], [123.571506789240843, 53.458804429734627], [125.068211297710434, 53.161044826868832], [125.946348911646169, 52.792798570356936], [126.564399041856959, 51.784255479532689], [126.939156528837657, 51.353894151405896], [127.287455682484904, 50.739797268265434], [127.657407261262378, 49.760270494172929]]]] } }, - { "type": "Feature", "properties": { "admin": "Ivory Coast", "name": "Côte d'Ivoire", "continent": "Africa" }, "geometry": { "type": "Polygon", "coordinates": [[[-2.856125047202397, 4.994475816259508], [-3.311084357100071, 4.984295559098014], [-4.008819545904941, 5.179813340674314], [-4.64991736491791, 5.168263658057084], [-5.834496222344525, 4.993700669775135], [-6.528769090185845, 4.705087795425015], [-7.518941209330434, 4.338288479017307], [-7.712159389669749, 4.364565944837721], [-7.63536821128403, 5.188159084489455], [-7.53971513511176, 5.313345241716517], [-7.570152553731686, 5.707352199725903], [-7.993692592795879, 6.126189683451541], [-8.311347622094017, 6.193033148621081], [-8.602880214868618, 6.467564195171659], [-8.385451626000572, 6.911800645368742], [-8.485445522485348, 7.395207831243068], [-8.439298468448696, 7.686042792181736], [-8.280703497744936, 7.687179673692156], [-8.221792364932197, 8.123328762235571], [-8.299048631208562, 8.316443589710302], [-8.203498907900878, 8.455453192575446], [-7.832100389019186, 8.575704250518625], [-8.079113735374348, 9.376223863152033], [-8.309616461612249, 9.789531968622439], [-8.22933712404682, 10.129020290563897], [-8.029943610048617, 10.206534939001711], [-7.89958980959237, 10.297382106970824], [-7.622759161804808, 10.147236232946792], [-6.850506557635057, 10.138993841996237], [-6.666460944027547, 10.430810655148447], [-6.493965013037267, 10.411302801958268], [-6.205222947606429, 10.524060777219132], [-6.050452032892266, 10.096360785355442], [-5.816926235365286, 10.222554633012191], [-5.404341599946973, 10.370736802609144], [-4.954653286143098, 10.152713934769732], [-4.779883592131966, 9.821984768101741], [-4.330246954760383, 9.610834865757139], [-3.980449184576684, 9.862344061721698], [-3.511898972986272, 9.900326239456216], [-2.827496303712706, 9.642460842319775], [-2.56218950032624, 8.219627793811481], [-2.983584967450326, 7.379704901555511], [-3.244370083011261, 6.2504715031135], [-2.810701463217839, 5.389051215024109], [-2.856125047202397, 4.994475816259508]]] } }, + { "type": "Feature", "properties": { "admin": "Ivory Coast", "name": "Côte d'Ivoire", "continent": "Africa" }, "geometry": { "type": "Polygon", "coordinates": [[[-2.856125047202397, 4.994475816259508], [-3.311084357100071, 4.984295559098014], [-4.008819545904941, 5.179813340674314], [-4.64991736491791, 5.168263658057084], [-5.834496222344525, 4.993700669775135], [-6.528769090185845, 4.705087795425015], [-7.518941209330434, 4.338288479017307], [-7.712159389669749, 4.364565944837721], [-7.63536821128403, 5.188159084489455], [-7.53971513511176, 5.313345241716517], [-7.570152553731686, 5.707352199725903], [-7.993692592795879, 6.126189683451541], [-8.311347622094017, 6.193033148621081], [-8.602880214868618, 6.467564195171659], [-8.385451626000572, 6.911800645368742], [-8.485445522485348, 7.395207831243068], [-8.439298468448696, 7.686042792181736], [-8.280703497744936, 7.687179673692156], [-8.221792364932197, 8.123328762235571], [-8.299048631208562, 8.316443589710302], [-8.203498907900878, 8.455453192575446], [-7.832100389019186, 8.575704250518625], [-8.079113735374348, 9.376223863152033], [-8.309616461612249, 9.789531968622439], [-8.22933712404682, 10.129020290563897], [-8.029943610048617, 10.206534939001711], [-7.89958980959237, 10.297382106970824], [-7.622759161804808, 10.147236232946792], [-6.850506557635057, 10.138993841996237], [-6.666460944027547, 10.430810655148447], [-6.493965013037267, 10.411302801958268], [-6.205222947606429, 10.524060777219132], [-6.050452032892266, 10.096360785355442], [-5.816926235365286, 10.222554633012191], [-5.404341599946973, 10.370736802609144], [-4.954653286143098, 10.152713934769732], [-4.779883592131966, 9.821984768101741], [-4.330246954760383, 9.610834865757139], [-3.980449184576684, 9.862344061721698], [-3.511898972986272, 9.900326239456216], [-2.827496303712706, 9.642460842319775], [-2.56218950032624, 8.219627793811481], [-2.983584967450326, 7.379704901555511], [-3.244370083011261, 6.2504715031135], [-2.810701463217839, 5.389051215024109], [-2.856125047202397, 4.994475816259508]]] } }, { "type": "Feature", "properties": { "admin": "Cameroon", "name": "Cameroon", "continent": "Africa" }, "geometry": { "type": "Polygon", "coordinates": [[[13.07582238124675, 2.267097072759014], [12.951333855855605, 2.321615708826939], [12.359380323952218, 2.19281220133945], [11.751665480199787, 2.326757513839993], [11.276449008843711, 2.261050930180871], [9.649158155972627, 2.283866075037735], [9.795195753629455, 3.073404445809117], [9.404366896205998, 3.734526882335202], [8.948115675501068, 3.904128933117135], [8.744923943729416, 4.352215277519959], [8.488815545290889, 4.495617377129917], [8.500287713259693, 4.771982937026847], [8.757532993208626, 5.47966583904791], [9.233162876023043, 6.444490668153334], [9.522705926154398, 6.453482367372116], [10.118276808318255, 7.038769639509879], [10.497375115611417, 7.055357774275562], [11.058787876030349, 6.644426784690593], [11.745774366918509, 6.981382961449753], [11.839308709366801, 7.397042344589434], [12.063946160539556, 7.799808457872301], [12.218872104550597, 8.305824082874322], [12.753671502339214, 8.717762762888993], [12.955467970438971, 9.417771714714702], [13.1675997249971, 9.64062632897341], [13.308676385153914, 10.160362046748926], [13.572949659894558, 10.798565985553564], [14.415378859116682, 11.572368882692071], [14.468192172918974, 11.90475169519341], [14.57717776862253, 12.085360826053501], [14.181336297266792, 12.483656927943112], [14.213530714584634, 12.802035427293344], [14.495787387762842, 12.859396267137326], [14.893385857816522, 12.219047756392582], [14.960151808337598, 11.555574042197222], [14.923564894274955, 10.891325181517471], [15.467872755605269, 9.982336737503429], [14.909353875394713, 9.99212942142273], [14.627200555081057, 9.920919297724536], [14.171466098699025, 10.021378282099928], [13.954218377344002, 9.549494940626685], [14.544466586981766, 8.965861314322266], [14.979995558337688, 8.796104234243471], [15.120865512765331, 8.382150173369423], [15.436091749745765, 7.692812404811971], [15.279460483469107, 7.421924546737968], [14.776545444404572, 6.408498033062044], [14.536560092841111, 6.22695872642069], [14.459407179429345, 5.451760565610299], [14.558935988023501, 5.03059764243153], [14.478372430080466, 4.732605495620446], [14.950953403389658, 4.21038930909492], [15.036219516671249, 3.851367295747123], [15.405395948964379, 3.335300604664339], [15.862732374747479, 3.013537298998982], [15.907380812247649, 2.557389431158612], [16.01285241055535, 2.267639675298084], [15.940918816805061, 1.727672634280295], [15.14634199388524, 1.964014797367184], [14.337812534246577, 2.22787466064949], [13.07582238124675, 2.267097072759014]]] } }, { "type": "Feature", "properties": { "admin": "Democratic Republic of the Congo", "name": "Dem. Rep. Congo", "continent": "Africa" }, "geometry": { "type": "Polygon", "coordinates": [[[30.833859897593801, 3.50916596111034], [30.773346795380036, 2.339883327642127], [31.174149204235807, 2.204465236821263], [30.852670118948048, 1.849396470543809], [30.468507521290292, 1.58380544677972], [30.086153598762703, 1.062312730306288], [29.875778842902488, 0.597379868976304], [29.819503208136634, -0.205310153813372], [29.587837762172164, -0.58740569417948], [29.579466180140876, -1.341313164885626], [29.29188683443661, -1.620055840667987], [29.254834832483336, -2.215109958508911], [29.117478875451546, -2.292211195488384], [29.02492638521678, -2.839257907730157], [29.276383904749046, -3.293907159034063], [29.339997592900342, -4.499983412294092], [29.519986606572925, -5.419978936386313], [29.41999271008816, -5.939998874539432], [29.620032179490003, -6.520015150583424], [30.199996779101692, -7.079980970898161], [30.740015496551781, -8.340007419470913], [30.34608605319081, -8.238256524288216], [29.002912225060467, -8.40703175215347], [28.734866570762495, -8.526559340044576], [28.449871046672818, -9.164918308146083], [28.673681674928922, -9.605924981324931], [28.496069777141763, -10.789883721564044], [28.372253045370421, -11.793646742401389], [28.642417433392346, -11.971568698782312], [29.341547885869087, -12.36074391037241], [29.616001417771223, -12.178894545137307], [29.699613885219485, -13.257226657771827], [28.934285922976834, -13.248958428605132], [28.52356163912102, -12.698604424696679], [28.15510867687998, -12.272480564017894], [27.38879886242378, -12.132747491100663], [27.164419793412456, -11.608748467661071], [26.55308759939961, -11.924439792532125], [25.752309604604726, -11.784965101776356], [25.418118116973197, -11.330935967659958], [24.783169793402948, -11.238693536018962], [24.314516228947948, -11.262826429899269], [24.257155389103982, -10.951992689663655], [23.912215203555714, -10.926826267137512], [23.456790805767433, -10.867863457892481], [22.837345411884733, -11.017621758674329], [22.402798292742371, -10.99307545333569], [22.155268182064304, -11.084801120653768], [22.208753289486388, -9.894796237836507], [21.87518191904234, -9.523707777548564], [21.801801385187897, -8.908706556842978], [21.949130893652036, -8.305900974158275], [21.746455926203303, -7.920084730667147], [21.728110792739695, -7.2908724910813], [20.514748162526498, -7.299605808138629], [20.601822950938292, -6.93931772219968], [20.091621534920645, -6.943090101756993], [20.037723016040214, -7.116361179231644], [19.417502475673157, -7.155428562044297], [19.166613396896107, -7.738183688999753], [19.016751743249664, -7.988245944860132], [18.464175652752683, -7.847014255406442], [18.134221632569048, -7.98767750410492], [17.472970004962232, -8.068551120641699], [17.089995965247166, -7.545688978712525], [16.860190870845198, -7.222297865429984], [16.573179965896141, -6.622644545115087], [16.326528354567042, -5.877470391466267], [13.375597364971892, -5.864241224799548], [13.02486941900696, -5.984388929878157], [12.735171339578695, -5.965682061388497], [12.322431674863507, -6.100092461779658], [12.182336866920249, -5.789930515163837], [12.436688266660866, -5.684303887559245], [12.468004184629734, -5.248361504745003], [12.631611769265788, -4.991271254092935], [12.995517205465173, -4.781103203961883], [13.258240187237044, -4.882957452009165], [13.600234816144676, -4.500138441590969], [14.144956088933295, -4.510008640158715], [14.209034864975219, -4.793092136253597], [14.582603794013179, -4.970238946150139], [15.170991652088441, -4.3435071753143], [15.753540073314749, -3.855164890156096], [16.006289503654298, -3.535132744972528], [15.972803175529149, -2.712392266453612], [16.407091912510051, -1.740927015798682], [16.86530683764212, -1.225816338713287], [17.523716261472853, -0.743830254726987], [17.638644646889983, -0.424831638189246], [17.663552687254676, -0.058083998213817], [17.826540154703245, 0.288923244626105], [17.774191928791563, 0.855658677571085], [17.89883548347958, 1.741831976728278], [18.09427575040743, 2.365721543788055], [18.39379235197114, 2.90044342692822], [18.453065219809925, 3.504385891123348], [18.542982211997778, 4.201785183118317], [18.932312452884755, 4.709506130385973], [19.467783644293146, 5.031527818212779], [20.290679152108932, 4.691677761245287], [20.927591180106273, 4.322785549329736], [21.659122755630019, 4.224341945813719], [22.405123732195531, 4.02916006104732], [22.704123569436284, 4.633050848810156], [22.841479526468103, 4.710126247573483], [23.297213982850135, 4.609693101414221], [24.41053104014625, 5.108784084489129], [24.805028924262409, 4.897246608902349], [25.128833449003274, 4.927244777847789], [25.278798455514302, 5.170408229997191], [25.650455356557465, 5.256087754737123], [26.402760857862535, 5.150874538590869], [27.044065382604703, 5.127852688004835], [27.374226108517483, 5.233944403500059], [27.979977247842807, 4.408413397637373], [28.428993768026906, 4.287154649264493], [28.696677687298795, 4.455077215996936], [29.159078403446497, 4.38926727947323], [29.715995314256013, 4.600804755060024], [29.953500197069467, 4.173699042167683], [30.833859897593801, 3.50916596111034]]] } }, { "type": "Feature", "properties": { "admin": "Republic of Congo", "name": "Congo", "continent": "Africa" }, "geometry": { "type": "Polygon", "coordinates": [[[12.995517205465173, -4.781103203961883], [12.620759718484491, -4.438023369976135], [12.318607618873923, -4.606230157086187], [11.914963006242086, -5.037986748884789], [11.093772820691923, -3.978826592630546], [11.855121697648114, -3.42687061932105], [11.478038771214299, -2.765618991714241], [11.820963575903189, -2.514161472181982], [12.495702752338159, -2.391688327650242], [12.575284458067639, -1.948511244315134], [13.109618767965626, -2.428740329603513], [13.992407260807706, -2.470804945489099], [14.299210239324564, -1.998275648612213], [14.425455763413593, -1.333406670744971], [14.316418491277741, -0.552627455247048], [13.843320753645653, 0.038757635901149], [14.276265903386953, 1.196929836426619], [14.026668735417214, 1.395677395021153], [13.282631463278816, 1.31418366129688], [13.003113641012074, 1.830896307783319], [13.07582238124675, 2.267097072759014], [14.337812534246577, 2.22787466064949], [15.14634199388524, 1.964014797367184], [15.940918816805061, 1.727672634280295], [16.01285241055535, 2.267639675298084], [16.537058139724135, 3.198254706226278], [17.133042433346297, 3.728196519379451], [17.809900343505259, 3.560196437998569], [18.453065219809925, 3.504385891123348], [18.39379235197114, 2.90044342692822], [18.09427575040743, 2.365721543788055], [17.89883548347958, 1.741831976728278], [17.774191928791563, 0.855658677571085], [17.826540154703245, 0.288923244626105], [17.663552687254676, -0.058083998213817], [17.638644646889983, -0.424831638189246], [17.523716261472853, -0.743830254726987], [16.86530683764212, -1.225816338713287], [16.407091912510051, -1.740927015798682], [15.972803175529149, -2.712392266453612], [16.006289503654298, -3.535132744972528], [15.753540073314749, -3.855164890156096], [15.170991652088441, -4.3435071753143], [14.582603794013179, -4.970238946150139], [14.209034864975219, -4.793092136253597], [14.144956088933295, -4.510008640158715], [13.600234816144676, -4.500138441590969], [13.258240187237044, -4.882957452009165], [12.995517205465173, -4.781103203961883]]] } }, @@ -934,7 +983,7 @@ module MenuComponent { - + module NavigationDrawerComponent { $(function () { @@ -946,15 +995,15 @@ module NavigationDrawerComponent { enableListView: true, listViewSettings: { width: 300, - selectedItemIndex: 0, - mouseUp: "headChange" + selectedItemIndex: 0 }, position: "normal" + }); + $("#navpane_listview").click(function(e: any) { + var text=e.target["text"]||$(e.target).closest("li.e-list").text(); + $("#butdrawer").parent().children("h2").text(text); }); }); - function headChange(e:any) { - $("#butdrawer").parent().children("h2").text(e.text); - } } @@ -962,7 +1011,7 @@ module NavigationDrawerComponent { module PDFViewerComponent { $(function () { var pdfviewerControl = new ej.PdfViewer($("#pdfviewer"), { - serviceUrl: (window).baseurl + "api/PdfViewer", + serviceUrl:(window).baseurl+ "api/PdfViewer", isResponsive: true }); }); @@ -970,9 +1019,348 @@ module PDFViewerComponent { +module PivotChartOlap { + $(function () { + var sample = new ej.PivotChart($("#PivotChart"),{ + dataSource: { + data: "http://bi.syncfusion.com/olap/msmdpump.dll", + catalog: "Adventure Works DW 2008 SE", + cube: "Adventure Works", + rows: [ + { + fieldName: "[Date].[Fiscal]" + } + ], + columns: [ + { + fieldName: "[Customer].[Customer Geography]" + } + ], + values: [ + { + measures: [ + { + fieldName: "[Measures].[Internet Sales Amount]" + } + ], + axis: "columns" + } + ], + filters:[] + }, + isResponsive: true,zooming:{enableScrollbar: true}, + commonSeriesOptions: { + type: "column" + }, + size: { height: "460px", width: "100%" }, + primaryXAxis: { title: { text: "Date - Fiscal" }, labelRotation: 0 }, + primaryYAxis: { title: { text: "Internet Sales Amount" } }, + legend: { visible: true, rowCount: 2 } + }); + }); +} +var pivot_dataset = [ + { Amount: 100, Country: "Canada", Date: "FY 2005", Product: "Bike", Quantity: 2, State: "Alberta" }, + { Amount: 200, Country: "Canada", Date: "FY 2006", Product: "Van", Quantity: 3, State: "British Columbia" }, + { Amount: 300, Country: "Canada", Date: "FY 2007", Product: "Car", Quantity: 4, State: "Brunswick" }, + { Amount: 150, Country: "Canada", Date: "FY 2008", Product: "Bike", Quantity: 3, State: "Manitoba" }, + { Amount: 200, Country: "Canada", Date: "FY 2006", Product: "Car", Quantity: 4, State: "Ontario" }, + { Amount: 100, Country: "Canada", Date: "FY 2007", Product: "Van", Quantity: 1, State: "Quebec" }, + { Amount: 200, Country: "France", Date: "FY 2005", Product: "Bike", Quantity: 2, State: "Charente-Maritime" }, + { Amount: 250, Country: "France", Date: "FY 2006", Product: "Van", Quantity: 4, State: "Essonne" }, + { Amount: 300, Country: "France", Date: "FY 2007", Product: "Car", Quantity: 3, State: "Garonne (Haute)" }, + { Amount: 150, Country: "France", Date: "FY 2008", Product: "Van", Quantity: 2, State: "Gers" }, + { Amount: 200, Country: "Germany", Date: "FY 2006", Product: "Van", Quantity: 3, State: "Bayern" }, + { Amount: 250, Country: "Germany", Date: "FY 2007", Product: "Car", Quantity: 3, State: "Brandenburg" }, + { Amount: 150, Country: "Germany", Date: "FY 2008", Product: "Car", Quantity: 4, State: "Hamburg" }, + { Amount: 200, Country: "Germany", Date: "FY 2008", Product: "Bike", Quantity: 4, State: "Hessen" }, + { Amount: 150, Country: "Germany", Date: "FY 2007", Product: "Van", Quantity: 3, State: "Nordrhein-Westfalen" }, + { Amount: 100, Country: "Germany", Date: "FY 2005", Product: "Bike", Quantity: 2, State: "Saarland" }, + { Amount: 150, Country: "United Kingdom", Date: "FY 2008", Product: "Bike", Quantity: 5, State: "England" }, + { Amount: 250, Country: "United States", Date: "FY 2007", Product: "Car", Quantity: 4, State: "Alabama" }, + { Amount: 200, Country: "United States", Date: "FY 2005", Product: "Van", Quantity: 4, State: "California" }, + { Amount: 100, Country: "United States", Date: "FY 2006", Product: "Bike", Quantity: 2, State: "Colorado" }, + { Amount: 150, Country: "United States", Date: "FY 2008", Product: "Car", Quantity: 3, State: "New Mexico" }, + { Amount: 200, Country: "United States", Date: "FY 2005", Product: "Bike", Quantity: 4, State: "New York" }, + { Amount: 250, Country: "United States", Date: "FY 2008", Product: "Car", Quantity: 3, State: "North Carolina" }, + { Amount: 300, Country: "United States", Date: "FY 2007", Product: "Van", Quantity: 4, State: "South Carolina" } +] + +module PivotChartRelational { + + $(function () { + var sample = new ej.PivotChart($("#PivotChart"),{ + dataSource: { + data: pivot_dataset, + rows: [ + { + fieldName: "Country", + fieldCaption: "Country" + }, + { + fieldName: "State", + fieldCaption: "State" + }, + { + fieldName: "Date", + fieldCaption: "Date" + } + ], + columns: [ + { + fieldName: "Product", + fieldCaption: "Product" + } + ], + values: [ + { + fieldName: "Amount", + fieldCaption: "Amount" + } + ], + filters:[] + }, + isResponsive: true,zooming:{enableScrollbar: true}, + commonSeriesOptions: { + type: "column" + }, + size: { height: "460px", width: "100%" }, + primaryYAxis: { title: { text: "Amount" } }, + legend: { visible: true } + }); + }); +} + + + +module PivotGaugeOlap { + + $(function () { + var sample = new ej.PivotGauge($("#PivotGauge"),{ + dataSource: { + data: "http://bi.syncfusion.com/olap/msmdpump.dll", + catalog: "Adventure Works DW 2008 SE", + cube: "Adventure Works", + rows: [ + { + fieldName: "[Date].[Fiscal]", + filterItems: { filterType: "include", values: ["[Date].[Fiscal].[Fiscal Year].&[2004]"] } + }, + ], + columns: [ + { + fieldName: "[Customer].[Customer Geography]" + } + ], + values: [ + { + measures: [ + { + fieldName: "[Measures].[Internet Sales Amount]" + }, + { + fieldName: "[Measures].[Internet Revenue Status]" + }, + { + fieldName: "[Measures].[Internet Revenue Trend]" + }, + { + fieldName: "[Measures].[Internet Revenue Goal]" + }, + ], + axis: "columns" + } + ], + filters:[] + }, + enableTooltip: true, isResponsive: true, + labelFormatSettings: { decimalPlaces: 2 }, + scales: [{ + showRanges: true, + radius: 150, showScaleBar: true, size: 1, + border: { + width: 0.5 + }, + showIndicators: true, showLabels: true, + pointers: [{ + showBackNeedle: true, + backNeedleLength: 20, + length: 120, + width: 7 + }, + { + type: "marker", + markerType: "diamond", + distanceFromScale: 5, + placement: "center", + backgroundColor: "#29A4D9", + length: 25, + width: 15 + }], + ticks: [{ + type: "major", + distanceFromScale: 2, + height: 16, + width: 1, color: "#8c8c8c" + }, + { + type: "minor", + height: 6, + width: 1, + distanceFromScale: 2, + color: "#8c8c8c" + }], + labels: [{ + color: "#8c8c8c" + }], + ranges: [{ + distanceFromScale: -5, + backgroundColor: "#fc0606", + border: { color: "#fc0606" } + }, + { + distanceFromScale: -5 + }], + customLabels: [{ + position: { x: 180, y: 290 }, + font: { size: "10px", fontFamily: "Segoe UI", fontStyle: "Normal" }, color: "#666666" + }, + { + position: { x: 180, y: 320 }, + font: { size: "10px", fontFamily: "Segoe UI", fontStyle: "Normal" }, color: "#666666" + }, + { + position: { x: 180, y: 150 }, + font: { size: "12px", fontFamily: "Segoe UI", fontStyle: "Normal" }, color: "#666666" + }] + }] + }); + }); +} + + + +var pivot_dataset = [ + { Amount: 100, Country: "Canada", Date: "FY 2005", Product: "Bike", Quantity: 2, State: "Alberta" }, + { Amount: 200, Country: "Canada", Date: "FY 2006", Product: "Van", Quantity: 3, State: "British Columbia" }, + { Amount: 300, Country: "Canada", Date: "FY 2007", Product: "Car", Quantity: 4, State: "Brunswick" }, + { Amount: 150, Country: "Canada", Date: "FY 2008", Product: "Bike", Quantity: 3, State: "Manitoba" }, + { Amount: 200, Country: "Canada", Date: "FY 2006", Product: "Car", Quantity: 4, State: "Ontario" }, + { Amount: 100, Country: "Canada", Date: "FY 2007", Product: "Van", Quantity: 1, State: "Quebec" }, + { Amount: 200, Country: "France", Date: "FY 2005", Product: "Bike", Quantity: 2, State: "Charente-Maritime" }, + { Amount: 250, Country: "France", Date: "FY 2006", Product: "Van", Quantity: 4, State: "Essonne" }, + { Amount: 300, Country: "France", Date: "FY 2007", Product: "Car", Quantity: 3, State: "Garonne (Haute)" }, + { Amount: 150, Country: "France", Date: "FY 2008", Product: "Van", Quantity: 2, State: "Gers" }, + { Amount: 200, Country: "Germany", Date: "FY 2006", Product: "Van", Quantity: 3, State: "Bayern" }, + { Amount: 250, Country: "Germany", Date: "FY 2007", Product: "Car", Quantity: 3, State: "Brandenburg" }, + { Amount: 150, Country: "Germany", Date: "FY 2008", Product: "Car", Quantity: 4, State: "Hamburg" }, + { Amount: 200, Country: "Germany", Date: "FY 2008", Product: "Bike", Quantity: 4, State: "Hessen" }, + { Amount: 150, Country: "Germany", Date: "FY 2007", Product: "Van", Quantity: 3, State: "Nordrhein-Westfalen" }, + { Amount: 100, Country: "Germany", Date: "FY 2005", Product: "Bike", Quantity: 2, State: "Saarland" }, + { Amount: 150, Country: "United Kingdom", Date: "FY 2008", Product: "Bike", Quantity: 5, State: "England" }, + { Amount: 250, Country: "United States", Date: "FY 2007", Product: "Car", Quantity: 4, State: "Alabama" }, + { Amount: 200, Country: "United States", Date: "FY 2005", Product: "Van", Quantity: 4, State: "California" }, + { Amount: 100, Country: "United States", Date: "FY 2006", Product: "Bike", Quantity: 2, State: "Colorado" }, + { Amount: 150, Country: "United States", Date: "FY 2008", Product: "Car", Quantity: 3, State: "New Mexico" }, + { Amount: 200, Country: "United States", Date: "FY 2005", Product: "Bike", Quantity: 4, State: "New York" }, + { Amount: 250, Country: "United States", Date: "FY 2008", Product: "Car", Quantity: 3, State: "North Carolina" }, + { Amount: 300, Country: "United States", Date: "FY 2007", Product: "Van", Quantity: 4, State: "South Carolina" } +] + +module PivotGaugeRelational { + $(function () { + var sample = new ej.PivotGauge($("#PivotGauge"),{ + dataSource: { + data: pivot_dataset, + rows: [ + { + fieldName: "Country", + }, + { + fieldName: "State", + } + ], + columns: [ + { + fieldName: "Product", + } + ], + values: [ + { + fieldName: "Amount", + }, + { + fieldName: "Quantity", + } + ] + }, + enableTooltip: true, isResponsive: true, + labelFormatSettings: { decimalPlaces: 2 }, + scales: [{ + showRanges: true, + radius: 150, showScaleBar: true, size: 1, + border: { + width: 0.5 + }, + showIndicators: true, showLabels: true, + pointers: [{ + showBackNeedle: true, + backNeedleLength: 20, + length: 120, + width: 7 + }, + { + type: "marker", + markerType: "diamond", + distanceFromScale: 5, + placement: "center", + backgroundColor: "#29A4D9", + length: 25, + width: 15 + }], + ticks: [{ + type: "major", + distanceFromScale: 2, + height: 16, + width: 1, color: "#8c8c8c" + }, + { + type: "minor", + height: 6, + width: 1, + distanceFromScale: 2, + color: "#8c8c8c" + }], + labels: [{ + color: "#8c8c8c" + }], + ranges: [{ + distanceFromScale: -5, + backgroundColor: "#fc0606", + border: { color: "#fc0606" } + }, + { + distanceFromScale: -5 + }], + customLabels: [{ + position: { x: 180, y: 290 }, + font: { size: "10px", fontFamily: "Segoe UI", fontStyle: "Normal" }, color: "#666666" + }, + { + position: { x: 180, y: 320 }, + font: { size: "10px", fontFamily: "Segoe UI", fontStyle: "Normal" }, color: "#666666" + }, + { + position: { x: 180, y: 150 }, + font: { size: "12px", fontFamily: "Segoe UI", fontStyle: "Normal" }, color: "#666666" + }] + }] + }); + }); +} @@ -1006,17 +1394,10 @@ module PivotGridOlap { ], filters:[] }, - hyperlinkSettings: { - enableValueCellHyperlink: true, - enableRowHeaderHyperlink: true, - enableColumnHeaderHyperlink: true, - enableSummaryCellHyperlink: true - }, - enableGroupingBar: true, - enableCellEditing: true, - enableCellSelection: true, - renderSuccess: function (args) {$("#PivotSchemaDesigner").ejPivotSchemaDesigner({ pivotControl: args, layout: "excel" });} + enableGroupingBar: true, + pivotTableFieldListID:"PivotSchemaDesigner" }); + $("#PivotSchemaDesigner").ejPivotSchemaDesigner(); }); } @@ -1064,7 +1445,7 @@ module PivotGridRelational { fieldCaption: "State" } ], - columns: + columns: [{ fieldName: "Product", fieldCaption: "Product" @@ -1082,17 +1463,11 @@ module PivotGridRelational { ], filters:[] }, - hyperlinkSettings: { - enableValueCellHyperlink: true, - enableRowHeaderHyperlink: true, - enableColumnHeaderHyperlink: true, - enableSummaryCellHyperlink: true - }, - enableGroupingBar: true, - enableCellEditing: true, - enableCellSelection: true, - renderSuccess: function (args) {$("#PivotSchemaDesigner").ejPivotSchemaDesigner({ pivotControl: args, layout: "excel" });} + enableGroupingBar: true, + pivotTableFieldListID:"PivotSchemaDesigner" }); + $("#PivotSchemaDesigner").ejPivotSchemaDesigner(); + }); } @@ -1156,7 +1531,7 @@ declare var rteObj: any; declare var data: any; var radialEle = $('#defaultradialmenu'), action = 0, forRedo = 0; var rteEle = $("#rteSample1"); -module AccordionComponent { +module RadialMenuComponent { $(function () { if (!(ej.browserInfo().name == "msie" && parseInt(ej.browserInfo().version) < 9)) { @@ -1165,6 +1540,7 @@ module AccordionComponent { backImageClass: "backimageclass", targetElementId: "radialtarget1" }); + $("#radialtarget1").parent().css("position", "relative"); } else { $("#contentDiv").html("Radial Menu is only supported from Internet Explorer Versioned 9 and above.").css({ "font-size": "20px", "color": "red" }); @@ -1176,7 +1552,7 @@ module AccordionComponent { select: (e) => { var target = $("#radialtarget1"), radialRadius = 150, radialDiameter = 2 * radialRadius, // To get Iframe positions - iframeY = target.offset().top + e.event.clientY, iframeX = target.offset().left + e.event.clientX, + iframeY = e.event.clientY, iframeX = e.event.clientX, // To set Radial Menu position within target x = iframeX > target.width() - radialRadius ? target.width() - radialDiameter : (iframeX > radialRadius ? iframeX - radialRadius : 0), y = iframeY > target.height() - radialRadius ? target.height() - radialDiameter : (iframeY > radialRadius ? iframeY - radialRadius : 0); @@ -1231,7 +1607,7 @@ function redo(e: any) { } - + module RadialSliderComponent { $(function () { @@ -1264,7 +1640,7 @@ module rangecomponent { fill: '#69D2E7' } ]; - } + } }); }); @@ -1316,7 +1692,7 @@ module RatingComponent { shapeWidth: 25, showTooltip: true }); - + var sample2 = new ej.Rating($("#halfRating"),{ precision: ej.Rating.Precision.Half, value: 3.5, @@ -1347,7 +1723,7 @@ module RatingComponent { shapeHeight: 25, shapeWidth: 25, showTooltip: true - }); + }); }); } @@ -1357,7 +1733,7 @@ module RatingComponent { module ReportViewerComponent { $(function () { var report = new ej.ReportViewer($("#territoryReportViewer"), { - reportServiceUrl: (window).baseurl + 'api/SSRSReport', + reportServiceUrl: (window).baseurl + 'api/ReportViewer', reportServerUrl: 'http://mvc.syncfusion.com/reportserver', processingMode: ej.ReportViewer.ProcessingMode.Remote, reportPath: "/SSRSSamples2/Territory Sales new", @@ -1380,7 +1756,7 @@ module RibbonComponent { toolTip: "Pin the Ribbon" }, applicationTab: { - type: ej.Ribbon.ApplicationTabType.Menu, menuItemID: "ribbonmenu", menuSettings: { openOnClick: false } + type: ej.Ribbon.ApplicationTabType.Menu, menuItemID: "ribbonmenu", menuSettings: { openOnClick: false } }, tabs: [{ id: "home", text: "HOME", groups: [{ @@ -1457,7 +1833,7 @@ module RibbonComponent { width: 60, isBig: false } - }] + }] }, { text: "Font", alignType: "rows", content: [{ @@ -1736,7 +2112,7 @@ module RibbonComponent { groups: [{ id: "zoomin", text: "Zoom In", - toolTip: "Zoom In", + toolTip: "Zoom In", buttonSettings: { width: 58, contentType: ej.ContentType.TextAndImage, @@ -1747,7 +2123,7 @@ module RibbonComponent { { id: "zoomout", text: "Zoom Out", - toolTip: "Zoom Out", + toolTip: "Zoom Out", buttonSettings: { width: 70, contentType: ej.ContentType.TextAndImage, @@ -1758,7 +2134,7 @@ module RibbonComponent { { id: "fullscreen", text: "Full Screen", - toolTip: "Full Screen", + toolTip: "Full Screen", buttonSettings: { width: 73, contentType: ej.ContentType.TextAndImage, @@ -1987,7 +2363,7 @@ module RibbonComponent { } ] } - ], + ], create: function createControl(args) { var ribbon = $("#defaultRibbon").data("ejRibbon"); $("#fontcolor").ejColorPicker({ value: "#FFFF00", modelType: "palette", cssClass: "e-ribbon", toolIcon: "e-fontcoloricon", select: colorHandler }); @@ -2003,7 +2379,7 @@ function colorHandler(args:any) { - + module RotatorComponent { $(function () { @@ -2045,14 +2421,14 @@ module RTEComponent { enableResize: true, enableTabKeyNavigation: true, fileBrowser: { - filePath: "../FileExplorerContent/", + filePath: (window).baseurl + "Content/FileBrowser/", extensionAllow: "*.png, *.doc, *.pdf, *.txt, *.docx", - ajaxAction: "http://mvc.syncfusion.com/OdataServices/api/fileoperation/", + ajaxAction: (window).baseurl + "api/FileExplorer/FileOperations" }, imageBrowser: { - filePath: "../FileExplorerContent/", + filePath: (window).baseurl + "Content/FileBrowser/", extensionAllow: "*.png, *.gif, *.jpg, *.jpeg, *.docx", - ajaxAction: "http://mvc.syncfusion.com/OdataServices/api/fileoperation/", + ajaxAction: (window).baseurl + "api/FileExplorer/FileOperations" }, isResponsive: true, showClearAll: true, @@ -2100,10 +2476,6 @@ module RTEComponent { -declare var window :myWindow; -export interface myWindow extends Window{ -Default:any; -} module ScheduleComponent { $(function () { var sample = new ej.Schedule($("#Schedule1"), { @@ -2157,7 +2529,7 @@ module ScheduleComponent { } }], appointmentSettings: { - dataSource: new ej.DataManager(window.Default).executeLocal(new ej.Query().take(10)), + dataSource: new ej.DataManager((window).Default).executeLocal(new ej.Query().take(10)), id: "Id", subject: "Subject", startTime: "StartTime", @@ -2170,7 +2542,7 @@ module ScheduleComponent { } }); }); -} +} @@ -2182,13 +2554,22 @@ module ScrollerComponent { }); $(window).bind('resize', function () { scrollerSample.refresh(); - }); - - }); + }); }); } +module SignatureComponent { + $(function () { + var basicSignature = new ej.Signature($("#signature"), { + height: "400px", + isResponsive: true, + strokeWidth: 3 + }); + }); +} + + module SliderComponent { @@ -2344,9 +2725,9 @@ module piesparkline4 { }); } - - + + module SplitterComponent { @@ -2373,15 +2754,15 @@ $(function () { height: 550, }, importSettings: { - importMapper: (window).baseurl + "api/JSXLExport/Import" + importMapper: (window).baseurl + "api/Spreadsheet/Import" }, exportSettings: { - excelUrl: (window).baseurl + "api/JSXLExport/ExportToExcel", - csvUrl: (window).baseurl + "api/JSXLExport/ExportToCsv", - pdfUrl: (window).baseurl + "api/JSXLExport/ExportToPdf" + excelUrl: (window).baseurl + "api/Spreadsheet/ExcelExport", + csvUrl: (window).baseurl + "api/Spreadsheet/CsvExport", + pdfUrl: (window).baseurl + "api/Spreadsheet/PdfExport" }, sheets: [{ rangeSettings: [{ dataSource: (window).defaultData, startCell: "A1" }] }], - loadComplete: () => { + loadComplete: () => { var spreadsheet = $("#basicSpreadsheet").data("ejSpreadsheet"), xlFormat = spreadsheet.XLFormat; if (!(spreadsheet).isImport) { spreadsheet.setWidthToColumns([140, 128, 105, 100, 100, 110, 120, 120, 100]); @@ -2396,6 +2777,69 @@ $(function () { +var default_data: Array = [ + { Category : "Employees", Country : "USA", JobDescription : "Sales", JobGroup:"Executive", EmployeesCount : 50 }, + { Category : "Employees", Country : "USA", JobDescription : "Sales", JobGroup : "Analyst", EmployeesCount : 40 }, + { Category : "Employees", Country : "USA", JobDescription : "Marketing", EmployeesCount : 40 }, + { Category : "Employees", Country : "USA", JobDescription : "Technical", JobGroup : "Testers", EmployeesCount : 55 }, + { Category : "Employees", Country : "USA", JobDescription : "Technical", JobGroup : "Developers", JobRole : "Windows", EmployeesCount : 175}, + { Category : "Employees", Country : "USA", JobDescription : "Technical", JobGroup : "Developers", JobRole : "Web", EmployeesCount : 70 }, + { Category : "Employees", Country : "USA", JobDescription : "Management", EmployeesCount : 40 }, + { Category : "Employees", Country : "USA", JobDescription : "Accounts", EmployeesCount : 60 }, + + { Category : "Employees", Country : "India", JobDescription : "Technical", JobGroup : "Testers", EmployeesCount : 43 }, + { Category : "Employees", Country : "India", JobDescription : "Technical", JobGroup : "Developers", JobRole : "Windows", EmployeesCount : 125}, + { Category : "Employees", Country : "India", JobDescription : "Technical", JobGroup : "Developers", JobRole : "Web", EmployeesCount : 60 }, + { Category : "Employees", Country : "India", JobDescription : "HR Executives", EmployeesCount : 70 }, + { Category : "Employees", Country : "India", JobDescription : "Accounts", EmployeesCount : 45 }, + + { Category : "Employees", Country : "Germany", JobDescription : "Sales", JobGroup : "Executive", EmployeesCount : 30 }, + { Category : "Employees", Country : "Germany", JobDescription : "Sales", JobGroup : "Analyst", EmployeesCount : 40 }, + { Category : "Employees", Country : "Germany", JobDescription : "Marketing", EmployeesCount : 50 }, + { Category : "Employees", Country : "Germany", JobDescription : "Technical", JobGroup : "Testers", EmployeesCount : 40 }, + { Category : "Employees", Country : "Germany", JobDescription : "Technical", JobGroup : "Developers", JobRole : "Windows", EmployeesCount : 65 }, + { Category : "Employees", Country : "Germany", JobDescription : "Technical", JobGroup : "Developers", JobRole : "Web", EmployeesCount : 27 }, + { Category : "Employees", Country : "Germany", JobDescription : "Management", EmployeesCount : 33 }, + { Category : "Employees", Country : "Germany", JobDescription : "Accounts", EmployeesCount : 55 }, + + { Category : "Employees", Country : "UK", JobDescription : "Technical", JobGroup : "Testers", EmployeesCount : 45 }, + { Category : "Employees", Country : "UK", JobDescription : "Technical", JobGroup : "Developers", JobRole : "Windows", EmployeesCount : 96 }, + { Category : "Employees", Country : "UK", JobDescription : "Technical", JobGroup : "Developers", JobRole : "Web", EmployeesCount : 55 }, + { Category : "Employees", Country : "UK", JobDescription : "HR Executives", EmployeesCount : 60 }, + { Category : "Employees", Country : "UK", JobDescription: "Accounts", EmployeesCount: 30 }, + + { Category : "Employees", Country : "France", JobDescription : "Technical", JobGroup : "Testers", EmployeesCount : 40 }, + { Category : "Employees", Country : "France", JobDescription : "Technical", JobGroup : "Developers", JobRole : "Windows", EmployeesCount : 65 }, + { Category : "Employees", Country : "France", JobDescription : "Technical", JobGroup : "Developers", JobRole : "Web", EmployeesCount : 27 }, + { Category : "Employees", Country : "France", JobDescription: "Marketing", EmployeesCount: 50 } +]; + +module sunburstcomponent { + $(function () { + var sunburstsample = new ej.SunburstChart($("#Sunburst"), { + valueMemberPath: "EmployeesCount", + levels: [ + {groupMemberPath: "Country"}, + {groupMemberPath: "JobDescription"}, + {groupMemberPath: "JobGroup"}, + {groupMemberPath: "JobRole"} + ], + dataSource: default_data, + dataLabelSettings:{visible:true}, + tooltip:{visible:false}, + enableAnimation:false, + size:{height:"600"}, + innerRadius:0.2, + title:{text:"Employees Count"}, + zoomSettings:{enable:false}, + legend:{visible:true,position:'top'} + }); + }); +} + + + + module TabComponent { $(function () { var sample = new ej.Tab($("#defaultTab"),{ @@ -2412,8 +2856,8 @@ module TabComponent { module TagCloudComponent { - - + + var websiteCollection = [ { text: "Google", url: "http://www.google.com", frequency: 12 }, { text: "All Things Digital", url: "http://allthingsd.com/", frequency: 3 }, @@ -2444,7 +2888,7 @@ module TagCloudComponent { text: "text", url: "url", frequency: "frequency" } }); - + }); } @@ -2484,9 +2928,9 @@ module EditorComponent { - -module AccordionComponent { + +module TileViewComponent { $(function () { var tile1 = new ej.Tile($("#tile1"), { imagePosition:"fill", @@ -2495,38 +2939,38 @@ module AccordionComponent { imageUrl:'content/images/tile/windows/people_1.png' }); var tile2 = new ej.Tile($("#tile2"), { - imagePosition:"center", + imagePosition:"center", tileSize:"small", - imageUrl:'content/images/tile/windows/alerts.png', - + imageUrl:'content/images/tile/windows/alerts.png', + }); var tile3 = new ej.Tile($("#tile3"), { - imagePosition:"center", + imagePosition:"center", tileSize:"small", - imageUrl:'content/images/tile/windows/bing.png', + imageUrl:'content/images/tile/windows/bing.png', }); var tile4 = new ej.Tile($("#tile4"), { tileSize:"small", - imageUrl:'content/images/tile/windows/camera.png', + imageUrl:'content/images/tile/windows/camera.png', }); var tile5 = new ej.Tile($("#tile5"), { - imagePosition:"center", + imagePosition:"center", tileSize:"small", - imageUrl:'content/images/tile/windows/messages.png', + imageUrl:'content/images/tile/windows/messages.png', }); var tile6 = new ej.Tile($("#tile6"), { - imagePosition:"center", + imagePosition:"center", tileSize:"medium", - imageUrl:'content/images/tile/windows/games.png', + imageUrl:'content/images/tile/windows/games.png', caption:{text:"Play"} }); - var tile7 = new ej.Tile($("#tile7"), { + var tile7 = new ej.Tile($("#tile7"), { tileSize:"medium", imageUrl:'content/images/tile/windows/map.png', caption:{text:"Maps"} }); var tile8 = new ej.Tile($("#tile8"), { - imagePosition:"fill", + imagePosition:"fill", tileSize:"wide", imageUrl:'content/images/tile/windows/sports.png', caption:{text:"Sports"} @@ -2578,7 +3022,7 @@ module TimePickerComponent { module ToolbarComponent { - + $(function () { var sample = new ej.Toolbar($("#editingToolbar"),{ width: "100%", @@ -2597,7 +3041,7 @@ module ToolbarComponent { module TooltipComponent { - + $(function () { var sample1 = new ej.Tooltip($("#link1"),{ @@ -2614,13 +3058,13 @@ module TooltipComponent { content: "The World Wide Web (WWW) is an information space where documents and other web resources are identified by URLs, interlinked by hypertext links, and can be accessed via the Internet.", position: { stem: { - horizontal: "left", + horizontal: "right", vertical: "center" }, target: { - horizontal: "right", - vertical: "center", - }, + horizontal: "left", + vertical: "center" + } }, autoCloseTimeout: 5000, collision: "fit", @@ -2685,14 +3129,14 @@ module TreeGridComponent { columns: [ { field: "taskID", headerText: "Task Id", allowFiltering: false, editType: "numericedit", filterEditType: "numericedit" }, { field: "taskName", headerText: "Task Name", editType: "stringedit", filterEditType: "stringedit" }, - { field: "startDate", headerText: "Start Date", editType: "datepicker", filterEditType: "datepicker" }, - { field: "endDate", headerText: "End Date", editType: "datepicker", filterEditType: "datepicker" }, + { field: "startDate", headerText: "Start Date", editType: "datepicker", filterEditType: "datepicker", format:"{0:MM/dd/yyyy}" }, + { field: "endDate", headerText: "End Date", editType: "datepicker", filterEditType: "datepicker", format:"{0:MM/dd/yyyy}" }, { field: "progress", headerText: "Progress", editType: "numericedit", filterEditType: "numericedit" } ], isResponsive: true, }); }); -} +} @@ -2737,7 +3181,7 @@ module treemapcomponent { - + module TreeViewComponent { $(function () { @@ -2754,13 +3198,13 @@ module TreeViewComponent { module UploadboxComponent { - + $(function () { var sample = new ej.Uploadbox($("#UploadDefault"),{ saveUrl: "uploadbox/saveFiles.ashx", removeUrl: "uploadbox/removeFiles.ashx", buttonText: { - browse: "Choose File", upload: "Upload the File", cancel: "Cancel the Upload" + browse: "Choose File", upload: "Upload", cancel: "Cancel" }, cssClass: "gradient- purple", dialogAction: { @@ -2782,8 +3226,10 @@ module WaitingPopupComponent { var sample = new ej.WaitingPopup($("#target"),{ showOnInit: true, showImage: true, - text: 'waiting…' + text: 'waiting…', + target: "#target", + appendTo: "#waiting" }); }); -} +} \ No newline at end of file diff --git a/ej.web.all/index.d.ts b/ej.web.all/index.d.ts index 41d0f2f54f..b1c4261705 100644 --- a/ej.web.all/index.d.ts +++ b/ej.web.all/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ej.web.all 14.4 +// Type definitions for ej.web.all 15.1 // Project: http://help.syncfusion.com/js/typescript // Definitions by: Syncfusion // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,16 +7,15 @@ /*! * filename: ej.web.all.d.ts -* version : 14.4.0.20 -* Copyright Syncfusion Inc. 2001 - 2016. All rights reserved. +* version : 15.1.0.37 +* Copyright Syncfusion Inc. 2001 - 2017. All rights reserved. * Use of this code is subject to the terms of our license. * A copy of the current license can be obtained at any time by e-mailing * licensing@syncfusion.com. Any infringement will be prosecuted under * applicable laws. */ -declare module ej { - - var dataUtil: dataUtil; +declare namespace ej { + const dataUtil: dataUtil; function isMobile(): boolean; function isIOS(): boolean; function isAndroid(): boolean; @@ -29,33 +28,33 @@ declare module ej { function isTouchDevice(): boolean; function addPrefix(style: string): string; function animationEndEvent(): string; - function blockDefaultActions(e: Object): void; - function buildTag(tag: string, innerHtml?: string, styles?: Object, attrs?: Object): JQuery; + function blockDefaultActions(e: any): void; + function buildTag(tag: string, innerHtml?: string, styles?: any, attrs?: any): JQuery; function cancelEvent(): string; function copyObject(): string; - function createObject(nameSpace: string, value: Object, initIn: any): JQuery; + function createObject(nameSpace: string, value: any, initIn: any): JQuery; function createObject(element: any, eventEmitter: any, model: any): any; function setCulture(culture: string): void; - function getObject(element :string, model :any ): T; - function defineClass(className: string, constructor:any, proto: Object, replace: boolean): Object; - function destroyWidgets(element: Object): void; + function getObject(element: string, model: any ): T; + function getObject(nameSpace: string, fromdata?: any): any; + function defineClass(className: string, constructor: any, proto: any, replace: boolean): any; + function destroyWidgets(element: any): void; function endEvent(): string; - function event(type: string, data: any, eventProp: Object): Object; - function getAndroidVersion(): Object; - function getAttrVal(ele: Object, val: string, option: Object): Object; - function getBooleanVal(ele: Object, val: string, option: Object): Object; + function event(type: string, data: any, eventProp: any): any; + function getAndroidVersion(): any; + function getAttrVal(ele: any, val: string, option: any): any; + function getBooleanVal(ele: any, val: string, option: any): any; function getClearString(): string; - function getDimension(element: Object, method: string): Object; - function getFontString(fontObj: Object): string; + function getDimension(element: any, method: string): any; + function getFontString(fontObj: any): string; function getFontStyle(style: string): string; function getMaxZindex(): number; function getNameSpace(className: string): string; - function getObject(nameSpace: string, fromdata?: any): Object; - function getOffset(ele: string): Object; + function getOffset(ele: string): any; function getRenderMode(): string; - function getScrollableParents(element: Object): void; + function getScrollableParents(element: any): void; function getTheme(): string; - function getZindexPartial(element: Object, popupEle: string): number; + function getZindexPartial(element: any, popupEle: string): number; function hasRenderMode(element: string): void; function hasStyle(prop: string): boolean; function hasTheme(element: string): string; @@ -66,87 +65,86 @@ declare module ej { function isIOS7(): boolean; function isIOSWebView(): boolean; function isLowerAndroid(): boolean; - function isNullOrUndefined(value: Object): boolean; + function isNullOrUndefined(value: any): boolean; function isPlainObject(): JQuery; function isPortrait(): any; function isTablet(): boolean; function isWindowsWebView(): string; - function listenEvents(selectors:any, eventTypes: any, handlers: any, remove?: any, pluginObj?: any, disableMouse?: boolean): void; - function listenTouchEvent(selectors:any, eventTypes: any, handlers: any, remove?: any, pluginObj?: any, disableMouse?: boolean): void; + function listenEvents(selectors: any, eventTypes: any, handlers: any, remove?: any, pluginObj?: any, disableMouse?: boolean): void; + function listenTouchEvent(selectors: any, eventTypes: any, handlers: any, remove?: any, pluginObj?: any, disableMouse?: boolean): void; function logBase(val: string, base: string): number; function measureText(text: string, maxwidth: number, font: string): string; function moveEvent(): string; function print(element: string, printWindow: any): void; - function proxy(fn: Object, context?: string, arg?: string): any; + function proxy(fn: any, context?: string, arg?: string): any; function round(value: string, div: string, up: string): any; - function sendAjaxRequest(ajaxOptions: Object): void; + function sendAjaxRequest(ajaxOptions: any): void; function setCaretToPos(nput: string, pos1: string, pos2: string): void; function setRenderMode(element: string): void; - function setTheme(): Object; + function setTheme(): any; function startEvent(): string; function tapEvent(): string; function tapHoldEvent(): string; - function throwError(): Object; - function transitionEndEvent(): Object; + function throwError(): any; + function transitionEndEvent(): any; function userAgent(): boolean; - function widget(pluginName: string, className: string, proto: Object): Object; - function avg(json: Object, filedName: string): any; + function widget(pluginName: string, className: string, proto: any): any; + function avg(json: any, filedName: string): any; function getGuid(prefix: string): number; - function group(jsonArray: any, field: string, agg: string, level: number, groupDs: string): Object; + function group(jsonArray: any, field: string, agg: string, level: number, groupDs: string): any; function isJson(jsonData: string): string; function max(jsonArray: any, fieldName?: string, comparer?: string): any; function min(jsonArray: any, fieldName: string, comparer: string): any; function merge(first: string, second: string): any; function mergeshort(jsonArray: any, fieldName: string, comparer: string): any; function parseJson(jsonText: string): string; - function parseTable(table: number, headerOption: string, headerRowIndex: string): Object; + function parseTable(table: number, headerOption: string, headerRowIndex: string): any; function select(jsonArray: any, fields: string): any; function setTransition(): boolean; function sum(json: string, fieldName: string): string; function swap(array: any, x: string, y: string): any; - var cssUA: string; - var serverTimezoneOffset: number; - var transform: string; - var transformOrigin: string; - var transformStyle: string; - var transition: string; - var transitionDelay: string; - var transitionDuration: string; - var transitionProperty: string; - var transitionTimingFunction: string; - var template: any; - var util: { + const cssUA: string; + const serverTimezoneOffset: number; + const transform: string; + const transformOrigin: string; + const transformStyle: string; + const transition: string; + const transitionDelay: string; + const transitionDuration: string; + const transitionProperty: string; + const transitionTimingFunction: string; + const template: any; + const util: { valueFunction(val: string): any; - } - export module device { + }; + export namespace device { function isAndroid(): boolean; function isIOS(): boolean; function isFlat(): boolean; function isIOS7(): boolean; function isWindows(): boolean; } - export module widget { - var autoInit: boolean; - var registeredInstances: Array; - var registeredWidgets: Array; + export namespace widget { + const autoInit: boolean; + const registeredInstances: any[]; + const registeredWidgets: any[]; function register(pluginName: string, className: string, prototype: any): void; function destroyAll(elements: Element): void; function init(element: Element): void; - function registerInstance(element: Element, pluginName: string, className: string, prototype: any):void; + function registerInstance(element: Element, pluginName: string, className: string, prototype: any): void; } - interface browserInfoOptions { name: string; version: string; - culture: Object; + culture: any; isMSPointerEnabled: boolean; } class WidgetBase { destroy(): void; element: JQuery; - setModel(options: Object, forceSet?: boolean):any; - option(prop?: Object, value?: Object, forceSet?: boolean): any; - _trigger(eventName?: string, eventProp?: Object): any; + setModel(options: any, forceSet?: boolean): any; + option(prop?: any, value?: any, forceSet?: boolean): any; + _trigger(eventName?: string, eventProp?: any): any; _on(element: JQuery, eventType?: string, handler?: (eventObject: JQueryEventObject) => any): any; _on(element: JQuery, eventType ?: string, selector ?: string, handler ?: (eventObject: JQueryEventObject) => any): any; _off(element: JQuery, eventName: string, handler ?: (eventObject: JQueryEventObject) => any): any; @@ -175,15 +173,15 @@ declare module ej { executeQuery(query?: ej.Query, done?: any, fail?: any, always?: any): JQueryPromise; executeLocal(query?: ej.Query): ej.DataManager; saveChanges(changes?: Changes, key?: string, tableName?: string): JQueryDeferred; - insert(data: Object, tableName?: string): JQueryPromise; - remove(keyField: string, value: any, tableName?: string): Object; - update(keyField: string, value: any, tableName?: string): Object; + insert(data: any, tableName?: string): JQueryPromise; + remove(keyField: string, value: any, tableName?: string): any; + update(keyField: string, value: any, tableName?: string): any; } class Query { constructor(); static fn: Query; - static extend(prototype: Object): Query; + static extend(prototype: any): Query; key(field: string): ej.Query; using(dataManager: ej.DataManager): ej.Query; execute(dataManager: ej.DataManager, done: any, fail?: string, always?: string): any; @@ -193,8 +191,8 @@ declare module ej { addParams(key: string, value: string): ej.Query; expand(tables: any): ej.Query; where(fieldName: string, operator: ej.FilterOperators, value: any, ignoreCase?: boolean): ej.Query; - where(predicate:ej.Predicate):ej.Query; - search(searchKey: any, fieldNames?: any, operator?: string, ignoreCase?: boolean): ej.Query; + where(predicate: ej.Predicate): ej.Query; + search(searchKey: any, fieldNames?: any, operator?: string, ignoreCase?: boolean): ej.Query; sortBy(fieldName: string, comparer?: ej.SortOrder, isFromGroup?: boolean): ej.Query; sortByDesc(fieldName: string): ej.Query; group(fieldName: string): ej.Query; @@ -205,17 +203,17 @@ declare module ej { hierarchy(query: ej.Query, selectorFn: any): ej.Query; foreignKey(key: string): ej.Query; requiresCount(): ej.Query; - range(start:number, end:number): ej.Query; + range(start: number, end: number): ej.Query; } class Adaptor { constructor(ds: any); - pvt: Object; + pvt: any; type: ej.Adaptor; options: AdaptorOptions; extend(overrides: any): ej.Adaptor; - processQuery(dm: ej.DataManager, query: ej.Query):any; - processResponse(data: Object, ds: any, query: ej.Query, xhr: JQueryXHR, request?: Object, changes?: Changes): Object; + processQuery(dm: ej.DataManager, query: ej.Query): any; + processResponse(data: any, ds: any, query: ej.Query, xhr: JQueryXHR, request?: any, changes?: Changes): any; convertToQueryString(req: any, query: ej.Query, dm: ej.DataManager): JQueryParam; } @@ -235,18 +233,18 @@ declare module ej { class UrlAdaptor extends ej.Adaptor { constructor(); - processQuery(dm: ej.DataManager, query: ej.Query, hierarchyFilters?: Object): { - type: string; url: string; ejPvtData: Object; contentType?: string; data?: Object; + processQuery(dm: ej.DataManager, query: ej.Query, hierarchyFilters?: any): { + type: string; url: string; ejPvtData: any; contentType?: string; data?: any; } - convertToQueryString(req: Object, query: ej.Query, dm: ej.DataManager): JQueryParam; - processResponse(data: Object, ds: any, query: ej.Query, xhr: JQueryXHR, request?: Object, changes?: Changes): Object; + convertToQueryString(req: any, query: ej.Query, dm: ej.DataManager): JQueryParam; + processResponse(data: any, ds: any, query: ej.Query, xhr: JQueryXHR, request?: any, changes?: Changes): any; onGroup(e: any): void; batchRequest(dm: ej.DataManager, changes: Changes, e: any): void; - beforeSend(dm: ej.DataManager, request: any, settings?:any): void; - insert(dm: ej.DataManager, data: Object, tableName: string): { url: string; data: any }; + beforeSend(dm: ej.DataManager, request: any, settings?: any): void; + insert(dm: ej.DataManager, data: any, tableName: string): { url: string; data: any }; remove(dm: ej.DataManager, keyField: string, value: any, tableName: string): { type: string; url: string; data?: any }; update(dm: ej.DataManager, keyField: string, value: any, tableName: string): { type: string; url: string; data: any }; - getFiltersFrom(data: Object, query: ej.Query): ej.Predicate; + getFiltersFrom(data: any, query: ej.Query): ej.Predicate; } class ODataAdaptor extends ej.UrlAdaptor { @@ -255,26 +253,26 @@ declare module ej { onEachWhere(filter: any, requiresCast: boolean): any; onPredicate(pred: ej.Predicate, query: ej.Query, requiresCast: boolean): string; onComplexPredicate(pred: ej.Predicate, requiresCast: boolean): string; - onWhere(filters: Array): string; - onEachSearch(e: Object): void; - onSearch(e: Object): string; - onEachSort(e: Object): string; - onSortBy(e: Object): string; - onGroup(e: Object): string; - onSelect(e: Object): string; - onCount(e: Object): string; + onWhere(filters: string[]): string; + onEachSearch(e: any): void; + onSearch(e: any): string; + onEachSort(e: any): string; + onSortBy(e: any): string; + onGroup(e: any): string; + onSelect(e: any): string; + onCount(e: any): string; beforeSend(dm: ej.DataManager, request: any, settings?: any): void; - processResponse(data: Object, ds: Object, query: ej.Query, xhr:any, request: any, changes: Changes): { - result: Object; count: number + processResponse(data: any, ds: any, query: ej.Query, xhr: any, request: any, changes: Changes): { + result: any; count: number }; - convertToQueryString(req: Object, query: ej.Query, dm: ej.DataManager): JQueryParam; - insert(dm: ej.DataManager, data: Object, tableName: string): { url: string; data: Object; } + convertToQueryString(req: any, query: ej.Query, dm: ej.DataManager): JQueryParam; + insert(dm: ej.DataManager, data: any, tableName: string): { url: string; data: any; } remove(dm: ej.DataManager, keyField: string, value: any, tableName: string): { url: string; type: string; } - update(dm: ej.DataManager, keyField: string, value: any, tableName: string): { url: string; type: string; data: Object; accept: string; } - batchRequest(dm: ej.DataManager, changes: Changes, e: any): { url: string; type: string; data: Object; contentType: string; } - generateDeleteRequest(arr: Array, e: any): string; - generateInsertRequest(arr: Array, e: any): string; - generateUpdateRequest(arr: Array, e: any): string; + update(dm: ej.DataManager, keyField: string, value: any, tableName: string): { url: string; type: string; data: any; accept: string; } + batchRequest(dm: ej.DataManager, changes: Changes, e: any): { url: string; type: string; data: any; contentType: string; } + generateDeleteRequest(arr: any[], e: any): string; + generateInsertRequest(arr: any[], e: any): string; + generateUpdateRequest(arr: any[], e: any): string; } interface UrlAdaptorOptions { requestType?: string; @@ -295,28 +293,25 @@ declare module ej { changeSetContent?: string; batchChangeSetContentType?: string; } - class WebApiAdaptor extends ej.ODataAdaptor { constructor(); - insert(dm: ej.DataManager, data: Object, tableName?: string): { url: string; type: string; data: Object; } - remove(dm: ej.DataManager, value: any, keyField?: string, tableName?: string): { url: string; type: string; data: Object; } - update(dm: ej.DataManager, value: any, keyField?: string, tableName?: string): { url: string; type: string; data: Object; accept: string; } - processResponse(data: Object, ds: Object, query: ej.Query, xhr: any, request: any, changes: Changes): { - result: Object; count: number + insert(dm: ej.DataManager, data: any, tableName?: string): { url: string; type: string; data: any; } + remove(dm: ej.DataManager, value: any, keyField?: string, tableName?: string): { url: string; type: string; data: any; } + update(dm: ej.DataManager, value: any, keyField?: string, tableName?: string): { url: string; type: string; data: any; accept: string; } + processResponse(data: any, ds: any, query: ej.Query, xhr: any, request: any, changes: Changes): { + result: any; count: number }; } - class ODataV4Adaptor extends ej.ODataAdaptor { constructor(); options: ODataAdaptorOptions; - onCount(e: Object): string; - onEachSearch(e: Object): void; - onSearch(e: Object): string; + onCount(e: any): string; + onEachSearch(e: any): void; + onSearch(e: any): string; beforeSend(dm: ej.DataManager, request: any, settings?: any): void; - processResponse(data: Object, ds: Object, query: ej.Query, xhr:any, request: any, changes: Changes): { - result: Object; count: number + processResponse(data: any, ds: any, query: ej.Query, xhr: any, request: any, changes: Changes): { + result: any; count: number }; - } interface ODataAdaptorOptions { requestType?: string; @@ -341,31 +336,31 @@ declare module ej { class JsonAdaptor extends ej.Adaptor { constructor(); - processQuery(ds: Object, query: ej.Query): string; - batchRequest(dm: ej.DataManager, changes: Changes, e:any): Changes; - onWhere(ds: Object, e: any): any; - onSearch(ds: Object, e: any): any - onSortBy(ds: Object, e: any, query: ej.Query): Object; - onGroup(ds: Object, e: any, query: ej.Query): Object; - onPage(ds: Object, e: any, query: ej.Query): Object; - onRange(ds: Object, e: any): Object; - onTake(ds: Object, e: any): Object; - onSkip(ds: Object, e: any): Object; - onSelect(ds: Object, e: any): Object; - insert(dm: ej.DataManager, data: any): Object; - remove(dm: ej.DataManager, keyField: string, value:any, tableName: string): Object; - update(dm: ej.DataManager, keyField: string, value:any, tableName: string): Object; + processQuery(ds: any, query: ej.Query): string; + batchRequest(dm: ej.DataManager, changes: Changes, e: any): Changes; + onWhere(ds: any, e: any): any; + onSearch(ds: any, e: any): any + onSortBy(ds: any, e: any, query: ej.Query): any; + onGroup(ds: any, e: any, query: ej.Query): any; + onPage(ds: any, e: any, query: ej.Query): any; + onRange(ds: any, e: any): any; + onTake(ds: any, e: any): any; + onSkip(ds: any, e: any): any; + onSelect(ds: any, e: any): any; + insert(dm: ej.DataManager, data: any): any; + remove(dm: ej.DataManager, keyField: string, value: any, tableName: string): any; + update(dm: ej.DataManager, keyField: string, value: any, tableName: string): any; } class remoteSaveAdaptor extends ej.UrlAdaptor { constructor(); batchRequest(dm: ej.DataManager, changes: Changes, e: any): void; beforeSend(dm: ej.DataManager, request: any, settings?: any): void; - insert(dm: ej.DataManager, data: Object, tableName: string): { url: string; data: any }; + insert(dm: ej.DataManager, data: any, tableName: string): { url: string; data: any }; remove(dm: ej.DataManager, keyField: string, value: any, tableName: string): { type: string; url: string; data?: any }; update(dm: ej.DataManager, keyField: string, value: any, tableName: string): { type: string; url: string; data: any }; } class TableModel { - constructor(name: string, jsonArray: Array, dataManager: ej.DataManager, modelComputed: any); + constructor(name: string, jsonArray: any[], dataManager: ej.DataManager, modelComputed: any); on(eventName: string, handler: any): void; off(eventName: string, handler: any): void; setDataManager(dataManager: DataManager): void; @@ -376,15 +371,15 @@ declare module ej { remove(key: string): void; isDirty(): boolean; getChanges(): Changes; - toArray(): Array; - setDirty(dirty:any, model:any): void; + toArray(): any[]; + setDirty(dirty: any, model: any): void; get(index: number): void; length(): number; bindTo(element: any): void; } class Model { constructor(json: any, table: string, name: string); - formElements: Array; + formElements: string[]; computes(value: any): void; on(eventName: string, handler: any): void; off(eventName: string, handler: any): void; @@ -400,17 +395,17 @@ declare module ej { unbind(element: any): void; } interface Changes { - changed?: Array; - added?: Array; - deleted?: Array; + changed?: any[]; + added?: any[]; + deleted?: any[]; } class Predicate { constructor(); constructor(field: string, operator: ej.FilterOperators, value: any, ignoreCase: boolean); - and(field: string, operator: any, value:any, ignoreCase:boolean): void; - or(field: string, operator: any, value: any, ignoreCase: boolean): void; - or(predicate: Array): any; - validate(record: Object): boolean; + and(field: string, operator: any, value: any, ignoreCase: boolean): ej.Predicate; + or(field: string, operator: any, value: any, ignoreCase: boolean): ej.Predicate; + or(predicate: any[]): any; + validate(record: any): boolean; toJSON(): { isComplex: boolean; field: string; @@ -422,16 +417,16 @@ declare module ej { }; } interface dataUtil { - swap(array: Array, x: number, y: number): void; - mergeSort(jsonArray: Array, fieldName?: string, comparer?:any): Array; - max(jsonArray: Array, fieldName?: string, comparer?: string): Array; - min(jsonArray: Array, fieldName: string, comparer: string): Array; - distinct(jsonArray: Array, fieldName?: string, requiresCompleteRecord?:any): Array; - sum(json:any, fieldName: string): number; - avg(json:any, fieldName: string): number; - select(jsonArray: Array, fieldName: string, fields:string): Array; - group(jsonArray: Array, field: string, /* internal */ level: number): Array; - parseTable(table: string, headerOption: ej.headerOption, headerRowIndex: number): Object; + swap(array: any[], x: number, y: number): void; + mergeSort(jsonArray: any[], fieldName?: string, comparer?: any): any[]; + max(jsonArray: any[], fieldName?: string, comparer?: string): any[]; + min(jsonArray: any[], fieldName: string, comparer: string): any[]; + distinct(jsonArray: any[], fieldName?: string, requiresCompleteRecord?: any): any[]; + sum(json: any, fieldName: string): number; + avg(json: any, fieldName: string): number; + select(jsonArray: any[], fieldName: string, fields: string): any[]; + group(jsonArray: any[], field: string, /* internal */ level: number): any[]; + parseTable(table: string, headerOption: ej.headerOption, headerRowIndex: number): any; } interface AjaxSettings { type?: string; @@ -491,8 +486,7 @@ declare module ej { row, tHead } - - enum filterType{ + enum filterType { StartsWith, Contains, EndsWith, @@ -503,33 +497,32 @@ declare module ej { Equal, NotEqual } - enum Animation{ + enum Animation { Fade, None, Slide } - enum Type{ + enum Type { Overlay, Slide } - enum SortOrder{ + enum SortOrder { Ascending, Descending } class Draggable extends ej.Widget { static fn: Draggable; - constructor(element: JQuery, options?: Draggable.Model); - constructor(element: Element, options?: Draggable.Model); + constructor(element: JQuery | Element, options?: Draggable.Model); static Locale: any; - model:Draggable.Model; - defaults:Draggable.Model; + model: Draggable.Model; + defaults: Draggable.Model; /** destroy in the draggable. * @returns {void} */ _destroy(): void; } -export module Draggable{ +export namespace Draggable { export interface Model { @@ -564,19 +557,19 @@ export interface Model { scope?: string; /** This event is triggered when dragging element is destroyed. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** This event is triggered when the mouse is moved during the dragging. */ - drag? (e: DragEventArgs): void; + drag?(e: DragEventArgs): void; /** Supply a callback function to handle the drag start event as an init option. */ - dragStart? (e: DragStartEventArgs): void; + dragStart?(e: DragStartEventArgs): void; /** This event is triggered when the mouse is moved during the dragging. */ - dragStop? (e: DragStopEventArgs): void; + dragStop?(e: DragStopEventArgs): void; /** This event is triggered when dragged. */ - helper? (e: HelperEventArgs): void; + helper?(e: HelperEventArgs): void; } export interface DestroyEventArgs { @@ -677,18 +670,17 @@ export interface HelperEventArgs { class Droppable extends ej.Widget { static fn: Droppable; - constructor(element: JQuery, options?: Droppable.Model); - constructor(element: Element, options?: Droppable.Model); + constructor(element: JQuery | Element, options?: Droppable.Model); static Locale: any; - model:Droppable.Model; - defaults:Droppable.Model; + model: Droppable.Model; + defaults: Droppable.Model; /** destroy in the Droppable. * @returns {void} */ _destroy(): void; } -export module Droppable{ +export namespace Droppable { export interface Model { @@ -703,13 +695,13 @@ export interface Model { scope?: string; /** This event is triggered when the mouse up is moved during the dragging. */ - drop? (e: DropEventArgs): void; + drop?(e: DropEventArgs): void; /** This event is triggered when the mouse is moved out. */ - out? (e: OutEventArgs): void; + out?(e: OutEventArgs): void; /** This event is triggered when the mouse is moved over. */ - over? (e: OverEventArgs): void; + over?(e: OverEventArgs): void; } export interface DropEventArgs { @@ -772,18 +764,17 @@ export interface OverEventArgs { class Resizable extends ej.Widget { static fn: Resizable; - constructor(element: JQuery, options?: Resizable.Model); - constructor(element: Element, options?: Resizable.Model); + constructor(element: JQuery | Element, options?: Resizable.Model); static Locale: any; - model:Resizable.Model; - defaults:Resizable.Model; + model: Resizable.Model; + defaults: Resizable.Model; /** destroy in the Resizable. * @returns {void} */ _destroy(): void; } -export module Resizable{ +export namespace Resizable { export interface Model { @@ -828,10 +819,10 @@ export interface Model { scope?: string; /** This event is triggered when the widget destroys. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** This event is triggered when resized. */ - helper? (e: HelperEventArgs): void; + helper?(e: HelperEventArgs): void; } export interface DestroyEventArgs { @@ -866,8 +857,8 @@ export interface HelperEventArgs { } - var globalize:globalize; - var cultures:culture; + const globalize: globalize; + const cultures: culture; function addCulture(name: string, culture ?: any): void; function preferredCulture(culture ?: string): culture; function format(value: any, format: string, culture ?: string): string; @@ -895,22 +886,22 @@ interface globalize { calendars?: calendarsSettings; } interface formatSettings { - pattern: Array; + pattern: string[]; decimals: number; - groupSizes: Array; + groupSizes: number[]; percent: percentSettings; currency: currencySettings; } interface percentSettings { - pattern: Array; + pattern: string[]; decimals: number; - groupSizes: Array; + groupSizes: number[]; symbol: string; } interface currencySettings { - pattern: Array; + pattern: string[]; decimals: number; - groupSizes: Array; + groupSizes: number[]; symbol: string; } interface calendarsSettings { @@ -920,19 +911,19 @@ interface globalize { firstDay: number; days: daySettings; months: monthSettings; - AM: Array; - PM: Array; + AM: string[]; + PM: string[]; twoDigitYearMax: number; patterns: patternSettings; } interface daySettings { - names: Array; - namesAbbr: Array; - namesShort: Array; + names: string[]; + namesAbbr: string[]; + namesShort: string[]; } interface monthSettings { - names: Array; - namesAbbr: Array; + names: string[]; + namesAbbr: string[]; } interface patternSettings { d: string; @@ -947,11 +938,10 @@ interface globalize { } class Scroller extends ej.Widget { static fn: Scroller; - constructor(element: JQuery, options?: Scroller.Model); - constructor(element: Element, options?: Scroller.Model); + constructor(element: JQuery | Element, options?: Scroller.Model); static Locale: any; - model:Scroller.Model; - defaults:Scroller.Model; + model: Scroller.Model; + defaults: Scroller.Model; /** destroy the Scroller control, unbind the all ej control related events automatically and bring the control to pre-init state. * @returns {void} @@ -999,7 +989,7 @@ class Scroller extends ej.Widget { */ scrollY(pixel: number|string, disableAnimation: boolean, animationSpeed: number): void; } -export module Scroller{ +export namespace Scroller { export interface Model { @@ -1074,28 +1064,28 @@ export interface Model { width?: number|string; /** Fires when Scroller control is created. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires when Scroller control is destroyed. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Fires when a thumb point is moved along the touch surface. */ - thumbMove? (e: ThumbMoveEventArgs): void; + thumbMove?(e: ThumbMoveEventArgs): void; /** Fires when a thumb point is placed on the touch surface. */ - thumbStart? (e: ThumbStartEventArgs): void; + thumbStart?(e: ThumbStartEventArgs): void; /** Fires when a thumb point is removed from the touch surface. */ - thumbEnd? (e: ThumbEndEventArgs): void; + thumbEnd?(e: ThumbEndEventArgs): void; /** It fires whenever the mouse wheel is rotated either in upwards or downwards. */ - wheelMove? (e: WheelMoveEventArgs): void; + wheelMove?(e: WheelMoveEventArgs): void; /** It will fire when mouse trackball has been start to wheel. */ - wheelStart? (e: WheelStartEventArgs): void; + wheelStart?(e: WheelStartEventArgs): void; /** It will fire when mouse trackball has been stop to wheel. */ - wheelStop? (e: WheelStopEventArgs): void; + wheelStop?(e: WheelStopEventArgs): void; } export interface CreateEventArgs { @@ -1253,11 +1243,10 @@ export interface WheelStopEventArgs { class Accordion extends ej.Widget { static fn: Accordion; - constructor(element: JQuery, options?: Accordion.Model); - constructor(element: Element, options?: Accordion.Model); + constructor(element: JQuery | Element, options?: Accordion.Model); static Locale: any; - model:Accordion.Model; - defaults:Accordion.Model; + model: Accordion.Model; + defaults: Accordion.Model; /** AddItem method is used to add the panel in dynamically. It receives the following parameters * @param {string} specify the name of the header @@ -1292,7 +1281,7 @@ class Accordion extends ej.Widget { * @param {Array} index values to disable the panels * @returns {void} */ - disableItems(index: Array): void; + disableItems(index: any[]): void; /** Enable the accordion widget includes all the headers and content panels. * @returns {void} @@ -1303,7 +1292,7 @@ class Accordion extends ej.Widget { * @param {Array} index values to enable the panels * @returns {void} */ - enableItems(index: Array): void; + enableItems(index: any[]): void; /** To expand all the accordion widget items. * @returns {void} @@ -1341,7 +1330,7 @@ class Accordion extends ej.Widget { */ show(): void; } -export module Accordion{ +export namespace Accordion { export interface Model { @@ -1353,7 +1342,7 @@ export interface Model { /** Accordion headers can be expanded and collapsed on keyboard action. * @Default {true} */ - allowKeyboardNavigation?: Boolean; + allowKeyboardNavigation?: boolean; /** To set the Accordion headers Collapse Speed. * @Default {300} @@ -1367,9 +1356,9 @@ export interface Model { /** Sets the root CSS class for Accordion theme, which is used customize. */ - cssClass?: String; + cssClass?: string; - /** Allows you to set the custom header Icon. It accepts two key values “header”, ”selectedHeader”. + /** Allows you to set the custom header Icon. It accepts two key values “header”, ”selectedHeader”. * @Default {{ header: e-collapse, selectedHeader: e-expand }} */ customIcon?: CustomIcon; @@ -1382,12 +1371,12 @@ export interface Model { /** Specifies the animation behavior in accordion. * @Default {true} */ - enableAnimation?: Boolean; + enableAnimation?: boolean; /** With this enabled property, you can enable or disable the Accordion. * @Default {true} */ - enabled?: Boolean; + enabled?: boolean; /** Used to enable the disabled items in accordion. * @Default {[]} @@ -1397,22 +1386,22 @@ export interface Model { /** Multiple content panels to activate at a time. * @Default {false} */ - enableMultipleOpen?: Boolean; + enableMultipleOpen?: boolean; /** Save current model value to browser cookies for maintaining states. When refreshing the accordion control page, the model value is applied from browser cookies or HTML 5local storage. * @Default {false} */ - enablePersistence?: Boolean; + enablePersistence?: boolean; /** Display headers and panel text from right-to-left. * @Default {false} */ - enableRTL?: Boolean; + enableRTL?: boolean; /** The events API binds the action for activating the accordion header. Users can activate the header by using mouse actions such as mouse-over, mouse-up, mouse-down, and soon. * @Default {click} */ - events?: String; + events?: string; /** To set the Accordion headers Expand Speed. * @Default {300} @@ -1451,7 +1440,7 @@ export interface Model { /** Used to determines the close button visibility an each accordion items. This close button helps to remove the accordion item from the control. * @Default {false} */ - showCloseButton?: Boolean; + showCloseButton?: boolean; /** Displays rounded corner borders on the Accordion control's panels and headers. * @Default {false} @@ -1464,34 +1453,34 @@ export interface Model { width?: number|string; /** Triggered after a Accordion item is active or inactive. Argument values are activeIndex, activeHeader, inActiveHeader, inActiveIndex and current model value. */ - activate? (e: ActivateEventArgs): void; + activate?(e: ActivateEventArgs): void; /** Triggered before the AJAX content is loaded in a content panel. Arguments have location of the content (URL) and current model value. */ - ajaxBeforeLoad? (e: AjaxBeforeLoadEventArgs): void; + ajaxBeforeLoad?(e: AjaxBeforeLoadEventArgs): void; /** Triggered after AJAX load failed action. Arguments have URL, error message, and current model value. */ - ajaxError? (e: AjaxErrorEventArgs): void; + ajaxError?(e: AjaxErrorEventArgs): void; /** Triggered after the AJAX content loads. Arguments have current model values. */ - ajaxLoad? (e: AjaxLoadEventArgs): void; + ajaxLoad?(e: AjaxLoadEventArgs): void; /** Triggered after AJAX success action. Arguments have URL, content, and current model values. */ - ajaxSuccess? (e: AjaxSuccessEventArgs): void; + ajaxSuccess?(e: AjaxSuccessEventArgs): void; /** Triggered before a tab item is active. Arguments have active index and model values. */ - beforeActivate? (e: BeforeActivateEventArgs): void; + beforeActivate?(e: BeforeActivateEventArgs): void; /** Triggered after a Accordion item is active or inactive. Argument values are activeIndex, activeHeader, inActiveHeader, inActiveIndex and current model value. */ - beforeInactivate? (e: BeforeInactivateEventArgs): void; + beforeInactivate?(e: BeforeInactivateEventArgs): void; /** Triggered after Accordion control creation. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Triggered after Accordion control destroy. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Triggered after a Accordion item is active or inactive. Argument values are activeIndex, activeHeader, inActiveHeader, inActiveIndex and current model value. */ - inActivate? (e: InActivateEventArgs): void; + inActivate?(e: InActivateEventArgs): void; } export interface ActivateEventArgs { @@ -1716,15 +1705,15 @@ export interface AjaxSettings { /** It specifies, whether to enable or disable asynchronous request. */ - async?: Boolean; + async?: boolean; /** It specifies the page will be cached in the web browser. */ - cache?: Boolean; + cache?: boolean; /** It specifies the type of data is send in the query string. */ - contentType?: String; + contentType?: string; /** It specifies the data as an object, will be passed in the query string. */ @@ -1732,25 +1721,25 @@ export interface AjaxSettings { /** It specifies the type of data that you're expecting back from the response. */ - dataType?: String; + dataType?: string; /** It specifies the HTTP request type. */ - type?: String; + type?: string; } export interface CustomIcon { /** This class name set to collapsing header. */ - header?: String; + header?: string; /** This class name set to expanded (active) header. */ - selectedHeader?: String; + selectedHeader?: string; } -enum HeightAdjustMode{ +enum HeightAdjustMode { ///Height fit to the content in the panel Content, @@ -1766,11 +1755,10 @@ enum HeightAdjustMode{ class Autocomplete extends ej.Widget { static fn: Autocomplete; - constructor(element: JQuery, options?: Autocomplete.Model); - constructor(element: Element, options?: Autocomplete.Model); + constructor(element: JQuery | Element, options?: Autocomplete.Model); static Locale: any; - model:Autocomplete.Model; - defaults:Autocomplete.Model; + model: Autocomplete.Model; + defaults: Autocomplete.Model; /** Clears the text in the Autocomplete textbox. * @returns {void} @@ -1829,7 +1817,7 @@ class Autocomplete extends ej.Widget { */ selectValueByText(Text: string): void; } -export module Autocomplete{ +export namespace Autocomplete { export interface Model { @@ -1838,7 +1826,8 @@ export interface Model { */ addNewText?: boolean; - /** Allows new values to be added to the autocomplete input other than the values in the suggestion list. Normally, when there are no suggestions it will display “No suggestions” label in the popup. + /** Allows new values to be added to the autocomplete input other than the values in the suggestion list. + * Normally, when there are no suggestions it will display “No suggestions” label in the popup. * @Default {false} */ allowAddNew?: boolean; @@ -1864,14 +1853,14 @@ export interface Model { caseSensitiveSearch?: boolean; /** The root class for the Autocomplete textbox widget which helps in customizing its theme. - * @Default {””} + * @Default {””} */ cssClass?: string; /** The data source contains the list of data for the suggestions list. It can be a string array or JSON array. * @Default {null} */ - dataSource?: any|Array; + dataSource?: any|any[]; /** The time delay (in milliseconds) after which the suggestion popup will be shown. * @Default {200} @@ -1879,12 +1868,12 @@ export interface Model { delaySuggestionTimeout?: number; /** The special character which acts as a separator for the given words for multi-mode search i.e. the text after the delimiter are considered as a separate word or query for search operation. - * @Default {’,’} + * @Default {’,’} */ delimiterChar?: string; /** The text to be displayed in the popup when there are no suggestions available for the entered text. - * @Default {“No suggestions”} + * @Default {“No suggestions”} */ emptyResultText?: string; @@ -1903,12 +1892,14 @@ export interface Model { */ enableDistinct?: boolean; - /** Allows the current model values to be saved in local storage or browser cookies for state maintenance when it is set to true. While refreshing the page, it retains the model value from browser cookies or local storage. + /** Allows the current model values to be saved in local storage or browser cookies for state maintenance + * when it is set to true. + * While refreshing the page, it retains the model value from browser cookies or local storage. * @Default {false} */ enablePersistence?: boolean; - /** Displays the Autocomplete widget’s content from right to left when enabled. + /** Displays the Autocomplete widget’s content from right to left when enabled. * @Default {false} */ enableRTL?: boolean; @@ -1918,7 +1909,10 @@ export interface Model { */ fields?: Fields; - /** Specifies the search filter type. There are several types of search filter available such as ‘startswith’, ‘contains’, ‘endswith’, ‘lessthan’, ‘lessthanorequal’, ‘greaterthan’, ‘greaterthanorequal’, ‘equal’, ‘notequal’. + /** Specifies the search filter type. + * There are several types of search filter available such as ‘startswith’, + * ‘contains’, ‘endswith’, ‘lessthan’, ‘lessthanorequal’, ‘greaterthan’, + * ‘greaterthanorequal’, ‘equal’, ‘notequal’. * @Default {ej.filterType.StartsWith} */ filterType?: string; @@ -1957,12 +1951,12 @@ export interface Model { multiSelectMode?: ej.Autocomplete.MultiSelectMode|string; /** The height of the suggestion list. - * @Default {“152px”} + * @Default {“152px”} */ popupHeight?: string; /** The width of the suggestion list. - * @Default {“auto”} + * @Default {“auto”} */ popupWidth?: string; @@ -2046,52 +2040,64 @@ export interface Model { width?: string; /** Triggers when the AJAX requests Begins. */ - actionBegin? (e: ActionBeginEventArgs): void; + actionBegin?(e: ActionBeginEventArgs): void; /** Triggers when the data requested from AJAX will get successfully loaded in the Autocomplete widget. */ - actionSuccess? (e: ActionSuccessEventArgs): void; + actionSuccess?(e: ActionSuccessEventArgs): void; /** Triggers when the AJAX requests complete. The request may get failed or succeed. */ - actionComplete? (e: ActionCompleteEventArgs): void; + actionComplete?(e: ActionCompleteEventArgs): void; /** Triggers when the data requested from AJAX get failed. */ - actionFailure? (e: ActionFailureEventArgs): void; + actionFailure?(e: ActionFailureEventArgs): void; /** Triggers when the text box value is changed. */ - change? (e: ChangeEventArgs): void; + change?(e: ChangeEventArgs): void; /** Triggers after the suggestion popup is closed. */ - close? (e: CloseEventArgs): void; + close?(e: CloseEventArgs): void; /** Triggers when Autocomplete widget is created. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Triggers after the Autocomplete widget is destroyed. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Triggers after the autocomplete textbox is focused. */ - focusIn? (e: FocusInEventArgs): void; + focusIn?(e: FocusInEventArgs): void; /** Triggers after the Autocomplete textbox gets out of the focus. */ - focusOut? (e: FocusOutEventArgs): void; + focusOut?(e: FocusOutEventArgs): void; /** Triggers after the suggestion list is opened. */ - open? (e: OpenEventArgs): void; + open?(e: OpenEventArgs): void; /** Triggers when an item has been selected from the suggestion list. */ - select? (e: SelectEventArgs): void; + select?(e: SelectEventArgs): void; } export interface ActionBeginEventArgs { + /** Returns the cancel option value. + */ + cancel?: boolean; } export interface ActionSuccessEventArgs { + /** Returns the cancel option value. + */ + cancel?: boolean; } export interface ActionCompleteEventArgs { + /** Returns the cancel option value. + */ + cancel?: boolean; } export interface ActionFailureEventArgs { + /** Returns the cancel option value. + */ + cancel?: boolean; } export interface ChangeEventArgs { @@ -2275,12 +2281,14 @@ export interface MultiColumnSettingsColumn { */ cssClass?: string; - /** Specifies the search data type. There are four types of data types available such as string, ‘number’, ‘boolean’ and ‘date’. + /** Specifies the search data type. There are four types of data types available such as string, ‘number’, ‘boolean’ and ‘date’. * @Default {ej.Type.String} */ type?: ej.Type|string; - /** Specifies the search filter type. There are several types of search filter available such as ‘startswith’, ‘contains’, ‘endswith’, ‘lessthan’, ‘lessthanorequal’, ‘greaterthan’, ‘greaterthanorequal’, ‘equal’, ‘notequal’. + /** Specifies the search filter type. There are several types of search filter available such as ‘startswith’, + * ‘contains’, ‘endswith’, ‘lessthan’, ‘lessthanorequal’, ‘greaterthan’, + * ‘greaterthanorequal’, ‘equal’, ‘notequal’. * @Default {ej.filterType.StartsWith} */ filterType?: ej.filterType|string; @@ -2293,7 +2301,7 @@ export interface MultiColumnSettingsColumn { /** Gets or sets a value that indicates to align the text within the column. See textAlign * @Default {ej.TextAlign.Left} */ - textAlign?: ej.TextAlign|string; + textAlign?: ej.TextAlign|string; } export interface MultiColumnSettings { @@ -2314,10 +2322,10 @@ export interface MultiColumnSettings { /** Field and Header Text collections can be defined and customized through columns field. */ - columns?: Array; + columns?: MultiColumnSettingsColumn[]; } -enum Animation{ +enum Animation { ///Supports to animation type with none type only. None, @@ -2330,7 +2338,7 @@ enum Animation{ } -enum MultiSelectMode{ +enum MultiSelectMode { ///Multiple values are separated using a given special character. Delimiter, @@ -2340,7 +2348,7 @@ enum MultiSelectMode{ } -enum SortOrder{ +enum SortOrder { ///Items to be displayed in the suggestion list in ascending order. Ascending, @@ -2353,11 +2361,10 @@ enum SortOrder{ class Button extends ej.Widget { static fn: Button; - constructor(element: JQuery, options?: Button.Model); - constructor(element: Element, options?: Button.Model); + constructor(element: JQuery | Element, options?: Button.Model); static Locale: any; - model:Button.Model; - defaults:Button.Model; + model: Button.Model; + defaults: Button.Model; /** destroy the button widget all events bound using this._on will be unbind automatically and bring the control to pre-init state. * @returns {void} @@ -2374,7 +2381,7 @@ class Button extends ej.Widget { */ enable(): void; } -export module Button{ +export namespace Button { export interface Model { @@ -2407,7 +2414,9 @@ export interface Model { */ htmlAttributes?: any; - /** Specifies the image position of the Button. This image position is applicable only with the textandimage contentType property. The images can be positioned in both imageLeft and imageRight options. See below to know about available ImagePosition + /** Specifies the image position of the Button. This image position is applicable + * only with the textandimage contentType property. The images can be positioned in both + * imageLeft and imageRight options. See below to know about available ImagePosition * @Default {ej.ImagePosition.ImageLeft} */ imagePosition?: ej.ImagePosition|string; @@ -2457,14 +2466,17 @@ export interface Model { */ width?: string|number; - /** Fires when Button control is clicked successfully.Consider the scenario to perform any validation,modification of content or any other operations click on button,we can make use of this click event to achieve the scenario. */ - click? (e: ClickEventArgs): void; + /** Fires when Button control is clicked successfully.Consider the scenario to perform any validation, + * modification of content or any other operations click on button,we can make use of this click event + * to achieve the scenario. + */ + click?(e: ClickEventArgs): void; /** Fires after Button control is created.If the user want to perform any operation after the button control creation then the user can make use of this create event. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires when the button is destroyed successfully.If the user want to perform any operation after the destroy button control then the user can make use of this destroy event. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; } export interface ClickEventArgs { @@ -2520,8 +2532,7 @@ export interface DestroyEventArgs { type?: string; } } -enum ContentType -{ +enum ContentType { //To display the text content only in button TextOnly, //To display the image only in button @@ -2533,8 +2544,7 @@ TextAndImage, //Supports to display image with both ends of the text ImageTextImage, } -enum ImagePosition -{ +enum ImagePosition { //support for aligning text in left and image in right ImageRight, //support for aligning text in right and image in left @@ -2544,8 +2554,7 @@ ImageTop, //support for aligning text in top and image in bottom ImageBottom, } -enum ButtonSize -{ +enum ButtonSize { //Creates button with Built-in default size height, width specified Normal, //Creates button with Built-in mini size height, width specified @@ -2557,8 +2566,7 @@ Medium, //Creates button with Built-in large size height, width specified Large, } -enum ButtonType -{ +enum ButtonType { //Creates button with Built-in button type specified Button, //Creates button with Built-in reset type specified @@ -2569,13 +2577,12 @@ Submit, class Captcha extends ej.Widget { static fn: Captcha; - constructor(element: JQuery, options?: Captcha.Model); - constructor(element: Element, options?: Captcha.Model); + constructor(element: JQuery | Element, options?: Captcha.Model); static Locale: any; - model:Captcha.Model; - defaults:Captcha.Model; + model: Captcha.Model; + defaults: Captcha.Model; } -export module Captcha{ +export namespace Captcha { export interface Model { @@ -2648,16 +2655,16 @@ export interface Model { width?: number; /** Fires when captcha refresh begins. */ - refreshBegin? (e: RefreshBeginEventArgs): void; + refreshBegin?(e: RefreshBeginEventArgs): void; /** Fires after captcha refresh completed. */ - refreshComplete? (e: RefreshCompleteEventArgs): void; + refreshComplete?(e: RefreshCompleteEventArgs): void; /** Fires when captcha refresh fails to load. */ - refreshFailure? (e: RefreshFailureEventArgs): void; + refreshFailure?(e: RefreshFailureEventArgs): void; /** Fires after captcha refresh succeeded. */ - refreshSuccess? (e: RefreshSuccessEventArgs): void; + refreshSuccess?(e: RefreshSuccessEventArgs): void; } export interface RefreshBeginEventArgs { @@ -2720,8 +2727,7 @@ export interface RefreshSuccessEventArgs { type?: string; } } -enum HatchStyle -{ +enum HatchStyle { //Set background as None to Captcha None, //Set background as BackwardDiagonal to Captcha @@ -2800,14 +2806,14 @@ ZigZag, class ListBox extends ej.Widget { static fn: ListBox; - constructor(element: JQuery, options?: ListBox.Model); - constructor(element: Element, options?: ListBox.Model); + constructor(element: JQuery | Element, options?: ListBox.Model); static Locale: any; - model:ListBox.Model; - defaults:ListBox.Model; + model: ListBox.Model; + defaults: ListBox.Model; /** Adds a given list items in the ListBox widget at a specified index. It accepts two parameters. - * @param {any|string} This can be a list item object (for JSON binding) or a string (for UL and LI rendering). Also we can the specify this as an array of list item object or an array of strings to add multiple items. + * @param {any|string} This can be a list item object (for JSON binding) or a string (for UL and LI rendering). + * Also we can the specify this as an array of list item object or an array of strings to add multiple items. * @param {number} The index value to add the given items at the specified index. If index is not specified, the given items will be added at the end of the list. * @returns {void} */ @@ -2886,29 +2892,29 @@ class ListBox extends ej.Widget { */ getSelectedItems(): any; - /** Returns an item’s index based on the given text. + /** Returns an item’s index based on the given text. * @param {string} The list item text (label) * @returns {number} */ getIndexByText(text: string): number; - /** Returns an item’s index based on the value given. - * @param {string} The list item’s value + /** Returns an item’s index based on the value given. + * @param {string} The list item’s value * @returns {number} */ getIndexByValue(indices: string): number; - /** Returns an item’s text (label) based on the index given. + /** Returns an item’s text (label) based on the index given. * @returns {string} */ getTextByIndex(): string; - /** Returns a list item’s object using its index. + /** Returns a list item’s object using its index. * @returns {any} */ getItemByIndex(): any; - /** Returns a list item’s object based on the text given. + /** Returns a list item’s object based on the text given. * @param {string} The list item text. * @returns {any} */ @@ -2918,7 +2924,7 @@ class ListBox extends ej.Widget { * @param {Array} Data to merge in listbox. * @returns {void} */ - mergeData(data: Array): void; + mergeData(data: any[]): void; /** Selects the next item based on the current selection. * @returns {void} @@ -3054,13 +3060,13 @@ class ListBox extends ej.Widget { * @param {Array} Values of the listbox items to be shown. * @returns {void} */ - showItemsByValues(values: Array): void; + showItemsByValues(values: any[]): void; /** Hides the list item using its values. * @param {Array} Values of the listbox items to be hidden. * @returns {void} */ - hideItemsByValues(values: Array): void; + hideItemsByValues(values: any[]): void; /** Shows a hidden list item using its value. * @param {string} Value of the listbox item to be shown. @@ -3106,7 +3112,7 @@ class ListBox extends ej.Widget { */ showAllItems(): void; } -export module ListBox{ +export namespace ListBox { export interface Model { @@ -3125,7 +3131,7 @@ export interface Model { */ allowMultiSelection?: boolean; - /** Loads the list data on demand via scrolling behavior to improve the application’s performance. There are two ways to load data which can be defined using “virtualScrollMode” property. + /** Loads the list data on demand via scrolling behavior to improve the application’s performance. There are two ways to load data which can be defined using “virtualScrollMode” property. * @Default {false} */ allowVirtualScrolling?: boolean; @@ -3135,7 +3141,9 @@ export interface Model { */ caseSensitiveSearch?: boolean; - /** Dynamically populate data of a list box while selecting an item in another list box i.e. rendering child list box based on the item selection in parent list box. This property accepts the id of the child ListBox widget to populate the data. + /** Dynamically populate data of a list box while selecting an item in another list box i.e. + * rendering child list box based on the item selection in parent list box. + * This property accepts the id of the child ListBox widget to populate the data. * @Default {null} */ cascadeTo?: string; @@ -3143,10 +3151,10 @@ export interface Model { /** Set of list items to be checked by default using its index. It works only when the showCheckbox property is set to true. * @Default {null} */ - checkedIndices?: Array; + checkedIndices?: any[]; /** The root class for the ListBox widget to customize the existing theme. - * @Default {“”} + * @Default {“”} */ cssClass?: string; @@ -3170,7 +3178,7 @@ export interface Model { */ enablePersistence?: boolean; - /** Displays the ListBox widget’s content from right to left when enabled. + /** Displays the ListBox widget’s content from right to left when enabled. * @Default {false} */ enableRTL?: boolean; @@ -3227,7 +3235,7 @@ export interface Model { /** The list items to be selected by default using its indices. To use this property allowMultiSelection should be enabled. * @Default {[]} */ - selectedIndices?: Array; + selectedIndices?: any[]; /** Enables/Disables the multi selection option with the help of checkbox control. * @Default {false} @@ -3245,7 +3253,7 @@ export interface Model { template?: string; /** Holds the selected items values and used to bind value to the list item using AngularJS and KnockoutJS. - * @Default {“”} + * @Default {“”} */ value?: number; @@ -3263,67 +3271,79 @@ export interface Model { targetID?: string; /** Triggers before the AJAX request begins to load data in the ListBox widget. */ - actionBegin? (e: ActionBeginEventArgs): void; + actionBegin?(e: ActionBeginEventArgs): void; /** Triggers after the data requested via AJAX is successfully loaded in the ListBox widget. */ - actionSuccess? (e: ActionSuccessEventArgs): void; + actionSuccess?(e: ActionSuccessEventArgs): void; /** Triggers when the AJAX requests complete. The request may get failed or succeed. */ - actionComplete? (e: ActionCompleteEventArgs): void; + actionComplete?(e: ActionCompleteEventArgs): void; /** Triggers when the data requested from AJAX get failed. */ - actionFailure? (e: ActionFailureEventArgs): void; + actionFailure?(e: ActionFailureEventArgs): void; /** Event will be triggered before the requested data via AJAX once loaded in successfully. */ - actionBeforeSuccess? (e: ActionBeforeSuccessEventArgs): void; + actionBeforeSuccess?(e: ActionBeforeSuccessEventArgs): void; /** Triggers when the item selection is changed. */ - change? (e: ChangeEventArgs): void; + change?(e: ChangeEventArgs): void; /** Triggers when the list item is checked or unchecked. */ - checkChange? (e: CheckChangeEventArgs): void; + checkChange?(e: CheckChangeEventArgs): void; /** Triggers when the ListBox widget is created successfully. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Triggers when the ListBox widget is destroyed successfully. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Triggers when focus the listbox items. */ - focusIn? (e: FocusInEventArgs): void; + focusIn?(e: FocusInEventArgs): void; /** Triggers when focus out from listbox items. */ - focusOut? (e: FocusOutEventArgs): void; + focusOut?(e: FocusOutEventArgs): void; /** Triggers when the list item is being dragged. */ - itemDrag? (e: ItemDragEventArgs): void; + itemDrag?(e: ItemDragEventArgs): void; /** Triggers when the list item is ready to be dragged. */ - itemDragStart? (e: ItemDragStartEventArgs): void; + itemDragStart?(e: ItemDragStartEventArgs): void; /** Triggers when the list item stops dragging. */ - itemDragStop? (e: ItemDragStopEventArgs): void; + itemDragStop?(e: ItemDragStopEventArgs): void; /** Triggers when the list item is dropped. */ - itemDrop? (e: ItemDropEventArgs): void; + itemDrop?(e: ItemDropEventArgs): void; /** Triggers when a list item gets selected. */ - select? (e: SelectEventArgs): void; + select?(e: SelectEventArgs): void; /** Triggers when a list item gets unselected. */ - unselect? (e: UnselectEventArgs): void; + unselect?(e: UnselectEventArgs): void; } export interface ActionBeginEventArgs { + /** Returns the cancel option value. + */ + cancel?: boolean; } export interface ActionSuccessEventArgs { + /** Returns the cancel option value. + */ + cancel?: boolean; } export interface ActionCompleteEventArgs { + /** Returns the cancel option value. + */ + cancel?: boolean; } export interface ActionFailureEventArgs { + /** Returns the cancel option value. + */ + cancel?: boolean; } export interface ActionBeforeSuccessEventArgs { @@ -3350,7 +3370,7 @@ export interface ActionBeforeSuccessEventArgs { /** List of array object */ - result?: Array; + result?: any[]; /** ExecuteQuery object of DataManager */ @@ -3375,7 +3395,7 @@ export interface ChangeEventArgs { */ data?: any; - /** List item’s index. + /** List item’s index. */ index?: number; @@ -3395,11 +3415,11 @@ export interface ChangeEventArgs { */ isEnabled?: boolean; - /** List item’s text (label). + /** List item’s text (label). */ text?: string; - /** List item’s value. + /** List item’s value. */ value?: string; } @@ -3422,7 +3442,7 @@ export interface CheckChangeEventArgs { */ data?: any; - /** List item’s index. + /** List item’s index. */ index?: number; @@ -3442,11 +3462,11 @@ export interface CheckChangeEventArgs { */ isEnabled?: boolean; - /** List item’s text (label). + /** List item’s text (label). */ text?: string; - /** List item’s value. + /** List item’s value. */ value?: string; } @@ -3529,7 +3549,7 @@ export interface ItemDragEventArgs { */ data?: any; - /** List item’s index. + /** List item’s index. */ index?: number; @@ -3545,11 +3565,11 @@ export interface ItemDragEventArgs { */ isEnabled?: boolean; - /** List item’s text (label). + /** List item’s text (label). */ text?: string; - /** List item’s value. + /** List item’s value. */ value?: string; } @@ -3572,7 +3592,7 @@ export interface ItemDragStartEventArgs { */ data?: any; - /** List item’s index. + /** List item’s index. */ index?: number; @@ -3588,11 +3608,11 @@ export interface ItemDragStartEventArgs { */ isEnabled?: boolean; - /** List item’s text (label). + /** List item’s text (label). */ text?: string; - /** List item’s value. + /** List item’s value. */ value?: string; } @@ -3615,7 +3635,7 @@ export interface ItemDragStopEventArgs { */ data?: any; - /** List item’s index. + /** List item’s index. */ index?: number; @@ -3631,11 +3651,11 @@ export interface ItemDragStopEventArgs { */ isEnabled?: boolean; - /** List item’s text (label). + /** List item’s text (label). */ text?: string; - /** List item’s value. + /** List item’s value. */ value?: string; } @@ -3658,7 +3678,7 @@ export interface ItemDropEventArgs { */ data?: any; - /** List item’s index. + /** List item’s index. */ index?: number; @@ -3674,11 +3694,11 @@ export interface ItemDropEventArgs { */ isEnabled?: boolean; - /** List item’s text (label). + /** List item’s text (label). */ text?: string; - /** List item’s value. + /** List item’s value. */ value?: string; } @@ -3701,7 +3721,7 @@ export interface SelectEventArgs { */ data?: any; - /** List item’s index. + /** List item’s index. */ index?: number; @@ -3721,11 +3741,11 @@ export interface SelectEventArgs { */ isEnabled?: boolean; - /** List item’s text (label). + /** List item’s text (label). */ text?: string; - /** List item’s value. + /** List item’s value. */ value?: string; } @@ -3748,7 +3768,7 @@ export interface UnselectEventArgs { */ data?: any; - /** List item’s index. + /** List item’s index. */ index?: number; @@ -3768,11 +3788,11 @@ export interface UnselectEventArgs { */ isEnabled?: boolean; - /** List item’s text (label). + /** List item’s text (label). */ text?: string; - /** List item’s value. + /** List item’s value. */ value?: string; } @@ -3827,11 +3847,10 @@ export interface Fields { class Calculate { static fn: Calculate; - constructor(element: JQuery, options?: Calculate.Model); - constructor(element: Element, options?: Calculate.Model); + constructor(element: JQuery | Element, options?: Calculate.Model); static Locale: any; - model:Calculate.Model; - defaults:Calculate.Model; + model: Calculate.Model; + defaults: Calculate.Model; /** Add the custom formulas with function in CalcEngine library * @param {string} pass the formula name @@ -3882,19 +3901,21 @@ class Calculate { */ computeFormula(Formula: string): string; } -export module Calculate{ +export namespace Calculate { export interface Model { + /** Returns the cancel option value. + */ + cancel?: boolean; } } class CheckBox extends ej.Widget { static fn: CheckBox; - constructor(element: JQuery, options?: CheckBox.Model); - constructor(element: Element, options?: CheckBox.Model); + constructor(element: JQuery | Element, options?: CheckBox.Model); static Locale: any; - model:CheckBox.Model; - defaults:CheckBox.Model; + model: CheckBox.Model; + defaults: CheckBox.Model; /** Destroy the CheckBox widget all events bound using this._on will be unbind automatically and bring the control to pre-init state. * @returns {void} @@ -3916,11 +3937,15 @@ class CheckBox extends ej.Widget { */ isChecked(): boolean; } -export module CheckBox{ +export namespace CheckBox { export interface Model { - /** Specifies whether CheckBox has to be in checked or not. We can also specify array of string as value for this property. If any of the value in the specified array matches the value of the textbox, then it will be considered as checked. It will be useful in MVVM binding, specify array type to identify the values of the checked CheckBoxes. + /** Specifies whether CheckBox has to be in checked or not. + * We can also specify array of string as value for this property. + * If any of the value in the specified array matches the value of the textbox, + * then it will be considered as checked. It will be useful in MVVM binding, + * specify array type to identify the values of the checked CheckBoxes. * @Default {false} */ checked?: boolean|string[]; @@ -3939,7 +3964,9 @@ export interface Model { */ enabled?: boolean; - /** Specifies the persist property for CheckBox while initialization. The persist API save current model value to browser cookies for state maintains. While refreshing the CheckBox control page the model value apply from browser cookies. + /** Specifies the persist property for CheckBox while initialization. + * The persist API save current model value to browser cookies for state maintains. + * While refreshing the CheckBox control page the model value apply from browser cookies. * @Default {false} */ enablePersistence?: boolean; @@ -4004,16 +4031,16 @@ export interface Model { value?: string; /** Fires before the CheckBox is going to changed its state successfully */ - beforeChange? (e: BeforeChangeEventArgs): void; + beforeChange?(e: BeforeChangeEventArgs): void; /** Fires when the CheckBox state is changed successfully */ - change? (e: ChangeEventArgs): void; + change?(e: ChangeEventArgs): void; /** Fires when the CheckBox state is created successfully */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires when the CheckBox state is destroyed successfully */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; } export interface BeforeChangeEventArgs { @@ -4096,8 +4123,7 @@ export interface DestroyEventArgs { type?: string; } } -enum CheckState -{ +enum CheckState { //string Uncheck, //string @@ -4105,8 +4131,7 @@ Check, //string Indeterminate, } -enum CheckboxSize -{ +enum CheckboxSize { //Displays the CheckBox in medium size Medium, //Displays the CheckBox in small size @@ -4115,11 +4140,10 @@ Small, class ColorPicker extends ej.Widget { static fn: ColorPicker; - constructor(element: JQuery, options?: ColorPicker.Model); - constructor(element: Element, options?: ColorPicker.Model); + constructor(element: JQuery | Element, options?: ColorPicker.Model); static Locale: any; - model:ColorPicker.Model; - defaults:ColorPicker.Model; + model: ColorPicker.Model; + defaults: ColorPicker.Model; /** Disables the color picker control * @returns {void} @@ -4156,26 +4180,26 @@ class ColorPicker extends ej.Widget { * @param {any} Specified HSV code converted to RGB * @returns {any} */ - HSVToRGB(hsv: any): any; + HSVToRGB(HSV: any): any; /** Convert color value from RGB to HEX * @param {any} Specified RGB code converted to HEX code * @returns {string} */ - RGBToHEX(rgb: any): string; + RGBToHEX(RGB: any): string; /** Convert color value from RGB to HSV * @param {any} Specified RGB code converted to HSV code * @returns {any} */ - RGBToHSV(rgb: any): any; + RGBToHSV(RGB: any): any; /** Open the ColorPicker popup. * @returns {void} */ show(): void; } -export module ColorPicker{ +export namespace ColorPicker { export interface Model { @@ -4201,7 +4225,7 @@ export interface Model { /** This property allows to define the custom colors in the palette model.Custom palettes are created by passing a comma delimited string of HEX values or an array of colors. * @Default {empty} */ - custom?: Array; + custom?: any[]; /** This property allows to embed the popup in the order of DOM element flow . When we set the value as true, the color picker popup is always in visible state. * @Default {false} @@ -4243,7 +4267,8 @@ export interface Model { */ palette?: ej.ColorPicker.Palette|string; - /** This property allows to define the preset model to be rendered initially in palette type.It consists of 12 different types of presets. Each presets have 50 colors. See below available Presets + /** This property allows to define the preset model to be rendered initially in palette type.It consists of 12 different types of presets. Each presets have 50 colors. + * See below available Presets * @Default {ej.ColorPicker.Presets.Basic} */ presetType?: ej.ColorPicker.Presets|string; @@ -4263,7 +4288,8 @@ export interface Model { */ showPreview?: boolean; - /** This property allows to store the color values in custom list.The ColorPicker will keep up to 11 colors in a custom list.By clicking the add button, the selected color from picker or palette will get added in the recent color list. + /** This property allows to store the color values in custom list.The ColorPicker will keep up to 11 colors in a custom list. + * By clicking the add button, the selected color from picker or palette will get added in the recent color list. * @Default {false} */ showRecentColors?: boolean; @@ -4284,7 +4310,9 @@ export interface Model { toolIcon?: string; /** This property allows to define the customized text or content to displayed when mouse over the following elements. This property also allows to use the culture values. - * @Default {{ switcher: Switcher, addbutton: Add Color, basic: Basic, monochrome: Mono Chrome, flatcolors: Flat Color, seawolf: Sea Wolf, webcolors: Web Colors, sandy: Sandy, pinkshades: Pink Shades, misty: Misty, citrus: Citrus, vintage: Vintage, moonlight: Moon Light, candycrush: Candy Crush, currentcolor: Current Color, selectedcolor: Selected Color }} + * @Default {{ switcher: Switcher, addbutton: Add Color, basic: Basic, monochrome: Mono Chrome, flatcolors: Flat Color, seawolf: Sea Wolf, webcolors: Web Colors, + * sandy: Sandy, pinkshades: Pink Shades, misty: Misty, citrus: Citrus, vintage: Vintage, moonlight: Moon Light, candycrush: Candy Crush, + * currentcolor: Current Color, selectedcolor: Selected Color }} */ tooltipText?: TooltipText; @@ -4294,22 +4322,22 @@ export interface Model { value?: string; /** Fires after Color value has been changed successfully.If the user want to perform any operation after the color value changed then the user can make use of this change event. */ - change? (e: ChangeEventArgs): void; + change?(e: ChangeEventArgs): void; /** Fires after closing the color picker popup. */ - close? (e: CloseEventArgs): void; + close?(e: CloseEventArgs): void; /** Fires after Color picker control is created. If the user want to perform any operation after the color picker control creation then the user can make use of this create event. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires after Color picker control is destroyed. If the user want to perform any operation after the color picker control destroyed then the user can make use of this destroy event. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Fires after opening the color picker popup */ - open? (e: OpenEventArgs): void; + open?(e: OpenEventArgs): void; /** Fires after Color value has been selected successfully. If the user want to perform any operation after the color value selected then the user can make use of this select event. */ - select? (e: SelectEventArgs): void; + select?(e: SelectEventArgs): void; } export interface ChangeEventArgs { @@ -4492,7 +4520,7 @@ export interface TooltipText { selectedcolor?: string; } -enum ModelType{ +enum ModelType { ///support palette type mode in color picker. Palette, @@ -4502,7 +4530,7 @@ enum ModelType{ } -enum Palette{ +enum Palette { ///used to show the basic palette BasicPalette, @@ -4512,7 +4540,7 @@ enum Palette{ } -enum Presets{ +enum Presets { ///used to show the basic presets Basic, @@ -4549,8 +4577,7 @@ enum Presets{ } } -enum ButtonMode -{ +enum ButtonMode { //Displays the button in split mode Split, //Displays the button in Dropdown mode @@ -4559,11 +4586,10 @@ Dropdown, class FileExplorer extends ej.Widget { static fn: FileExplorer; - constructor(element: JQuery, options?: FileExplorer.Model); - constructor(element: Element, options?: FileExplorer.Model); + constructor(element: JQuery | Element, options?: FileExplorer.Model); static Locale: any; - model:FileExplorer.Model; - defaults:FileExplorer.Model; + model: FileExplorer.Model; + defaults: FileExplorer.Model; /** Refresh the size of FileExplorer control. * @returns {void} @@ -4605,7 +4631,7 @@ class FileExplorer extends ej.Widget { */ removeToolbarItem(item: string|HTMLElement): void; } -export module FileExplorer{ +export namespace FileExplorer { export interface Model { @@ -4618,12 +4644,14 @@ export interface Model { */ ajaxDataType?: string; - /** By using ajaxSettings property, you can customize the AJAX configurations. Normally you can customize the following option in AJAX handling data, URL, type, async, contentType, dataType and success. For upload, download and getImage API, you can only customize URL. + /** By using ajaxSettings property, you can customize the AJAX configurations. Normally you can customize the following option in AJAX handling data, URL, type, async, contentType, dataType and + * success. For upload, download and getImage API, you can only customize URL. * @Default {{ read: {}, createFolder: {}, remove: {}, rename: {}, paste: {}, getDetails: {}, download: {}, upload: {}, getImage: {}, search: {}}} */ ajaxSettings?: any; - /** The FileExplorer allows to move the files from one folder to another folder of FileExplorer by using drag and drop option. Also it supports to upload a file by dragging it from windows explorer to the necessary folder of ejFileExplorer. + /** The FileExplorer allows to move the files from one folder to another folder of FileExplorer by using drag and drop option. Also it supports to upload a file by dragging it + * from windows explorer to the necessary folder of ejFileExplorer. * @Default {true} */ allowDragAndDrop?: boolean; @@ -4642,7 +4670,8 @@ export interface Model { */ contextMenuSettings?: ContextMenuSettings; - /** Sets the root class for FileExplorer theme. This cssClass API allows to use custom skinning option for File Explorer control. By defining the root class by using this API, you have to include this root class in CSS. + /** Sets the root class for FileExplorer theme. This cssClass API allows to use custom skinning option for File Explorer control. + * By defining the root class by using this API, you have to include this root class in CSS. */ cssClass?: string; @@ -4729,7 +4758,7 @@ export interface Model { /** The selectedItems is used to select the specified items (file, folder) of FileExplorer control. */ - selectedItems?: string|Array; + selectedItems?: string|any[]; /** Enables or disables the checkbox option in FileExplorer control. * @Default {true} @@ -4741,7 +4770,8 @@ export interface Model { */ showContextMenu?: boolean; - /** Enables or disables the footer in FileExplorer control. The footer element displays the details of the current selected files and folders. And also the footer having the switcher to change the layout view. + /** Enables or disables the footer in FileExplorer control. The footer element displays the details of the current selected files and folders. + * And also the footer having the switcher to change the layout view. * @Default {true} */ showFooter?: boolean; @@ -4761,20 +4791,22 @@ export interface Model { */ showToolbar?: boolean; - /** Enables or disables the navigation pane in FileExplorer control. The navigation pane contains a tree view element that displays all the folders from the filesystem in a hierarchical manner. This is useful to a quick navigation of any folder in the filesystem. + /** Enables or disables the navigation pane in FileExplorer control. The navigation pane contains a tree view element that displays all the folders from the filesystem in a hierarchical manner. + * This is useful to a quick navigation of any folder in the filesystem. * @Default {true} */ showNavigationPane?: boolean; /** The tools property is used to configure and group required toolbar items in FileExplorer control. - * @Default {{ creation: [NewFolder], navigation: [Back, Forward, Upward], addressBar: [Addressbar], editing: [Refresh, Upload, Delete, Rename, Download], copyPaste: [Cut, Copy, Paste], getProperties: [Details], searchBar: [Searchbar], layout: [Layout], sortBy: [SortBy]}} + * @Default {{ creation: [NewFolder], navigation: [Back, Forward, Upward], addressBar: [Addressbar], editing: [Refresh, Upload, Delete, Rename, Download], copyPaste: [Cut, Copy, Paste], + * getProperties: [Details], searchBar: [Searchbar], layout: [Layout], sortBy: [SortBy]}} */ tools?: any; /** The toolsList property is used to arrange the toolbar items in the FileExplorer control. * @Default {[layout, creation, navigation, addressBar, editing, copyPaste, sortBy, getProperties, searchBar]} */ - toolsList?: Array; + toolsList?: any[]; /** Gets or sets an object that indicates whether to customize the upload behavior in the FileExplorer. */ @@ -4786,55 +4818,93 @@ export interface Model { width?: string|number; /** Fires before the AJAX request is performed. */ - beforeAjaxRequest? (e: BeforeAjaxRequestEventArgs): void; + beforeAjaxRequest?(e: BeforeAjaxRequestEventArgs): void; /** Fires before downloading the files. */ - beforeDownload? (e: BeforeDownloadEventArgs): void; + beforeDownload?(e: BeforeDownloadEventArgs): void; - /** Fires before getting a requested image from server. Also this event will be triggered when you have enabled thumbnail image compression option in FileExplorer.Using this event, you can customize the image compression size. */ - beforeGetImage? (e: BeforeGetImageEventArgs): void; + /** Fires before getting a requested image from server. Also this event will be triggered when you have enabled thumbnail image compression option in FileExplorer. + * Using this event, you can customize the image compression size. + */ + beforeGetImage?(e: BeforeGetImageEventArgs): void; /** Fires before files or folders open. */ - beforeOpen? (e: BeforeOpenEventArgs): void; + beforeOpen?(e: BeforeOpenEventArgs): void; /** Fires before uploading the files. */ - beforeUpload? (e: BeforeUploadEventArgs): void; + beforeUpload?(e: BeforeUploadEventArgs): void; /** Fires when FileExplorer control was created */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires when file or folder is copied successfully. */ - copy? (e: CopyEventArgs): void; + copy?(e: CopyEventArgs): void; /** Fires when new folder is created successfully in file system. */ - createFolder? (e: CreateFolderEventArgs): void; + createFolder?(e: CreateFolderEventArgs): void; /** Fires when file or folder is cut successfully. */ - cut? (e: CutEventArgs): void; + cut?(e: CutEventArgs): void; /** Fires when the FileExplorer is destroyed successfully. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Fires when the files or directory has been started to drag over on the FileExplorer */ - dragStart? (e: DragStartEventArgs): void; + dragStart?(e: DragStartEventArgs): void; /** Fires when the files or directory is dragging over on the FileExplorer. */ - drag? (e: DragEventArgs): void; + drag?(e: DragEventArgs): void; /** Fires when the files or directory has been stopped to drag over on FileExplorer */ - dragStop? (e: DragStopEventArgs): void; + dragStop?(e: DragStopEventArgs): void; /** Fires when the files or directory is dropped to the target folder of FileExplorer */ - drop? (e: DropEventArgs): void; + drop?(e: DropEventArgs): void; /** Fires after loading the requested image from server. Using this event, you can get the details of loaded image. */ - getImage? (e: GetImageEventArgs): void; + getImage?(e: GetImageEventArgs): void; /** Fires when keydown in FileExplorer control. */ - keydown? (e: KeydownEventArgs): void; + keydown?(e: KeydownEventArgs): void; /** Fires when the file view type is changed. */ - layoutChange? (e: LayoutChangeEventArgs): void; + layoutChange?(e: LayoutChangeEventArgs): void; + + /** Fires when before the ContextMenu opening. */ + menuBeforeOpen?(e: MenuBeforeOpenEventArgs): void; + + /** Fires when click the ContextMenu item. */ + menuClick?(e: MenuClickEventArgs): void; + + /** Fires when ContextMenu is successfully opened. */ + menuOpen?(e: MenuOpenEventArgs): void; + + /** Fires when files are successfully opened. */ + open?(e: OpenEventArgs): void; + + /** Fires when a file or folder is pasted successfully. */ + paste?(e: PasteEventArgs): void; + + /** Fires when file or folder is deleted successfully. */ + remove?(e: RemoveEventArgs): void; + + /** Fires when resizing is performed for FileExplorer. */ + resize?(e: ResizeEventArgs): void; + + /** Fires when resizing is started for FileExplorer. */ + resizeStart?(e: ResizeStartEventArgs): void; + + /** Fires this event when the resizing is stopped for FileExplorer. */ + resizeStop?(e: ResizeStopEventArgs): void; + + /** Fires when the items from grid view or tile view of FileExplorer control is selected. */ + select?(e: SelectEventArgs): void; + + /** Triggered when refresh the template column elements in the grid view of FileExplorer control. */ + templateRefresh?(e: TemplateRefreshEventArgs): void; + + /** Fires when the items from grid view or tile view or large icons view of FileExplorer control is unselected. */ + unselect?(e: UnselectEventArgs): void; } export interface BeforeAjaxRequestEventArgs { @@ -4955,6 +5025,10 @@ export interface BeforeUploadEventArgs { */ selectedItems?: any; + /** returns the upload item details. + */ + uploadItemDetails?: any; + /** returns the name of the event. */ type?: string; @@ -5267,6 +5341,223 @@ export interface LayoutChangeEventArgs { */ isInteraction?: boolean; + /** returns the current view type. + */ + layoutType?: string; + + /** returns the FileExplorer model. + */ + model?: any; + + /** returns the name of the event. + */ + type?: string; +} + +export interface MenuBeforeOpenEventArgs { + + /** set to true when the event has to be canceled, else false. + */ + cancel?: boolean; + + /** returns the name of ContextMenu items group. + */ + contextMenu?: string; + + /** returns the dataSource of ContextMenu. + */ + dataSource?: any[]; + + /** returns the element of ContextMenu. + */ + element?: any; + + /** returns the event of ContextMenu. + */ + events?: any; + + /** returns the FileExplorer model. + */ + model?: ej.FileExplorer.Model; + + /** returns the target element. + */ + target?: any; + + /** returns the name of the event. + */ + type?: string; +} + +export interface MenuClickEventArgs { + + /** returns the ID of clicked ContextMenu item. + */ + ID?: string; + + /** set to true when the event has to be canceled, else false. + */ + cancel?: boolean; + + /** returns the name of ContextMenu items group. + */ + contextMenu?: string; + + /** returns the element of clicked ContextMenu item. + */ + element?: any; + + /** returns the event of ContextMenu. + */ + event?: any; + + /** returns the FileExplorer model. + */ + model?: ej.FileExplorer.Model; + + /** returns the parent element ID of clicked ContextMenu item. + */ + parentId?: string; + + /** returns the parent element text of clicked ContextMenu item. + */ + parentText?: string; + + /** returns the text of clicked ContextMenu item. + */ + text?: string; + + /** returns the name of the event. + */ + type?: string; +} + +export interface MenuOpenEventArgs { + + /** set to true when the event has to be canceled, else false. + */ + cancel?: boolean; + + /** returns the name of ContextMenu items group. + */ + contextMenu?: string; + + /** returns the element of ContextMenu. + */ + element?: any; + + /** returns the FileExplorer model. + */ + model?: ej.FileExplorer.Model; + + /** returns the target element. + */ + target?: any; + + /** returns the name of the event. + */ + type?: string; +} + +export interface OpenEventArgs { + + /** Set to true when the event has to be canceled, else false. + */ + cancel?: boolean; + + /** returns the opened item type. + */ + itemType?: string; + + /** returns the FileExplorer model. + */ + model?: ej.FileExplorer.Model; + + /** returns the path of currently opened item. + */ + path?: string; + + /** returns the selected item details. + */ + selectedItems?: any; + + /** returns the name of the event. + */ + type?: string; +} + +export interface PasteEventArgs { + + /** Set to true when the event has to be canceled, else false. + */ + cancel?: boolean; + + /** returns the FileExplorer model. + */ + model?: ej.FileExplorer.Model; + + /** returns the name of moved/copied file or folder. + */ + name?: string[]; + + /** returns the selected item details. + */ + selectedItems?: any; + + /** returns the target folder item details. + */ + targetFolder?: any; + + /** returns the target path. + */ + targetPath?: string; + + /** returns the name of the event. + */ + type?: string; +} + +export interface RemoveEventArgs { + + /** Set to true when the event has to be canceled, else false. + */ + cancel?: boolean; + + /** returns the AJAX response data. + */ + data?: any; + + /** returns the FileExplorer model. + */ + model?: ej.FileExplorer.Model; + + /** returns the names of deleted items. + */ + name?: string; + + /** returns the path of deleted item. + */ + path?: string; + + /** returns the removed item details. + */ + selectedItems?: any; + + /** returns the name of the event. + */ + type?: string; +} + +export interface ResizeEventArgs { + + /** if the event should be canceled; otherwise, false. + */ + cancel?: boolean; + + /** returns the mouse move event args. + */ + event?: any; + /** returns the FileExplorer model. */ model?: ej.FileExplorer.Model; @@ -5276,17 +5567,149 @@ export interface LayoutChangeEventArgs { type?: string; } +export interface ResizeStartEventArgs { + + /** Set to true when the event has to be canceled, else false. + */ + cancel?: boolean; + + /** returns the mouse down event args. + */ + event?: any; + + /** returns the FileExplorer model. + */ + model?: ej.FileExplorer.Model; + + /** returns the name of the event. + */ + type?: string; +} + +export interface ResizeStopEventArgs { + + /** Set to true when the event has to be canceled, else false. + */ + cancel?: boolean; + + /** returns the mouse leave event args. + */ + event?: any; + + /** returns the FileExplorer model. + */ + model?: ej.FileExplorer.Model; + + /** returns the name of the event. + */ + type?: string; +} + +export interface SelectEventArgs { + + /** Set to true when the event has to be canceled, else false. + */ + cancel?: boolean; + + /** returns the FileExplorer model. + */ + model?: ej.FileExplorer.Model; + + /** returns the name of selected items. + */ + name?: string[]; + + /** returns the path of selected items. + */ + path?: string; + + /** returns the selected item details + */ + selectedItems?: any; + + /** returns the name of the event. + */ + type?: string; +} + +export interface TemplateRefreshEventArgs { + + /** Set to true when the event has to be canceled, else false. + */ + cancel?: boolean; + + /** Returns the cell object. + */ + cell?: ej.FileExplorer.Model; + + /** Returns the column object. + */ + column?: any; + + /** Returns the current row data. + */ + data?: any; + + /** Returns the grid model of FileExplorer. + */ + model?: any; + + /** Returns the current row index. + */ + rowIndex?: number; + + /** returns the name of the event. + */ + type?: string; +} + +export interface UnselectEventArgs { + + /** Returns the FileExplorer model. + */ + model?: ej.FileExplorer.Model; + + /** Returns the name of unselected item. + */ + name?: string; + + /** Returns the name of unselected items. + */ + names?: string[]; + + /** Returns the type of unselected item. + */ + nodeType?: string; + + /** Returns the path of unselected item. + */ + path?: string; + + /** Returns the name of the event. + */ + type?: string; + + /** Returns the unselected item details. + */ + unselectedItem?: any; + + /** Returns the unselected items details. + */ + unselectedItems?: any[]; +} + export interface ContextMenuSettings { /** The items property is used to configure and group the required ContextMenu items in FileExplorer control. - * @Default {{% highlight javascript %}{navbar: [NewFolder, Upload, |, Delete, Rename, |, Cut, Copy, Paste, |, Getinfo],cwd: [Refresh, Paste,|, SortBy, |, NewFolder, Upload, |, Getinfo],files: [Open, Download, |, Upload, |, Delete, Rename, |, Cut, Copy, Paste, |, OpenFolderLocation, Getinfo]}{% endhighlight %}} + * @Default {{% highlight javascript %}{navbar: [NewFolder, Upload, |, Delete, Rename, |, Cut, Copy, Paste, |, Getinfo],cwd: [Refresh, Paste,|, SortBy, |, NewFolder, Upload, |, + * Getinfo],files: [Open, Download, |, Upload, |, Delete, Rename, |, Cut, Copy, Paste, |, OpenFolderLocation, Getinfo]}{% endhighlight %}} */ items?: any; /** The customMenuFields property is used to define custom functionality for custom ContextMenu item's which are defined in items property. * @Default {[]} */ - customMenuFields?: Array; + customMenuFields?: any[]; } export interface FilterSettings { @@ -5320,9 +5743,10 @@ export interface GridSettings { allowSorting?: boolean; /** Gets or sets an object that indicates to render the grid with specified columns. You can use this property same as the column property in Grid control. - * @Default {[{ field: name, headerText: Name, width: 30% }, { field: dateModified, headerText: Date Modified, width: 30% }, { field: type, headerText: Type, width: 15% }, { field: size, headerText: Size, width: 12%, textAlign: right, headerTextAlign: left }]} + * @Default {[{ field: name, headerText: Name, width: 30% }, { field: dateModified, headerText: Date Modified, width: 30% }, { field: type, headerText: Type, width: 15% }, + * { field: size, headerText: Size, width: 12%, textAlign: right, headerTextAlign: left }]} */ - columns?: Array; + columns?: any[]; } export interface UploadSettings { @@ -5343,7 +5767,7 @@ export interface UploadSettings { autoUpload?: boolean; } -enum layoutType{ +enum layoutType { ///Supports to display files in tile view Tile, @@ -5359,11 +5783,10 @@ enum layoutType{ class DatePicker extends ej.Widget { static fn: DatePicker; - constructor(element: JQuery, options?: DatePicker.Model); - constructor(element: Element, options?: DatePicker.Model); + constructor(element: JQuery | Element, options?: DatePicker.Model); static Locale: any; - model:DatePicker.Model; - defaults:DatePicker.Model; + model: DatePicker.Model; + defaults: DatePicker.Model; /** Disables the DatePicker control. * @returns {void} @@ -5390,7 +5813,7 @@ class DatePicker extends ej.Widget { */ show(): void; } -export module DatePicker{ +export namespace DatePicker { export interface Model { @@ -5428,7 +5851,8 @@ export interface Model { */ dayHeaderFormat?: string | ej.DatePicker.Header; - /** Specifies the navigation depth level in DatePicker calendar. This option is not applied when start level view option is lower than depth level view. See below to know available levels in DatePicker Calendar + /** Specifies the navigation depth level in DatePicker calendar. This option is not applied when start level view option is lower than depth level view. + * See below to know available levels in DatePicker Calendar */ depthLevel?: string | ej.DatePicker.Level; @@ -5457,7 +5881,8 @@ export interface Model { */ enableRTL?: boolean; - /** Allows to enter valid or invalid date in input textbox and indicate as error if it is invalid value, when this API value is set to true. For false value, invalid date is not allowed to input field and corrected to valid date automatically, even if invalid date is given. + /** Allows to enter valid or invalid date in input textbox and indicate as error if it is invalid value, when this API value is set to true. For false value, invalid date is not allowed + * to input field and corrected to valid date automatically, even if invalid date is given. * @Default {false} */ enableStrictMode?: boolean; @@ -5593,40 +6018,40 @@ export interface Model { width?: string; /** Fires before closing the DatePicker popup. */ - beforeClose? (e: BeforeCloseEventArgs): void; + beforeClose?(e: BeforeCloseEventArgs): void; /** Fires when each date is created in the DatePicker popup calendar. */ - beforeDateCreate? (e: BeforeDateCreateEventArgs): void; + beforeDateCreate?(e: BeforeDateCreateEventArgs): void; /** Fires before opening the DatePicker popup. */ - beforeOpen? (e: BeforeOpenEventArgs): void; + beforeOpen?(e: BeforeOpenEventArgs): void; /** Fires when the DatePicker input value is changed. */ - change? (e: ChangeEventArgs): void; + change?(e: ChangeEventArgs): void; /** Fires when DatePicker popup is closed. */ - close? (e: CloseEventArgs): void; + close?(e: CloseEventArgs): void; /** Fires when the DatePicker is created successfully. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires when the DatePicker is destroyed successfully. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Fires when DatePicker input gets focus. */ - focusIn? (e: FocusInEventArgs): void; + focusIn?(e: FocusInEventArgs): void; /** Fires when DatePicker input loses the focus. */ - focusOut? (e: FocusOutEventArgs): void; + focusOut?(e: FocusOutEventArgs): void; /** Fires when calender view navigates to month/year/decade/century. */ - navigate? (e: NavigateEventArgs): void; + navigate?(e: NavigateEventArgs): void; /** Fires when DatePicker popup is opened. */ - open? (e: OpenEventArgs): void; + open?(e: OpenEventArgs): void; /** Fires when a date is selected from the DatePicker popup. */ - select? (e: SelectEventArgs): void; + select?(e: SelectEventArgs): void; } export interface BeforeCloseEventArgs { @@ -5932,7 +6357,7 @@ export interface Fields { cssClass?: string; } -enum Header{ +enum Header { ///Removes day header in DatePicker None, @@ -5945,7 +6370,7 @@ enum Header{ } -enum Level{ +enum Level { ///allow navigation upto year level in DatePicker Year, @@ -5958,7 +6383,7 @@ enum Level{ } -enum HighlightSection{ +enum HighlightSection { ///Highlight the week of the currently selected date in DatePicker popup calendar Week, @@ -5974,11 +6399,10 @@ enum HighlightSection{ class DateTimePicker extends ej.Widget { static fn: DateTimePicker; - constructor(element: JQuery, options?: DateTimePicker.Model); - constructor(element: Element, options?: DateTimePicker.Model); + constructor(element: JQuery | Element, options?: DateTimePicker.Model); static Locale: any; - model:DateTimePicker.Model; - defaults:DateTimePicker.Model; + model: DateTimePicker.Model; + defaults: DateTimePicker.Model; /** Disables the DateTimePicker control. * @returns {void} @@ -6010,10 +6434,15 @@ class DateTimePicker extends ej.Widget { */ show(): void; } -export module DateTimePicker{ +export namespace DateTimePicker { export interface Model { + /** Used to allow or restrict the editing in DateTimePicker input field directly. By setting false to this API, You can only pick the date and time values from DateTimePicker popup. + * @Default {true} + */ + allowEdit?: boolean; + /** Displays the custom text for the buttons inside the DateTimePicker popup. when the culture value changed, we can change the buttons text based on the culture. * @Default {{ today: Today, timeNow: Time Now, done: Done, timeTitle: Time }} */ @@ -6033,7 +6462,8 @@ export interface Model { */ dayHeaderFormat?: ej.DatePicker.Header|string; - /** Specifies the navigation depth level in DatePicker calendar inside DateTimePicker popup. This option is not applied when start level view option is lower than depth level view. See ej.DatePicker.Level + /** Specifies the navigation depth level in DatePicker calendar inside DateTimePicker popup. This option is not applied + * when start level view option is lower than depth level view. See ej.DatePicker.Level */ depthLevel?: ej.DatePicker.Level|string; @@ -6102,7 +6532,7 @@ export interface Model { */ popupPosition?: string | ej.popupPosition; - /** Indicates that the DateTimePicker value can only be read and can’t change. + /** Indicates that the DateTimePicker value can only be read and can’t change. * @Default {false} */ readOnly?: boolean; @@ -6177,31 +6607,31 @@ export interface Model { width?: string|number; /** Fires before the datetime popup closed in the DateTimePicker. */ - beforeClose? (e: BeforeCloseEventArgs): void; + beforeClose?(e: BeforeCloseEventArgs): void; /** Fires before the datetime popup open in the DateTimePicker. */ - beforeOpen? (e: BeforeOpenEventArgs): void; + beforeOpen?(e: BeforeOpenEventArgs): void; /** Fires when the datetime value changed in the DateTimePicker textbox. */ - change? (e: ChangeEventArgs): void; + change?(e: ChangeEventArgs): void; /** Fires when DateTimePicker popup closes. */ - close? (e: CloseEventArgs): void; + close?(e: CloseEventArgs): void; /** Fires after DateTimePicker control is created. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires when the DateTimePicker is destroyed successfully */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Fires when the focus-in happens in the DateTimePicker textbox. */ - focusIn? (e: FocusInEventArgs): void; + focusIn?(e: FocusInEventArgs): void; /** Fires when the focus-out happens in the DateTimePicker textbox. */ - focusOut? (e: FocusOutEventArgs): void; + focusOut?(e: FocusOutEventArgs): void; /** Fires when DateTimePicker popup opens. */ - open? (e: OpenEventArgs): void; + open?(e: OpenEventArgs): void; } export interface BeforeCloseEventArgs { @@ -6433,8 +6863,7 @@ export interface TimeDrillDown { autoClose?: boolean; } } -enum popupPosition -{ +enum popupPosition { //Opens the DateTimePicker popup below to the DateTimePicker input box Bottom, //Opens the DateTimePicker popup above to the DateTimePicker input box @@ -6443,18 +6872,17 @@ Top, class DateRangePicker extends ej.Widget { static fn: DateRangePicker; - constructor(element: JQuery, options?: DateRangePicker.Model); - constructor(element: Element, options?: DateRangePicker.Model); + constructor(element: JQuery | Element, options?: DateRangePicker.Model); static Locale: any; - model:DateRangePicker.Model; - defaults:DateRangePicker.Model; + model: DateRangePicker.Model; + defaults: DateRangePicker.Model; /** Add the preset ranges to DateRangePicker popup. * @param {string} Display name * @param {Array} StartDate and endDate of range. * @returns {void} */ - addRanges(label: string, range: Array): void; + addRanges(label: string, range: any[]): void; /** Clears the all ranges selections in DateRangePicker popup * @returns {void} @@ -6491,7 +6919,7 @@ class DateRangePicker extends ej.Widget { */ setRange(): void; } -export module DateRangePicker{ +export namespace DateRangePicker { export interface Model { @@ -6514,7 +6942,7 @@ export interface Model { */ dateFormat?: string; - /** Allows to embed the Timepicker aling with the calendars in the page, two timepicker will be render, for selecting start and end date. + /** Allows to embed the Timepicker align with the calendars in the page, two timepicker will be render, for selecting start and end date. * @Default {false} */ enableTimePicker?: boolean; @@ -6585,28 +7013,28 @@ export interface Model { width?: string|number; /** Fires before closing the DateRangePicker popup. */ - beforeClose? (e: BeforeCloseEventArgs): void; + beforeClose?(e: BeforeCloseEventArgs): void; /** Fires before opening the DateRangePicker popup. */ - beforeOpen? (e: BeforeOpenEventArgs): void; + beforeOpen?(e: BeforeOpenEventArgs): void; /** Fires when the DateRangePicker values get changed. */ - onChange? (e: OnChangeEventArgs): void; + onChange?(e: OnChangeEventArgs): void; /** Fires when DateRangePicker popup is closed. */ - close? (e: CloseEventArgs): void; + close?(e: CloseEventArgs): void; /** Fires when the DateRangePicker is created successfully. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires when the DateRangePicker is destroyed successfully. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Fires when DateRangePicker popup is opened. */ - open? (e: OpenEventArgs): void; + open?(e: OpenEventArgs): void; /** Fires when a date ranges is selected from the DateRangePicker popup. */ - select? (e: SelectEventArgs): void; + select?(e: SelectEventArgs): void; } export interface BeforeCloseEventArgs { @@ -6784,11 +7212,10 @@ export interface SelectEventArgs { class Dialog extends ej.Widget { static fn: Dialog; - constructor(element: JQuery, options?: Dialog.Model); - constructor(element: Element, options?: Dialog.Model); + constructor(element: JQuery | Element, options?: Dialog.Model); static Locale: any; - model:Dialog.Model; - defaults:Dialog.Model; + model: Dialog.Model; + defaults: Dialog.Model; /** Closes the dialog widget dynamically. * @returns {any} @@ -6867,7 +7294,7 @@ class Dialog extends ej.Widget { */ focus(): any; } -export module Dialog{ +export namespace Dialog { export interface Model { @@ -6888,7 +7315,8 @@ export interface Model { */ allowKeyboardNavigation?: boolean; - /** Customizes the Dialog widget animations. The Dialog widget can be animated while opening and closing the dialog. In order to customize animation effects, you need to set “enableAnimation” as true. It contains the following sub properties. + /** Customizes the Dialog widget animations. The Dialog widget can be animated while opening and closing the dialog. + * In order to customize animation effects, you need to set “enableAnimation” as true. It contains the following sub properties. */ animation?: any; @@ -6900,11 +7328,12 @@ export interface Model { */ containment?: string; - /** The content type to load the dialog content at run time. The possible values are null, AJAX, iframe and image. When it is null (default value), the content inside dialog element will be displayed as content and when it is not null, the content will be loaded from the URL specified in the contentUrl property. + /** The content type to load the dialog content at run time. The possible values are null, AJAX, iframe and image. When it is null (default value), + * the content inside dialog element will be displayed as content and when it is not null, the content will be loaded from the URL specified in the contentUrl property. */ contentType?: string; - /** The URL to load the dialog content (such as AJAX, image, and iframe). In order to load content from URL, you need to set contentType as ‘ajax’ or ‘iframe’ or ‘image’. + /** The URL to load the dialog content (such as AJAX, image, and iframe). In order to load content from URL, you need to set contentType as ‘ajax’ or ‘iframe’ or ‘image’. */ contentUrl?: string; @@ -6936,11 +7365,12 @@ export interface Model { */ enableRTL?: boolean; - /** The CSS class name to display the favicon in the dialog header. In order to display favicon, you need to set showHeader as true since the favicon will be displayed in the dialog header. + /** The CSS class name to display the favicon in the dialog header. In order to display favicon, you need to set� showHeader� as true since the favicon will be displayed in the dialog header. */ faviconCSS?: string; - /** Sets the height for the dialog widget. It accepts both string and integer values. For example, it can accepts values like “auto”, “100%”, “100px” as string type and “100”, “500” as integer type. + /** Sets the height for the dialog widget. It accepts both string and integer values. For example, it can accepts values like “auto”, “100%”, “100px” as string type + * and “100”, “500” as integer type. */ height?: string|number; @@ -6953,7 +7383,7 @@ export interface Model { */ isResponsive?: boolean; - /** Default Value:{:.param}“en-US” + /** Default Value:{:.param}“en-US” */ locale?: number; @@ -7001,7 +7431,8 @@ export interface Model { */ tooltip?: any; - /** Sets the height for the dialog widget. It accepts both string and integer values. For example, it can accepts values like “auto”, “100%”, “100px” as string type and “100”, “500” as integer type. + /** Sets the height for the dialog widget. It accepts both string and integer values. For example, it can accepts values like “auto”, “100%”, + * “100px” as string type and “100”, “500” as integer type. */ width?: string|number; @@ -7018,58 +7449,58 @@ export interface Model { footerTemplateId?: string; /** This event is triggered before the dialog widgets gets open. */ - beforeOpen? (e: BeforeOpenEventArgs): void; + beforeOpen?(e: BeforeOpenEventArgs): void; /** This event is triggered whenever the AJAX request fails to retrieve the dialog content. */ - ajaxError? (e: AjaxErrorEventArgs): void; + ajaxError?(e: AjaxErrorEventArgs): void; /** This event is triggered whenever the AJAX request to retrieve the dialog content, gets succeed. */ - ajaxSuccess? (e: AjaxSuccessEventArgs): void; + ajaxSuccess?(e: AjaxSuccessEventArgs): void; /** This event is triggered before the dialog widgets get closed. */ - beforeClose? (e: BeforeCloseEventArgs): void; + beforeClose?(e: BeforeCloseEventArgs): void; /** This event is triggered after the dialog widget is closed. */ - close? (e: CloseEventArgs): void; + close?(e: CloseEventArgs): void; /** Triggered after the dialog content is loaded in DOM. */ - contentLoad? (e: ContentLoadEventArgs): void; + contentLoad?(e: ContentLoadEventArgs): void; /** Triggered after the dialog is created successfully */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Triggered after the dialog widget is destroyed successfully */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Triggered while the dialog is dragged. */ - drag? (e: DragEventArgs): void; + drag?(e: DragEventArgs): void; /** Triggered when the user starts dragging the dialog. */ - dragStart? (e: DragStartEventArgs): void; + dragStart?(e: DragStartEventArgs): void; /** Triggered when the user stops dragging the dialog. */ - dragStop? (e: DragStopEventArgs): void; + dragStop?(e: DragStopEventArgs): void; /** Triggered after the dialog is opened. */ - open? (e: OpenEventArgs): void; + open?(e: OpenEventArgs): void; /** Triggered while the dialog is resized. */ - resize? (e: ResizeEventArgs): void; + resize?(e: ResizeEventArgs): void; /** Triggered when the user starts resizing the dialog. */ - resizeStart? (e: ResizeStartEventArgs): void; + resizeStart?(e: ResizeStartEventArgs): void; /** Triggered when the user stops resizing the dialog. */ - resizeStop? (e: ResizeStopEventArgs): void; + resizeStop?(e: ResizeStopEventArgs): void; /** Triggered when the dialog content is expanded. */ - expand? (e: ExpandEventArgs): void; + expand?(e: ExpandEventArgs): void; /** Triggered when the dialog content is collapsed. */ - collapse? (e: CollapseEventArgs): void; + collapse?(e: CollapseEventArgs): void; /** Triggered when the custom action button clicked. */ - actionButtonClick? (e: ActionButtonClickEventArgs): void; + actionButtonClick?(e: ActionButtonClickEventArgs): void; } export interface BeforeOpenEventArgs { @@ -7442,163 +7873,18 @@ export interface AjaxSettings { } } -class DocumentEditor extends ej.Widget { - static fn: DocumentEditor; - constructor(element: JQuery, options?: DocumentEditor.Model); - constructor(element: Element, options?: DocumentEditor.Model); - static Locale: any; - model:DocumentEditor.Model; - defaults:DocumentEditor.Model; - - /** Loads the document from specified path using web API provided by importUrl. - * @param {string} Specifies the file path. - * @returns {void} - */ - load(path: string): void; - - /** Gets the page number of current selection in the document. - * @returns {number} - */ - getCurrentPageNumber(): number; - - /** Gets the total number of pages in the document. - * @returns {number} - */ - getPageCount(): number; - - /** Gets the text of current selection in the document. - * @returns {string} - */ - getSelectedText(): string; - - /** Gets the current zoom factor value of the document editor. - * @returns {number} - */ - getZoomFactor(): number; - - /** Scales the document editor with the specified zoom factor. The range of zoom factor should be 0.10 to 5.00 (10 - 500 %). - * @param {number} Specifies the factor for zooming. - * @returns {void} - */ - setZoomFactor(factor: number): void; - - /** Prints the document content as page by page. - * @returns {void} - */ - print(): void; - - /** Finds the first occurrence of specified text from current selection and highlights the result. If the document end is reached, find operation will occur from the document start position. - * @param {string} Specifies the text to search in a document. - * @returns {void} - */ - find(text: string): void; -} -export module DocumentEditor{ - -export interface Model { - - /** Gets or sets an object that indicates initialization of importing and exporting documents in document editor. - */ - importExportSettings?: ImportExportSettings; - - /** Triggers when the document changes. */ - onDocumentChange? (e: OnDocumentChangeEventArgs): void; - - /** Triggers when the selection changes. */ - onSelectionChange? (e: OnSelectionChangeEventArgs): void; - - /** Triggers when the zoom factor changes. */ - onZoomFactorChange? (e: OnZoomFactorChangeEventArgs): void; - - /** Triggers when the hyperlink is clicked. */ - onRequestNavigate? (e: OnRequestNavigateEventArgs): void; -} - -export interface OnDocumentChangeEventArgs { - - /** True, if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** Returns the document editor model. - */ - model?: any; - - /** Returns the name of the event. - */ - type?: string; -} - -export interface OnSelectionChangeEventArgs { - - /** True, if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** Returns the document editor model. - */ - model?: any; - - /** Returns the name of the event. - */ - type?: string; -} - -export interface OnZoomFactorChangeEventArgs { - - /** True, if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** Returns the document editor model. - */ - model?: any; - - /** Returns the name of the event. - */ - type?: string; -} - -export interface OnRequestNavigateEventArgs { - - /** true, if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** Returns the document editor model. - */ - model?: any; - - /** Returns the link type and navigation link. - */ - hyperlink?: any; - - /** Returns the name of the event. - */ - type?: string; -} - -export interface ImportExportSettings { - - /** Gets or sets URL of Web API that should be used to parse the document while loading. - */ - importUrl?: string; -} -} - class DropDownList extends ej.Widget { static fn: DropDownList; - constructor(element: JQuery, options?: DropDownList.Model); - constructor(element: Element, options?: DropDownList.Model); + constructor(element: JQuery | Element, options?: DropDownList.Model); static Locale: any; - model:DropDownList.Model; - defaults:DropDownList.Model; + model: DropDownList.Model; + defaults: DropDownList.Model; /** Adding a single item or an array of items into the DropDownList allows you to specify all the field attributes such as value, template, image URL, and HTML attributes for those items. * @param {any|Array} this parameter should have field attributes with respect to mapped field attributes and it's corresponding values to fields * @returns {void} */ - addItem(data: any|Array): void; + addItem(data: any|any[]): void; /** This method is used to select all the items in the DropDownList. * @returns {void} @@ -7624,7 +7910,7 @@ class DropDownList extends ej.Widget { * @param {string|number|Array} disable the given index list items * @returns {void} */ - disableItemsByIndices(index: string|number|Array): void; + disableItemsByIndices(index: string|number|any[]): void; /** This property enables the DropDownList control. * @returns {void} @@ -7635,13 +7921,13 @@ class DropDownList extends ej.Widget { * @param {string|number|Array} enable the given index list items if it's disabled * @returns {void} */ - enableItemsByIndices(index: string|number|Array): void; + enableItemsByIndices(index: string|number|any[]): void; /** This method retrieves the items using given value. * @param {string|number|any} Return the whole object of data based on given value * @returns {Array} */ - getItemDataByValue(value: string|number|any): Array; + getItemDataByValue(value: string|number|any): any[]; /** This method is used to retrieve the items that are bound with the DropDownList. * @returns {any} @@ -7651,7 +7937,7 @@ class DropDownList extends ej.Widget { /** This method is used to get the selected items in the DropDownList. * @returns {Array} */ - getSelectedItem(): Array; + getSelectedItem(): any[]; /** This method is used to retrieve the items value that are selected in the DropDownList. * @returns {string} @@ -7667,19 +7953,19 @@ class DropDownList extends ej.Widget { * @param {string|number|Array} select the given index list items * @returns {void} */ - selectItemsByIndices(index: string|number|Array): void; + selectItemsByIndices(index: string|number|any[]): void; /** This method is used to select an item in the DropDownList by using the given text value. * @param {string|number|Array} select the list items relates to given text * @returns {void} */ - selectItemByText(index: string|number|Array): void; + selectItemByText(index: string|number|any[]): void; /** This method is used to select an item in the DropDownList by using the given value. * @param {string|number|Array} select the list items relates to given values * @returns {void} */ - selectItemByValue(index: string|number|Array): void; + selectItemByValue(index: string|number|any[]): void; /** This method shows the DropDownList control with the suggestion popup. * @returns {void} @@ -7695,30 +7981,31 @@ class DropDownList extends ej.Widget { * @param {string|number|Array} unselect the given index list items * @returns {void} */ - unselectItemsByIndices(index: string|number|Array): void; + unselectItemsByIndices(index: string|number|any[]): void; /** This method is used to unselect an item in the DropDownList by using the given text value. * @param {string|number|Array} unselect the list items relates to given text * @returns {void} */ - unselectItemByText(index: string|number|Array): void; + unselectItemByText(index: string|number|any[]): void; /** This method is used to unselect an item in the DropDownList by using the given value. * @param {string|number|Array} unselect the list items relates to given values * @returns {void} */ - unselectItemByValue(index: string|number|Array): void; + unselectItemByValue(index: string|number|any[]): void; } -export module DropDownList{ +export namespace DropDownList { export interface Model { - /** The Virtual Scrolling(lazy loading) feature is used to display a large amount of data that you require without buffering the entire load of a huge database records in the DropDownList, that is, when scrolling, an AJAX request is sent to fetch some amount of data from the server dynamically. To achieve this scenario with DropDownList, set the allowVirtualScrolling to true. + /** The Virtual Scrolling(lazy loading) feature is used to display a large amount of data that you require without buffering the entire load of a huge database records in the DropDownList, + * that is, when scrolling, an AJAX request is sent to fetch some amount of data from the server dynamically. To achieve this scenario with DropDownList, set the allowVirtualScrolling to true. * @Default {false} */ allowVirtualScrolling?: boolean; - /** The cascading DropDownLists is a series of two or more DropDownLists in which each DropDownList is filtered according to the previous DropDownList’s value. + /** The cascading DropDownLists is a series of two or more DropDownLists in which each DropDownList is filtered according to the previous DropDownList’s value. * @Default {null} */ cascadeTo?: string; @@ -7728,16 +8015,19 @@ export interface Model { */ caseSensitiveSearch?: boolean; - /** Dropdown widget's style and appearance can be controlled based on 13 different default built-in themes.You can customize the appearance of the dropdown by using the cssClass property. You need to specify a class name in the cssClass property and the same class name is used before the class definitions wherever the custom styles are applied. + /** Dropdown widget's style and appearance can be controlled based on 13 different default built-in themes.You can customize the appearance of the dropdown by using the cssClass property. + * You need to specify a class name in the cssClass property and the same class name is used before the class definitions wherever the custom styles are applied. */ cssClass?: string; - /** This property is used to serve data from the data services based on the query provided. To bind the data to the dropdown widget, the dataSource property is assigned with the instance of the ej.DataManager. + /** This property is used to serve data from the data services based on the query provided. To bind the data to the dropdown widget, + * the dataSource property is assigned with the instance of the ej.DataManager. * @Default {null} */ dataSource?: any; - /** Sets the separator when the multiSelectMode with delimiter option or checkbox is enabled with the dropdown. When you enter the delimiter value, the texts after the delimiter are considered as a separate word or query. The delimiter string is a single character and must be a symbol. Mostly, the delimiter symbol is used as comma (,) or semi-colon (;) or any other special character. + /** Sets the separator when the multiSelectMode with delimiter option or checkbox is enabled with the dropdown. When you enter the delimiter value,the texts after the delimiter are considered + * as a separate word or query. The delimiter string is a single character and must be a symbol. Mostly, the delimiter symbol is used as comma (,) or semi-colon (;) or any other special character. * @Default {','} */ delimiterChar?: string; @@ -7747,7 +8037,8 @@ export interface Model { */ enableAnimation?: boolean; - /** This property is used to indicate whether the DropDownList control responds to the user interaction or not. By default, the control is in the enabled mode and you can disable it by setting it to false. + /** This property is used to indicate whether the DropDownList control responds to the user interaction or not. By default, the control is in the enabled mode + * and you can disable it by setting it to false. * @Default {true} */ enabled?: boolean; @@ -7762,7 +8053,8 @@ export interface Model { */ enableFilterSearch?: boolean; - /** Saves the current model value to the browser cookies for state maintenance. While refreshing the DropDownList control page, it retains the model value and it is applied from the browser cookies. + /** Saves the current model value to the browser cookies for state maintenance. While refreshing the DropDownList control page, it retains the model value and + * it is applied from the browser cookies. * @Default {false} */ enablePersistence?: boolean; @@ -7837,7 +8129,9 @@ export interface Model { */ minPopupWidth?: string|number; - /** With the help of this property, you can make a single or multi selection with the DropDownList and display the text in two modes, delimiter and visual mode. In delimiter mode, you can separate the items by using the delimiter character such as comma (,) or semi-colon (;) or any other special character. In the visual mode, the items are showcased like boxes with close icon in the textbox. + /** With the help of this property, you can make a single or multi selection with the DropDownList and display the text in two modes, delimiter and visual mode. + * In delimiter mode, you can separate the items by using the delimiter character such as comma (,) or semi-colon (;) or any other special character. + * In the visual mode, the items are showcased like boxes with close icon in the textbox. * @Default {ej.MultiSelectMode.None} */ multiSelectMode?: ej.MultiSelectMode|string; @@ -7870,7 +8164,7 @@ export interface Model { /** Specifies the selectedItems for the DropDownList. * @Default {[]} */ - selectedIndices?: Array; + selectedIndices?: any[]; /** Selects multiple items in the DropDownList with the help of the checkbox control. To achieve this, enable the showCheckbox option to true. * @Default {false} @@ -7892,7 +8186,7 @@ export interface Model { */ sortOrder?: ej.SortOrder|string; - /** Specifies the targetID for the DropDownList’s items. + /** Specifies the targetID for the DropDownList’s items. * @Default {null} */ targetID?: string; @@ -7932,73 +8226,75 @@ export interface Model { */ width?: string|number; - /** The Virtual Scrolling feature is used to display a large amount of records in the DropDownList, that is, when scrolling, an AJAX request is sent to fetch some amount of data from the server dynamically. To achieve this scenario with DropDownList, set the allowVirtualScrolling to true. You can set the itemsCount property that represents the number of items to be fetched from the server on every AJAX request. + /** The Virtual Scrolling feature is used to display a large amount of records in the DropDownList, that is, when scrolling, an AJAX request is sent to fetch some amount of data from + * the server dynamically. To achieve this scenario with DropDownList, set the allowVirtualScrolling to true. + * You can set the itemsCount property that represents the number of items to be fetched from the server on every AJAX request. * @Default {normal} */ virtualScrollMode?: ej.VirtualScrollMode|string; /** Fires the action before the XHR request. */ - actionBegin? (e: ActionBeginEventArgs): void; + actionBegin?(e: ActionBeginEventArgs): void; /** Fires the action when the list of items is bound to the DropDownList by xhr post calling */ - actionComplete? (e: ActionCompleteEventArgs): void; + actionComplete?(e: ActionCompleteEventArgs): void; /** Fires the action when the xhr post calling failed on remote data binding with the DropDownList control. */ - actionFailure? (e: ActionFailureEventArgs): void; + actionFailure?(e: ActionFailureEventArgs): void; /** Fires the action when the xhr post calling succeed on remote data binding with the DropDownList control */ - actionSuccess? (e: ActionSuccessEventArgs): void; + actionSuccess?(e: ActionSuccessEventArgs): void; /** Fires the action before the popup is ready to hide. */ - beforePopupHide? (e: BeforePopupHideEventArgs): void; + beforePopupHide?(e: BeforePopupHideEventArgs): void; /** Fires the action before the popup is ready to be displayed. */ - beforePopupShown? (e: BeforePopupShownEventArgs): void; + beforePopupShown?(e: BeforePopupShownEventArgs): void; /** Fires when the cascading happens between two DropDownList exactly after the value changes in the first dropdown and before filtering in the second Dropdown. */ - cascade? (e: CascadeEventArgs): void; + cascade?(e: CascadeEventArgs): void; - /** Fires the action when the DropDownList control’s value is changed. */ - change? (e: ChangeEventArgs): void; + /** Fires the action when the DropDownList control’s value is changed. */ + change?(e: ChangeEventArgs): void; /** Fires the action when the list item checkbox value is changed. */ - checkChange? (e: CheckChangeEventArgs): void; + checkChange?(e: CheckChangeEventArgs): void; /** Fires the action once the DropDownList is created. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires the action when the list items is bound to the DropDownList. */ - dataBound? (e: DataBoundEventArgs): void; + dataBound?(e: DataBoundEventArgs): void; /** Fires the action when the DropDownList is destroyed. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Fires the action when the DropDownList is focused. */ - focusIn? (e: FocusInEventArgs): void; + focusIn?(e: FocusInEventArgs): void; /** Fires the action when the DropDownList is about to lose focus. */ - focusOut? (e: FocusOutEventArgs): void; + focusOut?(e: FocusOutEventArgs): void; /** Fires the action, once the popup is closed */ - popupHide? (e: PopupHideEventArgs): void; + popupHide?(e: PopupHideEventArgs): void; /** Fires the action, when the popup is resized. */ - popupResize? (e: PopupResizeEventArgs): void; + popupResize?(e: PopupResizeEventArgs): void; /** Fires the action, once the popup is opened. */ - popupShown? (e: PopupShownEventArgs): void; + popupShown?(e: PopupShownEventArgs): void; /** Fires the action, when resizing a popup starts. */ - popupResizeStart? (e: PopupResizeStartEventArgs): void; + popupResizeStart?(e: PopupResizeStartEventArgs): void; /** Fires the action, when the popup resizing is stopped. */ - popupResizeStop? (e: PopupResizeStopEventArgs): void; + popupResizeStop?(e: PopupResizeStopEventArgs): void; /** Fires the action before filtering the list items that starts in the DropDownList when the enableFilterSearch is enabled. */ - search? (e: SearchEventArgs): void; + search?(e: SearchEventArgs): void; /** Fires the action, when the list of item is selected. */ - select? (e: SelectEventArgs): void; + select?(e: SelectEventArgs): void; } export interface ActionBeginEventArgs { @@ -8044,7 +8340,7 @@ export interface ActionCompleteEventArgs { /** Returns the number of items fetched from remote data */ - result?: Array; + result?: any[]; /** Returns the requested data */ @@ -8102,7 +8398,7 @@ export interface ActionSuccessEventArgs { /** Returns the number of items fetched from remote data */ - result?: Array; + result?: any[]; /** Returns the requested data */ @@ -8539,15 +8835,13 @@ export interface Fields { value?: string; } } -enum FilterType -{ +enum FilterType { //filter the data wherever contains search key Contains, //filter the data based on search key present at start position StartsWith, } -enum MultiSelectMode -{ +enum MultiSelectMode { // can select only single item in DropDownList None, //can select multiple items and it's separated by delimiterChar @@ -8555,8 +8849,7 @@ Delimiter, // can select multiple items and it's show's like visual box in textbox VisualMode, } -enum VirtualScrollMode -{ +enum VirtualScrollMode { // The data is loaded only to the corresponding page (display items). When scrolling some other position, it enables the load on demand with the DropDownList. Normal, //The data items are loaded from the remote when scroll handle reaches the end of the scrollbar like infinity scrolling. @@ -8565,11 +8858,10 @@ Continuous, class Tooltip extends ej.Widget { static fn: Tooltip; - constructor(element: JQuery, options?: Tooltip.Model); - constructor(element: Element, options?: Tooltip.Model); + constructor(element: JQuery | Element, options?: Tooltip.Model); static Locale: any; - model:Tooltip.Model; - defaults:Tooltip.Model; + model: Tooltip.Model; + defaults: Tooltip.Model; /** Destroys the Tooltip control. * @returns {void} @@ -8591,7 +8883,7 @@ class Tooltip extends ej.Widget { * @param {Function} optional custom effect takes place when hiding the tooltip. * @returns {void} */ - hide(effect?: string, func?: Function): void; + hide(effect?: string, func?: any): void; /** Shows the Tooltip popup for the given target element with the specified effect. * @param {string} optional Determines the type of effect that takes place when showing the tooltip. @@ -8599,9 +8891,9 @@ class Tooltip extends ej.Widget { * @param {JQuery} optional Tooltip will be shown for the given element * @returns {void} */ - show(effect?: string, func?: Function, target?: JQuery): void; + show(effect?: string, func?: any, target?: JQuery): void; } -export module Tooltip{ +export namespace Tooltip { export interface Model { @@ -8704,31 +8996,31 @@ export interface Model { width?: string|number; /** This event is triggered before the Tooltip widget get closed. */ - beforeClose? (e: BeforeCloseEventArgs): void; + beforeClose?(e: BeforeCloseEventArgs): void; /** This event is triggered before the Tooltip widget gets open. */ - beforeOpen? (e: BeforeOpenEventArgs): void; + beforeOpen?(e: BeforeOpenEventArgs): void; /** Fires on clicking to the target element. */ - click? (e: ClickEventArgs): void; + click?(e: ClickEventArgs): void; /** This event is triggered after the Tooltip widget is closed. */ - close? (e: CloseEventArgs): void; + close?(e: CloseEventArgs): void; /** This event is triggered after the Tooltip is created successfully. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** This event is triggered after the Tooltip widget is destroyed successfully. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** This event is triggered while hovering the target element, when tooltip positioning relates to target element. */ - hover? (e: HoverEventArgs): void; + hover?(e: HoverEventArgs): void; /** This event is triggered after the Tooltip is opened. */ - open? (e: OpenEventArgs): void; + open?(e: OpenEventArgs): void; /** This event is triggered while hover the target element, when the tooltip positioning is relates to the mouse. */ - tracking? (e: TrackingEventArgs): void; + tracking?(e: TrackingEventArgs): void; } export interface BeforeCloseEventArgs { @@ -8944,7 +9236,7 @@ export interface Position { stem?: PositionStem; } -enum effect{ +enum effect { ///No animation takes place when showing/hiding the Tooltip None, @@ -8957,7 +9249,7 @@ enum effect{ } -enum Associate{ +enum Associate { ///Sets the position related to target element. Target, @@ -8976,7 +9268,7 @@ enum Associate{ } -enum CloseMode{ +enum CloseMode { ///Enables close button in Tooltip. Sticky, @@ -8989,7 +9281,7 @@ enum CloseMode{ } -enum Collision{ +enum Collision { ///Flips the Tooltip to the opposite side of the target, if collision is occurs. Flip, @@ -9005,7 +9297,7 @@ enum Collision{ } -enum Trigger{ +enum Trigger { ///The Tooltip to be shown when the target element is clicked. Click, @@ -9021,11 +9313,10 @@ enum Trigger{ class Editor extends ej.Widget { static fn: Editor; - constructor(element: JQuery, options?: Editor.Model); - constructor(element: Element, options?: Editor.Model); + constructor(element: JQuery | Element, options?: Editor.Model); static Locale: any; - model:Editor.Model; - defaults:Editor.Model; + model: Editor.Model; + defaults: Editor.Model; /** destroy the editor widgets all events are unbind automatically and bring the control to pre-init state. * @returns {void} @@ -9048,18 +9339,23 @@ class Editor extends ej.Widget { getValue(): number; } - class NumericTextbox extends Editor{ + class NumericTextbox extends Editor { } - class CurrencyTextbox extends Editor{ + class CurrencyTextbox extends Editor { } - class PercentageTextbox extends Editor{ + class PercentageTextbox extends Editor { } -export module Editor{ +export namespace Editor { export interface Model { + /** Specifies the currency symbol of currency textbox, used when the user wants to overwrite the currency symbol commonly instead of the current culture symbol. + * @Default {Based on the culture} + */ + currencySymbol?: string; + /** Sets the root CSS class for Editors which allow us to customize the appearance. */ cssClass?: string; @@ -9134,12 +9430,14 @@ export interface Model { */ name?: string; - /** Specifies the pattern for formatting positive values in editor.We have maintained some standard to define the negative pattern. you have to specify 'n' to place the digit in your pattern.ejTextbox allows you to define a currency or percent symbol where you want to place it. + /** Specifies the pattern for formatting positive values in editor.We have maintained some standard to define the negative pattern. + * you have to specify 'n' to place the digit in your pattern.ejTextbox allows you to define a currency or percent symbol where you want to place it. * @Default {Based on the culture} */ negativePattern?: string; - /** Specifies the pattern for formatting positive values in editor.We have maintained some standard to define the positive pattern. you have to specify 'n' to place the digit in your pattern.ejTextbox allows you to define a currency or percent symbol where you want to place it. + /** Specifies the pattern for formatting positive values in editor.We have maintained some standard to define the positive pattern. + * you have to specify 'n' to place the digit in your pattern.ejTextbox allows you to define a currency or percent symbol where you want to place it. * @Default {Based on the culture} */ positivePattern?: string; @@ -9190,19 +9488,19 @@ export interface Model { width?: string; /** Fires after Editor control value is changed. */ - change? (e: ChangeEventArgs): void; + change?(e: ChangeEventArgs): void; /** Fires after Editor control is created. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires when the Editor is destroyed successfully. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Fires after Editor control is focused. */ - focusIn? (e: FocusInEventArgs): void; + focusIn?(e: FocusInEventArgs): void; /** Fires after Editor control is loss the focus. */ - focusOut? (e: FocusOutEventArgs): void; + focusOut?(e: FocusOutEventArgs): void; } export interface ChangeEventArgs { @@ -9299,11 +9597,10 @@ export interface FocusOutEventArgs { class ListView extends ej.Widget { static fn: ListView; - constructor(element: JQuery, options?: ListView.Model); - constructor(element: Element, options?: ListView.Model); + constructor(element: JQuery | Element, options?: ListView.Model); static Locale: any; - model:ListView.Model; - defaults:ListView.Model; + model: ListView.Model; + defaults: ListView.Model; /** To add item in the given index. If you have enabled grouping in ListView then you need to pass the corresponding group list title to add item in it. * @param {any} Specifies the item to be added in ListView @@ -9360,12 +9657,12 @@ class ListView extends ej.Widget { /** To get all the checked items. * @returns {Array} */ - getCheckedItems(): Array; + getCheckedItems(): any[]; /** To get the text of all the checked items. * @returns {Array} */ - getCheckedItemsText(): Array; + getCheckedItemsText(): any[]; /** To get the total item count. * @returns {number} @@ -9452,7 +9749,7 @@ class ListView extends ej.Widget { */ unCheckItem(index: number): void; } -export module ListView{ +export namespace ListView { export interface Model { @@ -9461,19 +9758,20 @@ export interface Model { */ ajaxSettings?: AjaxSettings; - /** Set the index values to be selected on intial loading. This works only when enableCheckMark is set true. + /** Set the index values to be selected on initial loading. This works only when enableCheckMark is set true. * @Default {[]} */ - checkedIndices?: Array; + checkedIndices?: any[]; - /** Sets the root class for ListView theme. This cssClass API helps to use custom skinning option for ListView control. By defining the root class using this API, we need to include this root class in CSS. + /** Sets the root class for ListView theme. This cssClass API helps to use custom skinning option for ListView control. By defining the root class using this API, + * we need to include this root class in CSS. */ cssClass?: string; /** Contains the list of data for generating the ListView items. * @Default {[]} */ - dataSource?: Array; + dataSource?: any[]; /** Specifies whether to load AJAX content while selecting item. * @Default {false} @@ -9512,7 +9810,7 @@ export interface Model { /** Contains the array of items to be added in ListView. * @Default {[]} */ - items?: Array; + items?: any[]; /** Specifies the text of the back button in the header. * @Default {null} @@ -9579,28 +9877,28 @@ export interface Model { width?: string|number; /** Event triggers before the AJAX request happens. */ - ajaxBeforeLoad? (e: AjaxBeforeLoadEventArgs): void; + ajaxBeforeLoad?(e: AjaxBeforeLoadEventArgs): void; /** Event triggers after the AJAX content loaded completely. */ - ajaxComplete? (e: AjaxCompleteEventArgs): void; + ajaxComplete?(e: AjaxCompleteEventArgs): void; /** Event triggers when the AJAX request failed. */ - ajaxError? (e: AjaxErrorEventArgs): void; + ajaxError?(e: AjaxErrorEventArgs): void; /** Event triggers after the AJAX content loaded successfully. */ - ajaxSuccess? (e: AjaxSuccessEventArgs): void; + ajaxSuccess?(e: AjaxSuccessEventArgs): void; /** Event triggers before the items loaded. */ - load? (e: LoadEventArgs): void; + load?(e: LoadEventArgs): void; /** Event triggers after the items loaded. */ - loadComplete? (e: LoadCompleteEventArgs): void; + loadComplete?(e: LoadCompleteEventArgs): void; /** Event triggers when mouse down happens on the item. */ - mouseDown? (e: MouseDownEventArgs): void; + mouseDown?(e: MouseDownEventArgs): void; /** Event triggers when mouse up happens on the item. */ - mouseUp? (e: MouseUpEventArgs): void; + mouseUp?(e: MouseUpEventArgs): void; } export interface AjaxBeforeLoadEventArgs { @@ -9853,11 +10151,10 @@ export interface AjaxSettings { class MaskEdit extends ej.Widget { static fn: MaskEdit; - constructor(element: JQuery, options?: MaskEdit.Model); - constructor(element: Element, options?: MaskEdit.Model); + constructor(element: JQuery | Element, options?: MaskEdit.Model); static Locale: any; - model:MaskEdit.Model; - defaults:MaskEdit.Model; + model: MaskEdit.Model; + defaults: MaskEdit.Model; /** To clear the text in mask edit textbox control. * @returns {void} @@ -9884,7 +10181,7 @@ class MaskEdit extends ej.Widget { */ get_UnstrippedValue(): string; } -export module MaskEdit{ +export namespace MaskEdit { export interface Model { @@ -9988,34 +10285,34 @@ export interface Model { width?: string; /** Fires when value changed in mask edit textbox control. */ - change? (e: ChangeEventArgs): void; + change?(e: ChangeEventArgs): void; /** Fires after MaskEdit control is created. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires when the MaskEdit is destroyed successfully. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Fires when focused in mask edit textbox control. */ - focusIn? (e: FocusInEventArgs): void; + focusIn?(e: FocusInEventArgs): void; /** Fires when focused out in mask edit textbox control. */ - focusOut? (e: FocusOutEventArgs): void; + focusOut?(e: FocusOutEventArgs): void; /** Fires when keydown in mask edit textbox control. */ - keydown? (e: KeydownEventArgs): void; + keydown?(e: KeydownEventArgs): void; /** Fires when key press in mask edit textbox control. */ - keyPress? (e: KeyPressEventArgs): void; + keyPress?(e: KeyPressEventArgs): void; /** Fires when keyup in mask edit textbox control. */ - keyup? (e: KeyupEventArgs): void; + keyup?(e: KeyupEventArgs): void; /** Fires when mouse out in mask edit textbox control. */ - mouseOut? (e: MouseOutEventArgs): void; + mouseOut?(e: MouseOutEventArgs): void; /** Fires when mouse over in mask edit textbox control. */ - mouseOver? (e: MouseOverEventArgs): void; + mouseOver?(e: MouseOverEventArgs): void; } export interface ChangeEventArgs { @@ -10232,15 +10529,13 @@ export interface MouseOverEventArgs { unmaskedValue?: string; } } -enum InputMode -{ +enum InputMode { //string Password, //string Text, } -enum TextAlign -{ +enum TextAlign { //string Center, //string @@ -10253,11 +10548,10 @@ Right, class Menu extends ej.Widget { static fn: Menu; - constructor(element: JQuery, options?: Menu.Model); - constructor(element: Element, options?: Menu.Model); + constructor(element: JQuery | Element, options?: Menu.Model); static Locale: any; - model:Menu.Model; - defaults:Menu.Model; + model: Menu.Model; + defaults: Menu.Model; /** Disables the Menu control. * @returns {void} @@ -10328,7 +10622,7 @@ class Menu extends ej.Widget { * @param {any|Array} Selector of target node or Object of target node. * @returns {void} */ - remove(target: any|Array): void; + remove(target: any|any[]): void; /** To show the Menu control. * @param {number} x co-ordinate position of context menu. @@ -10344,7 +10638,7 @@ class Menu extends ej.Widget { */ showItems(): void; } -export module Menu{ +export namespace Menu { export interface Model { @@ -10452,32 +10746,48 @@ export interface Model { */ width?: string|number; + /** Specifies the popup menu height. + * @Default {auto} + */ + overflowHeight?: string|number; + + /** Specifies the popup menu width. + * @Default {auto} + */ + overflowWidth?: string|number; + /** Fires before context menu gets open. */ - beforeOpen? (e: BeforeOpenEventArgs): void; + beforeOpen?(e: BeforeOpenEventArgs): void; /** Fires when mouse click on menu items. */ - click? (e: ClickEventArgs): void; + click?(e: ClickEventArgs): void; /** Fire when context menu on close. */ - close? (e: CloseEventArgs): void; + close?(e: CloseEventArgs): void; /** Fires when context menu on open. */ - open? (e: OpenEventArgs): void; + open?(e: OpenEventArgs): void; /** Fires to create menu items. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires to destroy menu items. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Fires when key down on menu items. */ - keydown? (e: KeydownEventArgs): void; + keydown?(e: KeydownEventArgs): void; /** Fires when mouse out from menu items. */ - mouseout? (e: MouseoutEventArgs): void; + mouseout?(e: MouseoutEventArgs): void; /** Fires when mouse over the Menu items. */ - mouseover? (e: MouseoverEventArgs): void; + mouseover?(e: MouseoverEventArgs): void; + + /** Fires when overflow popup menu opens. */ + overflowOpen?(e: OverflowOpenEventArgs): void; + + /** Fires when overflow popup menu closes. */ + overflowClose?(e: OverflowCloseEventArgs): void; } export interface BeforeOpenEventArgs { @@ -10647,6 +10957,44 @@ export interface MouseoverEventArgs { event?: any; } +export interface OverflowOpenEventArgs { + + /** returns the menu model + */ + model?: ej.Menu.Model; + + /** returns the name of the event + */ + type?: string; + + /** returns the event object + */ + e?: any; + + /** if the event should be cancelled ; otherwise ,false + */ + cancel?: boolean; +} + +export interface OverflowCloseEventArgs { + + /** returns the menu model + */ + model?: ej.Menu.Model; + + /** returns the name of the event + */ + type?: string; + + /** returns the event object + */ + e?: any; + + /** if the event should be cancelled ; otherwise ,false + */ + cancel?: boolean; +} + export interface Fields { /** It receives the child data for the inner level. @@ -10657,7 +11005,7 @@ export interface Fields { */ dataSource?: any; - /** Specifies the HTML attributes to “LI” item list. + /** Specifies the HTML attributes to “LI” item list. */ htmlAttribute?: string; @@ -10665,11 +11013,11 @@ export interface Fields { */ id?: string; - /** Specifies the image attribute to “img” tag inside items list. + /** Specifies the image attribute to “img” tag inside items list. */ imageAttribute?: string; - /** Specifies the image URL to “img” tag inside item list. + /** Specifies the image URL to “img” tag inside item list. */ imageUrl?: string; @@ -10685,7 +11033,7 @@ export interface Fields { */ query?: any; - /** Specifies the sprite CSS class to “LI” item list. + /** Specifies the sprite CSS class to “LI” item list. */ spriteCssClass?: string; @@ -10702,22 +11050,19 @@ export interface Fields { url?: string; } } -enum AnimationType -{ +enum AnimationType { //string Default, //string None, } -enum MenuType -{ +enum MenuType { //string ContextMenu, //string NormalMenu, } -enum Direction -{ +enum Direction { //string Left, //string @@ -10728,11 +11073,10 @@ Right, class Pager extends ej.Widget { static fn: Pager; - constructor(element: JQuery, options?: Pager.Model); - constructor(element: Element, options?: Pager.Model); + constructor(element: JQuery | Element, options?: Pager.Model); static Locale: any; - model:Pager.Model; - defaults:Pager.Model; + model: Pager.Model; + defaults: Pager.Model; /** Send a paging request to specified page through the pager control. * @param {number} Specifies the index to be navigated @@ -10745,7 +11089,7 @@ class Pager extends ej.Widget { */ refreshPager(): void; } -export module Pager{ +export namespace Pager { export interface Model { @@ -10777,7 +11121,8 @@ export interface Model { */ externalMessage?: string; - /** Gets or sets a value that indicates whether to customizing the user interface (UI) as locale-specific in order to display regional data i.e. in a language and culture specific to a particular country or region. + /** Gets or sets a value that indicates whether to customizing the user interface (UI) as locale-specific in order to display regional data i.e. + * in a language and culture specific to a particular country or region. * @Default {en-US} */ locale?: string; @@ -10808,7 +11153,7 @@ export interface Model { showPageInfo?: boolean; /** Triggered when pager numeric item is clicked in pager control. */ - click? (e: ClickEventArgs): void; + click?(e: ClickEventArgs): void; } export interface ClickEventArgs { @@ -10837,11 +11182,10 @@ export interface ClickEventArgs { class ProgressBar extends ej.Widget { static fn: ProgressBar; - constructor(element: JQuery, options?: ProgressBar.Model); - constructor(element: Element, options?: ProgressBar.Model); + constructor(element: JQuery | Element, options?: ProgressBar.Model); static Locale: any; - model:ProgressBar.Model; - defaults:ProgressBar.Model; + model: ProgressBar.Model; + defaults: ProgressBar.Model; /** Destroy the progressbar widget * @returns {void} @@ -10868,7 +11212,7 @@ class ProgressBar extends ej.Widget { */ getValue(): number; } -export module ProgressBar{ +export namespace ProgressBar { export interface Model { @@ -10938,19 +11282,19 @@ export interface Model { width?: number|string; /** Event triggers when the progress value changed */ - change? (e: ChangeEventArgs): void; + change?(e: ChangeEventArgs): void; /** Event triggers when the process completes (at 100%) */ - complete? (e: CompleteEventArgs): void; + complete?(e: CompleteEventArgs): void; /** Event triggers when the progressbar are created */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Event triggers when the progressbar are destroyed */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Event triggers when the process starts (from 0%) */ - start? (e: StartEventArgs): void; + start?(e: StartEventArgs): void; } export interface ChangeEventArgs { @@ -11055,11 +11399,10 @@ export interface StartEventArgs { class RadioButton extends ej.Widget { static fn: RadioButton; - constructor(element: JQuery, options?: RadioButton.Model); - constructor(element: Element, options?: RadioButton.Model); + constructor(element: JQuery | Element, options?: RadioButton.Model); static Locale: any; - model:RadioButton.Model; - defaults:RadioButton.Model; + model: RadioButton.Model; + defaults: RadioButton.Model; /** To disable the RadioButton * @returns {void} @@ -11071,7 +11414,7 @@ class RadioButton extends ej.Widget { */ enable(): void; } -export module RadioButton{ +export namespace RadioButton { export interface Model { @@ -11089,7 +11432,8 @@ export interface Model { */ enabled?: boolean; - /** Specifies the enablePersistence property for RadioButton while initialization. The enablePersistence API save current model value to browser cookies for state maintains. While refreshing the radio button control page the model value apply from browser cookies. + /** Specifies the enablePersistence property for RadioButton while initialization. The enablePersistence API save current model value to browser cookies for state maintains. + * While refreshing the radio button control page the model value apply from browser cookies. * @Default {false} */ enablePersistence?: boolean; @@ -11144,16 +11488,16 @@ export interface Model { value?: string; /** Fires before the RadioButton is going to changed its state successfully */ - beforeChange? (e: BeforeChangeEventArgs): void; + beforeChange?(e: BeforeChangeEventArgs): void; /** Fires when the RadioButton state is changed successfully */ - change? (e: ChangeEventArgs): void; + change?(e: ChangeEventArgs): void; /** Fires when the RadioButton created successfully */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires when the RadioButton destroyed successfully */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; } export interface BeforeChangeEventArgs { @@ -11232,8 +11576,7 @@ export interface DestroyEventArgs { type?: string; } } -enum RadioButtonSize -{ +enum RadioButtonSize { //Shows small size radio button Small, //Shows medium size radio button @@ -11242,11 +11585,10 @@ Medium, class Rating extends ej.Widget { static fn: Rating; - constructor(element: JQuery, options?: Rating.Model); - constructor(element: Element, options?: Rating.Model); + constructor(element: JQuery | Element, options?: Rating.Model); static Locale: any; - model:Rating.Model; - defaults:Rating.Model; + model: Rating.Model; + defaults: Rating.Model; /** Destroy the Rating widget all events bound will be unbind automatically and bring the control to pre-init state. * @returns {void} @@ -11284,7 +11626,7 @@ class Rating extends ej.Widget { */ show(): void; } -export module Rating{ +export namespace Rating { export interface Model { @@ -11373,22 +11715,22 @@ export interface Model { width?: string; /** Fires when Rating value changes. */ - change? (e: ChangeEventArgs): void; + change?(e: ChangeEventArgs): void; /** Fires when Rating control is clicked successfully. */ - click? (e: ClickEventArgs): void; + click?(e: ClickEventArgs): void; /** Fires when Rating control is created. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires when Rating control is destroyed successfully. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Fires when mouse hover is removed from Rating control. */ - mouseout? (e: MouseoutEventArgs): void; + mouseout?(e: MouseoutEventArgs): void; /** Fires when mouse hovered over the Rating control. */ - mouseover? (e: MouseoverEventArgs): void; + mouseover?(e: MouseoverEventArgs): void; } export interface ChangeEventArgs { @@ -11517,7 +11859,7 @@ export interface MouseoverEventArgs { index?: any; } -enum Precision{ +enum Precision { ///string Exact, @@ -11533,13 +11875,13 @@ enum Precision{ class Ribbon extends ej.Widget { static fn: Ribbon; - constructor(element: JQuery, options?: Ribbon.Model); - constructor(element: Element, options?: Ribbon.Model); + constructor(element: JQuery | Element, options?: Ribbon.Model); static Locale: any; - model:Ribbon.Model; - defaults:Ribbon.Model; + model: Ribbon.Model; + defaults: Ribbon.Model; - /** Adds contextual tab or contextual tab set dynamically in the ribbon control with contextual tabs object and index position. When index is null, ribbon contextual tab or contextual tab set is added at the last index. + /** Adds contextual tab or contextual tab set dynamically in the ribbon control with contextual tabs object and index position. + * When index is null, ribbon contextual tab or contextual tab set is added at the last index. * @param {any} contextual tab or contextual tab set object. * @param {number} index of the contextual tab or contextual tab set, this is optional. * @returns {void} @@ -11559,7 +11901,7 @@ class Ribbon extends ej.Widget { * @param {number} index of the ribbon tab,this is optional. * @returns {void} */ - addTab(tabText: string, ribbonGroups: Array, index?: number): void; + addTab(tabText: string, ribbonGroups: any[], index?: number): void; /** Adds tab group dynamically in the ribbon control with given tab index, tab group object and group index position. When group index is null, ribbon group is added at the last index. * @param {number} ribbon tab index. @@ -11569,7 +11911,8 @@ class Ribbon extends ej.Widget { */ addTabGroup(tabIndex: number, tabGroup: any, groupIndex?: number): void; - /** Adds group content dynamically in the ribbon control with given tab index, group index, sub group index, content and content index position. When content index is null, content is added at the last index. + /** Adds group content dynamically in the ribbon control with given tab index, group index, sub group index, content and content index position. + * When content index is null, content is added at the last index. * @param {number} ribbon tab index. * @param {number} ribbon group index. * @param {number} sub group index in the ribbon group, @@ -11603,7 +11946,7 @@ class Ribbon extends ej.Widget { * @param {number} index of the tab item. * @returns {String} */ - getTabText(index: number): String; + getTabText(index: number): string; /** Hides the given text tab in the ribbon control. * @param {string} text of the tab item. @@ -11615,13 +11958,13 @@ class Ribbon extends ej.Widget { * @param {string} text of the tab item. * @returns {Boolean} */ - isEnable(text: string): Boolean; + isEnable(text: string): boolean; /** Checks whether the given text tab in the ribbon control is visible or not. * @param {string} text of the tab item. * @returns {Boolean} */ - isVisible(text: string): Boolean; + isVisible(text: string): boolean; /** Removes the given index tab item from the ribbon control. * @param {number} index of tab item. @@ -11676,7 +12019,7 @@ class Ribbon extends ej.Widget { */ removeBackStageItem(index: number): void; } -export module Ribbon{ +export namespace Ribbon { export interface Model { @@ -11690,7 +12033,8 @@ export interface Model { */ isResponsive?: boolean; - /** Specifies the height, width, enableRTL, showRoundedCorner,enabled,cssClass property to the controls in the ribbon commonly andit will work only when those properties are not defined in buttonSettings and content defaults. + /** Specifies the height, width, enableRTL, showRoundedCorner,enabled,cssClass property to the controls in the ribbon commonly andit will work only when those properties + * are not defined in buttonSettings and content defaults. * @Default {Object} */ buttonDefaults?: any; @@ -11730,20 +12074,21 @@ export interface Model { */ applicationTab?: ApplicationTab; - /** Specifies the contextual tabs and tab set to the ribbon control with the background color and border color. Refer to the tabs section for adding tabs into the contextual tab and contextual tab set. + /** Specifies the contextual tabs and tab set to the ribbon control with the background color and border color. Refer to the tabs section for adding tabs + * into the contextual tab and contextual tab set. * @Default {Array} */ - contextualTabs?: Array; + contextualTabs?: ContextualTab[]; /** Specifies the index or indexes to disable the given index tab or indexes tabs in the ribbon control. * @Default {0} */ - disabledItemIndex?: Array; + disabledItemIndex?: any[]; /** Specifies the index or indexes to enable the given index tab or indexes tabs in the ribbon control. * @Default {null} */ - enabledItemIndex?: Array; + enabledItemIndex?: any[]; /** Specifies the index of the ribbon tab to select the given index tab item in the ribbon control. * @Default {1} @@ -11753,9 +12098,10 @@ export interface Model { /** Specifies the tabs and its groups. Also specifies the control details that has to be placed in the tab area in the ribbon control. * @Default {Array} */ - tabs?: Array; + tabs?: Tab[]; - /** Gets or sets a value that indicates whether to customizing the user interface (UI) as locale-specific in order to display regional data i.e. in a language and culture specific to a particular country or region and it will need to use the user's preference. + /** Gets or sets a value that indicates whether to customizing the user interface (UI) as locale-specific in order to display regional data i.e. in a language and culture specific + * to a particular country or region and it will need to use the user's preference. * @Default {en-US} */ locale?: string; @@ -11766,55 +12112,55 @@ export interface Model { width?: string|number; /** Triggered before the ribbon tab item is removed. */ - beforeTabRemove? (e: BeforeTabRemoveEventArgs): void; + beforeTabRemove?(e: BeforeTabRemoveEventArgs): void; /** Triggered before the ribbon control is created. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Triggered before the ribbon control is destroyed. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Triggered when the control in the group is clicked successfully. */ - groupClick? (e: GroupClickEventArgs): void; + groupClick?(e: GroupClickEventArgs): void; /** Triggered when the group expander in the group is clicked successfully. */ - groupExpand? (e: GroupExpandEventArgs): void; + groupExpand?(e: GroupExpandEventArgs): void; /** Triggered when an item in the Gallery control is clicked successfully. */ - galleryItemClick? (e: GalleryItemClickEventArgs): void; + galleryItemClick?(e: GalleryItemClickEventArgs): void; /** Triggered when a tab or button in the backstage page is clicked successfully. */ - backstageItemClick? (e: BackstageItemClickEventArgs): void; + backstageItemClick?(e: BackstageItemClickEventArgs): void; /** Triggered when the ribbon control is collapsed. */ - collapse? (e: CollapseEventArgs): void; + collapse?(e: CollapseEventArgs): void; /** Triggered when the ribbon control is expanded. */ - expand? (e: ExpandEventArgs): void; + expand?(e: ExpandEventArgs): void; /** Triggered before the ribbon control is load. */ - load? (e: LoadEventArgs): void; + load?(e: LoadEventArgs): void; /** Triggered after adding the new ribbon tab item. */ - tabAdd? (e: TabAddEventArgs): void; + tabAdd?(e: TabAddEventArgs): void; /** Triggered when tab is clicked successfully in the ribbon control. */ - tabClick? (e: TabClickEventArgs): void; + tabClick?(e: TabClickEventArgs): void; /** Triggered before the ribbon tab is created. */ - tabCreate? (e: TabCreateEventArgs): void; + tabCreate?(e: TabCreateEventArgs): void; /** Triggered after the tab item is removed from the ribbon control. */ - tabRemove? (e: TabRemoveEventArgs): void; + tabRemove?(e: TabRemoveEventArgs): void; /** Triggered after the ribbon tab item is selected in the ribbon control. */ - tabSelect? (e: TabSelectEventArgs): void; + tabSelect?(e: TabSelectEventArgs): void; /** Triggered when the expand/collapse button is clicked successfully . */ - toggleButtonClick? (e: ToggleButtonClickEventArgs): void; + toggleButtonClick?(e: ToggleButtonClickEventArgs): void; /** Triggered when the QAT menu item is clicked successfully . */ - qatMenuItemClick? (e: QatMenuItemClickEventArgs): void; + qatMenuItemClick?(e: QatMenuItemClickEventArgs): void; } export interface BeforeTabRemoveEventArgs { @@ -12202,7 +12548,8 @@ export interface ApplicationTabBackstageSettingsPage { */ text?: string; - /** Specifies the type for ribbon backstage page's contents. Set "ej.Ribbon.BackStageItemType.Tab" to render the tab or "ej.Ribbon.BackStageItemType.Button" to render the button. + /** Specifies the type for ribbon backstage page's contents. Set "ej.Ribbon.BackStageItemType.Tab" to render the tab or " + * ej.Ribbon.BackStageItemType.Button" to render the button. * @Default {ej.Ribbon.ItemType.Tab} */ itemType?: ej.Ribbon.ItemType|string; @@ -12238,7 +12585,7 @@ export interface ApplicationTabBackstageSettings { /** Specifies the ribbon backstage page with its tab and button elements. * @Default {Array} */ - pages?: Array; + pages?: ApplicationTabBackstageSettingsPage[]; /** Specifies the width of backstage page header that contains tabs and buttons. * @Default {null} @@ -12263,7 +12610,8 @@ export interface ApplicationTab { */ menuSettings?: any; - /** Specifies the application menu or backstage page. Specify the type of application tab as "ej.Ribbon.ApplicationTabType.Menu" to render the application menu or "ej.Ribbon.ApplicationTabType.Backstage" to render backstage page in the ribbon control. + /** Specifies the application menu or backstage page. Specify the type of application tab as "ej.Ribbon.ApplicationTabType.Menu" to render the application menu or + * "ej.Ribbon.ApplicationTabType.Backstage" to render backstage page in the ribbon control. * @Default {ej.Ribbon.ApplicationTabType.Menu} */ type?: ej.Ribbon.ApplicationTabType|string; @@ -12284,7 +12632,7 @@ export interface ContextualTab { /** Specifies the tabs to present in the contextual tabs and tab set. Refer to the tabs section for adding tabs into the contextual tabs and tab set. * @Default {Array} */ - tabs?: Array; + tabs?: any[]; } export interface TabsGroupsContentDefaults { @@ -12419,7 +12767,7 @@ export interface TabsGroupsContentGroup { /** Specifies the Syncfusion button and menu as gallery extra items. * @Default {Array} */ - customGalleryItems?: Array; + customGalleryItems?: TabsGroupsContentGroupsCustomGalleryItem[]; /** Provides custom tooltip for button, split button, dropdown list, toggle button, custom controls in the sub groups. Text and HTML support are also provided for title and content. * @Default {Object} @@ -12444,7 +12792,7 @@ export interface TabsGroupsContentGroup { /** Defines each gallery content. * @Default {Array} */ - galleryItems?: Array; + galleryItems?: TabsGroupsContentGroupsGalleryItem[]; /** Specifies the Id for button, split button, dropdown list, toggle button, gallery, custom controls in the sub groups. * @Default {null} @@ -12491,7 +12839,8 @@ export interface TabsGroupsContentGroup { */ quickAccessMode?: ej.Ribbon.QuickAccessMode|string; - /** Specifies the type as "ej.Ribbon.Type.Button" or "ej.Ribbon.Type.SplitButton" or "ej.Ribbon.Type.DropDownList" or "ej.Ribbon.Type.ToggleButton" or "ej.Ribbon.Type.Custom" or "ej.Ribbon.Type.Gallery" to render button, split, dropdown, toggle button, gallery, custom controls. + /** Specifies the type as "ej.Ribbon.Type.Button" or "ej.Ribbon.Type.SplitButton" or "ej.Ribbon.Type.DropDownList" or "ej.Ribbon.Type.ToggleButton" + * or "ej.Ribbon.Type.Custom" or "ej.Ribbon.Type.Gallery" to render button, split, dropdown, toggle button, gallery, custom controls. * @Default {ej.Ribbon.Type.Button} */ type?: ej.Ribbon.Type|string; @@ -12507,7 +12856,7 @@ export interface TabsGroupsContent { /** Specifies the controls such as Syncfusion button, split button, dropdown list, toggle button, gallery, custom controls in the subgroup of the ribbon tab . * @Default {Array} */ - groups?: Array; + groups?: TabsGroupsContentGroup[]; } export interface TabsGroupsGroupExpanderSettings { @@ -12525,7 +12874,8 @@ export interface TabsGroupsGroupExpanderSettings { export interface TabsGroup { - /** Specifies the alignment of controls in the groups in 'row' type or 'column' type. Value for row type is "ej.Ribbon.AlignType.Rows" and for column type is "ej.Ribbon.alignType.columns". + /** Specifies the alignment of controls in the groups in 'row' type or 'column' type. Value for row type is "ej.Ribbon.AlignType.Rows" + * and for column type is "ej.Ribbon.alignType.columns". * @Default {ej.Ribbon.AlignType.Rows} */ alignType?: ej.Ribbon.AlignType|string; @@ -12533,7 +12883,7 @@ export interface TabsGroup { /** Specifies the Syncfusion button, split button, dropdown list, toggle button, gallery, custom controls to the groups in the ribbon control. * @Default {Array} */ - content?: Array; + content?: TabsGroupsContent[]; /** Specifies the ID of custom items to be placed in the groups. * @Default {null} @@ -12571,7 +12921,7 @@ export interface Tab { /** Specifies single group or multiple groups and its contents to each tab in the ribbon control. * @Default {Array} */ - groups?: Array; + groups?: TabsGroup[]; /** Specifies the ID for each tab's content panel. * @Default {null} @@ -12584,17 +12934,17 @@ export interface Tab { text?: string; } -enum ItemType{ +enum ItemType { - ///To render the button for ribbon backstage page’s contents + ///To render the button for ribbon backstage page’s contents Button, - ///To render the tab for ribbon backstage page’s contents + ///To render the tab for ribbon backstage page’s contents Tab } -enum ApplicationTabType{ +enum ApplicationTabType { ///applicationTab display as menu Menu, @@ -12604,7 +12954,7 @@ enum ApplicationTabType{ } -enum AlignType{ +enum AlignType { ///To align the group content's in row Rows, @@ -12614,7 +12964,7 @@ enum AlignType{ } -enum CustomItemType{ +enum CustomItemType { ///Specifies the button type in customGalleryItems Button, @@ -12624,7 +12974,7 @@ enum CustomItemType{ } -enum QuickAccessMode{ +enum QuickAccessMode { ///Controls are hidden in Quick Access toolbar None, @@ -12637,7 +12987,7 @@ enum QuickAccessMode{ } -enum Type{ +enum Type { ///Specifies the button control Button, @@ -12662,11 +13012,10 @@ enum Type{ class Kanban extends ej.Widget { static fn: Kanban; - constructor(element: JQuery, options?: Kanban.Model); - constructor(element: Element, options?: Kanban.Model); + constructor(element: JQuery | Element, options?: Kanban.Model); static Locale: any; - model:Kanban.Model; - defaults:Kanban.Model; + model: Kanban.Model; + defaults: Kanban.Model; /** Add or remove columns in Kanban columns collections.Default action is add. * @param {Array|string} Pass array of columns or string of headerText to add/remove the column in Kanban @@ -12674,7 +13023,7 @@ class Kanban extends ej.Widget { * @param {string} optional Pass add/remove action to be performed. By default "add" action will perform * @returns {void} */ - columns(columndetails: Array|string, keyvalue: Array|string, action?: string): void; + columns(columndetails: any[]|string, keyvalue: any[]|string, action?: string): void; /** Destroy the Kanban widget all events bound using this._on will be unbind automatically and bring the control to pre-init state. * @returns {void} @@ -12685,7 +13034,7 @@ class Kanban extends ej.Widget { * @param {Array} Pass new data source to the Kanban * @returns {void} */ - dataSource(datasource: Array): void; + dataSource(datasource: any[]): void; /** toggleColumn based on the headerText in Kanban. * @param {any} Pass the header text of the column to get the corresponding column object @@ -12702,7 +13051,7 @@ class Kanban extends ej.Widget { /** Used for get the names of all the visible column name collections in Kanban. * @returns {Array} */ - getVisibleColumnNames(): Array; + getVisibleColumnNames(): any[]; /** Get the scroller object of Kanban. * @returns {ej.Scroller} @@ -12713,18 +13062,18 @@ class Kanban extends ej.Widget { * @param {string} Pass the header text of the column to get the corresponding column object * @returns {String} */ - getColumnByHeaderText(headerText: string): String; + getColumnByHeaderText(headerText: string): string; /** Get the table details based on the given header table in Kanban. * @returns {String} */ - getHeaderTable(): String; + getHeaderTable(): string; /** Hide columns from the Kanban based on the header text * @param {Array|string} you can pass either array of header text of various columns or a header text of a column to hide * @returns {void} */ - hideColumns(headerText: Array|string): void; + hideColumns(headerText: any[]|string): void; /** Print the Kanban Board * @returns {void} @@ -12746,14 +13095,14 @@ class Kanban extends ej.Widget { * @param {Array|string} You can pass either array of header text of various columns or a header text of a column to show * @returns {void} */ - showColumns(headerText: Array|string): void; + showColumns(headerText: any[]|string): void; /** Update a card in Kanban control based on key and JSON data given. * @param {string} Pass the key field Name of the column * @param {Array} Pass the edited JSON data of card need to be update. * @returns {void} */ - updateCard(key: string, data: Array): void; + updateCard(key: string, data: any[]): void; KanbanSelection: Kanban.KanbanSelection; @@ -12763,7 +13112,7 @@ class Kanban extends ej.Widget { KanbanEdit: Kanban.KanbanEdit; } -export module Kanban{ +export namespace Kanban { export interface KanbanSelection { @@ -12823,7 +13172,7 @@ export interface KanbanEdit { * @param {Array} Pass the edited JSON data of card need to be add. * @returns {void} */ - addCard(primaryKey: string,card: Array): void; + addCard(primaryKey: string, card: any[]): void; /** Send a cancel request of add/edit card in Kanban when allowEditing/allowAdding is set as true. * @returns {void} @@ -12852,7 +13201,7 @@ export interface KanbanEdit { * @param {any} Specify the validation rules for the field * @returns {void} */ - setValidationToField(name: string,rules: any): void; + setValidationToField(name: string, rules: any): void; } export interface Model { @@ -12920,7 +13269,7 @@ export interface Model { /** Gets or sets an object that indicates to render the Kanban with specified columns. * @Default {Array} */ - columns?: Array; + columns?: Column[]; /** Gets or sets an object that indicates whether to Customize the card settings. * @Default {Object} @@ -12930,7 +13279,7 @@ export interface Model { /** Gets or sets a value that indicates whether to add customToolbarItems within the toolbar to perform any action in the Kanban. * @Default {[]} */ - customToolbarItems?: Array; + customToolbarItems?: CustomToolbarItem[]; /** Gets or sets a value that indicates to render the Kanban with custom theme. */ @@ -12984,7 +13333,7 @@ export interface Model { /** To customize the filtering behavior based on queries given. * @Default {Array} */ - filterSettings?: Array; + filterSettings?: FilterSetting[]; /** ej Query to query database of Kanban. * @Default {null} @@ -13014,7 +13363,7 @@ export interface Model { /** Gets or sets an object that indicates to managing the collection of stacked header rows for the Kanban. * @Default {Array} */ - stackedHeaderRows?: Array; + stackedHeaderRows?: StackedHeaderRow[]; /** The tooltip allows to display card details in a tooltip while hovering on it. */ @@ -13023,87 +13372,88 @@ export interface Model { /** Gets or sets an object that indicates to render the Kanban with specified workflows. * @Default {Array} */ - workflows?: Array; + workflows?: Workflow[]; - /** Gets or sets a value that indicates whether to customizing the user interface (UI) as locale-specific in order to display regional data i.e. in a language and culture specific to a particular country or region. + /** Gets or sets a value that indicates whether to customizing the user interface (UI) as locale-specific in order to display regional data i.e. in a language and culture specific + * to a particular country or region. * @Default {en-US} */ locale?: string; /** Triggered for every Kanban action before its starts. */ - actionBegin? (e: ActionBeginEventArgs): void; + actionBegin?(e: ActionBeginEventArgs): void; /** Triggered for every Kanban action success event. */ - actionComplete? (e: ActionCompleteEventArgs): void; + actionComplete?(e: ActionCompleteEventArgs): void; /** Triggered for every Kanban action server failure event. */ - actionFailure? (e: ActionFailureEventArgs): void; + actionFailure?(e: ActionFailureEventArgs): void; /** Triggered before the task is going to be edited. */ - beginEdit? (e: BeginEditEventArgs): void; + beginEdit?(e: BeginEditEventArgs): void; /** Triggered before the card is going to be added */ - beginAdd? (e: BeginAddEventArgs): void; + beginAdd?(e: BeginAddEventArgs): void; /** Triggered before the card is selected. */ - beforeCardSelect? (e: BeforeCardSelectEventArgs): void; + beforeCardSelect?(e: BeforeCardSelectEventArgs): void; /** Trigger after the card is clicked. */ - cardClick? (e: CardClickEventArgs): void; + cardClick?(e: CardClickEventArgs): void; /** Triggered when the card is being dragged. */ - cardDrag? (e: CardDragEventArgs): void; + cardDrag?(e: CardDragEventArgs): void; /** Triggered when card dragging start. */ - cardDragStart? (e: CardDragStartEventArgs): void; + cardDragStart?(e: CardDragStartEventArgs): void; /** Triggered when card dragging stops. */ - cardDragStop? (e: CardDragStopEventArgs): void; + cardDragStop?(e: CardDragStopEventArgs): void; /** Triggered when the card is Dropped. */ - cardDrop? (e: CardDropEventArgs): void; + cardDrop?(e: CardDropEventArgs): void; /** Triggered after the card is selected. */ - cardSelect? (e: CardSelectEventArgs): void; + cardSelect?(e: CardSelectEventArgs): void; /** Triggered when card is double clicked. */ - cardDoubleClick? (e: CardDoubleClickEventArgs): void; + cardDoubleClick?(e: CardDoubleClickEventArgs): void; /** Triggered before the card is selected. */ - cardSelecting? (e: CardSelectingEventArgs): void; + cardSelecting?(e: CardSelectingEventArgs): void; /** Triggered when the Kanban is rendered completely */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Triggers after the cell is clicked. */ - cellClick? (e: CellClickEventArgs): void; + cellClick?(e: CellClickEventArgs): void; /** Triggered the Kanban is bound with data during initial rendering. */ - dataBound? (e: DataBoundEventArgs): void; + dataBound?(e: DataBoundEventArgs): void; /** Triggered when Kanban going to destroy. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Triggered after the card is deleted. */ - endDelete? (e: EndDeleteEventArgs): void; + endDelete?(e: EndDeleteEventArgs): void; /** Triggered after the card is edited. */ - endEdit? (e: EndEditEventArgs): void; + endEdit?(e: EndEditEventArgs): void; /** Triggers after the header is clicked. */ - headerClick? (e: HeaderClickEventArgs): void; + headerClick?(e: HeaderClickEventArgs): void; /** Triggered initial load. */ - load? (e: LoadEventArgs): void; + load?(e: LoadEventArgs): void; /** Triggered when toolbar item is clicked in Kanban. */ - toolbarClick? (e: ToolbarClickEventArgs): void; + toolbarClick?(e: ToolbarClickEventArgs): void; /** Triggered every time a single card rendered request is made to access particular card information. */ - queryCellInfo? (e: QueryCellInfoEventArgs): void; + queryCellInfo?(e: QueryCellInfoEventArgs): void; /** Triggered before the context menu is opened. */ - contextOpen? (e: ContextOpenEventArgs): void; + contextOpen?(e: ContextOpenEventArgs): void; } export interface ActionBeginEventArgs { @@ -13313,7 +13663,7 @@ export interface BeforeCardSelectEventArgs { /** Returns the previously select card indexes */ - previousRowcellindex?: Array; + previousRowcellindex?: any[]; /** Returns the Target item. */ @@ -13499,7 +13849,7 @@ export interface CardSelectEventArgs { /** Returns the previously select card indexes */ - previousRowcellindex?: Array; + previousRowcellindex?: any[]; /** Returns the current item. */ @@ -13561,7 +13911,7 @@ export interface CardSelectingEventArgs { /** Returns the previously rowcell is selecting card indexes */ - previousRowcellindex?: Array; + previousRowcellindex?: any[]; /** Returns the current item. */ @@ -13847,7 +14197,7 @@ export interface SwimlaneSettingsUnassignedGroup { /** To set the user defined values which are need to categorized as unassigned category swim lane groups. * @Default {[null,undefined,]} */ - keys?: Array; + keys?: any[]; } export interface SwimlaneSettings { @@ -13896,17 +14246,25 @@ export interface ContextMenuSettings { /** Gets or sets a value that indicates the list of items needs to be disable from default context menu items. * @Default {Array} */ - disableDefaultItems?: Array; + disableDefaultItems?: any[]; /** Its used to add specific default context menu items. * @Default {Array} */ - menuItems?: Array; + menuItems?: any[]; /** Gets or sets a value that indicates whether to add custom contextMenu items. * @Default {Array} */ - customMenuItems?: Array; + customMenuItems?: ContextMenuSettingsCustomMenuItem[]; +} + +export interface ColumnsTotalCount { + + /** To customize the totalCount text properties. + * @Default {null} + */ + text?: string; } export interface ColumnsConstraints { @@ -13935,9 +14293,9 @@ export interface Column { headerText?: string; /** To customize the totalCount properties. - * @Default {false} + * @Default {Object} */ - totalCount?: string; + totalCount?: ColumnsTotalCount; /** Gets or sets an object that indicates to render the Kanban with specified columns key. * @Default {null} @@ -13945,12 +14303,12 @@ export interface Column { key?: string|number; /** To enable/disable allowDrop for specific column wise. - * @Default {false} + * @Default {true} */ allowDrop?: boolean; /** To enable/disable allowDrag for specific column wise. - * @Default {false} + * @Default {true} */ allowDrag?: boolean; @@ -14059,7 +14417,7 @@ export interface EditSettings { /** Get or sets an object that indicates whether to customize the editing fields of Kanban card. * @Default {Array} */ - editItems?: Array; + editItems?: EditSettingsEditItem[]; /** This specifies the id of the template which is require to be edited using the External edit form. * @Default {null} @@ -14156,7 +14514,7 @@ export interface SearchSettings { /** To customize the fields the searching operation can be perform. * @Default {Array} */ - fields?: Array; + fields?: any[]; /** To customize the searching string. */ @@ -14191,7 +14549,7 @@ export interface StackedHeaderRow { /** Gets or sets a value that indicates whether to add stacked header columns into the stacked header rows. * @Default {Array} */ - stackedHeaderColumns?: Array; + stackedHeaderColumns?: StackedHeaderRowsStackedHeaderColumn[]; } export interface TooltipSettings { @@ -14220,7 +14578,7 @@ export interface Workflow { allowedTransitions?: string; } -enum Target{ +enum Target { ///Sets context menu to Kanban header Header, @@ -14236,7 +14594,7 @@ enum Target{ } -enum EditMode{ +enum EditMode { ///Creates Kanban with editMode as Dialog Dialog, @@ -14252,7 +14610,7 @@ enum EditMode{ } -enum EditingType{ +enum EditingType { ///Allows to set edit type as string edit type String, @@ -14277,7 +14635,7 @@ enum EditingType{ } -enum FormPosition{ +enum FormPosition { ///Form position is bottom. Bottom, @@ -14287,7 +14645,7 @@ enum FormPosition{ } -enum SelectionType{ +enum SelectionType { ///Support for Single selection in Kanban Single, @@ -14300,11 +14658,10 @@ enum SelectionType{ class Rotator extends ej.Widget { static fn: Rotator; - constructor(element: JQuery, options?: Rotator.Model); - constructor(element: Element, options?: Rotator.Model); + constructor(element: JQuery | Element, options?: Rotator.Model); static Locale: any; - model:Rotator.Model; - defaults:Rotator.Model; + model: Rotator.Model; + defaults: Rotator.Model; /** Disables the Rotator control. * @returns {void} @@ -14354,7 +14711,7 @@ class Rotator extends ej.Widget { */ updateTemplateById(index: number, id: string): void; } -export module Rotator{ +export namespace Rotator { export interface Model { @@ -14426,7 +14783,8 @@ export interface Model { */ isResponsive?: boolean; - /** Specifies the number of Rotator Items to navigate on a single click (next/previous/play buttons). The navigateSteps property value must be less than or equal to the displayItemsCount property value. + /** Specifies the number of Rotator Items to navigate on a single click (next/previous/play buttons). + * The navigateSteps property value must be less than or equal to the displayItemsCount property value. * @Default {1} */ navigateSteps?: string|number; @@ -14446,7 +14804,8 @@ export interface Model { */ query?: string; - /** If the Rotator Item is an image, you can specify a caption for the Rotator Item. The caption text for each Rotator Item must be set by using the title attribute of the respective tag. The caption cannot be displayed if multiple Rotator Items are present. + /** If the Rotator Item is an image, you can specify a caption for the Rotator Item. The caption text for each Rotator Item must be set by using the title attribute of the respective tag. + * The caption cannot be displayed if multiple Rotator Items are present. * @Default {false} */ showCaption?: boolean; @@ -14466,7 +14825,8 @@ export interface Model { */ showPlayButton?: boolean; - /** Turns on or off thumbnail support in the Rotator control. Thumbnail is used to navigate between slides. Thumbnail supports only single slide transition You must specify the source for thumbnail elements through the thumbnailSourceID property. + /** Turns on or off thumbnail support in the Rotator control. Thumbnail is used to navigate between slides. Thumbnail supports only single slide transition + * You must specify the source for thumbnail elements through the thumbnailSourceID property. * @Default {false} */ showThumbnail?: boolean; @@ -14497,7 +14857,7 @@ export interface Model { /** The templateId enables to bind multiple customized template items in Rotator. * @Default {null} */ - templateId?: Array; + templateId?: any[]; /** Specifies the source for thumbnail elements. * @Default {null} @@ -14505,25 +14865,25 @@ export interface Model { thumbnailSourceID?: any; /** This event is fired when the Rotator slides are changed. */ - change? (e: ChangeEventArgs): void; + change?(e: ChangeEventArgs): void; /** This event is fired when the Rotator control is initialized. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** This event is fired when the Rotator control is destroyed. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** This event is fired when a pager is clicked. */ - pagerClick? (e: PagerClickEventArgs): void; + pagerClick?(e: PagerClickEventArgs): void; /** This event is fired when enableAutoPlay is started. */ - start? (e: StartEventArgs): void; + start?(e: StartEventArgs): void; /** This event is fired when autoplay is stopped or paused. */ - stop? (e: StopEventArgs): void; + stop?(e: StopEventArgs): void; /** This event is fired when a thumbnail pager is clicked. */ - thumbItemClick? (e: ThumbItemClickEventArgs): void; + thumbItemClick?(e: ThumbItemClickEventArgs): void; } export interface ChangeEventArgs { @@ -14698,7 +15058,7 @@ export interface Fields { url?: string; } -enum PagerPosition{ +enum PagerPosition { ///string BottomLeft, @@ -14723,11 +15083,10 @@ enum PagerPosition{ class RTE extends ej.Widget { static fn: RTE; - constructor(element: JQuery, options?: RTE.Model); - constructor(element: Element, options?: RTE.Model); + constructor(element: JQuery | Element, options?: RTE.Model); static Locale: any; - model:RTE.Model; - defaults:RTE.Model; + model: RTE.Model; + defaults: RTE.Model; /** Returns the range object. * @returns {any} @@ -14800,20 +15159,21 @@ class RTE extends ej.Widget { insertMenuOption(): void; /** Add a table column at the right or left of the specified cell - * @param {boolean} If it’s true, add a column at the left of the cell, otherwise add a column at the right of the cell + * @param {boolean} If it’s true, add a column at the left of the cell, otherwise add a column at the right of the cell * @param {JQuery} Column will be added based on the given cell element * @returns {HTMLElement} */ insertColumn(before?: boolean, cell?: JQuery): HTMLElement; /** To add a table row below or above the specified cell. - * @param {boolean} If it’s true, add a row before the cell, otherwise add a row after the cell + * @param {boolean} If it’s true, add a row before the cell, otherwise add a row after the cell * @param {JQuery} Row will be added based on the given cell element * @returns {HTMLElement} */ insertRow(before?: boolean, cell?: JQuery): HTMLElement; - /** This method helps to insert/paste the content at the current cursor (caret) position or the selected content to be replaced with our text by passing the value as parameter to the pasteContent method in the Editor. + /** This method helps to insert/paste the content at the current cursor (caret) position or the selected content to be replaced with our text by passing the value as parameter to the + * pasteContent method in the Editor. * @returns {void} */ pasteContent(): void; @@ -14876,7 +15236,7 @@ class RTE extends ej.Widget { */ show(): void; } -export module RTE{ +export namespace RTE { export interface Model { @@ -14901,7 +15261,8 @@ export interface Model { autoHeight?: boolean; /** Sets the colorCode to display the color of the fontColor and backgroundColor in the font tools of the RTE. - * @Default {[000000, FFFFFF, C4C4C4, ADADAD, 595959, 262626, 4f81bd, dbe5f1, b8cce4, 95b3d7, 366092, 244061, c0504d, f2dcdb, e5b9b7, d99694, 953734,632423, 9bbb59, ebf1dd, d7e3bc, c3d69b, 76923c, 4f6128, 8064a2, e5e0ec, ccc1d9, b2a2c7, 5f497a, 3f3151, f79646, fdeada, fbd5b5, fac08f,e36c09, 974806]} + * @Default {[000000, FFFFFF, C4C4C4, ADADAD, 595959, 262626, 4f81bd, dbe5f1, b8cce4, 95b3d7, 366092, 244061, c0504d, f2dcdb, e5b9b7, d99694, 953734,632423, 9bbb59, + ebf1dd, d7e3bc, c3d69b, 76923c, 4f6128, 8064a2, e5e0ec, ccc1d9, b2a2c7, 5f497a, 3f3151, f79646, fdeada, fbd5b5, fac08f,e36c09, 974806]} */ colorCode?: any; @@ -14919,7 +15280,7 @@ export interface Model { */ cssClass?: string; - /** Enables/disables the RTE control’s accessibility or interaction. + /** Enables/disables the RTE control’s accessibility or interaction. * @Default {True} */ enabled?: boolean; @@ -14954,6 +15315,16 @@ export interface Model { */ enableTabKeyNavigation?: boolean; + /** This API allows to enable url and fileName for pdf export. + * @Default {null} + */ + exportToPdfSettings?: ExportToPdfSettings; + + /** This API allows to enable url and fileName for word export. + * @Default {null} + */ + exportToWordSettings?: ExportToWordSettings; + /** Load the external CSS file inside Iframe. * @Default {null} */ @@ -14965,17 +15336,23 @@ export interface Model { fileBrowser?: FileBrowser; /** Sets the fontName in the RTE. - * @Default {{text: Segoe UI, value: Segoe UI },{text: Arial, value: Arial,Helvetica,sans-serif },{text: Courier New, value: Courier New,Courier,Monospace },{text: Georgia, value: Georgia,serif },{text: Impact, value: Impact,Charcoal,sans-serif },{text: Lucida Console, value: Lucida Console,Monaco,Monospace },{text: Tahoma, value: Tahoma,Geneva,sans-serif },{text: Times New Roman, value: Times New Roman },{text: Trebuchet MS, value: Trebuchet MS,Helvetica,sans-serif },{text: Verdana, value: Verdana,Geneva,sans-serif}} + * @Default {{text: Segoe UI, value: Segoe UI },{text: Arial, value: Arial,Helvetica,sans-serif },{text: Courier New, value: Courier New,Courier,Monospace }, + * {text: Georgia, value: Georgia,serif },{text: Impact, value: Impact,Charcoal,sans-serif },{text: Lucida Console, value: Lucida Console,Monaco,Monospace }, + * {text: Tahoma, value: Tahoma,Geneva,sans-serif },{text: Times New Roman, value: Times New Roman },{text: Trebuchet MS, value: Trebuchet MS,Helvetica,sans-serif }, + * {text: Verdana, value: Verdana,Geneva,sans-serif}} */ fontName?: any; /** Sets the fontSize in the RTE. - * @Default {{ text: 1, value: 1 },{ text: 2 (10pt), value: 2 },{ text: 3 (12pt), value: 3 },{ text: 4 (14pt), value: 4 },{ text: 5 (18pt), value: 5 },{ text: 6 (24pt), value: 6 },{ text: 7 (36pt), value: 7 }} + * @Default {{ text: 1, value: 1 },{ text: 2 (10pt), value: 2 },{ text: 3 (12pt), value: 3 },{ text: 4 (14pt), value: 4 },{ text: 5 (18pt), value: 5 }, + * { text: 6 (24pt), value: 6 },{ text: 7 (36pt), value: 7 }} */ fontSize?: any; /** Sets the format in the RTE. - * @Default {{ text: Paragraph, value: <p>, spriteCssClass: e-paragraph },{ text: Quotation, value: <blockquote>, spriteCssClass: e-quotation },{ text: Heading 1, value: <h1>, spriteCssClass: e-h1 },{ text: Heading 2, value: <h2>, spriteCssClass: e-h2 },{ text: Heading 3, value: <h3>, spriteCssClass: e-h3 },{ text: Heading 4, value: <h4>, spriteCssClass: e-h4 },{ text: Heading 5, value: <h5>, spriteCssClass: e-h5 },{ text: Heading 6, value: <h6>, spriteCssClass: e-h6}} + * @Default {{ text: Paragraph, value: <p>, spriteCssClass: e-paragraph },{ text: Quotation, value: <blockquote>, spriteCssClass: e-quotation }, + * { text: Heading 1, value: <h1>, spriteCssClass: e-h1 },{ text: Heading 2, value: <h2>, spriteCssClass: e-h2 },{ text: Heading 3, value: <h3>, spriteCssClass: e-h3 }, + * { text: Heading 4, value: <h4>, spriteCssClass: e-h4 },{ text: Heading 5, value: <h5>, spriteCssClass: e-h5 },{ text: Heading 6, value: <h6>, spriteCssClass: e-h6}} */ format?: string; @@ -14999,6 +15376,11 @@ export interface Model { */ imageBrowser?: ImageBrowser; + /** This API allows to enable the url for connecting to RTE import. + * @Default {null} + */ + importSettings?: ImportSettings; + /** Enables/disables responsive support for the RTE control toolbar items during the window resizing time. * @Default {false} */ @@ -15114,14 +15496,17 @@ export interface Model { tableRows?: number; /** Sets the tools in the RTE and gets the inner display order of the corresponding group element. Tools are dependent on the toolsList property. - * @Default {formatStyle: [format],style: [bold, italic, underline, strikethrough],alignment: [justifyLeft, justifyCenter, justifyRight, justifyFull],lists: [unorderedList, orderedList],indenting: [outdent, indent],doAction: [undo, redo],links: [createLink,removeLink],images: [image],media: [video],tables: [createTable, addRowAbove, addRowBelow, addColumnLeft, addColumnRight, deleteRow, deleteColumn, deleteTable]],view:[“fullScreen”,zoomIn,zoomOut],print:[print]} + * @Default {formatStyle: [format],style: [bold, italic, underline, strikethrough],alignment: [justifyLeft, justifyCenter, justifyRight, justifyFull],lists: [unorderedList, orderedList], + * indenting: [outdent, indent],doAction: [undo, redo],links: [createLink,removeLink],images: [image],media: [video],tables: [createTable, addRowAbove, addRowBelow, + * addColumnLeft, addColumnRight, deleteRow, deleteColumn, deleteTable]],view:[“fullScreen”,zoomIn,zoomOut],print:[print]} */ tools?: Tools; - /** Specifies the list of groups and order of those groups displayed in the RTE toolbar. The toolsList property is used to get the root group order and tools property is used to get the inner order of the corresponding groups displayed. When the value is not specified, it gets its default display order and tools. + /** Specifies the list of groups and order of those groups displayed in the RTE toolbar. The toolsList property is used to get the root group order and tools property is used to get the + * inner order of the corresponding groups displayed. When the value is not specified, it gets its default display order and tools. * @Default {[formatStyle, font, style, effects, alignment, lists, indenting, clipboard, doAction, clear, links, images, media, tables, casing,view, customTools,print,edit]} */ - toolsList?: Array; + toolsList?: any[]; /** Display the hints for the tools in the Toolbar. * @Default {{ associate: mouseenter, showShadow: true, position: { stem: { horizontal: left, vertical: top } }, tip: { size: { width: 5, height: 5 }, isBalloon: false }} @@ -15159,31 +15544,31 @@ export interface Model { zoomStep?: string|number; /** Fires when changed successfully. */ - change? (e: ChangeEventArgs): void; + change?(e: ChangeEventArgs): void; /** Fires when the RTE is created successfully */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires when mouse click on menu items. */ - contextMenuClick? (e: ContextMenuClickEventArgs): void; + contextMenuClick?(e: ContextMenuClickEventArgs): void; /** Fires before the RTE is destroyed. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Fires when the commands are executed successfully. */ - execute? (e: ExecuteEventArgs): void; + execute?(e: ExecuteEventArgs): void; /** Fires when the keydown action is successful. */ - keydown? (e: KeydownEventArgs): void; + keydown?(e: KeydownEventArgs): void; /** Fires when the keyup action is successful. */ - keyup? (e: KeyupEventArgs): void; + keyup?(e: KeyupEventArgs): void; /** Fires before the RTE Edit area is rendered and after the toolbar is rendered. */ - preRender? (e: PreRenderEventArgs): void; + preRender?(e: PreRenderEventArgs): void; /** Fires when the text is selected in the text area */ - select? (e: SelectEventArgs): void; + select?(e: SelectEventArgs): void; } export interface ChangeEventArgs { @@ -15325,6 +15710,28 @@ export interface SelectEventArgs { event?: any; } +export interface ExportToPdfSettings { + + /** This API is used to receive the server-side handler for export related operations. + */ + url?: string; + + /** Specifies the file name for the exported pdf file. + */ + fileName?: string; +} + +export interface ExportToWordSettings { + + /** This API is used to receive the server-side handler for export related operations. + */ + url?: string; + + /** Specifies the file name for the exported word file. + */ + fileName?: string; +} + export interface FileBrowser { /** This API is used to receive the server-side handler for file related operations. @@ -15355,6 +15762,13 @@ export interface ImageBrowser { filePath?: string; } +export interface ImportSettings { + + /** This API is used to receive the server-side handler for import operations. + */ + url?: string; +} + export interface ToolsCustomOrderedList { /** Specifies the name for customOrderedList item. @@ -15417,89 +15831,92 @@ export interface Tools { /** Specifies the casing tools and the display order of this tool in the RTE toolbar. */ - casing?: Array; + casing?: any[]; /** Specifies the clear tools and the display order of this tool in the RTE toolbar. */ - clear?: Array; + clear?: any[]; /** Specifies the clipboard tools and the display order of this tool in the RTE toolbar. */ - clipboard?: Array; + clipboard?: any[]; /** Specifies the edit tools and the displays tool in the RTE toolbar. */ - edit?: Array; + edit?: any[]; /** Specifies the doAction tools and the display order of this tool in the RTE toolbar. */ - doAction?: Array; + doAction?: any[]; /** Specifies the effect of tools and the display order of this tool in RTE toolbar. */ - effects?: Array; + effects?: any[]; /** Specifies the font tools and the display order of this tool in the RTE toolbar. */ - font?: Array; + font?: any[]; /** Specifies the formatStyle tools and the display order of this tool in the RTE toolbar. */ - formatStyle?: Array; + formatStyle?: any[]; /** Specifies the image tools and the display order of this tool in the RTE toolbar. */ - images?: Array; + images?: any[]; /** Specifies the indent tools and the display order of this tool in the RTE toolbar. */ - indenting?: Array; + indenting?: any[]; /** Specifies the link tools and the display order of this tool in the RTE toolbar. */ - links?: Array; + links?: any[]; /** Specifies the list tools and the display order of this tool in the RTE toolbar. */ - lists?: Array; + lists?: any[]; /** Specifies the media tools and the display order of this tool in the RTE toolbar. */ - media?: Array; + media?: any[]; /** Specifies the style tools and the display order of this tool in the RTE toolbar. */ - style?: Array; + style?: any[]; /** Specifies the table tools and the display order of this tool in the RTE toolbar. */ - tables?: Array; + tables?: any[]; /** Specifies the view tools and the display order of this tool in the RTE toolbar. */ - view?: Array; + view?: any[]; /** Specifies the print tools and the display order of this tool in the RTE toolbar. */ - print?: Array; + print?: any[]; + + /** Specifies the importExport tools and the display order of this tool in the RTE toolbar. + */ + importExport?: any[]; /** Specifies the customOrderedList tools and the display order of this tool in the RTE toolbar. */ - customOrderedList?: Array; + customOrderedList?: ToolsCustomOrderedList[]; /** Specifies the customUnOrderedList tools and the display order of this tool in the RTE toolbar. */ - customUnorderedList?: Array; + customUnorderedList?: ToolsCustomUnorderedList[]; } } class Slider extends ej.Widget { static fn: Slider; - constructor(element: JQuery, options?: Slider.Model); - constructor(element: Element, options?: Slider.Model); + constructor(element: JQuery | Element, options?: Slider.Model); static Locale: any; - model:Slider.Model; - defaults:Slider.Model; + model: Slider.Model; + defaults: Slider.Model; /** To disable the slider * @returns {void} @@ -15521,7 +15938,7 @@ class Slider extends ej.Widget { */ setValue(): void; } -export module Slider{ +export namespace Slider { export interface Model { @@ -15637,7 +16054,7 @@ export interface Model { /** Specifies the values of the range slider. But it's not applicable for default and minRange sliders. we can use value property for default and minRange sliders. * @Default {[minValue,maxValue]} */ - values?: Array; + values?: any[]; /** Specifies the width of the slider. * @Default {100%} @@ -15645,25 +16062,25 @@ export interface Model { width?: string; /** Fires once Slider control value is changed successfully. */ - change? (e: ChangeEventArgs): void; + change?(e: ChangeEventArgs): void; /** Fires once Slider control has been created successfully. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires when Slider control has been destroyed successfully. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Fires once Slider control is sliding successfully. */ - slide? (e: SlideEventArgs): void; + slide?(e: SlideEventArgs): void; /** Fires once Slider control is started successfully. */ - start? (e: StartEventArgs): void; + start?(e: StartEventArgs): void; /** Fires when Slider control is stopped successfully. */ - stop? (e: StopEventArgs): void; + stop?(e: StopEventArgs): void; /** Fires when display the custom tooltip */ - tooltipChange? (e: TooltipChangeEventArgs): void; + tooltipChange?(e: TooltipChangeEventArgs): void; } export interface ChangeEventArgs { @@ -15809,12 +16226,13 @@ export interface StopEventArgs { } export interface TooltipChangeEventArgs { + /** Returns the cancel option value. + */ + cancel?: boolean; } } -module slider -{ -enum sliderType -{ +namespace slider { +enum sliderType { //Shows default slider Default, //Shows minRange slider @@ -15826,11 +16244,10 @@ Range, class SplitButton extends ej.Widget { static fn: SplitButton; - constructor(element: JQuery, options?: SplitButton.Model); - constructor(element: Element, options?: SplitButton.Model); + constructor(element: JQuery | Element, options?: SplitButton.Model); static Locale: any; - model:SplitButton.Model; - defaults:SplitButton.Model; + model: SplitButton.Model; + defaults: SplitButton.Model; /** Destroy the split button widget all events bound using this._on will be unbind automatically and bring the control to pre-init state. * @returns {void} @@ -15857,7 +16274,7 @@ class SplitButton extends ej.Widget { */ show(): void; } -export module SplitButton{ +export namespace SplitButton { export interface Model { @@ -15891,7 +16308,7 @@ export interface Model { enableRTL?: boolean; /** Specifies the height of the Split Button. - * @Default {“”} + * @Default {“”} */ height?: string|number; @@ -15932,36 +16349,36 @@ export interface Model { text?: string; /** Specifies the width of the Split Button. - * @Default {“”} + * @Default {“”} */ width?: string|number; /** Fires before menu of the split button control is opened. */ - beforeOpen? (e: BeforeOpenEventArgs): void; + beforeOpen?(e: BeforeOpenEventArgs): void; /** Fires when Button control is clicked successfully */ - click? (e: ClickEventArgs): void; + click?(e: ClickEventArgs): void; /** Fires before the list content of Button control is closed */ - close? (e: CloseEventArgs): void; + close?(e: CloseEventArgs): void; /** Fires after Split Button control is created. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires when the Split Button is destroyed successfully */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Fires when a menu item is Hovered out successfully */ - itemMouseOut? (e: ItemMouseOutEventArgs): void; + itemMouseOut?(e: ItemMouseOutEventArgs): void; /** Fires when a menu item is Hovered in successfully */ - itemMouseOver? (e: ItemMouseOverEventArgs): void; + itemMouseOver?(e: ItemMouseOverEventArgs): void; /** Fires when a menu item is clicked successfully */ - itemSelected? (e: ItemSelectedEventArgs): void; + itemSelected?(e: ItemSelectedEventArgs): void; /** Fires before the list content of Button control is opened */ - open? (e: OpenEventArgs): void; + open?(e: OpenEventArgs): void; } export interface BeforeOpenEventArgs { @@ -16147,8 +16564,7 @@ export interface OpenEventArgs { type?: string; } } -enum ArrowPosition -{ +enum ArrowPosition { //To set Left arrowPosition of the split button Left, //To set Right arrowPosition of the split button @@ -16161,11 +16577,10 @@ Bottom, class Splitter extends ej.Widget { static fn: Splitter; - constructor(element: JQuery, options?: Splitter.Model); - constructor(element: Element, options?: Splitter.Model); + constructor(element: JQuery | Element, options?: Splitter.Model); static Locale: any; - model:Splitter.Model; - defaults:Splitter.Model; + model: Splitter.Model; + defaults: Splitter.Model; /** To add a new pane to splitter control. * @param {string} content of pane. @@ -16198,7 +16613,7 @@ class Splitter extends ej.Widget { */ removeItem(index: number): void; } -export module Splitter{ +export namespace Splitter { export interface Model { @@ -16213,7 +16628,7 @@ export interface Model { animationSpeed?: number; /** Specify the CSS class to splitter control to achieve custom theme. - * @Default {“”} + * @Default {“”} */ cssClass?: string; @@ -16243,14 +16658,14 @@ export interface Model { isResponsive?: boolean; /** Specify the orientation for splitter control. See orientation - * @Default {ej.orientation.Horizontal or “horizontal”} + * @Default {ej.orientation.Horizontal or “horizontal”} */ orientation?: ej.Orientation|string; /** Specify properties for each pane like paneSize, minSize, maxSize, collapsible, expandable, resizable. * @Default {[]} */ - properties?: Array; + properties?: any[]; /** Specify width for splitter control. * @Default {null} @@ -16258,19 +16673,19 @@ export interface Model { width?: string; /** Fires before expanding / collapsing the split pane of splitter control. */ - beforeExpandCollapse? (e: BeforeExpandCollapseEventArgs): void; + beforeExpandCollapse?(e: BeforeExpandCollapseEventArgs): void; /** Fires when splitter control pane has been created. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires when splitter control pane has been destroyed. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Fires when expand / collapse operation in splitter control pane has been performed successfully. */ - expandCollapse? (e: ExpandCollapseEventArgs): void; + expandCollapse?(e: ExpandCollapseEventArgs): void; /** Fires when resize in splitter control pane. */ - resize? (e: ResizeEventArgs): void; + resize?(e: ResizeEventArgs): void; } export interface BeforeExpandCollapseEventArgs { @@ -16387,13 +16802,12 @@ export interface ResizeEventArgs { class Tab extends ej.Widget { static fn: Tab; - constructor(element: JQuery, options?: Tab.Model); - constructor(element: Element, options?: Tab.Model); + constructor(element: JQuery | Element, options?: Tab.Model); static Locale: any; - model:Tab.Model; - defaults:Tab.Model; + model: Tab.Model; + defaults: Tab.Model; - /** Add new tab items with given name, URL and given index position, if index null it’s add last item. + /** Add new tab items with given name, URL and given index position, if index null it’s add last item. * @param {string} URL name / tab id. * @param {string} Tab Display name. * @param {number} Index position to placed , this is optional. @@ -16446,7 +16860,7 @@ class Tab extends ej.Widget { */ showItem(index: number): void; } -export module Tab{ +export namespace Tab { export interface Model { @@ -16531,14 +16945,14 @@ export interface Model { /** Specifies to hide a pane of Tab control. * @Default {[]} */ - hiddenItemIndex?: Array; + hiddenItemIndex?: any[]; /** Specifies the HTML Attributes of the Tab. * @Default {{}} */ htmlAttributes?: any; - /** The idPrefix property appends the given string on the added tab item id’s in runtime. + /** The idPrefix property appends the given string on the added tab item id’s in runtime. * @Default {ej-tab-} */ idPrefix?: string; @@ -16563,43 +16977,43 @@ export interface Model { */ showRoundedCorner?: boolean; - /** Set the width for outer panel element, if not it’s take parent width. + /** Set the width for outer panel element, if not it’s take parent width. * @Default {null} */ width?: string|number; /** Triggered after a tab item activated. */ - itemActive? (e: ItemActiveEventArgs): void; + itemActive?(e: ItemActiveEventArgs): void; /** Triggered before AJAX content has been loaded. */ - ajaxBeforeLoad? (e: AjaxBeforeLoadEventArgs): void; + ajaxBeforeLoad?(e: AjaxBeforeLoadEventArgs): void; /** Triggered if error occurs in AJAX request. */ - ajaxError? (e: AjaxErrorEventArgs): void; + ajaxError?(e: AjaxErrorEventArgs): void; /** Triggered after AJAX content load action. */ - ajaxLoad? (e: AjaxLoadEventArgs): void; + ajaxLoad?(e: AjaxLoadEventArgs): void; /** Triggered after a tab item activated. */ - ajaxSuccess? (e: AjaxSuccessEventArgs): void; + ajaxSuccess?(e: AjaxSuccessEventArgs): void; /** Triggered before a tab item activated. */ - beforeActive? (e: BeforeActiveEventArgs): void; + beforeActive?(e: BeforeActiveEventArgs): void; /** Triggered before a tab item remove. */ - beforeItemRemove? (e: BeforeItemRemoveEventArgs): void; + beforeItemRemove?(e: BeforeItemRemoveEventArgs): void; /** Triggered before a tab item Create. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Triggered before a tab item destroy. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Triggered after new tab item add */ - itemAdd? (e: ItemAddEventArgs): void; + itemAdd?(e: ItemAddEventArgs): void; /** Triggered after tab item removed. */ - itemRemove? (e: ItemRemoveEventArgs): void; + itemRemove?(e: ItemRemoveEventArgs): void; } export interface ItemActiveEventArgs { @@ -16924,7 +17338,7 @@ export interface AjaxSettings { type?: string; } -enum Position{ +enum Position { ///Tab headers display to top position Top, @@ -16940,7 +17354,7 @@ enum Position{ } -enum HeightAdjustMode{ +enum HeightAdjustMode { ///string None, @@ -16959,11 +17373,10 @@ enum HeightAdjustMode{ class TagCloud extends ej.Widget { static fn: TagCloud; - constructor(element: JQuery, options?: TagCloud.Model); - constructor(element: Element, options?: TagCloud.Model); + constructor(element: JQuery | Element, options?: TagCloud.Model); static Locale: any; - model:TagCloud.Model; - defaults:TagCloud.Model; + model: TagCloud.Model; + defaults: TagCloud.Model; /** Inserts a new item into the TagCloud * @param {string} Insert new item into the TagCloud @@ -16990,7 +17403,7 @@ class TagCloud extends ej.Widget { */ removeAt(position: number): void; } -export module TagCloud{ +export namespace TagCloud { export interface Model { @@ -17054,19 +17467,19 @@ export interface Model { titleText?: string; /** Event triggers when the TagCloud items are clicked */ - click? (e: ClickEventArgs): void; + click?(e: ClickEventArgs): void; /** Event triggers when the TagCloud are created */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Event triggers when the TagCloud are destroyed */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Event triggers when the cursor leaves out from a tag item */ - mouseout? (e: MouseoutEventArgs): void; + mouseout?(e: MouseoutEventArgs): void; /** Event triggers when the cursor hovers on a tag item */ - mouseover? (e: MouseoverEventArgs): void; + mouseover?(e: MouseoverEventArgs): void; } export interface ClickEventArgs { @@ -17187,8 +17600,7 @@ export interface Fields { url?: string; } } -enum Format -{ +enum Format { //To render the TagCloud items in cloud format Cloud, //To render the TagCloud items in list format @@ -17197,11 +17609,10 @@ List, class TimePicker extends ej.Widget { static fn: TimePicker; - constructor(element: JQuery, options?: TimePicker.Model); - constructor(element: Element, options?: TimePicker.Model); + constructor(element: JQuery | Element, options?: TimePicker.Model); static Locale: any; - model:TimePicker.Model; - defaults:TimePicker.Model; + model: TimePicker.Model; + defaults: TimePicker.Model; /** Allows you to disable the TimePicker. * @returns {void} @@ -17233,7 +17644,7 @@ class TimePicker extends ej.Widget { */ show(): void; } -export module TimePicker{ +export namespace TimePicker { export interface Model { @@ -17266,7 +17677,8 @@ export interface Model { */ enableRTL?: boolean; - /** When the enableStrictMode is set as true it allows the value outside of the range and also indicate with red color border, otherwise it internally changed to the min or max range value based an input value. + /** When the enableStrictMode is set as true it allows the value outside of the range and also indicate with red color border, + * otherwise it internally changed to the min or max range value based an input value. * @Default {false} */ enableStrictMode?: boolean; @@ -17355,34 +17767,34 @@ export interface Model { width?: string|number; /** Fires when the time value changed in the TimePicker. */ - beforeChange? (e: BeforeChangeEventArgs): void; + beforeChange?(e: BeforeChangeEventArgs): void; /** Fires when the TimePicker popup before opened. */ - beforeOpen? (e: BeforeOpenEventArgs): void; + beforeOpen?(e: BeforeOpenEventArgs): void; /** Fires when the time value changed in the TimePicker. */ - change? (e: ChangeEventArgs): void; + change?(e: ChangeEventArgs): void; /** Fires when the TimePicker popup closed. */ - close? (e: CloseEventArgs): void; + close?(e: CloseEventArgs): void; /** Fires when create TimePicker successfully. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires when the TimePicker is destroyed successfully. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Fires when the TimePicker control gets focus. */ - focusIn? (e: FocusInEventArgs): void; + focusIn?(e: FocusInEventArgs): void; /** Fires when the TimePicker control get lost focus. */ - focusOut? (e: FocusOutEventArgs): void; + focusOut?(e: FocusOutEventArgs): void; /** Fires when the TimePicker popup opened. */ - open? (e: OpenEventArgs): void; + open?(e: OpenEventArgs): void; /** Fires when the value is selected from the TimePicker dropdown list. */ - select? (e: SelectEventArgs): void; + select?(e: SelectEventArgs): void; } export interface BeforeChangeEventArgs { @@ -17602,11 +18014,10 @@ export interface SelectEventArgs { class ToggleButton extends ej.Widget { static fn: ToggleButton; - constructor(element: JQuery, options?: ToggleButton.Model); - constructor(element: Element, options?: ToggleButton.Model); + constructor(element: JQuery | Element, options?: ToggleButton.Model); static Locale: any; - model:ToggleButton.Model; - defaults:ToggleButton.Model; + model: ToggleButton.Model; + defaults: ToggleButton.Model; /** Allows you to destroy the ToggleButton widget. * @returns {void} @@ -17623,7 +18034,7 @@ class ToggleButton extends ej.Widget { */ enable(): void; } -export module ToggleButton{ +export namespace ToggleButton { export interface Model { @@ -17723,16 +18134,16 @@ export interface Model { width?: number|string; /** Fires when ToggleButton control state is changed successfully. */ - change? (e: ChangeEventArgs): void; + change?(e: ChangeEventArgs): void; /** Fires when ToggleButton control is clicked successfully. */ - click? (e: ClickEventArgs): void; + click?(e: ClickEventArgs): void; /** Fires when ToggleButton control is created successfully. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires when ToggleButton control is destroyed successfully. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; } export interface ChangeEventArgs { @@ -17810,11 +18221,10 @@ export interface DestroyEventArgs { class Toolbar extends ej.Widget { static fn: Toolbar; - constructor(element: JQuery, options?: Toolbar.Model); - constructor(element: Element, options?: Toolbar.Model); + constructor(element: JQuery | Element, options?: Toolbar.Model); static Locale: any; - model:Toolbar.Model; - defaults:Toolbar.Model; + model: Toolbar.Model; + defaults: Toolbar.Model; /** Deselect the specified Toolbar item. * @param {any} The element need to be deselected @@ -17901,7 +18311,7 @@ class Toolbar extends ej.Widget { */ show(): void; } -export module Toolbar{ +export namespace Toolbar { export interface Model { @@ -17917,7 +18327,7 @@ export interface Model { /** Disables an Item or set of Items that are enabled in the Toolbar * @Default {[]} */ - disabledItemIndices?: Array; + disabledItemIndices?: any[]; /** Specifies the Toolbar control state. * @Default {true} @@ -17927,7 +18337,7 @@ export interface Model { /** Enables an Item or set of Items that are disabled in the Toolbar * @Default {[]} */ - enabledItemIndices?: Array; + enabledItemIndices?: any[]; /** Specifies enableRTL property to align the Toolbar control from right to left direction. * @Default {false} @@ -17964,6 +18374,11 @@ export interface Model { */ isResponsive?: boolean; + /** Specifies the items of Toolbar + * @Default {null} + */ + Items?: Items; + /** Specifies the Toolbar orientation. See orientation * @Default {Horizontal} */ @@ -17974,6 +18389,11 @@ export interface Model { */ query?: any; + /** Specifies the Toolbar responsive type. + * @Default {Popup} + */ + responsiveType?: ej.Toolbar.ResponsiveType|string; + /** Displays the Toolbar with rounded corners. * @Default {false} */ @@ -17984,22 +18404,28 @@ export interface Model { width?: number|string; /** Fires after Toolbar control is clicked. */ - click? (e: ClickEventArgs): void; + click?(e: ClickEventArgs): void; /** Fires after Toolbar control is created. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires after Toolbar control is focused. */ - focusOut? (e: FocusOutEventArgs): void; + focusOut?(e: FocusOutEventArgs): void; /** Fires when the Toolbar is destroyed successfully. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Fires after Toolbar control item is hovered. */ - itemHover? (e: ItemHoverEventArgs): void; + itemHover?(e: ItemHoverEventArgs): void; /** Fires after mouse leave from Toolbar control item. */ - itemLeave? (e: ItemLeaveEventArgs): void; + itemLeave?(e: ItemLeaveEventArgs): void; + + /** Fires when the overflow popup of toolbar is opened. */ + overflowOpen?(e: OverflowOpenEventArgs): void; + + /** Fires when the overflow popup of toolbar is closed. */ + overflowClose?(e: OverflowCloseEventArgs): void; } export interface ClickEventArgs { @@ -18128,6 +18554,60 @@ export interface ItemLeaveEventArgs { status?: boolean; } +export interface OverflowOpenEventArgs { + + /** if the event should be canceled; otherwise, false. + */ + cancel?: boolean; + + /** returns the Toolbar model + */ + model?: ej.Toolbar.Model; + + /** returns the name of the event + */ + type?: string; + + /** Returns the current X position of the target . + */ + clientX?: number; + + /** Returns the current Y position of the target . + */ + clientY?: number; + + /** returns the target of the current object. + */ + currentTarget?: any; +} + +export interface OverflowCloseEventArgs { + + /** if the event should be canceled; otherwise, false. + */ + cancel?: boolean; + + /** returns the Toolbar model + */ + model?: ej.Toolbar.Model; + + /** returns the name of the event + */ + type?: string; + + /** Returns the current X position of the target . + */ + clientX?: number; + + /** Returns the current Y position of the target . + */ + clientY?: number; + + /** returns the target of the current object. + */ + currentTarget?: any; +} + export interface Fields { /** Defines the group name for the item. @@ -18161,16 +18641,68 @@ export interface Fields { /** Defines the tooltip text for the tag. */ tooltipText?: string; + + /** Allows you to add template as toolbar item + */ + template?: string; } + +export interface Items { + + /** Defines the group name for the item. + */ + group?: string; + + /** Defines the HTML attributes such as id, class, styles for the item . + */ + htmlAttributes?: any; + + /** Defines id for the tag. + */ + id?: string; + + /** Defines the image attributes such as height, width, styles and so on. + */ + imageAttributes?: string; + + /** Defines the imageURL for the image location. + */ + imageUrl?: string; + + /** Defines the sprite CSS for the image tag. + */ + spriteCssClass?: string; + + /** Defines the text content for the tag. + */ + text?: string; + + /** Defines the tooltip text for the tag. + */ + tooltipText?: string; + + /** Allows to add template as toolbar item. + */ + template?: string; +} + +enum ResponsiveType { + + ///To display the toolbar overflow items as popup + Popup, + + ///To display the toolbar overflow items as inline toolbar + Inline +} + } class TreeView extends ej.Widget { static fn: TreeView; - constructor(element: JQuery, options?: TreeView.Model); - constructor(element: Element, options?: TreeView.Model); + constructor(element: JQuery | Element, options?: TreeView.Model); static Locale: any; - model:TreeView.Model; - defaults:TreeView.Model; + model: TreeView.Model; + defaults: TreeView.Model; /** To add a Node or collection of nodes in TreeView. If target tree node is specified, then the given nodes are added as child of target tree node, otherwise nodes are added in TreeView. * @param {string|any} New node text or JSON object @@ -18184,7 +18716,7 @@ class TreeView extends ej.Widget { * @param {string|any} ID of TreeView node/object of TreeView node * @returns {void} */ - addNodes(collection: any|Array, target: string|any): void; + addNodes(collection: any|any[], target: string|any): void; /** To check all the nodes in TreeView. * @returns {void} @@ -18192,12 +18724,13 @@ class TreeView extends ej.Widget { checkAll(): void; /** To check a node in TreeView. - * @param {string|any} ID of TreeView node/object of TreeView node + * @param {string|any|Array} ID of TreeView node/object of TreeView node/collection of ID/object of TreeView nodes * @returns {void} */ - checkNode(element: string|any): void; + checkNode(element: string|any|any[]): void; - /** This method is used to collapse all nodes in TreeView control. If you want to collapse all nodes up to the specific level in TreeView control then we need to pass levelUntil as argument to this method. + /** This method is used to collapse all nodes in TreeView control. If you want to collapse all nodes up to the specific level in + * TreeView control then we need to pass levelUntil as argument to this method. * @param {number} TreeView nodes will collapse until the given level * @param {boolean} Weather exclude the hidden nodes of TreeView while collapse all nodes * @returns {void} @@ -18205,22 +18738,22 @@ class TreeView extends ej.Widget { collapseAll(levelUntil?: number, excludeHiddenNodes?: boolean): void; /** To collapse a particular node in TreeView. - * @param {string|any} ID of TreeView node|object of TreeView node + * @param {string|any|Array} ID of TreeView node|object of TreeView node/collection of ID/object of TreeView nodes * @returns {void} */ - collapseNode(element: string|any): void; + collapseNode(element: string|any|any[]): void; /** To disable the node in the TreeView. - * @param {string|any} ID of TreeView node/object of TreeView node + * @param {string|any|Array} ID of TreeView node/object of TreeView node/collection of ID/object of TreeView nodes * @returns {void} */ - disableNode(element: string|any): void; + disableNode(element: string|any|any[]): void; /** To enable the node in the TreeView. - * @param {string|any} ID of TreeView node/object of TreeView node + * @param {string|any|Array} ID of TreeView node/object of TreeView node/collection of ID/object of TreeView nodes * @returns {void} */ - enableNode(element: string|any): void; + enableNode(element: string|any|any[]): void; /** To ensure that the TreeView node is visible in the TreeView. This method is useful if we need select a TreeView node dynamically. * @param {string|any} ID of TreeView node/object of TreeView node @@ -18228,7 +18761,8 @@ class TreeView extends ej.Widget { */ ensureVisible(element: string|any): boolean; - /** This method is used to expand all nodes in TreeView control. If you want to expand all nodes up to the specific level in TreeView control then we need to pass levelUntil as argument to this method. + /** This method is used to expand all nodes in TreeView control. If you want to expand all nodes up to the specific level in TreeView control + * then we need to pass levelUntil as argument to this method. * @param {number} TreeView nodes will expand until the given level * @param {boolean} Weather exclude the hidden nodes of TreeView while expand all nodes * @returns {void} @@ -18236,10 +18770,10 @@ class TreeView extends ej.Widget { expandAll(levelUntil?: number, excludeHiddenNodes?: boolean): void; /** To expandNode particular node in TreeView. - * @param {string|any} ID of TreeView node/object of TreeView node + * @param {string|any|Array} ID of TreeView node/object of TreeView node/collection of ID/object of TreeView nodes * @returns {void} */ - expandNode(element: string|any): void; + expandNode(element: string|any|any[]): void; /** To get currently checked nodes in TreeView. * @returns {any} @@ -18249,14 +18783,15 @@ class TreeView extends ej.Widget { /** To get currently checked nodes indexes in TreeView. * @returns {Array} */ - getCheckedNodesIndex(): Array; + getCheckedNodesIndex(): any[]; - /** This method is used to get immediate child nodes of a node in TreeView control. If you want to get the all child nodes include nested child nodes then we need to pass includeNestedChild as true along with element arguments to this method. + /** This method is used to get immediate child nodes of a node in TreeView control. If you want to get the all child nodes include nested + * child nodes then we need to pass includeNestedChild as true along with element arguments to this method. * @param {string|any} ID of TreeView node/object of TreeView node * @param {boolean} Weather include nested child nodes of TreeView node * @returns {Array} */ - getChildren(element: string|any, includeNestedChild?: boolean): Array; + getChildren(element: string|any, includeNestedChild?: boolean): any[]; /** To get number of nodes in TreeView. * @returns {number} @@ -18271,7 +18806,7 @@ class TreeView extends ej.Widget { /** To get currently expanded nodes indexes in TreeView. * @returns {Array} */ - getExpandedNodesIndex(): Array; + getExpandedNodesIndex(): any[]; /** To get TreeView node by using index position in TreeView. * @param {number} Index position of TreeView node @@ -18305,7 +18840,7 @@ class TreeView extends ej.Widget { /** To get the currently selected nodes in TreeView. * @returns {Array} */ - getSelectedNodes(): Array; + getSelectedNodes(): any[]; /** To get the index position of currently selected node in TreeView. * @returns {number} @@ -18315,7 +18850,7 @@ class TreeView extends ej.Widget { /** To get the index positions of currently selected nodes in TreeView. * @returns {Array} */ - getSelectedNodesIndex(): Array; + getSelectedNodesIndex(): any[]; /** To get the text of a node in TreeView. * @param {string|any} ID of TreeView node/object of TreeView node @@ -18327,7 +18862,7 @@ class TreeView extends ej.Widget { * @param {string|number} ID of TreeView node * @returns {Array} */ - getTreeData(id?: string|number): Array; + getTreeData(id?: string|number): any[]; /** To get currently visible nodes in TreeView. * @returns {any} @@ -18346,10 +18881,10 @@ class TreeView extends ej.Widget { hide(): void; /** To hide particular node in TreeView. - * @param {string|any} ID of TreeView node/object of TreeView node + * @param {string|any|Array} ID of TreeView node/object of TreeView node/collection of ID/object of TreeView nodes * @returns {void} */ - hideNode(element: string|any): void; + hideNode(element: string|any|any[]): void; /** To add a Node or collection of nodes after the particular TreeView node. * @param {string|any} New node text or JSON object @@ -18433,10 +18968,10 @@ class TreeView extends ej.Widget { removeAll(): void; /** To remove a node in TreeView. - * @param {string|any} ID of TreeView node/object of TreeView node + * @param {string|any|Array} ID of TreeView node/object of TreeView node/collection of ID/object of TreeView nodes * @returns {void} */ - removeNode(element: string|any): void; + removeNode(element: string|any|any[]): void; /** To select all the TreeView nodes when enable allowMultiSelection property. * @returns {void} @@ -18447,7 +18982,7 @@ class TreeView extends ej.Widget { * @param {string|any|Array} ID of TreeView node/object of TreeView node/ collection of ID/object of TreeView nodes * @returns {void} */ - selectNode(element: string|any|Array): void; + selectNode(element: string|any|any[]): void; /** To show nodes in TreeView. * @returns {void} @@ -18455,10 +18990,10 @@ class TreeView extends ej.Widget { show(): void; /** To show a node in TreeView. - * @param {string|any} ID of TreeView node/object of TreeView node + * @param {string|any|Array} ID of TreeView node/object of TreeView node/collection of ID/object of TreeView nodes * @returns {void} */ - showNode(element: string|any): void; + showNode(element: string|any|any[]): void; /** To uncheck all the nodes in TreeView. * @returns {void} @@ -18466,10 +19001,10 @@ class TreeView extends ej.Widget { unCheckAll(): void; /** To uncheck a node in TreeView. - * @param {string|any} ID of TreeView node/object of TreeView node + * @param {string|any|Array} ID of TreeView node/object of TreeView node/collection of ID/object of TreeView nodes * @returns {void} */ - uncheckNode(element: string|any): void; + uncheckNode(element: string|any|any[]): void; /** To unselect all the TreeView nodes when enable allowMultiSelection property. * @returns {void} @@ -18480,7 +19015,7 @@ class TreeView extends ej.Widget { * @param {string|any|Array} ID of TreeView node/object of TreeView node/ collection of ID/object of TreeView nodes * @returns {void} */ - unselectNode(element: string|any|Array): void; + unselectNode(element: string|any|any[]): void; /** To edit or update the text of the TreeView node. * @param {string|any} ID of TreeView node/object of TreeView node @@ -18489,7 +19024,7 @@ class TreeView extends ej.Widget { */ updateText(target: string|any, newText: string): void; } -export module TreeView{ +export namespace TreeView { export interface Model { @@ -18541,7 +19076,7 @@ export interface Model { /** Gets or sets a value that indicates the checkedNodes index collection as an array. The given array index position denotes the nodes, that are checked while rendering TreeView. * @Default {[]} */ - checkedNodes?: Array; + checkedNodes?: any[]; /** Sets the root CSS class for TreeView which allow us to customize the appearance. */ @@ -18575,7 +19110,7 @@ export interface Model { /** Gets or sets a array of value that indicates the expandedNodes index collection as an array. The given array index position denotes the nodes, that are expanded while rendering TreeView. * @Default {[]} */ - expandedNodes?: Array; + expandedNodes?: any[]; /** Gets or sets a value that indicates the TreeView node can be expand or collapse by using the specified action. * @Default {dblclick} @@ -18615,7 +19150,7 @@ export interface Model { /** Gets or sets a value that indicates the selectedNodes index collection as an array. The given array index position denotes the nodes, that are selected while rendering TreeView. * @Default {[]} */ - selectedNodes?: Array; + selectedNodes?: any[]; /** Gets or sets a value that indicates whether to display or hide checkbox for all TreeView nodes. * @Default {false} @@ -18637,100 +19172,100 @@ export interface Model { width?: string|number; /** Fires before adding node to TreeView. */ - beforeAdd? (e: BeforeAddEventArgs): void; + beforeAdd?(e: BeforeAddEventArgs): void; /** Fires before collapse a node. */ - beforeCollapse? (e: BeforeCollapseEventArgs): void; + beforeCollapse?(e: BeforeCollapseEventArgs): void; /** Fires before cut node in TreeView. */ - beforeCut? (e: BeforeCutEventArgs): void; + beforeCut?(e: BeforeCutEventArgs): void; /** Fires before deleting node in TreeView. */ - beforeDelete? (e: BeforeDeleteEventArgs): void; + beforeDelete?(e: BeforeDeleteEventArgs): void; /** Fires before editing the node in TreeView. */ - beforeEdit? (e: BeforeEditEventArgs): void; + beforeEdit?(e: BeforeEditEventArgs): void; /** Fires before expanding the node. */ - beforeExpand? (e: BeforeExpandEventArgs): void; + beforeExpand?(e: BeforeExpandEventArgs): void; /** Fires before loading nodes to TreeView. */ - beforeLoad? (e: BeforeLoadEventArgs): void; + beforeLoad?(e: BeforeLoadEventArgs): void; /** Fires before paste node in TreeView. */ - beforePaste? (e: BeforePasteEventArgs): void; + beforePaste?(e: BeforePasteEventArgs): void; /** Fires before selecting node in TreeView. */ - beforeSelect? (e: BeforeSelectEventArgs): void; + beforeSelect?(e: BeforeSelectEventArgs): void; /** Fires when TreeView created successfully. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires when TreeView destroyed successfully. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Fires before nodeEdit Successful. */ - inlineEditValidation? (e: InlineEditValidationEventArgs): void; + inlineEditValidation?(e: InlineEditValidationEventArgs): void; /** Fires when key pressed successfully. */ - keyPress? (e: KeyPressEventArgs): void; + keyPress?(e: KeyPressEventArgs): void; /** Fires when data load fails. */ - loadError? (e: LoadErrorEventArgs): void; + loadError?(e: LoadErrorEventArgs): void; /** Fires when data loaded successfully. */ - loadSuccess? (e: LoadSuccessEventArgs): void; + loadSuccess?(e: LoadSuccessEventArgs): void; /** Fires once node added successfully. */ - nodeAdd? (e: NodeAddEventArgs): void; + nodeAdd?(e: NodeAddEventArgs): void; /** Fires once node checked successfully. */ - nodeCheck? (e: NodeCheckEventArgs): void; + nodeCheck?(e: NodeCheckEventArgs): void; /** Fires when node clicked successfully. */ - nodeClick? (e: NodeClickEventArgs): void; + nodeClick?(e: NodeClickEventArgs): void; /** Fires when node collapsed successfully. */ - nodeCollapse? (e: NodeCollapseEventArgs): void; + nodeCollapse?(e: NodeCollapseEventArgs): void; /** Fires when node cut successfully. */ - nodeCut? (e: NodeCutEventArgs): void; + nodeCut?(e: NodeCutEventArgs): void; /** Fires when node deleted successfully. */ - nodeDelete? (e: NodeDeleteEventArgs): void; + nodeDelete?(e: NodeDeleteEventArgs): void; /** Fires when node dragging. */ - nodeDrag? (e: NodeDragEventArgs): void; + nodeDrag?(e: NodeDragEventArgs): void; /** Fires once node drag start successfully. */ - nodeDragStart? (e: NodeDragStartEventArgs): void; + nodeDragStart?(e: NodeDragStartEventArgs): void; /** Fires before the dragged node to be dropped. */ - nodeDragStop? (e: NodeDragStopEventArgs): void; + nodeDragStop?(e: NodeDragStopEventArgs): void; /** Fires once node dropped successfully. */ - nodeDropped? (e: NodeDroppedEventArgs): void; + nodeDropped?(e: NodeDroppedEventArgs): void; /** Fires once node edited successfully. */ - nodeEdit? (e: NodeEditEventArgs): void; + nodeEdit?(e: NodeEditEventArgs): void; /** Fires once node expanded successfully. */ - nodeExpand? (e: NodeExpandEventArgs): void; + nodeExpand?(e: NodeExpandEventArgs): void; /** Fires once node pasted successfully. */ - nodePaste? (e: NodePasteEventArgs): void; + nodePaste?(e: NodePasteEventArgs): void; /** Fires when node selected successfully. */ - nodeSelect? (e: NodeSelectEventArgs): void; + nodeSelect?(e: NodeSelectEventArgs): void; /** Fires once node unchecked successfully. */ - nodeUncheck? (e: NodeUncheckEventArgs): void; + nodeUncheck?(e: NodeUncheckEventArgs): void; /** Fires once node unselected successfully. */ - nodeUnselect? (e: NodeUnselectEventArgs): void; + nodeUnselect?(e: NodeUnselectEventArgs): void; /** Fires when TreeView nodes are loaded successfully */ - ready? (e: ReadyEventArgs): void; + ready?(e: ReadyEventArgs): void; } export interface BeforeAddEventArgs { @@ -18866,7 +19401,7 @@ export interface BeforeDeleteEventArgs { /** returns the currently removed nodes */ - removedNodes?: Array; + removedNodes?: any[]; } export interface BeforeEditEventArgs { @@ -19221,11 +19756,11 @@ export interface NodeCheckEventArgs { /** it returns the currently checked node name */ - currentNode?: Array; + currentNode?: any[]; /** it returns the currently checked and its child node details */ - currentCheckedNodes?: Array; + currentCheckedNodes?: any[]; } export interface NodeClickEventArgs { @@ -19357,7 +19892,7 @@ export interface NodeDeleteEventArgs { /** returns the currently removed nodes */ - removedNodes?: Array; + removedNodes?: any[]; } export interface NodeDragEventArgs { @@ -19657,7 +20192,7 @@ export interface NodeSelectEventArgs { /** returns the current selected nodes index of TreeView */ - selectedNodes?: Array; + selectedNodes?: any[]; /** returns the value of the node */ @@ -19712,7 +20247,7 @@ export interface NodeUncheckEventArgs { /** it returns currently unchecked node and its child node details. */ - currentUncheckedNodes?: Array; + currentUncheckedNodes?: any[]; } export interface NodeUnselectEventArgs { @@ -19739,7 +20274,7 @@ export interface NodeUnselectEventArgs { /** returns the current selected nodes index of TreeView */ - selectedNodes?: Array; + selectedNodes?: any[]; /** returns the name of the event */ @@ -19791,7 +20326,7 @@ export interface Fields { */ id?: string; - /** Specifies the image attribute to “img” tag inside items list + /** Specifies the image attribute to “img” tag inside items list */ imageAttribute?: any; @@ -19803,7 +20338,7 @@ export interface Fields { */ isChecked?: string; - /** Specifies the link attribute to “a” tag in item list. + /** Specifies the link attribute to “a” tag in item list. */ linkAttribute?: any; @@ -19845,8 +20380,7 @@ export interface SortSettings { sortOrder?: ej.sortOrder|string; } } -enum sortOrder -{ +enum sortOrder { //Enum for Ascending sort order Ascending, //Enum for Descending sort order @@ -19855,11 +20389,10 @@ Descending, class Uploadbox extends ej.Widget { static fn: Uploadbox; - constructor(element: JQuery, options?: Uploadbox.Model); - constructor(element: Element, options?: Uploadbox.Model); + constructor(element: JQuery | Element, options?: Uploadbox.Model); static Locale: any; - model:Uploadbox.Model; - defaults:Uploadbox.Model; + model: Uploadbox.Model; + defaults: Uploadbox.Model; /** The destroy method destroys the control and brings the control to a pre-init state. All the events of the Upload control is bound by using this._on unbinds automatically. * @returns {void} @@ -19881,7 +20414,7 @@ class Uploadbox extends ej.Widget { */ refresh(): void; } -export module Uploadbox{ +export namespace Uploadbox { export interface Model { @@ -20025,37 +20558,37 @@ export interface Model { width?: string; /** Fires when the upload progress beforeSend. */ - beforeSend? (e: BeforeSendEventArgs): void; + beforeSend?(e: BeforeSendEventArgs): void; /** Fires when the upload progress begins. */ - begin? (e: BeginEventArgs): void; + begin?(e: BeginEventArgs): void; /** Fires when the upload progress is cancelled. */ - cancel? (e: CancelEventArgs): void; + cancel?(e: CancelEventArgs): void; /** Fires when the file upload progress is completed. */ - complete? (e: CompleteEventArgs): void; + complete?(e: CompleteEventArgs): void; /** Fires when the file upload progress is succeeded. */ - success? (e: SuccessEventArgs): void; + success?(e: SuccessEventArgs): void; /** Fires when the Uploadbox control is created. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires when the Uploadbox control is destroyed. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Fires when the Upload process ends in Error. */ - error? (e: ErrorEventArgs): void; + error?(e: ErrorEventArgs): void; /** Fires when the file is selected for upload successfully. */ - fileSelect? (e: FileSelectEventArgs): void; + fileSelect?(e: FileSelectEventArgs): void; /** Fires when the file is uploading. */ - inProgress? (e: InProgressEventArgs): void; + inProgress?(e: InProgressEventArgs): void; /** Fires when the uploaded file is removed successfully. */ - remove? (e: RemoveEventArgs): void; + remove?(e: RemoveEventArgs): void; } export interface BeforeSendEventArgs { @@ -20331,14 +20864,14 @@ export interface DialogAction { */ drag?: boolean; - /** Enables or disables the Uploadbox dialog’s modal property to the dialog popup. + /** Enables or disables the Uploadbox dialog’s modal property to the dialog popup. */ modal?: boolean; } export interface DialogText { - /** Sets the uploaded file’s Name (header text) to the Dialog popup. + /** Sets the uploaded file’s Name (header text) to the Dialog popup. */ name?: string; @@ -20358,11 +20891,10 @@ export interface DialogText { class WaitingPopup extends ej.Widget { static fn: WaitingPopup; - constructor(element: JQuery, options?: WaitingPopup.Model); - constructor(element: Element, options?: WaitingPopup.Model); + constructor(element: JQuery | Element, options?: WaitingPopup.Model); static Locale: any; - model:WaitingPopup.Model; - defaults:WaitingPopup.Model; + model: WaitingPopup.Model; + defaults: WaitingPopup.Model; /** To hide the waiting popup * @returns {void} @@ -20379,7 +20911,7 @@ class WaitingPopup extends ej.Widget { */ show(): void; } -export module WaitingPopup{ +export namespace WaitingPopup { export interface Model { @@ -20424,10 +20956,10 @@ export interface Model { text?: string; /** Fires after Create WaitingPopup successfully */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires after Destroy WaitingPopup successfully */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; } export interface CreateEventArgs { @@ -20463,29 +20995,28 @@ export interface DestroyEventArgs { class Grid extends ej.Widget { static fn: Grid; - constructor(element: JQuery, options?: Grid.Model); - constructor(element: Element, options?: Grid.Model); + constructor(element: JQuery | Element, options?: Grid.Model); static Locale: any; - model:Grid.Model; - defaults:Grid.Model; + model: Grid.Model; + defaults: Grid.Model; /** Adds a grid model property which is to be ignored upon exporting. * @param {Array} Pass the array of parameters which need to be ignored on exporting * @returns {void} */ - addIgnoreOnExport(propertyNames: Array): void; + addIgnoreOnExport(propertyNames: any[]): void; /** Add a new record in grid control when allowAdding is set as true. * @returns {void} */ - addRecord(): void; + //addRecord(): void; /** Add a new record in grid control when allowAdding is set as true. * @param {Array} Pass the array of added Records * @param {Array} optionalIf we pass serverChange as true, send post to server side for server action. * @returns {void} */ - addRecord(data: Array, serverChange?: Array): void; + addRecord(data: any[], serverChange?: any[]): void; /** Cancel the modified changes in grid control when edit mode is "batch". * @returns {void} @@ -20510,20 +21041,20 @@ class Grid extends ej.Widget { /** It is used to clear all the cell selection. * @returns {Boolean} */ - clearCellSelection(): Boolean; + clearCellSelection(): boolean; /** It is used to clear specified cell selection based on the rowIndex and columnIndex provided. * @param {number} It is used to pass the row index of the cell * @param {number} It is used to pass the column index of the cell. * @returns {Boolean} */ - clearCellSelection(rowIndex: number, columnIndex: number): Boolean; + clearCellSelection(rowIndex: number, columnIndex: number): boolean; /** It is used to clear all the row selection or at specific row selection based on the index provided. * @param {number} optional If index of the column is specified then it will remove the selection from the particular column else it will clears all of the column selection * @returns {Boolean} */ - clearColumnSelection(index?: number): Boolean; + clearColumnSelection(index?: number): boolean; /** It is used to clear all the filtering done. * @param {string} If field of the column is specified then it will clear the particular filtering column @@ -20540,7 +21071,7 @@ class Grid extends ej.Widget { * @param {number} optional If index of the row is specified then it will remove the selection from the particular row else it will clears all of the row selection * @returns {Boolean} */ - clearSelection(index?: number): Boolean; + clearSelection(index?: number): boolean; /** Clear the sorting from columns in the grid * @returns {void} @@ -20562,21 +21093,27 @@ class Grid extends ej.Widget { * @param {string} optional Pass add/remove action to be performed. By default "add" action will perform * @returns {void} */ - columns(columnDetails: Array|string, action?: string): void; + columns(columnDetails: any[]|string, action?: string): void; /** Refresh the grid with new data source * @param {Array} Pass new data source to the grid * @param {boolean} optional When templateRefresh is set true, both header and contents get refreshed * @returns {void} */ - dataSource(datasource: Array, templateRefresh?: boolean): void; + dataSource(datasource: any[], templateRefresh?: boolean): void; /** Delete a record in grid control when allowDeleting is set as true * @param {string} Pass the primary key field Name of the column * @param {Array} Pass the JSON data of record need to be delete. * @returns {void} */ - deleteRecord(fieldName: string, data: Array): void; + deleteRecord(fieldName: string, data: any[]): void; + + /** Delete the row based on the given tr element in grid. + * @param {JQuery} Pass the tr element in grid content to get its row index + * @returns {HTMLElement} + */ + deleteRow($tr: JQuery): HTMLElement; /** Destroy the grid widget all events bound using this._on will be unbind automatically and bring the control to pre-init state. * @returns {void} @@ -20590,6 +21127,11 @@ class Grid extends ej.Widget { */ editCell(index: number, fieldName: string): void; + /** It returns a value and if the input field values of edit form is not based on the validation rules then it will show the validation message. + * @returns {Boolean} + */ + editFormValidate(): boolean; + /** Send a save request in grid. * @returns {void} */ @@ -20618,15 +21160,7 @@ class Grid extends ej.Widget { * @param {Array} optionalPass the array of the gridIds to be filtered * @returns {void} */ - export(action: string, serverEvent?: string, multipleExport?: boolean, gridIds?: Array): void; - - /** Export the grid content to excel, word or PDF document. - * @param {string} Pass the controller action name corresponding to exporting - * @param {string} optionalASP server event name corresponding to exporting - * @param {boolean} optionalPass the multiple exporting value as true/false - * @returns {void} - */ - export(action: string, serverEvent?: string, multipleExport?: boolean): void; + export(action: string, serverEvent?: string, multipleExport?: boolean, gridIds?: any[]): void; /** Send a filtering request to filter one column in grid. * @param {Array} Pass the field name of the column @@ -20637,13 +21171,13 @@ class Grid extends ej.Widget { * @param {any} optionalactualFilterValue denote the filter object of current filtered columns.Pass the value to filtered in a column * @returns {void} */ - filterColumn(fieldName: Array, filterOperator: string, filterValue: string, predicate: string, matchcase?: boolean, actualFilterValue?: any): void; + filterColumn(fieldName: any[], filterOperator: string, filterValue: string, predicate: string, matchcase?: boolean, actualFilterValue?: any): void; /** Send a filtering request to filter single or multiple column in grid. * @param {Array} Pass array of filterColumn query for performing filter operation * @returns {void} */ - filterColumn(filterQueries: Array): void; + filterColumn(filterQueries: any[]): void; /** Get the batch changes of edit, delete and add operations of grid. * @returns {any} @@ -20676,7 +21210,7 @@ class Grid extends ej.Widget { /** Get the list of field names from column collection in grid. * @returns {Array} */ - getColumnFieldNames(): Array; + getColumnFieldNames(): any[]; /** Get the column index of the given field in grid. * @param {string} Pass the field name of the column to get the corresponding column index @@ -20684,6 +21218,13 @@ class Grid extends ej.Widget { */ getColumnIndexByField(fieldName: string): number; + /** Get the column index of the given headerText of column in grid. + * @param {string} Pass the headerText of the column to get that column index + * @param {string} optionalOptional Pass the field name of the column. + * @returns {number} + */ + getColumnIndexByHeaderText(headerText: string, field?: string): number; + /** Get the content div element of grid. * @returns {HTMLElement} */ @@ -20692,7 +21233,7 @@ class Grid extends ej.Widget { /** Get the content table element of grid * @returns {Array} */ - getContentTable(): Array; + getContentTable(): HTMLTableElement[]; /** Get the data of currently edited cell value in "batch" edit mode * @returns {any} @@ -20707,13 +21248,18 @@ class Grid extends ej.Widget { /** Get the current page data source of grid. * @returns {Array} */ - getCurrentViewData(): Array; + getCurrentViewData(): any[]; + + /** Get the data of given row index in grid. + * @returns {any} + */ + getDataByIndex(): any; /** Get the column field name from the given header text in grid. * @param {string} Pass header text of the column to get its corresponding field name * @returns {String} */ - getFieldNameByHeaderText(headerText: string): String; + getFieldNameByHeaderText(headerText: string): string; /** Get the filter bar of grid * @returns {HTMLElement} @@ -20723,7 +21269,7 @@ class Grid extends ej.Widget { /** Get the records filtered or searched in Grid * @returns {Array} */ - getFilteredRecords(): Array; + getFilteredRecords(): any[]; /** Get the footer content of grid. * @returns {HTMLElement} @@ -20749,12 +21295,12 @@ class Grid extends ej.Widget { * @param {string} Pass field name of the column to get its corresponding header text * @returns {String} */ - getHeaderTextByFieldName(field: string): String; + getHeaderTextByFieldName(field: string): string; /** Get the names of all the hidden column collections in grid. * @returns {Array} */ - getHiddenColumnNames(): Array; + getHiddenColumnNames(): any[]; /** Get the row index based on the given tr element in grid. * @param {JQuery} Pass the tr element in grid content to get its row index @@ -20770,7 +21316,7 @@ class Grid extends ej.Widget { /** Get the names of primary key columns in Grid * @returns {Array} */ - getPrimaryKeyFieldNames(): Array; + getPrimaryKeyFieldNames(): any[]; /** Get the rows(tr element) from the given from and to row index in grid * @param {number} Pass the from index from which the rows to be returned @@ -20797,19 +21343,30 @@ class Grid extends ej.Widget { /** Get the selected records details in grid. * @returns {Array} */ - getSelectedRecords(): Array; + getSelectedRecords(): any[]; + + /** Get the selected row element details in grid. + * @returns {Array} + */ + getSelectedRows(): any[]; + + /** It accepts the string value and returns the field and sorted direction of the column in grid. + * @param {string} Pass the field of the column to get the sorted direction of the corresponding column in Grid. + * @returns {number} + */ + getsortColumnByField(field: string): number; /** Get the calculated summary values of JSON data passed to it * @param {any} Pass Summary Column details * @param {any} Pass JSON Array for which its field values to be calculated * @returns {Number} */ - getSummaryValues(summaryCol: any, summaryData: any): Number; + getSummaryValues(summaryCol: any, summaryData: any): number; /** Get the names of all the visible column collections in grid * @returns {Array} */ - getVisibleColumnNames(): Array; + getVisibleColumnNames(): any[]; /** Send a paging request to specified page in grid * @param {number} Pass the page index to perform paging at specified page index @@ -20827,7 +21384,7 @@ class Grid extends ej.Widget { * @param {Array|string} you can pass either array of header text of various columns or a header text of a column to hide * @returns {void} */ - hideColumns(headerText: Array|string): void; + hideColumns(headerText: any[]|string): void; /** Print the grid control * @returns {void} @@ -20839,6 +21396,11 @@ class Grid extends ej.Widget { */ refreshBatchEditChanges(): void; + /** It is used to refresh the grid header. + * @returns {void} + */ + refreshHeader(): void; + /** Refresh the grid contents. The template refreshment is based on the argument passed along with this method * @param {boolean} optional When templateRefresh is set true, template and grid contents both are refreshed in grid else only grid content is refreshed * @returns {void} @@ -20859,7 +21421,7 @@ class Grid extends ej.Widget { * @param {Array|string} Pass array of field names of the columns to remove a collection of sorted columns or pass a string of field name to remove a column from sorted column collections * @returns {void} */ - removeSortedColumns(fieldName: Array|string): void; + removeSortedColumns(fieldName: any[]|string): void; /** Creates a grid control * @returns {void} @@ -20873,6 +21435,13 @@ class Grid extends ej.Widget { */ reorderColumns(fromFieldName: string, toFieldName: string): void; + /** Re-order the row in grid + * @param {Array} Pass the indexes of the rows needs to reorder. + * @param {number} Pass the index of a row where to be reorderd. + * @returns {void} + */ + reorderRows(indexes: any[], toindex: number): void; + /** Reset the model collections like pageSettings, groupSettings, filterSettings, sortSettings and summaryRows. * @returns {void} */ @@ -20893,7 +21462,7 @@ class Grid extends ej.Widget { /** Save the particular edited cell in grid. * @returns {void} */ - saveCell(): void; + //saveCell(): void; /** We can prevent the client side cellSave event triggering by passing the preventSaveEvent argument as true. * @param {boolean} optionalIf we pass preventSaveEvent as true, it prevents the client side cellSave event triggering @@ -20936,7 +21505,7 @@ class Grid extends ej.Widget { * @param {number} optionalIt is used to set the ending index of column for selecting columns. * @returns {Boolean} */ - selectColumns(columnIndex: number, toIndex?: number): Boolean; + selectColumns(columnIndex: number, toIndex?: number): boolean; /** Select rows in grid. * @param {number} It is used to set the starting index of row for selecting rows. @@ -20951,13 +21520,13 @@ class Grid extends ej.Widget { * @param {any} optionalTarget element which is clicked. * @returns {void} */ - selectRows(from: Array|number, to: number, target?: any): void; + selectRows(from: any[]|number, to: number, target?: any): void; /** Select rows in grid. * @param {Array} Pass array of rowIndexes for selecting rows * @returns {void} */ - selectRows(rowIndexes: Array): void; + selectRows(rowIndexes: any[]): void; /** Used to update a particular cell value. * @returns {void} @@ -20972,6 +21541,11 @@ class Grid extends ej.Widget { */ setCellValue(Index: number, fieldName: string, value: any): void; + /** It sets the default data to the column in grid during adding record in batch edit mode. + * @returns {void} + */ + setDefaultData(): void; + /** The grid rows has to be rendered as detail view in mobile mode based on given value. * @param {number} It is used to render grid rows as details view in mobile mode. * @returns {void} @@ -20989,7 +21563,7 @@ class Grid extends ej.Widget { * @param {Array|string} you can pass either array of header text of various columns or a header text of a column to show * @returns {void} */ - showColumns(headerText: Array|string): void; + showColumns(headerText: any[]|string): void; /** Send a sorting request in grid. * @param {string} Pass the field name of the column as columnName for which sorting have to be performed @@ -21015,100 +21589,105 @@ class Grid extends ej.Widget { * @param {Array} Pass the edited JSON data of record need to be update. * @returns {void} */ - updateRecord(fieldName: string, data: Array): void; + updateRecord(fieldName: string, data: any[]): void; /** It adapts grid to its parent element or to the browsers window. * @returns {void} */ windowonresize(): void; } -export module Grid{ +export namespace Grid { export interface Model { /** Gets or sets a value that indicates whether to customizing cell based on our needs. * @Default {false} */ - allowCellMerging?: Boolean; + allowCellMerging?: boolean; - /** Gets or sets a value that indicates whether to enable dynamic grouping behavior. Grouping can be done by drag on drop desired columns to grid’s GroupDropArea. This can be further customized through “groupSettings” property. + /** Gets or sets a value that indicates whether to enable dynamic grouping behavior. Grouping can be done by drag on drop desired columns to grid’s GroupDropArea. + * This can be further customized through “groupSettings” property. * @Default {false} */ - allowGrouping?: Boolean; + allowGrouping?: boolean; - /** Gets or sets a value that indicates whether to enable keyboard support for performing grid actions. selectionType – Gets or sets a value that indicates whether to enable single row or multiple rows selection behavior in grid. Multiple selection can be done through by holding CTRL and clicking the grid rows + /** Gets or sets a value that indicates whether to enable keyboard support for performing grid actions. selectionType – Gets or sets a value that indicates whether to enable single + * row or multiple rows selection behavior in grid. Multiple selection can be done through by holding CTRL and clicking the grid rows * @Default {true} */ - allowKeyboardNavigation?: Boolean; + allowKeyboardNavigation?: boolean; - /** Gets or sets a value that indicates whether to enable dynamic filtering behavior on grid. Filtering can be used to limit the records displayed using required criteria and this can be further customized through “filterSettings” property + /** Gets or sets a value that indicates whether to enable dynamic filtering behavior on grid. Filtering can be used to limit the records displayed using required criteria and + * this can be further customized through “filterSettings” property * @Default {false} */ - allowFiltering?: Boolean; + allowFiltering?: boolean; /** Gets or sets a value that indicates whether to enable the dynamic sorting behavior on grid data. Sorting can be done through clicking on particular column header. * @Default {false} */ - allowSorting?: Boolean; + allowSorting?: boolean; /** Gets or sets a value that indicates whether to enable multi columns sorting behavior in grid. Sort multiple columns by holding CTRL and click on the corresponding column header. * @Default {false} */ - allowMultiSorting?: Boolean; + allowMultiSorting?: boolean; - /** This specifies the grid to show the paginated data. Also enables pager control at the bottom of grid for dynamic navigation through data source. Paging can be further customized through “pageSettings” property. + /** This specifies the grid to show the paginated data. Also enables pager control at the bottom of grid for dynamic navigation through data source. + * Paging can be further customized through “pageSettings” property. * @Default {false} */ - allowPaging?: Boolean; + allowPaging?: boolean; - /** Gets or sets a value that indicates whether to enable the columns reordering behavior in the grid. Reordering can be done through by drag and drop the particular column from one index to another index within the grid. + /** Gets or sets a value that indicates whether to enable the columns reordering behavior in the grid. Reordering can be done through by drag and drop the particular column + * from one index to another index within the grid. * @Default {false} */ - allowReordering?: Boolean; + allowReordering?: boolean; /** Gets or sets a value that indicates whether the column is non resizable. Column width is set automatically based on the content or header text which is large. * @Default {false} */ - allowResizeToFit?: Boolean; + allowResizeToFit?: boolean; /** Gets or sets a value that indicates whether to enable dynamic resizable of columns. Resize the width of the columns by simply click and move the particular column header line * @Default {false} */ - allowResizing?: Boolean; + allowResizing?: boolean; /** Gets or sets a value that indicates whether to enable the rows reordering in Grid and drag & drop rows between multiple Grid. * @Default {false} */ - allowRowDragAndDrop?: Boolean; + allowRowDragAndDrop?: boolean; /** Gets or sets a value that indicates whether to enable the scrollbar in the grid and view the records by scroll through the grid manually * @Default {false} */ - allowScrolling?: Boolean; + allowScrolling?: boolean; - /** Gets or sets a value that indicates whether to enable dynamic searching behavior in grid. Currently search box can be enabled through “toolbarSettings” + /** Gets or sets a value that indicates whether to enable dynamic searching behavior in grid. Currently search box can be enabled through “toolbarSettings” * @Default {false} */ - allowSearching?: Boolean; + allowSearching?: boolean; /** Gets or sets a value that indicates whether user can select rows on grid. On enabling feature, selected row will be highlighted. * @Default {true} */ - allowSelection?: Boolean; + allowSelection?: boolean; /** Gets or sets a value that indicates whether the Content will wrap to the next line if the content exceeds the boundary of the Column Cells. * @Default {false} */ - allowTextWrap?: Boolean; + allowTextWrap?: boolean; /** Gets or sets a value that indicates whether to enable the multiple exporting behavior on grid data. * @Default {false} */ - allowMultipleExporting?: Boolean; + allowMultipleExporting?: boolean; /** Gets or sets a value that indicates to define common width for all the columns in the grid. */ - commonWidth?: Number; + commonWidth?: number; /** Gets or sets a value that indicates to enable the visibility of the grid lines. * @Default {ej.Grid.GridLines.Both} @@ -21128,7 +21707,7 @@ export interface Model { /** Gets or sets an object that indicates to render the grid with specified columns * @Default {[]} */ - columns?: Array; + columns?: Column[]; /** Gets or sets an object that indicates whether to customize the context menu behavior of the grid. */ @@ -21136,7 +21715,7 @@ export interface Model { /** Gets or sets a value that indicates to render the grid with custom theme. */ - cssClass?: String; + cssClass?: string; /** Gets or sets the data to render the grid with records * @Default {null} @@ -21146,7 +21725,7 @@ export interface Model { /** Default Value: * @Default {null} */ - detailsTemplate?: String; + detailsTemplate?: string; /** Gets or sets an object that indicates whether to customize the editing behavior of the grid. */ @@ -21155,42 +21734,62 @@ export interface Model { /** Gets or sets a value that indicates whether to enable the alternative rows differentiation in the grid records based on corresponding theme. * @Default {true} */ - enableAltRow?: Boolean; + enableAltRow?: boolean; /** Gets or sets a value that indicates whether to enable the save action in the grid through row selection * @Default {true} */ - enableAutoSaveOnSelectionChange?: Boolean; + enableAutoSaveOnSelectionChange?: boolean; /** Gets or sets a value that indicates whether to enable mouse over effect on the corresponding column header cell of the grid * @Default {false} */ - enableHeaderHover?: Boolean; + enableHeaderHover?: boolean; /** Gets or sets a value that indicates whether to persist the grid model state in page using applicable medium i.e., HTML5 localStorage or cookies * @Default {false} */ - enablePersistence?: Boolean; + enablePersistence?: boolean; /** Gets or sets a value that indicates whether the grid rows has to be rendered as detail view in mobile mode * @Default {false} */ - enableResponsiveRow?: Boolean; + enableResponsiveRow?: boolean; /** Gets or sets a value that indicates whether to enable mouse over effect on corresponding grid row. * @Default {true} */ - enableRowHover?: Boolean; + enableRowHover?: boolean; /** Align content in the grid control from right to left by setting the property as true. * @Default {false} */ - enableRTL?: Boolean; + enableRTL?: boolean; /** To Disable the mouse swipe property as false. * @Default {true} */ - enableTouch?: Boolean; + enableTouch?: boolean; + + /** It sets a value that indicates whether to enable toolbar items, when allowEditing, allowAdding and allowDeleting property set as false in the grid. + * @Default {false} + */ + enableToolbarItems?: boolean; + + /** Act as mapper for the excel exporting URL. + * @Default {ExportToExcel} + */ + exportToExcelAction?: string; + + /** Act as mapper for the PDF exporting URL. + * @Default {ExportToPdf} + */ + exportToPdfAction?: string; + + /** Act as mapper for the Word exporting URL. + * @Default {ExportToWord} + */ + exportToWordAction?: string; /** Gets or sets an object that indicates whether to customize the filtering behavior of the grid */ @@ -21203,22 +21802,23 @@ export interface Model { /** Gets or sets a value that indicates whether the grid design has be to made responsive. * @Default {false} */ - isResponsive?: Boolean; + isResponsive?: boolean; /** This specifies to change the key in keyboard interaction to grid control * @Default {null} */ keySettings?: any; - /** Gets or sets a value that indicates whether to customizing the user interface (UI) as locale-specific in order to display regional data i.e. in a language and culture specific to a particular country or region. + /** Gets or sets a value that indicates whether to customizing the user interface (UI) as locale-specific in order to display regional data i.e. in a language and + * culture specific to a particular country or region. * @Default {en-US} */ - locale?: String; + locale?: string; /** Gets or sets a value that indicates whether to set the minimum width of the responsive grid while isResponsive property is true and enableResponsiveRow property is set as false. * @Default {0} */ - minWidth?: Number; + minWidth?: number; /** Gets or sets an object that indicates whether to modify the pager default configuration. */ @@ -21233,10 +21833,11 @@ export interface Model { */ resizeSettings?: ResizeSettings; - /** Gets or sets a value that indicates to render the grid with template rows. The template row must be a table row. That table row must have the JavaScript render binding format ({{:columnName}}) then the grid data source binds the data to the corresponding table row of the template. + /** Gets or sets a value that indicates to render the grid with template rows. The template row must be a table row. That table row must have the JavaScript render binding format ({{:columnName}}) + * then the grid data source binds the data to the corresponding table row of the template. * @Default {null} */ - rowTemplate?: String; + rowTemplate?: string; /** Gets or sets an object that indicates whether to customize the drag and drop behavior of the grid rows */ @@ -21246,20 +21847,21 @@ export interface Model { */ searchSettings?: SearchSettings; - /** Gets a value that indicates whether the grid model to hold multiple selected records . selectedRecords can be used to displayed hold the single or multiple selected records using “selectedRecords” property + /** Gets a value that indicates whether the grid model to hold multiple selected records . selectedRecords can be used to displayed hold the single + * or multiple selected records using “selectedRecords” property * @Default {null} */ - selectedRecords?: Array; + selectedRecords?: any[]; /** Gets or sets a value that indicates to select the row while initializing the grid * @Default {-1} */ - selectedRowIndex?: Number; + selectedRowIndex?: number; /** Gets or sets a value that indicates the selected rows in grid * @Default {[]} */ - selectedRowIndices?: Array; + selectedRowIndices?: any[]; /** This property is used to configure the selection behavior of the grid. */ @@ -21277,17 +21879,17 @@ export interface Model { /** Default Value: * @Default {false} */ - showColumnChooser?: Boolean; + showColumnChooser?: boolean; - /** Gets or sets a value that indicates stacked header should be shown on grid layout when the property “stackedHeaderRows” is set. + /** Gets or sets a value that indicates stacked header should be shown on grid layout when the property “stackedHeaderRows” is set. * @Default {false} */ - showStackedHeader?: Boolean; + showStackedHeader?: boolean; - /** Gets or sets a value that indicates summary rows should be shown on grid layout when the property “summaryRows” is set + /** Gets or sets a value that indicates summary rows should be shown on grid layout when the property “summaryRows” is set * @Default {false} */ - showSummary?: Boolean; + showSummary?: boolean; /** Gets or sets a value that indicates whether to customize the sorting behavior of the grid. */ @@ -21296,12 +21898,12 @@ export interface Model { /** Gets or sets an object that indicates to managing the collection of stacked header rows for the grid. * @Default {[]} */ - stackedHeaderRows?: Array; + stackedHeaderRows?: StackedHeaderRow[]; /** Gets or sets an object that indicates to managing the collection of summary rows for the grid. * @Default {[]} */ - summaryRows?: Array; + summaryRows?: SummaryRow[]; /** Gets or sets an object that indicates whether to auto wrap the grid header or content or both */ @@ -21312,142 +21914,166 @@ export interface Model { toolbarSettings?: ToolbarSettings; /** Triggered for every grid action before its starts. */ - actionBegin? (e: ActionBeginEventArgs): void; + actionBegin?(e: ActionBeginEventArgs): void; /** Triggered for every grid action success event. */ - actionComplete? (e: ActionCompleteEventArgs): void; + actionComplete?(e: ActionCompleteEventArgs): void; /** Triggered for every grid action server failure event. */ - actionFailure? (e: ActionFailureEventArgs): void; + actionFailure?(e: ActionFailureEventArgs): void; /** Triggered when record batch add. */ - batchAdd? (e: BatchAddEventArgs): void; + batchAdd?(e: BatchAddEventArgs): void; /** Triggered when record batch delete. */ - batchDelete? (e: BatchDeleteEventArgs): void; + batchDelete?(e: BatchDeleteEventArgs): void; /** Triggered before the batch add. */ - beforeBatchAdd? (e: BeforeBatchAddEventArgs): void; + beforeBatchAdd?(e: BeforeBatchAddEventArgs): void; /** Triggered before the batch delete. */ - beforeBatchDelete? (e: BeforeBatchDeleteEventArgs): void; + beforeBatchDelete?(e: BeforeBatchDeleteEventArgs): void; /** Triggered before the batch save. */ - beforeBatchSave? (e: BeforeBatchSaveEventArgs): void; + beforeBatchSave?(e: BeforeBatchSaveEventArgs): void; + + /** Triggered before the print. */ + beforePrint?(e: BeforePrintEventArgs): void; + + /** Triggered before row drop in the grid */ + beforeRowDrop?(e: BeforeRowDropEventArgs): void; /** Triggered before the record is going to be edited. */ - beginEdit? (e: BeginEditEventArgs): void; + beginEdit?(e: BeginEditEventArgs): void; /** Triggered when record cell edit. */ - cellEdit? (e: CellEditEventArgs): void; + cellEdit?(e: CellEditEventArgs): void; /** Triggered when record cell save. */ - cellSave? (e: CellSaveEventArgs): void; + cellSave?(e: CellSaveEventArgs): void; /** Triggered after the cell is selected. */ - cellSelected? (e: CellSelectedEventArgs): void; + cellSelected?(e: CellSelectedEventArgs): void; /** Triggered before the cell is going to be selected. */ - cellSelecting? (e: CellSelectingEventArgs): void; + cellSelecting?(e: CellSelectingEventArgs): void; + + /** Triggered after the cell is deselected. */ + cellDeselected?(e: CellDeselectedEventArgs): void; + + /** Triggered before the cell is going to be deselected. */ + cellDeselecting?(e: CellDeselectingEventArgs): void; /** Triggered when the column is being dragged. */ - columnDrag? (e: ColumnDragEventArgs): void; + columnDrag?(e: ColumnDragEventArgs): void; /** Triggered when column dragging begins. */ - columnDragStart? (e: ColumnDragStartEventArgs): void; + columnDragStart?(e: ColumnDragStartEventArgs): void; /** Triggered when the column is dropped. */ - columnDrop? (e: ColumnDropEventArgs): void; + columnDrop?(e: ColumnDropEventArgs): void; /** Triggered when the row is being dragged. */ - rowDrag? (e: RowDragEventArgs): void; + rowDrag?(e: RowDragEventArgs): void; /** Triggered when row dragging begins. */ - rowDragStart? (e: RowDragStartEventArgs): void; + rowDragStart?(e: RowDragStartEventArgs): void; /** Triggered when the row is dropped. */ - rowDrop? (e: RowDropEventArgs): void; + rowDrop?(e: RowDropEventArgs): void; /** Triggered after the column is selected. */ - columnSelected? (e: ColumnSelectedEventArgs): void; + columnSelected?(e: ColumnSelectedEventArgs): void; /** Triggered before the column is going to be selected. */ - columnSelecting? (e: ColumnSelectingEventArgs): void; + columnSelecting?(e: ColumnSelectingEventArgs): void; + + /** Triggered after the column is deselected. */ + columnDeselected?(e: ColumnDeselectedEventArgs): void; + + /** Triggered before the column is going to be deselected. */ + columnDeselecting?(e: ColumnDeselectingEventArgs): void; /** Triggered when context menu item is clicked */ - contextClick? (e: ContextClickEventArgs): void; + contextClick?(e: ContextClickEventArgs): void; /** Triggered before the context menu is opened. */ - contextOpen? (e: ContextOpenEventArgs): void; + contextOpen?(e: ContextOpenEventArgs): void; /** Triggered when the grid is rendered completely. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Triggered when the grid is bound with data during initial rendering. */ - dataBound? (e: DataBoundEventArgs): void; + dataBound?(e: DataBoundEventArgs): void; /** Triggered when grid going to destroy. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Triggered when detail template row is clicked to collapse. */ - detailsCollapse? (e: DetailsCollapseEventArgs): void; + detailsCollapse?(e: DetailsCollapseEventArgs): void; /** Triggered detail template row is initialized. */ - detailsDataBound? (e: DetailsDataBoundEventArgs): void; + detailsDataBound?(e: DetailsDataBoundEventArgs): void; /** Triggered when detail template row is clicked to expand. */ - detailsExpand? (e: DetailsExpandEventArgs): void; + detailsExpand?(e: DetailsExpandEventArgs): void; /** Triggered after the record is added. */ - endAdd? (e: EndAddEventArgs): void; + endAdd?(e: EndAddEventArgs): void; /** Triggered after the record is deleted. */ - endDelete? (e: EndDeleteEventArgs): void; + endDelete?(e: EndDeleteEventArgs): void; /** Triggered after the record is edited. */ - endEdit? (e: EndEditEventArgs): void; + endEdit?(e: EndEditEventArgs): void; /** Triggered initial load. */ - load? (e: LoadEventArgs): void; + load?(e: LoadEventArgs): void; /** Triggered every time a request is made to access particular cell information, element and data. */ - mergeCellInfo? (e: MergeCellInfoEventArgs): void; + mergeCellInfo?(e: MergeCellInfoEventArgs): void; /** Triggered every time a request is made to access particular cell information, element and data. */ - queryCellInfo? (e: QueryCellInfoEventArgs): void; + queryCellInfo?(e: QueryCellInfoEventArgs): void; /** Triggered when record is clicked. */ - recordClick? (e: RecordClickEventArgs): void; + recordClick?(e: RecordClickEventArgs): void; /** Triggered when record is double clicked. */ - recordDoubleClick? (e: RecordDoubleClickEventArgs): void; + recordDoubleClick?(e: RecordDoubleClickEventArgs): void; /** Triggered after column resized. */ - resized? (e: ResizedEventArgs): void; + resized?(e: ResizedEventArgs): void; /** Triggered when column resize end. */ - resizeEnd? (e: ResizeEndEventArgs): void; + resizeEnd?(e: ResizeEndEventArgs): void; /** Triggered when column resize start. */ - resizeStart? (e: ResizeStartEventArgs): void; + resizeStart?(e: ResizeStartEventArgs): void; /** Triggered when right clicked on grid element. */ - rightClick? (e: RightClickEventArgs): void; + rightClick?(e: RightClickEventArgs): void; /** Triggered every time a request is made to access row information, element and data. */ - rowDataBound? (e: RowDataBoundEventArgs): void; + rowDataBound?(e: RowDataBoundEventArgs): void; /** Triggered after the row is selected. */ - rowSelected? (e: RowSelectedEventArgs): void; + rowSelected?(e: RowSelectedEventArgs): void; /** Triggered before the row is going to be selected. */ - rowSelecting? (e: RowSelectingEventArgs): void; + rowSelecting?(e: RowSelectingEventArgs): void; + + /** Triggered after the row is deselected. */ + rowDeselected?(e: RowDeselectedEventArgs): void; + + /** Triggered before the row is going to be deselected. */ + rowDeselecting?(e: RowDeselectingEventArgs): void; /** Triggered when refresh the template column elements in the Grid. */ - templateRefresh? (e: TemplateRefreshEventArgs): void; + templateRefresh?(e: TemplateRefreshEventArgs): void; /** Triggered when toolbar item is clicked in grid. */ - toolbarClick? (e: ToolbarClickEventArgs): void; + toolbarClick?(e: ToolbarClickEventArgs): void; } export interface ActionBeginEventArgs { @@ -21914,6 +22540,48 @@ export interface BeforeBatchSaveEventArgs { batchChanges?: any; } +export interface BeforePrintEventArgs { + + /** Returns the grid model. + */ + model?: any; + + /** Returns the name of the event. + */ + type?: string; + + /** Returns the Grid element. + */ + element?: any; + + /** Returns the selected records. + */ + selectedRows?: any; +} + +export interface BeforeRowDropEventArgs { + + /** Returns the cancel option value. + */ + cancel?: boolean; + + /** Returns the targeted row. + */ + target?: any; + + /** Returns the targeted row index. + */ + targetIndex?: any; + + /** Returns the dragged record details + */ + draggedRecords?: any; + + /** Returns the drop details + */ + dropDetails?: any; +} + export interface BeginEditEventArgs { /** Returns the cancel option value. @@ -22059,7 +22727,7 @@ export interface CellSelectedEventArgs { /** Returns the selected row cell index values. */ - selectedRowCellIndex?: Array; + selectedRowCellIndex?: any[]; /** Returns the cancel option value. */ @@ -22113,6 +22781,60 @@ export interface CellSelectingEventArgs { type?: string; } +export interface CellDeselectedEventArgs { + + /** Returns the deselected cell index value. + */ + cellIndex?: number; + + /** Returns the deselected cell element. + */ + currentCell?: any; + + /** Returns current record object (JSON). + */ + data?: any; + + /** Returns the grid model. + */ + model?: any; + + /** Returns the name of the event. + */ + type?: string; +} + +export interface CellDeselectingEventArgs { + + /** Returns the deselecting cell index value. + */ + cellIndex?: number; + + /** Returns the deselecting cell element. + */ + currentCell?: any; + + /** Returns current record object (JSON). + */ + data?: any; + + /** Returns whether the ctrl key is pressed while deselecting cell + */ + isCtrlKeyPressed?: boolean; + + /** Returns whether the shift key is pressed while deselecting cell + */ + isShiftKeyPressed?: boolean; + + /** Returns the grid model. + */ + model?: any; + + /** Returns the name of the event. + */ + type?: string; +} + export interface ColumnDragEventArgs { /** Returns the cancel option value. @@ -22311,7 +23033,7 @@ export interface ColumnSelectedEventArgs { /** Returns the selected columns values. */ - selectedColumnsIndex?: Array; + selectedColumnsIndex?: any[]; /** Returns the cancel option value. */ @@ -22365,6 +23087,60 @@ export interface ColumnSelectingEventArgs { type?: string; } +export interface ColumnDeselectedEventArgs { + + /** Returns the Deselected column index value. + */ + columnIndex?: number; + + /** Returns the Deselected column header element. + */ + headerCell?: any; + + /** Returns corresponding column object (JSON). + */ + column?: any; + + /** Returns the grid model. + */ + model?: any; + + /** Returns the name of the event. + */ + type?: string; +} + +export interface ColumnDeselectingEventArgs { + + /** Returns the deselecting column index value. + */ + columnIndex?: number; + + /** Returns the deselecting column header element. + */ + headerCell?: any; + + /** Returns corresponding column object (JSON). + */ + column?: any; + + /** Returns whether the ctrl key is pressed while deselecting column + */ + isCtrlKeyPressed?: boolean; + + /** Returns whether the shift key is pressed while deselecting column + */ + isShiftKeyPressed?: boolean; + + /** Returns the grid model. + */ + model?: any; + + /** Returns the name of the event. + */ + type?: string; +} + export interface ContextClickEventArgs { /** Returns the cancel option value. @@ -22637,15 +23413,15 @@ export interface MergeCellInfoEventArgs { /** Method to merge Grid rows. */ - rowMerge?: void; + rowMerge?: any; /** Method to merge Grid columns. */ - colMerge?: void; + colMerge?: any; /** Method to merge Grid rows and columns. */ - merge?: void; + merge?: any; /** Returns the grid model. */ @@ -23030,6 +23806,60 @@ export interface RowSelectingEventArgs { type?: string; } +export interface RowDeselectedEventArgs { + + /** Returns current record object (JSON). + */ + data?: any; + + /** Returns the row index of the deselected row. + */ + rowIndex?: number; + + /** Returns the current deselected row element. + */ + row?: any; + + /** Returns the grid model. + */ + model?: any; + + /** Returns the name of the event. + */ + type?: string; +} + +export interface RowDeselectingEventArgs { + + /** Returns the deselecting row index value. + */ + rowIndex?: number; + + /** Returns the deselecting row element. + */ + row?: any; + + /** Returns current record object (JSON). + */ + data?: any; + + /** Returns whether the ctrl key is pressed while deselecting row + */ + isCtrlKeyPressed?: boolean; + + /** Returns whether the shift key is pressed while deselecting row + */ + isShiftKeyPressed?: boolean; + + /** Returns the grid model. + */ + model?: any; + + /** Returns the name of the event. + */ + type?: string; +} + export interface TemplateRefreshEventArgs { /** Returns the cancel option value. @@ -23129,59 +23959,60 @@ export interface Column { /** Gets or sets a value that indicates whether to enable editing behavior for particular column. * @Default {true} */ - allowEditing?: Boolean; + allowEditing?: boolean; /** Gets or sets a value that indicates whether to enable dynamic filtering behavior for particular column. * @Default {true} */ - allowFiltering?: Boolean; + allowFiltering?: boolean; /** Gets or sets a value that indicates whether to enable dynamic grouping behavior for particular column. * @Default {true} */ - allowGrouping?: Boolean; + allowGrouping?: boolean; /** Gets or sets a value that indicates whether to enable dynamic sorting behavior for particular column. * @Default {true} */ - allowSorting?: Boolean; + allowSorting?: boolean; /** Gets or sets a value that indicates whether to enable dynamic resizable for particular column. * @Default {true} */ - allowResizing?: Boolean; + allowResizing?: boolean; /** Gets or sets an object that indicates to define a command column in the grid. * @Default {[]} */ - commands?: Array; + commands?: ColumnsCommand[]; /** Gets or sets a value that indicates to provide custom CSS for an individual column. */ - cssClass?: String; + cssClass?: string; /** Gets or sets a value that indicates the attribute values to the td element of a particular column */ customAttributes?: any; - /** Gets or sets a value that indicates to bind the external datasource to the particular column when column editType as dropdownedit and also it is used to bind the datasource to the foreign key column while editing the grid. //Where data is array of JSON objects of text and value for the drop-down and array of JSON objects for foreign key column. + /** Gets or sets a value that indicates to bind the external datasource to the particular column when column editType as dropdownedit and also it is used to bind the datasource + * to the foreign key column while editing the grid. //Where data is array of JSON objects of text and value for the drop-down and array of JSON objects for foreign key column. * @Default {null} */ - dataSource?: Array; + dataSource?: any[]; /** Gets or sets a value that indicates to display the specified default value while adding a new record to the grid */ - defaultValue?: String|Number|Boolean|Date; + defaultValue?: string|number|boolean|Date; /** Gets or sets a value that indicates to render the grid content and header with an HTML elements * @Default {false} */ - disableHtmlEncode?: Boolean; + disableHtmlEncode?: boolean; /** Gets or sets a value that indicates to display a column value as checkbox or string * @Default {true} */ - displayAsCheckBox?: Boolean; + displayAsCheckBox?: boolean; /** Gets or sets a value that indicates to customize ejNumericTextbox of an editable column. See editingType */ @@ -23200,79 +24031,89 @@ export interface Column { /** Gets or sets a value that indicates to groups the column based on its column format. * @Default {false} */ - enableGroupByFormat?: Boolean; + enableGroupByFormat?: boolean; /** Gets or sets a value that indicates to display the columns in the grid mapping with column name of the dataSource. */ - field?: String; + field?: string; /** Gets or sets a template that customize the filter control from default . See filterBarTemplate * @Default {null} */ filterBarTemplate?: any; + /** Gets or sets a value that indicates to render the excel or menu filter dialog to the grid columns. See filterType + * @Default {null} + */ + filterType?: ej.Grid.FilterType|string; + /** Gets or sets a value that indicates to define foreign key field name of the grid datasource. * @Default {null} */ - foreignKeyField?: String; + foreignKeyField?: string; /** Gets or sets a value that indicates to bind the field which is in foreign column datasource based on the foreignKeyField * @Default {null} */ - foreignKeyValue?: String; + foreignKeyValue?: string; /** Gets or sets a value that indicates the format for the text applied on the column */ - format?: String; + format?: string; /** Gets or sets a value that indicates to add the template within the header element of the particular column. * @Default {null} */ - headerTemplateID?: String; + headerTemplateID?: string; /** Gets or sets a value that indicates to display the title of that particular column. */ - headerText?: String; + headerText?: string; /** This defines the text alignment of a particular column header cell value. See headerTextAlign * @Default {null} */ headerTextAlign?: ej.TextAlign|string; + /** It accepts the string value and shows the tooltip for the Grid column header. + * @Default {null} + */ + headerTooltip?: string; + /** You can use this property to freeze selected columns in grid at the time of scrolling. * @Default {false} */ - isFrozen?: Boolean; + isFrozen?: boolean; /** Gets or sets a value that indicates the column has an identity in the database. * @Default {false} */ - isIdentity?: Boolean; + isIdentity?: boolean; /** Gets or sets a value that indicates the column is act as a primary key(read-only) of the grid. The editing is performed based on the primary key column * @Default {false} */ - isPrimaryKey?: Boolean; + isPrimaryKey?: boolean; /** Gets or sets a value that indicates the order of Column that are to be hidden or visible when Grid element is in responsive mode and could not occupy all columns. - * @Default {null} + * @Default {-1} */ - priority?: Number; + priority?: number; /** Used to hide the particular column in column chooser by giving value as false. * @Default {true} */ - showInColumnChooser?: Boolean; + showInColumnChooser?: boolean; /** Gets or sets a value that indicates whether to enables column template for a particular column. * @Default {false} */ - template?: Boolean|String; + template?: boolean|string; /** Gets or sets a value that indicates to align the text within the column. See textAlign * @Default {ej.TextAlign.Left} */ - textAlign?: ej.TextAlign|string; + textAlign?: ej.TextAlign|string; /** Sets the template for Tooltip in Grid Columns(both header and content) */ @@ -23280,7 +24121,7 @@ export interface Column { /** Gets or sets a value that indicates to specify the data type of the specified columns. */ - type?: String; + type?: string; /** Gets or sets a value that indicates to define constraints for saving data to the database. */ @@ -23289,11 +24130,11 @@ export interface Column { /** Gets or sets a value that indicates whether this column is visible in the grid. * @Default {true} */ - visible?: Boolean; + visible?: boolean; /** Gets or sets a value that indicates to define the width for a particular column in the grid. */ - width?: Number; + width?: number; } export interface ContextMenuSettingsSubContextMenu { @@ -23306,34 +24147,35 @@ export interface ContextMenuSettingsSubContextMenu { /** Used to get or set the sub menu items to the custom context menu item. * @Default {[]} */ - subMenu?: Array; + subMenu?: any[]; } export interface ContextMenuSettings { - /** Gets or sets a value that indicates whether to add the default context menu actions as a context menu items If enableContextMenu is true it will show all the items related to the target, if you want selected items from contextmenu you have to mention in the contextMenuItems + /** Gets or sets a value that indicates whether to add the default context menu actions as a context menu items If enableContextMenu is true it will show all the items related to the target, + * if you want selected items from contextmenu you have to mention in the contextMenuItems * @Default {[]} */ - contextMenuItems?: Array; + contextMenuItems?: any[]; /** Gets or sets a value that indicates whether to add custom contextMenu items within the toolbar to perform any action in the grid * @Default {[]} */ - customContextMenuItems?: Array; + customContextMenuItems?: any[]; /** Gets or sets a value that indicates whether to enable the context menu action in the grid. * @Default {false} */ - enableContextMenu?: Boolean; + enableContextMenu?: boolean; /** Used to get or set the subMenu to the corresponding custom context menu item. */ - subContextMenu?: Array; + subContextMenu?: ContextMenuSettingsSubContextMenu[]; /** Gets or sets a value that indicates whether to disable the default context menu items in the grid. * @Default {false} */ - disableDefaultItems?: Boolean; + disableDefaultItems?: boolean; } export interface EditSettings { @@ -23341,27 +24183,27 @@ export interface EditSettings { /** Gets or sets a value that indicates whether to enable insert action in the editing mode. * @Default {false} */ - allowAdding?: Boolean; + allowAdding?: boolean; /** Gets or sets a value that indicates whether to enable the delete action in the editing mode. * @Default {false} */ - allowDeleting?: Boolean; + allowDeleting?: boolean; /** Gets or sets a value that indicates whether to enable the edit action in the editing mode. * @Default {false} */ - allowEditing?: Boolean; + allowEditing?: boolean; /** Gets or sets a value that indicates whether to enable the editing action while double click on the record * @Default {true} */ - allowEditOnDblClick?: Boolean; + allowEditOnDblClick?: boolean; /** This specifies the id of the template. This template can be used to display the data that you require to be edited using the Dialog Box * @Default {null} */ - dialogEditorTemplateID?: String; + dialogEditorTemplateID?: string; /** Gets or sets a value that indicates whether to define the mode of editing See editMode * @Default {ej.Grid.EditMode.Normal} @@ -23371,7 +24213,7 @@ export interface EditSettings { /** This specifies the id of the template. This template can be used to display the data that you require to be edited using the External edit form * @Default {null} */ - externalFormTemplateID?: String; + externalFormTemplateID?: string; /** This specifies to set the position of an External edit form either in the top-right or bottom-left of the grid * @Default {ej.Grid.FormPosition.BottomLeft} @@ -23381,7 +24223,7 @@ export interface EditSettings { /** This specifies the id of the template. This template can be used to display the data that you require to be edited using the Inline edit form * @Default {null} */ - inlineFormTemplateID?: String; + inlineFormTemplateID?: string; /** This specifies to set the position of an adding new row either in the top or bottom of the grid * @Default {ej.Grid.RowPosition.Top} @@ -23391,22 +24233,22 @@ export interface EditSettings { /** Gets or sets a value that indicates whether the confirm dialog has to be shown while saving or discarding the batch changes * @Default {true} */ - showConfirmDialog?: Boolean; + showConfirmDialog?: boolean; /** Gets or sets a value that indicates whether the confirm dialog has to be shown while deleting record * @Default {false} */ - showDeleteConfirmDialog?: Boolean; + showDeleteConfirmDialog?: boolean; /** Gets or sets a value that indicates whether the title for edit form is different from the primarykey column. * @Default {null} */ - titleColumn?: String; + titleColumn?: string; /** Gets or sets a value that indicates whether to display the add new form by default in the grid. * @Default {false} */ - showAddNewRow?: Boolean; + showAddNewRow?: boolean; } export interface FilterSettingsFilteredColumn { @@ -23415,7 +24257,11 @@ export interface FilterSettingsFilteredColumn { */ field?: string; - /** Gets or sets a value that indicates whether to define the filter condition to filtered column. + /** Gets or sets a value that indicates whether to define the matchCase of given value to be filter. + */ + matchCase?: boolean; + + /** Gets or sets a value that indicates whether to define the filter condition to filtered column. See operator */ operator?: ej.FilterOperators|string; @@ -23433,9 +24279,14 @@ export interface FilterSettings { /** Gets or sets a value that indicates to perform the filter operation with case sensitive in excel styled filter menu mode * @Default {false} */ - enableCaseSensitivity?: Boolean; + enableCaseSensitivity?: boolean; - /** This specifies the grid to starts the filter action while typing in the filterBar or after pressing the enter key. based on the filterBarMode. See filterBarMode + /** Gets or sets a value that indicates to define the interDeterminateState of checkbox in excel filter dialog. + * @Default {true} + */ + enableInterDeterminateState?: boolean; + + /** This specifies the grid to starts the filter action while typing in the filterBar or after pressing the enter key. based on the filterBarMode. See filterBarMode. * @Default {ej.Grid.FilterBarMode.Immediate} */ filterBarMode?: ej.Grid.FilterBarMode|string; @@ -23443,27 +24294,32 @@ export interface FilterSettings { /** Gets or sets a value that indicates whether to define the filtered columns details programmatically at initial load * @Default {[]} */ - filteredColumns?: Array; + filteredColumns?: FilterSettingsFilteredColumn[]; /** This specifies the grid to show the filterBar or filterMenu to the grid records. See filterType * @Default {ej.Grid.FilterType.FilterBar} */ filterType?: ej.Grid.FilterType|string; + /** This specifies the grid to delay the filter action while typing in the filterBar. + * @Default {1500} + */ + immediateModeDelay?: number; + /** Gets or sets a value that indicates the maximum number of filter choices that can be showed in the excel styled filter menu. * @Default {1000} */ - maxFilterChoices?: Number; + maxFilterChoices?: number; /** This specifies the grid to show the filter text within the grid pager itself. * @Default {true} */ - showFilterBarMessage?: Boolean; + showFilterBarMessage?: boolean; /** Gets or sets a value that indicates whether to enable the predicate options in the filtering menu * @Default {false} */ - showPredicate?: Boolean; + showPredicate?: boolean; } export interface GroupSettings { @@ -23471,37 +24327,38 @@ export interface GroupSettings { /** Gets or sets a value that customize the group caption format. * @Default {null} */ - captionFormat?: String; + captionFormat?: string; /** Gets or sets a value that indicates whether to enable animation button option in the group drop area of the grid. * @Default {false} */ - enableDropAreaAutoSizing?: Boolean; + enableDropAreaAutoSizing?: boolean; /** Gets or sets a value that indicates whether to add grouped columns programmatically at initial load * @Default {[]} */ - groupedColumns?: Array; + groupedColumns?: any[]; /** Gets or sets a value that indicates whether to show the group drop area just above the column header. It can be used to avoid ungrouping the already grouped column using groupSettings. * @Default {true} */ - showDropArea?: Boolean; + showDropArea?: boolean; /** Gets or sets a value that indicates whether to hide the grouped columns from the grid * @Default {false} */ - showGroupedColumn?: Boolean; + showGroupedColumn?: boolean; - /** Gets or sets a value that indicates whether to show the group button image(toggle button)in the column header and also in the grouped column in the group drop area . It can be used to group/ungroup the columns by click on the toggle button. + /** Gets or sets a value that indicates whether to show the group button image(toggle button)in the column header and also in the grouped column in the group drop area. + * It can be used to group/ungroup the columns by click on the toggle button. * @Default {false} */ - showToggleButton?: Boolean; + showToggleButton?: boolean; /** Gets or sets a value that indicates whether to enable the close button in the grouped column which is in the group drop area to ungroup the grouped column * @Default {false} */ - showUngroupButton?: Boolean; + showUngroupButton?: boolean; } export interface PageSettings { @@ -23509,47 +24366,47 @@ export interface PageSettings { /** Gets or sets a value that indicates whether to define which page to display currently in the grid * @Default {1} */ - currentPage?: Number; + currentPage?: number; /** Gets or sets a value that indicates whether to pass the current page information as a query string along with the URL while navigating to other page. * @Default {false} */ - enableQueryString?: Boolean; + enableQueryString?: boolean; /** Gets or sets a value that indicates whether to enables pager template for the grid. * @Default {false} */ - enableTemplates?: Boolean; + enableTemplates?: boolean; /** Gets or sets a value that indicates whether to define the number of pages displayed in the pager for navigation * @Default {8} */ - pageCount?: Number; + pageCount?: number; /** Gets or sets a value that indicates whether to define the number of records displayed per page * @Default {12} */ - pageSize?: Number; + pageSize?: number; /** Gets or sets a value that indicates whether to enables default pager for the grid. * @Default {false} */ - showDefaults?: Boolean; + showDefaults?: boolean; /** Gets or sets a value that indicates to add the template as a pager template for grid. * @Default {null} */ - template?: String; + template?: string; /** Get the value of total number of pages in the grid. The totalPages value is calculated based on page size and total records of grid * @Default {null} */ - totalPages?: Number; + totalPages?: number; /** Get the value of total number of records which is bound to the grid. The totalRecordsCount value is calculated based on dataSource bound to the grid. * @Default {null} */ - totalRecordsCount?: Number; + totalRecordsCount?: number; /** Gets or sets a value that indicates whether to define the number of pages to print * @Default {ej.Grid.PrintMode.AllPages} @@ -23607,15 +24464,20 @@ export interface SearchSettings { export interface SelectionSettings { + /** Gets or sets a value that indicates the cell selection actions based on the cell selection mode. + * @Default {flow} + */ + cellSelectionMode?: string; + /** Gets or sets a value that indicates whether to enable the toggle selection behavior for row, cell and column. * @Default {false} */ - enableToggle?: Boolean; + enableToggle?: boolean; /** Gets or sets a value that indicates whether to add the default selection actions as a selection mode.See selectionMode * @Default {[row]} */ - selectionMode?: Array; + selectionMode?: any[]; } export interface ScrollSettings { @@ -23623,27 +24485,42 @@ export interface ScrollSettings { /** This specify the grid to to view data that you require without buffering the entire load of a huge database * @Default {false} */ - allowVirtualScrolling?: Boolean; + allowVirtualScrolling?: boolean; + + /** It accepts the boolean value and shows or hides the scrollbar while focus in or focus out of the Grid. + * @Default {false} + */ + autoHide?: boolean; + + /** Specifies the height and width of button in the scrollbar. + * @Default {18} + */ + buttonSize?: number; /** This specify the grid to enable/disable touch control for scrolling. * @Default {true} */ - enableTouchScroll?: Boolean; + enableTouchScroll?: boolean; /** This specify the grid to freeze particular columns at the time of scrolling. * @Default {0} */ - frozenColumns?: Number; + frozenColumns?: number; /** This specify the grid to freeze particular rows at the time of scrolling. * @Default {0} */ - frozenRows?: Number; + frozenRows?: number; /** This specify the grid to show the vertical scroll bar, to scroll and view the grid contents. * @Default {0} */ - height?: String|Number; + height?: string|number; + + /** It accepts the integer value and sets the width of scrollbar. + * @Default {18} + */ + scrollerSize?: number; /** This is used to define the mode of virtual scrolling in grid. See virtualScrollMode * @Default {ej.Grid.VirtualScrollMode.Normal} @@ -23653,35 +24530,35 @@ export interface ScrollSettings { /** This is used to enable the enhanced virtual scrolling in Grid. * @Default {false} */ - enableVirtualization?: Boolean; + enableVirtualization?: boolean; /** This specify the grid to show the horizontal scroll bar, to scroll and view the grid contents * @Default {250} */ - width?: String|Number; + width?: string|number; /** This specify the scroll down pixel of mouse wheel, to scroll mouse wheel and view the grid contents. * @Default {57} */ - scrollOneStepBy?: Number; + scrollOneStepBy?: number; } export interface SortSettingsSortedColumn { /** Gets or sets a value that indicates whether to define the direction to sort the column. */ - direction?: String; + direction?: string; /** Gets or sets a value that indicates whether to define the field name of the column to be sort */ - field?: String; + field?: string; } export interface SortSettings { /** Gets or sets a value that indicates whether to define the direction and field to sort the column. */ - sortedColumns?: Array; + sortedColumns?: SortSettingsSortedColumn[]; } export interface StackedHeaderRowsStackedHeaderColumn { @@ -23694,17 +24571,22 @@ export interface StackedHeaderRowsStackedHeaderColumn { /** Gets or sets a value that indicates class to the corresponding stackedHeaderColumn. * @Default {null} */ - cssClass?: String; + cssClass?: string; /** Gets or sets a value that indicates the header text for the particular stacked header column. * @Default {null} */ - headerText?: String; + headerText?: string; /** Gets or sets a value that indicates the text alignment of the corresponding headerText. * @Default {ej.TextAlign.Left} */ - textAlign?: String; + textAlign?: string; + + /** Sets the template for tooltip for the Grid stackedHeaderColumns. + * @Default {null} + */ + tooltip?: string; } export interface StackedHeaderRow { @@ -23712,7 +24594,7 @@ export interface StackedHeaderRow { /** Gets or sets a value that indicates whether to add stacked header columns into the stacked header rows * @Default {[]} */ - stackedHeaderColumns?: Array; + stackedHeaderColumns?: StackedHeaderRowsStackedHeaderColumn[]; } export interface SummaryRowsSummaryColumn { @@ -23720,32 +24602,32 @@ export interface SummaryRowsSummaryColumn { /** Gets or sets a value that indicates the text displayed in the summary column as a value * @Default {null} */ - customSummaryValue?: String; + customSummaryValue?: string; /** This specifies summary column used to perform the summary calculation * @Default {null} */ - dataMember?: String; + dataMember?: string; /** Gets or sets a value that indicates to define the target column at which to display the summary. * @Default {null} */ - displayColumn?: String; + displayColumn?: string; /** Gets or sets a value that indicates the format for the text applied on the column * @Default {null} */ - format?: String; + format?: string; /** Gets or sets a value that indicates the text displayed before the summary column value * @Default {null} */ - prefix?: String; + prefix?: string; /** Gets or sets a value that indicates the text displayed after the summary column value * @Default {null} */ - suffix?: String; + suffix?: string; /** Gets or sets a value that indicates the type of calculations to be performed for the corresponding summary column * @Default {[]} @@ -23755,7 +24637,7 @@ export interface SummaryRowsSummaryColumn { /** Gets or sets a value that indicates to add the template for the summary value of dataMember given. * @Default {null} */ - template?: String; + template?: string; } export interface SummaryRow { @@ -23763,31 +24645,31 @@ export interface SummaryRow { /** Gets or sets a value that indicates whether to show the summary value within the group caption area for the corresponding summary column while grouping the column * @Default {false} */ - showCaptionSummary?: Boolean; + showCaptionSummary?: boolean; /** Gets or sets a value that indicates whether to show the group summary value for the corresponding summary column while grouping a column * @Default {false} */ - showGroupSummary?: Boolean; + showGroupSummary?: boolean; /** Gets or sets a value that indicates whether to show the total summary value the for the corresponding summary column. The summary row is added after the grid content. * @Default {true} */ - showTotalSummary?: Boolean; + showTotalSummary?: boolean; /** Gets or sets a value that indicates whether to add summary columns into the summary rows. * @Default {[]} */ - summaryColumns?: Array; + summaryColumns?: SummaryRowsSummaryColumn[]; /** This specifies the grid to show the title for the summary rows. */ - title?: String; + title?: string; /** This specifies the grid to show the title of summary row in the specified column. * @Default {null} */ - titleColumn?: String; + titleColumn?: string; } export interface TextWrapSettings { @@ -23803,12 +24685,12 @@ export interface ToolbarSettings { /** Gets or sets a value that indicates whether to add custom toolbar items within the toolbar to perform any action in the grid * @Default {[]} */ - customToolbarItems?: Array; + customToolbarItems?: any[]; /** Gets or sets a value that indicates whether to enable toolbar in the grid. * @Default {false} */ - showToolbar?: Boolean; + showToolbar?: boolean; /** Gets or sets a value that indicates whether to add the default editing actions as a toolbar items * @Default {[]} @@ -23816,7 +24698,7 @@ export interface ToolbarSettings { toolbarItems?: Array; } -enum GridLines{ +enum GridLines { ///Displays both the horizontal and vertical grid lines. Both, @@ -23832,7 +24714,7 @@ enum GridLines{ } -enum ClipMode{ +enum ClipMode { ///Shows ellipsis for the overflown cell. Ellipsis, @@ -23845,7 +24727,7 @@ enum ClipMode{ } -enum ColumnLayout{ +enum ColumnLayout { ///Column layout is auto(based on width). Auto, @@ -23855,7 +24737,7 @@ enum ColumnLayout{ } -enum UnboundType{ +enum UnboundType { ///Unbound type is edit. Edit, @@ -23871,7 +24753,7 @@ enum UnboundType{ } -enum EditingType{ +enum EditingType { ///Specifies editing type as string edit. String, @@ -23893,7 +24775,17 @@ enum EditingType{ } -enum EditMode{ +enum FilterType { + + ///Specifies the filter type as menu. + Menu, + + ///Specifies the filter type as excel. + Excel +} + + +enum EditMode { ///Edit mode is normal. Normal, @@ -23921,7 +24813,7 @@ enum EditMode{ } -enum FormPosition{ +enum FormPosition { ///Form position is bottomleft. BottomLeft, @@ -23931,7 +24823,7 @@ enum FormPosition{ } -enum RowPosition{ +enum RowPosition { ///Specifies position of add new row as top. Top, @@ -23941,7 +24833,7 @@ enum RowPosition{ } -enum FilterBarMode{ +enum FilterBarMode { ///Initiate filter operation on typing the filter query. Immediate, @@ -23951,20 +24843,7 @@ enum FilterBarMode{ } -enum FilterType{ - - ///Specifies the filter type as menu. - Menu, - - ///Specifies the filter type as excel. - Excel, - - ///Specifies the filter type as filterbar. - FilterBar -} - - -enum PrintMode{ +enum PrintMode { ///Prints all pages. AllPages, @@ -23974,7 +24853,7 @@ enum PrintMode{ } -enum ResizeMode{ +enum ResizeMode { ///New column size will be adjusted by all other Columns Normal, @@ -23987,7 +24866,7 @@ enum ResizeMode{ } -enum SelectionType{ +enum SelectionType { ///Specifies the selection type as single. Single, @@ -23997,7 +24876,7 @@ enum SelectionType{ } -enum VirtualScrollMode{ +enum VirtualScrollMode { ///virtual scroll mode is normal. Normal, @@ -24007,7 +24886,7 @@ enum VirtualScrollMode{ } -enum SummaryType{ +enum SummaryType { ///Summary type is average. Average, @@ -24035,7 +24914,7 @@ enum SummaryType{ } -enum WrapMode{ +enum WrapMode { ///Auto wrap is applied for both content and header. Both, @@ -24048,7 +24927,7 @@ enum WrapMode{ } -enum ToolBarItems{ +enum ToolBarItems { ///Toolbar item is add. Add, @@ -24082,18 +24961,17 @@ enum ToolBarItems{ class Sparkline extends ej.Widget { static fn: Sparkline; - constructor(element: JQuery, options?: Sparkline.Model); - constructor(element: Element, options?: Sparkline.Model); + constructor(element: JQuery | Element, options?: Sparkline.Model); static Locale: any; - model:Sparkline.Model; - defaults:Sparkline.Model; + model: Sparkline.Model; + defaults: Sparkline.Model; /** Redraws the entire sparkline. You can call this method whenever you update, add or remove points from the data source or whenever you want to refresh the UI. * @returns {void} */ redraw(): void; } -export module Sparkline{ +export namespace Sparkline { export interface Model { @@ -24216,28 +25094,28 @@ export interface Model { axisLineSettings?: AxisLineSettings; /** Fires before loading the sparkline. */ - load? (e: LoadEventArgs): void; + load?(e: LoadEventArgs): void; /** Fires after loaded the sparkline. */ - loaded? (e: LoadedEventArgs): void; + loaded?(e: LoadedEventArgs): void; /** Fires before rendering trackball tooltip. You can use this event to customize the text displayed in trackball tooltip. */ - tooltipInitialize? (e: TooltipInitializeEventArgs): void; + tooltipInitialize?(e: TooltipInitializeEventArgs): void; /** Fires before rendering a series. This event is fired for each series in Sparkline. */ - seriesRendering? (e: SeriesRenderingEventArgs): void; + seriesRendering?(e: SeriesRenderingEventArgs): void; /** Fires when mouse is moved over a point. */ - pointRegionMouseMove? (e: PointRegionMouseMoveEventArgs): void; + pointRegionMouseMove?(e: PointRegionMouseMoveEventArgs): void; /** Fires on clicking a point in sparkline. You can use this event to handle clicks made on points. */ - pointRegionMouseClick? (e: PointRegionMouseClickEventArgs): void; + pointRegionMouseClick?(e: PointRegionMouseClickEventArgs): void; /** Fires on moving mouse over the sparkline. */ - sparklineMouseMove? (e: SparklineMouseMoveEventArgs): void; + sparklineMouseMove?(e: SparklineMouseMoveEventArgs): void; /** Fires on moving mouse outside the sparkline. */ - sparklineMouseLeave? (e: SparklineMouseLeaveEventArgs): void; + sparklineMouseLeave?(e: SparklineMouseLeaveEventArgs): void; } export interface LoadEventArgs { @@ -24612,10 +25490,8 @@ export interface AxisLineSettings { dashArray?: number; } } -module Sparkline -{ -enum Type -{ +namespace Sparkline { +enum Type { //string Area, //string @@ -24628,10 +25504,8 @@ Pie, WinLoss, } } -module Sparkline -{ -enum Theme -{ +namespace Sparkline { +enum Theme { //string Azure, //string @@ -24654,20 +25528,16 @@ GradientLight, GradientDark, } } -module Sparkline -{ -enum FontStyle -{ +namespace Sparkline { +enum FontStyle { //string Normal, //string Italic, } } -module Sparkline -{ -enum FontWeight -{ +namespace Sparkline { +enum FontWeight { //string Regular, //string @@ -24677,13 +25547,1169 @@ Lighter, } } +class SunburstChart extends ej.Widget { + static fn: SunburstChart; + constructor(element: JQuery | Element, options?: SunburstChart.Model); + static Locale: any; + model: SunburstChart.Model; + defaults: SunburstChart.Model; + + /** Redraws the entire sunburst. You can call this method whenever you update, add or remove points from the data source or whenever you want to refresh the UI. + * @returns {void} + */ + redraw(): void; + + /** destroy the sunburst + * @returns {void} + */ + _destroy(): void; +} +export namespace SunburstChart { + +export interface Model { + + /** Background color of the plot area. + * @Default {null} + */ + background?: string; + + /** Bind the data field from the data source. + * @Default {null} + */ + valueMemberPath?: string; + + /** Options for customizing the sunburst border. + */ + border?: Border; + + /** Options for customizing the sunburst segment border. + */ + segmentBorder?: SegmentBorder; + + /** Specifies the dataSource to the sunburst. + * @Default {null} + */ + dataSource?: any; + + /** Palette color for the data points. + * @Default {null} + */ + palette?: string; + + /** Parent node of the data points. + * @Default {null} + */ + parentNode?: string; + + /** Name of the property in the datasource that contains x values. + * @Default {null} + */ + xName?: string; + + /** Name of the property in the datasource that contains y values. + * @Default {null} + */ + yName?: string; + + /** Controls whether sunburst has to be responsive or not. + * @Default {true} + */ + isResponsive?: boolean; + + /** Options to customize the Sunburst size. + */ + size?: Size; + + /** Controls the visibility of sunburst. + * @Default {true} + */ + visible?: boolean; + + /** Options to customize the Sunburst tooltip. + */ + tooltip?: Tooltip; + + /** Options for customizing sunburst points. + */ + points?: Points; + + /** Sunburst rendering will start from the specified value + * @Default {null} + */ + startAngle?: number; + + /** Sunburst rendering will end at the specified value + * @Default {null} + */ + endAngle?: number; + + /** Sunburst outer radius value + * @Default {1} + */ + radius?: number; + + /** Sunburst inner radius value + * @Default {0.4} + */ + innerRadius?: number; + + /** Options to customize the Sunburst dataLabel. + */ + dataLabelSettings?: DataLabelSettings; + + /** Options for customizing the title and subtitle of sunburst. + */ + title?: Title; + + /** Options for customizing the appearance of the levels or point while highlighting. + */ + highlightSettings?: HighlightSettings; + + /** Options for customizing the appearance of the levels or data point while selection. + */ + selectionSettings?: SelectionSettings; + + /** Specify levels of sunburst for grouped visualization of data + * @Default {[]} + */ + levels?: Level[]; + + /** Options to customize the legend items and legend title. + */ + legend?: Legend; + + /** Specifies the theme for Sunburst. + * @Default {Flatlight. See Theme} + */ + theme?: ej.datavisualization.Sunburst.SunburstTheme|string; + + /** Options to customize the left, right, top and bottom margins of sunburst area. + */ + margin?: Margin; + + /** Enable/disable the animation for all the levels. + * @Default {false} + */ + enableAnimation?: boolean; + + /** Opacity of the levels. + * @Default {1} + */ + opacity?: number; + + /** Options for enable zooming feature of chart. + */ + zoomSettings?: ZoomSettings; + + /** Animation type of sunburst + * @Default {rotation. See Alignment} + */ + animationType?: ej.datavisualization.Sunburst.Animation|string; + + /** Fires before loading. */ + load?(e: LoadEventArgs): void; + + /** Fires before rendering sunburst. */ + preRender?(e: PreRenderEventArgs): void; + + /** Fires after rendering sunburst. */ + loaded?(e: LoadedEventArgs): void; + + /** Fires before rendering the datalabel */ + dataLabelRendering?(e: DataLabelRenderingEventArgs): void; + + /** Fires before rendering each segment */ + segmentRendering?(e: SegmentRenderingEventArgs): void; + + /** Fires before rendering sunburst title. */ + titleRendering?(e: TitleRenderingEventArgs): void; + + /** Fires during initialization of tooltip. */ + tooltipInitialize?(e: TooltipInitializeEventArgs): void; + + /** Fires after clicking the point in sunburst */ + pointRegionClick?(e: PointRegionClickEventArgs): void; + + /** Fires while moving the mouse over sunburst points */ + pointRegionMouseMove?(e: PointRegionMouseMoveEventArgs): void; + + /** Fires when clicking the point to perform drilldown. */ + drillDownClick?(e: DrillDownClickEventArgs): void; + + /** Fires when resetting drilldown points. */ + drillDownBack?(e: DrillDownBackEventArgs): void; + + /** Fires after resetting the sunburst points */ + drillDownReset?(e: DrillDownResetEventArgs): void; +} + +export interface LoadEventArgs { + + /** Load event data + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface PreRenderEventArgs { + + /** PreRender event data + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface LoadedEventArgs { + + /** Loaded event data + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface DataLabelRenderingEventArgs { + + /** Sunburst datalabel data + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface SegmentRenderingEventArgs { + + /** Sunburst datalabel data + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface TitleRenderingEventArgs { + + /** Sunburst title data + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface TooltipInitializeEventArgs { + + /** Sunburst tooltip data + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface PointRegionClickEventArgs { + + /** Includes clicked points region data + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface PointRegionMouseMoveEventArgs { + + /** Includes data of mouse moved region + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface DrillDownClickEventArgs { + + /** Clicked point data + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface DrillDownBackEventArgs { + + /** Drill down data of points + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface DrillDownResetEventArgs { + + /** Drill down reset data + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface Border { + + /** Border color of the sunburst. + * @Default {null} + */ + color?: string; + + /** Width of the Sunburst border. + * @Default {2} + */ + width?: number; +} + +export interface SegmentBorder { + + /** Segment Border color of the sunburst. + * @Default {null} + */ + color?: string; + + /** Width of the Sunburst segment border. + * @Default {2} + */ + width?: number; +} + +export interface Size { + + /** Height of the Sunburst. + * @Default {''} + */ + height?: string; + + /** Width of the Sunburst. + * @Default {''} + */ + width?: string; +} + +export interface TooltipBorder { + + /** Border color of the tooltip. + * @Default {null} + */ + color?: string; + + /** Border width of the tooltip. + * @Default {5} + */ + width?: number; +} + +export interface TooltipFont { + + /** Font color of the text in the tooltip. + * @Default {null} + */ + color?: string; + + /** Font Family for the tooltip. + * @Default {Segoe UI} + */ + fontFamily?: string; + + /** Specifies the font Style for the tooltip. + * @Default {Normal} + */ + fontStyle?: ej.datavisualization.Sunburst.FontStyle|string; + + /** Specifies the font weight for the tooltip. + * @Default {Regular} + */ + fontWeight?: ej.datavisualization.Sunburst.FontWeight|string; + + /** Opacity for text in the tooltip. + * @Default {1} + */ + opacity?: number; + + /** Font size for text in the tooltip. + * @Default {12px} + */ + size?: string; +} + +export interface Tooltip { + + /** tooltip visibility of the Sunburst. + * @Default {true} + */ + visible?: boolean; + + /** Options for customizing the border of the sunburst tooltip. + */ + border?: TooltipBorder; + + /** Fill color for the sunburst tooltip. + * @Default {null} + */ + fill?: string; + + /** Options for customizing the font of the tooltip. + */ + font?: TooltipFont; + + /** Custom template to the tooltip. + * @Default {null} + */ + template?: string; +} + +export interface Points { + + /** Points x value of the sunburst. + * @Default {null} + */ + x?: string; + + /** Points y value of the sunburst. + * @Default {null} + */ + y?: number; + + /** Points text of the sunburst. + * @Default {null} + */ + text?: string; + + /** Points fill color of the sunburst. + * @Default {null} + */ + fill?: string; +} + +export interface DataLabelSettingsFont { + + /** Font family of the data label. + * @Default {Segoe UI} + */ + fontFamily?: string; + + /** Font style of the data label. + * @Default {normal. See FontStyle} + */ + fontStyle?: ej.datavisualization.Sunburst.FontStyle|string; + + /** Font weight of the data label. + * @Default {regular. See FontWeight} + */ + fontWeight?: ej.datavisualization.Sunburst.FontWeight|string; + + /** Opacity of the text. + * @Default {1} + */ + opacity?: number; + + /** Font color of the data label text. + * @Default {null} + */ + color?: string; + + /** Font size of the data label. + * @Default {12px} + */ + size?: string; +} + +export interface DataLabelSettings { + + /** Datalabel visibility of the Sunburst. + * @Default {false} + */ + visible?: boolean; + + /** Alignment of sunburst datalabel + * @Default {Angle. See DatalabelAlignment} + */ + labelRotationMode?: ej.datavisualization.Sunburst.SunburstLabelRotationMode|string; + + /** Options for customizing the data label font. + */ + font?: DataLabelSettingsFont; + + /** Custom template for datalabel + * @Default {null} + */ + template?: string; + + /** Fill color for the datalabel + * @Default {null} + */ + fill?: string; + + /** Datalabel overflow mode + * @Default {Trim. See LabelOverflowMode} + */ + labelOverflowMode?: ej.datavisualization.Sunburst.SunburstLabelOverflowMode|string; +} + +export interface TitleFont { + + /** Font family for Sunburst title. + * @Default {Segoe UI} + */ + fontFamily?: string; + + /** Font style for Sunburst title. + * @Default {Normal. See FontStyle} + */ + fontStyle?: ej.datavisualization.Sunburst.FontStyle|string; + + /** Font weight for Sunburst title. + * @Default {Regular. See FontWeight} + */ + fontWeight?: ej.datavisualization.Sunburst.FontWeight|string; + + /** Opacity of the Sunburst title. + * @Default {1} + */ + opacity?: number; + + /** Font size for Sunburst title. + * @Default {20px} + */ + size?: string; +} + +export interface TitleSubtitleFont { + + /** Font family of sub title. + * @Default {Segoe UI} + */ + fontFamily?: string; + + /** Font style for sub title. + * @Default {Normal. See FontStyle} + */ + fontStyle?: ej.datavisualization.Sunburst.FontStyle|string; + + /** Font weight for sub title. + * @Default {Regular. See FontWeight} + */ + fontWeight?: ej.datavisualization.Sunburst.FontWeight|string; + + /** Opacity of the sub title. + * @Default {1} + */ + opacity?: number; + + /** Font size for sub title. + * @Default {12px} + */ + size?: string; +} + +export interface TitleSubtitle { + + /** Subtitle text for sunburst + */ + text?: string; + + /** Sub title text visibility for sunburst + * @Default {true} + */ + visible?: string; + + /** Sub title text alignment + * @Default {far. See TextAlignment} + */ + textAlignment?: ej.datavisualization.Sunburst.SunburstAlignment|string; + + /** Options for customizing the font of sub title. + */ + font?: TitleSubtitleFont; +} + +export interface Title { + + /** Title text for sunburst + */ + text?: string; + + /** Title text visibility for sunburst + * @Default {true} + */ + visible?: string; + + /** Title text alignment + * @Default {center. See TextAlignment} + */ + textAlignment?: ej.datavisualization.Sunburst.SunburstAlignment|string; + + /** Options for customizing the font of sunburst title. + */ + font?: TitleFont; + + /** Options to customize the sub title of Sunburst. + */ + subtitle?: TitleSubtitle; +} + +export interface HighlightSettings { + + /** Enables/disables the ability to highlight the levels or point interactively. + * @Default {false} + */ + enable?: boolean; + + /** Specifies whether the levels or point has to be highlighted. + * @Default {point. See Mode} + */ + mode?: ej.datavisualization.Sunburst.SunburstHighlightMode|string; + + /** Color of the levels/point on highlight. + * @Default {red} + */ + color?: string; + + /** Opacity of the levels/point on highlight. + * @Default {0.5} + */ + opacity?: number; + + /** Specifies whether the levels or data point has to be highlighted. + * @Default {opacity. See Mode} + */ + type?: ej.datavisualization.Sunburst.SunburstHighlightType|string; +} + +export interface SelectionSettings { + + /** Enables/disables the ability to select the levels or data point interactively. + * @Default {false} + */ + enable?: boolean; + + /** Specifies whether the levels or data point has to be selected. + * @Default {point. See Mode} + */ + mode?: ej.datavisualization.Sunburst.SunburstHighlightMode|string; + + /** Color of the levels/point on selection. + * @Default {green} + */ + color?: string; + + /** Opacity of the levels/point on selection. + * @Default {0.5} + */ + opacity?: number; + + /** Specifies whether the levels or data point has to be selected. + * @Default {opacity. See Mode} + */ + type?: ej.datavisualization.Sunburst.SunburstHighlightType|string; +} + +export interface Level { + + /** Specifies the group member path + * @Default {null} + */ + groupMemberPath?: string; +} + +export interface LegendBorder { + + /** Border color of the legend. + * @Default {null} + */ + color?: string; + + /** Border width of the legend. + * @Default {1} + */ + width?: number; +} + +export interface LegendFont { + + /** Font family for legend item text. + * @Default {Segoe UI} + */ + fontFamily?: string; + + /** Font style for legend item text. + * @Default {Normal. See FontStyle} + */ + fontStyle?: ej.datavisualization.Sunburst.FontStyle|string; + + /** Font weight for legend item text. + * @Default {Regular. See FontWeight} + */ + fontWeight?: ej.datavisualization.Sunburst.FontWeight|string; + + /** Font size for legend item text. + * @Default {12px} + */ + size?: string; +} + +export interface LegendItemStyle { + + /** Height of the shape in legend items. + * @Default {10} + */ + height?: number; + + /** Width of the shape in legend items. + * @Default {10} + */ + width?: number; +} + +export interface LegendLocation { + + /** X value or horizontal offset to position the legend in chart. + * @Default {0} + */ + x?: number; + + /** Y value or vertical offset to position the legend. + * @Default {0} + */ + y?: number; +} + +export interface LegendSize { + + /** Height of the legend. Height can be specified in either pixel or percentage. + * @Default {null} + */ + height?: string; + + /** Width of the legend. Width can be specified in either pixel or percentage. + * @Default {null} + */ + width?: string; +} + +export interface LegendTitleFont { + + /** Font family for the text in legend title. + * @Default {Segoe UI} + */ + fontFamily?: string; + + /** Font style for legend title. + * @Default {normal. See FontStyle} + */ + fontStyle?: ej.datavisualization.Sunburst.FontStyle|string; + + /** Font weight for legend title. + * @Default {normal. See FontWeight} + */ + fontWeight?: ej.datavisualization.Sunburst.FontWeight|string; + + /** Font size for legend title. + * @Default {12px} + */ + size?: string; +} + +export interface LegendTitle { + + /** Options to customize the font used for legend title + */ + font?: LegendTitleFont; + + /** Enables or disables the legend title. + * @Default {true} + */ + visible?: string; + + /** Text to be displayed in legend title. + */ + text?: string; + + /** Alignment of the legend title. + * @Default {center. See Alignment} + */ + textAlignment?: ej.datavisualization.Sunburst.SunburstAlignment|string; +} + +export interface Legend { + + /** Visibility of the legend. + * @Default {false} + */ + visible?: boolean; + + /** Interactive action of legend items. + * @Default {toggleSegmentVisibility. See Alignment} + */ + clickAction?: ej.datavisualization.Sunburst.SunburstClickAction|string; + + /** Horizontal alignment of the legend. + * @Default {Center. See Alignment} + */ + alignment?: ej.datavisualization.Sunburst.SunburstAlignment|string; + + /** Options for customizing the legend border. + */ + border?: LegendBorder; + + /** Number of columns to arrange the legend items. + * @Default {null} + */ + columnCount?: number; + + /** Number of rows to arrange the legend items. + * @Default {null} + */ + rowCount?: number; + + /** Options to customize the font used for legend item text. + */ + font?: LegendFont; + + /** Gap or padding between the legend items. + * @Default {10} + */ + itemPadding?: number; + + /** Options to customize the style of legend items. + */ + itemStyle?: LegendItemStyle; + + /** Options to customize the location of sunburst legend. Legend is placed in provided location only when value of position property is custom + */ + location?: LegendLocation; + + /** Places the legend at specified position. Legend can be placed at left, right, top or bottom of the chart area.To manually specify the location of legend, set custom as value to this property. + * @Default {Bottom. See Position} + */ + position?: ej.datavisualization.Sunburst.SunburstLegendPosition|string; + + /** Shape of the legend items. + * @Default {None. See Shape} + */ + shape?: ej.datavisualization.Sunburst.SunburstLegendShape|string; + + /** Options to customize the size of the legend. + */ + size?: LegendSize; + + /** Options to customize the legend title. + */ + title?: LegendTitle; +} + +export interface Margin { + + /** Spacing for the left margin of chart area. Setting positive value decreases the width of the chart area from left side. + * @Default {10} + */ + left?: number; + + /** Spacing for the right margin of chart area. Setting positive value decreases the width of the chart area from right side. + * @Default {10} + */ + right?: number; + + /** Spacing for the top margin of chart area. Setting positive value decreases the height of the chart area from the top. + * @Default {10} + */ + top?: number; + + /** Spacing for the bottom margin of the chart area. Setting positive value decreases the height of the chart area from the bottom. + * @Default {10} + */ + bottom?: number; +} + +export interface ZoomSettings { + + /** Enables or disables zooming. + * @Default {false} + */ + enable?: boolean; + + /** Toolbar horizontal alignment + * @Default {right. See Alignment} + */ + toolbarHorizontalAlignment?: ej.datavisualization.Sunburst.SunburstHorizontalAlignment|string; + + /** Toolbar vertical alignment + * @Default {top. See Alignment} + */ + toolbarVerticalAlignment?: ej.datavisualization.Sunburst.SunburstVerticalAlignment|string; +} +} +namespace Sunburst { +enum FontStyle { +//string +Normal, +//string +Italic, +} +} +namespace Sunburst { +enum FontWeight { +//string +Regular, +//string +Bold, +//string +Lighter, +} +} +namespace Sunburst { +enum SunburstLabelRotationMode { +//string +Angle, +//string +Normal, +} +} +namespace Sunburst { +enum SunburstLabelOverflowMode { +//string +Trim, +//string +Hide, +//string +None, +} +} +namespace Sunburst { +enum SunburstAlignment { +//string +Center, +//string +Near, +//string +Far, +} +} +namespace Sunburst { +enum SunburstHighlightMode { +//string +Point, +//string +Parent, +//string +Child, +//string +All, +} +} +namespace Sunburst { +enum SunburstHighlightType { +//string +Opacity, +//string +Color, +} +} +namespace Sunburst { +enum SunburstClickAction { +//string +None, +//string +ToggleSegmentVisibility, +//string +ToggleSegmentSelection, +} +} +namespace Sunburst { +enum SunburstLegendPosition { +//string +Left, +//string +Right, +//string +Top, +//string +Bottom, +} +} +namespace Sunburst { +enum SunburstLegendShape { +//string +Diamond, +//string +Pentagon, +//string +Rectangle, +//string +Circle, +//string +Cross, +//string +Triangle, +} +} +namespace Sunburst { +enum SunburstTheme { +//string +FlatLight, +//string +FlatDark, +} +} +namespace Sunburst { +enum SunburstHorizontalAlignment { +//string +Center, +//string +Left, +//string +Right, +} +} +namespace Sunburst { +enum SunburstVerticalAlignment { +//string +Top, +//string +Bottom, +//string +Middle, +} +} +namespace Sunburst { +enum Animation { +//string +Rotation, +//string +FadeIn, +} +} + class PivotGrid extends ej.Widget { static fn: PivotGrid; - constructor(element: JQuery, options?: PivotGrid.Model); - constructor(element: Element, options?: PivotGrid.Model); + constructor(element: JQuery | Element, options?: PivotGrid.Model); static Locale: any; - model:PivotGrid.Model; - defaults:PivotGrid.Model; + model: PivotGrid.Model; + defaults: PivotGrid.Model; /** Performs an asynchronous HTTP (AJAX) request. * @returns {void} @@ -24753,7 +26779,7 @@ class PivotGrid extends ej.Widget { /** Returns the JSON records formed to render the control. * @returns {Array} */ - getJSONRecords(): Array; + getJSONRecords(): any[]; /** Sets the JSON records formed to render the control. * @returns {void} @@ -24770,7 +26796,7 @@ class PivotGrid extends ej.Widget { */ renderControlFromJSON(): void; } -export module PivotGrid{ +export namespace PivotGrid { export interface Model { @@ -24780,12 +26806,12 @@ export interface Model { analysisMode?: ej.Pivot.AnalysisMode|string; /** Specifies the CSS class to PivotGrid to achieve custom theme. - * @Default {“”} + * @Default {“”} */ cssClass?: string; /** Connects the PivotSchemaDesigner with the specified ID to the PivotGrid Control. - * @Default {“”} + * @Default {“”} */ pivotTableFieldListID?: string; @@ -24794,6 +26820,11 @@ export interface Model { */ dataSource?: DataSource; + /** Holds the neccessary properties for value sorting. + * @Default {{}} + */ + valueSortSettings?: ValueSortSettings; + /** Object that holds the settings of frozen headers. * @Default {{}} */ @@ -24819,7 +26850,7 @@ export interface Model { */ enableCellSelection?: boolean; - /** Enables the Drill-Through feature which retrieves the raw items that are used to create the specific cell in PivotGrid. This is only applicable in server mode component. + /** Enables the Drill-Through feature which retrieves the raw items that are used to create the specific cell in PivotGrid. * @Default {false} */ enableDrillThrough?: boolean; @@ -24849,6 +26880,11 @@ export interface Model { */ enableConditionalFormatting?: boolean; + /** Enables the advanced filtering options Value Filtering, Label Filtering and Sorting for each fields in server mode. + * @Default {false} + */ + enableAdvancedFilter?: boolean; + /** Allows the user to refresh the control on-demand and not during every UI operation. * @Default {false} */ @@ -24914,7 +26950,7 @@ export interface Model { */ hyperlinkSettings?: HyperlinkSettings; - /** Allows the user to enable PivotGrid’s responsiveness in the browser layout. + /** Allows the user to enable PivotGrid’s responsiveness in the browser layout. * @Default {false} */ isResponsive?: boolean; @@ -24944,69 +26980,69 @@ export interface Model { serviceMethodSettings?: ServiceMethodSettings; /** Connects the service using the specified URL for any server updates. - * @Default {“”} + * @Default {“”} */ url?: string; /** Triggers when it reaches client-side after any AJAX request. */ - afterServiceInvoke? (e: AfterServiceInvokeEventArgs): void; + afterServiceInvoke?(e: AfterServiceInvokeEventArgs): void; /** Triggers before any AJAX request is passed from PivotGrid to service methods. */ - beforeServiceInvoke? (e: BeforeServiceInvokeEventArgs): void; + beforeServiceInvoke?(e: BeforeServiceInvokeEventArgs): void; /** Triggers before Pivot Engine starts to populate. */ - beforePivotEnginePopulate? (e: BeforePivotEnginePopulateEventArgs): void; + beforePivotEnginePopulate?(e: BeforePivotEnginePopulateEventArgs): void; /** Triggers when double click action is performed over a cell. */ - cellDoubleClick? (e: CellDoubleClickEventArgs): void; + cellDoubleClick?(e: CellDoubleClickEventArgs): void; /** Triggers when right-click action is performed on a cell. */ - cellContext? (e: CellContextEventArgs): void; + cellContext?(e: CellContextEventArgs): void; /** Triggers when a specific range of value cells are selected. */ - cellSelection? (e: CellSelectionEventArgs): void; + cellSelection?(e: CellSelectionEventArgs): void; /** Triggers when the hyperlink of column header is clicked. */ - columnHeaderHyperlinkClick? (e: ColumnHeaderHyperlinkClickEventArgs): void; + columnHeaderHyperlinkClick?(e: ColumnHeaderHyperlinkClickEventArgs): void; /** Triggers after performing drill operation in PivotGrid. */ - drillSuccess? (e: DrillSuccessEventArgs): void; + drillSuccess?(e: DrillSuccessEventArgs): void; /** Triggers while clicking "OK" button in the drill-through dialog. */ - drillThrough? (e: DrillThroughEventArgs): void; + drillThrough?(e: DrillThroughEventArgs): void; /** Triggers when PivotGrid loading is initiated. */ - load? (e: LoadEventArgs): void; + load?(e: LoadEventArgs): void; /** Triggers when PivotGrid widget completes all operations at client-side after any AJAX request. */ - renderComplete? (e: RenderCompleteEventArgs): void; + renderComplete?(e: RenderCompleteEventArgs): void; /** Triggers when any error occurred during AJAX request. */ - renderFailure? (e: RenderFailureEventArgs): void; + renderFailure?(e: RenderFailureEventArgs): void; /** Triggers when PivotGrid successfully reaches client-side after any AJAX request. */ - renderSuccess? (e: RenderSuccessEventArgs): void; + renderSuccess?(e: RenderSuccessEventArgs): void; /** Triggers when the hyperlink of row header is clicked. */ - rowHeaderHyperlinkClick? (e: RowHeaderHyperlinkClickEventArgs): void; + rowHeaderHyperlinkClick?(e: RowHeaderHyperlinkClickEventArgs): void; /** Triggers when the hyperlink of summary cell is clicked. */ - summaryCellHyperlinkClick? (e: SummaryCellHyperlinkClickEventArgs): void; + summaryCellHyperlinkClick?(e: SummaryCellHyperlinkClickEventArgs): void; /** Triggers when the hyperlink of value cell is clicked. */ - valueCellHyperlinkClick? (e: ValueCellHyperlinkClickEventArgs): void; + valueCellHyperlinkClick?(e: ValueCellHyperlinkClickEventArgs): void; /** Triggers before saving the current report to database. */ - saveReport? (e: SaveReportEventArgs): void; + saveReport?(e: SaveReportEventArgs): void; /** Triggers before loading a report from database. */ - loadReport? (e: LoadReportEventArgs): void; + loadReport?(e: LoadReportEventArgs): void; /** Triggers before performing exporting in pivot grid. */ - beforeExport? (e: BeforeExportEventArgs): void; + beforeExport?(e: BeforeExportEventArgs): void; /** Triggers before editing the cells. */ - cellEdit? (e: CellEditEventArgs): void; + cellEdit?(e: CellEditEventArgs): void; } export interface AfterServiceInvokeEventArgs { @@ -25050,7 +27086,7 @@ export interface CellDoubleClickEventArgs { /** returns the JSON details of the double clicked cell. */ - selectedData?: Array; + selectedData?: any[]; /** returns the custom object bound with PivotGrid control. */ @@ -25282,7 +27318,7 @@ export interface CellEditEventArgs { /** contains the array of cells selected for editing. */ - editCellsInfo?: Array; + editCellsInfo?: any[]; } export interface DataSourceColumnsAdvancedFilter { @@ -25311,7 +27347,7 @@ export interface DataSourceColumnsAdvancedFilter { /** Allows the user to hold the filter operand values in advanced filtering. */ - values?: Array; + values?: any[]; } export interface DataSourceColumnsFilterItems { @@ -25324,7 +27360,7 @@ export interface DataSourceColumnsFilterItems { /** Contains the collection of items to be included/excluded among the field members. * @Default {[]} */ - values?: Array; + values?: any[]; } export interface DataSourceColumn { @@ -25340,7 +27376,7 @@ export interface DataSourceColumn { /** Allows the user to filter the report by default using advanced filtering (excel-like) option for OLAP data source in client-mode. * @Default {[]} */ - advancedFilter?: Array; + advancedFilter?: DataSourceColumnsAdvancedFilter[]; /** Allows the user to indicate whether the added item is a named set or not. * @Default {false} @@ -25360,7 +27396,7 @@ export interface DataSourceColumn { /** Contains the list of members need to be drilled down by default in the field. * @Default {[]} */ - drilledItems?: Array; + drilledItems?: any[]; /** Applies filter to the field members. * @Default {null} @@ -25394,7 +27430,7 @@ export interface DataSourceRowsAdvancedFilter { /** Allows the user to hold the filter operand values in advanced filtering. */ - values?: Array; + values?: any[]; } export interface DataSourceRowsFilterItems { @@ -25407,7 +27443,7 @@ export interface DataSourceRowsFilterItems { /** Contains the collection of items to be included/excluded among the field members. * @Default {[]} */ - values?: Array; + values?: any[]; } export interface DataSourceRow { @@ -25423,7 +27459,7 @@ export interface DataSourceRow { /** Allows the user to filter the report by default using advanced filtering (excel-like) option for OLAP data source in client-mode. * @Default {[]} */ - advancedFilter?: Array; + advancedFilter?: DataSourceRowsAdvancedFilter[]; /** Allows the user to indicate whether the added item is a named set or not. * @Default {false} @@ -25443,7 +27479,7 @@ export interface DataSourceRow { /** Contains the list of members need to be drilled down by default in the field. * @Default {[]} */ - drilledItems?: Array; + drilledItems?: any[]; /** Applies filter to the field members. * @Default {null} @@ -25471,7 +27507,7 @@ export interface DataSourceValue { /** This holds the list of unique names of measures to bind them from the OLAP cube. * @Default {[]} */ - measures?: Array; + measures?: DataSourceValuesMeasure[]; /** Allows to set the axis name to place the measures items. * @Default {rows} @@ -25511,7 +27547,7 @@ export interface DataSourceFiltersFilterItems { /** Contains the collection of items to be included/excluded among the field members. * @Default {[]} */ - values?: Array; + values?: any[]; } export interface DataSourceFilter { @@ -25558,25 +27594,25 @@ export interface DataSource { /** Lists out the items to be arranged in columns section of PivotGrid. * @Default {[]} */ - columns?: Array; + columns?: DataSourceColumn[]; /** Lists out the items to be arranged in rows section of PivotGrid. * @Default {[]} */ - rows?: Array; + rows?: DataSourceRow[]; /** Lists out the items which supports calculation in PivotGrid. * @Default {[]} */ - values?: Array; + values?: DataSourceValue[]; /** Lists out the items which supports filtering of values without displaying the members in UI in PivotGrid. * @Default {[]} */ - filters?: Array; + filters?: DataSourceFilter[]; /** Contains the respective cube name from OLAP database as string type. - * @Default {“”} + * @Default {“”} */ cube?: string; @@ -25586,7 +27622,7 @@ export interface DataSource { data?: any; /** In connection with an OLAP database, this property contains the database name as string to fetch the data from the given connection string. - * @Default {“”} + * @Default {“”} */ catalog?: string; @@ -25605,6 +27641,22 @@ export interface DataSource { pagerOptions?: DataSourcePagerOptions; } +export interface ValueSortSettings { + + /** Contains the headers of the specific column to which value sorting is applied. + */ + headerText?: string; + + /** Allows the user to set the string for separating column headers provided in the above property headerText. + */ + headerDelimiters?: string; + + /** Allows the user to set the sorting order of the values of the field. + * @Default {ej.PivotAnalysis.SortOrder.Ascending} + */ + sortOrder?: ej.PivotAnalysis.SortOrder|string; +} + export interface FrozenHeaderSettings { /** Allows the user to freeze the row headers alone on scrolling the horizontal scroll bar. @@ -25739,7 +27791,7 @@ export interface ServiceMethodSettings { writeBack?: string; } -enum Layout{ +enum Layout { ///To set normal summary layout in PivotGrid. Normal, @@ -25755,20 +27807,16 @@ enum Layout{ } } -module Pivot -{ -enum AnalysisMode -{ +namespace Pivot { +enum AnalysisMode { //To bind an OLAP data source to PivotGrid. OLAP, //To bind a relational data source to PivotGrid. Pivot, } } -module PivotAnalysis -{ -enum SortOrder -{ +namespace PivotAnalysis { +enum SortOrder { //Sorts the members of the field in ascending order. Ascending, //Sorts the members of the field in descending order. @@ -25777,20 +27825,16 @@ Descending, None, } } -module PivotAnalysis -{ -enum FilterType -{ +namespace PivotAnalysis { +enum FilterType { //Excludes the specified values among the members of the field. Exclude, //Includes the specified values alone among the members of the field. Include, } } -module PivotAnalysis -{ -enum SummaryType -{ +namespace PivotAnalysis { +enum SummaryType { //Calculates the summary as the total of all values. Sum, //Displays the average of all values as the summaries. @@ -25803,10 +27847,8 @@ Min, Max, } } -module Pivot -{ -enum OperationalMode -{ +namespace Pivot { +enum OperationalMode { //To bind data source completely from client-side. ClientMode, //To bind data source completely from server-side. @@ -25816,11 +27858,10 @@ ServerMode, class PivotSchemaDesigner extends ej.Widget { static fn: PivotSchemaDesigner; - constructor(element: JQuery, options?: PivotSchemaDesigner.Model); - constructor(element: Element, options?: PivotSchemaDesigner.Model); + constructor(element: JQuery | Element, options?: PivotSchemaDesigner.Model); static Locale: any; - model:PivotSchemaDesigner.Model; - defaults:PivotSchemaDesigner.Model; + model: PivotSchemaDesigner.Model; + defaults: PivotSchemaDesigner.Model; /** Performs an asynchronous HTTP (AJAX) request. * @returns {void} @@ -25832,12 +27873,12 @@ class PivotSchemaDesigner extends ej.Widget { */ refreshControl(): void; } -export module PivotSchemaDesigner{ +export namespace PivotSchemaDesigner { export interface Model { /** Specifies the CSS class to PivotSchemaDesigner to achieve custom theme. - * @Default {“”} + * @Default {“”} */ cssClass?: string; @@ -25846,7 +27887,8 @@ export interface Model { */ customObject?: any; - /** For ASP.NET and MVC Wrapper, PivotSchemaDesigner will be initialized and rendered empty initially. Once the connected pivot control widget is rendered completely, PivotSchemaDesigner will just be populated with data source by setting this property to “true”. + /** For ASP.NET and MVC Wrapper, PivotSchemaDesigner will be initialized and rendered empty initially. Once the connected pivot control widget is rendered completely, + * PivotSchemaDesigner will just be populated with data source by setting this property to “true”. * @Default {false} */ enableWrapper?: boolean; @@ -25867,7 +27909,7 @@ export interface Model { enableDragDrop?: boolean; /** Sets the height for PivotSchemaDesigner. - * @Default {“”} + * @Default {“”} */ height?: string; @@ -25887,12 +27929,12 @@ export interface Model { serviceMethod?: ServiceMethod; /** Connects the service using the specified URL for any server updates. - * @Default {“”} + * @Default {“”} */ url?: string; /** Sets the width for PivotSchemaDesigner. - * @Default {“”} + * @Default {“”} */ width?: string; @@ -25902,13 +27944,13 @@ export interface Model { layout?: ej.PivotSchemaDesigner.Layouts|string; /** Triggers when it reaches client-side after any AJAX request. */ - afterServiceInvoke? (e: AfterServiceInvokeEventArgs): void; + afterServiceInvoke?(e: AfterServiceInvokeEventArgs): void; /** Triggers before any AJAX request is passed from PivotSchemaDesigner to service methods. */ - beforeServiceInvoke? (e: BeforeServiceInvokeEventArgs): void; + beforeServiceInvoke?(e: BeforeServiceInvokeEventArgs): void; /** Triggers when we start dragging any field from PivotSchemaDesigner. */ - dragMove? (e: DragMoveEventArgs): void; + dragMove?(e: DragMoveEventArgs): void; } export interface AfterServiceInvokeEventArgs { @@ -26006,7 +28048,7 @@ export interface ServiceMethod { removeButton?: string; } -enum Layouts{ +enum Layouts { ///To set the layout as same in the Excel. Excel, @@ -26022,18 +28064,17 @@ enum Layouts{ class PivotPager extends ej.Widget { static fn: PivotPager; - constructor(element: JQuery, options?: PivotPager.Model); - constructor(element: Element, options?: PivotPager.Model); + constructor(element: JQuery | Element, options?: PivotPager.Model); static Locale: any; - model:PivotPager.Model; - defaults:PivotPager.Model; + model: PivotPager.Model; + defaults: PivotPager.Model; /** This function initializes the page counts and page numbers for the PivotPager. * @returns {void} */ initPagerProperties(): void; } -export module PivotPager{ +export namespace PivotPager { export interface Model { @@ -26068,12 +28109,12 @@ export interface Model { seriesPageCount?: number; /** Contains the ID of the target element for which paging needs to be done. - * @Default {“”} + * @Default {“”} */ targetControlID?: string; } -enum Mode{ +enum Mode { ///To set both categorical and series pager for paging. Both, @@ -26089,11 +28130,10 @@ enum Mode{ class PivotChart extends ej.Widget { static fn: PivotChart; - constructor(element: JQuery, options?: PivotChart.Model); - constructor(element: Element, options?: PivotChart.Model); + constructor(element: JQuery | Element, options?: PivotChart.Model); static Locale: any; - model:PivotChart.Model; - defaults:PivotChart.Model; + model: PivotChart.Model; + defaults: PivotChart.Model; /** Performs an asynchronous HTTP (AJAX) request. * @returns {void} @@ -26133,7 +28173,7 @@ class PivotChart extends ej.Widget { /** Returns the JSON records formed to render the control. * @returns {Array} */ - getJSONRecords(): Array; + getJSONRecords(): any[]; /** Sets the JSON records to render the control. * @returns {void} @@ -26143,7 +28183,7 @@ class PivotChart extends ej.Widget { /** Returns the PivotEngine formed to render the control. * @returns {Array} */ - getPivotEngine(): Array; + getPivotEngine(): any[]; /** Sets the PivotEngine required to render the control. * @returns {void} @@ -26165,7 +28205,7 @@ class PivotChart extends ej.Widget { */ refreshPagedPivotChart(): void; } -export module PivotChart{ +export namespace PivotChart { export interface Model { @@ -26175,7 +28215,7 @@ export interface Model { analysisMode?: ej.Pivot.AnalysisMode|string; /** Specifies the CSS class to PivotChart to achieve custom theme. - * @Default {“”} + * @Default {“”} */ cssClass?: string; @@ -26209,7 +28249,7 @@ export interface Model { */ enableRTL?: boolean; - /** Allows the user to enable PivotChart’s responsiveness in the browser layout. + /** Allows the user to enable PivotChart’s responsiveness in the browser layout. * @Default {false} */ isResponsive?: boolean; @@ -26229,12 +28269,16 @@ export interface Model { */ operationalMode?: ej.Pivot.OperationalMode|string; - /** This is a horizontal axis that contains options to configure axis and it is the primary x axis for all the series in series array. To override x axis for particular series, create an axis object by providing unique name by using name property and add it to axes array. Then, assign the name to the series’s xAxisName property to link both axis and series. + /** This is a horizontal axis that contains options to configure axis and it is the primary x axis for all the series in series array. + * To override x axis for particular series, create an axis object by providing unique name by using name property and add it to axes array. + * Then, assign the name to the series’s xAxisName property to link both axis and series. * @Default {{}} */ primaryXAxis?: any; - /** This is a vertical axis that contains options to configure axis. This is the primary y axis for all the series in series array. To override y axis for particular series, create an axis object by providing unique name by using name property and add it to axes array. Then, assign the name to the series’s yAxisName property to link both axis and series. + /** This is a vertical axis that contains options to configure axis. This is the primary y axis for all the series in series array. + * To override y axis for particular series, create an axis object by providing unique name by using name property and add it to axes array. + * Then, assign the name to the series’s yAxisName property to link both axis and series. * @Default {{}} */ primaryYAxis?: any; @@ -26255,33 +28299,33 @@ export interface Model { size?: any; /** Connects the service using the specified URL for any server updates on operating the control in server mode. - * @Default {“”} + * @Default {“”} */ url?: string; /** Triggers when PivotChart starts to render. */ - load? (e: LoadEventArgs): void; + load?(e: LoadEventArgs): void; /** Triggers when it reaches client-side after any AJAX request. */ - afterServiceInvoke? (e: AfterServiceInvokeEventArgs): void; + afterServiceInvoke?(e: AfterServiceInvokeEventArgs): void; /** Triggers before any AJAX request is passed from PivotChart to service methods. */ - beforeServiceInvoke? (e: BeforeServiceInvokeEventArgs): void; + beforeServiceInvoke?(e: BeforeServiceInvokeEventArgs): void; /** Triggers on performing drill up/down in PivotChart control. */ - drillSuccess? (e: DrillSuccessEventArgs): void; + drillSuccess?(e: DrillSuccessEventArgs): void; /** Triggers when PivotChart widget completes all operations at client-side after any AJAX request. */ - renderComplete? (e: RenderCompleteEventArgs): void; + renderComplete?(e: RenderCompleteEventArgs): void; /** Triggers when any error occurred during AJAX request. */ - renderFailure? (e: RenderFailureEventArgs): void; + renderFailure?(e: RenderFailureEventArgs): void; /** Triggers when PivotChart successfully reaches client-side after any AJAX request. */ - renderSuccess? (e: RenderSuccessEventArgs): void; + renderSuccess?(e: RenderSuccessEventArgs): void; /** Triggers before performing exporting in pivot chart. */ - beforeExport? (e: BeforeExportEventArgs): void; + beforeExport?(e: BeforeExportEventArgs): void; } export interface LoadEventArgs { @@ -26426,7 +28470,7 @@ export interface DataSourceColumnsFilterItems { /** Contains the collection of items to be included/excluded among the field members. * @Default {[]} */ - values?: Array; + values?: any[]; } export interface DataSourceColumn { @@ -26465,7 +28509,7 @@ export interface DataSourceRowsFilterItems { /** Contains the collection of items to be included/excluded among the field members. * @Default {[]} */ - values?: Array; + values?: any[]; } export interface DataSourceRow { @@ -26514,7 +28558,7 @@ export interface DataSourceValue { /** This holds the list of unique names of measures to bind them from the OLAP cube. * @Default {[]} */ - measures?: Array; + measures?: DataSourceValuesMeasure[]; /** Allows to set the axis name to place the measures items. * @Default {rows} @@ -26541,7 +28585,7 @@ export interface DataSourceFiltersFilterItems { /** Contains the collection of items to be included/excluded among the field members. * @Default {[]} */ - values?: Array; + values?: any[]; } export interface DataSourceFilter { @@ -26559,7 +28603,7 @@ export interface DataSourceFilter { export interface DataSource { /** Contains the respective cube name from OLAP database as string type. - * @Default {“”} + * @Default {“”} */ cube?: string; @@ -26569,29 +28613,29 @@ export interface DataSource { data?: any; /** In connection with an OLAP database, this property contains the database name as string to fetch the data from the given connection string. - * @Default {“”} + * @Default {“”} */ catalog?: string; /** Lists out the items to be displayed as series of PivotChart. * @Default {[]} */ - columns?: Array; + columns?: DataSourceColumn[]; /** Lists out the items to be displayed as segments of PivotChart. * @Default {[]} */ - rows?: Array; + rows?: DataSourceRow[]; /** Lists out the items supports calculation in PivotChart. * @Default {[]} */ - values?: Array; + values?: DataSourceValue[]; /** Lists out the items which supports filtering of values without displaying the members in UI in PivotChart. * @Default {[]} */ - filters?: Array; + filters?: DataSourceFilter[]; } export interface ServiceMethodSettings { @@ -26617,7 +28661,7 @@ export interface ServiceMethodSettings { paging?: string; } -enum ChartTypes{ +enum ChartTypes { ///To render a Line type PivotChart. Line, @@ -26675,11 +28719,10 @@ enum ChartTypes{ class PivotClient extends ej.Widget { static fn: PivotClient; - constructor(element: JQuery, options?: PivotClient.Model); - constructor(element: Element, options?: PivotClient.Model); + constructor(element: JQuery | Element, options?: PivotClient.Model); static Locale: any; - model:PivotClient.Model; - defaults:PivotClient.Model; + model: PivotClient.Model; + defaults: PivotClient.Model; /** Performs an asynchronous HTTP (AJAX) request. * @returns {void} @@ -26724,14 +28767,14 @@ class PivotClient extends ej.Widget { /** Returns the JSON records formed to render the control. * @returns {Array} */ - getJSONRecords(): Array; + getJSONRecords(): any[]; /** Sets the JSON records formed to render the control to a property. * @returns {void} */ setJSONRecords(): void; } -export module PivotClient{ +export namespace PivotClient { export interface Model { @@ -26751,7 +28794,7 @@ export interface Model { clientExportMode?: ej.PivotClient.ClientExportMode|string; /** Specifies the CSS class to PivotClient to achieve custom theme. - * @Default {“”} + * @Default {“”} */ cssClass?: string; @@ -26770,6 +28813,11 @@ export interface Model { */ displaySettings?: DisplaySettings; + /** Enables the splitter option for resizing the elements inside the control. + * @Default {false} + */ + enableSplitter?: boolean; + /** Enables the advanced filtering options Value Filtering, Label Filtering and Sorting for each dimensions on binding OLAP data in server mode. * @Default {false} */ @@ -26849,40 +28897,40 @@ export interface Model { url?: string; /** Triggers when it reaches client-side after any AJAX request. */ - afterServiceInvoke? (e: AfterServiceInvokeEventArgs): void; + afterServiceInvoke?(e: AfterServiceInvokeEventArgs): void; /** Triggers before any AJAX request is passed from client-side to service methods. */ - beforeServiceInvoke? (e: BeforeServiceInvokeEventArgs): void; + beforeServiceInvoke?(e: BeforeServiceInvokeEventArgs): void; /** Triggers before saving the current collection of reports. */ - saveReport? (e: SaveReportEventArgs): void; + saveReport?(e: SaveReportEventArgs): void; /** Triggers before loading a saved collection of reports. */ - loadReport? (e: LoadReportEventArgs): void; + loadReport?(e: LoadReportEventArgs): void; /** Triggers before fetching the report collection from storage. */ - fetchReport? (e: FetchReportEventArgs): void; + fetchReport?(e: FetchReportEventArgs): void; /** Triggers before exporting the control. */ - beforeExport? (e: BeforeExportEventArgs): void; + beforeExport?(e: BeforeExportEventArgs): void; /** Triggers before rendering the PivotChart. */ - chartLoad? (e: ChartLoadEventArgs): void; + chartLoad?(e: ChartLoadEventArgs): void; /** Triggers before rendering the PivotTreeMap. */ - treeMapLoad? (e: TreeMapLoadEventArgs): void; + treeMapLoad?(e: TreeMapLoadEventArgs): void; /** Triggers while we initiate loading of the widget. */ - load? (e: LoadEventArgs): void; + load?(e: LoadEventArgs): void; /** Triggers when PivotClient widget completes all operations at client-end after any AJAX request. */ - renderComplete? (e: RenderCompleteEventArgs): void; + renderComplete?(e: RenderCompleteEventArgs): void; /** Triggers when any error occurred during AJAX request. */ - renderFailure? (e: RenderFailureEventArgs): void; + renderFailure?(e: RenderFailureEventArgs): void; /** Triggers when PivotClient successfully completes rendering. */ - renderSuccess? (e: RenderSuccessEventArgs): void; + renderSuccess?(e: RenderSuccessEventArgs): void; } export interface AfterServiceInvokeEventArgs { @@ -27059,7 +29107,7 @@ export interface DataSourceColumnsAdvancedFilter { /** Allows the user to hold the filter operand values in advanced filtering. */ - values?: Array; + values?: any[]; } export interface DataSourceColumnsFilterItems { @@ -27072,7 +29120,7 @@ export interface DataSourceColumnsFilterItems { /** Contains the collection of items to be included/excluded among the field members. * @Default {[]} */ - values?: Array; + values?: any[]; } export interface DataSourceColumn { @@ -27088,7 +29136,7 @@ export interface DataSourceColumn { /** Allows the user to filter the report by default using advanced filtering (excel-like) option for OLAP data source in client-mode. * @Default {[]} */ - advancedFilter?: Array; + advancedFilter?: DataSourceColumnsAdvancedFilter[]; /** Allows the user to indicate whether the added item is a named set or not. * @Default {false} @@ -27108,7 +29156,7 @@ export interface DataSourceColumn { /** Contains the list of members need to be drilled down by default in the field. * @Default {[]} */ - drilledItems?: Array; + drilledItems?: any[]; /** Applies filter to the field members. * @Default {null} @@ -27142,7 +29190,7 @@ export interface DataSourceRowsAdvancedFilter { /** Allows the user to hold the filter operand values in advanced filtering. */ - values?: Array; + values?: any[]; } export interface DataSourceRowsFilterItems { @@ -27155,7 +29203,7 @@ export interface DataSourceRowsFilterItems { /** Contains the collection of items to be included/excluded among the field members. * @Default {[]} */ - values?: Array; + values?: any[]; } export interface DataSourceRow { @@ -27171,7 +29219,7 @@ export interface DataSourceRow { /** Allows the user to filter the report by default using advanced filtering (excel-like) option for OLAP data source in client-mode. * @Default {[]} */ - advancedFilter?: Array; + advancedFilter?: DataSourceRowsAdvancedFilter[]; /** Allows the user to indicate whether the added item is a named set or not. * @Default {false} @@ -27191,7 +29239,7 @@ export interface DataSourceRow { /** Contains the list of members need to be drilled down by default in the field. * @Default {[]} */ - drilledItems?: Array; + drilledItems?: any[]; /** Applies filter to the field members. * @Default {null} @@ -27219,7 +29267,7 @@ export interface DataSourceValue { /** This holds the list of unique names of measures to bind them from the OLAP cube. * @Default {[]} */ - measures?: Array; + measures?: DataSourceValuesMeasure[]; /** Allows to set the axis name to place the measures items. * @Default {rows} @@ -27259,7 +29307,7 @@ export interface DataSourceFiltersFilterItems { /** Contains the collection of items to be included/excluded among the field members. * @Default {[]} */ - values?: Array; + values?: any[]; } export interface DataSourceFilter { @@ -27306,25 +29354,25 @@ export interface DataSource { /** Lists out the items to be arranged in columns section of PivotClient. * @Default {[]} */ - columns?: Array; + columns?: DataSourceColumn[]; /** Lists out the items to be arranged in rows section of PivotClient. * @Default {[]} */ - rows?: Array; + rows?: DataSourceRow[]; /** Lists out the items which supports calculation in PivotClient. * @Default {[]} */ - values?: Array; + values?: DataSourceValue[]; /** Lists out the items which supports filtering of values without displaying the members in UI in PivotClient. * @Default {[]} */ - filters?: Array; + filters?: DataSourceFilter[]; /** Contains the respective cube name from OLAP database as string type. - * @Default {“”} + * @Default {“”} */ cube?: string; @@ -27334,11 +29382,11 @@ export interface DataSource { data?: any; /** In connection with an OLAP database, this property contains the database name as string to fetch the data from the given connection string. - * @Default {“”} + * @Default {“”} */ catalog?: string; - /** Allows user to filter the members (by its name and values) through advanced filtering (excel-like) option for OLAP data source in client-mode. + /** Allows user to filter the members (by its name and values) through advanced filtering (excel-like) option in client-mode. * @Default {false} */ enableAdvancedFilter?: boolean; @@ -27375,7 +29423,7 @@ export interface DisplaySettings { */ enableTogglePanel?: boolean; - /** Allows the user to enable PivotClient’s responsiveness in the browser layout. + /** Allows the user to enable PivotClient’s responsiveness in the browser layout. * @Default {false} */ isResponsive?: boolean; @@ -27474,7 +29522,7 @@ export interface ServiceMethodSettings { paging?: string; } -enum ClientExportMode{ +enum ClientExportMode { ///Exports both the PivotChart and PivotGrid on exporting. ChartAndGrid, @@ -27487,7 +29535,7 @@ enum ClientExportMode{ } -enum ControlPlacement{ +enum ControlPlacement { ///Displays PivotChart and PivotGrid widgets in separate tabs. Tab, @@ -27497,7 +29545,7 @@ enum ControlPlacement{ } -enum DefaultView{ +enum DefaultView { ///To set PivotChart as a default control in view. Chart, @@ -27507,7 +29555,7 @@ enum DefaultView{ } -enum DisplayMode{ +enum DisplayMode { ///To display only PivotChart widget. ChartOnly, @@ -27523,11 +29571,10 @@ enum DisplayMode{ class PivotGauge extends ej.Widget { static fn: PivotGauge; - constructor(element: JQuery, options?: PivotGauge.Model); - constructor(element: Element, options?: PivotGauge.Model); + constructor(element: JQuery | Element, options?: PivotGauge.Model); static Locale: any; - model:PivotGauge.Model; - defaults:PivotGauge.Model; + model: PivotGauge.Model; + defaults: PivotGauge.Model; /** Performs an asynchronous HTTP (AJAX) request. * @returns {void} @@ -27562,7 +29609,7 @@ class PivotGauge extends ej.Widget { /** Returns the JSON records formed to render the control. * @returns {Array} */ - getJSONRecords(): Array; + getJSONRecords(): any[]; /** Sets the JSON records to render the control. * @returns {void} @@ -27574,7 +29621,7 @@ class PivotGauge extends ej.Widget { */ getJSONData(): void; } -export module PivotGauge{ +export namespace PivotGauge { export interface Model { @@ -27584,7 +29631,7 @@ export interface Model { columnsCount?: number; /** Specifies the CSS class to PivotGauge to achieve custom theme. - * @Default {“”} + * @Default {“”} */ cssClass?: string; @@ -27613,7 +29660,7 @@ export interface Model { */ enableRTL?: boolean; - /** Allows the user to enable PivotGauge’s responsiveness in the browser layout. + /** Allows the user to enable PivotGauge’s responsiveness in the browser layout. * @Default {false} */ isResponsive?: boolean; @@ -27649,7 +29696,7 @@ export interface Model { showHeaderLabel?: boolean; /** Connects the service using the specified URL for any server updates on server mode operation. - * @Default {“”} + * @Default {“”} */ url?: string; @@ -27664,25 +29711,25 @@ export interface Model { operationalMode?: ej.Pivot.OperationalMode|string; /** Triggers when it reaches client-side after any AJAX request. */ - afterServiceInvoke? (e: AfterServiceInvokeEventArgs): void; + afterServiceInvoke?(e: AfterServiceInvokeEventArgs): void; /** Triggers before any AJAX request is passed from PivotGauge to service methods. */ - beforeServiceInvoke? (e: BeforeServiceInvokeEventArgs): void; + beforeServiceInvoke?(e: BeforeServiceInvokeEventArgs): void; /** Triggers before populating the pivot engine on operating in client mode. */ - beforePivotEnginePopulate? (e: BeforePivotEnginePopulateEventArgs): void; + beforePivotEnginePopulate?(e: BeforePivotEnginePopulateEventArgs): void; /** Triggers when PivotGauge started loading at client-side. */ - load? (e: LoadEventArgs): void; + load?(e: LoadEventArgs): void; /** Triggers when PivotGauge widget completes all operations at client-side after any AJAX request. */ - renderComplete? (e: RenderCompleteEventArgs): void; + renderComplete?(e: RenderCompleteEventArgs): void; /** Triggers when any error occurred during AJAX request. */ - renderFailure? (e: RenderFailureEventArgs): void; + renderFailure?(e: RenderFailureEventArgs): void; /** Triggers when PivotGauge successfully reaches client-side after any AJAX request. */ - renderSuccess? (e: RenderSuccessEventArgs): void; + renderSuccess?(e: RenderSuccessEventArgs): void; } export interface AfterServiceInvokeEventArgs { @@ -27780,7 +29827,7 @@ export interface DataSourceColumnsFilterItems { /** Contains the collection of items to be included/excluded among the field members. * @Default {[]} */ - values?: Array; + values?: any[]; } export interface DataSourceColumn { @@ -27805,7 +29852,7 @@ export interface DataSourceRowsFilterItems { /** Contains the collection of items to be included/excluded among the field members. * @Default {[]} */ - values?: Array; + values?: any[]; } export interface DataSourceRow { @@ -27840,7 +29887,7 @@ export interface DataSourceValue { /** This holds the list of unique names of measures to bind them from the OLAP cube. * @Default {[]} */ - measures?: Array; + measures?: DataSourceValuesMeasure[]; /** Allows to set the axis name to place the measures items. * @Default {rows} @@ -27867,7 +29914,7 @@ export interface DataSourceFiltersFilterItems { /** Contains the collection of items to be included/excluded among the field members. * @Default {[]} */ - values?: Array; + values?: any[]; } export interface DataSourceFilter { @@ -27885,7 +29932,7 @@ export interface DataSourceFilter { export interface DataSource { /** Contains the respective cube name from OLAP database as string type. - * @Default {“”} + * @Default {“”} */ cube?: string; @@ -27895,29 +29942,29 @@ export interface DataSource { data?: any; /** In connection with an OLAP database, this property contains the database name as string to fetch the data from the given connection string. - * @Default {“”} + * @Default {“”} */ catalog?: string; /** Lists out the items to bind in columns section. * @Default {[]} */ - columns?: Array; + columns?: DataSourceColumn[]; /** Lists out the items to bind in rows section. * @Default {[]} */ - rows?: Array; + rows?: DataSourceRow[]; /** Lists out the items supports calculation in PivotGauge. * @Default {[]} */ - values?: Array; + values?: DataSourceValue[]; /** Lists out the items which supports filtering of values without displaying the members in UI in PivotGauge. * @Default {[]} */ - filters?: Array; + filters?: DataSourceFilter[]; } export interface LabelFormatSettings { @@ -27949,7 +29996,7 @@ export interface ServiceMethodSettings { initialize?: string; } -enum NumberFormat{ +enum NumberFormat { ///To set default format for label values. Default, @@ -27977,11 +30024,10 @@ enum NumberFormat{ class PivotTreeMap extends ej.Widget { static fn: PivotTreeMap; - constructor(element: JQuery, options?: PivotTreeMap.Model); - constructor(element: Element, options?: PivotTreeMap.Model); + constructor(element: JQuery | Element, options?: PivotTreeMap.Model); static Locale: any; - model:PivotTreeMap.Model; - defaults:PivotTreeMap.Model; + model: PivotTreeMap.Model; + defaults: PivotTreeMap.Model; /** Performs an asynchronous HTTP (AJAX) request. * @returns {void} @@ -28001,7 +30047,7 @@ class PivotTreeMap extends ej.Widget { /** Returns the JSON records formed to render the control. * @returns {Array} */ - getJSONRecords(): Array; + getJSONRecords(): any[]; /** Sets the JSON records to render the control. * @returns {void} @@ -28023,12 +30069,12 @@ class PivotTreeMap extends ej.Widget { */ renderControlSuccess(): void; } -export module PivotTreeMap{ +export namespace PivotTreeMap { export interface Model { /** Specifies the CSS class to PivotTreeMap to achieve custom theme. - * @Default {“”} + * @Default {“”} */ cssClass?: string; @@ -28042,7 +30088,7 @@ export interface Model { */ customObject?: any; - /** Allows the user to enable PivotTreeMap’s responsiveness in the browser layout. + /** Allows the user to enable PivotTreeMap’s responsiveness in the browser layout. * @Default {false} */ isResponsive?: boolean; @@ -28063,33 +30109,33 @@ export interface Model { serviceMethodSettings?: ServiceMethodSettings; /** Connects the service using the specified URL for any server updates. - * @Default {“”} + * @Default {“”} */ url?: string; /** Triggers when it reaches client-side after any AJAX request. */ - afterServiceInvoke? (e: AfterServiceInvokeEventArgs): void; + afterServiceInvoke?(e: AfterServiceInvokeEventArgs): void; /** Triggers before any AJAX request is passed from PivotTreeMap to service methods. */ - beforeServiceInvoke? (e: BeforeServiceInvokeEventArgs): void; + beforeServiceInvoke?(e: BeforeServiceInvokeEventArgs): void; /** Triggers when PivotTreeMap starts to render. */ - load? (e: LoadEventArgs): void; + load?(e: LoadEventArgs): void; /** Triggers before populating the pivot engine from datasource. */ - beforePivotEnginePopulate? (e: BeforePivotEnginePopulateEventArgs): void; + beforePivotEnginePopulate?(e: BeforePivotEnginePopulateEventArgs): void; /** Triggers when drill up/down happens in PivotTreeMap control. And it returns the outer HTML of PivotTreeMap control. */ - drillSuccess? (e: DrillSuccessEventArgs): void; + drillSuccess?(e: DrillSuccessEventArgs): void; /** Triggers when PivotTreeMap widget completes all operations at client-side after any AJAX request. */ - renderComplete? (e: RenderCompleteEventArgs): void; + renderComplete?(e: RenderCompleteEventArgs): void; /** Triggers when any error occurred during AJAX request. */ - renderFailure? (e: RenderFailureEventArgs): void; + renderFailure?(e: RenderFailureEventArgs): void; /** Triggers when PivotTreeMap successfully reaches client-side after any AJAX request. */ - renderSuccess? (e: RenderSuccessEventArgs): void; + renderSuccess?(e: RenderSuccessEventArgs): void; } export interface AfterServiceInvokeEventArgs { @@ -28205,7 +30251,7 @@ export interface DataSourceColumnsFilterItems { /** Contains the collection of items to be excluded among the field members. * @Default {[]} */ - values?: Array; + values?: any[]; } export interface DataSourceColumn { @@ -28230,7 +30276,7 @@ export interface DataSourceRowsFilterItems { /** Contains the collection of items to be excluded among the field members. * @Default {[]} */ - values?: Array; + values?: any[]; } export interface DataSourceRow { @@ -28262,7 +30308,7 @@ export interface DataSourceValue { /** This holds the list of unique names of measures to bind them from the OLAP cube. * @Default {[]} */ - measures?: Array; + measures?: DataSourceValuesMeasure[]; /** Allows to set the axis name to place the measures items. * @Default {rows} @@ -28275,7 +30321,7 @@ export interface DataSourceFiltersFilterItems { /** Contains the collection of items to be excluded among the field members. * @Default {[]} */ - values?: Array; + values?: any[]; } export interface DataSourceFilter { @@ -28298,34 +30344,34 @@ export interface DataSource { data?: any; /** Contains the respective cube name from OLAP database as string type. - * @Default {“”} + * @Default {“”} */ cube?: string; /** In connection with an OLAP database, this property contains the database name as string to fetch the data from the given connection string. - * @Default {“”} + * @Default {“”} */ catalog?: string; /** Lists out the items to be displayed as series of PivotTreeMap. * @Default {[]} */ - columns?: Array; + columns?: DataSourceColumn[]; /** Lists out the items to be displayed as segments of PivotTreeMap. * @Default {[]} */ - rows?: Array; + rows?: DataSourceRow[]; /** Lists out the items supports calculation in PivotTreeMap. * @Default {[]} */ - values?: Array; + values?: DataSourceValue[]; /** Lists out the items which supports filtering of values without displaying the members in UI in PivotTreeMap. * @Default {[]} */ - filters?: Array; + filters?: DataSourceFilter[]; } export interface ServiceMethodSettings { @@ -28344,11 +30390,10 @@ export interface ServiceMethodSettings { class Schedule extends ej.Widget { static fn: Schedule; - constructor(element: JQuery, options?: Schedule.Model); - constructor(element: Element, options?: Schedule.Model); + constructor(element: JQuery | Element, options?: Schedule.Model); static Locale: any; - model:Schedule.Model; - defaults:Schedule.Model; + model: Schedule.Model; + defaults: Schedule.Model; /** This method is used to delete the appointment based on the guid value or the appointment data passed to it. * @param {string|any} GUID value of an appointment element or an appointment object @@ -28373,14 +30418,15 @@ class Schedule extends ej.Widget { * @param {Array} Holds array of one or more conditional objects for filtering the appointments based on it. * @returns {Array} */ - filterAppointments(filterConditions: Array): Array; + filterAppointments(filterConditions: any[]): any[]; /** Gets the complete appointment list of Schedule control. * @returns {Array} */ - getAppointments(): Array; + getAppointments(): any[]; - /** Prints the entire Scheduler or a single appointment based on the appointment data passed as an argument to it. Simply calling the print() method, without passing any argument will print the entire Scheduler. + /** Prints the entire Scheduler or a single appointment based on the appointment data passed as an argument to it. Simply calling the print() method, + * without passing any argument will print the entire Scheduler. * @param {any} Either accepts no arguments at all or else accepts an appointment object. * @returns {void} */ @@ -28402,7 +30448,9 @@ class Schedule extends ej.Widget { */ getRecurrenceRule(): string; - /** Retrieves the time slot information (start/end time and resource details) of the given element. The parameter is optional - as when no element is passed to it, the currently selected cell information will be retrieved. When multiple cells are selected in the Scheduler, it is not necessary to provide the parameter. + /** Retrieves the time slot information (start/end time and resource details) of the given element. + * The parameter is optional - as when no element is passed to it, the currently selected cell information will be retrieved. When multiple cells are selected in the Scheduler, + * it is not necessary to provide the parameter. * @param {any} TD element object rendered as Scheduler work cell * @returns {any} */ @@ -28415,7 +30463,7 @@ class Schedule extends ej.Widget { * @param {boolean} Defines the ignoreCase value for performing the search operation. * @returns {Array} */ - searchAppointments(searchString: any|string, field: string, operator: ej.FilterOperators|string, ignoreCase: boolean): Array; + searchAppointments(searchString: any|string, field: string, operator: ej.FilterOperators|string, ignoreCase: boolean): any[]; /** Refreshes the entire Schedule control. * @returns {void} @@ -28432,7 +30480,7 @@ class Schedule extends ej.Widget { */ notifyChanges(): void; } -export module Schedule{ +export namespace Schedule { export interface Model { @@ -28446,11 +30494,13 @@ export interface Model { */ allowKeyboardNavigation?: boolean; - /** It includes the dataSource option and the fields related to Schedule appointments. The appointment fields within the appointmentSettings can accept both string and object type values. To apply validation rules on the appointment window fields, then the appointment fields needs to be defined with object type values. + /** It includes the dataSource option and the fields related to Schedule appointments. The appointment fields within the appointmentSettings can accept both string and object type values. + * To apply validation rules on the appointment window fields, then the appointment fields needs to be defined with object type values. */ appointmentSettings?: AppointmentSettings; - /** Template design that applies on the Schedule appointments. All the field names that are mapped from dataSource to the appropriate field properties within the appointmentSettings can be used within the template. + /** Template design that applies on the Schedule appointments. All the field names that are mapped from dataSource + * to the appropriate field properties within the appointmentSettings can be used within the template. * @Default {null} */ appointmentTemplateId?: string; @@ -28481,7 +30531,9 @@ export interface Model { */ currentDate?: any; - /** Sets current view of the Schedule. Schedule renders initially with the view that is specified here. The available views are day, week, workweek, month, agenda and custom view - from which any one of the required view can be set to the Schedule. It accepts both string or enum values. The enum values that are accepted by currentView(ej.Schedule.CurrentView) are as follows, + /** Sets current view of the Schedule. Schedule renders initially with the view that is specified here. The available views are day, week, workweek, month, agenda and + * custom view - from which any one of the required view can be set to the Schedule. It accepts both string or enum values. The enum values that are accepted + * by currentView(ej.Schedule.CurrentView) are as follows, * @Default {ej.Schedule.CurrentView.Week} */ currentView?: string|ej.Schedule.CurrentView; @@ -28558,7 +30610,8 @@ export interface Model { */ minDate?: any; - /** Sets the mode of Schedule rendering either in a vertical or horizontal direction. It accepts either string("vertical" or "horizontal") or enum values. The enum values that are accepted by orientation(ej.Schedule.Orientation) are as follows, + /** Sets the mode of Schedule rendering either in a vertical or horizontal direction. It accepts either string("vertical" or "horizontal") or enum values. + * The enum values that are accepted by orientation(ej.Schedule.Orientation) are as follows, * @Default {ej.Schedule.Orientation.Vertical} */ orientation?: string|ej.Schedule.Orientation; @@ -28576,7 +30629,8 @@ export interface Model { */ reminderSettings?: ReminderSettings; - /** Defines the specific start and end dates to be rendered in the Schedule control. To render such user-specified custom date ranges in the Schedule control, set the currentView property to ej.Schedule.CurrentView.CustomView. + /** Defines the specific start and end dates to be rendered in the Schedule control. To render such user-specified custom date ranges in the Schedule control, + * set the currentView property to ej.Schedule.CurrentView.CustomView. * @Default {null} */ renderDates?: RenderDates; @@ -28586,10 +30640,11 @@ export interface Model { */ resourceHeaderTemplateId?: string; - /** Holds all the options related to the resources settings of the Schedule. It is a collection of one or more resource objects, where the levels of resources are rendered on the Schedule based on the order of the resource data provided within this collection. + /** Holds all the options related to the resources settings of the Schedule. It is a collection of one or more resource objects, where the levels of resources are rendered on the Schedule + * based on the order of the resource data provided within this collection. * @Default {null} */ - resources?: Array; + resources?: Resource[]; /** When set to true, displays the all-day row cells on the Schedule. * @Default {true} @@ -28626,7 +30681,8 @@ export interface Model { */ startHour?: number; - /** Sets either 12 or 24 hour time mode on the Schedule. It accepts either the string value("12" or "24") or the below mentioned enum values. The enum values that are accepted by timeMode(ej.Schedule.TimeMode) are as follows, + /** Sets either 12 or 24 hour time mode on the Schedule. It accepts either the string value("12" or "24") or the below mentioned enum values. + * The enum values that are accepted by timeMode(ej.Schedule.TimeMode) are as follows, * @Default {null} */ timeMode?: string|ej.Schedule.TimeMode; @@ -28643,14 +30699,15 @@ export interface Model { /** Defines the view collection to be displayed on the Schedule. By default, it displays all the views namely, Day, Week, WorkWeek and Month. * @Default {[Day, Week, WorkWeek, Month, Agenda]} */ - views?: Array; + views?: any[]; /** Sets the width of the Schedule. Accepts both pixel and percentage values. * @Default {100%} */ width?: string; - /** When set to true, Schedule allows the validation of recurrence pattern to take place before it is being assigned to the appointments. For example, when one of the instance of recurrence appointment is dragged beyond the next or previous instance of the same recurrence appointment, a pop-up is displayed with the validation message disallowing the drag functionality. + /** When set to true, Schedule allows the validation of recurrence pattern to take place before it is being assigned to the appointments. For example, when one of the instance of + * recurrence appointment is dragged beyond the next or previous instance of the same recurrence appointment, a pop-up is displayed with the validation message disallowing the drag functionality. * @Default {true} */ enableRecurrenceValidation?: boolean; @@ -28667,7 +30724,7 @@ export interface Model { /** Sets different day collection within workWeek view. * @Default {[Monday, Tuesday, Wednesday, Thursday, Friday]} */ - workWeek?: Array; + workWeek?: any[]; /** Allows to pop-up appointment details in a tooltip while hovering over the appointments. */ @@ -28711,99 +30768,100 @@ export interface Model { */ showNextPrevMonth?: boolean; - /** Blocks the user-specific time interval on the Scheduler, so that no appointments can be created on that particular time slots. It includes the dataSource option and also the fields related to block intervals. + /** Blocks the user-specific time interval on the Scheduler, so that no appointments can be created on that particular time slots. + * It includes the dataSource option and also the fields related to block intervals. */ blockoutSettings?: BlockoutSettings; /** Triggers on the beginning of every action that starts within the Schedule. */ - actionBegin? (e: ActionBeginEventArgs): void; + actionBegin?(e: ActionBeginEventArgs): void; /** Triggers after the completion of every action within the Schedule. */ - actionComplete? (e: ActionCompleteEventArgs): void; + actionComplete?(e: ActionCompleteEventArgs): void; /** Triggers after an appointment is clicked. */ - appointmentClick? (e: AppointmentClickEventArgs): void; + appointmentClick?(e: AppointmentClickEventArgs): void; /** Triggers before the appointment is being removed from the Scheduler. */ - beforeAppointmentRemove? (e: BeforeAppointmentRemoveEventArgs): void; + beforeAppointmentRemove?(e: BeforeAppointmentRemoveEventArgs): void; /** Triggers before the edited appointment is being saved. */ - beforeAppointmentChange? (e: BeforeAppointmentChangeEventArgs): void; + beforeAppointmentChange?(e: BeforeAppointmentChangeEventArgs): void; /** Triggers on hovering the mouse over the appointments. */ - appointmentHover? (e: AppointmentHoverEventArgs): void; + appointmentHover?(e: AppointmentHoverEventArgs): void; /** Triggers before the new appointment gets saved. */ - beforeAppointmentCreate? (e: BeforeAppointmentCreateEventArgs): void; + beforeAppointmentCreate?(e: BeforeAppointmentCreateEventArgs): void; /** Triggers before the appointment window opens. */ - appointmentWindowOpen? (e: AppointmentWindowOpenEventArgs): void; + appointmentWindowOpen?(e: AppointmentWindowOpenEventArgs): void; /** Triggers before the context menu opens. */ - beforeContextMenuOpen? (e: BeforeContextMenuOpenEventArgs): void; + beforeContextMenuOpen?(e: BeforeContextMenuOpenEventArgs): void; /** Triggers after the cell is clicked. */ - cellClick? (e: CellClickEventArgs): void; + cellClick?(e: CellClickEventArgs): void; /** Triggers after the cell is clicked twice. */ - cellDoubleClick? (e: CellDoubleClickEventArgs): void; + cellDoubleClick?(e: CellDoubleClickEventArgs): void; /** Triggers on hovering the mouse overs the cells. */ - cellHover? (e: CellHoverEventArgs): void; + cellHover?(e: CellHoverEventArgs): void; /** Triggers when the Scheduler completely renders on the page. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Triggers when the Scheduler and all its sub-components gets destroyed. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Triggers while the appointment is being dragged over the work cells. */ - drag? (e: DragEventArgs): void; + drag?(e: DragEventArgs): void; /** Triggers when the appointment dragging begins. */ - dragStart? (e: DragStartEventArgs): void; + dragStart?(e: DragStartEventArgs): void; /** Triggers when the appointment is dropped. */ - dragStop? (e: DragStopEventArgs): void; + dragStop?(e: DragStopEventArgs): void; /** Triggers after the menu/sub-menu items within the context menu is clicked. */ - menuItemClick? (e: MenuItemClickEventArgs): void; + menuItemClick?(e: MenuItemClickEventArgs): void; /** Triggers after the Schedule view or date is navigated. */ - navigation? (e: NavigationEventArgs): void; + navigation?(e: NavigationEventArgs): void; /** Triggers every time before the elements of the scheduler such as work cells, time cells or header cells and so on renders or re-renders on a page. */ - queryCellInfo? (e: QueryCellInfoEventArgs): void; + queryCellInfo?(e: QueryCellInfoEventArgs): void; /** Triggers when the reminder is raised for an appointment based on the alertBefore value. */ - reminder? (e: ReminderEventArgs): void; + reminder?(e: ReminderEventArgs): void; /** Triggers while resizing the appointment. */ - resize? (e: ResizeEventArgs): void; + resize?(e: ResizeEventArgs): void; /** Triggers when the appointment resizing begins. */ - resizeStart? (e: ResizeStartEventArgs): void; + resizeStart?(e: ResizeStartEventArgs): void; /** Triggers when an appointment resizing stops. */ - resizeStop? (e: ResizeStopEventArgs): void; + resizeStop?(e: ResizeStopEventArgs): void; /** Triggers when the overflow button is clicked. */ - overflowButtonClick? (e: OverflowButtonClickEventArgs): void; + overflowButtonClick?(e: OverflowButtonClickEventArgs): void; /** Triggers while mouse hovering on the overflow button. */ - overflowButtonHover? (e: OverflowButtonHoverEventArgs): void; + overflowButtonHover?(e: OverflowButtonHoverEventArgs): void; /** Triggers when any of the keyboard keys are pressed. */ - keyDown? (e: KeyDownEventArgs): void; + keyDown?(e: KeyDownEventArgs): void; /** Triggers after the new appointment is saved. */ - appointmentCreated? (e: AppointmentCreatedEventArgs): void; + appointmentCreated?(e: AppointmentCreatedEventArgs): void; /** Triggers after an existing appointment is edited. */ - appointmentChanged? (e: AppointmentChangedEventArgs): void; + appointmentChanged?(e: AppointmentChangedEventArgs): void; /** Triggers after the appointment is deleted. */ - appointmentRemoved? (e: AppointmentRemovedEventArgs): void; + appointmentRemoved?(e: AppointmentRemovedEventArgs): void; } export interface ActionBeginEventArgs { @@ -29569,7 +31627,7 @@ export interface AppointmentSettings { /** The dataSource option accepts either JSON object collection or DataManager (ej.DataManager) instance that contains Schedule appointments. * @Default {[]} */ - dataSource?: any|Array; + dataSource?: any|any[]; /** It holds either the ej.Query() object or simply the query string that retrieves the specified records from the table. * @Default {null} @@ -29646,12 +31704,14 @@ export interface AppointmentSettings { */ priority?: string; - /** Binds the name of start timezone field in dataSource. It indicates the timezone of appointment start date. When startTimeZone field is not mentioned, the appointment uses the Schedule timeZone or System timeZone. + /** Binds the name of start timezone field in dataSource. It indicates the timezone of appointment start date. When startTimeZone field is not mentioned, + * the appointment uses the Schedule timeZone or System timeZone. * @Default {null} */ startTimeZone?: string; - /** Binds the name of end timezone field in dataSource. It indicates the timezone of appointment end date. When the endTimeZone field is not mentioned, the appointment uses the Schedule timeZone or System timeZone. + /** Binds the name of end timezone field in dataSource. It indicates the timezone of appointment end date. When the endTimeZone field is not mentioned, + * the appointment uses the Schedule timeZone or System timeZone. * @Default {null} */ endTimeZone?: string; @@ -29671,7 +31731,7 @@ export interface CategorizeSettings { /** The dataSource option accepts either the JSON object collection or DataManager [ej.DataManager] instance that contains the categorize data. */ - dataSource?: Array|any; + dataSource?: any[]|any; /** Binds id field name in the dataSource to id of category data. * @Default {id} @@ -29698,11 +31758,11 @@ export interface ContextMenuSettingsMenuItems { /** All the appointment related context menu items are grouped under this appointment menu collection. */ - appointment?: Array; + appointment?: any[]; /** All the Scheduler cell related context menu items are grouped under this cells menu item collection. */ - cells?: Array; + cells?: any[]; } export interface ContextMenuSettings { @@ -29721,7 +31781,7 @@ export interface Group { /** Holds the array of resource names to be grouped on the Schedule. */ - resources?: Array; + resources?: any[]; } export interface WorkHours { @@ -29752,7 +31812,7 @@ export interface PrioritySettings { /** The dataSource option can accept the JSON object collection that contains the priority related data. * @Default {{% highlight js%}[{ text: None, value: none },{ text: High, value: high },{ text: Medium, value: medium },{ text: Low, value: low }]{% endhighlight %}} */ - dataSource?: any|Array; + dataSource?: any|any[]; /** Binds text field name in the dataSource to prioritySettings text. These text gets listed out in priority field of the appointment window. * @Default {text} @@ -29801,7 +31861,7 @@ export interface ResourcesResourceSettings { /** The dataSource option accepts either JSON object collection or DataManager (ejDataManager) instance that contains the resources related data. * @Default {[]} */ - dataSource?: any|Array; + dataSource?: any|any[]; /** Binds text field name in the dataSource to resourceSettings text. These text gets listed out in resources field of the appointment window. * @Default {null} @@ -29833,7 +31893,8 @@ export interface ResourcesResourceSettings { */ end?: string; - /** Binds the resources working days field name in the dataSource. It's optional, and accepts the array of strings (week day names). When provided with specific collection of days (array of day names), only those days will render for the specific resources. + /** Binds the resources working days field name in the dataSource. It's optional, and accepts the array of strings (week day names). When provided with specific collection of + * days (array of day names), only those days will render for the specific resources. * @Default {null} */ workWeek?: string; @@ -29918,7 +31979,8 @@ export interface TooltipSettings { */ enable?: boolean; - /** Template design that customizes the tooltip. All the field names that are mapped from dataSource to the appropriate field properties within the appointmentSettings can be accessed within the template. + /** Template design that customizes the tooltip. All the field names that are mapped from dataSource to the appropriate field properties within + * the appointmentSettings can be accessed within the template. * @Default {null} */ templateId?: string; @@ -29959,7 +32021,8 @@ export interface BlockoutSettings { */ enable?: boolean; - /** Template design that applies on the Schedule block intervals. All the field names that are mapped from dataSource to the appropriate field properties within the blockoutSettings can be used within the template. + /** Template design that applies on the Schedule block intervals. All the field names that are mapped from dataSource to the appropriate field + * properties within the blockoutSettings can be used within the template. * @Default {null} */ templateId?: string; @@ -29967,7 +32030,7 @@ export interface BlockoutSettings { /** The dataSource option accepts either JSON object collection or DataManager (ej.DataManager) instance that contains Schedule block intervals. * @Default {[]} */ - dataSource?: any|Array; + dataSource?: any|any[]; /** It holds either the ej.Query() object or simply the query string that retrieves the specified records from the table. * @Default {null} @@ -30020,7 +32083,7 @@ export interface BlockoutSettings { customStyle?: string; } -enum CurrentView{ +enum CurrentView { ///Sets currentView of the Scheduler as Day Day, @@ -30042,7 +32105,7 @@ enum CurrentView{ } -enum Orientation{ +enum Orientation { ///Set orientation as vertical to Scheduler Vertical, @@ -30052,7 +32115,7 @@ enum Orientation{ } -enum TimeMode{ +enum TimeMode { ///Sets 12 hour time mode to Scheduler Hour12, @@ -30065,16 +32128,15 @@ enum TimeMode{ class RecurrenceEditor extends ej.Widget { static fn: RecurrenceEditor; - constructor(element: JQuery, options?: RecurrenceEditor.Model); - constructor(element: Element, options?: RecurrenceEditor.Model); + constructor(element: JQuery | Element, options?: RecurrenceEditor.Model); static Locale: any; - model:RecurrenceEditor.Model; - defaults:RecurrenceEditor.Model; + model: RecurrenceEditor.Model; + defaults: RecurrenceEditor.Model; /** Generates the recurrence rule with the options selected within the Recurrence Editor. * @returns {String} */ - getRecurrenceRule(): String; + getRecurrenceRule(): string; /** Generates the collection of date, that lies within the selected recurrence start and end date for which the recurrence pattern applies. * @param {string} It refers the recurrence rule. @@ -30090,14 +32152,14 @@ class RecurrenceEditor extends ej.Widget { */ recurrenceRuleSplit(recurrenceRule: string, exDate: any): any; } -export module RecurrenceEditor{ +export namespace RecurrenceEditor { export interface Model { /** Defines the collection of recurrence frequencies within Recurrence Editor such as Never, Daily, Weekly, Monthly, Yearly and Every Weekday. * @Default {[never, daily, weekly, monthly, yearly, everyweekday]} */ - frequencies?: Array; + frequencies?: any[]; /** Sets the starting day of the week. * @Default {null} @@ -30128,17 +32190,20 @@ export interface Model { */ enableRTL?: boolean; - /** Sets the active/current repeat type(frequency) on Recurrence Editor based on the index value provided. For example, setting the value 1 will initially set the repeat type as Daily and display its related options. + /** Sets the active/current repeat type(frequency) on Recurrence Editor based on the index value provided. For example, setting the value 1 will initially set the repeat type + * as Daily and display its related options. * @Default {0} */ selectedRecurrenceType?: number; - /** Sets the minimum date limit to display on the datepickers defined within the Recurrence Editor. Setting minDate with specific date value disallows the datepickers within Recurrence Editor to navigate beyond that date. + /** Sets the minimum date limit to display on the datepickers defined within the Recurrence Editor. Setting minDate with specific date value disallows the datepickers within + * Recurrence Editor to navigate beyond that date. * @Default {new Date(1900, 01, 01)} */ minDate?: any; - /** Sets the maximum date limit to display on the datepickers used within the Recurrence Editor. Setting maxDate with specific date value disallows the datepickers within the Recurrence Editor to navigate beyond that date. + /** Sets the maximum date limit to display on the datepickers used within the Recurrence Editor. Setting maxDate with specific date value disallows the + * datepickers within the Recurrence Editor to navigate beyond that date. * @Default {new Date(2099, 12, 31)} */ maxDate?: any; @@ -30148,7 +32213,7 @@ export interface Model { cssClass?: string; /** Triggers whenever any of the Recurrence Editor's value is changed. */ - change? (e: ChangeEventArgs): void; + change?(e: ChangeEventArgs): void; } export interface ChangeEventArgs { @@ -30173,11 +32238,10 @@ export interface ChangeEventArgs { class Gantt extends ej.Widget { static fn: Gantt; - constructor(element: JQuery, options?: Gantt.Model); - constructor(element: Element, options?: Gantt.Model); + constructor(element: JQuery | Element, options?: Gantt.Model); static Locale: any; - model:Gantt.Model; - defaults:Gantt.Model; + model: Gantt.Model; + defaults: Gantt.Model; /** To add a new item in Gantt * @param {any} Item to add in Gantt row. @@ -30191,7 +32255,7 @@ class Gantt extends ej.Widget { * @param {boolean} Defines that we need to preserve the previously selected cells of not * @returns {void} */ - selectCells(Indexes: Array, preservePreviousSelectedCell: boolean): void; + selectCells(Indexes: any[], preservePreviousSelectedCell: boolean): void; /** Positions the splitter by the specified column index. * @param {number} Set the splitter position based on column index. @@ -30279,14 +32343,14 @@ class Gantt extends ej.Widget { */ showColumn(headerText: string): void; } -export module Gantt{ +export namespace Gantt { export interface Model { /** Specifies the fields to be included in the add dialog in Gantt * @Default {[]} */ - addDialogFields?: Array; + addDialogFields?: any[]; /** Enables or disables the ability to resize column. * @Default {false} @@ -30353,7 +32417,7 @@ export interface Model { /** To Specify the column fields to be displayed in the dialog while inserting a column using column menu. * @Default {[]} */ - columnDialogFields?: Array; + columnDialogFields?: any[]; /** Specifies the background of connector lines in Gantt */ @@ -30380,7 +32444,7 @@ export interface Model { /** Collection of data or hierarchical data to represent in Gantt * @Default {null} */ - dataSource?: Array; + dataSource?: any[]; /** Specifies the dateFormat for Gantt , given format is displayed in tooltip , Grid . * @Default {MM/dd/yyyy} @@ -30399,7 +32463,7 @@ export interface Model { /** Specifies the fields to be included in the edit dialog in Gantt * @Default {[]} */ - editDialogFields?: Array; + editDialogFields?: any[]; /** Enables or disables the responsiveness of Gantt * @Default {false} @@ -30492,7 +32556,7 @@ export interface Model { /** Collection of holidays with date, background and label information to be displayed in Gantt. * @Default {[]} */ - holidays?: Array; + holidays?: any[]; /** Specifies whether to include weekends while calculating the duration of a task. * @Default {true} @@ -30623,7 +32687,7 @@ export interface Model { /** Collection of data regarding resources involved in entire project * @Default {[]} */ - resources?: Array; + resources?: any[]; /** Specifies whether rounding off the day working time edits * @Default {true} @@ -30690,7 +32754,7 @@ export interface Model { /** Specifies the selected cell information on rendering Gantt. */ - selectedCellIndexes?: Array; + selectedCellIndexes?: SelectedCellIndex[]; /** Specifies the sorting options for Gantt. */ @@ -30708,7 +32772,7 @@ export interface Model { /** Specifies the options for striplines * @Default {[]} */ - stripLines?: Array; + stripLines?: any[]; /** Specifies the background of the taskbar in Gantt */ @@ -30776,79 +32840,79 @@ export interface Model { workingTimeScale?: ej.Gantt.workingTimeScale|string; /** Triggered for every Gantt action before its starts. */ - actionBegin? (e: ActionBeginEventArgs): void; + actionBegin?(e: ActionBeginEventArgs): void; /** Triggered for every Gantt action success event. */ - actionComplete? (e: ActionCompleteEventArgs): void; + actionComplete?(e: ActionCompleteEventArgs): void; /** Triggered while enter the edit mode in the TreeGrid cell */ - beginEdit? (e: BeginEditEventArgs): void; + beginEdit?(e: BeginEditEventArgs): void; /** Triggered before selecting a cell */ - cellSelecting? (e: CellSelectingEventArgs): void; + cellSelecting?(e: CellSelectingEventArgs): void; /** Triggered after selected a cell */ - cellSelected? (e: CellSelectedEventArgs): void; + cellSelected?(e: CellSelectedEventArgs): void; /** Triggered while dragging a row in Gantt control */ - rowDrag? (e: RowDragEventArgs): void; + rowDrag?(e: RowDragEventArgs): void; /** Triggered while start to drag row in Gantt control */ - rowDragStart? (e: RowDragStartEventArgs): void; + rowDragStart?(e: RowDragStartEventArgs): void; /** Triggered while drop a row in Gantt control */ - rowDragStop? (e: RowDragStopEventArgs): void; + rowDragStop?(e: RowDragStopEventArgs): void; /** Triggered after collapsed the Gantt record */ - collapsed? (e: CollapsedEventArgs): void; + collapsed?(e: CollapsedEventArgs): void; /** Triggered while collapsing the Gantt record */ - collapsing? (e: CollapsingEventArgs): void; + collapsing?(e: CollapsingEventArgs): void; /** Triggered while Context Menu is rendered in Gantt control */ - contextMenuOpen? (e: ContextMenuOpenEventArgs): void; + contextMenuOpen?(e: ContextMenuOpenEventArgs): void; /** Triggered when Gantt is rendered completely. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Triggered after save the modified cellValue in Gantt. */ - endEdit? (e: EndEditEventArgs): void; + endEdit?(e: EndEditEventArgs): void; /** Triggered after expand the record */ - expanded? (e: ExpandedEventArgs): void; + expanded?(e: ExpandedEventArgs): void; /** Triggered while expanding the Gantt record */ - expanding? (e: ExpandingEventArgs): void; + expanding?(e: ExpandingEventArgs): void; /** Triggered while Gantt is loaded */ - load? (e: LoadEventArgs): void; + load?(e: LoadEventArgs): void; /** Triggered while rendering each cell in the TreeGrid */ - queryCellInfo? (e: QueryCellInfoEventArgs): void; + queryCellInfo?(e: QueryCellInfoEventArgs): void; /** Triggered while rendering each taskbar in the Gantt */ - queryTaskbarInfo? (e: QueryTaskbarInfoEventArgs): void; + queryTaskbarInfo?(e: QueryTaskbarInfoEventArgs): void; /** Triggered while rendering each row */ - rowDataBound? (e: RowDataBoundEventArgs): void; + rowDataBound?(e: RowDataBoundEventArgs): void; /** Triggered after the row is selected. */ - rowSelected? (e: RowSelectedEventArgs): void; + rowSelected?(e: RowSelectedEventArgs): void; /** Triggered before the row is going to be selected. */ - rowSelecting? (e: RowSelectingEventArgs): void; + rowSelecting?(e: RowSelectingEventArgs): void; /** Triggered after completing the editing operation in taskbar */ - taskbarEdited? (e: TaskbarEditedEventArgs): void; + taskbarEdited?(e: TaskbarEditedEventArgs): void; /** Triggered while editing the Gantt chart (dragging, resizing the taskbar ) */ - taskbarEditing? (e: TaskbarEditingEventArgs): void; + taskbarEditing?(e: TaskbarEditingEventArgs): void; /** Triggered when taskbar item is clicked in Gantt. */ - taskbarClick? (e: TaskbarClickEventArgs): void; + taskbarClick?(e: TaskbarClickEventArgs): void; /** Triggered when toolbar item is clicked in Gantt. */ - toolbarClick? (e: ToolbarClickEventArgs): void; + toolbarClick?(e: ToolbarClickEventArgs): void; } export interface ActionBeginEventArgs { @@ -31185,7 +33249,7 @@ export interface ContextMenuOpenEventArgs { /** Returns the default context menu items to which we add custom items. */ - contextMenuItems?: Array; + contextMenuItems?: any[]; /** Returns the Gantt model. */ @@ -31544,7 +33608,7 @@ export interface DragTooltip { /** Specifies the data source fields to be displayed in the drag tooltip. * @Default {[]} */ - tooltipItems?: Array; + tooltipItems?: any[]; /** Specifies the custom template for drag tooltip. * @Default {null} @@ -31599,6 +33663,11 @@ export interface EditSettings { * @Default {normal} */ editMode?: string; + + /** Specifies the position where the new row has to be added. + * @Default {ej.Gantt.RowPosition.BelowSelectedRow} + */ + rowPosition?: ej.Gantt.RowPosition|string; } export interface ScheduleHeaderSettings { @@ -31647,6 +33716,16 @@ export interface ScheduleHeaderSettings { * @Default {yyyy} */ yearHeaderFormat?: string; + + /** Specifies the size of the lowest time unit along the timescale, with minimum value as "50%" and maximum value as "500%". It is also possible to set the value in pixels. + * @Default {100%} + */ + timescaleUnitSize?: string; + + /** Specifies the start day of the week in week timescale mode + * @Default {0} + */ + weekStartDay?: number; } export interface SizeSettings { @@ -31679,7 +33758,7 @@ export interface SortSettings { /** Specifies the sorted columns for Gantt * @Default {[]} */ - sortedColumns?: Array; + sortedColumns?: any[]; } export interface ToolbarSettings { @@ -31692,10 +33771,10 @@ export interface ToolbarSettings { /** Specifies the list of toolbar items to be rendered in Gantt toolbar * @Default {[]} */ - toolbarItems?: Array; + toolbarItems?: any[]; } -enum DurationUnit{ +enum DurationUnit { ///Sets the Duration Unit as day. Day, @@ -31708,7 +33787,7 @@ enum DurationUnit{ } -enum BeginEditAction{ +enum BeginEditAction { ///you can begin the editing at double click DblClick, @@ -31718,7 +33797,26 @@ enum BeginEditAction{ } -enum TaskType{ +enum RowPosition { + + ///you can add a new row at top. + Top, + + ///you can add a new row at bottom. + Bottom, + + ///you can add a new row to above selected row. + AboveSelectedRow, + + ///you can add a new row to below selected row. + BelowSelectedRow, + + ///you can add a new row as a child for selected row. + Child +} + + +enum TaskType { ///Resource unit remains constant while editing the work and duration values. FixedUnit, @@ -31731,7 +33829,7 @@ enum TaskType{ } -enum WorkUnit{ +enum WorkUnit { ///Displays the work involved in a task in days. Day, @@ -31744,7 +33842,7 @@ enum WorkUnit{ } -enum TaskSchedulingMode{ +enum TaskSchedulingMode { ///All the tasks in the project will be displayed in auto scheduled mode, where the tasks are scheduled automatically over non-working days and holidays. Auto, @@ -31757,7 +33855,7 @@ enum TaskSchedulingMode{ } -enum SelectionType{ +enum SelectionType { ///you can select a single row. Single, @@ -31767,7 +33865,7 @@ enum SelectionType{ } -enum minutesPerInterval{ +enum minutesPerInterval { ///Sets the interval automatically according with schedule start and end date. Auto, @@ -31786,7 +33884,7 @@ enum minutesPerInterval{ } -enum ScheduleHeaderType{ +enum ScheduleHeaderType { ///Sets year Schedule Mode. Year, @@ -31805,7 +33903,7 @@ enum ScheduleHeaderType{ } -enum TimescaleRoundMode{ +enum TimescaleRoundMode { ///The round-off value will be automatically calculated based on the data source values. Auto, @@ -31821,7 +33919,7 @@ enum TimescaleRoundMode{ } -enum SelectionMode{ +enum SelectionMode { ///you can select a row. Row, @@ -31831,7 +33929,7 @@ enum SelectionMode{ } -enum workingTimeScale{ +enum workingTimeScale { ///Sets eight hour timescale. TimeScale8Hours, @@ -31844,11 +33942,10 @@ enum workingTimeScale{ class ReportViewer extends ej.Widget { static fn: ReportViewer; - constructor(element: JQuery, options?: ReportViewer.Model); - constructor(element: Element, options?: ReportViewer.Model); + constructor(element: JQuery | Element, options?: ReportViewer.Model); static Locale: any; - model:ReportViewer.Model; - defaults:ReportViewer.Model; + model: ReportViewer.Model; + defaults: ReportViewer.Model; /** Export the report to the specified format. * @returns {void} @@ -31920,19 +34017,19 @@ class ReportViewer extends ej.Widget { */ refresh(): void; } -export module ReportViewer{ +export namespace ReportViewer { export interface Model { /** Gets or sets the list of data sources for the RDLC report. * @Default {[]} */ - dataSources?: Array; + dataSources?: DataSource[]; /** Enables or disables the page cache of report. * @Default {false} */ - enablePageCache?: Boolean; + enablePageCache?: boolean; /** Specifies the export settings. */ @@ -31941,12 +34038,12 @@ export interface Model { /** When set to true, adapts the report layout to fit the screen size of devices on which it renders. * @Default {true} */ - isResponsive?: Boolean; + isResponsive?: boolean; /** Specifies the locale for report viewer. * @Default {en-US} */ - locale?: String; + locale?: string; /** Specifies the page settings. */ @@ -31955,12 +34052,12 @@ export interface Model { /** Gets or sets the list of parameters associated with the report. * @Default {[]} */ - parameters?: Array; + parameters?: Parameter[]; /** Enables and disables the print mode. * @Default {false} */ - printMode?: Boolean; + printMode?: boolean; /** Specifies the print option of the report. * @Default {ej.ReportViewer.PrintOptions.Default} @@ -31980,17 +34077,17 @@ export interface Model { /** Gets or sets the path of the report file. * @Default {empty} */ - reportPath?: String; + reportPath?: string; /** Gets or sets the reports server URL. * @Default {empty} */ - reportServerUrl?: String; + reportServerUrl?: string; /** Specifies the report Web API service URL. * @Default {empty} */ - reportServiceUrl?: String; + reportServiceUrl?: string; /** Specifies the toolbar settings. */ @@ -31999,31 +34096,31 @@ export interface Model { /** Gets or sets the zoom factor for report viewer. * @Default {1} */ - zoomFactor?: Number; + zoomFactor?: number; /** Fires when the report viewer is destroyed successfully.If you want to perform any operation after destroying the reportviewer control,you can make use of the destroy event. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Fires during drill through action done in report.If you want to perform any operation when a drill through action is performed, you can make use of the drillThrough event. */ - drillThrough? (e: DrillThroughEventArgs): void; + drillThrough?(e: DrillThroughEventArgs): void; /** Fires before report rendering is completed.If you want to perform any operation before the rendering of report,you can make use of the renderingBegin event. */ - renderingBegin? (e: RenderingBeginEventArgs): void; + renderingBegin?(e: RenderingBeginEventArgs): void; /** Fires after report rendering completed.If you want to perform any operation after the rendering of report,you can make use of this renderingComplete event. */ - renderingComplete? (e: RenderingCompleteEventArgs): void; + renderingComplete?(e: RenderingCompleteEventArgs): void; /** Fires when any error occurred while rendering the report.If you want to perform any operation when an error occurs in the report, you can make use of the reportError event. */ - reportError? (e: ReportErrorEventArgs): void; + reportError?(e: ReportErrorEventArgs): void; /** Fires when the report is being exported.If you want to perform any operation before exporting of report, you can make use of the reportExport event. */ - reportExport? (e: ReportExportEventArgs): void; + reportExport?(e: ReportExportEventArgs): void; /** Fires when the report is loaded.If you want to perform any operation after the successful loading of report, you can make use of the reportLoaded event. */ - reportLoaded? (e: ReportLoadedEventArgs): void; + reportLoaded?(e: ReportLoadedEventArgs): void; /** Fires when click the View Report Button. */ - viewReportClick? (e: ViewReportClickEventArgs): void; + viewReportClick?(e: ViewReportClickEventArgs): void; } export interface DestroyEventArgs { @@ -32167,12 +34264,12 @@ export interface DataSource { /** Gets or sets the name of the data source. * @Default {empty} */ - name?: String; + name?: string; /** Gets or sets the values of data source. * @Default {[]} */ - values?: Array; + values?: any[]; } export interface ExportSettings { @@ -32211,27 +34308,27 @@ export interface Parameter { /** Gets or sets the parameter labels. * @Default {null} */ - labels?: Array; + labels?: any[]; /** Gets or sets the name of the parameter. * @Default {empty} */ - name?: String; + name?: string; /** Gets or sets whether the parameter allows nullable value or not. * @Default {false} */ - nullable?: Boolean; + nullable?: boolean; /** Gets or sets the prompt message associated with the specified parameter. * @Default {empty} */ - prompt?: String; + prompt?: string; /** Gets or sets the parameter values. * @Default {[]} */ - values?: Array; + values?: any[]; } export interface ToolbarSettings { @@ -32239,7 +34336,7 @@ export interface ToolbarSettings { /** Fires when user click on toolbar item in the toolbar. * @Default {empty} */ - click?: String; + click?: string; /** Specifies the toolbar items. * @Default {ej.ReportViewer.ToolbarItems.All} @@ -32249,20 +34346,20 @@ export interface ToolbarSettings { /** Shows or hides the toolbar. * @Default {true} */ - showToolbar?: Boolean; + showToolbar?: boolean; /** Shows or hides the tooltip of toolbar items. * @Default {true} */ - showTooltip?: Boolean; + showTooltip?: boolean; /** Specifies the toolbar template ID. * @Default {empty} */ - templateId?: String; + templateId?: string; } -enum ExportOptions{ +enum ExportOptions { ///Specifies the All property in ExportOptions to get all available options. All, @@ -32281,7 +34378,7 @@ enum ExportOptions{ } -enum ExcelFormats{ +enum ExcelFormats { ///Specifies the Excel97to2003 property in ExcelFormats to get specified version of exported format. Excel97to2003, @@ -32297,7 +34394,7 @@ enum ExcelFormats{ } -enum WordFormats{ +enum WordFormats { ///Specifies the Doc property in WordFormats to get specified version of exported format. Doc, @@ -32364,7 +34461,7 @@ enum WordFormats{ } -enum Orientation{ +enum Orientation { ///Specifies the Landscape property in pageSettings.orientation to get specified layout. Landscape, @@ -32374,7 +34471,7 @@ enum Orientation{ } -enum PaperSize{ +enum PaperSize { ///Specifies the A3 as value in pageSettings.paperSize to get specified size. A3, @@ -32411,7 +34508,7 @@ enum PaperSize{ } -enum PrintOptions{ +enum PrintOptions { ///Specifies the Default property in printOptions. Default, @@ -32424,7 +34521,7 @@ enum PrintOptions{ } -enum ProcessingMode{ +enum ProcessingMode { ///Specifies the Remote property in processingMode. Remote, @@ -32434,7 +34531,7 @@ enum ProcessingMode{ } -enum RenderMode{ +enum RenderMode { ///Specifies the Default property in RenderMode to get default output. Default, @@ -32447,7 +34544,7 @@ enum RenderMode{ } -enum ToolbarItems{ +enum ToolbarItems { ///Specifies the Print as value in ToolbarItems to get specified item. Print, @@ -32481,11 +34578,10 @@ enum ToolbarItems{ class TreeGrid extends ej.Widget { static fn: TreeGrid; - constructor(element: JQuery, options?: TreeGrid.Model); - constructor(element: Element, options?: TreeGrid.Model); + constructor(element: JQuery | Element, options?: TreeGrid.Model); static Locale: any; - model:TreeGrid.Model; - defaults:TreeGrid.Model; + model: TreeGrid.Model; + defaults: TreeGrid.Model; /** Add a new row in TreeGrid, while allowAdding is set to true * @param {any} Item to add in TreeGrid row. @@ -32505,7 +34601,7 @@ class TreeGrid extends ej.Widget { * @param {boolean} Defines that we need to preserve the previously selected cells or not * @returns {void} */ - selectCells(Indexes: Array, preservePreviousSelectedCell: boolean): void; + selectCells(Indexes: any[], preservePreviousSelectedCell: boolean): void; /** To rename a column with the specified name * @param {number} Index of the column to be renamed @@ -32548,7 +34644,7 @@ class TreeGrid extends ej.Widget { * @param {any} Pass which data you want to show in tree grid * @returns {void} */ - refresh(dataSource: Array, query: any): void; + refresh(dataSource: any[], query: any): void; /** Freeze all the columns preceding to the column specified by the field name. * @param {string} Freeze all Columns before this field column. @@ -32594,7 +34690,7 @@ class TreeGrid extends ej.Widget { */ reorderColumn(fieldName: string, targetIndex: string): void; } -export module TreeGrid{ +export namespace TreeGrid { export interface Model { @@ -32613,7 +34709,8 @@ export interface Model { */ allowDragAndDrop?: boolean; - /** Enables or disables the ability to filter the data on all the columns. Enabling this property will display a row with editor controls corresponding to each column. You can restrict filtering on particular column by disabling this property directly on that column instance itself. + /** Enables or disables the ability to filter the data on all the columns. Enabling this property will display a row with editor controls corresponding to each column. + * You can restrict filtering on particular column by disabling this property directly on that column instance itself. * @Default {false} */ allowFiltering?: boolean; @@ -32653,12 +34750,12 @@ export interface Model { /** Option for adding columns; each column has the option to bind to a field in the dataSource. */ - columns?: Array; + columns?: Column[]; /** To Specify the column fields to be displayed in the dialog while inserting a column using column menu. * @Default {[]} */ - columnDialogFields?: Array; + columnDialogFields?: any[]; /** Options for displaying and customizing context menu items. */ @@ -32671,7 +34768,7 @@ export interface Model { /** Specifies hierarchical or self-referential data to populate the TreeGrid. * @Default {null} */ - dataSource?: Array; + dataSource?: any[]; /** Specifies whether to wrap the header text when it is overflown i.e., when it exceeds the header width. * @Default {none} @@ -32719,6 +34816,11 @@ export interface Model { */ locale?: string; + /** Enables or disables internal parsing of a row. When disabled this property, row will be displayed using the defined template without any internal event bindings. + * @Default {true} + */ + parseRowTemplate?: boolean; + /** Specifies the name of the field in the dataSource, which contains the id of that row. */ idMapping?: string; @@ -32769,7 +34871,8 @@ export interface Model { */ showColumnOptions?: boolean; - /** Controls the visibility of the menu button, which is displayed on the column header. Clicking on this button will show a popup menu. When you choose Columns item from this popup, a list box with column names will be shown, from which you can select/deselect a column name to control the visibility of the respective columns. + /** Controls the visibility of the menu button, which is displayed on the column header. Clicking on this button will show a popup menu. When you choose Columns item from this popup, + * a list box with column names will be shown, from which you can select/deselect a column name to control the visibility of the respective columns. * @Default {false} */ showColumnChooser?: boolean; @@ -32806,7 +34909,7 @@ export interface Model { /** Specifies the summary row collection object to be displayed * @Default {[]} */ - summaryRows?: Array; + summaryRows?: any[]; /** Specifies whether to show tooltip when mouse is hovered on the cell. * @Default {true} @@ -32836,85 +34939,88 @@ export interface Model { treeColumnIndex?: number; /** Triggered before every success event of TreeGrid action. */ - actionBegin? (e: ActionBeginEventArgs): void; + actionBegin?(e: ActionBeginEventArgs): void; /** Triggered for every TreeGrid action success event. */ - actionComplete? (e: ActionCompleteEventArgs): void; + actionComplete?(e: ActionCompleteEventArgs): void; /** Triggered while enter the edit mode in the TreeGrid cell */ - beginEdit? (e: BeginEditEventArgs): void; + beginEdit?(e: BeginEditEventArgs): void; /** Triggered after collapsed the TreeGrid record */ - collapsed? (e: CollapsedEventArgs): void; + collapsed?(e: CollapsedEventArgs): void; /** Triggered while collapsing the TreeGrid record */ - collapsing? (e: CollapsingEventArgs): void; + collapsing?(e: CollapsingEventArgs): void; + + /** Triggered while clicking a row, even when allowSelection property is disabled. */ + recordClick?(e: RecordClickEventArgs): void; /** Triggered when you start to drag a column */ - columnDragStart? (e: ColumnDragStartEventArgs): void; + columnDragStart?(e: ColumnDragStartEventArgs): void; /** Triggered while dragging a column */ - columnDrag? (e: ColumnDragEventArgs): void; + columnDrag?(e: ColumnDragEventArgs): void; /** Triggered when a column is dropped */ - columnDrop? (e: ColumnDropEventArgs): void; + columnDrop?(e: ColumnDropEventArgs): void; /** Triggered after a column resized */ - columnResized? (e: ColumnResizedEventArgs): void; + columnResized?(e: ColumnResizedEventArgs): void; /** Triggered while start to resize a column */ - columnResizeStart? (e: ColumnResizeStartEventArgs): void; + columnResizeStart?(e: ColumnResizeStartEventArgs): void; /** Triggered when a column has been resized */ - columnResizeEnd? (e: ColumnResizeEndEventArgs): void; + columnResizeEnd?(e: ColumnResizeEndEventArgs): void; /** Triggered while Context Menu is rendered in TreeGrid control */ - contextMenuOpen? (e: ContextMenuOpenEventArgs): void; + contextMenuOpen?(e: ContextMenuOpenEventArgs): void; /** Triggered when TreeGrid is rendered completely */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Triggered after saved the modified cellValue in TreeGrid */ - endEdit? (e: EndEditEventArgs): void; + endEdit?(e: EndEditEventArgs): void; /** Triggered after expand the record */ - expanded? (e: ExpandedEventArgs): void; + expanded?(e: ExpandedEventArgs): void; /** Triggered while expanding the TreeGrid record */ - expanding? (e: ExpandingEventArgs): void; + expanding?(e: ExpandingEventArgs): void; /** Triggered while Treegrid is loaded */ - load? (e: LoadEventArgs): void; + load?(e: LoadEventArgs): void; /** Triggered while rendering each cell in the TreeGrid */ - queryCellInfo? (e: QueryCellInfoEventArgs): void; + queryCellInfo?(e: QueryCellInfoEventArgs): void; /** Triggered while rendering each row */ - rowDataBound? (e: RowDataBoundEventArgs): void; + rowDataBound?(e: RowDataBoundEventArgs): void; /** Triggered while dragging a row in TreeGrid control */ - rowDrag? (e: RowDragEventArgs): void; + rowDrag?(e: RowDragEventArgs): void; /** Triggered while start to drag row in TreeGrid control */ - rowDragStart? (e: RowDragStartEventArgs): void; + rowDragStart?(e: RowDragStartEventArgs): void; /** Triggered while drop a row in TreeGrid control */ - rowDragStop? (e: RowDragStopEventArgs): void; + rowDragStop?(e: RowDragStopEventArgs): void; /** Triggered before selecting a cell */ - cellSelecting? (e: CellSelectingEventArgs): void; + cellSelecting?(e: CellSelectingEventArgs): void; /** Triggered after selected a cell */ - cellSelected? (e: CellSelectedEventArgs): void; + cellSelected?(e: CellSelectedEventArgs): void; /** Triggered after the row is selected. */ - rowSelected? (e: RowSelectedEventArgs): void; + rowSelected?(e: RowSelectedEventArgs): void; /** Triggered before the row is going to be selected. */ - rowSelecting? (e: RowSelectingEventArgs): void; + rowSelecting?(e: RowSelectingEventArgs): void; /** Triggered when toolbar item is clicked in TreeGrid. */ - toolbarClick? (e: ToolbarClickEventArgs): void; + toolbarClick?(e: ToolbarClickEventArgs): void; } export interface ActionBeginEventArgs { @@ -33064,6 +35170,37 @@ export interface CollapsingEventArgs { expanded?: boolean; } +export interface RecordClickEventArgs { + + /** Returns the cancel option value. + */ + cancel?: boolean; + + /** Returns the element of clicked cell. + */ + cell?: any; + + /** Returns the index of the clicked cell. + */ + cellIndex?: number; + + /** Returns the data of clicked cell. + */ + cellValue?: any; + + /** Returns the element of the clicked row. + */ + row?: any; + + /** Returns the index of the clicked row. + */ + rowIndex?: number; + + /** Returns the column name of the clicked cell. + */ + columnName?: string; +} + export interface ColumnDragStartEventArgs { /** Returns the cancel option value. @@ -33262,7 +35399,7 @@ export interface ContextMenuOpenEventArgs { /** Returns the default context menu items to which we add custom items. */ - contextMenuItems?: Array; + contextMenuItems?: any[]; /** Returns the TreeGrid model. */ @@ -33728,9 +35865,13 @@ export interface Column { */ visible?: boolean; + /** Gets or sets a value for treegrid column width + */ + width?: number; + /** Specifies the header template value for the column header */ - headerTemplateID?: String; + headerTemplateID?: string; /** Specifies the display format of a column * @Default {null} @@ -33759,7 +35900,7 @@ export interface Column { /** Specifies the template for the TreeGrid column */ - templateID?: String; + templateID?: string; /** Enables or disables the ability to edit a row or cell. * @Default {false} @@ -33777,7 +35918,7 @@ export interface ContextMenuSettings { /** Option for adding items to context menu. * @Default {[]} */ - contextMenuItems?: Array; + contextMenuItems?: any[]; /** Shows/hides the context menu. * @Default {false} @@ -33795,7 +35936,7 @@ export interface DragTooltip { /** Option to add field names whose corresponding values in the dragged row needs to be shown in the preview tooltip. * @Default {[]} */ - tooltipItems?: Array; + tooltipItems?: any[]; /** Custom template for that tooltip that is shown while dragging a row. * @Default {null} @@ -33859,7 +36000,7 @@ export interface FilterSettings { /** Specifies the column collection for filtering the TreeGrid content on initial load * @Default {[]} */ - filteredColumns?: Array; + filteredColumns?: any[]; } export interface PageSettings { @@ -33936,7 +36077,7 @@ export interface SortSettings { /** Option to add columns based on which the rows have to be sorted recursively. * @Default {[]} */ - sortedColumns?: Array; + sortedColumns?: any[]; } export interface ToolbarSettings { @@ -33949,10 +36090,10 @@ export interface ToolbarSettings { /** Specifies the list of toolbar items to be rendered in TreeGrid toolbar * @Default {[]} */ - toolbarItems?: Array; + toolbarItems?: any[]; } -enum EditingType{ +enum EditingType { ///It Specifies String edit type. String, @@ -33977,7 +36118,7 @@ enum EditingType{ } -enum BeginEditAction{ +enum BeginEditAction { ///you can begin the editing at double click DblClick, @@ -33987,7 +36128,7 @@ enum BeginEditAction{ } -enum EditMode{ +enum EditMode { ///you can edit a cell. CellEditing, @@ -33997,7 +36138,7 @@ enum EditMode{ } -enum RowPosition{ +enum RowPosition { ///you can add a new row at top. Top, @@ -34016,7 +36157,7 @@ enum RowPosition{ } -enum PageSizeMode{ +enum PageSizeMode { ///To count all the parent and child records. All, @@ -34026,7 +36167,7 @@ enum PageSizeMode{ } -enum SelectionMode{ +enum SelectionMode { ///you can select a row. Row, @@ -34036,7 +36177,7 @@ enum SelectionMode{ } -enum SelectionType{ +enum SelectionType { ///you can select a single row. Single, @@ -34052,11 +36193,10 @@ enum SelectionType{ class GroupButton extends ej.Widget { static fn: GroupButton; - constructor(element: JQuery, options?: GroupButton.Model); - constructor(element: Element, options?: GroupButton.Model); + constructor(element: JQuery | Element, options?: GroupButton.Model); static Locale: any; - model:GroupButton.Model; - defaults:GroupButton.Model; + model: GroupButton.Model; + defaults: GroupButton.Model; /** Remove the selection state of the specified the button element from the GroupButton * @param {JQuery} Specific button element @@ -34140,7 +36280,7 @@ class GroupButton extends ej.Widget { */ showItem(element: JQuery): void; } -export module GroupButton{ +export namespace GroupButton { export interface Model { @@ -34193,7 +36333,7 @@ export interface Model { */ query?: any; - /** Sets the list of button elements to be selected. To enable this option groupButtonMode should be in “checkbox” mode. + /** Sets the list of button elements to be selected. To enable this option groupButtonMode should be in “checkbox” mode. * @Default {[]} */ selectedItemIndex?: number[]|string[]; @@ -34213,19 +36353,19 @@ export interface Model { width?: string|number; /** Triggered before any button element in the GroupButton get selected. */ - beforeSelect? (e: BeforeSelectEventArgs): void; + beforeSelect?(e: BeforeSelectEventArgs): void; /** Fires after GroupButton control is created.If the user want to perform any operation after the button control creation then the user can make use of this create event. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires when the GroupButton is destroyed successfully.If the user want to perform any operation after the destroy button control then the user can make use of this destroy event. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Triggered once the key is pressed, when the control is in focused state. */ - keyPress? (e: KeyPressEventArgs): void; + keyPress?(e: KeyPressEventArgs): void; /** Triggered when the button element get selected. */ - select? (e: SelectEventArgs): void; + select?(e: SelectEventArgs): void; } export interface BeforeSelectEventArgs { @@ -34375,8 +36515,7 @@ export interface SelectEventArgs { status?: boolean; } } -enum GroupButtonMode -{ +enum GroupButtonMode { //Sets the GroupButton to work as checkbox mode CheckBox, //Sets the RadioButton to work as radio button mode @@ -34385,11 +36524,10 @@ RadioButton, class NavigationDrawer extends ej.Widget { static fn: NavigationDrawer; - constructor(element: JQuery, options?: NavigationDrawer.Model); - constructor(element: Element, options?: NavigationDrawer.Model); + constructor(element: JQuery | Element, options?: NavigationDrawer.Model); static Locale: any; - model:NavigationDrawer.Model; - defaults:NavigationDrawer.Model; + model: NavigationDrawer.Model; + defaults: NavigationDrawer.Model; /** To close the navigation drawer control * @returns {void} @@ -34411,7 +36549,7 @@ class NavigationDrawer extends ej.Widget { */ toggle(): void; } -export module NavigationDrawer{ +export namespace NavigationDrawer { export interface Model { @@ -34425,7 +36563,8 @@ export interface Model { */ contentId?: string; - /** Sets the root class for NavigationDrawer theme. This cssClass API helps to use custom skinning option for NavigationDrawer control. By defining the root class using this API, we need to include this root class in CSS. + /** Sets the root class for NavigationDrawer theme. This cssClass API helps to use custom skinning option for NavigationDrawer control. + * By defining the root class using this API, we need to include this root class in CSS. */ cssClass?: string; @@ -34442,7 +36581,7 @@ export interface Model { /** Specifies the listview items as an array of object. * @Default {[]} */ - items?: Array; + items?: any[]; /** Sets all the properties of listview to render in navigation drawer */ @@ -34473,22 +36612,22 @@ export interface Model { isPaneOpen?: boolean; /** Event triggers after the AJAX content loaded completely. */ - ajaxComplete? (e: AjaxCompleteEventArgs): void; + ajaxComplete?(e: AjaxCompleteEventArgs): void; /** Event triggers when the AJAX request failed. */ - ajaxError? (e: AjaxErrorEventArgs): void; + ajaxError?(e: AjaxErrorEventArgs): void; /** Event triggers after the AJAX content loaded successfully. */ - ajaxSuccess? (e: AjaxSuccessEventArgs): void; + ajaxSuccess?(e: AjaxSuccessEventArgs): void; /** Event triggers before the control gets closed. */ - beforeClose? (e: BeforeCloseEventArgs): void; + beforeClose?(e: BeforeCloseEventArgs): void; /** Event triggers when the control open. */ - open? (e: OpenEventArgs): void; + open?(e: OpenEventArgs): void; /** Event triggers when the Swipe happens. */ - swipe? (e: SwipeEventArgs): void; + swipe?(e: SwipeEventArgs): void; } export interface AjaxCompleteEventArgs { @@ -34627,11 +36766,10 @@ export interface AjaxSettings { class RadialMenu extends ej.Widget { static fn: RadialMenu; - constructor(element: JQuery, options?: RadialMenu.Model); - constructor(element: Element, options?: RadialMenu.Model); + constructor(element: JQuery | Element, options?: RadialMenu.Model); static Locale: any; - model:RadialMenu.Model; - defaults:RadialMenu.Model; + model: RadialMenu.Model; + defaults: RadialMenu.Model; /** To hide the radialmenu * @returns {void} @@ -34663,7 +36801,7 @@ class RadialMenu extends ej.Widget { * @param {Array} Index of the Radialmenu to be enabled. * @returns {void} */ - enableItemsByIndices(itemIndices: Array): void; + enableItemsByIndices(itemIndices: any[]): void; /** To disable menu item using index * @param {number} Index of the Radialmenu to be disabled. @@ -34675,7 +36813,7 @@ class RadialMenu extends ej.Widget { * @param {Array} items of the Radialmenu to disable. * @returns {void} */ - disableItemsByIndices(itemIndices: Array): void; + disableItemsByIndices(itemIndices: any[]): void; /** To enable menu item using item text * @param {string} item of the Radialmenu item to enable. @@ -34693,13 +36831,13 @@ class RadialMenu extends ej.Widget { * @param {Array} items of the Radialmenu item to enable. * @returns {void} */ - enableItems(items: Array): void; + enableItems(items: any[]): void; /** To disable menu items using item texts * @param {Array} items of the Radialmenu item to disable. * @returns {void} */ - disableItems(items: Array): void; + disableItems(items: any[]): void; /** To update menu item badge value * @param {number} The index value to add the given items at the specified index. If index is not specified, the given value will not be updated. @@ -34720,7 +36858,7 @@ class RadialMenu extends ej.Widget { */ hideBadge(index: number): void; } -export module RadialMenu{ +export namespace RadialMenu { export interface Model { @@ -34732,7 +36870,8 @@ export interface Model { */ backImageClass?: string; - /** Sets the root class for RadialMenu theme. This cssClass API helps to use custom skinning option for RadialMenu control. By defining the root class using this API, we need to include this root class in CSS. + /** Sets the root class for RadialMenu theme. This cssClass API helps to use custom skinning option for RadialMenu control. By defining the root class using this API, + * we need to include this root class in CSS. */ cssClass?: string; @@ -34746,7 +36885,7 @@ export interface Model { /** Specify the items of radial menu */ - items?: Array; + items?: Item[]; /** Specifies the radius of radial menu */ @@ -34761,13 +36900,13 @@ export interface Model { position?: any; /** Event triggers when we click an item. */ - click? (e: ClickEventArgs): void; + click?(e: ClickEventArgs): void; /** Event triggers when the menu is opened. */ - open? (e: OpenEventArgs): void; + open?(e: OpenEventArgs): void; /** Event triggers when the menu is closed. */ - close? (e: CloseEventArgs): void; + close?(e: CloseEventArgs): void; } export interface ClickEventArgs { @@ -34838,7 +36977,7 @@ export interface ItemsSliderSettings { /** Specifies the sliderSettings ticks values of nested radial menu items. */ - ticks?: Array; + ticks?: any[]; /** Specifies the sliderSettings stroke Width value. */ @@ -34881,17 +37020,16 @@ export interface Item { /** Specifies to add sub level items . */ - items?: Array; + items?: any[]; } } class Tile extends ej.Widget { static fn: Tile; - constructor(element: JQuery, options?: Tile.Model); - constructor(element: Element, options?: Tile.Model); + constructor(element: JQuery | Element, options?: Tile.Model); static Locale: any; - model:Tile.Model; - defaults:Tile.Model; + model: Tile.Model; + defaults: Tile.Model; /** Update the image template of tile item to another one. * @param {string} UpdateTemplate by using id @@ -34900,7 +37038,7 @@ class Tile extends ej.Widget { */ updateTemplate(id: string, index: number): void; } -export module Tile{ +export namespace Tile { export interface Model { @@ -34948,7 +37086,7 @@ export interface Model { /** Set the localization culture for Tile Widget. */ - locale?: String; + locale?: string; /** Section for liveTile specific functionalities. */ @@ -34980,10 +37118,10 @@ export interface Model { backgroundColor?: string; /** Event triggers when the mouseDown happens in the tile */ - mouseDown? (e: MouseDownEventArgs): void; + mouseDown?(e: MouseDownEventArgs): void; /** Event triggers when the mouseUp happens in the tile */ - mouseUp? (e: MouseUpEventArgs): void; + mouseUp?(e: MouseUpEventArgs): void; } export interface MouseDownEventArgs { @@ -35060,7 +37198,7 @@ export interface Badge { value?: number; /** Sets position for tile badge. - * @Default {“bottomright”} + * @Default {“bottomright”} */ position?: ej.Tile.BadgePosition|string; } @@ -35103,17 +37241,17 @@ export interface LiveTile { /** Specifies liveTile images in CSS classes. * @Default {null} */ - imageClass?: Array; + imageClass?: any[]; /** Specifies liveTile images in templates. * @Default {null} */ - imageTemplateId?: Array; + imageTemplateId?: any[]; /** Specifies liveTile images in CSS classes. * @Default {null} */ - imageUrl?: Array; + imageUrl?: any[]; /** Specifies liveTile type for Tile. See orientation * @Default {flip} @@ -35128,10 +37266,10 @@ export interface LiveTile { /** Sets the text to each living tile * @Default {Null} */ - text?: Array; + text?: any[]; } -enum BadgePosition{ +enum BadgePosition { ///To set the topright position of tile badge Topright, @@ -35141,7 +37279,7 @@ enum BadgePosition{ } -enum CaptionAlignment{ +enum CaptionAlignment { ///To set the normal alignment of text in tile control Normal, @@ -35157,7 +37295,7 @@ enum CaptionAlignment{ } -enum CaptionPosition{ +enum CaptionPosition { ///To set the inner top position of the tile text Innertop, @@ -35170,7 +37308,7 @@ enum CaptionPosition{ } -enum ImagePosition{ +enum ImagePosition { ///To set the center position of tile image Center, @@ -35204,7 +37342,7 @@ enum ImagePosition{ } -enum liveTileType{ +enum liveTileType { ///To set flip type of liveTile for tile control Flip, @@ -35217,7 +37355,7 @@ enum liveTileType{ } -enum TileSize{ +enum TileSize { ///To set the medium size for tile control Medium, @@ -35236,11 +37374,10 @@ enum TileSize{ class Signature extends ej.Widget { static fn: Signature; - constructor(element: JQuery, options?: Signature.Model); - constructor(element: Element, options?: Signature.Model); + constructor(element: JQuery | Element, options?: Signature.Model); static Locale: any; - model:Signature.Model; - defaults:Signature.Model; + model: Signature.Model; + defaults: Signature.Model; /** Clears the strokes in the signature. * @returns {void} @@ -35287,7 +37424,7 @@ class Signature extends ej.Widget { */ undo(): void; } -export module Signature{ +export namespace Signature { export interface Model { @@ -35345,16 +37482,16 @@ export interface Model { width?: string; /** Triggers when the stroke is changed. */ - change? (e: ChangeEventArgs): void; + change?(e: ChangeEventArgs): void; /** Triggered when the pointer is clicked or touched in the signature canvas. */ - mouseDown? (e: MouseDownEventArgs): void; + mouseDown?(e: MouseDownEventArgs): void; /** Triggered when the pointer is moved in the signature canvas. */ - mouseMove? (e: MouseMoveEventArgs): void; + mouseMove?(e: MouseMoveEventArgs): void; /** Triggered when the pointer is released after click or touch in the signature canvas. */ - mouseUp? (e: MouseUpEventArgs): void; + mouseUp?(e: MouseUpEventArgs): void; } export interface ChangeEventArgs { @@ -35433,7 +37570,7 @@ export interface MouseUpEventArgs { value?: any; } -enum SaveImageFormat{ +enum SaveImageFormat { ///To save the signature image with PNG format only. PNG, @@ -35452,11 +37589,10 @@ enum SaveImageFormat{ class RadialSlider extends ej.Widget { static fn: RadialSlider; - constructor(element: JQuery, options?: RadialSlider.Model); - constructor(element: Element, options?: RadialSlider.Model); + constructor(element: JQuery | Element, options?: RadialSlider.Model); static Locale: any; - model:RadialSlider.Model; - defaults:RadialSlider.Model; + model: RadialSlider.Model; + defaults: RadialSlider.Model; /** To show the radialslider * @returns {void} @@ -35468,7 +37604,7 @@ class RadialSlider extends ej.Widget { */ hide(): void; } -export module RadialSlider{ +export namespace RadialSlider { export interface Model { @@ -35477,7 +37613,8 @@ export interface Model { */ autoOpen?: boolean; - /** Sets the root class for RadialSlider theme. This cssClass API helps to use custom skinning option for RadialSlider control. By defining the root class using this API, we need to include this root class in CSS. + /** Sets the root class for RadialSlider theme. This cssClass API helps to use custom skinning option for RadialSlider control. + * By defining the root class using this API, we need to include this root class in CSS. */ cssClass?: string; @@ -35538,7 +37675,7 @@ export interface Model { /** Specifies the ticks value of radial slider */ - ticks?: Array; + ticks?: any[]; /** Specifies the value of radial slider * @Default {10} @@ -35546,22 +37683,22 @@ export interface Model { value?: number; /** Event triggers when the change occurs. */ - change? (e: ChangeEventArgs): void; + change?(e: ChangeEventArgs): void; /** Event triggers when the radial slider is created. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Event triggers when the mouse pointer is dragged over the radial slider. */ - mouseover? (e: MouseoverEventArgs): void; + mouseover?(e: MouseoverEventArgs): void; /** Event triggers when the Radial slider slides. */ - slide? (e: SlideEventArgs): void; + slide?(e: SlideEventArgs): void; /** Event triggers when the radial slider starts. */ - start? (e: StartEventArgs): void; + start?(e: StartEventArgs): void; /** Event triggers when the radial slider stops. */ - stop? (e: StopEventArgs): void; + stop?(e: StopEventArgs): void; } export interface ChangeEventArgs { @@ -35593,7 +37730,7 @@ export interface CreateEventArgs { */ cancel?: boolean; - /** returns the Radialslider model /td> + /** returns the Radialslider model */ model?: any; @@ -35689,11 +37826,10 @@ export interface StopEventArgs { class Spreadsheet extends ej.Widget { static fn: Spreadsheet; - constructor(element: JQuery, options?: Spreadsheet.Model); - constructor(element: Element, options?: Spreadsheet.Model); + constructor(element: JQuery | Element, options?: Spreadsheet.Model); static Locale: any; - model:Spreadsheet.Model; - defaults:Spreadsheet.Model; + model: Spreadsheet.Model; + defaults: Spreadsheet.Model; /** This method is used to add custom formulas in Spreadsheet. * @param {string} Pass the name of the formula. @@ -35711,25 +37847,25 @@ class Spreadsheet extends ej.Widget { * @param {string|Array} Optional. If range is specified, then it will clear all content in the specified range else it will use the current selected range. * @returns {void} */ - clearAll(range?: string|Array): void; + clearAll(range?: string|any[]): void; /** This property is used to clear all the formats applied in the specified range in Spreadsheet. * @param {string|Array} Optional. If range is specified, then it will clear all format in the specified range else it will use the current selected range. * @returns {void} */ - clearAllFormat(range?: string|Array): void; + clearAllFormat(range?: string|any[]): void; /** Used to clear the applied border in the specified range in Spreadsheet. * @param {string|Array} Optional. If range is specified, then it will clear border in the specified range else it will use the current selected range. * @returns {void} */ - clearBorder(range?: string|Array): void; + clearBorder(range?: string|any[]): void; /** This property is used to clear the contents in the specified range in Spreadsheet. * @param {string|Array} Optional. If the range is specified, then it will clear the content in the specified range else it will use the current selected range. * @returns {void} */ - clearContents(range?: string|Array): void; + clearContents(range?: string|any[]): void; /** This method is used to remove only the data in the range denoted by the specified range name. * @param {string} Pass the defined rangeSettings property name. @@ -35741,17 +37877,22 @@ class Spreadsheet extends ej.Widget { * @param {Array|string} Optional. If range is specified, it will clear data for the specified range else it will use the current selected range. * @param {string} Optional. If property is specified, it will remove the specified property in the range else it will remove default properties * @param {any} Optional. - * @param {boolean} Optional. pass `true`, if you want to skip the hidden rows + * @param {boolean} Optional. pass {{'`true`' | markdownify}}, if you want to skip the hidden rows * @param {any} Optional. Pass the status to perform undo and redo operation. * @param {any} Optional. It specifies whether to skip element processing or not. * @returns {void} */ - clearRangeData(range?: Array|string, property?: string, cells?: any, skipHiddenRow?: boolean, status?: any, skipCell?: any): void; + clearRangeData(range?: any[]|string, property?: string, cells?: any, skipHiddenRow?: boolean, status?: any, skipCell?: any): void; + + /** This method is used to clear undo and redo collections in the Spreadsheet. + * @returns {void} + */ + clearUndoRedo(): void; /** This method is used to copy or move the sheets in Spreadsheet. * @param {number} Pass the sheet index that you want to copy or move. * @param {number} Pass the position index where you want to copy or move. - * @param {boolean} Pass `true`,If you want to copy sheet or else it will move sheet. + * @param {boolean} Pass {{'`true`' | markdownify}},If you want to copy sheet or else it will move sheet. * @returns {void} */ copySheet(fromIdx: number, toIdx: number, isCopySheet: boolean): void; @@ -35795,7 +37936,7 @@ class Spreadsheet extends ej.Widget { * @param {Function} Pass the function that you want to perform range edit. * @returns {void} */ - editRange(rangeName: string, fn: Function): void; + editRange(rangeName: string, fn: any): void; /** This method is used to get the activation panel in the Spreadsheet. * @returns {HTMLElement} @@ -35815,9 +37956,9 @@ class Spreadsheet extends ej.Widget { getActiveCellElem(sheetIdx?: number): HTMLElement; /** This method is used to get the current active sheet index in Spreadsheet. - * @returns {Number} + * @returns {number} */ - getActiveSheetIndex(): Number; + getActiveSheetIndex(): number; /** This method is used to get the auto fill element in Spreadsheet. * @returns {HTMLElement} @@ -35834,21 +37975,21 @@ class Spreadsheet extends ej.Widget { /** This method is used to get the data settings in the Spreadsheet. * @param {number} Pass the sheet index. - * @returns {Number} + * @returns {number} */ - getDataSettings(sheetIdx: number): Number; + getDataSettings(sheetIdx: number): number; /** This method is used to get the frozen columns index in the Spreadsheet. * @param {number} Pass the sheet index. - * @returns {Number} + * @returns {number} */ - getFrozenColumns(sheetIdx: number): Number; + getFrozenColumns(sheetIdx: number): number; /** This method is used to get the frozen row index in Spreadsheet. * @param {number} Pass the sheet index. - * @returns {Number} + * @returns {number} */ - getFrozenRows(sheetIdx: number): Number; + getFrozenRows(sheetIdx: number): number; /** This method is used to get the hyperlink data as object from the specified cell in Spreadsheet. * @param {HTMLElement} Pass the DOM element to get hyperlink @@ -35859,7 +38000,7 @@ class Spreadsheet extends ej.Widget { /** This method is used to get all cell elements in the specified range. * @param {string} Pass the range that you want to get the cells. * @param {number} Pass the index of the sheet. - * @param {boolean} Optional. Pass `true`, if you want to skip the hidden rows. + * @param {boolean} Optional. Pass {{'`true`' | markdownify}}, if you want to skip the hidden rows. * @returns {HTMLElement} */ getRange(range: string, sheetIdx: number, skipHiddenRow?: boolean): HTMLElement; @@ -35868,13 +38009,13 @@ class Spreadsheet extends ej.Widget { * @param {any} Optional. Pass the range, property, sheetIdx, valueOnly in options. * @returns {Array} */ - getRangeData(options?: any): Array; + getRangeData(options?: any): any[]; /** This method is used to get the range indices array based on the specified alpha range in Spreadsheet. * @param {string} Pass the alpha range that you want to get range indices. * @returns {Array} */ - getRangeIndices(range: string): Array; + getRangeIndices(range: string): any[]; /** This method is used to get the sheet details based on the given sheet index in Spreadsheet. * @param {number} Pass the sheet index to get the sheet object. @@ -35888,9 +38029,14 @@ class Spreadsheet extends ej.Widget { */ getSheetElement(sheetIdx: number): HTMLElement; + /** This method is used to get all the sheets in workbook. + * @returns {Array} + */ + getSheets(): any[]; + /** This method is used to send a paging request to the specified sheet Index in the Spreadsheet. * @param {number} Pass the sheet index to perform paging at specified sheet index - * @param {boolean} Pass `true` to create a new sheet. If the specified sheet index is already exist, it navigate to that sheet else it create a new sheet. + * @param {boolean} Pass {{'`true`' | markdownify}} to create a new sheet. If the specified sheet index is already exist, it navigate to that sheet else it create a new sheet. * @returns {void} */ gotoPage(sheetIdx: number, newSheet: boolean): void; @@ -35972,24 +38118,31 @@ class Spreadsheet extends ej.Widget { /** This method is used to lock/unlock the range of cells in active sheet. Lock cells are activated only after the sheet is protected. Once the sheet is protected it is unable to lock/unlock cells. * @param {string|Array} Pass the alpha range cells or array range of cells. - * @param {string} Optional. By default is `true`. If it is `false` locked cells are unlocked. + * @param {string} Optional. By default is {{'`true`' | markdownify}}. If it is {{'`false`' | markdownify}} locked cells are unlocked. * @returns {void} */ - lockCells(range: string|Array, isLocked?: string): void; + lockCells(range: string|any[], isLocked?: string): void; /** This method is used to merge cells by across in the Spreadsheet. * @param {string} Optional. To pass the cell range or selected cells are process. - * @param {boolean} Optional. If pass `true` it does not show alert. + * @param {boolean} Optional. If pass {{'`true`' | markdownify}} it does not show alert. * @returns {void} */ mergeAcrossCells(range?: string, alertStatus?: boolean): void; /** This method is used to merge the selected cells in the Spreadsheet. * @param {string|Array} Optional. To pass the cell range or selected cells are process. - * @param {boolean} Optional. If pass `true` it does not show alert. + * @param {boolean} Optional. If pass {{'`true`' | markdownify}} it does not show alert. * @returns {void} */ - mergeCells(range?: string|Array, alertStatus?: boolean): void; + mergeCells(range?: string|any[], alertStatus?: boolean): void; + + /** This method is used to select a cell or range in the Spreadsheet. + * @param {any} Pass the start cell to perform selection. + * @param {any} Pass the end cell to perform selection. + * @returns {void} + */ + performSelection(startCell: any, endCell: any): void; /** This method is used to protect or unprotect active sheet. * @param {boolean} Optional. By default is `true`. If it is `false` active sheet is unprotected. @@ -36017,10 +38170,10 @@ class Spreadsheet extends ej.Widget { /** This method is used to remove the hyperlink from selected cells of current sheet. * @param {string} Hyperlink remove from the specified range. - * @param {boolean} Optional. If it is `true`, It will clear link only not format. + * @param {boolean} Optional. If it is {{'`true`' | markdownify}}, It will clear link only not format. * @param {boolean} Optional. Pass the status to perform undo and redo operations. * @param {any} Optional. Pass the cells that you want to remove hyperlink. - * @param {boolean} Optional. Pass `true`, if you want to skip the hidden rows. + * @param {boolean} Optional. Pass {{'`true`' | markdownify}}, if you want to skip the hidden rows. * @returns {void} */ removeHyperlink(range: string, isClearHLink?: boolean, status?: boolean, cells?: any, skipHiddenRow?: boolean): void; @@ -36031,6 +38184,12 @@ class Spreadsheet extends ej.Widget { */ removeRange(rangeName: string): void; + /** This method is used to remove the readonly option for the specified range. + * @param {string|Array} Pass the range. + * @returns {void} + */ + removeReadOnly(range?: string|any[]): void; + /** This method is used to save JSON data in Spreadsheet. * @returns {any} */ @@ -36063,13 +38222,25 @@ class Spreadsheet extends ej.Widget { */ setBorder(property: any, range?: string): void; + /** This method is used to set the height for the rows in the Spreadsheet. + * @param {Array|any} Pass the row index and height of the rows. + * @returns {void} + */ + setHeightToRows(heightColl: any[]|any): void; + /** This method is used to set the hyperlink in selected cells of the current sheet. * @param {string|Array} If range is specified, it will set the hyperlink in range of the cells. * @param {any} Pass cellAddress or webAddress * @param {number} If we pass cellAddress then which sheet to be navigate in the applied link. * @returns {void} */ - setHyperlink(range: string|Array, link: any, sheetIdx: number): void; + setHyperlink(range: string|any[], link: any, sheetIdx: number): void; + + /** This method is used to set the readonly option for the specified range. + * @param {string|Array} Pass the range. + * @returns {void} + */ + setReadOnly(range?: string|any[]): void; /** This method is used to set the focus to the Spreadsheet. * @returns {void} @@ -36080,7 +38251,7 @@ class Spreadsheet extends ej.Widget { * @param {Array|any} Pass the column index and width of the columns. * @returns {void} */ - setWidthToColumns(widthColl: Array|any): void; + setWidthToColumns(widthColl: any[]|any): void; /** This method is used to rename the active sheet. * @param {string} Pass the sheet name that you want to change the current active sheet name. @@ -36107,17 +38278,23 @@ class Spreadsheet extends ej.Widget { showFormulaBar(): void; /** This method is used to show/hide gridlines in active sheet in the Spreadsheet. - * @param {boolean} Pass `true` to show the gridlines + * @param {boolean} Pass {{'`true`' | markdownify}} to show the gridlines * @returns {void} */ showGridlines(status: boolean): void; /** This method is used to show/hide the headers in active sheet in the Spreadsheet. - * @param {boolean} Pass `true` to show the sheet headers. + * @param {boolean} Pass {{'`true`' | markdownify}} to show the sheet headers. * @returns {void} */ showHeadings(startRow: boolean): void; + /** This method is used to show/hide pager in the Spreadsheet. + * @param {boolean} Pass {{'`true`' | markdownify}} to show pager. + * @returns {void} + */ + showPager(status: boolean): void; + /** This method is used to show the hidden rows in the specified range in the Spreadsheet. * @param {number} Index of the start row. * @param {number} Optional. Index of the end row. @@ -36151,14 +38328,14 @@ class Spreadsheet extends ej.Widget { * @param {Array|string} Optional. If the range is specified, then it will update unwrap in the specified range else it will use the current selected range. * @returns {void} */ - unWrapText(range?: Array|string): void; + unWrapText(range?: any[]|string): void; /** This method is used to update the data for the specified range of cells in the Spreadsheet. * @param {any} Pass the cells data that you want to update. * @param {Array|string} Optional. If range is specified, it will update data for the specified range else it will use the current selected range. * @returns {void} */ - updateData(data: any, range?: Array|string): void; + updateData(data: any, range?: any[]|string): void; /** This method is used to update the formula bar in the Spreadsheet. * @returns {void} @@ -36172,19 +38349,25 @@ class Spreadsheet extends ej.Widget { */ updateRange(sheetIdx: number, settings: any): void; + /** This method is used to update the details for custom undo and redo operations. + * @param {any} Pass the details to update undo and redo collection + * @returns {void} + */ + updateUndoRedoCollection(details: any): void; + /** This method is used to update the unique data for the specified range of cells in Spreadsheet. * @param {any} Pass the data that you want to update in the particular range * @param {Array|string} Optional. If range is specified, it will update data for the specified range else it will use the current selected range. * @param {any} Optional. It specifies whether to skip element processing or not. * @returns {void} */ - updateUniqueData(data: any, range?: Array|string, skipCell?: any): void; + updateUniqueData(data: any, range?: any[]|string, skipCell?: any): void; /** This method is used to wrap the selected range of cells in the Spreadsheet. * @param {Array|string} Optional. If the range is specified, then it will update wrap in the specified range else it will use the current selected range. * @returns {void} */ - wrapText(range?: Array|string): void; + wrapText(range?: any[]|string): void; XLCellType: Spreadsheet.XLCellType; @@ -36235,7 +38418,7 @@ class Spreadsheet extends ej.Widget { XLValidate: Spreadsheet.XLValidate; } -export module Spreadsheet{ +export namespace Spreadsheet { export interface XLCellType { @@ -36245,31 +38428,31 @@ export interface XLCellType { * @param {number} Optional. Pass sheet index. * @returns {void} */ - addCellTypes(range: string,settings: any,sheetIdx: number): void; + addCellTypes(range: string, settings: any, sheetIdx: number): void; /** This method is used to remove cell type from the specified range of cells in the Spreadsheet. * @param {string|Array} Pass the range where you want remove cell type. * @param {number} Optional. Pass sheet index. * @returns {void} */ - removeCellTypes(range: string|Array,sheetIdx: number): void; + removeCellTypes(range: string|any[], sheetIdx: number): void; } export interface XLCFormat { /** This method is used to clear the applied conditional formatting rules in the Spreadsheet. - * @param {boolean} Pass `true` if you want to clear rules from selected cells else it will clear rules from entire sheet. + * @param {boolean} Pass {{'`true`' | markdownify}} if you want to clear rules from selected cells else it will clear rules from entire sheet. * @param {Array|string} Optional. If range is specified, it will clear rules for the specified range else it will use the current selected range. * @returns {void} */ - clearCF(isSelected: boolean,range: Array|string): void; + clearCF(isSelected: boolean, range: any[]|string): void; /** This method is used to get the applied conditional formatting rules as array of objects based on the specified row Index and column Index in the Spreadsheet. * @param {number} Pass the row index. * @param {number} Pass the column index. * @returns {Array} */ - getCFRule(rowIdx: number,colIdx: number): Array; + getCFRule(rowIdx: number, colIdx: number): any[]; /** This method is used to set the conditional formatting rule in the Spreadsheet. * @param {any} Pass the rule to set. @@ -36285,7 +38468,14 @@ export interface XLChart { * @param {ej.datavisualization.Chart.Theme} Pass the chart theme which want to update. * @returns {void} */ - changeTheme(chartId: string,theme: ej.datavisualization.Chart.Theme): void; + changeTheme(chartId: string, theme: ej.datavisualization.Chart.Theme): void; + + /** This method is used to change the type of the chart in the Spreadsheet. + * @param {string} Pass the chart id. + * @param {any} Pass the chart type. + * @returns {void} + */ + changeType(chartId: string, option: any): void; /** This method is used to change the data range of the chart in the Spreadsheet. * @param {string} Pass the chart id. @@ -36294,21 +38484,21 @@ export interface XLChart { * @param {string} Legend range of chart data. * @returns {void} */ - changeDataRange(chartId: string,xRange: string,yRange: string,lRange: string): void; + changeDataRange(chartId: string, xRange: string, yRange: string, lRange: string): void; /** This method is used to create a chart for specified range in Spreadsheet. * @param {string|Array} Optional. If range is specified, it will create chart for the specified range else it will use the current selected range. * @param {any} Optional. To pass the type of chart and chart name. * @returns {void} */ - createChart(range: string|Array,options: any): void; + createChart(range: string|any[], options: any): void; /** This method is used to refresh the chart in the Spreadsheet. * @param {string} To pass the chart Id. * @param {any} To pass the type of chart and chart name. * @returns {void} */ - refreshChart(id: string,options: any): void; + refreshChart(id: string, options: any): void; /** This method is used to resize the chart of specified id in the Spreadsheet. * @param {string} To pass the chart id. @@ -36316,14 +38506,14 @@ export interface XLChart { * @param {number} To pass the width value. * @returns {void} */ - resizeChart(id: string,height: number,width: number): void; + resizeChart(id: string, height: number, width: number): void; /** This method is used to update the chart element, such as axes, titles, data labels, grid lines and legends in the Spreadsheet. * @param {string} Pass the chart id. * @param {ej.Spreadsheet.ChartProperties} Pass chart element value which you want to update. * @returns {void} */ - updateChartElement(chartId: string,value: ej.Spreadsheet.ChartProperties): void; + updateChartElement(chartId: string, value: ej.Spreadsheet.ChartProperties): void; /** This method is used switch row to columns and vice versa for chart in the Spreadsheet. So that the data is displayed in the chart the way you want. * @param {string} Pass the chart id. @@ -36355,10 +38545,10 @@ export interface XLComment { /** This method is used to delete the comment in the specified range in Spreadsheet. * @param {Array|string} Optional. If range is specified, it will delete comments for the specified range else it will use the current selected range. * @param {number} Optional. If sheetIdx is specified, it will delete comment in specified sheet else it will use active sheet. - * @param {boolean} Optional. Pass `true`, if you want to skip the hidden rows data. + * @param {boolean} Optional. Pass {{'`true`' | markdownify}}, if you want to skip the hidden rows data. * @returns {void} */ - deleteComment(range: Array|string,sheetIdx: number,skipHiddenRow: boolean): void; + deleteComment(range: any[]|string, sheetIdx: number, skipHiddenRow: boolean): void; /** This method is used to edit the comment in the target Cell in Spreadsheet. * @param {any} Optional. Pass the row index and column index of the cell which contains comment. @@ -36367,14 +38557,14 @@ export interface XLComment { editComment(targetCell: any): void; /** This method is used to find the next comment from the active cell in Spreadsheet. - * @returns {Boolean} + * @returns {boolean} */ - findNextComment(): Boolean; + findNextComment(): boolean; /** This method is used to find the previous comment from the active cell in Spreadsheet. - * @returns {Boolean} + * @returns {boolean} */ - findPrevComment(): Boolean; + findPrevComment(): boolean; /** This method is used to get comment data for the specified cell. * @param {HTMLElement} Pass the DOM element to get comment data as object. @@ -36385,11 +38575,11 @@ export interface XLComment { /** This method is used to set new comment in Spreadsheet. * @param {string|Array} Optional. If we pass the range comment will set in the range otherwise it will set with selected cells. * @param {string} Optional. Pass the comment data. - * @param {boolean} Optional. Pass `true` to show comment in edit mode - * @param {boolean} Optional. Pass `true` to show the user name + * @param {boolean} Optional. Pass {{'`true`' | markdownify}} to show comment in edit mode + * @param {boolean} Optional. Pass {{'`true`' | markdownify}} to show the user name * @returns {void} */ - setComment(range: string|Array,data: string,showEditPanel: boolean,showUserName: boolean): void; + setComment(range: string|any[], data: string, showEditPanel: boolean, showUserName: boolean): void; /** This method is used to show all the comments in the Spreadsheet. * @returns {void} @@ -36411,35 +38601,35 @@ export interface XLCMenu { * @param {string} Specifies the type of operation to be performed * @returns {void} */ - addItem(target: string,itemColl: Array,operation: string): void; + addItem(target: string, itemColl: any[], operation: string): void; /** This method is used to change data source in the context menu. * @param {string} Specifies the context menu type to bind the data source. * @param {Array} Pass the data source to be binded * @returns {void} */ - changeDataSource(target: string,data: Array): void; + changeDataSource(target: string, data: any[]): void; /** This method is used to disable the items in the context menu. * @param {string} Specifies the context menu type in which the item to be disabled. * @param {Array} Specifies the Menu Item id collection to be disabled * @returns {void} */ - disableItem(target: string,idxColl: Array): void; + disableItem(target: string, idxColl: any[]): void; /** This method is used to enable the items in the context menu. * @param {string} Specifies the context menu type in which the item to be enabled. * @param {Array} Specifies the Menu Item id collection to be enabled * @returns {void} */ - enableItem(target: string,idxColl: Array): void; + enableItem(target: string, idxColl: any[]): void; /** This method is used to remove the items in the context menu. * @param {string} Specifies the context menu type in which the item to be removed. * @param {Array} Specifies the Menu Item id collection to be removed * @returns {void} */ - removeItem(target: string,idxColl: Array): void; + removeItem(target: string, idxColl: any[]): void; } export interface XLDragDrop { @@ -36449,7 +38639,7 @@ export interface XLDragDrop { * @param {any|Array} Pass the destination range to drop the dragged cells. * @returns {void} */ - moveRangeTo(sourceRange: any|Array,destinationRange: any|Array): void; + moveRangeTo(sourceRange: any|any[], destinationRange: any|any[]): void; } export interface XLDragFill { @@ -36471,7 +38661,7 @@ export interface XLDragFill { hideAutoFillOptions(): void; /** This method is used to set position of the auto fill element in the Spreadsheet. - * @param {boolean} Pass the isDragFill option as `boolean` value to show auto fill options in Spreadsheet. + * @param {boolean} Pass the isDragFill option as {{'`boolean`' | markdownify}} value to show auto fill options in Spreadsheet. * @returns {void} */ positionAutoFillElement(isDragFill: boolean): void; @@ -36488,27 +38678,31 @@ export interface XLEdit { /** This method is used to edit a particular cell based on the row index and column index in the Spreadsheet. * @param {number} Pass the row index to edit particular cell. * @param {number} Pass the column index to edit particular cell. - * @param {boolean} Pass `true`, if you want to maintain previous cell value. + * @param {boolean} Pass {{'`true`' | markdownify}}, if you want to maintain previous cell value. * @returns {void} */ - editCell(rowIdx: number,colIdx: number,oldData: boolean): void; + editCell(rowIdx: number, colIdx: number, oldData: boolean): void; /** This method is used to get the property value of particular cell, based on the row and column index in the Spreadsheet. * @param {number} Pass the row index to get the property value. * @param {number} Pass the column index to get the property value. - * @param {string} Optional. Pass the property name that you want("value", "value2", "type", "cFormatRule", "range", "thousandSeparator", "rule", "format", "border", "picture", "chart", "calcValue", "align", "hyperlink", "formats", "borders", "tformats", "tborders", "isFilterHeader", "filterState", "tableName", "comment", "formatStr", "decimalPlaces", "cellType"). + * @param {string} Optional. Pass the property name that you want("value", "value2", "type", "cFormatRule", "range", "thousandSeparator", "rule", "format", "border", "picture", + * "chart", "calcValue", "align", "hyperlink", "formats", "borders", "tformats", "tborders", "isFilterHeader", "filterState", "tableName", "comment", "formatStr", + * "decimalPlaces", "cellType"). * @param {number} Optional. Pass the index of the sheet. - * @returns {any|String|Array} + * @returns {any|string|Array} */ - getPropertyValue(rowIdx: number,colIdx: number,prop: string,sheetIdx: number): any|String|Array; + getPropertyValue(rowIdx: number, colIdx: number, prop: string, sheetIdx: number): any|string|any[]; /** This method is used to get the property value in specified cell in Spreadsheet. * @param {HTMLElement} Pass the cell element to get property value. - * @param {string} Pass the property name that you want ("value", "value2", "type", "cFormatRule", "range", "thousandSeparator", "rule", "format", "border", "picture", "chart", "calcValue", "align", "hyperlink", "formats", "borders", "tformats", "tborders", "isFilterHeader", "filterState", "tableName", "comment", "formatStr", "decimalPlaces", "cellType"). + * @param {string} Pass the property name that you want ("value", "value2", "type", "cFormatRule", "range", "thousandSeparator", "rule", "format", "border", + * "picture", "chart", "calcValue", "align", "hyperlink", "formats", "borders", "tformats", "tborders", "isFilterHeader", "filterState", "tableName", + * "comment", "formatStr", "decimalPlaces", "cellType"). * @param {number} Pass the index of sheet. - * @returns {any|String|Array} + * @returns {any|string|Array} */ - getPropertyValueByElem(elem: HTMLElement,property: string,sheetIdx: number): any|String|Array; + getPropertyValueByElem(elem: HTMLElement, property: string, sheetIdx: number): any|string|any[]; /** This method is used to save the edited cell value in the Spreadsheet. * @returns {void} @@ -36520,7 +38714,7 @@ export interface XLEdit { * @param {string|number} Pass the cell value. * @returns {void} */ - updateCell(cell: any,value: string|number): void; + updateCell(cell: any, value: string|number): void; /** This method is used to update a particular cell value and its format in the Spreadsheet. * @param {any} Pass row index and column index of the cell. @@ -36529,7 +38723,7 @@ export interface XLEdit { * @param {number} Pass sheet index. * @returns {void} */ - updateCellValue(cellIdx: any,val: string|number,formatClass: string,sheetIdx: number): void; + updateCellValue(cellIdx: any, val: string|number, formatClass: string, sheetIdx: number): void; } export interface XLExport { @@ -36557,7 +38751,7 @@ export interface XLFilter { * @param {string|Array} Pass the range of the selected cells. * @returns {void} */ - filter(range: string|Array): void; + filter(range: string|any[]): void; /** This method is used to apply filter for the column by active cell's value in the Spreadsheet. * @returns {void} @@ -36567,26 +38761,32 @@ export interface XLFilter { export interface XLFormat { + /** This method is used to convert table range to normal range. + * @param {any} Pass the sheet index and table id. + * @returns {void} + */ + convertToRange(options: any): void; + /** This method is used to create a table for the selected range of cells in the Spreadsheet. * @param {any} Pass the table object. * @param {string|Array} Optional. If the range is specified, then it will create table in the specified range else it will use the current selected range. - * @returns {String} + * @returns {string} */ - createTable(tableObject: any,range: string|Array): String; + createTable(tableObject: any, range: string|any[]): string; /** This method is used to set format style and values in a cell or range of cells. * @param {any} Pass the formatObject which contains style, type, format, groupSeparator and decimalPlaces. * @param {string} Pass the range to format cells. * @returns {void} */ - format(formatObj: any,range: string): void; + format(formatObj: any, range: string): void; /** This method is used to remove the style in the specified range. * @param {Array|string} Pass the cell range . * @param {any} Optional. Pass the options for which the style gets removed. * @returns {void} */ - removeStyle(range: Array|string,options: any): void; + removeStyle(range: any[]|string, options: any): void; /** This method is used to remove table with specified tableId in the Spreadsheet. * @param {number} Pass the tableId that you want to remove. @@ -36599,21 +38799,21 @@ export interface XLFormat { * @param {string|Array} Pass the range. * @returns {void} */ - updateDecimalPlaces(type: string,range: string|Array): void; + updateDecimalPlaces(type: string, range: string|any[]): void; /** This method is used to update the format for the selected range of cells in the Spreadsheet. * @param {any} Pass the format object that you want to update. * @param {Array} Optional. If the range is specified, then it will update format in the specified range else it will use the current selected range. * @returns {void} */ - updateFormat(formatObj: any,range: Array): void; + updateFormat(formatObj: any, range: any[]): void; /** This method is used to update the unique format for selected range of cells in the Spreadsheet. * @param {string} Pass the unique format class. * @param {Array} Optional. If the range is specified, then it will update format in the specified range else it will use the current selected range. * @returns {void} */ - updateUniqueFormat(formatClass: string,range: Array): void; + updateUniqueFormat(formatClass: string, range: any[]): void; } export interface XLFreeze { @@ -36661,9 +38861,9 @@ export interface XLPivot { * @param {string} It specifies the name of the pivot table. * @param {any} Pass the pivot table settings. * @param {any} Pass the pivot range, sheet index, address and data source . - * @returns {String} + * @returns {string} */ - createPivotTable(range: string,location: string,name: string,settings: any,pvt: any): String; + createPivotTable(range: string, location: string, name: string, settings: any, pvt: any): string; /** This method is used to delete the pivot table which is selected. * @param {string} Pass the name of the pivot table. @@ -36676,7 +38876,7 @@ export interface XLPivot { * @param {number} Optional. Pass the index of the sheet. * @returns {void} */ - refreshDataSource(name: string,sheetIdx: number): void; + refreshDataSource(name: string, sheetIdx: number): void; } export interface XLPrint { @@ -36698,39 +38898,39 @@ export interface XLResize { * @param {Array} Optional. Pass row index collection that you want to fit its height. * @returns {void} */ - fitHeight(rowIndexes: Array): void; + fitHeight(rowIndexes: any[]): void; /** This method is used to fit the width of columns in the Spreadsheet. * @param {Array} Optional. Pass column index collection that you want to fit its width. * @returns {void} */ - fitWidth(colIndexes: Array): void; + fitWidth(colIndexes: any[]): void; /** This method is used to get the column width of the specified column index in the Spreadsheet. * @param {number} Pass the column index. - * @returns {Number} + * @returns {number} */ - getColWidth(colIdx: number): Number; + getColWidth(colIdx: number): number; /** This method is used to get the row height of the specified row index in the Spreadsheet. * @param {number} Pass the row index which you want to find its height. - * @returns {Number} + * @returns {number} */ - getRowHeight(rowIdx: number): Number; + getRowHeight(rowIdx: number): number; /** This method is used to set the column width of the specified column index in the Spreadsheet. * @param {number} Pass the column index. * @param {number} Pass the width value that you want to set. * @returns {void} */ - setColWidth(colIdx: number,size: number): void; + setColWidth(colIdx: number, size: number): void; /** This method is used to set the row height of the specified row index in the Spreadsheet. * @param {number} Pass the row index. * @param {number} Pass the height value that you want to set. * @returns {void} */ - setRowHeight(rowIdx: number,size: number): void; + setRowHeight(rowIdx: number, size: number): void; } export interface XLRibbon { @@ -36740,21 +38940,21 @@ export interface XLRibbon { * @param {number} pass the index of the item to be added in the backstage. * @returns {void} */ - addBackStageItem(pageItem: any,index: number): void; + addBackStageItem(pageItem: any, index: number): void; /** This method is used to dynamically add the contextual tabs in the ribbon. * @param {any} Specifies the contextual tab set object. * @param {number} pass the index of the contextual tab. * @returns {void} */ - addContextualTabs(contextualTabSet: any,index: number): void; + addContextualTabs(contextualTabSet: any, index: number): void; /** This method is used to dynamically add the menu item in the file menu. * @param {Array} Specifies the item to be added * @param {number} pass the index of the menu item. * @returns {void} */ - addMenuItem(item: Array,index: number): void; + addMenuItem(item: any[], index: number): void; /** This method is used to add a new name in the Spreadsheet name manager. * @param {string} Pass the name that you want to define in name manager. @@ -36763,7 +38963,7 @@ export interface XLRibbon { * @param {number} Optional. Pass the sheet index. * @returns {void} */ - addNamedRange(name: string,refersTo: string,comment: string,sheetIdx: number): void; + addNamedRange(name: string, refersTo: string, comment: string, sheetIdx: number): void; /** This method is used to dynamically add the tab in the ribbon. * @param {Array} Specifies the text to be displayed in the tab. @@ -36771,7 +38971,7 @@ export interface XLRibbon { * @param {number} pass the index of the tab. * @returns {void} */ - addTab(tabText: Array,ribbonGroups: number,index: number): void; + addTab(tabText: any[], ribbonGroups: number, index: number): void; /** This method is used to dynamically add the tab group in the ribbon. * @param {number} Specifies the ribbon tab index. @@ -36779,14 +38979,14 @@ export interface XLRibbon { * @param {number} pass the index of the ribbon group. * @returns {void} */ - addTabGroup(tabIndex: number,tabGroup: any,groupIndex: number): void; + addTabGroup(tabIndex: number, tabGroup: any, groupIndex: number): void; /** This method is used to insert the few type (SUM, MAX, MIN, AVG, COUNT) of formulas in the selected range of cells in the Spreadsheet. * @param {string} To pass the type("SUM","MAX","MIN","AVG","COUNT"). * @param {string|Array} If range is specified, it will apply auto sum for the specified range else it will use the current selected range. * @returns {void} */ - autoSum(type: string,range: string|Array): void; + autoSum(type: string, range: string|any[]): void; /** This method is used to hide the file menu in the ribbon tab. * @returns {void} @@ -36816,14 +39016,14 @@ export interface XLRibbon { * @param {boolean} pass the boolean value to remove the tab from ribbon * @returns {void} */ - removeTab(index: number,isRemoveMenu: boolean): void; + removeTab(index: number, isRemoveMenu: boolean): void; /** This method is used to remove the tab group form ribbon in the spreadsheet. * @param {number} Specifies the index of the tab group to be removed from the ribbon. * @param {string} Specifies the text to be displayed in the tab group * @returns {void} */ - removeTabGroup(tabIndex: number,groupText: string): void; + removeTabGroup(tabIndex: number, groupText: string): void; /** This method is used to show the file menu in the ribbon tab. * @returns {void} @@ -36835,7 +39035,7 @@ export interface XLRibbon { * @param {number} pass the index of the item to be updated * @returns {void} */ - updateMenuItem(item: any,index: number): void; + updateMenuItem(item: any, index: number): void; /** This method is used to update the ribbon icons in the Spreadsheet. * @returns {void} @@ -36848,20 +39048,20 @@ export interface XLSearch { /** This method is used to find and replace all data by workbook in the Spreadsheet. * @param {string} Pass the search data. * @param {string} Pass the replace data. - * @param {boolean} Pass `true`, if you want to match with case-sensitive. - * @param {boolean} Pass `true`, if you want to match with entire cell contents. + * @param {boolean} Pass {{'`true`' | markdownify}}, if you want to match with case-sensitive. + * @param {boolean} Pass {{'`true`' | markdownify}}, if you want to match with entire cell contents. * @returns {void} */ - replaceAllByBook(findData: string,replaceData: string,isCSen: boolean,isEMatch: boolean): void; + replaceAllByBook(findData: string, replaceData: string, isCSen: boolean, isEMatch: boolean): void; /** This method is used to find and replace all data by sheet in Spreadsheet. * @param {string} Pass the search data. * @param {string} Pass the replace data. - * @param {boolean} Pass `true`, if you want to match with case-sensitive. - * @param {boolean} Pass `true`, if you want to match with entire cell contents. + * @param {boolean} Pass {{'`true`' | markdownify}}, if you want to match with case-sensitive. + * @param {boolean} Pass {{'`true`' | markdownify}}, if you want to match with entire cell contents. * @returns {void} */ - replaceAllBySheet(findData: string,replaceData: string,isCSen: boolean,isEMatch: boolean): void; + replaceAllBySheet(findData: string, replaceData: string, isCSen: boolean, isEMatch: boolean): void; } export interface XLSelection { @@ -36881,7 +39081,7 @@ export interface XLSelection { * @param {Array|string} Optional. Pass range to refresh selection. * @returns {void} */ - refreshSelection(range: Array|string): void; + refreshSelection(range: any[]|string): void; /** This method is used to select a single column in the Spreadsheet. * @param {number} Pass the column index value. @@ -36894,7 +39094,7 @@ export interface XLSelection { * @param {number} Pass the column end index. * @returns {void} */ - selectColumns(startIdx: number,endIdx: number): void; + selectColumns(startIdx: number, endIdx: number): void; /** This method is used to select the specified range of cells in the Spreadsheet. * @param {string} Pass range which want to select. @@ -36913,7 +39113,7 @@ export interface XLSelection { * @param {number} Pass the end row index. * @returns {void} */ - selectRows(startIdx: number,endIdx: number): void; + selectRows(startIdx: number, endIdx: number): void; /** This method is used to select all cells in active sheet. * @returns {void} @@ -36930,28 +39130,28 @@ export interface XLShape { * @param {number} Optional. Pass the height of the image that you want to set. * @param {number} Optional. Pass the top of the image that you want to set. * @param {number} Optional. Pass the left of the image that you want to set. - * @returns {String} + * @returns {string} */ - setPicture(range: string,url: string,width: number,height: number,top: number,left: number): String; + setPicture(range: string, url: string, width: number, height: number, top: number, left: number): string; } export interface XLSort { /** This method is used to sort a particular range of cells based on its cell or font color in the Spreadsheet. - * @param {string} Pass 'PutCellColor' to sort by cell color or 'PutFontColor' for by font color. + * @param {string} Pass {{'`PutCellColor`' | markdownify}} to sort by cell color or {{'`PutFontColor`' | markdownify}} for sort by font color. * @param {any} Pass the HEX color code to sort. * @param {string} Pass the range * @returns {void} */ - sortByColor(operation: string,color: any,range: string): void; + sortByColor(operation: string, color: any, range: string): void; /** This method is used to sort a particular range of cells based on its values in the Spreadsheet. * @param {Array|string} Pass the range to sort. * @param {string} Pass the column name. * @param {any} Pass the direction to sort (ascending or descending). - * @returns {Boolean} + * @returns {boolean} */ - sortByRange(range: Array|string,columnName: string,direction: any): Boolean; + sortByRange(range: any[]|string, columnName: string, direction: any): boolean; } export interface XLValidate { @@ -36960,23 +39160,23 @@ export interface XLValidate { * @param {string|Array} If range is specified, it will apply rules for the specified range else it will use the current selected range. * @param {Array} Pass the validation condition, value1 and value2. * @param {string} Pass the data type. - * @param {boolean} Pass `true` if you ignore blank values. - * @param {boolean} Pass `true` if you want to show an error alert. + * @param {boolean} Pass {{'`true`' | markdownify}} if you ignore blank values. + * @param {boolean} Pass {{'`true`' | markdownify}} if you want to show an error alert. * @returns {void} */ - applyDVRules(range: string|Array,values: Array,type: string,required: boolean,showErrorAlert: boolean): void; + applyDVRules(range: string|any[], values: any[], type: string, required: boolean, showErrorAlert: boolean): void; /** This method is used to clear the applied validation rules in a specified range of cells in the Spreadsheet. * @param {string|Array} Optional. If range is specified, it will clear rules for the specified range else it will use the current selected range. * @returns {void} */ - clearDV(range: string|Array): void; + clearDV(range: string|any[]): void; /** This method is used to highlight invalid data in a specified range of cells in the Spreadsheet. * @param {string|Array} Optional. If range is specified, it will clear rules for the specified range else it will use the current selected range. * @returns {void} */ - highlightInvalidData(range: string|Array): void; + highlightInvalidData(range: string|any[]): void; } export interface Model { @@ -36984,7 +39184,7 @@ export interface Model { /** Gets or sets an active sheet index in the Spreadsheet. By defining this value, you can specify which sheet should be active in workbook. * @Default {1} */ - activeSheetIndex?: Number; + activeSheetIndex?: number; /** Gets or sets a value that indicates whether to enable or disable auto rendering of cell type in the Spreadsheet. * @Default {false} @@ -37031,7 +39231,8 @@ export interface Model { */ allowComments?: boolean; - /** Gets or sets a value that indicates whether to enable or disable Conditional Format feature in the Spreadsheet. By enabling this, you can apply formatting to the selected range of cells based on the provided conditions (Greater than, Less than, Equal, Between, Contains, etc.). + /** Gets or sets a value that indicates whether to enable or disable Conditional Format feature in the Spreadsheet. By enabling this, you can apply formatting to the selected range + * of cells based on the provided conditions (Greater than, Less than, Equal, Between, Contains, etc.). * @Default {true} */ allowConditionalFormats?: boolean; @@ -37066,7 +39267,8 @@ export interface Model { */ allowFormatAsTable?: boolean; - /** Get or sets a value that indicates whether to enable or disable format painter feature in the Spreadsheet. By enabling this feature, you can copy the format from the selected range and apply it to another range. + /** Get or sets a value that indicates whether to enable or disable format painter feature in the Spreadsheet. By enabling this feature, you can copy + * the format from the selected range and apply it to another range. * @Default {true} */ allowFormatPainter?: boolean; @@ -37076,12 +39278,14 @@ export interface Model { */ allowFormulaBar?: boolean; - /** Gets or sets a value that indicates whether to enable or disable freeze pane support in Spreadsheet. After enabling this feature, you can use freeze top row, freeze first column and freeze panes options. + /** Gets or sets a value that indicates whether to enable or disable freeze pane support in Spreadsheet. After enabling this feature, + * you can use freeze top row, freeze first column and freeze panes options. * @Default {false} */ allowFreezing?: boolean; - /** Gets or sets a value that indicates whether to enable or disable hyperlink feature in the Spreadsheet. By enabling this feature, you can add hyperlink which is used to easily navigate to the cell reference from one sheet to another or a web page. + /** Gets or sets a value that indicates whether to enable or disable hyperlink feature in the Spreadsheet. By enabling this feature, you can add hyperlink which is used to + * easily navigate to the cell reference from one sheet to another or a web page. * @Default {true} */ allowHyperlink?: boolean; @@ -37116,12 +39320,14 @@ export interface Model { */ allowOverflow?: boolean; - /** Gets or sets a value that indicates whether to enable or disable resizing feature in the Spreadsheet. By enabling this feature, you can change the column width and row height by dragging its header boundaries. + /** Gets or sets a value that indicates whether to enable or disable resizing feature in the Spreadsheet. By enabling this feature, you can change the column width and + * row height by dragging its header boundaries. * @Default {true} */ allowResizing?: boolean; - /** Gets or sets a value that indicates whether to enable or disable find and replace feature in the Spreadsheet. By enabling this, you can easily find and replace a specific value in the sheet or workbook. By using goto behavior, you can select and highlight all cells that contains specific data or data types. + /** Gets or sets a value that indicates whether to enable or disable find and replace feature in the Spreadsheet. By enabling this, you can easily find and replace + * a specific value in the sheet or workbook. By using goto behavior, you can select and highlight all cells that contains specific data or data types. * @Default {true} */ allowSearching?: boolean; @@ -37141,7 +39347,8 @@ export interface Model { */ allowUndoRedo?: boolean; - /** Gets or sets a value that indicates whether to enable or disable wrap text feature in the Spreadsheet. By enabling this, cell content can wrap to the next line, if the cell content exceeds the boundary of the cell. + /** Gets or sets a value that indicates whether to enable or disable wrap text feature in the Spreadsheet. By enabling this, cell content can wrap to the next line, + * if the cell content exceeds the boundary of the cell. * @Default {true} */ allowWrap?: boolean; @@ -37149,7 +39356,7 @@ export interface Model { /** Gets or sets a value that indicates to define the width of the activation panel in Spreadsheet. * @Default {300} */ - apWidth?: Number; + apWidth?: number; /** Gets or sets an object that indicates to customize the auto fill behavior in the Spreadsheet. */ @@ -37162,12 +39369,12 @@ export interface Model { /** Gets or sets a value that defines the number of columns displayed in the sheet. * @Default {21} */ - columnCount?: Number; + columnCount?: number; /** Gets or sets a value that indicates to define the common width for each column in the Spreadsheet. * @Default {64} */ - columnWidth?: Number; + columnWidth?: number; /** Gets or sets a value to add root CSS class for customizing Spreadsheet skins. */ @@ -37176,7 +39383,7 @@ export interface Model { /** Gets or sets a value that indicates custom formulas in Spreadsheet. * @Default {[]} */ - customFormulas?: Array; + customFormulas?: any[]; /** Gets or sets a value that indicates whether to enable or disable context menu in the Spreadsheet. * @Default {true} @@ -37210,7 +39417,8 @@ export interface Model { */ isReadOnly?: boolean; - /** Gets or sets a value that indicates whether to customizing the user interface (UI) as locale-specific in order to display regional data (i.e.) in a language and culture specific to a particular country or region. + /** Gets or sets a value that indicates whether to customizing the user interface (UI) as locale-specific in order to display regional data (i.e.) + * in a language and culture specific to a particular country or region. * @Default {en-US} */ locale?: string; @@ -37230,12 +39438,12 @@ export interface Model { /** Gets or sets a value that indicates whether to define the number of rows to be displayed in the sheet. * @Default {20} */ - rowCount?: Number; + rowCount?: number; /** Gets or sets a value that indicates to define the common height for each row in the sheet. * @Default {20} */ - rowHeight?: Number; + rowHeight?: number; /** Gets or sets an object that indicates to customize the scroll options in the Spreadsheet. */ @@ -37248,11 +39456,11 @@ export interface Model { /** Gets or sets a value that indicates to define the number of sheets to be created at the initial load. * @Default {1} */ - sheetCount?: Number; + sheetCount?: number; /** Gets or sets an object that indicates to customize the sheet behavior in Spreadsheet. */ - sheets?: Array; + sheets?: Sheet[]; /** Gets or sets a value that indicates whether to show or hide pager in the Spreadsheet. * @Default {true} @@ -37267,7 +39475,7 @@ export interface Model { /** This is used to set the number of undo-redo steps in the Spreadsheet. * @Default {20} */ - undoRedoStep?: Number; + undoRedoStep?: number; /** Define the username for the Spreadsheet which is displayed in comment. * @Default {User Name} @@ -37275,112 +39483,118 @@ export interface Model { userName?: string; /** Triggered for every action before its starts. */ - actionBegin? (e: ActionBeginEventArgs): void; + actionBegin?(e: ActionBeginEventArgs): void; /** Triggered for every action complete. */ - actionComplete? (e: ActionCompleteEventArgs): void; + actionComplete?(e: ActionCompleteEventArgs): void; /** Triggered when the auto fill operation begins. */ - autoFillBegin? (e: AutoFillBeginEventArgs): void; + autoFillBegin?(e: AutoFillBeginEventArgs): void; /** Triggered when the auto fill operation completes. */ - autoFillComplete? (e: AutoFillCompleteEventArgs): void; + autoFillComplete?(e: AutoFillCompleteEventArgs): void; /** Triggered before the batch save. */ - beforeBatchSave? (e: BeforeBatchSaveEventArgs): void; + beforeBatchSave?(e: BeforeBatchSaveEventArgs): void; /** Triggered before the cells to be formatted. */ - beforeCellFormat? (e: BeforeCellFormatEventArgs): void; + beforeCellFormat?(e: BeforeCellFormatEventArgs): void; /** Triggered before the cell selection. */ - beforeCellSelect? (e: BeforeCellSelectEventArgs): void; + beforeCellSelect?(e: BeforeCellSelectEventArgs): void; /** Triggered before the selected cells are dropped. */ - beforeDrop? (e: BeforeDropEventArgs): void; + beforeDrop?(e: BeforeDropEventArgs): void; /** Triggered while start to edit the comment. */ - beforeEditComment? (e: BeforeEditCommentEventArgs): void; + beforeEditComment?(e: BeforeEditCommentEventArgs): void; /** Triggered before the contextmenu is open. */ - beforeOpen? (e: BeforeOpenEventArgs): void; + beforeOpen?(e: BeforeOpenEventArgs): void; /** Triggered before the activation panel is open. */ - beforePanelOpen? (e: BeforePanelOpenEventArgs): void; + beforePanelOpen?(e: BeforePanelOpenEventArgs): void; /** Triggered when click on sheet cell. */ - cellClick? (e: CellClickEventArgs): void; + cellClick?(e: CellClickEventArgs): void; /** Triggered when the cell is edited. */ - cellEdit? (e: CellEditEventArgs): void; + cellEdit?(e: CellEditEventArgs): void; /** Triggered while cell is formatting. */ - cellFormatting? (e: CellFormattingEventArgs): void; + cellFormatting?(e: CellFormattingEventArgs): void; /** Triggered when mouse hover on cell in sheets. */ - cellHover? (e: CellHoverEventArgs): void; + cellHover?(e: CellHoverEventArgs): void; /** Triggered when save the edited cell. */ - cellSave? (e: CellSaveEventArgs): void; + cellSave?(e: CellSaveEventArgs): void; /** Triggered when the cell is selected. */ - cellSelected? (e: CellSelectedEventArgs): void; + cellSelected?(e: CellSelectedEventArgs): void; /** Triggered when click the contextmenu items. */ - contextMenuClick? (e: ContextMenuClickEventArgs): void; + contextMenuClick?(e: ContextMenuClickEventArgs): void; /** Triggered when the selected cells are being dragged. */ - drag? (e: DragEventArgs): void; + drag?(e: DragEventArgs): void; /** Triggered when you start to drag the picture or chart. */ - dragShape? (e: DragShapeEventArgs): void; + dragShape?(e: DragShapeEventArgs): void; /** Triggered when the selected cells are initiated to drag. */ - dragStart? (e: DragStartEventArgs): void; + dragStart?(e: DragStartEventArgs): void; /** Triggered when the selected cells are dropped. */ - drop? (e: DropEventArgs): void; + drop?(e: DropEventArgs): void; /** Triggered before the range editing starts. */ - editRangeBegin? (e: EditRangeBeginEventArgs): void; + editRangeBegin?(e: EditRangeBeginEventArgs): void; /** Triggered after range editing completes. */ - editRangeComplete? (e: EditRangeCompleteEventArgs): void; + editRangeComplete?(e: EditRangeCompleteEventArgs): void; + + /** Triggered when the key is pressed down. */ + keyDown?(e: KeyDownEventArgs): void; + + /** Triggered when the key is released. */ + keyUp?(e: KeyUpEventArgs): void; /** Triggered before the sheet is loaded. */ - load? (e: LoadEventArgs): void; + load?(e: LoadEventArgs): void; /** Triggered after the sheet is loaded. */ - loadComplete? (e: LoadCompleteEventArgs): void; + loadComplete?(e: LoadCompleteEventArgs): void; /** Triggered every click of the menu item. */ - menuClick? (e: MenuClickEventArgs): void; + menuClick?(e: MenuClickEventArgs): void; /** Triggered when a file is imported. */ - onImport? (e: OnImportEventArgs): void; + onImport?(e: OnImportEventArgs): void; /** Triggered when import sheet is failed to open. */ - openFailure? (e: OpenFailureEventArgs): void; + openFailure?(e: OpenFailureEventArgs): void; /** Triggered when pager item is clicked in the Spreadsheet. */ - pagerClick? (e: PagerClickEventArgs): void; + pagerClick?(e: PagerClickEventArgs): void; /** Triggered when you start resizing the chart, picture, row and column. */ - resizeStart? (e: ResizeStartEventArgs): void; + resizeStart?(e: ResizeStartEventArgs): void; /** Triggered after end of resizing the chart, picture, row and column. */ - resizeEnd? (e: ResizeEndEventArgs): void; + resizeEnd?(e: ResizeEndEventArgs): void; /** Triggered when click on the ribbon. */ - ribbonClick? (e: RibbonClickEventArgs): void; + ribbonClick?(e: RibbonClickEventArgs): void; /** Triggered when the chart series rendering. */ - seriesRendering? (e: SeriesRenderingEventArgs): void; + seriesRendering?(e: SeriesRenderingEventArgs): void; /** Triggered when click the ribbon tab. */ - tabClick? (e: TabClickEventArgs): void; + tabClick?(e: TabClickEventArgs): void; /** Triggered when select the ribbon tab. */ - tabSelect? (e: TabSelectEventArgs): void; + tabSelect?(e: TabSelectEventArgs): void; } export interface ActionBeginEventArgs { @@ -37399,7 +39613,7 @@ export interface ActionBeginEventArgs { /** Returns the cell range. */ - range?: Array; + range?: any[]; /** Returns the action format. */ @@ -37434,7 +39648,7 @@ export interface ActionCompleteEventArgs { /** Returns the applied cell format object. */ - selectedCell?: Array|any; + selectedCell?: any[]|any; /** Returns the sheet index. */ @@ -37457,7 +39671,7 @@ export interface AutoFillBeginEventArgs { /** Returns auto fill begin cell range. */ - dataRange?: Array; + dataRange?: any[]; /** Returns which direction drag the auto fill. */ @@ -37465,7 +39679,7 @@ export interface AutoFillBeginEventArgs { /** Returns fill cells range. */ - fillRange?: Array; + fillRange?: any[]; /** Returns the auto fill type. */ @@ -37492,7 +39706,7 @@ export interface AutoFillCompleteEventArgs { /** Returns auto fill begin cell range. */ - dataRange?: Array; + dataRange?: any[]; /** Returns which direction to drag the auto fill. */ @@ -37500,7 +39714,7 @@ export interface AutoFillCompleteEventArgs { /** Returns fill cells range. */ - fillRange?: Array; + fillRange?: any[]; /** Returns the auto fill type. */ @@ -37550,7 +39764,7 @@ export interface BeforeCellFormatEventArgs { /** Returns the selected cells. */ - cells?: Array|any; + cells?: any[]|any; /** Returns the Spreadsheet model. */ @@ -37569,11 +39783,11 @@ export interface BeforeCellSelectEventArgs { /** Returns the previous cell range. */ - prevRange?: Array; + prevRange?: any[]; /** Returns the current cell range. */ - currRange?: Array; + currRange?: any[]; /** Returns the Spreadsheet model. */ @@ -37879,7 +40093,7 @@ export interface CellSelectedEventArgs { /** Returns the selected range. */ - selectedRange?: Array; + selectedRange?: any[]; /** Returns the target element. */ @@ -38099,6 +40313,76 @@ export interface EditRangeCompleteEventArgs { cancel?: boolean; } +export interface KeyDownEventArgs { + + /** Returns the sheet index. + */ + sheetIndex?: number; + + /** Returns the Spreadsheet model. + */ + model?: ej.Spreadsheet.Model; + + /** Returns the boolean value. + */ + isCommentEdit?: boolean; + + /** Returns the boolean value. + */ + isEdit?: boolean; + + /** Returns the boolean value. + */ + isSheetRename?: boolean; + + /** Returns the target element. + */ + target?: HTMLElement; + + /** Returns the name of the event. + */ + type?: string; + + /** Returns the cancel option value. + */ + cancel?: boolean; +} + +export interface KeyUpEventArgs { + + /** Returns the sheet index. + */ + sheetIndex?: number; + + /** Returns the Spreadsheet model. + */ + model?: ej.Spreadsheet.Model; + + /** Returns the boolean value. + */ + isCommentEdit?: boolean; + + /** Returns the boolean value. + */ + isEdit?: boolean; + + /** Returns the boolean value. + */ + isSheetRename?: boolean; + + /** Returns the target element. + */ + target?: HTMLElement; + + /** Returns the name of the event. + */ + type?: string; + + /** Returns the cancel option value. + */ + cancel?: boolean; +} + export interface LoadEventArgs { /** Returns the name of the event. @@ -38457,12 +40741,12 @@ export interface ChartSettings { /** Gets or sets a value that defines the chart height in Spreadsheet. * @Default {220} */ - height?: Number; + height?: number; /** Gets or sets a value that defines the chart width in the Spreadsheet. * @Default {440} */ - width?: Number; + width?: number; } export interface ExportSettings { @@ -38541,12 +40825,12 @@ export interface PictureSettings { /** Gets or sets a value that indicates to define height to picture in the Spreadsheet. * @Default {220} */ - height?: Number; + height?: number; /** Gets or sets a value that indicates to define width to picture in the Spreadsheet. * @Default {440} */ - width?: Number; + width?: number; } export interface PrintSettings { @@ -38577,7 +40861,7 @@ export interface RibbonSettingsApplicationTabMenuSettings { /** Specifies the data source to append in application tab. * @Default {[]} */ - dataSource?: Array; + dataSource?: any[]; } export interface RibbonSettingsApplicationTab { @@ -38619,7 +40903,7 @@ export interface ScrollSettings { /** Gets or sets the value that indicates to define the height of spreadsheet. * @Default {100%} */ - height?: Number|string; + height?: number|string; /** Gets or sets the value that indicates whether to enable or disable responsive mode in the Spreadsheet. * @Default {true} @@ -38634,7 +40918,7 @@ export interface ScrollSettings { /** Gets or sets the value that indicates to define the height of the spreadsheet. * @Default {100%} */ - width?: Number|string; + width?: number|string; } export interface SelectionSettings { @@ -38646,7 +40930,7 @@ export interface SelectionSettings { /** Gets or sets a value that indicates to define animation time while selection in the Spreadsheet. * @Default {0.001} */ - animationTime?: Number; + animationTime?: number; /** Gets or sets a value that indicates to enable or disable animation while selection. * @Default {false} @@ -38692,7 +40976,7 @@ export interface SheetsCFormatRule { /** Specifies the inputs for conditional formatting in Spreadsheet. * @Default {[]} */ - inputs?: Array; + inputs?: any[]; /** Specifies the range for conditional formatting in Spreadsheet. */ @@ -38745,6 +41029,20 @@ export interface SheetsRowsCellsComment { export interface SheetsRowsCellsFormat { + /** Specifies the number of decimal places for the given input. + * @Default {2} + */ + decimalPlaces?: number; + + /** Specifies the string format for the given input. + */ + formatStr?: string; + + /** Specifies the thousand separator for the given input. + * @Default {false} + */ + thousandSeparator?: boolean; + /** Specifies the type of the format in Spreadsheet. */ type?: string; @@ -38763,7 +41061,7 @@ export interface SheetsRowsCellsHyperlink { /** Specifies the sheet index to which the cell is referred. * @Default {1} */ - sheetIndex?: Number; + sheetIndex?: number; } export interface SheetsRowsCellsStyle { @@ -38801,7 +41099,12 @@ export interface SheetsRowsCell { /** Specifies the index of a cell in Spreadsheet. * @Default {0} */ - index?: Number; + index?: number; + + /** Specifies whether to lock or unlock a particular cell. + * @Default {false} + */ + isLocked?: boolean; /** Specifies the styles of a cell in Spreadsheet. * @Default {null} @@ -38818,17 +41121,17 @@ export interface SheetsRow { /** Gets or sets the height of a row in Spreadsheet. * @Default {20} */ - height?: Number; + height?: number; /** Specifies the cells of a row in Spreadsheet. * @Default {[]} */ - cells?: Array; + cells?: SheetsRowsCell[]; /** Gets or sets the index of a row in Spreadsheet. * @Default {0} */ - index?: Number; + index?: number; } export interface Sheet { @@ -38836,22 +41139,22 @@ export interface Sheet { /** Specifies the border for the cell in the Spreadsheet. * @Default {[]} */ - border?: Array; + border?: SheetsBorder[]; /** Specifies the conditional formatting for the range of cell in Spreadsheet. * @Default {[]} */ - cFormatRule?: Array; + cFormatRule?: SheetsCFormatRule[]; /** Gets or sets a value that indicates to define column count in the Spreadsheet. * @Default {21} */ - colCount?: Number; + colCount?: number; /** Gets or sets a value that indicates to define column width in the Spreadsheet. * @Default {64} */ - columnWidth?: Number; + columnWidth?: number; /** Gets or sets the data to render the Spreadsheet. * @Default {null} @@ -38871,17 +41174,17 @@ export interface Sheet { /** To hide the specified columns in Spreadsheet. * @Default {[]} */ - hideColumns?: Array; + hideColumns?: any[]; /** To hide the specified rows in Spreadsheet. * @Default {[]} */ - hideRows?: Array; + hideRows?: any[]; /** To merge specified ranges in Spreadsheet. * @Default {[]} */ - mergeCells?: Array; + mergeCells?: any[]; /** Specifies the primary key for the datasource in Spreadsheet. */ @@ -38895,17 +41198,17 @@ export interface Sheet { /** Specifies single range or multiple range settings for a sheet in Spreadsheet. * @Default {[]} */ - rangeSettings?: Array; + rangeSettings?: SheetsRangeSetting[]; /** Gets or sets a value that indicates to define row count in the Spreadsheet. * @Default {20} */ - rowCount?: Number; + rowCount?: number; /** Specifies the rows for a sheet in Spreadsheet. * @Default {[]} */ - rows?: Array; + rows?: SheetsRow[]; /** Gets or sets a value that indicates whether to show or hide grid lines in the Spreadsheet. * @Default {true} @@ -38928,7 +41231,7 @@ export interface Sheet { startCell?: string; } -enum AutoFillOptions{ +enum AutoFillOptions { ///Specifies the CopyCells property in AutoFillOptions. CopyCells, @@ -38947,7 +41250,7 @@ enum AutoFillOptions{ } -enum scrollMode{ +enum scrollMode { ///To enable Infinite scroll mode for Spreadsheet. Infinite, @@ -38957,7 +41260,7 @@ enum scrollMode{ } -enum SelectionType{ +enum SelectionType { ///To select only Column in Spreadsheet. Column, @@ -38970,7 +41273,7 @@ enum SelectionType{ } -enum SelectionUnit{ +enum SelectionUnit { ///To enable Single selection in Spreadsheet Single, @@ -38983,7 +41286,7 @@ enum SelectionUnit{ } -enum BorderType{ +enum BorderType { ///To apply top border for the given range of cell. Top, @@ -39017,7 +41320,7 @@ enum BorderType{ } -enum CFormatRule{ +enum CFormatRule { ///To identify greater than values in the given range of cells. GreaterThan, @@ -39039,7 +41342,7 @@ enum CFormatRule{ } -enum CFormatHighlightColor{ +enum CFormatHighlightColor { ///Highlights red with dark red text color. RedFillwithDarkRedText, @@ -39058,7 +41361,7 @@ enum CFormatHighlightColor{ } -enum ChartProperties{ +enum ChartProperties { ///Specifies to make the data label center of the chart. DataLabelCenter, @@ -39131,56 +41434,61 @@ enum ChartProperties{ class PdfViewer extends ej.Widget { static fn: PdfViewer; - constructor(element: JQuery, options?: PdfViewer.Model); - constructor(element: Element, options?: PdfViewer.Model); + constructor(element: JQuery | Element, options?: PdfViewer.Model); static Locale: any; - model:PdfViewer.Model; - defaults:PdfViewer.Model; + model: PdfViewer.Model; + defaults: PdfViewer.Model; /** Loads the document with the filename and displays it in PDF viewer. + * @param {string} File name to be loaded * @returns {void} */ - load(): void; + load(fileName: string): void; - /** Shows/hides the tool bar in the PDF viewer. + /** Shows/hides the toolbar in the PDF viewer. + * @param {boolean} shows/hides the toolbar * @returns {void} */ - showToolbar(): void; + showToolbar(show: boolean): void; /** Prints the PDF document. * @returns {void} */ print(): void; - /** Abort the printing function and restores the PDF Viewer. + /** Abort the printing function and restores the PDF viewer. * @returns {void} */ abortPrint(): void; - /** Shows/hides the print icon in the tool bar. + /** Shows/hides the print icon in the toolbar. + * @param {boolean} shows/hides print button in the toolbar * @returns {void} */ - showPrintTools(): void; + showPrintTools(show: boolean): void; /** Downloads the PDF document being loaded in the ejPdfViewer control. * @returns {void} */ download(): void; - /** Shows/hides the download tool in the tool bar. + /** Shows/hides the download tool in the toolbar. + * @param {boolean} shows/hides download button in the toolbar * @returns {void} */ - showDownloadTool(): void; + showDownloadTool(show: boolean): void; /** Shows/hides the page navigation tools in the toolbar + * @param {boolean} shows/hides navigation tools in the toolbar * @returns {void} */ - showPageNavigationTools(): void; + showPageNavigationTools(show: boolean): void; /** Navigates to the specific page in the PDF document. If the page is not available for the given pageNumber, PDF viewer retains the existing page in view. + * @param {number} navigates to the page number in the PDF document * @returns {void} */ - goToPage(): void; + goToPage(pageNumber: number): void; /** Navigates to the last page of the PDF document. * @returns {void} @@ -39202,10 +41510,11 @@ class PdfViewer extends ej.Widget { */ goToPreviousPage(): void; - /** Shows/hides the zoom tools in the tool bar. + /** Shows/hides the zoom tools in the toolbar. + * @param {boolean} shows/hides zoom tools in the toolbar * @returns {void} */ - showMagnificationTools(): void; + showMagnificationTools(show: boolean): void; /** Scales the page to fit the page in the container in the control. * @returns {void} @@ -39228,41 +41537,51 @@ class PdfViewer extends ej.Widget { zoomOut(): void; /** Scales the page to the specified percentage ranging from 50 to 400. If the given zoomValue is less than 50 or greater than 400; the PDF viewer scales the page to 50 and 400 respectively. + * @param {number} zoom value for scaling the pages in the PDF Viewer * @returns {void} */ - zoomTo(): void; + zoomTo(zoomValue: number): void; + + /** Unloads the PDF document being displayed in the PDF viewer. + * @returns {void} + */ + unload(): void; } -export module PdfViewer{ +export namespace PdfViewer { export interface Model { /** Specifies the locale information of the PDF viewer. */ - locale?: String; + locale?: string; /** Specifies the toolbar settings. */ toolbarSettings?: ToolbarSettings; - /** Shows or hides the grouped items in the toolbar with the help of enum ej.PdfViewer.ToolbarItems + /** Specifies the name of the action method in the server. */ - toolbarItems?: ej.PdfViewer.ToolbarItems|string; + serverActionSettings?: ServerActionSettings; /** Sets the PDF Web API service URL */ - serviceUrl?: String; + serviceUrl?: string; + + /** Sets the PDF document path for initial loading. + */ + documentPath?: string; /** Gets the total number of pages in PDF document. */ - pageCount?: Number; + pageCount?: number; - /** Gets the number of the page being displayed in the PDF Viewer. + /** Gets the number of the page being displayed in the PDF viewer. */ - currentPageNumber?: Number; + currentPageNumber?: number; /** Gets the current zoom percentage of the PDF document in viewer. */ - zoomPercentage?: Number; + zoomPercentage?: number; /** Specifies the location of the supporting PDF service */ @@ -39272,52 +41591,74 @@ export interface Model { */ hyperlinkOpenState?: ej.PdfViewer.LinkTarget|string; - /** Enables or disables the responsive support for PDF Viewer control during the window resizing time. + /** Enables or disables the hyperlinks in PDF document. */ - isResponsive?: Boolean; + enableHyperlink?: boolean; + + /** Enables or disables the text selection in PDF document. + */ + enableTextSelection?: boolean; + + /** Enables or disables the responsiveness of the PDF viewer control during the window resize. + */ + isResponsive?: boolean; + + /** Checks whether the PDF document is edited. + */ + isDocumentEdited?: boolean; + + /** Enables or disables the buffering of the PDF pages in the client side. + */ + allowClientBuffering?: boolean; /** Gets the name of the PDF document which loaded in the ejPdfViewer control for downloading. */ fileName?: string; /** Triggers when the PDF document gets loaded and is ready to view in the Control. */ - documentLoad? (e: DocumentLoadEventArgs): void; + documentLoad?(e: DocumentLoadEventArgs): void; /** Triggers when there is change in current page number. */ - pageChange? (e: PageChangeEventArgs): void; + pageChange?(e: PageChangeEventArgs): void; /** Triggers when there is change in the magnification value. */ - zoomChange? (e: ZoomChangeEventArgs): void; + zoomChange?(e: ZoomChangeEventArgs): void; /** Triggers when hyperlink in the PDF Document is clicked */ - hyperlinkClick? (e: HyperlinkClickEventArgs): void; + hyperlinkClick?(e: HyperlinkClickEventArgs): void; /** Triggers before the printing starts. */ - beforePrint? (e: BeforePrintEventArgs): void; + beforePrint?(e: BeforePrintEventArgs): void; /** Triggers after the printing is completed. */ - afterPrint? (e: AfterPrintEventArgs): void; + afterPrint?(e: AfterPrintEventArgs): void; /** Triggers when the mouse click is performed over the page of the PDF document. */ - pageClick? (e: PageClickEventArgs): void; + pageClick?(e: PageClickEventArgs): void; + + /** Triggers when the client buffering process starts. */ + bufferStart?(e: BufferStartEventArgs): void; + + /** Triggers when the client buffering process ends. */ + bufferEnd?(e: BufferEndEventArgs): void; /** Triggers when PDF viewer control is destroyed successfully. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; } export interface DocumentLoadEventArgs { /** true, if the event should be canceled; otherwise, false. */ - Cancel?: boolean; + cancel?: boolean; /** Returns the PDF viewer model */ - Model?: any; + model?: any; /** Returns the name of the event */ - Type?: string; + type?: string; } export interface PageChangeEventArgs { @@ -39434,6 +41775,44 @@ export interface PageClickEventArgs { offsetY?: number; } +export interface BufferStartEventArgs { + + /** True, if the event should be canceled; otherwise, false. + */ + cancel?: boolean; + + /** Returns the PDF viewer model + */ + model?: any; + + /** Returns the name of the event + */ + type?: string; + + /** Specifies the state of the buffering + */ + isBuffering?: boolean; +} + +export interface BufferEndEventArgs { + + /** True, if the event should be canceled; otherwise, false. + */ + cancel?: boolean; + + /** Returns the PDF viewer model + */ + model?: any; + + /** Returns the name of the event + */ + type?: string; + + /** Specifies the state of the buffering + */ + isBuffering?: boolean; +} + export interface DestroyEventArgs { /** True, if the event should be canceled; otherwise, false. @@ -39453,10 +41832,33 @@ export interface ToolbarSettings { /** Shows or hides the tooltip of the toolbar items. */ - showToolTip?: Boolean; + showToolTip?: boolean; + + /** Shows or hides the grouped items in the toolbar with the help of enum ej.PdfViewer.ToolbarItems + */ + toolbarItem?: ej.PdfViewer.ToolbarItems|string; } -enum ToolbarItems{ +export interface ServerActionSettings { + + /** Specifies the name of the action method used for loading the PDF document. + */ + load?: string; + + /** Specifies the name of the action method used for uploading the PDF document to the PDF viewer control. + */ + fileUpload?: string; + + /** Specifies the name of the action method used for printing the PDF document in the PDF viewer control. + */ + print?: string; + + /** Specifies the name of the action method used for downloading the PDF document from the PDF viewer control. + */ + download?: string; +} + +enum ToolbarItems { ///Shows only magnification tools in the toolbar. MagnificationTools, @@ -39475,7 +41877,7 @@ enum ToolbarItems{ } -enum PdfService{ +enum PdfService { ///Denotes that the service is located in the local project Local, @@ -39485,7 +41887,7 @@ enum PdfService{ } -enum LinkTarget{ +enum LinkTarget { ///Opens the hyperlink in the same tab of the browser. Default, @@ -39501,11 +41903,10 @@ enum LinkTarget{ class SpellCheck extends ej.Widget { static fn: SpellCheck; - constructor(element: JQuery, options?: SpellCheck.Model); - constructor(element: Element, options?: SpellCheck.Model); + constructor(element: JQuery | Element, options?: SpellCheck.Model); static Locale: any; - model:SpellCheck.Model; - defaults:SpellCheck.Model; + model: SpellCheck.Model; + defaults: SpellCheck.Model; /** Open the dialog to correct the spelling of the target content. * @returns {void} @@ -39562,7 +41963,7 @@ class SpellCheck extends ej.Widget { */ addToDictionary(customWord: string): any; } -export module SpellCheck{ +export namespace SpellCheck { export interface Model { @@ -39588,7 +41989,7 @@ export interface Model { /** To ignore the words from the error word consideration. * @Default {[]} */ - ignoreWords?: Array; + ignoreWords?: any[]; /** Holds all options related to the context menu settings of SpellCheck. */ @@ -39598,38 +41999,50 @@ export interface Model { */ ignoreSettings?: IgnoreSettings; + /** When set to true, allows the spellcheck to render based upon screen size. + * @Default {true} + */ + isResponsive?: boolean; + + /** It allows to spell check the multiple target HTML element's texts and correct its error words. + * @Default {null} + */ + controlsToValidate?: string; + /** Triggers on the success of AJAX call request. */ - actionSuccess? (e: ActionSuccessEventArgs): void; + actionSuccess?(e: ActionSuccessEventArgs): void; /** Triggers on the AJAX call request beginning. */ - actionBegin? (e: ActionBeginEventArgs): void; + actionBegin?(e: ActionBeginEventArgs): void; /** Triggers when the AJAX call request failure. */ - actionFailure? (e: ActionFailureEventArgs): void; + actionFailure?(e: ActionFailureEventArgs): void; /** Triggers when the dialog mode spell check starting. */ - start? (e: StartEventArgs): void; + start?(e: StartEventArgs): void; /** Triggers when the spell check operations completed through dialog mode. */ - complete? (e: CompleteEventArgs): void; + complete?(e: CompleteEventArgs): void; /** Triggers before context menu opening. */ - contextOpen? (e: ContextOpenEventArgs): void; + contextOpen?(e: ContextOpenEventArgs): void; /** Triggers when the context menu item clicked. */ - contextClick? (e: ContextClickEventArgs): void; + contextClick?(e: ContextClickEventArgs): void; /** Triggers before the spell check dialog opens. */ - dialogBeforeOpen? (e: DialogBeforeOpenEventArgs): void; - + dialogBeforeOpen?(e: DialogBeforeOpenEventArgs): void; /** Triggers after the spell check dialog opens. */ - dialogOpen? (e: DialogOpenEventArgs): void; + dialogOpen?(e: DialogOpenEventArgs): void; /** Triggers when the spell check dialog closed. */ - dialogClose? (e: DialogCloseEventArgs): void; + dialogClose?(e: DialogCloseEventArgs): void; /** Triggers when the spell check control performing the spell check operations such as ignore, ignoreAll, change, changeAll and addToDictionary. */ - validating? (e: ValidatingEventArgs): void; + validating?(e: ValidatingEventArgs): void; + + /** Triggers before loading the target HTML element text into the dialog sentence area. */ + targetUpdating?(e: TargetUpdatingEventArgs): void; } export interface ActionSuccessEventArgs { @@ -39925,6 +42338,33 @@ export interface ValidatingEventArgs { customWord?: string; } +export interface TargetUpdatingEventArgs { + + /** Returns the previous target element value. + */ + previousElement?: any; + + /** Returns the current target element value. + */ + currentElement?: any; + + /** Returns the target html value. + */ + targetHtml?: string; + + /** Returns the cancel option value. + */ + cancel?: boolean; + + /** Returns the SpellCheck model. + */ + model?: ej.SpellCheck.Model; + + /** Returns the name of the event. + */ + type?: string; +} + export interface DictionarySettings { /** The dictionaryUrl option accepts string, which is the method path to find the error words and get the suggestions to correct the errors. @@ -39943,10 +42383,11 @@ export interface ContextMenuSettings { */ enable?: boolean; - /** Contains all the default context menu options that are applicable for SpellCheck. It also supports adding custom menu items. All the SpellCheck related context menu items are grouped under this menu collection. + /** Contains all the default context menu options that are applicable for SpellCheck. It also supports adding custom menu items. + * All the SpellCheck related context menu items are grouped under this menu collection. * @Default {{% highlight javascript %}[{ id: IgnoreAll, text: Ignore All },{ id: AddToDictionary, text: Add To Dictionary }]{% endhighlight %}} */ - menuItems?: Array; + menuItems?: any[]; } export interface IgnoreSettings { @@ -39983,18 +42424,174 @@ export interface IgnoreSettings { } } +class DocumentEditor extends ej.Widget { + static fn: DocumentEditor; + constructor(element: JQuery | Element, options?: DocumentEditor.Model); + static Locale: any; + model: DocumentEditor.Model; + defaults: DocumentEditor.Model; + + /** Loads the document from specified path using web API provided by importUrl. + * @param {string} Specifies the file path. + * @returns {void} + */ + load(path: string): void; + + /** Gets the page number of current selection in the document. + * @returns {number} + */ + getCurrentPageNumber(): number; + + /** Gets the total number of pages in the document. + * @returns {number} + */ + getPageCount(): number; + + /** Gets the text of current selection in the document. + * @returns {string} + */ + getSelectedText(): string; + + /** Gets the current zoom factor value of the document editor. + * @returns {number} + */ + getZoomFactor(): number; + + /** Scales the document editor with the specified zoom factor. The range of zoom factor should be 0.10 to 5.00 (10 - 500 %). + * @param {number} Specifies the factor for zooming. + * @returns {void} + */ + setZoomFactor(factor: number): void; + + /** Prints the document content as page by page. + * @returns {void} + */ + print(): void; + + /** Finds the first occurrence of specified text from current selection and highlights the result. If the document end is reached, find operation will occur from the document start position. + * @param {string} Specifies the text to search in a document. + * @returns {void} + */ + find(text: string): void; } -declare module ej.datavisualization { +export namespace DocumentEditor { + +export interface Model { + + /** Gets or sets an object that indicates initialization of importing and exporting documents in document editor. + */ + importExportSettings?: ImportExportSettings; + + /** Triggers when the document changes. */ + onDocumentChange?(e: OnDocumentChangeEventArgs): void; + + /** Triggers when the selection changes. */ + onSelectionChange?(e: OnSelectionChangeEventArgs): void; + + /** Triggers when the zoom factor changes. */ + onZoomFactorChange?(e: OnZoomFactorChangeEventArgs): void; + + /** Triggers when the hyperlink is clicked. */ + onRequestNavigate?(e: OnRequestNavigateEventArgs): void; +} + +export interface OnDocumentChangeEventArgs { + + /** True, if the event should be canceled; otherwise, false. + */ + cancel?: boolean; + + /** Returns the document editor model. + */ + model?: any; + + /** Returns the name of the event. + */ + type?: string; +} + +export interface OnSelectionChangeEventArgs { + + /** True, if the event should be canceled; otherwise, false. + */ + cancel?: boolean; + + /** Returns the document editor model. + */ + model?: any; + + /** Returns the name of the event. + */ + type?: string; +} + +export interface OnZoomFactorChangeEventArgs { + + /** True, if the event should be canceled; otherwise, false. + */ + cancel?: boolean; + + /** Returns the document editor model. + */ + model?: any; + + /** Returns the name of the event. + */ + type?: string; +} + +export interface OnRequestNavigateEventArgs { + + /** true, if the event should be canceled; otherwise, false. + */ + cancel?: boolean; + + /** Returns the document editor model. + */ + model?: any; + + /** Returns the link type and navigation link. + */ + hyperlink?: any; + + /** Returns the name of the event. + */ + type?: string; +} + +export interface ImportExportSettings { + + /** Gets or sets URL of Web API that should be used to parse the document while loading. + */ + importUrl?: string; +} +} + +} +declare namespace ej.datavisualization { class SymbolPalette extends ej.Widget { static fn: SymbolPalette; - constructor(element: JQuery, options?: SymbolPalette.Model); - constructor(element: Element, options?: SymbolPalette.Model); + constructor(element: JQuery | Element, options?: SymbolPalette.Model); static Locale: any; - model:SymbolPalette.Model; - defaults:SymbolPalette.Model; + model: SymbolPalette.Model; + defaults: SymbolPalette.Model; + + /** Add items to Palettes at runtime + * @param {string} name of the Palette + * @param {any} JSON for the new items to added in Palette + * @returns {void} + */ + addPaletteItem(paletteName: string, node: any): void; + + /** Remove items to Palettes at runtime + * @param {string} name of the Palette + * @param {any} JSON for the new node to removed in Palette + * @returns {void} + */ + removePaletteItem(paletteName: string, node: any): void; } -export module SymbolPalette{ +export namespace SymbolPalette { export interface Model { @@ -40040,7 +42637,7 @@ export interface Model { /** An array of JSON objects, where each object represents a node/connector * @Default {[]} */ - palettes?: Array; + palettes?: Palette[]; /** Defines the preview height of the symbols * @Default {100} @@ -40068,7 +42665,7 @@ export interface Model { width?: number; /** Triggers when a palette item is selected or unselected */ - selectionChange? (e: SelectionChangeEventArgs): void; + selectionChange?(e: SelectionChangeEventArgs): void; } export interface SelectionChangeEventArgs { @@ -40110,17 +42707,16 @@ export interface Palette { /** Defines the palette items * @Default {[]} */ - items?: Array; + items?: any[]; } } class LinearGauge extends ej.Widget { static fn: LinearGauge; - constructor(element: JQuery, options?: LinearGauge.Model); - constructor(element: Element, options?: LinearGauge.Model); + constructor(element: JQuery | Element, options?: LinearGauge.Model); static Locale: any; - model:LinearGauge.Model; - defaults:LinearGauge.Model; + model: LinearGauge.Model; + defaults: LinearGauge.Model; /** destroy the linear gauge all events bound using this._on will be unbind automatically and bring the control to pre-init state. * @returns {void} @@ -40537,7 +43133,7 @@ class LinearGauge extends ej.Widget { */ setTickYDistanceFromScale(): void; } -export module LinearGauge{ +export namespace LinearGauge { export interface Model { @@ -40624,7 +43220,7 @@ export interface Model { /** Specifies the scales * @Default {null} */ - scales?: Array; + scales?: Scale[]; /** Specifies the theme for Linear gauge. See LinearGauge.Themes * @Default {flatlight} @@ -40652,43 +43248,43 @@ export interface Model { width?: number; /** Triggers while the bar pointer are being drawn on the gauge. */ - drawBarPointers? (e: DrawBarPointersEventArgs): void; + drawBarPointers?(e: DrawBarPointersEventArgs): void; /** Triggers while the customLabel are being drawn on the gauge. */ - drawCustomLabel? (e: DrawCustomLabelEventArgs): void; + drawCustomLabel?(e: DrawCustomLabelEventArgs): void; /** Triggers while the Indicator are being drawn on the gauge. */ - drawIndicators? (e: DrawIndicatorsEventArgs): void; + drawIndicators?(e: DrawIndicatorsEventArgs): void; /** Triggers while the label are being drawn on the gauge. */ - drawLabels? (e: DrawLabelsEventArgs): void; + drawLabels?(e: DrawLabelsEventArgs): void; /** Triggers while the marker are being drawn on the gauge. */ - drawMarkerPointers? (e: DrawMarkerPointersEventArgs): void; + drawMarkerPointers?(e: DrawMarkerPointersEventArgs): void; /** Triggers while the range are being drawn on the gauge. */ - drawRange? (e: DrawRangeEventArgs): void; + drawRange?(e: DrawRangeEventArgs): void; /** Triggers while the ticks are being drawn on the gauge. */ - drawTicks? (e: DrawTicksEventArgs): void; + drawTicks?(e: DrawTicksEventArgs): void; /** Triggers when the gauge is initialized. */ - init? (e: InitEventArgs): void; + init?(e: InitEventArgs): void; /** Triggers while the gauge start to Load. */ - load? (e: LoadEventArgs): void; + load?(e: LoadEventArgs): void; /** Triggers when the left mouse button is clicked. */ - mouseClick? (e: MouseClickEventArgs): void; + mouseClick?(e: MouseClickEventArgs): void; /** Triggers when clicking and dragging the mouse pointer over the gauge pointer. */ - mouseClickMove? (e: MouseClickMoveEventArgs): void; + mouseClickMove?(e: MouseClickMoveEventArgs): void; /** Triggers when the mouse click is released. */ - mouseClickUp? (e: MouseClickUpEventArgs): void; + mouseClickUp?(e: MouseClickUpEventArgs): void; /** Triggers while the rendering of the gauge completed. */ - renderComplete? (e: RenderCompleteEventArgs): void; + renderComplete?(e: RenderCompleteEventArgs): void; } export interface DrawBarPointersEventArgs { @@ -41556,7 +44152,7 @@ export interface ScalesIndicator { /** Specifies the state ranges in bar indicators * @Default {Array} */ - stateRanges?: Array; + stateRanges?: ScalesIndicatorsStateRange[]; /** Specifies the textLocation in bar indicators * @Default {null} @@ -41868,7 +44464,7 @@ export interface Scale { /** Specifies the scaleBar Gradient of bar pointer * @Default {Array} */ - barPointers?: Array; + barPointers?: ScalesBarPointer[]; /** Specifies the border of the Scale. * @Default {null} @@ -41878,7 +44474,7 @@ export interface Scale { /** Specifies the customLabel * @Default {Array} */ - customLabels?: Array; + customLabels?: ScalesCustomLabel[]; /** Specifies the scale Direction of the Scale. See Directions * @Default {CounterClockwise} @@ -41888,12 +44484,12 @@ export interface Scale { /** Specifies the indicator * @Default {Array} */ - indicators?: Array; + indicators?: ScalesIndicator[]; /** Specifies the labels. * @Default {Array} */ - labels?: Array; + labels?: ScalesLabel[]; /** Specifies the scaleBar Length. * @Default {290} @@ -41908,7 +44504,7 @@ export interface Scale { /** Specifies the markerPointers * @Default {Array} */ - markerPointers?: Array; + markerPointers?: ScalesMarkerPointer[]; /** Specifies the maximum of the Scale. * @Default {null} @@ -41938,7 +44534,7 @@ export interface Scale { /** Specifies the ranges in the tick. * @Default {Array} */ - ranges?: Array; + ranges?: ScalesRange[]; /** Specifies the shadowOffset. * @Default {0} @@ -41983,7 +44579,7 @@ export interface Scale { /** Specifies the ticks in the scale. * @Default {Array} */ - ticks?: Array; + ticks?: ScalesTick[]; /** Specifies the scaleBar type .See ScaleType * @Default {Rectangle} @@ -42014,10 +44610,8 @@ export interface Tooltip { templateID?: string; } } -module LinearGauge -{ -enum OuterCustomLabelPosition -{ +namespace LinearGauge { +enum OuterCustomLabelPosition { //string Left, //string @@ -42028,10 +44622,8 @@ Top, Bottom, } } -module LinearGauge -{ -enum FontStyle -{ +namespace LinearGauge { +enum FontStyle { //string Bold, //string @@ -42044,20 +44636,16 @@ Strikeout, Underline, } } -module LinearGauge -{ -enum Direction -{ +namespace LinearGauge { +enum Direction { //string Clockwise, //string CounterClockwise, } } -module LinearGauge -{ -enum IndicatorTypes -{ +namespace LinearGauge { +enum IndicatorTypes { //string Rectangle, //string @@ -42068,10 +44656,8 @@ RoundedRectangle, Text, } } -module LinearGauge -{ -enum PointerPlacement -{ +namespace LinearGauge { +enum PointerPlacement { //string Near, //string @@ -42080,30 +44666,24 @@ Far, Center, } } -module LinearGauge -{ -enum ScaleType -{ +namespace LinearGauge { +enum ScaleType { //string Major, //string Minor, } } -module LinearGauge -{ -enum UnitTextPlacement -{ +namespace LinearGauge { +enum UnitTextPlacement { //string Back, //string From, } } -module LinearGauge -{ -enum MarkerType -{ +namespace LinearGauge { +enum MarkerType { //string Rectangle, //string @@ -42130,20 +44710,16 @@ Trapezoid, RoundedRectangle, } } -module LinearGauge -{ -enum TicksType -{ +namespace LinearGauge { +enum TicksType { //string Majorinterval, //string Minorinterval, } } -module LinearGauge -{ -enum Themes -{ +namespace LinearGauge { +enum Themes { //string FlatLight, //string @@ -42153,11 +44729,10 @@ FlatDark, class CircularGauge extends ej.Widget { static fn: CircularGauge; - constructor(element: JQuery, options?: CircularGauge.Model); - constructor(element: Element, options?: CircularGauge.Model); + constructor(element: JQuery | Element, options?: CircularGauge.Model); static Locale: any; - model:CircularGauge.Model; - defaults:CircularGauge.Model; + model: CircularGauge.Model; + defaults: CircularGauge.Model; /** destroy the circular gauge widget. all events bound using this._on will be unbind automatically and bring the control to pre-init state. * @returns {void} @@ -42579,7 +45154,7 @@ class CircularGauge extends ej.Widget { */ setTickWidth(): void; } -export module CircularGauge{ +export namespace CircularGauge { export interface Model { @@ -42661,7 +45236,7 @@ export interface Model { /** Specify the pointers, ticks, labels, indicators, ranges of circular gauge * @Default {null} */ - scales?: Array; + scales?: Scale[]; /** Specify the theme of circular gauge. * @Default {flatlight} @@ -42684,40 +45259,40 @@ export interface Model { width?: number; /** Triggers while the custom labels are being drawn on the gauge. */ - drawCustomLabel? (e: DrawCustomLabelEventArgs): void; + drawCustomLabel?(e: DrawCustomLabelEventArgs): void; /** Triggers while the indicators are being started to drawn on the gauge. */ - drawIndicators? (e: DrawIndicatorsEventArgs): void; + drawIndicators?(e: DrawIndicatorsEventArgs): void; /** Triggers while the labels are being drawn on the gauge. */ - drawLabels? (e: DrawLabelsEventArgs): void; + drawLabels?(e: DrawLabelsEventArgs): void; /** Triggers while the pointer cap is being drawn on the gauge. */ - drawPointerCap? (e: DrawPointerCapEventArgs): void; + drawPointerCap?(e: DrawPointerCapEventArgs): void; /** Triggers while the pointers are being drawn on the gauge. */ - drawPointers? (e: DrawPointersEventArgs): void; + drawPointers?(e: DrawPointersEventArgs): void; /** Triggers when the ranges begin to be getting drawn on the gauge. */ - drawRange? (e: DrawRangeEventArgs): void; + drawRange?(e: DrawRangeEventArgs): void; /** Triggers while the ticks are being drawn on the gauge. */ - drawTicks? (e: DrawTicksEventArgs): void; + drawTicks?(e: DrawTicksEventArgs): void; /** Triggers while the gauge start to Load. */ - load? (e: LoadEventArgs): void; + load?(e: LoadEventArgs): void; /** Triggers when the left mouse button is clicked. */ - mouseClick? (e: MouseClickEventArgs): void; + mouseClick?(e: MouseClickEventArgs): void; /** Triggers when clicking and dragging the mouse pointer over the gauge pointer. */ - mouseClickMove? (e: MouseClickMoveEventArgs): void; + mouseClickMove?(e: MouseClickMoveEventArgs): void; /** Triggers when the mouse click is released. */ - mouseClickUp? (e: MouseClickUpEventArgs): void; + mouseClickUp?(e: MouseClickUpEventArgs): void; /** Triggers when the rendering of the gauge is completed. */ - renderComplete? (e: RenderCompleteEventArgs): void; + renderComplete?(e: RenderCompleteEventArgs): void; } export interface DrawCustomLabelEventArgs { @@ -43438,7 +46013,7 @@ export interface ScalesIndicator { /** Specify the various states of circular gauge * @Default {Array} */ - stateRanges?: Array; + stateRanges?: ScalesIndicatorsStateRange[]; /** Specify indicator style of circular gauge. See IndicatorType * @Default {Circle} @@ -43871,17 +46446,17 @@ export interface Scale { /** Specify the custom labels for the scales. * @Default {Array} */ - customLabels?: Array; + customLabels?: ScalesCustomLabel[]; /** Specify representing state of circular gauge * @Default {Array} */ - indicators?: Array; + indicators?: ScalesIndicator[]; /** Specify the text values displayed in a meaningful manner alongside the ticks of circular gauge * @Default {Array} */ - labels?: Array; + labels?: ScalesLabel[]; /** Specify majorIntervalValue of circular gauge * @Default {10} @@ -43916,7 +46491,7 @@ export interface Scale { /** Specify pointers value of circular gauge * @Default {Array} */ - pointers?: Array; + pointers?: ScalesPointer[]; /** Specify scale radius of circular gauge * @Default {170} @@ -43926,7 +46501,7 @@ export interface Scale { /** Specify ranges value of circular gauge * @Default {Array} */ - ranges?: Array; + ranges?: ScalesRange[]; /** Specify shadowOffset value of circular gauge * @Default {0} @@ -43976,7 +46551,7 @@ export interface Scale { /** Specify subGauge of circular gauge * @Default {Array} */ - subGauges?: Array; + subGauges?: ScalesSubGauge[]; /** Specify sweepAngle of circular gauge * @Default {310} @@ -43986,7 +46561,7 @@ export interface Scale { /** Specify ticks of circular gauge * @Default {Array} */ - ticks?: Array; + ticks?: ScalesTick[]; } export interface Tooltip { @@ -44007,20 +46582,16 @@ export interface Tooltip { templateID?: string; } } -module CircularGauge -{ -enum FrameType -{ +namespace CircularGauge { +enum FrameType { //string FullCircle, //string HalfCircle, } } -module CircularGauge -{ -enum gaugePosition -{ +namespace CircularGauge { +enum gaugePosition { //string TopLeft, //string @@ -44041,10 +46612,8 @@ BottomRight, BottomCenter, } } -module CircularGauge -{ -enum CustomLabelPositionType -{ +namespace CircularGauge { +enum CustomLabelPositionType { //string Top, //string @@ -44055,20 +46624,16 @@ Right, Left, } } -module CircularGauge -{ -enum Direction -{ +namespace CircularGauge { +enum Direction { //string Clockwise, //string CounterClockwise, } } -module CircularGauge -{ -enum IndicatorTypes -{ +namespace CircularGauge { +enum IndicatorTypes { //string Rectangle, //string @@ -44081,40 +46646,32 @@ RoundedRectangle, Image, } } -module CircularGauge -{ -enum Placement -{ +namespace CircularGauge { +enum Placement { //string Near, //string Far, } } -module CircularGauge -{ -enum LabelType -{ +namespace CircularGauge { +enum LabelType { //string Major, //string Minor, } } -module CircularGauge -{ -enum UnitTextPlacement -{ +namespace CircularGauge { +enum UnitTextPlacement { //string Back, //string Front, } } -module CircularGauge -{ -enum MarkerType -{ +namespace CircularGauge { +enum MarkerType { //string Rectangle, //string @@ -44141,10 +46698,8 @@ RoundedRectangle, Image, } } -module CircularGauge -{ -enum NeedleType -{ +namespace CircularGauge { +enum NeedleType { //string Triangle, //string @@ -44157,10 +46712,8 @@ Image, Trapezoid, } } -module CircularGauge -{ -enum PointerType -{ +namespace CircularGauge { +enum PointerType { //string Needle, //string @@ -44170,11 +46723,10 @@ Marker, class DigitalGauge extends ej.Widget { static fn: DigitalGauge; - constructor(element: JQuery, options?: DigitalGauge.Model); - constructor(element: Element, options?: DigitalGauge.Model); + constructor(element: JQuery | Element, options?: DigitalGauge.Model); static Locale: any; - model:DigitalGauge.Model; - defaults:DigitalGauge.Model; + model: DigitalGauge.Model; + defaults: DigitalGauge.Model; /** To destroy the digital gauge * @returns {void} @@ -44219,7 +46771,7 @@ class DigitalGauge extends ej.Widget { */ setValue(itemIndex: number, value: string): void; } -export module DigitalGauge{ +export namespace DigitalGauge { export interface Model { @@ -44241,7 +46793,7 @@ export interface Model { /** Specifies the items for the DigitalGauge. * @Default {null} */ - items?: Array; + items?: Item[]; /** Specifies the matrixSegmentData for the DigitalGauge. */ @@ -44267,16 +46819,16 @@ export interface Model { width?: number; /** Triggers when the gauge is initialized. */ - init? (e: InitEventArgs): void; + init?(e: InitEventArgs): void; /** Triggers when the gauge item rendering. */ - itemRendering? (e: ItemRenderingEventArgs): void; + itemRendering?(e: ItemRenderingEventArgs): void; /** Triggers when the gauge is start to load. */ - load? (e: LoadEventArgs): void; + load?(e: LoadEventArgs): void; /** Triggers when the gauge render is completed. */ - renderComplete? (e: RenderCompleteEventArgs): void; + renderComplete?(e: RenderCompleteEventArgs): void; } export interface InitEventArgs { @@ -44555,10 +47107,8 @@ export interface Item { value?: string; } } -module DigitalGauge -{ -enum CharacterType -{ +namespace DigitalGauge { +enum CharacterType { //string SevenSegment, //string @@ -44571,10 +47121,8 @@ EightCrossEightDotMatrix, EightCrossEightSquareMatrix, } } -module DigitalGauge -{ -enum FontStyle -{ +namespace DigitalGauge { +enum FontStyle { //string Normal, //string @@ -44590,14 +47138,14 @@ Strikeout, class Chart extends ej.Widget { static fn: Chart; - constructor(element: JQuery, options?: Chart.Model); - constructor(element: Element, options?: Chart.Model); + constructor(element: JQuery | Element, options?: Chart.Model); static Locale: any; - model:Chart.Model; - defaults:Chart.Model; + model: Chart.Model; + defaults: Chart.Model; /** Animates the series and/or indicators in Chart. When parameter is not passed to this method, then all the series and indicators present in Chart are animated. - * @param {any} If an array collection is passed as parameter, series and indicator objects passed in array collection are animated.ExampleIf a series or indicator object is passed to this method, then the specific series or indicator is animated.Example, + * @param {any} If an array collection is passed as parameter, series and indicator objects passed in array collection are animated.ExampleIf a series + * or indicator object is passed to this method, then the specific series or indicator is animated.Example, * @returns {void} */ animate(options: any): void; @@ -44605,7 +47153,8 @@ class Chart extends ej.Widget { /** Exports chart as an image or to an excel file. Chart can be exported as an image only when exportCanvasRendering option is set to true. * @param {string} Type of the export operation to be performed. Following are the two export types that are supported now,1. 'image'2. 'excel'Example * @param {string} URL of the service, where the chart will be exported to excel.Example, - * @param {boolean} When this parameter is true, all the chart objects initialized to the same document are exported to a single excel file. This is an optional parameter. By default, it is false.Example, + * @param {boolean} When this parameter is true, all the chart objects initialized to the same document are exported to a single excel file. + * This is an optional parameter. By default, it is false.Example, * @returns {any} */ export(type: string, URL: string, exportMultipleChart: boolean): any; @@ -44615,13 +47164,13 @@ class Chart extends ej.Widget { */ redraw(): void; } -export module Chart{ +export namespace Chart { export interface Model { /** Options for adding and customizing annotations in Chart. */ - annotations?: Array; + annotations?: Annotation[]; /** URL of the image to be used as chart background. * @Default {null} @@ -44642,7 +47191,7 @@ export interface Model { /** Options to split Chart into multiple plotting areas vertically. Each object in the collection represents a plotting area in Chart. */ - columnDefinitions?: Array; + columnDefinitions?: ColumnDefinition[]; /** Options for configuring the properties of all the series. You can also override the options for specific series by using series collection. */ @@ -44667,6 +47216,12 @@ export interface Model { */ enableCanvasRendering?: boolean; + /** Controls whether the series has to be rendered at initial loading of chart, this will be useful in scenarios where chart is placed at the bottom of the web page + * and we need to render the series only when the chart is visible while scrolling to the top. + * @Default {true} + */ + initSeriesRender?: boolean; + /** Controls whether 3D view has to be rotated on dragging. This property is applicable only for 3D view. * @Default {false} */ @@ -44674,7 +47229,7 @@ export interface Model { /** Options to customize the technical indicators. */ - indicators?: Array; + indicators?: Indicator[]; /** Controls whether Chart has to be responsive while resizing. * @Default {false} @@ -44685,7 +47240,8 @@ export interface Model { */ legend?: Legend; - /** Name of the culture based on which chart should be localized. Number and date time values are localized with respect to the culture name.String type properties like title text are not localized automatically. Provide localized text as value to string type properties. + /** Name of the culture based on which chart should be localized. Number and date time values are localized with respect to the culture name.String type properties like title text are + * not localized automatically. Provide localized text as value to string type properties. * @Default {en-US} */ locale?: string; @@ -44693,26 +47249,32 @@ export interface Model { /** Palette is used to store the series fill color in array and apply the color to series collection in the order of series index. * @Default {null} */ - palette?: Array; + palette?: any[]; /** Options to customize the left, right, top and bottom margins of chart area. */ Margin?: any; - /** Perspective angle of the 3D view. Chart appears closer when perspective angle is decreased, and distant when perspective angle is increased.This property is applicable only when 3D view is enabled + /** Perspective angle of the 3D view. Chart appears closer when perspective angle is decreased, and distant when perspective angle is increased. + * This property is applicable only when 3D view is enabled * @Default {90} */ perspectiveAngle?: number; - /** This is a horizontal axis that contains options to configure axis and it is the primary x axis for all the series in series array. To override x axis for particular series, create an axis object by providing unique name by using name property and add it to axes array. Then, assign the name to the series’s xAxisName property to link both axis and series. + /** This is a horizontal axis that contains options to configure axis and it is the primary x axis for all the series in series array. + * To override x axis for particular series, create an axis object by providing unique name by using name property and add it to axes array. + * Then, assign the name to the series’s xAxisName property to link both axis and series. */ primaryXAxis?: PrimaryXAxis; - /** To override x axis for particular series, create an axis object by providing unique name by using name property and add it to axes array. Then, assign the name to the series’s xAxisName property to link both axis and series. + /** To override x axis for particular series, create an axis object by providing unique name by using name property and add it to axes array. + * Then, assign the name to the series’s xAxisName property to link both axis and series. */ - axes?: Array; + axes?: Axis[]; - /** This is a vertical axis that contains options to configure axis. This is the primary y axis for all the series in series array. To override y axis for particular series, create an axis object by providing unique name by using name property and add it to axes array. Then, assign the name to the series’s yAxisName property to link both axis and series. + /** This is a vertical axis that contains options to configure axis. This is the primary y axis for all the series in series array. + * To override y axis for particular series, create an axis object by providing unique name by using name property and add it to axes array. + * Then, assign the name to the series’s yAxisName property to link both axis and series. */ primaryYAxis?: PrimaryYAxis; @@ -44723,11 +47285,11 @@ export interface Model { /** Options to split Chart into multiple plotting areas horizontally. Each object in the collection represents a plotting area in Chart. */ - rowDefinitions?: Array; + rowDefinitions?: RowDefinition[]; /** Specifies the properties used for customizing the series. */ - series?: Array; + series?: Series[]; /** Controls whether data points has to be displayed side by side or along the depth of the axis. * @Default {false} @@ -44762,112 +47324,116 @@ export interface Model { zooming?: Zooming; /** Fires after the series animation is completed. This event will be triggered for each series when animation is enabled. */ - animationComplete? (e: AnimationCompleteEventArgs): void; + animationComplete?(e: AnimationCompleteEventArgs): void; /** Fires before rendering the labels. This event is fired for each label in axis. You can use this event to add custom text to axis labels. */ - axesLabelRendering? (e: AxesLabelRenderingEventArgs): void; + axesLabelRendering?(e: AxesLabelRenderingEventArgs): void; /** Fires during the initialization of axis labels. */ - axesLabelsInitialize? (e: AxesLabelsInitializeEventArgs): void; + axesLabelsInitialize?(e: AxesLabelsInitializeEventArgs): void; /** Fires during axes range calculation. This event is fired for each axis present in Chart. You can use this event to customize axis range as required. */ - axesRangeCalculate? (e: AxesRangeCalculateEventArgs): void; + axesRangeCalculate?(e: AxesRangeCalculateEventArgs): void; /** Fires before rendering the axis title. This event is triggered for each axis with title. You can use this event to add custom text to axis title. */ - axesTitleRendering? (e: AxesTitleRenderingEventArgs): void; + axesTitleRendering?(e: AxesTitleRenderingEventArgs): void; /** Fires during the calculation of chart area bounds. You can use this event to customize the bounds of chart area. */ - chartAreaBoundsCalculate? (e: ChartAreaBoundsCalculateEventArgs): void; + chartAreaBoundsCalculate?(e: ChartAreaBoundsCalculateEventArgs): void; /** Fires after chart is created. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; /** Fires when chart is destroyed completely. */ - destroy? (e: DestroyEventArgs): void; + destroy?(e: DestroyEventArgs): void; /** Fires before rendering the data labels. This event is triggered for each data label in the series. You can use this event to add custom text in data labels. */ - displayTextRendering? (e: DisplayTextRenderingEventArgs): void; + displayTextRendering?(e: DisplayTextRenderingEventArgs): void; /** Fires during the calculation of legend bounds. You can use this event to customize the bounds of legend. */ - legendBoundsCalculate? (e: LegendBoundsCalculateEventArgs): void; + legendBoundsCalculate?(e: LegendBoundsCalculateEventArgs): void; /** Fires on clicking the legend item. */ - legendItemClick? (e: LegendItemClickEventArgs): void; + legendItemClick?(e: LegendItemClickEventArgs): void; /** Fires when moving mouse over legend item. You can use this event for hit testing on legend items. */ - legendItemMouseMove? (e: LegendItemMouseMoveEventArgs): void; + legendItemMouseMove?(e: LegendItemMouseMoveEventArgs): void; /** Fires before rendering the legend item. This event is fired for each legend item in Chart. You can use this event to customize legend item shape or add custom text to legend item. */ - legendItemRendering? (e: LegendItemRenderingEventArgs): void; + legendItemRendering?(e: LegendItemRenderingEventArgs): void; /** Fires before loading the chart. */ - load? (e: LoadEventArgs): void; + load?(e: LoadEventArgs): void; + + /** Fires after selected the data in chart. */ + rangeSelected?(e: RangeSelectedEventArgs): void; /** Fires on clicking a point in chart. You can use this event to handle clicks made on points. */ - pointRegionClick? (e: PointRegionClickEventArgs): void; + pointRegionClick?(e: PointRegionClickEventArgs): void; /** Fires when mouse is moved over a point. */ - pointRegionMouseMove? (e: PointRegionMouseMoveEventArgs): void; + pointRegionMouseMove?(e: PointRegionMouseMoveEventArgs): void; /** Fires before rendering chart. */ - preRender? (e: PreRenderEventArgs): void; + preRender?(e: PreRenderEventArgs): void; /** Fires after selecting a series. This event is triggered after selecting a series only if selection mode is series. */ - seriesRegionClick? (e: SeriesRegionClickEventArgs): void; + seriesRegionClick?(e: SeriesRegionClickEventArgs): void; /** Fires before rendering a series. This event is fired for each series in Chart. */ - seriesRendering? (e: SeriesRenderingEventArgs): void; + seriesRendering?(e: SeriesRenderingEventArgs): void; /** Fires before rendering the marker symbols. This event is triggered for each marker in Chart. */ - symbolRendering? (e: SymbolRenderingEventArgs): void; + symbolRendering?(e: SymbolRenderingEventArgs): void; /** Fires before rendering the Chart title. You can use this event to add custom text in Chart title. */ - titleRendering? (e: TitleRenderingEventArgs): void; + titleRendering?(e: TitleRenderingEventArgs): void; /** Fires before rendering the tooltip. This event is fired when tooltip is enabled and mouse is hovered on a Chart point. You can use this event to customize tooltip before rendering. */ - toolTipInitialize? (e: ToolTipInitializeEventArgs): void; + toolTipInitialize?(e: ToolTipInitializeEventArgs): void; /** Fires before rendering crosshair tooltip in axis. This event is fired for each axis with crosshair label enabled. You can use this event to customize crosshair label before rendering */ - trackAxisToolTip? (e: TrackAxisToolTipEventArgs): void; + trackAxisToolTip?(e: TrackAxisToolTipEventArgs): void; - /** Fires before rendering trackball tooltip. This event is fired for each series in Chart because trackball tooltip is displayed for all the series. You can use this event to customize the text displayed in trackball tooltip. */ - trackToolTip? (e: TrackToolTipEventArgs): void; + /** Fires before rendering trackball tooltip. This event is fired for each series in Chart because trackball tooltip is displayed for all the series. + * You can use this event to customize the text displayed in trackball tooltip. */ + trackToolTip?(e: TrackToolTipEventArgs): void; /** Fires, on clicking the axis label. */ - axisLabelClick? (e: AxisLabelClickEventArgs): void; + axisLabelClick?(e: AxisLabelClickEventArgs): void; /** Fires on moving mouse over the axis label. */ - axisLabelMouseMove? (e: AxisLabelMouseMoveEventArgs): void; + axisLabelMouseMove?(e: AxisLabelMouseMoveEventArgs): void; /** Fires, on the clicking the chart. */ - chartClick? (e: ChartClickEventArgs): void; + chartClick?(e: ChartClickEventArgs): void; /** Fires on moving mouse over the chart. */ - chartMouseMove? (e: ChartMouseMoveEventArgs): void; + chartMouseMove?(e: ChartMouseMoveEventArgs): void; /** Fires, on double clicking the chart. */ - chartDoubleClick? (e: ChartDoubleClickEventArgs): void; + chartDoubleClick?(e: ChartDoubleClickEventArgs): void; /** Fires on clicking the annotation. */ - annotationClick? (e: AnnotationClickEventArgs): void; + annotationClick?(e: AnnotationClickEventArgs): void; /** Fires, after the chart is resized. */ - afterResize? (e: AfterResizeEventArgs): void; + afterResize?(e: AfterResizeEventArgs): void; /** Fires, when chart size is changing. */ - beforeResize? (e: BeforeResizeEventArgs): void; + beforeResize?(e: BeforeResizeEventArgs): void; /** Fires, when error bar is rendering. */ - errorBarRendering? (e: ErrorBarRenderingEventArgs): void; + errorBarRendering?(e: ErrorBarRenderingEventArgs): void; /** Trigger, after the scrollbar position is changed. */ - scrollChanged? (e: ScrollChangedEventArgs): void; + scrollChanged?(e: ScrollChangedEventArgs): void; /** Event triggered when scroll starts */ - scrollStart? (e: ScrollStartEventArgs): void; + scrollStart?(e: ScrollStartEventArgs): void; /** Event triggered when scroll end */ - scrollEnd? (e: ScrollEndEventArgs): void; + scrollEnd?(e: ScrollEndEventArgs): void; } export interface AnimationCompleteEventArgs { @@ -45146,7 +47712,7 @@ export interface LegendItemClickEventArgs { */ LegendItem?: any; - /** Options to customize the legend item styles such as border, color, size, etc…, + /** Options to customize the legend item styles such as border, color, size, etc…, */ style?: any; @@ -45189,11 +47755,11 @@ export interface LegendItemMouseMoveEventArgs { */ LegendItem?: any; - /** Options to customize the legend item styles such as border, color, size, etc…, + /** Options to customize the legend item styles such as border, color, size, etc…, */ style?: any; - /** Options to customize the legend item styles such as border, color, size, etc…, + /** Options to customize the legend item styles such as border, color, size, etc…, */ Bounds?: any; @@ -45256,6 +47822,25 @@ export interface LoadEventArgs { type?: string; } +export interface RangeSelectedEventArgs { + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the chart model object + */ + model?: any; + + /** Name of the event + */ + type?: string; + + /** Selected data collection of object + */ + data?: any; +} + export interface PointRegionClickEventArgs { /** Set this option to true to cancel the event @@ -45954,7 +48539,8 @@ export interface Annotation { */ visible?: boolean; - /** Represents the horizontal offset when coordinateUnit is pixels.when coordinateUnit is points, it represents the x-coordinate of axis bounded with xAxisName property or primary X axis when xAxisName is not provided.This property is not applicable when coordinateUnit is none. + /** Represents the horizontal offset when coordinateUnit is pixels.when coordinateUnit is points, it represents the x-coordinate of axis bounded with xAxisName property + * or primary X axis when xAxisName is not provided.This property is not applicable when coordinateUnit is none. * @Default {0} */ x?: number; @@ -45963,7 +48549,8 @@ export interface Annotation { */ xAxisName?: string; - /** Represents the vertical offset when coordinateUnit is pixels.When coordinateUnit is points, it represents the y-coordinate of axis bounded with yAxisName property or primary Y axis when yAxisName is not provided.This property is not applicable when coordinateUnit is none. + /** Represents the vertical offset when coordinateUnit is pixels.When coordinateUnit is points, it represents the y-coordinate of axis bounded with + * yAxisName property or primary Y axis when yAxisName is not provided.This property is not applicable when coordinateUnit is none. * @Default {0} */ y?: number; @@ -46290,7 +48877,7 @@ export interface CommonSeriesOptionsMarkerDataLabel { */ shape?: ej.datavisualization.Chart.Shape|string; - /** Custom template to format the data label content. Use “point.x” and “point.y” as a placeholder text to display the corresponding data point’s x and y value. + /** Custom template to format the data label content. Use “point.x” and “point.y” as a placeholder text to display the corresponding data point’s x and y value. */ template?: string; @@ -46342,7 +48929,7 @@ export interface CommonSeriesOptionsMarker { */ fill?: string; - /** The URL for the Image to be displayed as marker. In order to display image as marker, set series.marker.shape as ‘image’. + /** The URL for the Image to be displayed as marker. In order to display image as marker, set series.marker.shape as ‘image’. */ imageUrl?: string; @@ -46366,6 +48953,31 @@ export interface CommonSeriesOptionsMarker { visible?: boolean; } +export interface CommonSeriesOptionsOutlierSettingsSize { + + /** Height of the outlier shape. + * @Default {6} + */ + height?: number; + + /** Width of the outlier shape. + * @Default {6} + */ + width?: number; +} + +export interface CommonSeriesOptionsOutlierSettings { + + /** Specifies the shape of the outlier. + * @Default {circle. See Shape} + */ + shape?: ej.datavisualization.Chart.Shape|string; + + /** Options for customizing the size of the outlier shape. + */ + size?: CommonSeriesOptionsOutlierSettingsSize; +} + export interface CommonSeriesOptionsCornerRadius { /** Specifies the radius for the top left corner. @@ -46443,7 +49055,7 @@ export interface CommonSeriesOptionsTooltip { */ opacity?: number; - /** Custom template to format the tooltip content. Use “point.x” and “point.y” as a placeholder text to display the corresponding data point’s x and y value. + /** Custom template to format the tooltip content. Use “point.x” and “point.y” as a placeholder text to display the corresponding data point’s x and y value. * @Default {null} */ template?: string; @@ -46517,6 +49129,19 @@ export interface CommonSeriesOptionsConnectorLine { opacity?: number; } +export interface CommonSeriesOptionsDragSettings { + + /** drag/drop the series + * @Default {false} + */ + enable?: boolean; + + /** Specifies the type of drag settings. + * @Default {xy} + */ + type?: string; +} + export interface CommonSeriesOptionsErrorBarCap { /** Show/Hides the error bar cap. @@ -46535,7 +49160,7 @@ export interface CommonSeriesOptionsErrorBarCap { length?: number; /** Color of the error bar cap. - * @Default {“#000000”} + * @Default {“#000000”} */ fill?: string; } @@ -46793,6 +49418,10 @@ export interface CommonSeriesOptions { */ visibleOnLegend?: string; + /** Group of the stacking collection series. + */ + stackingGroup?: string; + /** Pattern of dashes and gaps used to stroke all the line type series. */ dashArray?: string; @@ -46891,11 +49520,21 @@ export interface CommonSeriesOptions { */ isTransposed?: boolean; + /** Render the x mark in the center of the box and whisker series type.x represents the average value of the box and whisker series. + * @Default {true} + */ + showMedian?: boolean; + /** Position of the data label in pie/doughnut/pyramid/funnel series. OutsideExtended position is not applicable for pyramid/funnel. * @Default {inside. See LabelPosition} */ labelPosition?: ej.datavisualization.Chart.LabelPosition|string; + /** Quartile calculation has been performed in three different formulas to render the box and whisker series. + * @Default {exclusive} + */ + boxPlotMode?: ej.datavisualization.Chart.boxPlotMode|string; + /** Specifies the line cap of the series. * @Default {butt. See LineCap} */ @@ -46915,6 +49554,10 @@ export interface CommonSeriesOptions { */ opacity?: number; + /** Options for customizing the outlier of the series. + */ + outlierSettings?: CommonSeriesOptionsOutlierSettings; + /** Name of a field in data source, where the fill color for all the data points is generated. */ palette?: string; @@ -47015,13 +49658,17 @@ export interface CommonSeriesOptions { */ connectorLine?: CommonSeriesOptionsConnectorLine; + /** Options to customize the drag and drop in series. + */ + dragSettings?: CommonSeriesOptionsDragSettings; + /** Options to customize the error bar in series. */ errorBar?: CommonSeriesOptionsErrorBar; /** Option to add the trendlines to chart. */ - trendlines?: Array; + trendlines?: CommonSeriesOptionsTrendline[]; /** Options for customizing the appearance of the series or data point while highlighting. */ @@ -47255,7 +49902,7 @@ export interface IndicatorsTooltip { */ enableAnimation?: boolean; - /** Format of indicator tooltip. Use “point.x” and “point.y” as a placeholder text to display the corresponding data point’s x and y value. + /** Format of indicator tooltip. Use “point.x” and “point.y” as a placeholder text to display the corresponding data point’s x and y value. * @Default {#point.x# : #point.y#} */ format?: string; @@ -47669,6 +50316,10 @@ export interface PrimaryXAxisAxisLine { */ visible?: boolean; + /** Default Value + */ + color?: string; + /** Width of axis line. * @Default {1} */ @@ -47996,7 +50647,8 @@ export interface PrimaryXAxisStripLine { */ width?: number; - /** Specifies the order where the strip line and the series have to be rendered. When Z-order is “behind”, strip line is rendered under the series and when it is “over”, it is rendered above the series. + /** Specifies the order where the strip line and the series have to be rendered. When Z-order is “behind”, strip line is rendered + * under the series and when it is “over”, it is rendered above the series. * @Default {over. See ZIndex} */ zIndex?: ej.datavisualization.Chart.ZIndex|string; @@ -48090,17 +50742,19 @@ export interface PrimaryXAxis { */ alternateGridBand?: PrimaryXAxisAlternateGridBand; - /** Specifies where horizontal axis should intersect the vertical axis or vice versa. Value should be provided in axis co-ordinates. If provided value is greater than the maximum value of crossing axis, then axis will be placed at the opposite side. + /** Specifies where horizontal axis should intersect the vertical axis or vice versa. Value should be provided in axis co-ordinates. + * If provided value is greater than the maximum value of crossing axis, then axis will be placed at the opposite side. * @Default {null} */ crossesAt?: number; - /** Name of the axis used for crossing. Vertical axis name should be provided for horizontal axis and vice versa. If the provided name does not belongs to a valid axis, then primary X axis or primary Y axis will be used for crossing + /** Name of the axis used for crossing. Vertical axis name should be provided for horizontal axis and vice versa. + * If the provided name does not belongs to a valid axis, then primary X axis or primary Y axis will be used for crossing * @Default {null} */ crossesInAxis?: string; - /** Category axis can also plot points based on index value of data points. Index based plotting can be enabled by setting ‘isIndexed’ property to true. + /** Category axis can also plot points based on index value of data points. Index based plotting can be enabled by setting ‘isIndexed’ property to true. * @Default {false} */ isIndexed?: boolean; @@ -48250,12 +50904,12 @@ export interface PrimaryXAxis { /** Options for customizing the multi level labels. * @Default {[ ]} */ - multiLevelLabels?: Array; + multiLevelLabels?: PrimaryXAxisMultiLevelLabel[]; /** Options for customizing the strip lines. * @Default {[ ]} */ - stripLine?: Array; + stripLine?: PrimaryXAxisStripLine[]; /** Specifies the position of the axis tick lines. * @Default {outside. See TickLinesPosition} @@ -48345,6 +50999,10 @@ export interface AxesAxisLine { */ visible?: boolean; + /** Color of axis line. + */ + color?: string; + /** Width of axis line. * @Default {1} */ @@ -48672,7 +51330,8 @@ export interface AxesStripLine { */ width?: number; - /** Specifies the order where the strip line and the series have to be rendered. When Z-order is “behind”, strip line is rendered under the series and when it is “over”, it is rendered above the series. + /** Specifies the order where the strip line and the series have to be rendered. When Z-order is “behind”, strip line is rendered under the series and when it is “over”, + * it is rendered above the series. * @Default {over. See ZIndex} */ zIndex?: ej.datavisualization.Chart.ZIndex|string; @@ -48766,12 +51425,13 @@ export interface Axis { */ alternateGridBand?: AxesAlternateGridBand; - /** Specifies where axis should intersect the vertical axis or vice versa. Value should be provided in axis co-ordinates. If provided value is greater than the maximum value of crossing axis, then axis will be placed at the opposite side. + /** Specifies where axis should intersect the vertical axis or vice versa. Value should be provided in axis co-ordinates. If provided value is greater than the maximum value of crossing axis, + * then axis will be placed at the opposite side. * @Default {null} */ crossesAt?: number; - /** Category axis can also plot points based on index value of data points. Index based plotting can be enabled by setting ‘isIndexed’ property to true. + /** Category axis can also plot points based on index value of data points. Index based plotting can be enabled by setting ‘isIndexed’ property to true. * @Default {false} */ isIndexed?: boolean; @@ -48921,12 +51581,12 @@ export interface Axis { /** Options for customizing the multi level labels. * @Default {[ ]} */ - multiLevelLabels?: Array; + multiLevelLabels?: AxesMultiLevelLabel[]; /** Options for customizing the strip lines. * @Default {[ ]} */ - stripLine?: Array; + stripLine?: AxesStripLine[]; /** Specifies the position of the axis tick lines. * @Default {outside. See TickLinesPosition} @@ -49016,6 +51676,10 @@ export interface PrimaryYAxisAxisLine { */ visible?: boolean; + /** Color of axis line. + */ + color?: string; + /** Width of axis line. * @Default {1} */ @@ -49318,7 +51982,7 @@ export interface PrimaryYAxisStripLine { */ start?: number; - /** Indicates whether to render the strip line from the minimum/start value of the axis. This property won’t work when start property is set. + /** Indicates whether to render the strip line from the minimum/start value of the axis. This property won’t work when start property is set. * @Default {false} */ startFromAxis?: boolean; @@ -49343,7 +52007,8 @@ export interface PrimaryYAxisStripLine { */ width?: number; - /** Specifies the order in which strip line and the series have to be rendered. When Z-order is “behind”, strip line is rendered below the series and when it is “over”, it is rendered above the series. + /** Specifies the order in which strip line and the series have to be rendered. When Z-order is “behind”, strip line is rendered below the series and + * when it is “over”, it is rendered above the series. * @Default {over. See ZIndex} */ zIndex?: ej.datavisualization.Chart.ZIndex|string; @@ -49441,12 +52106,14 @@ export interface PrimaryYAxis { */ axisLine?: PrimaryYAxisAxisLine; - /** Specifies where horizontal axis should intersect the vertical axis or vice versa. Value should be provided in axis co-ordinates. If provided value is greater than the maximum value of crossing axis, then axis will be placed at the opposite side. + /** Specifies where horizontal axis should intersect the vertical axis or vice versa. Value should be provided in axis co-ordinates. + * If provided value is greater than the maximum value of crossing axis, then axis will be placed at the opposite side. * @Default {null} */ crossesAt?: number; - /** Name of the axis used for crossing. Vertical axis name should be provided for horizontal axis and vice versa. If the provided name does not belongs to a valid axis, then primary X axis or primary Y axis will be used for crossing + /** Name of the axis used for crossing. Vertical axis name should be provided for horizontal axis and vice versa. If the provided name does not belongs to a valid axis, + * then primary X axis or primary Y axis will be used for crossing * @Default {null} */ crossesInAxis?: string; @@ -49587,12 +52254,12 @@ export interface PrimaryYAxis { /** Options for customizing the multi level labels. * @Default {[ ]} */ - multiLevelLabels?: Array; + multiLevelLabels?: PrimaryYAxisMultiLevelLabel[]; /** Options for customizing the strip lines. * @Default {[ ]} */ - stripLine?: Array; + stripLine?: PrimaryYAxisStripLine[]; /** Specifies the position of the axis tick lines. * @Default {outside. See TickLinesPosition} @@ -49856,7 +52523,7 @@ export interface SeriesMarkerDataLabel { opacity?: number; /** Background shape of the data label. - * @Default {No shape is rendered by default, so its value is ‘none’. See Shape} + * @Default {No shape is rendered by default, so its value is ‘none’. See Shape} */ shape?: ej.datavisualization.Chart.Shape|string; @@ -49879,7 +52546,7 @@ export interface SeriesMarkerDataLabel { */ visible?: boolean; - /** Custom template to format the data label content. Use “point.x” and “point.y” as a placeholder text to display the corresponding data point’s x and y value. + /** Custom template to format the data label content. Use “point.x” and “point.y” as a placeholder text to display the corresponding data point’s x and y value. */ template?: string; @@ -49917,7 +52584,7 @@ export interface SeriesMarker { */ fill?: string; - /** The URL for the Image that is to be displayed as marker. In order to display image as marker, set series.marker.shape as ‘image’. + /** The URL for the Image that is to be displayed as marker. In order to display image as marker, set series.marker.shape as ‘image’. */ imageUrl?: string; @@ -49941,6 +52608,31 @@ export interface SeriesMarker { visible?: boolean; } +export interface SeriesOutlierSettingsSize { + + /** Height of the outlier shape. + * @Default {6} + */ + height?: number; + + /** Width of the outlier shape. + * @Default {6} + */ + width?: number; +} + +export interface SeriesOutlierSettings { + + /** Specifies the shape of the outlier. + * @Default {circle. See Shape} + */ + shape?: ej.datavisualization.Chart.Shape|string; + + /** Options for customizing the size of the outlier shape. + */ + size?: SeriesOutlierSettingsSize; +} + export interface SeriesEmptyPointSettingsStyleBorder { /** Border color of the empty point. @@ -50004,6 +52696,19 @@ export interface SeriesConnectorLine { opacity?: number; } +export interface SeriesDragSettings { + + /** drag/drop the series + * @Default {false} + */ + enable?: boolean; + + /** Specifies the type of drag settings. + * @Default {xy} + */ + type?: string; +} + export interface SeriesErrorBarCap { /** Show/Hides the error bar cap. @@ -50236,7 +52941,7 @@ export interface SeriesPointsMarkerDataLabel { opacity?: number; /** Background shape of the data label. - * @Default {No shape is rendered by default, so its value is ‘none’. See Shape} + * @Default {No shape is rendered by default, so its value is ‘none’. See Shape} */ shape?: ej.datavisualization.Chart.Shape|string; @@ -50255,7 +52960,7 @@ export interface SeriesPointsMarkerDataLabel { */ visible?: boolean; - /** Custom template to format the data label content. Use “point.x” and “point.y” as a placeholder text to display the corresponding data point’s x and y value. + /** Custom template to format the data label content. Use “point.x” and “point.y” as a placeholder text to display the corresponding data point’s x and y value. */ template?: string; @@ -50293,7 +52998,7 @@ export interface SeriesPointsMarker { */ fill?: string; - /** The URL for the Image that is to be displayed as marker. In order to display image as marker, set series.marker.shape as ‘image’. + /** The URL for the Image that is to be displayed as marker. In order to display image as marker, set series.marker.shape as ‘image’. */ imageUrl?: string; @@ -50465,7 +53170,7 @@ export interface SeriesTooltip { */ opacity?: number; - /** Custom template to format the tooltip content. Use “point.x” and “point.y” as a placeholder text to display the corresponding data point’s x and y value. + /** Custom template to format the tooltip content. Use “point.x” and “point.y” as a placeholder text to display the corresponding data point’s x and y value. * @Default {null} */ template?: string; @@ -50667,6 +53372,10 @@ export interface Series { */ columnSpacing?: number; + /** To group the series of stacking collection. + */ + stackingGroup?: string; + /** Pattern of dashes and gaps used to stroke the line type series. */ dashArray?: string; @@ -50765,11 +53474,21 @@ export interface Series { */ isTransposed?: boolean; + /** Render the x mark in the center of the box and whisker series type.x represents the average value of the box and whisker series. + * @Default {true} + */ + showMedian?: boolean; + /** Position of the data label in pie/doughnut/pyramid/funnel series. OutsideExtended position is not applicable for pyramid/funnel. * @Default {inside. See LabelPosition} */ labelPosition?: ej.datavisualization.Chart.LabelPosition|string; + /** Quartile calculation has been performed in three different formulas to render the boxplot series . + * @Default {exclusive} + */ + boxPlotMode?: ej.datavisualization.Chart.LabelPosition|string; + /** Specifies the line cap of the series. * @Default {Butt. See LineCap} */ @@ -50794,6 +53513,10 @@ export interface Series { */ opacity?: number; + /** Options for customizing the outlier of individual series. + */ + outlierSettings?: SeriesOutlierSettings; + /** Name of a field in data source where fill color for all the data points is generated. */ palette?: string; @@ -50816,13 +53539,17 @@ export interface Series { */ connectorLine?: SeriesConnectorLine; + /** Options to customize the drag and drop in series. + */ + dragSettings?: SeriesDragSettings; + /** Options to customize the error bar in series. */ errorBar?: SeriesErrorBar; /** Option to add data points; each point should have x and y property. Also, optionally, you can customize the points color, border, marker by using fill, border and marker options. */ - points?: Array; + points?: SeriesPoint[]; /** Specifies the mode of the pyramid series. * @Default {linear} @@ -50919,7 +53646,7 @@ export interface Series { /** Option to add trendlines to chart. */ - trendlines?: Array; + trendlines?: SeriesTrendline[]; /** Options for customizing the appearance of the series or data point while highlighting. */ @@ -51134,13 +53861,11 @@ export interface Zooming { /** To display user specified buttons in zooming toolbar. * @Default {[zoomIn, zoomOut, zoom, pan, reset]} */ - toolbarItems?: Array; + toolbarItems?: any[]; } } -module Chart -{ -enum CoordinateUnit -{ +namespace Chart { +enum CoordinateUnit { //string None, //string @@ -51149,10 +53874,8 @@ Pixels, Points, } } -module Chart -{ -enum HorizontalAlignment -{ +namespace Chart { +enum HorizontalAlignment { //string Left, //string @@ -51161,20 +53884,16 @@ Right, Middle, } } -module Chart -{ -enum Region -{ +namespace Chart { +enum Region { //string Chart, //string Series, } } -module Chart -{ -enum VerticalAlignment -{ +namespace Chart { +enum VerticalAlignment { //string Top, //string @@ -51183,10 +53902,8 @@ Bottom, Middle, } } -module Chart -{ -enum ExportingType -{ +namespace Chart { +enum ExportingType { //string PNG, //string @@ -51201,50 +53918,40 @@ XLSX, SVG, } } -module Chart -{ -enum ExportingOrientation -{ +namespace Chart { +enum ExportingOrientation { //string Portrait, //string Landscape, } } -module Chart -{ -enum ExportingMode -{ +namespace Chart { +enum ExportingMode { //string ServerSide, //string ClientSide, } } -module Chart -{ -enum Unit -{ +namespace Chart { +enum Unit { //string Percentage, //string Pixel, } } -module Chart -{ -enum ColumnFacet -{ +namespace Chart { +enum ColumnFacet { //string Rectangle, //string Cylinder, } } -module Chart -{ -enum DrawType -{ +namespace Chart { +enum DrawType { //string Line, //string @@ -51253,20 +53960,16 @@ Area, Column, } } -module Chart -{ -enum FontStyle -{ +namespace Chart { +enum FontStyle { //string Normal, //string Italic, } } -module Chart -{ -enum FontWeight -{ +namespace Chart { +enum FontWeight { //string Regular, //string @@ -51275,10 +53978,8 @@ Bold, Lighter, } } -module Chart -{ -enum LabelPosition -{ +namespace Chart { +enum LabelPosition { //string Inside, //string @@ -51287,10 +53988,18 @@ Outside, OutsideExtended, } } -module Chart -{ -enum LineCap -{ +namespace Chart { +enum boxPlotMode { +//string +Exclusive, +//string +Inclusive, +//string +Normal, +} +} +namespace Chart { +enum LineCap { //string Butt, //string @@ -51299,10 +54008,8 @@ Round, Square, } } -module Chart -{ -enum LineJoin -{ +namespace Chart { +enum LineJoin { //string Round, //string @@ -51311,20 +54018,16 @@ Bevel, Miter, } } -module Chart -{ -enum ConnectorLineType -{ +namespace Chart { +enum ConnectorLineType { //string Line, //string Bezier, } } -module Chart -{ -enum HorizontalTextAlignment -{ +namespace Chart { +enum HorizontalTextAlignment { //string Center, //string @@ -51333,10 +54036,8 @@ Near, Far, } } -module Chart -{ -enum Shape -{ +namespace Chart { +enum Shape { //string None, //string @@ -51377,10 +54078,8 @@ Image, SeriesType, } } -module Chart -{ -enum TextPosition -{ +namespace Chart { +enum TextPosition { //string Top, //string @@ -51389,10 +54088,8 @@ Bottom, Middle, } } -module Chart -{ -enum VerticalTextAlignment -{ +namespace Chart { +enum VerticalTextAlignment { //string Center, //string @@ -51401,20 +54098,16 @@ Near, Far, } } -module Chart -{ -enum PyramidMode -{ +namespace Chart { +enum PyramidMode { //string Linear, //string Surface, } } -module Chart -{ -enum Type -{ +namespace Chart { +enum Type { //string Area, //string @@ -51471,10 +54164,8 @@ Radar, RangeArea, } } -module Chart -{ -enum EmptyPointMode -{ +namespace Chart { +enum EmptyPointMode { //string Gap, //string @@ -51483,10 +54174,8 @@ Zero, Average, } } -module Chart -{ -enum ErrorBarType -{ +namespace Chart { +enum ErrorBarType { //string FixedValue, //string @@ -51497,10 +54186,8 @@ StandardDeviation, StandardError, } } -module Chart -{ -enum ErrorBarMode -{ +namespace Chart { +enum ErrorBarMode { //string Both, //string @@ -51509,10 +54196,8 @@ Vertical, Horizontal, } } -module Chart -{ -enum ErrorBarDirection -{ +namespace Chart { +enum ErrorBarDirection { //string Both, //string @@ -51521,10 +54206,8 @@ Plus, Minus, } } -module Chart -{ -enum Mode -{ +namespace Chart { +enum Mode { //string Series, //string @@ -51535,20 +54218,16 @@ Cluster, Range, } } -module Chart -{ -enum SelectionType -{ +namespace Chart { +enum SelectionType { //string Single, //string Multiple, } } -module Chart -{ -enum RangeType -{ +namespace Chart { +enum RangeType { //string XY, //string @@ -51557,30 +54236,24 @@ X, Y, } } -module Chart -{ -enum CrosshairMode -{ +namespace Chart { +enum CrosshairMode { //string Float, //string Grouping, } } -module Chart -{ -enum CrosshairType -{ +namespace Chart { +enum CrosshairType { //string Crosshair, //string Trackball, } } -module Chart -{ -enum Alignment -{ +namespace Chart { +enum Alignment { //string Center, //string @@ -51589,10 +54262,8 @@ Near, Far, } } -module Chart -{ -enum Position -{ +namespace Chart { +enum Position { //string Left, //string @@ -51603,10 +54274,8 @@ Top, Bottom, } } -module Chart -{ -enum TextOverflow -{ +namespace Chart { +enum TextOverflow { //string None, //string @@ -51617,20 +54286,16 @@ Wrap, WrapAndTrim, } } -module Chart -{ -enum LabelPlacement -{ +namespace Chart { +enum LabelPlacement { //string OnTicks, //string BetweenTicks, } } -module Chart -{ -enum EdgeLabelPlacement -{ +namespace Chart { +enum EdgeLabelPlacement { //string None, //string @@ -51639,10 +54304,8 @@ Shift, Hide, } } -module Chart -{ -enum IntervalType -{ +namespace Chart { +enum IntervalType { //string Days, //string @@ -51659,10 +54322,8 @@ Months, Years, } } -module Chart -{ -enum LabelIntersectAction -{ +namespace Chart { +enum LabelIntersectAction { //string None, //string @@ -51681,10 +54342,8 @@ Hide, MultipleRows, } } -module Chart -{ -enum LabelAlignment -{ +namespace Chart { +enum LabelAlignment { //string Near, //string @@ -51693,10 +54352,8 @@ Far, Center, } } -module Chart -{ -enum RangePadding -{ +namespace Chart { +enum RangePadding { //string Additional, //string @@ -51707,10 +54364,8 @@ None, Round, } } -module Chart -{ -enum MultiLevelLabelsBorderType -{ +namespace Chart { +enum MultiLevelLabelsBorderType { //string Rectangle, //string @@ -51723,10 +54378,8 @@ Brace, CurlyBrace, } } -module Chart -{ -enum TextAlignment -{ +namespace Chart { +enum TextAlignment { //string MiddleTop, //string @@ -51735,30 +54388,24 @@ MiddleCenter, MiddleBottom, } } -module Chart -{ -enum ZIndex -{ +namespace Chart { +enum ZIndex { //string Inside, //string Over, } } -module Chart -{ -enum TickLinesPosition -{ +namespace Chart { +enum TickLinesPosition { //string Inside, //string Outside, } } -module Chart -{ -enum ValueType -{ +namespace Chart { +enum ValueType { //string Double, //string @@ -51769,10 +54416,8 @@ DateTime, Logarithmic, } } -module Chart -{ -enum Theme -{ +namespace Chart { +enum Theme { //string Azure, //string @@ -51798,18 +54443,17 @@ GradientDark, class RangeNavigator extends ej.Widget { static fn: RangeNavigator; - constructor(element: JQuery, options?: RangeNavigator.Model); - constructor(element: Element, options?: RangeNavigator.Model); + constructor(element: JQuery | Element, options?: RangeNavigator.Model); static Locale: any; - model:RangeNavigator.Model; - defaults:RangeNavigator.Model; + model: RangeNavigator.Model; + defaults: RangeNavigator.Model; /** destroy the range navigator widget * @returns {void} */ _destroy(): void; } -export module RangeNavigator{ +export namespace RangeNavigator { export interface Model { @@ -51828,7 +54472,7 @@ export interface Model { /** Specifies the properties used for customizing the range series. */ - series?: Array; + series?: Series[]; /** Toggles the redrawing of chart on moving the sliders. * @Default {true} @@ -51920,22 +54564,22 @@ export interface Model { yName?: any; /** Fires on load of range navigator. */ - load? (e: LoadEventArgs): void; + load?(e: LoadEventArgs): void; /** Fires after range navigator is loaded. */ - loaded? (e: LoadedEventArgs): void; + loaded?(e: LoadedEventArgs): void; /** Fires on changing the range of range navigator. */ - rangeChanged? (e: RangeChangedEventArgs): void; + rangeChanged?(e: RangeChangedEventArgs): void; /** Fires on changing the scrollbar position of range navigator. */ - scrollChanged? (e: ScrollChangedEventArgs): void; + scrollChanged?(e: ScrollChangedEventArgs): void; /** Fires on when starting to change the scrollbar position of range navigator. */ - scrollStart? (e: ScrollStartEventArgs): void; + scrollStart?(e: ScrollStartEventArgs): void; /** Fires on changes ending the scrollbar position of range navigator. */ - scrollEnd? (e: ScrollEndEventArgs): void; + scrollEnd?(e: ScrollEndEventArgs): void; } export interface LoadEventArgs { @@ -52794,10 +55438,8 @@ export interface ValueAxisSettings { visible?: boolean; } } -module RangeNavigator -{ -enum Type -{ +namespace RangeNavigator { +enum Type { //string Area, //string @@ -52812,10 +55454,8 @@ SplineArea, StepLine, } } -module RangeNavigator -{ -enum IntervalType -{ +namespace RangeNavigator { +enum IntervalType { //string Years, //string @@ -52832,30 +55472,24 @@ Hours, Minutes, } } -module RangeNavigator -{ -enum LabelPlacement -{ +namespace RangeNavigator { +enum LabelPlacement { //string Inside, //string Outside, } } -module RangeNavigator -{ -enum Position -{ +namespace RangeNavigator { +enum Position { //string Top, //string Bottom, } } -module RangeNavigator -{ -enum FontStyle -{ +namespace RangeNavigator { +enum FontStyle { //string Normal, //string @@ -52864,20 +55498,16 @@ Bold, Italic, } } -module RangeNavigator -{ -enum FontWeight -{ +namespace RangeNavigator { +enum FontWeight { //string Regular, //string Lighter, } } -module RangeNavigator -{ -enum HorizontalAlignment -{ +namespace RangeNavigator { +enum HorizontalAlignment { //string Middle, //string @@ -52886,10 +55516,8 @@ Left, Right, } } -module RangeNavigator -{ -enum RangePadding -{ +namespace RangeNavigator { +enum RangePadding { //string Additional, //string @@ -52900,10 +55528,8 @@ None, Round, } } -module RangeNavigator -{ -enum ValueType -{ +namespace RangeNavigator { +enum ValueType { //string Numeric, //string @@ -52913,11 +55539,10 @@ DateTime, class BulletGraph extends ej.Widget { static fn: BulletGraph; - constructor(element: JQuery, options?: BulletGraph.Model); - constructor(element: Element, options?: BulletGraph.Model); + constructor(element: JQuery | Element, options?: BulletGraph.Model); static Locale: any; - model:BulletGraph.Model; - defaults:BulletGraph.Model; + model: BulletGraph.Model; + defaults: BulletGraph.Model; /** To destroy the bullet graph * @returns {void} @@ -52939,7 +55564,7 @@ class BulletGraph extends ej.Widget { */ setFeatureMeasureBarValue(): void; } -export module BulletGraph{ +export namespace BulletGraph { export interface Model { @@ -52989,7 +55614,7 @@ export interface Model { /** Contains property to customize the qualitative ranges. */ - qualitativeRanges?: Array; + qualitativeRanges?: QualitativeRange[]; /** Size of the qualitative range depends up on the specified value. * @Default {32} @@ -53005,11 +55630,6 @@ export interface Model { */ quantitativeScaleSettings?: QuantitativeScaleSettings; - /** Contains property to add dataSource and dataSource fields. - * @Default {null} - */ - fields?: any; - /** By specifying this property the user can change the theme of the bullet graph. * @Default {flatlight} */ @@ -53030,28 +55650,28 @@ export interface Model { width?: number; /** Fires on rendering the caption of bullet graph. */ - drawCaption? (e: DrawCaptionEventArgs): void; + drawCaption?(e: DrawCaptionEventArgs): void; /** Fires on rendering the category. */ - drawCategory? (e: DrawCategoryEventArgs): void; + drawCategory?(e: DrawCategoryEventArgs): void; /** Fires on rendering the comparative measure symbol. */ - drawComparativeMeasureSymbol? (e: DrawComparativeMeasureSymbolEventArgs): void; + drawComparativeMeasureSymbol?(e: DrawComparativeMeasureSymbolEventArgs): void; /** Fires on rendering the feature measure bar. */ - drawFeatureMeasureBar? (e: DrawFeatureMeasureBarEventArgs): void; + drawFeatureMeasureBar?(e: DrawFeatureMeasureBarEventArgs): void; /** Fires on rendering the indicator of bullet graph. */ - drawIndicator? (e: DrawIndicatorEventArgs): void; + drawIndicator?(e: DrawIndicatorEventArgs): void; /** Fires on rendering the labels. */ - drawLabels? (e: DrawLabelsEventArgs): void; + drawLabels?(e: DrawLabelsEventArgs): void; /** Fires on rendering the qualitative ranges. */ - drawQualitativeRanges? (e: DrawQualitativeRangesEventArgs): void; + drawQualitativeRanges?(e: DrawQualitativeRangesEventArgs): void; /** Fires on loading bullet graph. */ - load? (e: LoadEventArgs): void; + load?(e: LoadEventArgs): void; } export interface DrawCaptionEventArgs { @@ -53188,6 +55808,9 @@ export interface DrawQualitativeRangesEventArgs { } export interface LoadEventArgs { + /** Returns the cancel option value. + */ + cancel?: boolean; } export interface CaptionSettingsFont { @@ -53352,7 +55975,8 @@ export interface CaptionSettingsIndicator { */ textAlignment?: ej.datavisualization.BulletGraph.TextAlignment|string; - /** Specifies where indicator text should be anchored when indicator overlaps with other caption group text. Text will be anchored when overlapping caption group text are at same position. Anchoring is not applicable for float position. + /** Specifies where indicator text should be anchored when indicator overlaps with other caption group text. Text will be anchored when overlapping caption group text are at same position. + * Anchoring is not applicable for float position. * @Default {'start'} */ textAnchor?: ej.datavisualization.BulletGraph.TextAnchor|string; @@ -53461,7 +56085,8 @@ export interface CaptionSettingsSubTitle { */ textAlignment?: ej.datavisualization.BulletGraph.TextAlignment|string; - /** Specifies where subtitle text should be anchored when sub title text overlaps with other caption group text. Text will be anchored when overlapping caption group text are at same position. Anchoring is not applicable for float position. + /** Specifies where subtitle text should be anchored when sub title text overlaps with other caption group text. Text will be anchored when overlapping + * caption group text are at same position. Anchoring is not applicable for float position. * @Default {'start'} */ textAnchor?: ej.datavisualization.BulletGraph.TextAnchor|string; @@ -53514,7 +56139,8 @@ export interface CaptionSettings { */ textAlignment?: ej.datavisualization.BulletGraph.TextAlignment|string; - /** Specifies caption text anchoring when caption text overlaps with other caption group text. Text will be anchored when overlapping caption group text are at same position. Anchoring is not applicable for float position. + /** Specifies caption text anchoring when caption text overlaps with other caption group text. + * Text will be anchored when overlapping caption group text are at same position. Anchoring is not applicable for float position. * @Default {'start'} */ textAnchor?: ej.datavisualization.BulletGraph.TextAnchor|string; @@ -53751,7 +56377,7 @@ export interface QuantitativeScaleSettings { /** Contains property to customize the featured measure. */ - featureMeasures?: Array; + featureMeasures?: QuantitativeScaleSettingsFeatureMeasure[]; /** Contains property to customize the fields. */ @@ -53827,10 +56453,8 @@ export interface TooltipSettings { visible?: boolean; } } -module BulletGraph -{ -enum FontStyle -{ +namespace BulletGraph { +enum FontStyle { //string Normal, //string @@ -53839,10 +56463,8 @@ Italic, Oblique, } } -module BulletGraph -{ -enum FontWeight -{ +namespace BulletGraph { +enum FontWeight { //string Normal, //string @@ -53853,10 +56475,8 @@ Bolder, Lighter, } } -module BulletGraph -{ -enum TextAlignment -{ +namespace BulletGraph { +enum TextAlignment { //string Near, //string @@ -53865,10 +56485,8 @@ Far, Center, } } -module BulletGraph -{ -enum TextAnchor -{ +namespace BulletGraph { +enum TextAnchor { //string Start, //string @@ -53877,10 +56495,8 @@ Middle, End, } } -module BulletGraph -{ -enum TextPosition -{ +namespace BulletGraph { +enum TextPosition { //string Top, //string @@ -53893,60 +56509,48 @@ Bottom, Float, } } -module BulletGraph -{ -enum FlowDirection -{ +namespace BulletGraph { +enum FlowDirection { //string Forward, //string Backward, } } -module BulletGraph -{ -enum Orientation -{ +namespace BulletGraph { +enum Orientation { //string Horizontal, //string Vertical, } } -module BulletGraph -{ -enum LabelPlacement -{ +namespace BulletGraph { +enum LabelPlacement { //string Inside, //string Outside, } } -module BulletGraph -{ -enum LabelPosition -{ +namespace BulletGraph { +enum LabelPosition { //string Above, //string Below, } } -module BulletGraph -{ -enum TickPlacement -{ +namespace BulletGraph { +enum TickPlacement { //string Inside, //string Outside, } } -module BulletGraph -{ -enum TickPosition -{ +namespace BulletGraph { +enum TickPosition { //string Below, //string @@ -53958,11 +56562,10 @@ Cross, class Barcode extends ej.Widget { static fn: Barcode; - constructor(element: JQuery, options?: Barcode.Model); - constructor(element: Element, options?: Barcode.Model); + constructor(element: JQuery | Element, options?: Barcode.Model); static Locale: any; - model:Barcode.Model; - defaults:Barcode.Model; + model: Barcode.Model; + defaults: Barcode.Model; /** To disable the barcode * @returns {void} @@ -53974,7 +56577,7 @@ class Barcode extends ej.Widget { */ enable(): void; } -export module Barcode{ +export namespace Barcode { export interface Model { @@ -53982,7 +56585,8 @@ export interface Model { */ barcodeToTextGapHeight?: number; - /** Specifies the height of bars in the Barcode. By modifying the barHeight, the entire barcode height can be customized. Please refer to xDimension for two dimensional barcode height customization. + /** Specifies the height of bars in the Barcode. By modifying the barHeight, the entire barcode height can be customized. + * Please refer to xDimension for two dimensional barcode height customization. */ barHeight?: number; @@ -53998,7 +56602,8 @@ export interface Model { */ enabled?: boolean; - /** Specifies the start and stop encode symbol in the Barcode. In one dimensional barcodes, an additional character is added as start and stop delimiters. These symbols are optional and the unique of the symbol allows the reader to determine the direction of the barcode being scanned. + /** Specifies the start and stop encode symbol in the Barcode. In one dimensional barcodes, an additional character is added as start and stop delimiters. + * These symbols are optional and the unique of the symbol allows the reader to determine the direction of the barcode being scanned. */ encodeStartStopSymbol?: number; @@ -54006,11 +56611,13 @@ export interface Model { */ lightBarColor?: any; - /** Specifies the width of the narrow bars in the barcode. The dark bars in the one dimensional barcode contains random narrow and wide bars based on the provided input which can be specified during initialization. + /** Specifies the width of the narrow bars in the barcode. The dark bars in the one dimensional barcode contains random narrow and wide bars based on + * the provided input which can be specified during initialization. */ narrowBarWidth?: number; - /** Specifies the width of the quiet zone. In barcode, a quiet zone is the blank margin on either side of a barcode which informs the reader where a barcode's symbology starts and stops. The purpose of a quiet zone is to prevent the reader from picking up unrelated information. + /** Specifies the width of the quiet zone. In barcode, a quiet zone is the blank margin on either side of a barcode which informs the reader where a barcode's symbology starts and stops. + * The purpose of a quiet zone is to prevent the reader from picking up unrelated information. */ quietZone?: QuietZone; @@ -54035,7 +56642,7 @@ export interface Model { xDimension?: number; /** Fires after Barcode control is loaded. */ - load? (e: LoadEventArgs): void; + load?(e: LoadEventArgs): void; } export interface LoadEventArgs { @@ -54080,10 +56687,8 @@ export interface QuietZone { top?: number; } } -module Barcode -{ -enum SymbologyType -{ +namespace Barcode { +enum SymbologyType { //Represents the QR code QRBarcode, //Represents the Data Matrix barcode @@ -54113,11 +56718,10 @@ Code128C, class Map extends ej.Widget { static fn: Map; - constructor(element: JQuery, options?: Map.Model); - constructor(element: Element, options?: Map.Model); + constructor(element: JQuery | Element, options?: Map.Model); static Locale: any; - model:Map.Model; - defaults:Map.Model; + model: Map.Model; + defaults: Map.Model; /** Method for navigating to specific shape based on latitude, longitude and zoom level. * @param {number} Pass the latitude value for map @@ -54156,7 +56760,7 @@ class Map extends ej.Widget { */ zoom(level: number, isAnimate: boolean): void; } -export module Map{ +export namespace Map { export interface Model { @@ -54205,31 +56809,31 @@ export interface Model { /** Layer for holding the map shapes */ - layers?: Array; + layers?: Layer[]; /** Triggered on selecting the map markers. */ - markerSelected? (e: MarkerSelectedEventArgs): void; + markerSelected?(e: MarkerSelectedEventArgs): void; /** Triggers while leaving the hovered map shape */ - mouseleave? (e: MouseleaveEventArgs): void; + mouseleave?(e: MouseleaveEventArgs): void; /** Triggers while hovering the map shape. */ - mouseover? (e: MouseoverEventArgs): void; + mouseover?(e: MouseoverEventArgs): void; /** Triggers once map render completed. */ - onRenderComplete? (e: OnRenderCompleteEventArgs): void; + onRenderComplete?(e: OnRenderCompleteEventArgs): void; /** Triggers when map panning ends. */ - panned? (e: PannedEventArgs): void; + panned?(e: PannedEventArgs): void; /** Triggered on selecting the map shapes. */ - shapeSelected? (e: ShapeSelectedEventArgs): void; + shapeSelected?(e: ShapeSelectedEventArgs): void; /** Triggered when map is zoomed-in. */ - zoomedIn? (e: ZoomedInEventArgs): void; + zoomedIn?(e: ZoomedInEventArgs): void; /** Triggers when map is zoomed out. */ - zoomedOut? (e: ZoomedOutEventArgs): void; + zoomedOut?(e: ZoomedOutEventArgs): void; } export interface MarkerSelectedEventArgs { @@ -54371,7 +56975,7 @@ export interface LayersBubbleSettingsColorMappingsRangeColorMapping { /** GradientColors in the bubble layer of map. */ - gradientColors?: Array; + gradientColors?: any[]; /** Color of the bubble layer. * @Default {null} @@ -54384,7 +56988,7 @@ export interface LayersBubbleSettingsColorMappings { /** Specifies the range colorMappings in the bubble layer. * @Default {null} */ - rangeColorMapping?: Array; + rangeColorMapping?: LayersBubbleSettingsColorMappingsRangeColorMapping[]; } export interface LayersBubbleSettings { @@ -54445,7 +57049,7 @@ export interface LayersLabelSettings { /** enable or disable the enableSmartLabel property * @Default {false} */ - enableSmartLabel?: Boolean; + enableSmartLabel?: boolean; /** set the labelLength property * @Default {'2'} @@ -54576,7 +57180,7 @@ export interface LayersShapeSettingsColorMappingsRangeColorMapping { /** Specifies the gradientColors in the shape layer of map. * @Default {null} */ - gradientColors?: Array; + gradientColors?: any[]; } export interface LayersShapeSettingsColorMappingsEqualColorMapping { @@ -54597,12 +57201,12 @@ export interface LayersShapeSettingsColorMappings { /** Specifies the range colorMappings in the shape layer of map. * @Default {null} */ - rangeColorMapping?: Array; + rangeColorMapping?: LayersShapeSettingsColorMappingsRangeColorMapping[]; /** Specifies the equalColorMapping in the shape layer of map. * @Default {null} */ - equalColorMapping?: Array; + equalColorMapping?: LayersShapeSettingsColorMappingsEqualColorMapping[]; } export interface LayersShapeSettings { @@ -54725,6 +57329,11 @@ export interface Layer { */ labelSettings?: LayersLabelSettings; + /** Specifies the map view type. + * @Default {'geographic'} + */ + geometryType?: ej.datavisualization.Map.GeometryType|string; + /** Specifies the map type. * @Default {'geometry'} */ @@ -54741,7 +57350,7 @@ export interface Layer { /** Specify markers for shape layer. * @Default {[]} */ - markers?: Array; + markers?: any[]; /** Specifies the map marker template for map layer. * @Default {null} @@ -54751,7 +57360,7 @@ export interface Layer { /** Specify selectedMapShapes for shape layer * @Default {[]} */ - selectedMapShapes?: Array; + selectedMapShapes?: any[]; /** Specifies the selection mode of the map. Accepted selection mode values are Default and Multiple. * @Default {default} @@ -54786,10 +57395,8 @@ export interface Layer { urlTemplate?: string; } } -module Map -{ -enum Position -{ +namespace Map { +enum Position { //specifies the none position None, //specifies the topleft position @@ -54812,20 +57419,16 @@ Bottomcenter, Bottomright, } } -module Map -{ -enum LabelOrientation -{ +namespace Map { +enum LabelOrientation { //specifies the horizontal position Horizontal, //specifies the vertical position Vertical, } } -module Map -{ -enum BingMapType -{ +namespace Map { +enum BingMapType { //specifies the aerial type Aerial, //specifies the aerialwithlabel type @@ -54834,20 +57437,24 @@ Aerialwithlabel, Road, } } -module Map -{ -enum LabelSize -{ +namespace Map { +enum LabelSize { //specifies the fixed size Fixed, //specifies the default size Default, } } -module Map -{ -enum LayerType -{ +namespace Map { +enum GeometryType { +//specifies the geographic view of map +Geographic, +//specifies the normal land view of map +Normal, +} +} +namespace Map { +enum LayerType { //specifies the geometry type Geometry, //specifies the osm type @@ -54856,10 +57463,8 @@ Osm, Bing, } } -module Map -{ -enum DockPosition -{ +namespace Map { +enum DockPosition { //specifies the top position Top, //specifies the bottom position @@ -54870,50 +57475,40 @@ Right, Left, } } -module Map -{ -enum LegendIcons -{ +namespace Map { +enum LegendIcons { //specifies the rectangle position Rectangle, //specifies the circle position Circle, } } -module Map -{ -enum Mode -{ +namespace Map { +enum Mode { //specifies the default mode Default, //specifies the interactive mode Interactive, } } -module Map -{ -enum LegendType -{ +namespace Map { +enum LegendType { //specifies the layers type Layers, //specifies the bubbles type Bubbles, } } -module Map -{ -enum SelectionMode -{ +namespace Map { +enum SelectionMode { //specifies the default position Default, //specifies the multiple position Multiple, } } -module Map -{ -enum ColorPalette -{ +namespace Map { +enum ColorPalette { //specifies the palette1 color Palette1, //specifies the palette2 color @@ -54927,18 +57522,17 @@ Custompalette, class TreeMap extends ej.Widget { static fn: TreeMap; - constructor(element: JQuery, options?: TreeMap.Model); - constructor(element: Element, options?: TreeMap.Model); + constructor(element: JQuery | Element, options?: TreeMap.Model); static Locale: any; - model:TreeMap.Model; - defaults:TreeMap.Model; + model: TreeMap.Model; + defaults: TreeMap.Model; /** Method to reload treemap with updated values. * @returns {void} */ refresh(): void; } -export module TreeMap{ +export namespace TreeMap { export interface Model { @@ -54989,6 +57583,16 @@ export interface Model { */ drillDownSelectionColor?: string; + /** Specifies whether datasource is hierarchical or not. + * @Default {false} + */ + isHierarchicalDatasource?: boolean; + + /** Specifies the header for parent item during drilldown. This is applicable only for hierarchical data source. + * @Default {null} + */ + header?: string; + /** Enable/Disable the drillDown for treemap * @Default {false} */ @@ -55017,7 +57621,7 @@ export interface Model { /** Specifies the group color mapping of the treemap * @Default {[]} */ - groupColorMapping?: Array; + groupColorMapping?: GroupColorMapping[]; /** Specifies the legend settings of the treemap */ @@ -55065,7 +57669,7 @@ export interface Model { /** Specifies the rangeColorMapping settings of the treemap * @Default {[]} */ - rangeColorMapping?: Array; + rangeColorMapping?: RangeColorMapping[]; /** Specifies the selection mode of treemap item. Accepted selection mode values are Default and Multiple. * @Default {default} @@ -55099,12 +57703,12 @@ export interface Model { /** Hold the treeMapItems to be displayed in treemap * @Default {[]} */ - treeMapItems?: Array; + treeMapItems?: any[]; /** Specify levels of treemap for grouped visualization of data * @Default {[]} */ - levels?: Array; + levels?: Level[]; /** Specifies the weight value path of the treemap * @Default {null} @@ -55112,7 +57716,7 @@ export interface Model { weightValuePath?: string; /** Triggers on treemap item selected. */ - treeMapItemSelected? (e: TreeMapItemSelectedEventArgs): void; + treeMapItemSelected?(e: TreeMapItemSelectedEventArgs): void; } export interface TreeMapItemSelectedEventArgs { @@ -55163,7 +57767,7 @@ export interface PaletteColorMapping { /** Specifies the colors of the paletteColorMapping * @Default {[]} */ - colors?: Array; + colors?: any[]; } export interface GroupColorMapping { @@ -55282,7 +57886,7 @@ export interface RangeColorMapping { /** specifies the gradient colors for th given range value * @Default {[]} */ - gradientColors?: Array; + gradientColors?: any[]; /** Specifies the from value for rangeColorMapping. * @Default {-1} @@ -55372,10 +57976,8 @@ export interface Level { showLabels?: boolean; } } -module TreeMap -{ -enum DockPosition -{ +namespace TreeMap { +enum DockPosition { //specifies the top position Top, //specifies the bottom position @@ -55386,10 +57988,8 @@ Right, Left, } } -module TreeMap -{ -enum ItemsLayoutMode -{ +namespace TreeMap { +enum ItemsLayoutMode { //specifies the squarified as layout type position Squarified, //specifies the sliceanddicehorizontal as layout type position @@ -55400,10 +58000,8 @@ Sliceanddicevertical, Sliceanddiceauto, } } -module TreeMap -{ -enum Position -{ +namespace TreeMap { +enum Position { //specifies the none position None, //specifies the topleft position @@ -55426,30 +58024,24 @@ Bottomcenter, Bottomright, } } -module TreeMap -{ -enum VisibilityMode -{ +namespace TreeMap { +enum VisibilityMode { //specifies the visible mode Top, //specifies the hide on exceeded length mode Hideonexceededlength, } } -module TreeMap -{ -enum selectionMode -{ +namespace TreeMap { +enum selectionMode { //specifies the default mode Default, //specifies the multiple mode Multiple, } } -module TreeMap -{ -enum groupSelectionMode -{ +namespace TreeMap { +enum groupSelectionMode { //specifies the default mode Default, //specifies the multiple mode @@ -55459,11 +58051,10 @@ Multiple, class Diagram extends ej.Widget { static fn: Diagram; - constructor(element: JQuery, options?: Diagram.Model); - constructor(element: Element, options?: Diagram.Model); + constructor(element: JQuery | Element, options?: Diagram.Model); static Locale: any; - model:Diagram.Model; - defaults:Diagram.Model; + model: Diagram.Model; + defaults: Diagram.Model; /** Add nodes and connectors to diagram at runtime * @param {any} a JSON to define a node/connector or an array of nodes and connector @@ -55478,6 +58069,13 @@ class Diagram extends ej.Widget { */ addLabel(nodeName: string, newLabel: any): void; + /** Add dynamic Lanes to swimlane at runtime + * @param {any} JSON for the new lane to be added + * @param {number} Index value to add the lane in swimlane + * @returns {void} + */ + addLane(lane: any, index: number): void; + /** Add a phase to a swimlane at runtime * @param {string} name of the swimlane to which the phase will be added * @param {any} JSON object to define the phase to be added @@ -55490,7 +58088,7 @@ class Diagram extends ej.Widget { * @param {Array} a collection of ports to be added to the specified node * @returns {void} */ - addPorts(name: string, ports: Array): void; + addPorts(name: string, ports: any[]): void; /** Add the specified node to selection list * @param {any} the node to be selected @@ -55548,7 +58146,7 @@ class Diagram extends ej.Widget { cut(): void; /** Export the diagram as downloadable files or as data - * @param {Diagram.Options} options to export the desired region of diagram to the desired formats.NameTypeDescriptionfileNamestringname of the file to be downloaded.formatstringformat of the exported file/data. See [File Formats](/api/js/global#fileformats).modestringto set whether to export diagram as a file or as raw data. See [Export Modes](/api/js/global#exportmodes).regionstringto set the region of the diagram to be exported. See [Region](/api/js/global#region).boundsobjectto export any custom region of diagram.marginobjectto set margin to the exported data. + * @param {Diagram.Options} options to export the desired region of diagram to the desired formats. * @returns {string} */ exportDiagram(options?: Diagram.Options): string; @@ -55771,12 +58369,12 @@ class Diagram extends ej.Widget { upgrade(data: any): void; /** Used to zoomIn/zoomOut diagram - * @param {any} options to zoom the diagram(zoom factor, zoomIn/zoomOut) + * @param {Diagram.Zoom} options to zoom the diagram(zoom factor, zoomIn/zoomOut) * @returns {void} */ - zoomTo(zoom: any): void; + zoomTo(Zoom?: Diagram.Zoom): void; } -export module Diagram{ +export namespace Diagram { export interface Options { @@ -55803,6 +58401,25 @@ export interface Options { /** to set margin to the exported data. */ margin?: any; + + /** to set stretch to the exported data. + */ + stretch?: string; +} + +export interface Zoom { + + /** Used to increase the zoom-in or zoom-out based on the zoom factor value. + */ + zoomFactor?: number; + + /** Used to zoom-in or zoom-out the diagram. + */ + zoomCommand?: ej.datavisualization.Diagram.ZoomCommand; + + /** Used to zoom-in or zoom-out the diagram based on the point. + */ + focusPoint?: ej.datavisualization.Diagram.ConnectorsSourcePoint; } export interface Model { @@ -55828,7 +58445,7 @@ export interface Model { /** A collection of JSON objects where each object represents a connector * @Default {[]} */ - connectors?: Array; + connectors?: Connector[]; /** Binds the custom JSON data with connector properties * @Default {null} @@ -55877,6 +58494,11 @@ export interface Model { */ historyManager?: HistoryManager; + /** Defines the type of the rendering mode of label. + * @Default {Html} + */ + labelRenderingMode?: ej.datavisualization.Diagram.LabelRenderingMode|string; + /** Automatically arranges the nodes and connectors in a predefined manner. */ layout?: Layout; @@ -55889,7 +58511,7 @@ export interface Model { /** Array of JSON objects where each object represents a node * @Default {[]} */ - nodes?: Array; + nodes?: Node[]; /** Binds the custom JSON data with node properties * @Default {null} @@ -55938,94 +58560,94 @@ export interface Model { zoomFactor?: number; /** Triggers When auto scroll is changed */ - autoScrollChange? (e: AutoScrollChangeEventArgs): void; + autoScrollChange?(e: AutoScrollChangeEventArgs): void; /** Triggers when a node, connector or diagram is clicked */ - click? (e: ClickEventArgs): void; + click?(e: ClickEventArgs): void; /** Triggers when the connection is changed */ - connectionChange? (e: ConnectionChangeEventArgs): void; + connectionChange?(e: ConnectionChangeEventArgs): void; /** Triggers when the connector collection is changed */ - connectorCollectionChange? (e: ConnectorCollectionChangeEventArgs): void; + connectorCollectionChange?(e: ConnectorCollectionChangeEventArgs): void; /** Triggers when the connectors' source point is changed */ - connectorSourceChange? (e: ConnectorSourceChangeEventArgs): void; + connectorSourceChange?(e: ConnectorSourceChangeEventArgs): void; /** Triggers when the connectors' target point is changed */ - connectorTargetChange? (e: ConnectorTargetChangeEventArgs): void; + connectorTargetChange?(e: ConnectorTargetChangeEventArgs): void; /** Triggers before opening the context menu */ - contextMenuBeforeOpen? (e: ContextMenuBeforeOpenEventArgs): void; + contextMenuBeforeOpen?(e: ContextMenuBeforeOpenEventArgs): void; /** Triggers when a context menu item is clicked */ - contextMenuClick? (e: ContextMenuClickEventArgs): void; + contextMenuClick?(e: ContextMenuClickEventArgs): void; /** Triggers when a node, connector or diagram model is clicked twice */ - doubleClick? (e: DoubleClickEventArgs): void; + doubleClick?(e: DoubleClickEventArgs): void; /** Triggers while dragging the elements in diagram */ - drag? (e: DragEventArgs): void; + drag?(e: DragEventArgs): void; /** Triggers when a symbol is dragged into diagram from symbol palette */ - dragEnter? (e: DragEnterEventArgs): void; + dragEnter?(e: DragEnterEventArgs): void; /** Triggers when a symbol is dragged outside of the diagram. */ - dragLeave? (e: DragLeaveEventArgs): void; + dragLeave?(e: DragLeaveEventArgs): void; /** Triggers when a symbol is dragged over diagram */ - dragOver? (e: DragOverEventArgs): void; + dragOver?(e: DragOverEventArgs): void; /** Triggers when a symbol is dragged and dropped from symbol palette to drawing area */ - drop? (e: DropEventArgs): void; + drop?(e: DropEventArgs): void; /** Triggers when editor got focus at the time of node's label or text node editing. */ - editorFocusChange? (e: EditorFocusChangeEventArgs): void; + editorFocusChange?(e: EditorFocusChangeEventArgs): void; /** Triggers when a child is added to or removed from a group */ - groupChange? (e: GroupChangeEventArgs): void; + groupChange?(e: GroupChangeEventArgs): void; /** Triggers when a change is reverted or restored(undo/redo) */ - historyChange? (e: HistoryChangeEventArgs): void; + historyChange?(e: HistoryChangeEventArgs): void; /** Triggers when a diagram element is clicked */ - itemClick? (e: ItemClickEventArgs): void; + itemClick?(e: ItemClickEventArgs): void; /** Triggers when mouse enters a node/connector */ - mouseEnter? (e: MouseEnterEventArgs): void; + mouseEnter?(e: MouseEnterEventArgs): void; /** Triggers when mouse leaves node/connector */ - mouseLeave? (e: MouseLeaveEventArgs): void; + mouseLeave?(e: MouseLeaveEventArgs): void; /** Triggers when mouse hovers over a node/connector */ - mouseOver? (e: MouseOverEventArgs): void; + mouseOver?(e: MouseOverEventArgs): void; /** Triggers when node collection is changed */ - nodeCollectionChange? (e: NodeCollectionChangeEventArgs): void; + nodeCollectionChange?(e: NodeCollectionChangeEventArgs): void; /** Triggers when the node properties(x, y,width and height alone) are changed using nudge commands or updateNode API. */ - propertyChange? (e: PropertyChangeEventArgs): void; + propertyChange?(e: PropertyChangeEventArgs): void; /** Triggers when the diagram elements are rotated */ - rotationChange? (e: RotationChangeEventArgs): void; + rotationChange?(e: RotationChangeEventArgs): void; /** Triggers when the diagram is zoomed or panned */ - scrollChange? (e: ScrollChangeEventArgs): void; + scrollChange?(e: ScrollChangeEventArgs): void; /** Triggers when a connector segment is edited */ - segmentChange? (e: SegmentChangeEventArgs): void; + segmentChange?(e: SegmentChangeEventArgs): void; /** Triggers when the selection is changed in diagram */ - selectionChange? (e: SelectionChangeEventArgs): void; + selectionChange?(e: SelectionChangeEventArgs): void; /** Triggers when a node is resized */ - sizeChange? (e: SizeChangeEventArgs): void; + sizeChange?(e: SizeChangeEventArgs): void; /** Triggers when label editing is ended */ - textChange? (e: TextChangeEventArgs): void; + textChange?(e: TextChangeEventArgs): void; /** Triggered when the diagram is rendered completely. */ - create? (e: CreateEventArgs): void; + create?(e: CreateEventArgs): void; } export interface AutoScrollChangeEventArgs { @@ -56355,6 +58977,9 @@ export interface DropEventArgs { } export interface EditorFocusChangeEventArgs { + /** Returns the cancel option value. + */ + cancel?: boolean; } export interface GroupChangeEventArgs { @@ -56384,11 +59009,11 @@ export interface HistoryChangeEventArgs { /** An array of objects, where each object represents the changes made in last undo/redo. To explore how the changes are defined, refer [Undo Redo Changes](#undo-redo-changes) */ - changes?: Array; + changes?: any[]; /** A collection of objects that are changed in the last undo/redo */ - Source?: Array; + Source?: any[]; /** parameter returns the id of the diagram */ @@ -56598,15 +59223,15 @@ export interface SelectionChangeEventArgs { /** parameter returns the collection of nodes and connectors that have to be removed from selection list */ - oldItems?: Array; + oldItems?: any[]; /** parameter returns the collection of nodes and connectors that have to be added to selection list */ - newItems?: Array; + newItems?: any[]; /** parameter returns the collection of nodes and connectors that will be selected after selection change */ - selectedItems?: Array; + selectedItems?: any[]; /** parameter to specify whether or not to cancel the selection change event */ @@ -56711,11 +59336,11 @@ export interface CommandManagerCommands { /** A method that defines whether the command is executable at the moment or not. */ - canExecute?: Function; + canExecute?: any; /** A method that defines what to be executed when the key combination is recognized. */ - execute?: Function; + execute?: any; /** Defines a combination of keys and key modifiers, on recognition of which the command will be executed */ @@ -56810,6 +59435,11 @@ export interface ConnectorsLabel { */ horizontalAlignment?: ej.datavisualization.Diagram.HorizontalAlignment|string; + /** Sets the hyperlink for the labels in the connectors. + * @Default {none} + */ + hyperlink?: string; + /** Enables/disables the italic style * @Default {false} */ @@ -57007,6 +59637,11 @@ export interface ConnectorsShape { * @Default {null} */ multiplicity?: ConnectorsShapeMultiplicity; + + /** Defines the shape of UMLActivity to connector. Applicable, if the connector is of type UMLActivity + * @Default {ej.datavisualization.Diagram.UMLActivityFlow.Control} + */ + ActivityFlow?: ej.datavisualization.Diagram.UMLActivityFlow|string; } export interface ConnectorsSourceDecorator { @@ -57125,7 +59760,7 @@ export interface Connector { /** A collection of JSON objects where each object represents a label. * @Default {[]} */ - labels?: Array; + labels?: ConnectorsLabel[]; /** Sets the stroke color of the connector * @Default {black} @@ -57187,7 +59822,7 @@ export interface Connector { /** An array of JSON objects where each object represents a segment * @Default {[ { type:straight } ]} */ - segments?: Array; + segments?: ConnectorsSegment[]; /** Defines the role/meaning of the connector * @Default {null} @@ -57261,12 +59896,40 @@ export interface Connector { zOrder?: number; } +export interface ContextMenuItem { + + /** Defines the text for the collection of context menu item + * @Default {null} + */ + text?: string; + + /** Defines the name for the collection of context menu items + * @Default {null} + */ + name?: string; + + /** Defines the image url for the collection of context menu items + * @Default {null} + */ + imageUrl?: string; + + /** Defines the CssClass for the collection of context menu items + * @Default {null} + */ + cssClass?: string; + + /** Defines the collection of sub items for the context menu items + * @Default {[]} + */ + subItems?: any[]; +} + export interface ContextMenu { /** Defines the collection of context menu items * @Default {[]} */ - items?: Array; + items?: ContextMenuItem[]; /** To set whether to display the default context menu items or not * @Default {false} @@ -57327,29 +59990,29 @@ export interface HistoryManager { /** A method that takes a history entry as argument and returns whether the specific entry can be popped or not */ - canPop?: Function; + canPop?: any; /** A method that ends grouping the changes */ - closeGroupAction?: Function; + closeGroupAction?: any; /** A method that removes the history of a recent change made in diagram */ - pop?: Function; + pop?: any; /** A method that allows to track the custom changes made in diagram */ - push?: Function; + push?: any; /** Defines what should be happened while trying to restore a custom change * @Default {null} */ - redo?: Function; + redo?: any; /** The redoStack property is used to get the number of redo actions to be stored on the history manager. Its an read-only property and the collection should not be modified. * @Default {[]} */ - redoStack?: Array; + redoStack?: any[]; /** The stackLimit property used to restrict the undo and redo actions to a certain limit. * @Default {null} @@ -57358,16 +60021,16 @@ export interface HistoryManager { /** A method that starts to group the changes to revert/restore them in a single undo or redo */ - startGroupAction?: Function; + startGroupAction?: any; /** Defines what should be happened while trying to revert a custom change */ - undo?: Function; + undo?: any; /** The undoStack property is used to get the number of undo actions to be stored on the history manager. Its an read-only property and the collection should not be modified. * @Default {[]} */ - undoStack?: Array; + undoStack?: any[]; } export interface Layout { @@ -57487,12 +60150,12 @@ export interface NodesClass { /** Defines the collection of attributes * @Default {[]} */ - attributes?: Array; + attributes?: NodesClassAttribute[]; /** Defines the collection of methods of a Class. * @Default {[]} */ - methods?: Array; + methods?: NodesClassMethod[]; } export interface NodesCollapseIcon { @@ -57585,7 +60248,7 @@ export interface NodesEnumeration { /** Defines the collection of enumeration members * @Default {[]} */ - members?: Array; + members?: NodesEnumerationMember[]; } export interface NodesExpandIcon { @@ -57641,7 +60304,7 @@ export interface NodesGradientLinearGradient { /** Defines the different colors and the region of color transitions * @Default {[]} */ - stops?: Array; + stops?: any[]; /** Defines the left most position(relative to node) of the rectangular region that needs to be painted * @Default {0} @@ -57689,7 +60352,7 @@ export interface NodesGradientRadialGradient { /** Defines the different colors and the region of color transitions. * @Default {[]} */ - stops?: Array; + stops?: any[]; } export interface NodesGradientStop { @@ -57755,12 +60418,12 @@ export interface NodesInterface { /** Defines a collection of attributes of the interface * @Default {[]} */ - attributes?: Array; + attributes?: NodesInterfaceAttribute[]; /** Defines the collection of public methods of an interface * @Default {[]} */ - methods?: Array; + methods?: NodesInterfaceMethod[]; } export interface NodesLabel { @@ -57834,6 +60497,11 @@ export interface NodesLabel { */ opacity?: number; + /** Sets the overflowType of the labels + * @Default {ej.datavisualization.Diagram.OverflowType.Ellipsis} + */ + overflowType?: ej.datavisualization.Diagram.OverflowType|string; + /** Defines whether the label is editable or not * @Default {false} */ @@ -57858,6 +60526,11 @@ export interface NodesLabel { */ textDecoration?: ej.datavisualization.Diagram.TextDecorations|string; + /** Defines the overflowed content is displayed or not. + * @Default {false} + */ + textOverflow?: boolean; + /** Sets the vertical alignment of the label. * @Default {ej.datavisualization.Diagram.VerticalAlignment.Center} */ @@ -57904,7 +60577,7 @@ export interface NodesLane { /** An array of objects where each object represents a child node of the lane * @Default {[]} */ - children?: Array; + children?: any[]; /** Defines the fill color of the lane * @Default {white} @@ -58109,7 +60782,7 @@ export interface NodesSubProcess { /** Defines the collection of events that need to be appended with BPMN Sub-Process */ - events?: Array; + events?: any[]; /** Defines the loop type of a sub process. * @Default {ej.datavisualization.Diagram.BPMNLoops.None} @@ -58119,7 +60792,7 @@ export interface NodesSubProcess { /** Defines the children for BPMN's SubProcess * @Default {[]} */ - Processes?: Array; + Processes?: any[]; /** Defines the type of the event trigger * @Default {ej.datavisualization.Diagram.BPMNTriggers.Message} @@ -58194,7 +60867,7 @@ export interface Node { /** Array of JSON objects where each object represents a child node/connector * @Default {[]} */ - children?: Array; + children?: any[]; /** Sets the type of UML classifier. Applicable, if the node is a UML Class Diagram shape. * @Default {ej.datavisualization.Diagram.ClassifierShapes.Class} @@ -58294,7 +60967,7 @@ export interface Node { /** A read only collection of the incoming connectors/edges of the node * @Default {[]} */ - inEdges?: Array; + inEdges?: any[]; /** Defines an interface in a UML Class Diagram * @Default {null} @@ -58314,12 +60987,12 @@ export interface Node { /** A collection of objects where each object represents a label * @Default {[]} */ - labels?: Array; + labels?: NodesLabel[]; /** An array of objects where each object represents a lane. Applicable, if the node is a swimlane. * @Default {[]} */ - lanes?: Array; + lanes?: NodesLane[]; /** Defines the minimum space to be left between the bottom of parent bounds and the node. Applicable, if the parent is a container. * @Default {0} @@ -58388,7 +61061,7 @@ export interface Node { /** A read only collection of outgoing connectors/edges of the node * @Default {[]} */ - outEdges?: Array; + outEdges?: any[]; /** Defines the minimum padding value to be left between the bottom most position of a group and its children. Applicable, if the group is a container. * @Default {0} @@ -58426,7 +61099,7 @@ export interface Node { /** An array of objects, where each object represents a smaller region(phase) of a swimlane. * @Default {[]} */ - phases?: Array; + phases?: NodesPhase[]; /** Sets the height of the phase headers * @Default {0} @@ -58441,12 +61114,12 @@ export interface Node { /** Defines a collection of points to draw a polygon. Applicable, if the shape is a polygon. * @Default {[]} */ - points?: Array; + points?: any[]; /** An array of objects where each object represents a port * @Default {[]} */ - ports?: Array; + ports?: NodesPort[]; /** Sets the angle to which the node should be rotated * @Default {0} @@ -58461,7 +61134,7 @@ export interface Node { /** Sets the shape of the node. It depends upon the type of node. * @Default {ej.datavisualization.Diagram.BasicShapes.Rectangle} */ - shape?: ej.datavisualization.Diagram.BasicShapes|string; + shape?: ej.datavisualization.Diagram.BasicShapes | ej.datavisualization.Diagram.FlowShapes | ej.datavisualization.Diagram.BPMNShapes | ej.datavisualization.Diagram.UMLActivityShapes|string; /** Sets the source path of the image. Applicable, if the type of the node is image. */ @@ -58674,7 +61347,7 @@ export interface SelectedItems { /** A read only collection of the selected items * @Default {[]} */ - children?: Array; + children?: any[]; /** Controls the visibility of selector. * @Default {ej.datavisualization.Diagram.SelectorConstraints.All} @@ -58714,7 +61387,7 @@ export interface SelectedItems { /** A collection of frequently used commands that will be added around the selector * @Default {[]} */ - userHandles?: Array; + userHandles?: SelectedItemsUserHandle[]; /** Sets the width of the selected items * @Default {0} @@ -58736,12 +61409,12 @@ export interface SnapSettingsHorizontalGridLines { /** A pattern of lines and gaps that defines a set of horizontal gridlines * @Default {[1.25, 18.75, 0.25, 19.75, 0.25, 19.75, 0.25, 19.75, 0.25, 19.75]} */ - linesInterval?: Array; + linesInterval?: any[]; /** Specifies a set of intervals to snap the objects * @Default {[20]} */ - snapInterval?: Array; + snapInterval?: any[]; } export interface SnapSettingsVerticalGridLines { @@ -58758,12 +61431,12 @@ export interface SnapSettingsVerticalGridLines { /** A pattern of lines and gaps that defines a set of horizontal gridlines * @Default {[1.25, 18.75, 0.25, 19.75, 0.25, 19.75, 0.25, 19.75, 0.25, 19.75]} */ - linesInterval?: Array; + linesInterval?: any[]; /** Specifies a set of intervals to snap the objects * @Default {[20]} */ - snapInterval?: Array; + snapInterval?: any[]; } export interface SnapSettings { @@ -58830,10 +61503,8 @@ export interface Tooltip { templateId?: string; } } -module Diagram -{ -enum ImageAlignment -{ +namespace Diagram { +enum ImageAlignment { //Scales the graphic content non-uniformly to the width and height of the diagram area None, //Used to align the image at the top left of diagram area @@ -58856,10 +61527,8 @@ XMaxYMid, XMaxYMax, } } -module Diagram -{ -enum BridgeDirection -{ +namespace Diagram { +enum BridgeDirection { //Used to set the direction of line bridges as left Left, //Used to set the direction of line bridges as right @@ -58870,10 +61539,8 @@ Top, Bottom, } } -module Diagram -{ -enum Keys -{ +namespace Diagram { +enum Keys { //No key pressed. None, //The A key. @@ -58966,10 +61633,8 @@ Tab, Enter, } } -module Diagram -{ -enum KeyModifiers -{ +namespace Diagram { +enum KeyModifiers { //No modifiers are pressed. None, //The ALT key. @@ -58980,10 +61645,8 @@ Control, Shift, } } -module Diagram -{ -enum ConnectorConstraints -{ +namespace Diagram { +enum ConnectorConstraints { //Disable all connector Constraints None, //Enables connector to be selected @@ -59012,10 +61675,8 @@ CrispEdges, Default, } } -module Diagram -{ -enum HorizontalAlignment -{ +namespace Diagram { +enum HorizontalAlignment { //Used to align text horizontally on left side of node/connector Left, //Used to align text horizontally on center of node/connector @@ -59024,10 +61685,8 @@ Center, Right, } } -module Diagram -{ -enum Alignment -{ +namespace Diagram { +enum Alignment { //Used to align the label either top or left(before) of the connector segment Before, //Used to align the label at center of the connector segment @@ -59036,20 +61695,16 @@ Center, After, } } -module Diagram -{ -enum LabelRelativeMode -{ +namespace Diagram { +enum LabelRelativeMode { //Sets the relativeMode as SegmentPath SegmentPath, //Sets the relativeMode as SegmentBounds SegmentBounds, } } -module Diagram -{ -enum Segments -{ +namespace Diagram { +enum Segments { //Used to specify the lines as Straight Straight, //Used to specify the lines as Orthogonal @@ -59058,20 +61713,18 @@ Orthogonal, Bezier, } } -module Diagram -{ -enum ConnectorShapes -{ +namespace Diagram { +enum ConnectorShapes { //Used to specify connector type as BPMN BPMN, -//Used to specify connector type as Classifier -Classifier, +//Used to specify connector type as UMLClassifier +UMLClassifier, +//Used to specify connector type as UMLActivity +UMLActivity, } } -module Diagram -{ -enum BPMNFlows -{ +namespace Diagram { +enum BPMNFlows { //Used to specify the Sequence flow in a BPMN Process Sequence, //Used to specify the Association flow in a BPMN Process @@ -59080,10 +61733,8 @@ Association, Message, } } -module Diagram -{ -enum AssociationFlows -{ +namespace Diagram { +enum AssociationFlows { //Used to notate default association in a BPMN Process Default, //Used to notate directional association in a BPMN Process @@ -59092,10 +61743,8 @@ Directional, BiDirectional, } } -module Diagram -{ -enum BPMNMessageFlows -{ +namespace Diagram { +enum BPMNMessageFlows { //Used to notate the default message flow in a BPMN Process Default, //Used to notate the instantiating message flow in a BPMN Process @@ -59104,10 +61753,8 @@ InitiatingMessage, NonInitiatingMessage, } } -module Diagram -{ -enum BPMNSequenceFlows -{ +namespace Diagram { +enum BPMNSequenceFlows { //Used to notate the normal sequence flow in a BPMN Process Normal, //Used to notate the conditional sequence flow in a BPMN Process @@ -59116,10 +61763,8 @@ Conditional, Default, } } -module Diagram -{ -enum ClassifierShapes -{ +namespace Diagram { +enum ClassifierShapes { //Used to define a Class Class, //Used to define an Interface @@ -59138,10 +61783,8 @@ Dependency, Inheritance, } } -module Diagram -{ -enum Multiplicity -{ +namespace Diagram { +enum Multiplicity { //Each entity instance is related to a single instance of another entity OneToOne, //An entity instance can be related to multiple instances of the other entities @@ -59152,10 +61795,18 @@ ManyToOne, ManyToMany, } } -module Diagram -{ -enum DecoratorShapes -{ +namespace Diagram { +enum UMLActivityFlow { +//Defines a activity flow as Object in UML Activity Diagram +Object, +//Defines a activity flow as Control in UML Activity Diagram +Control, +//Defines a activity flow as Exception in UML Activity Diagram +Exception, +} +} +namespace Diagram { +enum DecoratorShapes { //Used to set decorator shape as none None, //Used to set decorator shape as Arrow @@ -59170,10 +61821,8 @@ Diamond, Path, } } -module Diagram -{ -enum VerticalAlignment -{ +namespace Diagram { +enum VerticalAlignment { //Used to align text Vertically on left side of node/connector Top, //Used to align text Vertically on center of node/connector @@ -59182,10 +61831,8 @@ Center, Bottom, } } -module Diagram -{ -enum DiagramConstraints -{ +namespace Diagram { +enum DiagramConstraints { //Disables all DiagramConstraints None, //Enables/Disables PageEditing @@ -59208,10 +61855,16 @@ CrispEdges, Default, } } -module Diagram -{ -enum LayoutOrientations -{ +namespace Diagram { +enum LabelRenderingMode { +//Sets the labelRenderingMode as Html +Html, +//Sets the labelRenderingMode as Svg +Svg, +} +} +namespace Diagram { +enum LayoutOrientations { //Used to set LayoutOrientation from top to bottom TopToBottom, //Used to set LayoutOrientation from bottom to top @@ -59222,10 +61875,8 @@ LeftToRight, RightToLeft, } } -module Diagram -{ -enum LayoutTypes -{ +namespace Diagram { +enum LayoutTypes { //Used not to set any specific layout None, //Used to set layout type as hierarchical layout @@ -59234,10 +61885,8 @@ HierarchicalTree, OrganizationalChart, } } -module Diagram -{ -enum BPMNActivity -{ +namespace Diagram { +enum BPMNActivity { //Used to set BPMN Activity as None None, //Used to set BPMN Activity as Task @@ -59246,10 +61895,8 @@ Task, SubProcess, } } -module Diagram -{ -enum BPMNAnnotationDirection -{ +namespace Diagram { +enum BPMNAnnotationDirection { //Used to set the direction of BPMN Annotation as left Left, //Used to set the direction of BPMN Annotation as right @@ -59260,10 +61907,8 @@ Top, Bottom, } } -module Diagram -{ -enum IconShapes -{ +namespace Diagram { +enum IconShapes { //Used to set collapse icon shape as none None, //Used to set collapse icon shape as Arrow(Up/Down) @@ -59280,10 +61925,8 @@ Template, Image, } } -module Diagram -{ -enum NodeConstraints -{ +namespace Diagram { +enum NodeConstraints { //Disable all node Constraints None, //Enables node to be selected @@ -59330,20 +61973,16 @@ CrispEdges, Default, } } -module Diagram -{ -enum ContainerType -{ +namespace Diagram { +enum ContainerType { //Sets the container type as Canvas Canvas, //Sets the container type as Stack Stack, } } -module Diagram -{ -enum BPMNDataObjects -{ +namespace Diagram { +enum BPMNDataObjects { //Used to notate the Input type BPMN data object Input, //Used to notate the Output type BPMN data object @@ -59352,10 +61991,8 @@ Output, None, } } -module Diagram -{ -enum BPMNEvents -{ +namespace Diagram { +enum BPMNEvents { //Used to set BPMN Event as Start Start, //Used to set BPMN Event as Intermediate @@ -59370,10 +62007,8 @@ NonInterruptingIntermediate, ThrowingIntermediate, } } -module Diagram -{ -enum BPMNGateways -{ +namespace Diagram { +enum BPMNGateways { //Used to set BPMN Gateway as None None, //Used to set BPMN Gateway as Exclusive @@ -59392,20 +62027,24 @@ ExclusiveEventBased, ParallelEventBased, } } -module Diagram -{ -enum LabelEditMode -{ +namespace Diagram { +enum LabelEditMode { //Used to set label edit mode as edit Edit, //Used to set label edit mode as view View, } } -module Diagram -{ -enum TextAlign -{ +namespace Diagram { +enum OverflowType { +//Set overflow Type as ellipsis +Ellipsis, +//Set overflow Type as Clip +Clip, +} +} +namespace Diagram { +enum TextAlign { //Used to align text on left side of node/connector Left, //Used to align text on center of node/connector @@ -59414,10 +62053,8 @@ Center, Right, } } -module Diagram -{ -enum TextDecorations -{ +namespace Diagram { +enum TextDecorations { //Used to set text decoration of the label as Underline Underline, //Used to set text decoration of the label as Overline @@ -59428,10 +62065,8 @@ LineThrough, None, } } -module Diagram -{ -enum TextWrapping -{ +namespace Diagram { +enum TextWrapping { //Disables wrapping NoWrap, //Enables Line-break at normal word break points @@ -59440,10 +62075,8 @@ Wrap, WrapWithOverflow, } } -module Diagram -{ -enum PortConstraints -{ +namespace Diagram { +enum PortConstraints { //Disable all constraints None, //Enables connections with connector @@ -59452,10 +62085,8 @@ Connect, ConnectOnDrag, } } -module Diagram -{ -enum PortShapes -{ +namespace Diagram { +enum PortShapes { //Used to set port shape as X X, //Used to set port shape as Circle @@ -59466,10 +62097,8 @@ Square, Path, } } -module Diagram -{ -enum PortVisibility -{ +namespace Diagram { +enum PortVisibility { //Set the port visibility as Visible Visible, //Set the port visibility as Hidden @@ -59482,10 +62111,8 @@ Connect, Default, } } -module Diagram -{ -enum BasicShapes -{ +namespace Diagram { +enum BasicShapes { //Used to specify node Shape as Rectangle Rectangle, //Used to specify node Shape as Ellipse @@ -59516,10 +62143,106 @@ RightTriangle, Cylinder, } } -module Diagram -{ -enum BPMNBoundary -{ +namespace Diagram { +enum FlowShapes { +//Used to specify node Shape as Process +Process, +//Used to specify node Shape as Decision +Decision, +//Used to specify node Shape as Document +Document, +//Used to specify node Shape as PreDefinedProcess +PreDefinedProcess, +//Used to specify node Shape as Terminator +Terminator, +//Used to specify node Shape as PaperTap +PaperTap, +//Used to specify node Shape as DirectData +DirectData, +//Used to specify node Shape as SequentialData +SequentialData, +//Used to specify node Shape as Sort +Sort, +//Used to specify node Shape as MultiDocument +MultiDocument, +//Used to specify node Shape as Collate +Collate, +//Used to specify node Shape as SummingJunction +SummingJunction, +//Used to specify node Shape as Or +Or, +//Used to specify node Shape as InternalStorage +InternalStorage, +//Used to specify node Shape as Extract +Extract, +//Used to specify node Shape as ManualOperation +ManualOperation, +//Used to specify node Shape as Merge +Merge, +//Used to specify node Shape as OffPageReference +OffPageReference, +//Used to specify node Shape as SequentialAccessStorage +SequentialAccessStorage, +//Used to specify node Shape as Annotation1 +Annotation1, +//Used to specify node Shape as Annotation2 +Annotation2, +//Used to specify node Shape as Data +Data, +//Used to specify node Shape as Card +Card, +} +} +namespace Diagram { +enum BPMNShapes { +//Used to specify node Shape as Event +Event, +//Used to specify node Shape as Gateway +Gateway, +//Used to specify node Shape as Message +Message, +//Used to specify node Shape as DataObject +DataObject, +//Used to specify node Shape as DataSource +DataSource, +//Used to specify node Shape as Activity +Activity, +//Used to specify node Shape as Group +Group, +} +} +namespace Diagram { +enum UMLActivityShapes { +//Used to set UML ActivityShapes as Action +Action, +//Used to set UML ActivityShapes as Decision +Decision, +//Used to set UML ActivityShapes as MergeNode +MergeNode, +//Used to set UML ActivityShapes as InitialNode +InitialNode, +//Used to set UML ActivityShapes as FinalNode +FinalNode, +//Used to set UML ActivityShapes as ForkNode +ForkNode, +//Used to set UML ActivityShapes as JoinNode +JoinNode, +//Used to set UML ActivityShapes as TimeEvent +TimeEvent, +//Used to set UML ActivityShapes as AcceptingEvent +AcceptingEvent, +//Used to set UML ActivityShapes as SendSignal +SendSignal, +//Used to set UML ActivityShapes as ReceiveSignal +ReceiveSignal, +//Used to set UML ActivityShapes as StructuredNode +StructuredNode, +//Used to set UML ActivityShapes as Note +Note, +} +} +namespace Diagram { +enum BPMNBoundary { //Used to set BPMN SubProcess's Boundary as Default Default, //Used to set BPMN SubProcess's Boundary as Call @@ -59528,10 +62251,8 @@ Call, Event, } } -module Diagram -{ -enum BPMNLoops -{ +namespace Diagram { +enum BPMNLoops { //Used to set BPMN Activity's Loop as None None, //Used to set BPMN Activity's Loop as Standard @@ -59542,10 +62263,8 @@ ParallelMultiInstance, SequenceMultiInstance, } } -module Diagram -{ -enum BPMNSubProcessTypes -{ +namespace Diagram { +enum BPMNSubProcessTypes { //Used to set BPMN SubProcess type as None None, //Used to set BPMN SubProcess type as Transaction @@ -59554,10 +62273,8 @@ Transaction, Event, } } -module Diagram -{ -enum BPMNTasks -{ +namespace Diagram { +enum BPMNTasks { //Used to set BPMN Task Type as None None, //Used to set BPMN Task Type as Service @@ -59580,10 +62297,8 @@ Script, Parallel, } } -module Diagram -{ -enum BPMNTriggers -{ +namespace Diagram { +enum BPMNTriggers { //Used to set Event Trigger as None None, //Used to set Event Trigger as Message @@ -59612,38 +62327,38 @@ Termination, Cancel, } } -module Diagram -{ -enum Shapes -{ -//Used to set decorator shape as none -None, -//Used to set decorator shape as Arrow -Arrow, -//Used to set decorator shape as Open Arrow -OpenArrow, -//Used to set decorator shape as Circle -Circle, -//Used to set decorator shape as Diamond -Diamond, -//Used to set decorator shape as path -Path, +namespace Diagram { +enum Shapes { +//Used to specify node type as Text +Text, +//Used to specify node type as Image +Image, +//Used to specify node type as Html +Html, +//Used to specify node type as Native +Native, +//Used to specify node type as Basic +Basic, +//Used to specify node type as Flow +Flow, +//Used to specify node type as BPMN +BPMN, +//Used to specify node type as UMLClassifier +UMLClassifier, +//Used to specify node type as UMLActivity +UMLActivity, } } -module Diagram -{ -enum PageOrientations -{ +namespace Diagram { +enum PageOrientations { //Used to set orientation as Landscape Landscape, //Used to set orientation as portrait Portrait, } } -module Diagram -{ -enum ScrollLimit -{ +namespace Diagram { +enum ScrollLimit { //Used to set scrollLimit as Infinite Infinite, //Used to set scrollLimit as Diagram @@ -59652,10 +62367,8 @@ Diagram, Limited, } } -module Diagram -{ -enum BoundaryConstraints -{ +namespace Diagram { +enum BoundaryConstraints { //Used to set boundaryConstraints as Infinite Infinite, //Used to set boundaryConstraints as Diagram @@ -59664,10 +62377,8 @@ Diagram, Page, } } -module Diagram -{ -enum SelectorConstraints -{ +namespace Diagram { +enum SelectorConstraints { //Hides the selector None, //Sets the visibility of rotation handle as visible @@ -59680,10 +62391,8 @@ UserHandles, All, } } -module Diagram -{ -enum UserHandlePositions -{ +namespace Diagram { +enum UserHandlePositions { //Set the position of the userhandle as topleft TopLeft, //Set the position of the userhandle as topcenter @@ -59702,10 +62411,8 @@ BottomCenter, BottomRight, } } -module Diagram -{ -enum SnapConstraints -{ +namespace Diagram { +enum SnapConstraints { //Enables node to be snapped to horizontal gridlines None, //Enables node to be snapped to vertical gridlines @@ -59724,10 +62431,8 @@ ShowLines, All, } } -module Diagram -{ -enum Tool -{ +namespace Diagram { +enum Tool { //Disables all Tools None, //Enables/Disables SingleSelect tool @@ -59742,26 +62447,31 @@ DrawOnce, ContinuesDraw, } } -module Diagram -{ -enum RelativeMode -{ +namespace Diagram { +enum RelativeMode { //Shows tooltip around the node Object, //Shows tooltip at the mouse position Mouse, } } +namespace Diagram { +enum ZoomCommand { +//Used to zoom in the Diagram +ZoomIn, +//Used to zoom out the diagram +ZoomOut, +} +} class HeatMap extends ej.Widget { static fn: HeatMap; - constructor(element: JQuery, options?: HeatMap.Model); - constructor(element: Element, options?: HeatMap.Model); + constructor(element: JQuery | Element, options?: HeatMap.Model); static Locale: any; - model:HeatMap.Model; - defaults:HeatMap.Model; + model: HeatMap.Model; + defaults: HeatMap.Model; } -export module HeatMap{ +export namespace HeatMap { export interface Model { @@ -59780,6 +62490,15 @@ export interface Model { */ id?: number; + /** Enables or disables tooltip of heatmap + * @Default {true} + */ + showTooltip?: boolean; + + /** Defines the tooltip that should be shown when the mouse hovers over rows/columns. + */ + tooltipSettings?: TooltipSettings; + /** Specifies the source data of the heat map. * @Default {[]} */ @@ -59808,7 +62527,7 @@ export interface Model { /** Specifies the no of legends can sync with heat map. * @Default {[]} */ - legendCollection?: Array; + legendCollection?: any[]; /** Specifies the property and display value of the heat map column. * @Default {[]} @@ -59818,19 +62537,19 @@ export interface Model { /** Specifies the color values of the heat map column data. * @Default {[]} */ - colorMappingCollection?: Array; + colorMappingCollection?: ColorMappingCollection[]; /** Triggered when the mouse over on the cell. */ - cellMouseOver? (e: CellMouseOverEventArgs): void; + cellMouseOver?(e: CellMouseOverEventArgs): void; /** Triggered when the mouse over on the cell. */ - cellMouseEnter? (e: CellMouseEnterEventArgs): void; + cellMouseEnter?(e: CellMouseEnterEventArgs): void; /** Triggered when the mouse over on the cell. */ - cellMouseLeave? (e: CellMouseLeaveEventArgs): void; + cellMouseLeave?(e: CellMouseLeaveEventArgs): void; /** Triggered when the mouse over on the cell. */ - cellSelected? (e: CellSelectedEventArgs): void; + cellSelected?(e: CellSelectedEventArgs): void; } export interface CellMouseOverEventArgs { @@ -59893,6 +62612,86 @@ export interface CellSelectedEventArgs { cell?: any; } +export interface TooltipSettingsPositionTarget { + + /** Sets the arrow position again popup based on horizontal(x) value + * @Default {center} + */ + horizontal?: ej.datavisualization.HeatMap.Horizontal|string; + + /** Sets the arrow position again popup based on vertical(y) value + * @Default {top} + */ + vertical?: ej.datavisualization.HeatMap.Vertical|string; +} + +export interface TooltipSettingsPositionStem { + + /** Sets the arrow position again popup based on horizontal(x) value + * @Default {center} + */ + horizontal?: ej.datavisualization.HeatMap.Horizontal|string; + + /** Sets the arrow position again popup based on vertical(y) value + * @Default {bottom} + */ + vertical?: ej.datavisualization.HeatMap.Vertical|string; +} + +export interface TooltipSettingsPosition { + + /** Sets the Tooltip position against target. + */ + target?: TooltipSettingsPositionTarget; + + /** Sets the arrow position again popup. + */ + stem?: TooltipSettingsPositionStem; +} + +export interface TooltipSettingsAnimation { + + /** Defines the animation effect for the tooltip that should be shown when the mouse hovers over rows/columns. + * @Default {none} + */ + effect?: ej.datavisualization.HeatMap.Effect|string; + + /** Defines the animation speed for the tooltip that should be shown when the mouse hovers over rows/columns. + * @Default {0} + */ + speed?: number; +} + +export interface TooltipSettings { + + /** Defines the tooltip that should be shown when the mouse hovers over rows/columns. + * @Default {null} + */ + templateId?: string; + + /** Defines the tooltip of associate that should be shown when the mouse hovers over rows/columns. + */ + associate?: ej.datavisualization.HeatMap.Associate|string; + + /** Enables/ disables the balloon for the tooltip to be shown + * @Default {true} + */ + isBalloon?: boolean; + + /** Defines various attributes of the Tooltip position + */ + position?: TooltipSettingsPosition; + + /** Defines the tooltip to be triggered. + * @Default {hover} + */ + trigger?: ej.datavisualization.HeatMap.Trigger|string; + + /** Defines the animation for the tooltip that should be shown when the mouse hovers over rows/columns. + */ + animation?: TooltipSettingsAnimation; +} + export interface HeatMapCell { /** Specifies whether the cell content can be visible or not. @@ -60022,7 +62821,7 @@ export interface ItemsMapping { /** Specifies the property and display value of the collection of column. * @Default {[]} */ - columnMapping?: Array; + columnMapping?: any[]; } export interface ColorMappingCollectionLabel { @@ -60080,20 +62879,64 @@ export interface ColorMappingCollection { label?: ColorMappingCollectionLabel; } } -module HeatMap -{ -enum CellVisibility -{ +namespace HeatMap { +enum Associate { +//Used to set the associate of tooltip as Target +Target, +//Used to set the associate of tooltip as MouseFollow +MouseFollow, +//Used to set the associate of tooltip as MouseEnter +MouseEnter, +} +} +namespace HeatMap { +enum Horizontal { +//Used to display the tooltip horizontally on left side of rows/columns +Left, +//Used to display the tooltip horizontally on center side of rows/columns +Center, +//Used to display the tooltip horizontally on right side of rows/columns +Right, +} +} +namespace HeatMap { +enum Vertical { +//Used to display the tooltip horizontally on left side of rows/columns +Top, +//Used to display the tooltip horizontally on center side of rows/columns +Center, +//Used to display the tooltip horizontally on right side of rows/columns +Bottom, +} +} +namespace HeatMap { +enum Trigger { +//Tooltip can be triggered on mouse hovers +Hover, +//Tooltip can be triggered on mouse click +Click, +} +} +namespace HeatMap { +enum Effect { +//Sets tooltip animation as None +None, +//Sets tooltip animation as Fade +Fade, +//Sets tooltip animation as Slide +Slide, +} +} +namespace HeatMap { +enum CellVisibility { //Display the content of the cell Visible, //Hide the content of the cell Hidden, } } -module HeatMap -{ -enum TextDecoration -{ +namespace HeatMap { +enum TextDecoration { //Defines a line below the text Underline, //Defines a line above the text @@ -60107,13 +62950,12 @@ None, class HeatMapLegend extends ej.Widget { static fn: HeatMapLegend; - constructor(element: JQuery, options?: HeatMapLegend.Model); - constructor(element: Element, options?: HeatMapLegend.Model); + constructor(element: JQuery | Element, options?: HeatMapLegend.Model); static Locale: any; - model:HeatMapLegend.Model; - defaults:HeatMapLegend.Model; + model: HeatMapLegend.Model; + defaults: HeatMapLegend.Model; } -export module HeatMapLegend{ +export namespace HeatMapLegend { export interface Model { @@ -60140,7 +62982,7 @@ export interface Model { /** Specifies the color values of the column data. * @Default {[]} */ - colorMappingCollection?: Array; + colorMappingCollection?: ColorMappingCollection[]; /** Specifies the orientation of the heatmap legend * @Default {ej.HeatMap.LegendOrientation.Horizontal} @@ -60208,20 +63050,16 @@ export interface ColorMappingCollection { label?: ColorMappingCollectionLabel; } } -module HeatMap -{ -enum LegendOrientation -{ +namespace HeatMap { +enum LegendOrientation { //Scales the graphic content non-uniformly to the width and height of the diagram area Horizontal, //Used to align the image at the top left of diagram area Vertical, } } -module HeatMap -{ -enum LegendMode -{ +namespace HeatMap { +enum LegendMode { //Scales the graphic content non-uniformly to the width and height of the diagram area Gradient, //Used to align the image at the top left of diagram area @@ -60231,18 +63069,17 @@ List, class Sparkline extends ej.Widget { static fn: Sparkline; - constructor(element: JQuery, options?: Sparkline.Model); - constructor(element: Element, options?: Sparkline.Model); + constructor(element: JQuery | Element, options?: Sparkline.Model); static Locale: any; - model:Sparkline.Model; - defaults:Sparkline.Model; + model: Sparkline.Model; + defaults: Sparkline.Model; /** Redraws the entire sparkline. You can call this method whenever you update, add or remove points from the data source or whenever you want to refresh the UI. * @returns {void} */ redraw(): void; } -export module Sparkline{ +export namespace Sparkline { export interface Model { @@ -60365,28 +63202,28 @@ export interface Model { axisLineSettings?: AxisLineSettings; /** Fires before loading the sparkline. */ - load? (e: LoadEventArgs): void; + load?(e: LoadEventArgs): void; /** Fires after loaded the sparkline. */ - loaded? (e: LoadedEventArgs): void; + loaded?(e: LoadedEventArgs): void; /** Fires before rendering trackball tooltip. You can use this event to customize the text displayed in trackball tooltip. */ - tooltipInitialize? (e: TooltipInitializeEventArgs): void; + tooltipInitialize?(e: TooltipInitializeEventArgs): void; /** Fires before rendering a series. This event is fired for each series in Sparkline. */ - seriesRendering? (e: SeriesRenderingEventArgs): void; + seriesRendering?(e: SeriesRenderingEventArgs): void; /** Fires when mouse is moved over a point. */ - pointRegionMouseMove? (e: PointRegionMouseMoveEventArgs): void; + pointRegionMouseMove?(e: PointRegionMouseMoveEventArgs): void; /** Fires on clicking a point in sparkline. You can use this event to handle clicks made on points. */ - pointRegionMouseClick? (e: PointRegionMouseClickEventArgs): void; + pointRegionMouseClick?(e: PointRegionMouseClickEventArgs): void; /** Fires on moving mouse over the sparkline. */ - sparklineMouseMove? (e: SparklineMouseMoveEventArgs): void; + sparklineMouseMove?(e: SparklineMouseMoveEventArgs): void; /** Fires on moving mouse outside the sparkline. */ - sparklineMouseLeave? (e: SparklineMouseLeaveEventArgs): void; + sparklineMouseLeave?(e: SparklineMouseLeaveEventArgs): void; } export interface LoadEventArgs { @@ -60761,10 +63598,8 @@ export interface AxisLineSettings { dashArray?: number; } } -module Sparkline -{ -enum Type -{ +namespace Sparkline { +enum Type { //string Area, //string @@ -60777,10 +63612,8 @@ Pie, WinLoss, } } -module Sparkline -{ -enum Theme -{ +namespace Sparkline { +enum Theme { //string Azure, //string @@ -60803,20 +63636,16 @@ GradientLight, GradientDark, } } -module Sparkline -{ -enum FontStyle -{ +namespace Sparkline { +enum FontStyle { //string Normal, //string Italic, } } -module Sparkline -{ -enum FontWeight -{ +namespace Sparkline { +enum FontWeight { //string Regular, //string @@ -60826,15 +63655,1171 @@ Lighter, } } +class SunburstChart extends ej.Widget { + static fn: SunburstChart; + constructor(element: JQuery | Element, options?: SunburstChart.Model); + static Locale: any; + model: SunburstChart.Model; + defaults: SunburstChart.Model; + + /** Redraws the entire sunburst. You can call this method whenever you update, add or remove points from the data source or whenever you want to refresh the UI. + * @returns {void} + */ + redraw(): void; + + /** destroy the sunburst + * @returns {void} + */ + _destroy(): void; +} +export namespace SunburstChart { + +export interface Model { + + /** Background color of the plot area. + * @Default {null} + */ + background?: string; + + /** Bind the data field from the data source. + * @Default {null} + */ + valueMemberPath?: string; + + /** Options for customizing the sunburst border. + */ + border?: Border; + + /** Options for customizing the sunburst segment border. + */ + segmentBorder?: SegmentBorder; + + /** Specifies the dataSource to the sunburst. + * @Default {null} + */ + dataSource?: any; + + /** Palette color for the data points. + * @Default {null} + */ + palette?: string; + + /** Parent node of the data points. + * @Default {null} + */ + parentNode?: string; + + /** Name of the property in the datasource that contains x values. + * @Default {null} + */ + xName?: string; + + /** Name of the property in the datasource that contains y values. + * @Default {null} + */ + yName?: string; + + /** Controls whether sunburst has to be responsive or not. + * @Default {true} + */ + isResponsive?: boolean; + + /** Options to customize the Sunburst size. + */ + size?: Size; + + /** Controls the visibility of sunburst. + * @Default {true} + */ + visible?: boolean; + + /** Options to customize the Sunburst tooltip. + */ + tooltip?: Tooltip; + + /** Options for customizing sunburst points. + */ + points?: Points; + + /** Sunburst rendering will start from the specified value + * @Default {null} + */ + startAngle?: number; + + /** Sunburst rendering will end at the specified value + * @Default {null} + */ + endAngle?: number; + + /** Sunburst outer radius value + * @Default {1} + */ + radius?: number; + + /** Sunburst inner radius value + * @Default {0.4} + */ + innerRadius?: number; + + /** Options to customize the Sunburst dataLabel. + */ + dataLabelSettings?: DataLabelSettings; + + /** Options for customizing the title and subtitle of sunburst. + */ + title?: Title; + + /** Options for customizing the appearance of the levels or point while highlighting. + */ + highlightSettings?: HighlightSettings; + + /** Options for customizing the appearance of the levels or data point while selection. + */ + selectionSettings?: SelectionSettings; + + /** Specify levels of sunburst for grouped visualization of data + * @Default {[]} + */ + levels?: Level[]; + + /** Options to customize the legend items and legend title. + */ + legend?: Legend; + + /** Specifies the theme for Sunburst. + * @Default {Flatlight. See Theme} + */ + theme?: ej.datavisualization.Sunburst.SunburstTheme|string; + + /** Options to customize the left, right, top and bottom margins of sunburst area. + */ + margin?: Margin; + + /** Enable/disable the animation for all the levels. + * @Default {false} + */ + enableAnimation?: boolean; + + /** Opacity of the levels. + * @Default {1} + */ + opacity?: number; + + /** Options for enable zooming feature of chart. + */ + zoomSettings?: ZoomSettings; + + /** Animation type of sunburst + * @Default {rotation. See Alignment} + */ + animationType?: ej.datavisualization.Sunburst.Animation|string; + + /** Fires before loading. */ + load?(e: LoadEventArgs): void; + + /** Fires before rendering sunburst. */ + preRender?(e: PreRenderEventArgs): void; + + /** Fires after rendering sunburst. */ + loaded?(e: LoadedEventArgs): void; + + /** Fires before rendering the datalabel */ + dataLabelRendering?(e: DataLabelRenderingEventArgs): void; + + /** Fires before rendering each segment */ + segmentRendering?(e: SegmentRenderingEventArgs): void; + + /** Fires before rendering sunburst title. */ + titleRendering?(e: TitleRenderingEventArgs): void; + + /** Fires during initialization of tooltip. */ + tooltipInitialize?(e: TooltipInitializeEventArgs): void; + + /** Fires after clicking the point in sunburst */ + pointRegionClick?(e: PointRegionClickEventArgs): void; + + /** Fires while moving the mouse over sunburst points */ + pointRegionMouseMove?(e: PointRegionMouseMoveEventArgs): void; + + /** Fires when clicking the point to perform drilldown. */ + drillDownClick?(e: DrillDownClickEventArgs): void; + + /** Fires when resetting drilldown points. */ + drillDownBack?(e: DrillDownBackEventArgs): void; + + /** Fires after resetting the sunburst points */ + drillDownReset?(e: DrillDownResetEventArgs): void; +} + +export interface LoadEventArgs { + + /** Load event data + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface PreRenderEventArgs { + + /** PreRender event data + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface LoadedEventArgs { + + /** Loaded event data + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface DataLabelRenderingEventArgs { + + /** Sunburst datalabel data + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface SegmentRenderingEventArgs { + + /** Sunburst datalabel data + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface TitleRenderingEventArgs { + + /** Sunburst title data + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface TooltipInitializeEventArgs { + + /** Sunburst tooltip data + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface PointRegionClickEventArgs { + + /** Includes clicked points region data + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface PointRegionMouseMoveEventArgs { + + /** Includes data of mouse moved region + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface DrillDownClickEventArgs { + + /** Clicked point data + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface DrillDownBackEventArgs { + + /** Drill down data of points + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface DrillDownResetEventArgs { + + /** Drill down reset data + */ + data?: string; + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the sunburst model object + */ + model?: any; + + /** Name of the event + */ + type?: string; +} + +export interface Border { + + /** Border color of the sunburst. + * @Default {null} + */ + color?: string; + + /** Width of the Sunburst border. + * @Default {2} + */ + width?: number; +} + +export interface SegmentBorder { + + /** Segment Border color of the sunburst. + * @Default {null} + */ + color?: string; + + /** Width of the Sunburst segment border. + * @Default {2} + */ + width?: number; +} + +export interface Size { + + /** Height of the Sunburst. + * @Default {''} + */ + height?: string; + + /** Width of the Sunburst. + * @Default {''} + */ + width?: string; +} + +export interface TooltipBorder { + + /** Border color of the tooltip. + * @Default {null} + */ + color?: string; + + /** Border width of the tooltip. + * @Default {5} + */ + width?: number; +} + +export interface TooltipFont { + + /** Font color of the text in the tooltip. + * @Default {null} + */ + color?: string; + + /** Font Family for the tooltip. + * @Default {Segoe UI} + */ + fontFamily?: string; + + /** Specifies the font Style for the tooltip. + * @Default {Normal} + */ + fontStyle?: ej.datavisualization.Sunburst.FontStyle|string; + + /** Specifies the font weight for the tooltip. + * @Default {Regular} + */ + fontWeight?: ej.datavisualization.Sunburst.FontWeight|string; + + /** Opacity for text in the tooltip. + * @Default {1} + */ + opacity?: number; + + /** Font size for text in the tooltip. + * @Default {12px} + */ + size?: string; +} + +export interface Tooltip { + + /** tooltip visibility of the Sunburst. + * @Default {true} + */ + visible?: boolean; + + /** Options for customizing the border of the sunburst tooltip. + */ + border?: TooltipBorder; + + /** Fill color for the sunburst tooltip. + * @Default {null} + */ + fill?: string; + + /** Options for customizing the font of the tooltip. + */ + font?: TooltipFont; + + /** Custom template to the tooltip. + * @Default {null} + */ + template?: string; +} + +export interface Points { + + /** Points x value of the sunburst. + * @Default {null} + */ + x?: string; + + /** Points y value of the sunburst. + * @Default {null} + */ + y?: number; + + /** Points text of the sunburst. + * @Default {null} + */ + text?: string; + + /** Points fill color of the sunburst. + * @Default {null} + */ + fill?: string; +} + +export interface DataLabelSettingsFont { + + /** Font family of the data label. + * @Default {Segoe UI} + */ + fontFamily?: string; + + /** Font style of the data label. + * @Default {normal. See FontStyle} + */ + fontStyle?: ej.datavisualization.Sunburst.FontStyle|string; + + /** Font weight of the data label. + * @Default {regular. See FontWeight} + */ + fontWeight?: ej.datavisualization.Sunburst.FontWeight|string; + + /** Opacity of the text. + * @Default {1} + */ + opacity?: number; + + /** Font color of the data label text. + * @Default {null} + */ + color?: string; + + /** Font size of the data label. + * @Default {12px} + */ + size?: string; +} + +export interface DataLabelSettings { + + /** Datalabel visibility of the Sunburst. + * @Default {false} + */ + visible?: boolean; + + /** Alignment of sunburst datalabel + * @Default {Angle. See DatalabelAlignment} + */ + labelRotationMode?: ej.datavisualization.Sunburst.SunburstLabelRotationMode|string; + + /** Options for customizing the data label font. + */ + font?: DataLabelSettingsFont; + + /** Custom template for datalabel + * @Default {null} + */ + template?: string; + + /** Fill color for the datalabel + * @Default {null} + */ + fill?: string; + + /** Datalabel overflow mode + * @Default {Trim. See LabelOverflowMode} + */ + labelOverflowMode?: ej.datavisualization.Sunburst.SunburstLabelOverflowMode|string; +} + +export interface TitleFont { + + /** Font family for Sunburst title. + * @Default {Segoe UI} + */ + fontFamily?: string; + + /** Font style for Sunburst title. + * @Default {Normal. See FontStyle} + */ + fontStyle?: ej.datavisualization.Sunburst.FontStyle|string; + + /** Font weight for Sunburst title. + * @Default {Regular. See FontWeight} + */ + fontWeight?: ej.datavisualization.Sunburst.FontWeight|string; + + /** Opacity of the Sunburst title. + * @Default {1} + */ + opacity?: number; + + /** Font size for Sunburst title. + * @Default {20px} + */ + size?: string; +} + +export interface TitleSubtitleFont { + + /** Font family of sub title. + * @Default {Segoe UI} + */ + fontFamily?: string; + + /** Font style for sub title. + * @Default {Normal. See FontStyle} + */ + fontStyle?: ej.datavisualization.Sunburst.FontStyle|string; + + /** Font weight for sub title. + * @Default {Regular. See FontWeight} + */ + fontWeight?: ej.datavisualization.Sunburst.FontWeight|string; + + /** Opacity of the sub title. + * @Default {1} + */ + opacity?: number; + + /** Font size for sub title. + * @Default {12px} + */ + size?: string; +} + +export interface TitleSubtitle { + + /** Subtitle text for sunburst + */ + text?: string; + + /** Sub title text visibility for sunburst + * @Default {true} + */ + visible?: string; + + /** Sub title text alignment + * @Default {far. See TextAlignment} + */ + textAlignment?: ej.datavisualization.Sunburst.SunburstAlignment|string; + + /** Options for customizing the font of sub title. + */ + font?: TitleSubtitleFont; +} + +export interface Title { + + /** Title text for sunburst + */ + text?: string; + + /** Title text visibility for sunburst + * @Default {true} + */ + visible?: string; + + /** Title text alignment + * @Default {center. See TextAlignment} + */ + textAlignment?: ej.datavisualization.Sunburst.SunburstAlignment|string; + + /** Options for customizing the font of sunburst title. + */ + font?: TitleFont; + + /** Options to customize the sub title of Sunburst. + */ + subtitle?: TitleSubtitle; +} + +export interface HighlightSettings { + + /** Enables/disables the ability to highlight the levels or point interactively. + * @Default {false} + */ + enable?: boolean; + + /** Specifies whether the levels or point has to be highlighted. + * @Default {point. See Mode} + */ + mode?: ej.datavisualization.Sunburst.SunburstHighlightMode|string; + + /** Color of the levels/point on highlight. + * @Default {red} + */ + color?: string; + + /** Opacity of the levels/point on highlight. + * @Default {0.5} + */ + opacity?: number; + + /** Specifies whether the levels or data point has to be highlighted. + * @Default {opacity. See Mode} + */ + type?: ej.datavisualization.Sunburst.SunburstHighlightType|string; +} + +export interface SelectionSettings { + + /** Enables/disables the ability to select the levels or data point interactively. + * @Default {false} + */ + enable?: boolean; + + /** Specifies whether the levels or data point has to be selected. + * @Default {point. See Mode} + */ + mode?: ej.datavisualization.Sunburst.SunburstHighlightMode|string; + + /** Color of the levels/point on selection. + * @Default {green} + */ + color?: string; + + /** Opacity of the levels/point on selection. + * @Default {0.5} + */ + opacity?: number; + + /** Specifies whether the levels or data point has to be selected. + * @Default {opacity. See Mode} + */ + type?: ej.datavisualization.Sunburst.SunburstHighlightType|string; +} + +export interface Level { + + /** Specifies the group member path + * @Default {null} + */ + groupMemberPath?: string; +} + +export interface LegendBorder { + + /** Border color of the legend. + * @Default {null} + */ + color?: string; + + /** Border width of the legend. + * @Default {1} + */ + width?: number; +} + +export interface LegendFont { + + /** Font family for legend item text. + * @Default {Segoe UI} + */ + fontFamily?: string; + + /** Font style for legend item text. + * @Default {Normal. See FontStyle} + */ + fontStyle?: ej.datavisualization.Sunburst.FontStyle|string; + + /** Font weight for legend item text. + * @Default {Regular. See FontWeight} + */ + fontWeight?: ej.datavisualization.Sunburst.FontWeight|string; + + /** Font size for legend item text. + * @Default {12px} + */ + size?: string; +} + +export interface LegendItemStyle { + + /** Height of the shape in legend items. + * @Default {10} + */ + height?: number; + + /** Width of the shape in legend items. + * @Default {10} + */ + width?: number; +} + +export interface LegendLocation { + + /** X value or horizontal offset to position the legend in chart. + * @Default {0} + */ + x?: number; + + /** Y value or vertical offset to position the legend. + * @Default {0} + */ + y?: number; +} + +export interface LegendSize { + + /** Height of the legend. Height can be specified in either pixel or percentage. + * @Default {null} + */ + height?: string; + + /** Width of the legend. Width can be specified in either pixel or percentage. + * @Default {null} + */ + width?: string; +} + +export interface LegendTitleFont { + + /** Font family for the text in legend title. + * @Default {Segoe UI} + */ + fontFamily?: string; + + /** Font style for legend title. + * @Default {normal. See FontStyle} + */ + fontStyle?: ej.datavisualization.Sunburst.FontStyle|string; + + /** Font weight for legend title. + * @Default {normal. See FontWeight} + */ + fontWeight?: ej.datavisualization.Sunburst.FontWeight|string; + + /** Font size for legend title. + * @Default {12px} + */ + size?: string; +} + +export interface LegendTitle { + + /** Options to customize the font used for legend title + */ + font?: LegendTitleFont; + + /** Enables or disables the legend title. + * @Default {true} + */ + visible?: string; + + /** Text to be displayed in legend title. + */ + text?: string; + + /** Alignment of the legend title. + * @Default {center. See Alignment} + */ + textAlignment?: ej.datavisualization.Sunburst.SunburstAlignment|string; +} + +export interface Legend { + + /** Visibility of the legend. + * @Default {false} + */ + visible?: boolean; + + /** Interactive action of legend items. + * @Default {toggleSegmentVisibility. See Alignment} + */ + clickAction?: ej.datavisualization.Sunburst.SunburstClickAction|string; + + /** Horizontal alignment of the legend. + * @Default {Center. See Alignment} + */ + alignment?: ej.datavisualization.Sunburst.SunburstAlignment|string; + + /** Options for customizing the legend border. + */ + border?: LegendBorder; + + /** Number of columns to arrange the legend items. + * @Default {null} + */ + columnCount?: number; + + /** Number of rows to arrange the legend items. + * @Default {null} + */ + rowCount?: number; + + /** Options to customize the font used for legend item text. + */ + font?: LegendFont; + + /** Gap or padding between the legend items. + * @Default {10} + */ + itemPadding?: number; + + /** Options to customize the style of legend items. + */ + itemStyle?: LegendItemStyle; + + /** Options to customize the location of sunburst legend. Legend is placed in provided location only when value of position property is custom + */ + location?: LegendLocation; + + /** Places the legend at specified position. Legend can be placed at left, right, top or bottom of the chart area.To manually specify the location of legend, set custom as value to this property. + * @Default {Bottom. See Position} + */ + position?: ej.datavisualization.Sunburst.SunburstLegendPosition|string; + + /** Shape of the legend items. + * @Default {None. See Shape} + */ + shape?: ej.datavisualization.Sunburst.SunburstLegendShape|string; + + /** Options to customize the size of the legend. + */ + size?: LegendSize; + + /** Options to customize the legend title. + */ + title?: LegendTitle; +} + +export interface Margin { + + /** Spacing for the left margin of chart area. Setting positive value decreases the width of the chart area from left side. + * @Default {10} + */ + left?: number; + + /** Spacing for the right margin of chart area. Setting positive value decreases the width of the chart area from right side. + * @Default {10} + */ + right?: number; + + /** Spacing for the top margin of chart area. Setting positive value decreases the height of the chart area from the top. + * @Default {10} + */ + top?: number; + + /** Spacing for the bottom margin of the chart area. Setting positive value decreases the height of the chart area from the bottom. + * @Default {10} + */ + bottom?: number; +} + +export interface ZoomSettings { + + /** Enables or disables zooming. + * @Default {false} + */ + enable?: boolean; + + /** Toolbar horizontal alignment + * @Default {right. See Alignment} + */ + toolbarHorizontalAlignment?: ej.datavisualization.Sunburst.SunburstHorizontalAlignment|string; + + /** Toolbar vertical alignment + * @Default {top. See Alignment} + */ + toolbarVerticalAlignment?: ej.datavisualization.Sunburst.SunburstVerticalAlignment|string; +} +} +namespace Sunburst { +enum FontStyle { +//string +Normal, +//string +Italic, +} +} +namespace Sunburst { +enum FontWeight { +//string +Regular, +//string +Bold, +//string +Lighter, +} +} +namespace Sunburst { +enum SunburstLabelRotationMode { +//string +Angle, +//string +Normal, +} +} +namespace Sunburst { +enum SunburstLabelOverflowMode { +//string +Trim, +//string +Hide, +//string +None, +} +} +namespace Sunburst { +enum SunburstAlignment { +//string +Center, +//string +Near, +//string +Far, +} +} +namespace Sunburst { +enum SunburstHighlightMode { +//string +Point, +//string +Parent, +//string +Child, +//string +All, +} +} +namespace Sunburst { +enum SunburstHighlightType { +//string +Opacity, +//string +Color, +} +} +namespace Sunburst { +enum SunburstClickAction { +//string +None, +//string +ToggleSegmentVisibility, +//string +ToggleSegmentSelection, +} +} +namespace Sunburst { +enum SunburstLegendPosition { +//string +Left, +//string +Right, +//string +Top, +//string +Bottom, +} +} +namespace Sunburst { +enum SunburstLegendShape { +//string +Diamond, +//string +Pentagon, +//string +Rectangle, +//string +Circle, +//string +Cross, +//string +Triangle, +} +} +namespace Sunburst { +enum SunburstTheme { +//string +FlatLight, +//string +FlatDark, +} +} +namespace Sunburst { +enum SunburstHorizontalAlignment { +//string +Center, +//string +Left, +//string +Right, +} +} +namespace Sunburst { +enum SunburstVerticalAlignment { +//string +Top, +//string +Bottom, +//string +Middle, +} +} +namespace Sunburst { +enum Animation { +//string +Rotation, +//string +FadeIn, +} +} + class Overview extends ej.Widget { static fn: Overview; - constructor(element: JQuery, options?: Overview.Model); - constructor(element: Element, options?: Overview.Model); + constructor(element: JQuery | Element, options?: Overview.Model); static Locale: any; - model:Overview.Model; - defaults:Overview.Model; + model: Overview.Model; + defaults: Overview.Model; } -export module Overview{ +export namespace Overview { export interface Model { @@ -60858,12 +64843,24 @@ export interface Model { } interface JQueryXHR { + /** Returns the cancel option value. + */ + cancel?: boolean; } interface JQueryPromise { + /** Returns the cancel option value. + */ + cancel?: boolean; } interface JQueryDeferred extends JQueryPromise { + /** Returns the cancel option value. + */ + cancel?: boolean; } interface JQueryParam { + /** Returns the cancel option value. + */ + cancel?: boolean; } interface JQuery { data(key: any): any; @@ -60873,408 +64870,332 @@ interface Window { } interface JQuery { -ejAccordion(): JQuery; ejAccordion(options?: ej.Accordion.Model): JQuery; ejAccordion(memberName: any, value?: any, param?: any): any; -data(key: "ejAccordion"): ej.Accordion; -ejAutocomplete(): JQuery; ejAutocomplete(options?: ej.Autocomplete.Model): JQuery; ejAutocomplete(memberName: any, value?: any, param?: any): any; -data(key: "ejAutocomplete"): ej.Autocomplete; -ejBarcode(): JQuery; ejBarcode(options?: ej.datavisualization.Barcode.Model): JQuery; ejBarcode(memberName: any, value?: any, param?: any): any; -data(key: "ejBarcode"): ej.datavisualization.Barcode; -ejBulletGraph(): JQuery; ejBulletGraph(options?: ej.datavisualization.BulletGraph.Model): JQuery; ejBulletGraph(memberName: any, value?: any, param?: any): any; -data(key: "ejBulletGraph"): ej.datavisualization.BulletGraph; -ejButton(): JQuery; ejButton(options?: ej.Button.Model): JQuery; ejButton(memberName: any, value?: any, param?: any): any; -data(key: "ejButton"): ej.Button; -ejCaptcha(): JQuery; ejCaptcha(options?: ej.Captcha.Model): JQuery; ejCaptcha(memberName: any, value?: any, param?: any): any; -data(key: "ejCaptcha"): ej.Captcha; -ejChart(): JQuery; ejChart(options?: ej.datavisualization.Chart.Model): JQuery; ejChart(memberName: any, value?: any, param?: any): any; -data(key: "ejChart"): ej.datavisualization.Chart; -ejCheckBox(): JQuery; ejCheckBox(options?: ej.CheckBox.Model): JQuery; ejCheckBox(memberName: any, value?: any, param?: any): any; -data(key: "ejCheckBox"): ej.CheckBox; -ejCircularGauge(): JQuery; ejCircularGauge(options?: ej.datavisualization.CircularGauge.Model): JQuery; ejCircularGauge(memberName: any, value?: any, param?: any): any; -data(key: "ejCircularGauge"): ej.datavisualization.CircularGauge; -ejColorPicker(): JQuery; ejColorPicker(options?: ej.ColorPicker.Model): JQuery; ejColorPicker(memberName: any, value?: any, param?: any): any; -data(key: "ejColorPicker"): ej.ColorPicker; -ejDatePicker(): JQuery; ejDatePicker(options?: ej.DatePicker.Model): JQuery; ejDatePicker(memberName: any, value?: any, param?: any): any; -data(key: "ejDatePicker"): ej.DatePicker; -ejDateRangePicker(): JQuery; ejDateRangePicker(options?: ej.DateRangePicker.Model): JQuery; ejDateRangePicker(memberName: any, value?: any, param?: any): any; -data(key: "ejDateRangePicker"): ej.DateRangePicker; -ejDateTimePicker(): JQuery; ejDateTimePicker(options?: ej.DateTimePicker.Model): JQuery; ejDateTimePicker(memberName: any, value?: any, param?: any): any; -data(key: "ejDateTimePicker"): ej.DateTimePicker; -ejDiagram(): JQuery; ejDiagram(options?: ej.datavisualization.Diagram.Model): JQuery; ejDiagram(memberName: any, value?: any, param?: any): any; -data(key: "ejDiagram"): ej.datavisualization.Diagram; -ejDialog(): JQuery; ejDialog(options?: ej.Dialog.Model): JQuery; ejDialog(memberName: any, value?: any, param?: any): any; -data(key: "ejDialog"): ej.Dialog; -ejDigitalGauge(): JQuery; ejDigitalGauge(options?: ej.datavisualization.DigitalGauge.Model): JQuery; ejDigitalGauge(memberName: any, value?: any, param?: any): any; -data(key: "ejDigitalGauge"): ej.datavisualization.DigitalGauge; -ejDocumentEditor(): JQuery; ejDocumentEditor(options?: ej.DocumentEditor.Model): JQuery; ejDocumentEditor(memberName: any, value?: any, param?: any): any; -data(key: "ejDocumentEditor"): ej.DocumentEditor; -ejDraggable(): JQuery; ejDraggable(options?: ej.Draggable.Model): JQuery; ejDraggable(memberName: any, value?: any, param?: any): any; -data(key: "ejDraggable"): ej.Draggable; -ejDropDownList(): JQuery; ejDropDownList(options?: ej.DropDownList.Model): JQuery; ejDropDownList(memberName: any, value?: any, param?: any): any; -data(key: "ejDropDownList"): ej.DropDownList; -ejDroppable(): JQuery; ejDroppable(options?: ej.Droppable.Model): JQuery; ejDroppable(memberName: any, value?: any, param?: any): any; -data(key: "ejDroppable"): ej.Droppable; -ejFileExplorer(): JQuery; ejFileExplorer(options?: ej.FileExplorer.Model): JQuery; ejFileExplorer(memberName: any, value?: any, param?: any): any; -data(key: "ejFileExplorer"): ej.FileExplorer; -ejGantt(): JQuery; ejGantt(options?: ej.Gantt.Model): JQuery; ejGantt(memberName: any, value?: any, param?: any): any; -data(key: "ejGantt"): ej.Gantt; -ejGrid(): JQuery; ejGrid(options?: ej.Grid.Model): JQuery; ejGrid(memberName: any, value?: any, param?: any): any; -data(key: "ejGrid"): ej.Grid; -ejGroupButton(): JQuery; ejGroupButton(options?: ej.GroupButton.Model): JQuery; ejGroupButton(memberName: any, value?: any, param?: any): any; -data(key: "ejGroupButton"): ej.GroupButton; -ejHeatMap(): JQuery; ejHeatMap(options?: ej.datavisualization.HeatMap.Model): JQuery; ejHeatMap(memberName: any, value?: any, param?: any): any; -data(key: "ejHeatMap"): ej.datavisualization.HeatMap; -ejHeatMapLegend(): JQuery; ejHeatMapLegend(options?: ej.datavisualization.HeatMapLegend.Model): JQuery; ejHeatMapLegend(memberName: any, value?: any, param?: any): any; -data(key: "ejHeatMapLegend"): ej.datavisualization.HeatMapLegend; -ejKanban(): JQuery; ejKanban(options?: ej.Kanban.Model): JQuery; ejKanban(memberName: any, value?: any, param?: any): any; -data(key: "ejKanban"): ej.Kanban; -ejLinearGauge(): JQuery; ejLinearGauge(options?: ej.datavisualization.LinearGauge.Model): JQuery; ejLinearGauge(memberName: any, value?: any, param?: any): any; -data(key: "ejLinearGauge"): ej.datavisualization.LinearGauge; -ejListBox(): JQuery; ejListBox(options?: ej.ListBox.Model): JQuery; ejListBox(memberName: any, value?: any, param?: any): any; -data(key: "ejListBox"): ej.ListBox; -ejListView(): JQuery; ejListView(options?: ej.ListView.Model): JQuery; ejListView(memberName: any, value?: any, param?: any): any; -data(key: "ejListView"): ej.ListView; -ejMap(): JQuery; ejMap(options?: ej.datavisualization.Map.Model): JQuery; ejMap(memberName: any, value?: any, param?: any): any; -data(key: "ejMap"): ej.datavisualization.Map; -ejMaskEdit(): JQuery; ejMaskEdit(options?: ej.MaskEdit.Model): JQuery; ejMaskEdit(memberName: any, value?: any, param?: any): any; -data(key: "ejMaskEdit"): ej.MaskEdit; -ejMenu(): JQuery; ejMenu(options?: ej.Menu.Model): JQuery; ejMenu(memberName: any, value?: any, param?: any): any; -data(key: "ejMenu"): ej.Menu; -ejNavigationDrawer(): JQuery; ejNavigationDrawer(options?: ej.NavigationDrawer.Model): JQuery; ejNavigationDrawer(memberName: any, value?: any, param?: any): any; -data(key: "ejNavigationDrawer"): ej.NavigationDrawer; -ejOverview(): JQuery; ejOverview(options?: ej.datavisualization.Overview.Model): JQuery; ejOverview(memberName: any, value?: any, param?: any): any; -data(key: "ejOverview"): ej.datavisualization.Overview; -ejPager(): JQuery; ejPager(options?: ej.Pager.Model): JQuery; ejPager(memberName: any, value?: any, param?: any): any; -data(key: "ejPager"): ej.Pager; -ejPdfViewer(): JQuery; ejPdfViewer(options?: ej.PdfViewer.Model): JQuery; ejPdfViewer(memberName: any, value?: any, param?: any): any; -data(key: "ejPdfViewer"): ej.PdfViewer; -ejPivotChart(): JQuery; ejPivotChart(options?: ej.PivotChart.Model): JQuery; ejPivotChart(memberName: any, value?: any, param?: any): any; -data(key: "ejPivotChart"): ej.PivotChart; -ejPivotClient(): JQuery; ejPivotClient(options?: ej.PivotClient.Model): JQuery; ejPivotClient(memberName: any, value?: any, param?: any): any; -data(key: "ejPivotClient"): ej.PivotClient; -ejPivotGauge(): JQuery; ejPivotGauge(options?: ej.PivotGauge.Model): JQuery; ejPivotGauge(memberName: any, value?: any, param?: any): any; -data(key: "ejPivotGauge"): ej.PivotGauge; -ejPivotGrid(): JQuery; ejPivotGrid(options?: ej.PivotGrid.Model): JQuery; ejPivotGrid(memberName: any, value?: any, param?: any): any; -data(key: "ejPivotGrid"): ej.PivotGrid; -ejPivotPager(): JQuery; ejPivotPager(options?: ej.PivotPager.Model): JQuery; ejPivotPager(memberName: any, value?: any, param?: any): any; -data(key: "ejPivotPager"): ej.PivotPager; -ejPivotSchemaDesigner(): JQuery; ejPivotSchemaDesigner(options?: ej.PivotSchemaDesigner.Model): JQuery; ejPivotSchemaDesigner(memberName: any, value?: any, param?: any): any; -data(key: "ejPivotSchemaDesigner"): ej.PivotSchemaDesigner; -ejPivotTreeMap(): JQuery; ejPivotTreeMap(options?: ej.PivotTreeMap.Model): JQuery; ejPivotTreeMap(memberName: any, value?: any, param?: any): any; -data(key: "ejPivotTreeMap"): ej.PivotTreeMap; -ejProgressBar(): JQuery; ejProgressBar(options?: ej.ProgressBar.Model): JQuery; ejProgressBar(memberName: any, value?: any, param?: any): any; -data(key: "ejProgressBar"): ej.ProgressBar; -ejRadialMenu(): JQuery; ejRadialMenu(options?: ej.RadialMenu.Model): JQuery; ejRadialMenu(memberName: any, value?: any, param?: any): any; -data(key: "ejRadialMenu"): ej.RadialMenu; -ejRadialSlider(): JQuery; ejRadialSlider(options?: ej.RadialSlider.Model): JQuery; ejRadialSlider(memberName: any, value?: any, param?: any): any; -data(key: "ejRadialSlider"): ej.RadialSlider; -ejRadioButton(): JQuery; ejRadioButton(options?: ej.RadioButton.Model): JQuery; ejRadioButton(memberName: any, value?: any, param?: any): any; -data(key: "ejRadioButton"): ej.RadioButton; -ejRangeNavigator(): JQuery; ejRangeNavigator(options?: ej.datavisualization.RangeNavigator.Model): JQuery; ejRangeNavigator(memberName: any, value?: any, param?: any): any; -data(key: "ejRangeNavigator"): ej.datavisualization.RangeNavigator; -ejRating(): JQuery; ejRating(options?: ej.Rating.Model): JQuery; ejRating(memberName: any, value?: any, param?: any): any; -data(key: "ejRating"): ej.Rating; -ejRecurrenceEditor(): JQuery; ejRecurrenceEditor(options?: ej.RecurrenceEditor.Model): JQuery; ejRecurrenceEditor(memberName: any, value?: any, param?: any): any; -data(key: "ejRecurrenceEditor"): ej.RecurrenceEditor; -ejReportViewer(): JQuery; ejReportViewer(options?: ej.ReportViewer.Model): JQuery; ejReportViewer(memberName: any, value?: any, param?: any): any; -data(key: "ejReportViewer"): ej.ReportViewer; -ejResizable(): JQuery; ejResizable(options?: ej.Resizable.Model): JQuery; ejResizable(memberName: any, value?: any, param?: any): any; -data(key: "ejResizable"): ej.Resizable; -ejRibbon(): JQuery; ejRibbon(options?: ej.Ribbon.Model): JQuery; ejRibbon(memberName: any, value?: any, param?: any): any; -data(key: "ejRibbon"): ej.Ribbon; -ejRotator(): JQuery; ejRotator(options?: ej.Rotator.Model): JQuery; ejRotator(memberName: any, value?: any, param?: any): any; -data(key: "ejRotator"): ej.Rotator; -ejRTE(): JQuery; ejRTE(options?: ej.RTE.Model): JQuery; ejRTE(memberName: any, value?: any, param?: any): any; -data(key: "ejRTE"): ej.RTE; -ejSchedule(): JQuery; ejSchedule(options?: ej.Schedule.Model): JQuery; ejSchedule(memberName: any, value?: any, param?: any): any; -data(key: "ejSchedule"): ej.Schedule; -ejScroller(): JQuery; ejScroller(options?: ej.Scroller.Model): JQuery; ejScroller(memberName: any, value?: any, param?: any): any; -data(key: "ejScroller"): ej.Scroller; -ejSignature(): JQuery; ejSignature(options?: ej.Signature.Model): JQuery; ejSignature(memberName: any, value?: any, param?: any): any; -data(key: "ejSignature"): ej.Signature; -ejSlider(): JQuery; ejSlider(options?: ej.Slider.Model): JQuery; ejSlider(memberName: any, value?: any, param?: any): any; -data(key: "ejSlider"): ej.Slider; -ejSparkline(): JQuery; ejSparkline(options?: ej.datavisualization.Sparkline.Model): JQuery; ejSparkline(memberName: any, value?: any, param?: any): any; -data(key: "ejSparkline"): ej.datavisualization.Sparkline; -ejSpellCheck(): JQuery; ejSpellCheck(options?: ej.SpellCheck.Model): JQuery; ejSpellCheck(memberName: any, value?: any, param?: any): any; -data(key: "ejSpellCheck"): ej.SpellCheck; -ejSplitButton(): JQuery; ejSplitButton(options?: ej.SplitButton.Model): JQuery; ejSplitButton(memberName: any, value?: any, param?: any): any; -data(key: "ejSplitButton"): ej.SplitButton; -ejSplitter(): JQuery; ejSplitter(options?: ej.Splitter.Model): JQuery; ejSplitter(memberName: any, value?: any, param?: any): any; -data(key: "ejSplitter"): ej.Splitter; -ejSpreadsheet(): JQuery; ejSpreadsheet(options?: ej.Spreadsheet.Model): JQuery; ejSpreadsheet(memberName: any, value?: any, param?: any): any; -data(key: "ejSpreadsheet"): ej.Spreadsheet; -ejSymbolPalette(): JQuery; +ejSunburstChart(options?: ej.datavisualization.SunburstChart.Model): JQuery; +ejSunburstChart(memberName: any, value?: any, param?: any): any; + ejSymbolPalette(options?: ej.datavisualization.SymbolPalette.Model): JQuery; ejSymbolPalette(memberName: any, value?: any, param?: any): any; -data(key: "ejSymbolPalette"): ej.datavisualization.SymbolPalette; -ejTab(): JQuery; ejTab(options?: ej.Tab.Model): JQuery; ejTab(memberName: any, value?: any, param?: any): any; -data(key: "ejTab"): ej.Tab; -ejTagCloud(): JQuery; ejTagCloud(options?: ej.TagCloud.Model): JQuery; ejTagCloud(memberName: any, value?: any, param?: any): any; -data(key: "ejTagCloud"): ej.TagCloud; -ejNumericTextbox(): JQuery; ejNumericTextbox(options?: ej.Editor.Model): JQuery; ejNumericTextbox(memberName: any, value?: any, param?: any): any; -data(key: "ejNumericTextbox"): ej.NumericTextbox; -ejCurrencyTextbox(): JQuery; ejCurrencyTextbox(options?: ej.Editor.Model): JQuery; ejCurrencyTextbox(memberName: any, value?: any, param?: any): any; -data(key: "ejCurrencyTextbox"): ej.CurrencyTextbox; -ejPercentageTextbox(): JQuery; ejPercentageTextbox(options?: ej.Editor.Model): JQuery; ejPercentageTextbox(memberName: any, value?: any, param?: any): any; -data(key: "ejPercentageTextbox"): ej.PercentageTextbox; -ejTile(): JQuery; ejTile(options?: ej.Tile.Model): JQuery; ejTile(memberName: any, value?: any, param?: any): any; -data(key: "ejTile"): ej.Tile; -ejTimePicker(): JQuery; ejTimePicker(options?: ej.TimePicker.Model): JQuery; ejTimePicker(memberName: any, value?: any, param?: any): any; -data(key: "ejTimePicker"): ej.TimePicker; -ejToggleButton(): JQuery; ejToggleButton(options?: ej.ToggleButton.Model): JQuery; ejToggleButton(memberName: any, value?: any, param?: any): any; -data(key: "ejToggleButton"): ej.ToggleButton; -ejToolbar(): JQuery; ejToolbar(options?: ej.Toolbar.Model): JQuery; ejToolbar(memberName: any, value?: any, param?: any): any; -data(key: "ejToolbar"): ej.Toolbar; -ejTooltip(): JQuery; ejTooltip(options?: ej.Tooltip.Model): JQuery; ejTooltip(memberName: any, value?: any, param?: any): any; -data(key: "ejTooltip"): ej.Tooltip; -ejTreeGrid(): JQuery; ejTreeGrid(options?: ej.TreeGrid.Model): JQuery; ejTreeGrid(memberName: any, value?: any, param?: any): any; -data(key: "ejTreeGrid"): ej.TreeGrid; -ejTreeMap(): JQuery; ejTreeMap(options?: ej.datavisualization.TreeMap.Model): JQuery; ejTreeMap(memberName: any, value?: any, param?: any): any; -data(key: "ejTreeMap"): ej.datavisualization.TreeMap; -ejTreeView(): JQuery; ejTreeView(options?: ej.TreeView.Model): JQuery; ejTreeView(memberName: any, value?: any, param?: any): any; -data(key: "ejTreeView"): ej.TreeView; -ejUploadbox(): JQuery; ejUploadbox(options?: ej.Uploadbox.Model): JQuery; ejUploadbox(memberName: any, value?: any, param?: any): any; -data(key: "ejUploadbox"): ej.Uploadbox; -ejWaitingPopup(): JQuery; ejWaitingPopup(options?: ej.WaitingPopup.Model): JQuery; ejWaitingPopup(memberName: any, value?: any, param?: any): any; + +data(key: "ejAccordion"): ej.Accordion; +data(key: "ejAutocomplete"): ej.Autocomplete; +data(key: "ejBarcode"): ej.datavisualization.Barcode; +data(key: "ejBulletGraph"): ej.datavisualization.BulletGraph; +data(key: "ejButton"): ej.Button; +data(key: "ejCaptcha"): ej.Captcha; +data(key: "ejChart"): ej.datavisualization.Chart; +data(key: "ejCheckBox"): ej.CheckBox; +data(key: "ejCircularGauge"): ej.datavisualization.CircularGauge; +data(key: "ejColorPicker"): ej.ColorPicker; +data(key: "ejDatePicker"): ej.DatePicker; +data(key: "ejDateRangePicker"): ej.DateRangePicker; +data(key: "ejDateTimePicker"): ej.DateTimePicker; +data(key: "ejDiagram"): ej.datavisualization.Diagram; +data(key: "ejDialog"): ej.Dialog; +data(key: "ejDigitalGauge"): ej.datavisualization.DigitalGauge; +data(key: "ejDocumentEditor"): ej.DocumentEditor; +data(key: "ejDraggable"): ej.Draggable; +data(key: "ejDropDownList"): ej.DropDownList; +data(key: "ejDroppable"): ej.Droppable; +data(key: "ejFileExplorer"): ej.FileExplorer; +data(key: "ejGantt"): ej.Gantt; +data(key: "ejGrid"): ej.Grid; +data(key: "ejGroupButton"): ej.GroupButton; +data(key: "ejHeatMap"): ej.datavisualization.HeatMap; +data(key: "ejHeatMapLegend"): ej.datavisualization.HeatMapLegend; +data(key: "ejKanban"): ej.Kanban; +data(key: "ejLinearGauge"): ej.datavisualization.LinearGauge; +data(key: "ejListBox"): ej.ListBox; +data(key: "ejListView"): ej.ListView; +data(key: "ejMap"): ej.datavisualization.Map; +data(key: "ejMaskEdit"): ej.MaskEdit; +data(key: "ejMenu"): ej.Menu; +data(key: "ejNavigationDrawer"): ej.NavigationDrawer; +data(key: "ejOverview"): ej.datavisualization.Overview; +data(key: "ejPager"): ej.Pager; +data(key: "ejPdfViewer"): ej.PdfViewer; +data(key: "ejPivotChart"): ej.PivotChart; +data(key: "ejPivotClient"): ej.PivotClient; +data(key: "ejPivotGauge"): ej.PivotGauge; +data(key: "ejPivotGrid"): ej.PivotGrid; +data(key: "ejPivotPager"): ej.PivotPager; +data(key: "ejPivotSchemaDesigner"): ej.PivotSchemaDesigner; +data(key: "ejPivotTreeMap"): ej.PivotTreeMap; +data(key: "ejProgressBar"): ej.ProgressBar; +data(key: "ejRadialMenu"): ej.RadialMenu; +data(key: "ejRadialSlider"): ej.RadialSlider; +data(key: "ejRadioButton"): ej.RadioButton; +data(key: "ejRangeNavigator"): ej.datavisualization.RangeNavigator; +data(key: "ejRating"): ej.Rating; +data(key: "ejRecurrenceEditor"): ej.RecurrenceEditor; +data(key: "ejReportViewer"): ej.ReportViewer; +data(key: "ejResizable"): ej.Resizable; +data(key: "ejRibbon"): ej.Ribbon; +data(key: "ejRotator"): ej.Rotator; +data(key: "ejRTE"): ej.RTE; +data(key: "ejSchedule"): ej.Schedule; +data(key: "ejScroller"): ej.Scroller; +data(key: "ejSignature"): ej.Signature; +data(key: "ejSlider"): ej.Slider; +data(key: "ejSparkline"): ej.datavisualization.Sparkline; +data(key: "ejSpellCheck"): ej.SpellCheck; +data(key: "ejSplitButton"): ej.SplitButton; +data(key: "ejSplitter"): ej.Splitter; +data(key: "ejSpreadsheet"): ej.Spreadsheet; +data(key: "ejSunburstChart"): ej.datavisualization.SunburstChart; +data(key: "ejSymbolPalette"): ej.datavisualization.SymbolPalette; +data(key: "ejTab"): ej.Tab; +data(key: "ejTagCloud"): ej.TagCloud; +data(key: "ejNumericTextbox"): ej.NumericTextbox; +data(key: "ejCurrencyTextbox"): ej.CurrencyTextbox; +data(key: "ejPercentageTextbox"): ej.PercentageTextbox; +data(key: "ejTile"): ej.Tile; +data(key: "ejTimePicker"): ej.TimePicker; +data(key: "ejToggleButton"): ej.ToggleButton; +data(key: "ejToolbar"): ej.Toolbar; +data(key: "ejTooltip"): ej.Tooltip; +data(key: "ejTreeGrid"): ej.TreeGrid; +data(key: "ejTreeMap"): ej.datavisualization.TreeMap; +data(key: "ejTreeView"): ej.TreeView; +data(key: "ejUploadbox"): ej.Uploadbox; data(key: "ejWaitingPopup"): ej.WaitingPopup; -} +} \ No newline at end of file diff --git a/ej.web.all/tslint.json b/ej.web.all/tslint.json new file mode 100644 index 0000000000..b0b7c81ba5 --- /dev/null +++ b/ej.web.all/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/elasticsearch/index.d.ts b/elasticsearch/index.d.ts index 84c8f281f9..a0606a4961 100644 --- a/elasticsearch/index.d.ts +++ b/elasticsearch/index.d.ts @@ -88,6 +88,7 @@ declare module Elasticsearch { export interface ConfigOptions { host?: any; hosts?: any; + httpAuth?: string; log?: any; apiVersion?: string; plugins?: any; diff --git a/electron-devtools-installer/electron-devtools-installer-tests.ts b/electron-devtools-installer/electron-devtools-installer-tests.ts index a923e2b20e..a453221698 100644 --- a/electron-devtools-installer/electron-devtools-installer-tests.ts +++ b/electron-devtools-installer/electron-devtools-installer-tests.ts @@ -1,5 +1,3 @@ -/// - import installExtension, { EMBER_INSPECTOR, REACT_DEVELOPER_TOOLS, BACKBONE_DEBUGGER, JQUERY_DEBUGGER, diff --git a/electron/index.d.ts b/electron/index.d.ts index 448df1915f..0b98ae1944 100644 --- a/electron/index.d.ts +++ b/electron/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Electron v1.4.8 // Project: http://electron.atom.io/ -// Definitions by: jedmao , rhysd , Milan Burda , aliib +// Definitions by: jedmao , rhysd , Milan Burda , aliib , Daniel Perez Alvarez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -398,6 +398,20 @@ declare namespace Electron { * This method can only be called before app is ready. */ disableHardwareAcceleration(): void; + /** + * Sets the counter badge for current app. Setting the count to 0 will hide the badge. + * + * @returns True when the call succeeded, otherwise returns false. + * + * Note: This API is only available on macOS and Linux. + */ + setBadgeCount(count: number): boolean; + /** + * @returns The current value displayed in the counter badge. + * + * Note: This API is only available on macOS and Linux. + */ + getBadgeCount(): number; /** * @returns whether current desktop environment is Unity launcher. (Linux) * @@ -505,20 +519,6 @@ declare namespace Electron { * Note: This API is only available on macOS. */ getBadge(): string; - /** - * Sets the counter badge for current app. Setting the count to 0 will hide the badge. - * - * @returns True when the call succeeded, otherwise returns false. - * - * Note: This API is only available on macOS and Linux. - */ - setBadgeCount(count: number): boolean; - /** - * @returns The current value displayed in the counter badge. - * - * Note: This API is only available on macOS and Linux. - */ - getBadgeCount(): number; /** * Hides the dock icon. * diff --git a/electron/test/main.ts b/electron/test/main.ts index 9912b62eea..276a15d851 100644 --- a/electron/test/main.ts +++ b/electron/test/main.ts @@ -232,7 +232,8 @@ app.dock.setBadge('foo'); var id = app.dock.bounce('informational'); app.dock.cancelBounce(id); app.dock.setIcon('/path/to/icon.png'); -app.dock.setBadgeCount(app.dock.getBadgeCount() + 1); + +app.setBadgeCount(app.getBadgeCount() + 1); app.setUserTasks([ { diff --git a/ember/v1/ember-tests.ts b/ember/v1/ember-tests.ts index 25ca3e3cc5..103fb0146e 100644 --- a/ember/v1/ember-tests.ts +++ b/ember/v1/ember-tests.ts @@ -1,6 +1,3 @@ -/// - - var App : any; App = Em.Application.create(); diff --git a/esprima/esprima-tests.ts b/esprima/esprima-tests.ts index d7c748d3b8..60b54e0679 100644 --- a/esprima/esprima-tests.ts +++ b/esprima/esprima-tests.ts @@ -1,6 +1,3 @@ -/// - - import esprima = require('esprima'); import * as ESTree from 'estree'; diff --git a/express-serve-static-core/index.d.ts b/express-serve-static-core/index.d.ts index 42f1a535f7..a4ce9612e7 100644 --- a/express-serve-static-core/index.d.ts +++ b/express-serve-static-core/index.d.ts @@ -848,6 +848,8 @@ interface Response extends http.ServerResponse, Express.Response { * */ vary(field: string): Response; + + app: Application; } interface Handler extends RequestHandler { } diff --git a/extended-listbox/extended-listbox-tests.ts b/extended-listbox/extended-listbox-tests.ts index 0ca2f862b1..dfa51ffebf 100644 --- a/extended-listbox/extended-listbox-tests.ts +++ b/extended-listbox/extended-listbox-tests.ts @@ -1,5 +1,4 @@ - - +/// var $test = $("#test"); @@ -126,54 +125,3 @@ instance.onItemEnterPressed((event: ListboxEvent) => { instance.onItemDoubleClicked((event: ListboxEvent) => { console.log(event.args); }); - - - -/////// LEGACY API /////// - -// Add string item -instance.target.listbox("addItem", "Test2"); - - -// Add item -var item: ListboxItem = {}; -item.selected = true; -item.disabled = false; -item.childItems = ["Test4"]; -item.groupHeader = false; -item.id = "ouetioreit"; -item.index = 0; -item.text = "Test3"; -var id: string = instance.target.listbox("addItem", item); - - -// Remove item -instance.target.listbox("removeItem", id); - - -// Get item -var i: ListboxItem = instance.target.listbox("getItem", id); - - -// Get items -var allItems: ListboxItem[] = instance.target.listbox("getItems"); - - -// Move item up -var newIndex: number = instance.target.listbox("moveItemUp", i.id); - - -// Move item down -newIndex = instance.target.listbox("moveItemDown", i.id); - - -// Clear selection -instance.target.listbox("clearSelection"); - - -// Enable -instance.target.listbox("enable", false); - - -// Destroy -instance.target.listbox("destroy"); diff --git a/extended-listbox/index.d.ts b/extended-listbox/index.d.ts index eb5f0eec04..3f3527b903 100644 --- a/extended-listbox/index.d.ts +++ b/extended-listbox/index.d.ts @@ -1,10 +1,8 @@ -// Type definitions for extended-listbox 1.1.x +// Type definitions for extended-listbox 2.0.x // Project: https://github.com/code-chris/extended-listbox // Definitions by: Christian Kotzbauer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - interface ListboxItem { /** display text */ text?: string; @@ -147,37 +145,4 @@ interface JQuery { /** constructs a new instance of Listbox on the given DOM item */ listbox(options: ListBoxOptions): ExtendedListboxInstance|ExtendedListboxInstance[]; - - /** @deprecated: use method in ExtendedListboxInstance */ - listbox(methodName: 'addItem'): string; - - /** @deprecated: use method in ExtendedListboxInstance */ - listbox(methodName: 'removeItem'): void; - - /** @deprecated: use method in ExtendedListboxInstance */ - listbox(methodName: 'destroy'): void; - - /** @deprecated: use method in ExtendedListboxInstance */ - listbox(methodName: 'getItem'): ListboxItem; - - /** @deprecated: use method in ExtendedListboxInstance */ - listbox(methodName: 'getItems'): ListboxItem[]; - - /** @deprecated: use method in ExtendedListboxInstance */ - listbox(methodName: 'moveItemUp'): number; - - /** @deprecated: use method in ExtendedListboxInstance */ - listbox(methodName: 'moveItemDown'): number; - - /** @deprecated: use method in ExtendedListboxInstance */ - listbox(methodName: 'clearSelection'): void; - - /** @deprecated: use method in ExtendedListboxInstance */ - listbox(methodName: 'enable'): void; - - /** @deprecated: use method in ExtendedListboxInstance */ - listbox(methodName: string): any; - - /** @deprecated: use method in ExtendedListboxInstance */ - listbox(methodName: string, methodParameter: any): any; } diff --git a/extract-text-webpack-plugin/extract-text-webpack-plugin-tests.ts b/extract-text-webpack-plugin/extract-text-webpack-plugin-tests.ts index 63177ebde3..ca992ea3ef 100644 --- a/extract-text-webpack-plugin/extract-text-webpack-plugin-tests.ts +++ b/extract-text-webpack-plugin/extract-text-webpack-plugin-tests.ts @@ -22,18 +22,18 @@ configuration = { // Extract css files { test: /\.css$/, - loader: ExtractTextPlugin.extract({ - fallbackLoader: "style-loader", - loader: "css-loader", + use: ExtractTextPlugin.extract({ + fallback: "style-loader", + use: "css-loader", }) }, // Optionally extract less files // or any other compile-to-css language { test: /\.less$/, - loader: ExtractTextPlugin.extract({ - fallbackLoader: "style-loader", - loader: ["css-loader", "less-loader"], + use: ExtractTextPlugin.extract({ + fallback: "style-loader", + use: ["css-loader", "less-loader"], }) } // You could also use other loaders the same way. I. e. the autoprefixer-loader @@ -70,10 +70,13 @@ configuration = { // ... module: { rules: [ - { test: /\.css$/, loader: ExtractTextPlugin.extract({ - fallbackLoader: "style-loader", - loader: "css-loader" - }) } + { + test: /\.css$/, + use: ExtractTextPlugin.extract({ + fallback: "style-loader", + use: "css-loader" + }) + } ] }, plugins: [ @@ -89,8 +92,8 @@ configuration = { // ... module: { rules: [ - { test: /\.scss$/i, loader: extractCSS.extract(['css','sass']) }, - { test: /\.less$/i, loader: extractLESS.extract(['css','less']) }, + { test: /\.scss$/i, use: extractCSS.extract(['css','sass']) }, + { test: /\.less$/i, use: extractLESS.extract(['css','less']) }, ] }, plugins: [ diff --git a/extract-text-webpack-plugin/index.d.ts b/extract-text-webpack-plugin/index.d.ts index 21052b08c1..6da0c183c3 100644 --- a/extract-text-webpack-plugin/index.d.ts +++ b/extract-text-webpack-plugin/index.d.ts @@ -1,15 +1,15 @@ // Type definitions for extract-text-webpack-plugin 2.0.0 -// Project: https://github.com/webpack/extract-text-webpack-plugin -// Definitions by: flying-sheep +// Project: https://github.com/webpack-contrib/extract-text-webpack-plugin +// Definitions by: flying-sheep , kayo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import { Plugin, OldLoader } from 'webpack' +import { Plugin, OldLoader, NewLoader } from 'webpack' /** * extract-text-webpack-plugin has no support for .options instead of .query yet. * See https://github.com/webpack/extract-text-webpack-plugin/issues/281 */ -type Loader = string | OldLoader +type Loader = string | OldLoader | NewLoader interface ExtractPluginOptions { /** the filename of the result file. May contain `[name]`, `[id]` and `[contenthash]` */ @@ -24,9 +24,9 @@ interface ExtractPluginOptions { interface ExtractOptions { /** the loader(s) that should be used for converting the resource to a css exporting module */ - loader: Loader | Loader[] + use: Loader | Loader[] /** the loader(s) that should be used when the css is not extracted (i.e. in an additional chunk when `allChunks: false`) */ - fallbackLoader?: Loader | Loader[] + fallback?: Loader | Loader[] /** override the `publicPath` setting for this loader */ publicPath?: string } diff --git a/facebook-js-sdk/index.d.ts b/facebook-js-sdk/index.d.ts index a7b78e73b0..cb1981580a 100644 --- a/facebook-js-sdk/index.d.ts +++ b/facebook-js-sdk/index.d.ts @@ -172,6 +172,7 @@ declare namespace facebook { authResponse: { accessToken: string; expiresIn: number; + grantedScopes: string; signedRequest: string; userID: string; }; diff --git a/faker/faker-tests.ts b/faker/faker-tests.ts index 4dc2a3735f..5fb6a53746 100644 --- a/faker/faker-tests.ts +++ b/faker/faker-tests.ts @@ -52,6 +52,11 @@ resultStr = faker.company.bsAdjective(); resultStr = faker.company.bsBuzz(); resultStr = faker.company.bsNoun(); +resultStr = faker.database.column(); +resultStr = faker.database.type(); +resultStr = faker.database.collation(); +resultStr = faker.database.engine(); + resultDate = faker.date.past(); resultDate = faker.date.future(); resultDate = faker.date.between('foo', 'bar'); @@ -80,6 +85,8 @@ resultStr = faker.finance.transactionType(); resultStr = faker.finance.currencyCode(); resultStr = faker.finance.currencyName(); resultStr = faker.finance.currencySymbol(); +resultStr = faker.finance.bitcoinAddress(); +resultStr = faker.finance.bic(); resultStr = faker.hacker.abbreviation(); resultStr = faker.hacker.adjective(); @@ -110,6 +117,8 @@ resultStr = userCard.address.suite; resultStr = faker.internet.avatar(); resultStr = faker.internet.email(); resultStr = faker.internet.email('foo', 'bar', 'quux'); +resultStr = faker.internet.exampleEmail(); +resultStr = faker.internet.exampleEmail('foo', 'bar'); resultStr = faker.internet.protocol(); resultStr = faker.internet.url(); resultStr = faker.internet.domainName(); @@ -128,12 +137,18 @@ resultStr = faker.lorem.words(); resultStr = faker.lorem.words(0); resultStr = faker.lorem.sentence(); resultStr = faker.lorem.sentence(0, 0); +resultStr = faker.lorem.slug(); +resultStr = faker.lorem.slug(0); resultStr = faker.lorem.sentences(); resultStr = faker.lorem.sentences(0); resultStr = faker.lorem.paragraph(); resultStr = faker.lorem.paragraph(0); resultStr = faker.lorem.paragraphs(); resultStr = faker.lorem.paragraphs(0, ''); +resultStr = faker.lorem.text(); +resultStr = faker.lorem.text(0); +resultStr = faker.lorem.lines(); +resultStr = faker.lorem.lines(0); resultStr = faker.name.firstName(); resultStr = faker.name.firstName(0); @@ -169,6 +184,13 @@ resultStr = faker.random.objectElement(); resultStr = faker.random.objectElement({foo: 'bar', field: 'foo'}); resultStr = faker.random.uuid(); resultBool = faker.random.boolean(); +resultStr = faker.random.word(); +resultStr = faker.random.words(); +resultStr = faker.random.words(0); +resultStr = faker.random.image(); +resultStr = faker.random.locale(); +resultStr = faker.random.alphaNumeric(); +resultStr = faker.random.alphaNumeric(0); resultStr = faker.system.fileName( "foo", "bar" ); resultStr = faker.system.commonFileName( "foo", "bar" ); diff --git a/faker/index.d.ts b/faker/index.d.ts index 01e01b8b8b..ccca40e51a 100644 --- a/faker/index.d.ts +++ b/faker/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for faker v3.1 +// Type definitions for faker v4.1.0 // Project: http://marak.com/faker.js/ -// Definitions by: Bas Pennings , Yuki Kokubun +// Definitions by: Ben Swartz , Bas Pennings , Yuki Kokubun // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare var fakerStatic: Faker.FakerStatic; @@ -52,6 +52,13 @@ declare namespace Faker { bsNoun(): string; }; + database: { + column(): string; + type(): string; + collation(): string; + engine(): string; + }; + date: { past(years?: number, refDate?: string|Date): Date; future(years?: number, refDate?: string|Date): Date; @@ -72,6 +79,8 @@ declare namespace Faker { currencyCode(): string; currencyName(): string; currencySymbol(): string; + bitcoinAddress(): string; + bic(): string }; hacker: { @@ -116,11 +125,13 @@ declare namespace Faker { sports(width?: number, height?: number): string; technics(width?: number, height?: number): string; transport(width?: number, height?: number): string; + dataUri(width?: number, height?: number): string; }; internet: { avatar(): string; email(firstName?: string, lastName?: string, provider?: string): string; + exampleEmail(firstName?: string, lastName?: string): string; userName(firstName?: string, lastName?: string): string; protocol(): string; url(): string; @@ -128,6 +139,7 @@ declare namespace Faker { domainSuffix(): string; domainWord(): string; ip(): string; + ipv6(): string; userAgent(): string; color(baseRed255?: number, baseGreen255?: number, baseBlue255?: number): string; mac(): string; @@ -138,9 +150,12 @@ declare namespace Faker { word(): string; words(num?: number): string; sentence(wordCount?: number, range?: number): string; + slug(wordCount?: number): string; sentences(sentenceCount?: number): string; paragraph(sentenceCount?: number): string; paragraphs(paragraphCount?: number, separator?: string): string; + text(times?: number): string; + lines(lineCount?: number): string; }; name: { @@ -171,6 +186,11 @@ declare namespace Faker { objectElement(object?: { [key: string]: T }, field?: any): T; uuid(): string; boolean(): boolean; + word(): string; // TODO: have ability to return specific type of word? As in: noun, adjective, verb, etc + words(count?: number): string; + image(): string; + locale(): string; + alphaNumeric(count?: number): string; }; system: { @@ -275,6 +295,14 @@ declare module "faker" { export = fakerStatic; } +declare module "faker/locale/az" { + export = fakerStatic; +} + +declare module "faker/locale/cz" { + export = fakerStatic; +} + declare module "faker/locale/de" { export = fakerStatic; } @@ -351,6 +379,10 @@ declare module "faker/locale/ge" { export = fakerStatic; } +declare module "faker/locale/id_ID" { + export = fakerStatic; +} + declare module "faker/locale/it" { export = fakerStatic; } diff --git a/faker/tsconfig.json b/faker/tsconfig.json index c2ce14c941..0589e5dc54 100644 --- a/faker/tsconfig.json +++ b/faker/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,4 +19,4 @@ "index.d.ts", "faker-tests.ts" ] -} \ No newline at end of file +} diff --git a/faker/v3/faker-tests.ts b/faker/v3/faker-tests.ts new file mode 100644 index 0000000000..4dc2a3735f --- /dev/null +++ b/faker/v3/faker-tests.ts @@ -0,0 +1,183 @@ + + +let resultStr: string; +let resultBool: boolean; +let resultNum: number; +let resultStrArr: string[]; +let resultDate: Date; + +import faker = require('faker'); +faker.locale = 'en'; + +resultStr = faker.address.zipCode(); +resultStr = faker.address.zipCode('###'); +resultStr = faker.address.city(); +resultStr = faker.address.city(0); +resultStr = faker.address.cityPrefix(); +resultStr = faker.address.citySuffix(); +resultStr = faker.address.streetName(); +resultStr = faker.address.streetAddress(); +resultStr = faker.address.streetAddress(false);; +resultStr = faker.address.streetSuffix(); +resultStr = faker.address.streetPrefix(); +resultStr = faker.address.secondaryAddress(); +resultStr = faker.address.county(); +resultStr = faker.address.country(); +resultStr = faker.address.countryCode(); +resultStr = faker.address.state(); +resultStr = faker.address.state(false); +resultStr = faker.address.stateAbbr(); +resultStr = faker.address.latitude(); +resultStr = faker.address.longitude(); + +resultStr = faker.commerce.color(); +resultStr = faker.commerce.department(); +resultStr = faker.commerce.productName(); +resultStr = faker.commerce.price(); +resultStr = faker.commerce.price(0, 0, 0, '#'); +resultStr = faker.commerce.productAdjective(); +resultStr = faker.commerce.productMaterial(); +resultStr = faker.commerce.product(); + +resultStrArr = faker.company.suffixes(); +resultStr = faker.company.companyName(); +resultStr = faker.company.companyName(0); +resultStr = faker.company.companySuffix(); +resultStr = faker.company.catchPhrase(); +resultStr = faker.company.bs(); +resultStr = faker.company.catchPhraseAdjective(); +resultStr = faker.company.catchPhraseDescriptor(); +resultStr = faker.company.catchPhraseNoun(); +resultStr = faker.company.bsAdjective(); +resultStr = faker.company.bsBuzz(); +resultStr = faker.company.bsNoun(); + +resultDate = faker.date.past(); +resultDate = faker.date.future(); +resultDate = faker.date.between('foo', 'bar'); +resultDate = faker.date.between(new Date(), new Date()); +resultDate = faker.date.recent(); +resultDate = faker.date.recent(100); +resultStr = faker.date.month(); +resultStr = faker.date.month({ + abbr: true, + context: true +}); +resultStr = faker.date.weekday(); +resultStr = faker.date.weekday({ + abbr: true, + context: true +}); + +resultStr = faker.finance.account(); +resultStr = faker.finance.account(0); +resultStr = faker.finance.accountName(); +resultStr = faker.finance.mask(); +resultStr = faker.finance.mask(0, false, false); +resultStr = faker.finance.amount(); +resultStr = faker.finance.amount(0, 0, 0, '#'); +resultStr = faker.finance.transactionType(); +resultStr = faker.finance.currencyCode(); +resultStr = faker.finance.currencyName(); +resultStr = faker.finance.currencySymbol(); + +resultStr = faker.hacker.abbreviation(); +resultStr = faker.hacker.adjective(); +resultStr = faker.hacker.noun(); +resultStr = faker.hacker.verb(); +resultStr = faker.hacker.ingverb(); +resultStr = faker.hacker.phrase(); + +resultStr = faker.helpers.randomize(); +resultNum = faker.helpers.randomize([1,2,3,4]); +resultStr = faker.helpers.randomize(['foo', 'bar', 'quux']); +resultStr = faker.helpers.slugify('foo bar quux'); +resultStr = faker.helpers.replaceSymbolWithNumber('foo# bar#'); +resultStr = faker.helpers.replaceSymbols('foo# bar? quux#'); +resultStrArr = faker.helpers.shuffle(['foo', 'bar', 'quux']); +resultStr = faker.helpers.mustache('{{foo}}{{bar}}', {foo: 'x', bar: 'y'}); + +const card = faker.helpers.createCard(); +resultStr = card.name; +resultStr = card.address.streetA; +const contextualCard = faker.helpers.contextualCard(); +resultStr = contextualCard.name; +resultStr = contextualCard.address.suite; +const userCard = faker.helpers.userCard(); +resultStr = userCard.name; +resultStr = userCard.address.suite; + +resultStr = faker.internet.avatar(); +resultStr = faker.internet.email(); +resultStr = faker.internet.email('foo', 'bar', 'quux'); +resultStr = faker.internet.protocol(); +resultStr = faker.internet.url(); +resultStr = faker.internet.domainName(); +resultStr = faker.internet.domainSuffix(); +resultStr = faker.internet.domainWord(); +resultStr = faker.internet.ip(); +resultStr = faker.internet.userAgent(); +resultStr = faker.internet.color(); +resultStr = faker.internet.color(0, 0, 0); +resultStr = faker.internet.mac(); +resultStr = faker.internet.password(); +resultStr = faker.internet.password(0, false, '#', 'foo'); + +resultStr = faker.lorem.word(); +resultStr = faker.lorem.words(); +resultStr = faker.lorem.words(0); +resultStr = faker.lorem.sentence(); +resultStr = faker.lorem.sentence(0, 0); +resultStr = faker.lorem.sentences(); +resultStr = faker.lorem.sentences(0); +resultStr = faker.lorem.paragraph(); +resultStr = faker.lorem.paragraph(0); +resultStr = faker.lorem.paragraphs(); +resultStr = faker.lorem.paragraphs(0, ''); + +resultStr = faker.name.firstName(); +resultStr = faker.name.firstName(0); +resultStr = faker.name.lastName(); +resultStr = faker.name.lastName(0); +resultStr = faker.name.findName(); +resultStr = faker.name.findName('', '', 0); +resultStr = faker.name.jobTitle(); +resultStr = faker.name.prefix(); +resultStr = faker.name.suffix(); +resultStr = faker.name.title(); +resultStr = faker.name.jobDescriptor(); +resultStr = faker.name.jobArea(); +resultStr = faker.name.jobType(); + +resultStr = faker.phone.phoneNumber(); +resultStr = faker.phone.phoneNumber('#'); +resultStr = faker.phone.phoneNumberFormat(); +// https://github.com/Marak/faker.js/blob/master/lib/phone_number.js#L9-L13 +resultStr = faker.phone.phoneNumberFormat(0); +resultStr = faker.phone.phoneFormats(); + +resultNum = faker.random.number(); +resultNum = faker.random.number(0); +resultNum = faker.random.number({ + min: 0, + max: 0, + precision: 0 +}); +resultStr = faker.random.arrayElement(); +resultStr = faker.random.arrayElement(['foo', 'bar', 'quux']) +resultStr = faker.random.objectElement(); +resultStr = faker.random.objectElement({foo: 'bar', field: 'foo'}); +resultStr = faker.random.uuid(); +resultBool = faker.random.boolean(); + +resultStr = faker.system.fileName( "foo", "bar" ); +resultStr = faker.system.commonFileName( "foo", "bar" ); +resultStr = faker.system.mimeType(); +resultStr = faker.system.commonFileType(); +resultStr = faker.system.commonFileExt(); +resultStr = faker.system.fileType(); +resultStr = faker.system.fileExt( "foo" ); +resultStr = faker.system.semver(); + +import fakerEn = require('faker/locale/en'); +resultStr = faker.name.firstName(); diff --git a/faker/v3/index.d.ts b/faker/v3/index.d.ts new file mode 100644 index 0000000000..01e01b8b8b --- /dev/null +++ b/faker/v3/index.d.ts @@ -0,0 +1,416 @@ +// Type definitions for faker v3.1 +// Project: http://marak.com/faker.js/ +// Definitions by: Bas Pennings , Yuki Kokubun +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare var fakerStatic: Faker.FakerStatic; + +declare namespace Faker { + interface FakerStatic { + locale: string; + + address: { + zipCode(format?: string): string; + city(format?: number): string; + cityPrefix(): string; + citySuffix(): string; + streetName(): string; + streetAddress(useFullAddress?: boolean): string; + streetSuffix(): string; + streetPrefix(): string; + secondaryAddress(): string; + county(): string; + country(): string; + countryCode(): string; + state(useAbbr?: boolean): string; + stateAbbr(): string; + latitude(): string; + longitude(): string; + }; + + commerce: { + color(): string; + department(): string; + productName(): string; + price(min?: number, max?: number, dec?: number, symbol?: string): string; + productAdjective(): string; + productMaterial(): string; + product(): string; + }; + + company: { + suffixes(): string[]; + companyName(format?: number): string; + companySuffix(): string; + catchPhrase(): string; + bs(): string; + catchPhraseAdjective(): string; + catchPhraseDescriptor(): string; + catchPhraseNoun(): string; + bsAdjective(): string; + bsBuzz(): string; + bsNoun(): string; + }; + + date: { + past(years?: number, refDate?: string|Date): Date; + future(years?: number, refDate?: string|Date): Date; + between(from: string|number|Date, to: string|Date): Date; + recent(days?: number): Date; + month(options?: { abbr?: boolean, context?: boolean }): string; + weekday(options?: { abbr?: boolean, context?: boolean }): string; + }; + + fake(str: string): string; + + finance: { + account(length?: number): string; + accountName(): string; + mask(length?: number, parens?: boolean, elipsis?: boolean): string; + amount(min?:number, max?: number, dec?: number, symbol?: string): string; + transactionType(): string; + currencyCode(): string; + currencyName(): string; + currencySymbol(): string; + }; + + hacker: { + abbreviation(): string; + adjective(): string; + noun(): string; + verb(): string; + ingverb(): string; + phrase(): string; + }; + + helpers: { + randomize(array: T[]): T; + randomize(): string; + slugify(string?: string): string; + replaceSymbolWithNumber(string?: string, symbol?: string): string; + replaceSymbols(string?: string): string; + shuffle(o: T[]): T[]; + shuffle(): string[]; + mustache(str: string, data: { [key: string]: string|((substring: string, ...args: any[]) => string) }): string; + createCard(): Faker.Card; + contextualCard(): Faker.ContextualCard; + userCard(): Faker.UserCard; + createTransaction(): Faker.Transaction; + }; + + + image: { + image(): string; + avatar(): string; + imageUrl(width?: number, height?: number, category?: string): string; + abstract(width?: number, height?: number): string; + animals(width?: number, height?: number): string; + business(width?: number, height?: number): string; + cats(width?: number, height?: number): string; + city(width?: number, height?: number): string; + food(width?: number, height?: number): string; + nightlife(width?: number, height?: number): string; + fashion(width?: number, height?: number): string; + people(width?: number, height?: number): string; + nature(width?: number, height?: number): string; + sports(width?: number, height?: number): string; + technics(width?: number, height?: number): string; + transport(width?: number, height?: number): string; + }; + + internet: { + avatar(): string; + email(firstName?: string, lastName?: string, provider?: string): string; + userName(firstName?: string, lastName?: string): string; + protocol(): string; + url(): string; + domainName(): string; + domainSuffix(): string; + domainWord(): string; + ip(): string; + userAgent(): string; + color(baseRed255?: number, baseGreen255?: number, baseBlue255?: number): string; + mac(): string; + password(len?: number, memorable?: boolean, pattern?: string|RegExp, prefix?: string): string; + }; + + lorem: { + word(): string; + words(num?: number): string; + sentence(wordCount?: number, range?: number): string; + sentences(sentenceCount?: number): string; + paragraph(sentenceCount?: number): string; + paragraphs(paragraphCount?: number, separator?: string): string; + }; + + name: { + firstName(gender?: number): string; + lastName(gender?: number): string; + findName(firstName?: string, lastName?: string, gender?: number): string; + jobTitle(): string; + prefix(): string; + suffix(): string; + title(): string; + jobDescriptor(): string; + jobArea(): string; + jobType(): string; + }; + + phone: { + phoneNumber(format?: string): string; + phoneNumberFormat(phoneFormatsArrayIndex?: number): string; + phoneFormats(): string; + }; + + random: { + number(max: number): number; + number(options?: { min?: number, max?: number, precision?: number }): number; + arrayElement(): string; + arrayElement(array: T[]): T; + objectElement(object?: { [key: string]: any }, field?: "key"): string; + objectElement(object?: { [key: string]: T }, field?: any): T; + uuid(): string; + boolean(): boolean; + }; + + system: { + fileName(ext: string, type: string): string; + commonFileName(ext: string, type: string): string; + mimeType(): string; + commonFileType(): string; + commonFileExt(): string; + fileType(): string; + fileExt(mimeType: string): string; + //directoryPath(): string; + //filePath(): string; + semver(): string; + }; + + seed(value: number): void; + } + + interface Card { + name: string; + username: string; + email: string; + address: FullAddress; + phone: string; + website: string; + company: Company; + posts: Post[]; + accountHistory: string[]; + } + + interface FullAddress { + streetA: string; + streetB: string; + streetC: string; + streetD: string; + city: string; + state: string; + county: string; + zipcode: string; + geo: Geo; + } + + interface Geo { + lat: string; + lng: string; + } + + interface Company { + name: string; + catchPhrase: string; + bs: string; + } + + interface Post { + words: string; + sentence: string; + sentences: string; + paragraph: string; + } + + interface ContextualCard { + name: string; + username: string; + email: string; + dob: Date; + phone: string; + address: Address; + website: string; + company: Company; + } + + interface Address { + street: string; + suite: string; + city: string; + state: string; + zipcode: string; + geo: Geo; + } + + interface UserCard { + name: string; + username: string; + email: string; + address: Address; + phone: string; + website: string; + company: Company; + } + + interface Transaction { + amount: string; + date: Date; + business: string; + name: string; + type: string; + account: string; + } +} + +declare module "faker" { + export = fakerStatic; +} + +declare module "faker/locale/de" { + export = fakerStatic; +} + +declare module "faker/locale/de_AT" { + export = fakerStatic; +} + +declare module "faker/locale/de_CH" { + export = fakerStatic; +} + +declare module "faker/locale/el_GR" { + export = fakerStatic; +} + +declare module "faker/locale/en" { + export = fakerStatic; +} + +declare module "faker/locale/en_AU" { + export = fakerStatic; +} + +declare module "faker/locale/en_BORK" { + export = fakerStatic; +} + +declare module "faker/locale/en_CA" { + export = fakerStatic; +} + +declare module "faker/locale/en_GB" { + export = fakerStatic; +} + +declare module "faker/locale/en_IE" { + export = fakerStatic; +} + +declare module "faker/locale/en_IND" { + export = fakerStatic; +} + +declare module "faker/locale/en_US" { + export = fakerStatic; +} + +declare module "faker/locale/en_au_ocker" { + export = fakerStatic; +} + +declare module "faker/locale/es" { + export = fakerStatic; +} + +declare module "faker/locale/es_MX" { + export = fakerStatic; +} + +declare module "faker/locale/fa" { + export = fakerStatic; +} + +declare module "faker/locale/fr" { + export = fakerStatic; +} + +declare module "faker/locale/fr_CA" { + export = fakerStatic; +} + +declare module "faker/locale/ge" { + export = fakerStatic; +} + +declare module "faker/locale/it" { + export = fakerStatic; +} + +declare module "faker/locale/ja" { + export = fakerStatic; +} + +declare module "faker/locale/ko" { + export = fakerStatic; +} + +declare module "faker/locale/nb_NO" { + export = fakerStatic; +} + +declare module "faker/locale/nep" { + export = fakerStatic; +} + +declare module "faker/locale/nl" { + export = fakerStatic; +} + +declare module "faker/locale/pl" { + export = fakerStatic; +} + +declare module "faker/locale/pt_BR" { + export = fakerStatic; +} + +declare module "faker/locale/ru" { + export = fakerStatic; +} + +declare module "faker/locale/sk" { + export = fakerStatic; +} + +declare module "faker/locale/sv" { + export = fakerStatic; +} + +declare module "faker/locale/tr" { + export = fakerStatic; +} + +declare module "faker/locale/uk" { + export = fakerStatic; +} + +declare module "faker/locale/vi" { + export = fakerStatic; +} + +declare module "faker/locale/zh_CN" { + export = fakerStatic; +} + +declare module "faker/locale/zh_TW" { + export = fakerStatic; +} diff --git a/faker/v3/tsconfig.json b/faker/v3/tsconfig.json new file mode 100644 index 0000000000..052493a9c7 --- /dev/null +++ b/faker/v3/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "faker": [ "faker/v3" ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "faker-tests.ts" + ] +} diff --git a/falcor-express/falcor-express-tests.ts b/falcor-express/falcor-express-tests.ts index f4a4ed8b52..c76a61f901 100644 --- a/falcor-express/falcor-express-tests.ts +++ b/falcor-express/falcor-express-tests.ts @@ -1,7 +1,3 @@ - -/// -/// - import express = require('express'); import Router = require('falcor-router'); import falcorExpress = require('falcor-express') diff --git a/fancybox/fancybox-tests.ts b/fancybox/fancybox-tests.ts index 2d5743c950..eac3f31771 100644 --- a/fancybox/fancybox-tests.ts +++ b/fancybox/fancybox-tests.ts @@ -1,6 +1,3 @@ -/// - - $('.fancybox').fancybox(); $('.fancybox').fancybox({ padding: 0, diff --git a/featherlight/featherlight-tests.ts b/featherlight/featherlight-tests.ts index 4d609d3475..e241a30990 100644 --- a/featherlight/featherlight-tests.ts +++ b/featherlight/featherlight-tests.ts @@ -1,7 +1,5 @@ // Tests by: Kaur Kuut -/// - // Every option as default var defaultOptions = { namespace: 'featherlight', diff --git a/fetch.io/fetch.io-tests.ts b/fetch.io/fetch.io-tests.ts new file mode 100644 index 0000000000..4e14a7a9a9 --- /dev/null +++ b/fetch.io/fetch.io-tests.ts @@ -0,0 +1,60 @@ + +import Fetch from 'fetch.io' + +const request = new Fetch() + +request + .get('') + .query({}) + .json() + +request + .delete('') + .json() + +request + .head('') + .json() + +request + .options('') + .json() + +request + .put('') + .json() + +request + .config('key', 'value') + .json() + +request + .config({key: 'value'}) + .json() + +request + .config('set', 'value') + .json() + +request + .set({key: 'value'}) + .json() + +request + .type('json') + .json() + +request + .get('') + .query({}) + .text() + +request + .get('') + .query({}) + .then(() => {}) + +request + .post('') + .send({}) + .json() diff --git a/fetch.io/index.d.ts b/fetch.io/index.d.ts new file mode 100644 index 0000000000..3c4ff7d781 --- /dev/null +++ b/fetch.io/index.d.ts @@ -0,0 +1,126 @@ +// Type definitions for fetch.io 3.1 +// Project: https://github.com/haoxins/fetch.io +// Definitions by: newraina +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + type TUrl = string; + + type TMethod = 'delete' | 'get' | 'head' | 'options' | 'post' | 'put'; + + interface Query { + [key: string]: number | boolean | string; + } + + interface Header { + [key: string]: string; + } + + interface Options extends RequestInit { + + prefix?: string; + + query?: Query; + + header?: Header; + + beforeRequest?(url: TUrl, body: BodyInit): boolean; + + afterResponse?(res: Response): void; + + afterJSON?(body: any): void; + } + + declare namespace FetchIo { + + class Request { + + constructor(method: TMethod, url: TUrl, options: Options) + + /** + * HTTP delete method + */ + delete: (url: TUrl) => this; + + /** + * HTTP get method + */ + get: (url: TUrl) => this; + + /** + * HTTP head method + */ + head: (url: TUrl) => this; + + /** + * HTTP options method + */ + options: (url: TUrl) => this; + + /** + * HTTP post method + */ + post: (url: TUrl) => this; + + /** + * HTTP put method + */ + put: (url: TUrl) => this; + + /** + * Set Options + */ + config(key: string, value: any): this + + config(opts: {[key: string]: any}): this + + /** + * Set Header + */ + set(key: string, value: any): this + + set(opts: {[key: string]: any}): this + + /** + * Set Content-Type + */ + type(type: 'json' | 'form' | 'urlencoded'): this + + /** + * Add query string + */ + query(object: {[key: string]: any}): this + + /** + * Send data + */ + send(data: {[key: string]: any}): this + + /** + * ppend formData + */ + append(key: string, value: string): this + + /** + * Get Response directly + */ + then(resolve: (value?: Response) => void, reject?: (reason?: any) => void): Promise + + /** + * Make Response to JSON + */ + json(strict?: boolean): Promise + + /** + * Make Response to string + */ + text(): Promise + } + + class Fetch extends Request { + constructor(options?: Options) + } +} + +export default FetchIo.Fetch; diff --git a/fetch.io/tsconfig.json b/fetch.io/tsconfig.json new file mode 100644 index 0000000000..8b05d3ca33 --- /dev/null +++ b/fetch.io/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fetch.io-tests.ts" + ] +} diff --git a/fetch.io/tslint.json b/fetch.io/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/fetch.io/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/file-type/index.d.ts b/file-type/index.d.ts index a1bc0d8466..3a88fe0a94 100644 --- a/file-type/index.d.ts +++ b/file-type/index.d.ts @@ -5,11 +5,13 @@ /// -interface FileTypeResult { - ext: string - mime: string +export = FileType; + +declare function FileType(buf: Buffer): FileType.FileTypeResult; + +declare namespace FileType { + export interface FileTypeResult { + ext: string; + mime: string; + } } - -declare function FileType(buf: Buffer): FileTypeResult - -export = FileType diff --git a/fine-uploader/index.d.ts b/fine-uploader/index.d.ts deleted file mode 100644 index dab4e720ea..0000000000 --- a/fine-uploader/index.d.ts +++ /dev/null @@ -1,346 +0,0 @@ -// Type definitions for FineUploader for 5.11 -// Project: http://fineuploader.com/ -// Definitions by: Bradford Wagner -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace qq { - interface BlobsOptions { - defaultName?: string; - } - - interface CameraOptions { - button?: HTMLElement; - ios?: boolean; - } - - interface ChunkingOptions { - concurrent?: ChunkingConcurrentOptions; - enabled?: boolean; // default false - mandatory?: boolean; // default false - partSize?: number; // default 2,000,000 - paramNames?: ChunkingParamNames; - success?: ChunkingSuccess; - } - - interface ChunkingConcurrentOptions { - enabled?: boolean; // default false - } - - interface ChunkingParamNames { - chunkSize?: string; // default: qqchunksize - partByteOffset?: string; // default: qqpartbyteoffset - partIndex?: string; // default: qqpartindex - totalParts?: string; // default: qqtotalparts - } - - interface ChunkingSuccess { - endpoint?: string | null; // default: null - } - - interface CorsOptions { - allowXdr?: boolean; // default: false - expected?: boolean; // default: false - sendCredentials: boolean; // default: false - } - - interface DeleteFileOptions { - customHeader?: H; // default: {} - enabled?: boolean; // default false - endpoint?: string; // default: /server/upload - method?: string; // default: DELETE - params?: P; // default: {} - } - - interface ExtraButtonsOptions { - element: HTMLElement | undefined; // default: undefined - fileInputTitle?: string; // default: file input - folders?: boolean; // default: false - multiple?: boolean; // default: true - validation?: V; // default: 'validation' - } - - interface FormOptions { - element?: string | HTMLElement; // default: qq-form - autoUpload?: boolean; // default: false - interceptSubmit?: boolean; // default: true - } - - interface MessagesOptions { - emptyError?: string; // default: {file} is empty, please select files again without it. - maxHeightImageError?: string; // default: Image is too tall. - maxWidthImageError?: string; // default: Image is too wide. - minHeightImageError?: string; // default: Image is not tall enough. - minWidthImageError?: string; // default: Image is not wide enough. - minSizeError?: string; // default: {file} is too small, minimum file size is {minSizeLimit}. - noFilesError?: string; // default: No files to upload. - onLeave?: string; // default: The files are being uploaded, if you leave now the upload will be canceled. - retryFailTooManyItemsError?: string; // default: Too many items ({netItems}) would be uploaded. Item limit is {itemLimit}. - typeError?: string; // default: {file} has an invalid extension. Valid extension(s): {extensions}. - // tslint:disable-next-line:max-line-length - unsupportedBrowserIos8Safari?: string; // default: Unrecoverable error - this browser does not permit file uploading of any kind due to serious bugs in iOS8 Safari. Please use iOS8 Chrome until Apple fixes these issues. - } - - interface PasteOptions { - defaultName?: string; // default: pasted_image - targetElement?: HTMLElement | null; // default: null - } - - interface ResumeOptions { - recordsExpireIn?: number; // default: 7 - enabled?: boolean; // default: false - paramNames?: ResumeParamNameOptions; - } - - interface ResumeParamNameOptions { - resuming: string; // default: qqresume - } - - interface RetryOptions { - autoAttemptDelay?: number; // default: 5 - enableAuto?: boolean; // default: false - maxAutoAttempts?: number; // default: 3 - preventRetryResponseProperty?: string; // default: preventRetry - } - - interface RequestOptions { - customHeaders?: H; // default: {} - endpoint?: string; // default: /server/upload - filenameParam?: string; // default: qqfilename - forceMultipart?: boolean; // default: true - inputName?: string; // default: qqfile - method?: string; // default: POST - params?: P; // default: {} - paramsInBody?: boolean; // default: true - uuid?: string; // default: qquuid - totalFileSizeName?: string; // default: qqtotalfilesize - } - - interface ScalingOptions { - customResizer?: ( - blob: File | Blob, - height: number, - image: HTMLImageElement, - sourceCanvas: HTMLCanvasElement, - targetCanvas: HTMLCanvasElement, - width: number) => Promise | undefined; // default: undefined - defaultQuality?: number; // default: 80 - defaultType?: string | null; // default: null - failureText?: string; // default: Failed to scale - includeExif?: boolean; // default: false - orient?: boolean; // default: true - sendOriginal?: boolean; // default: false - sizes?: Size[]; // default: [] - } - - /** - * From Documentation: - * An array containing size objects that describe scaled versions of each submitted image that should be generated and uploaded. - * A size object should usually contain a name String property (which will be appended to the file name of the scaled file), and must always contain a maxSize integer property. - * A type MIME string property is optional. - */ - interface Size { - name: string; - maxSize: number; - type?: string; - } - - interface SessionOptions { - customHeaders?: H; // default: {} - endpoint?: string | null; // default: null - params?: P; // default: {} - refreshOnReset?: boolean; // default: true - } - - interface TextOptions { - defaultResponseError?: string; // default: Upload failure reason unknown - fileInputTitle?: string; // default: file input - sizeSymbols?: string[]; // default: ['kB', 'MB', 'GB', 'TB', 'PB', 'EB'] - } - - interface ValidationOptions { - acceptFiles?: MimeType[] | null; // default: null - allowedExtensions?: string[]; // default: [] - itemLimit?: number; // default: 0 - minSizeLimit?: number; // default: 0 - sizeLimit?: number; // default: 0 - stopOnFirstInvalidFile?: boolean; // default: true - image?: ValidationImageOptions; - } - - interface ValidationImageOptions { - maxHeight?: number; // default: 0 - maxWidth?: number; // default: 0 - minWidth?: number; // default: 0 - minHeight?: number; // default: 0 - } - - interface WorkaroundOptions { - iosEmptyVideos?: boolean; // default: true - ios8BrowserCrash?: boolean; // default: false - ios8SafariUploads?: boolean; // default: true - } - - interface ChunkData { - partIndex: number; - startByte: number; - endByte: number; - totalParts: number; - } - - interface ValidateMetadata { - name: string; - size?: number; - } - - interface CallbackOptions { - onAutoRetry?: (id: number, name: string, attemptNumber: number) => void; - onCancel?: (id: number, name: string) => void; - onComplete?: (id: number, name: string, responseJSON: T, xhr: XMLHttpRequest) => void; // ignore xhr: XDomainRequest as it is not compatible for all versions of TypeScript - onAllComplete?: (succeeded: number[], failed: number[]) => void; - onDelete?: (id: number) => void; - onDeleteComplete?: (id: number, xhr: XMLHttpRequest, isError: boolean) => void; // ignore xhr: XDomainRequest as it is not compatible for all versions of TypeScript - onError?: (id: number, name: string, errorReason: string, xhr: XMLHttpRequest) => void; // ignore xhr: XDomainRequest as it is not compatible for all versions of TypeScript - onManualRetry?: (id: number, name: string) => boolean; // return false to prevent this and all future retries - onPasteReceived?: (blob: Blob) => void; - onProgress?: (id: number, name: string, uploadedBytes: number, totalBytes: number) => void; - onResume?: (id: number, name: string, chunkData: T) => void; - onSessionRequestComplete?: (response: T[], success: boolean, xhrOrXdr: XMLHttpRequest) => void; // ignore xhr: XDomainRequest as it is not compatible for all versions of TypeScript - onStatusChange?: (id: number, oldStatus: string, newStatus: string) => void; - onSubmit?: (id: number, name: string) => void; - onSubmitDelete?: (id: number) => void; - onSubmitted?: (id: number, name: string) => void; - onTotalProgress?: (totalUploadedBytes: number, totalBytes: number) => void; - onUpload?: (id: number, name: string) => void; - onUploadChunk?: (id: number, name: string, chunkData: ChunkData) => void; - // ignore xhr: XDomainRequest as it is not compatible for all versions of TypeScript - onUploadChunkSuccess?: (id: number, chunkData: ChunkData, responseJSON: T, xhr: XMLHttpRequest) => void; - onValidate?: (data: ValidateMetadata, buttonContainer: HTMLElement) => void; - onValidateBatch?: (fileOrBlobDataArray: ValidateMetadata[], buttomContainer: HTMLElement) => void; - } - - interface BasicOptions { - // core options - autoUpload?: boolean; // default true - button?: HTMLElement; - debug?: boolean; - disableCancelForFormUploads?: boolean; - formatFileName?: (rawFileName: string) => string; // rawFilename to display filename - maxConnections?: number; - multiple?: boolean; - - blobs?: BlobsOptions; - camera?: CameraOptions; - chunking?: ChunkingOptions; - cors?: CorsOptions; - deleteFile?: DeleteFileOptions; - extraButtons?: ExtraButtonsOptions; - form?: FormOptions; - messages?: MessagesOptions; - paste?: PasteOptions; - resume?: ResumeOptions; - retry?: RetryOptions; - request?: RequestOptions; - scaling?: ScalingOptions; - session?: SessionOptions; - text?: TextOptions; - validation?: ValidationOptions; - workarounds?: WorkaroundOptions; - - callbacks?: CallbackOptions; - } - - interface BlobWrapper { - blob: Blob; - name: string; - } - - interface CanvasWrapper { - canvas: HTMLCanvasElement; - name: string; - quality: number; // 1-100 - type: MimeType; - } - - interface ResizeInfo { - blob: File | Blob; - height: number; - image: HTMLImageElement; - sourceCanvas: HTMLCanvasElement; - targetCanvas: HTMLCanvasElement; - width: number; - } - - interface ResumableItem { - name: string; - uuid: string; - partIdx: number; - } - - interface FilterOption { - id?: number; - uuid?: string; - originalName?: string; - name?: string; - status?: string; - size?: number; - } - - interface ScaleImageOptions { - maxSize: number; - orient?: boolean; // default: true - type?: string; // default: type or reference image - quality?: number; // 0-100 - default: 80 - includeExif?: boolean; // default: false - customResizer?: (resizeInfo: ResizeInfo) => Promise; - } - - class FineUploaderBasic { - constructor(options: BasicOptions) - - addFiles(files: File[] | HTMLInputElement[] | Blob[] | BlobWrapper[] | HTMLCanvasElement[] | CanvasWrapper[] | FileList, params: T, endpoint: string): void; - addInitialFiles(initialFiles: T[]): void; - cancel(id: number): void; - cancelAll(): void; - clearStoredFiles(): void; - continueUpload(id: number): boolean; // true if successful - deleteFile(id: number): void; - - /** - * TODO: need someone who has used this to update the returned promise related fields - */ - drawThumbnail(id: number, targetContainer: HTMLElement, maxSize: number, fromServer: boolean, customResizer: (resizeInfo: ResizeInfo) => Promise): Promise - getButton(id: number): HTMLElement; - getFile(id: number): File | Blob; - getInProgress(): number; - getName(id: number): string; - getParentId(scaledFileId: number): number; - getRemainingAllowedItems(): number; - getResumableFilesData(): ResumableItem[]; - getSize(id: number): number; - getUploads(filter: FilterOption): T | T[]; - getUuid(id: number): string; - log(message: string, level: string): void; - pauseUpload(id: number): boolean; // true if successful - reset(): void; - retry(id: number): void; - scaleImage(id: number, options: ScaleImageOptions): Promise; - setCustomHeaders(customHeaders: H, id: number): void; - setEndpoint(path: string, identifier: number | HTMLElement): void; - setDeleteFileCustomHeaders(customHeaders: H, id: number): void; - setDeleteFileEndpoint(path: string, identifier: number | HTMLElement): void; - setDeleteFileParams

    (params: P, id: number): void; - setItemLimit(newItemLimit: number): void; - setForm(formElementOrId: HTMLFormElement | string): void; - setName(id: number, name: string): void; - setParams

    (params: P, id: number): void; - setUuid(id: number, uuid: string): void; - uploadStoredFiles(): void; // throws NoFilesError - - // ui - addExtraDropzone(element: HTMLElement): void; - getDropTarget(id: number): HTMLElement; - getId(element: HTMLElement): number; - getItemByFileId(id: number): HTMLElement; - removeExtraDropzone(element: HTMLElement): void; - } -} diff --git a/fine-uploader/test/blobs.ts b/fine-uploader/test/blobs.ts deleted file mode 100644 index 99e5355460..0000000000 --- a/fine-uploader/test/blobs.ts +++ /dev/null @@ -1,9 +0,0 @@ -function testBlob() { - const config: qq.BasicOptions = { - blobs: { - defaultName: "hi.png" - } - }; - - const uploader = new qq.FineUploaderBasic(config); -} diff --git a/fine-uploader/test/callbacks.ts b/fine-uploader/test/callbacks.ts deleted file mode 100644 index eba85ad2a0..0000000000 --- a/fine-uploader/test/callbacks.ts +++ /dev/null @@ -1,59 +0,0 @@ -class CallbacksTest { - constructor(private opts: qq.CallbackOptions) { - - } - - testCallbacks() { - const opts = this.opts; - - interface CustomType { - myTypeOfClass: string; - } - - opts.onAutoRetry = (id, name, attemptNumber) => {}; - - opts.onCancel = (id, name) => {}; - - opts.onComplete = (id: number, name: string, responseJSON: CustomType, xhr: XMLHttpRequest) => {}; - - opts.onAllComplete = (succeeded, failed) => {}; - - opts.onDelete = (id) => {}; - - opts.onDeleteComplete = (id, xhr, isError) => {}; - - opts.onError = (id, name, errorReason, xhr) => {}; - - opts.onManualRetry = (id, name) => { - return true; - }; - - opts.onPasteReceived = (blob) => {}; - - opts.onProgress = (id, name, uploadedBytes, totalBytes) => {}; - - opts.onResume = (id: number, name: string, chunkData: CustomType) => {}; - - opts.onSessionRequestComplete = (response: CustomType[], success: boolean, xhrOrXdr: XMLHttpRequest) => {}; - - opts.onStatusChange = (id, oldStatus, newStatus) => {}; - - opts.onSubmit = (id, name) => {}; - - opts.onSubmitDelete = (id) => {}; - - opts.onSubmitted = (id, name) => {}; - - opts.onTotalProgress = (totalUploadedBytes, totalBytes) => {}; - - opts.onUpload = (id, name) => {}; - - opts.onUploadChunk = (id, name, chunkData) => {}; - - opts.onUploadChunkSuccess = (id: number, chunkData: qq.ChunkData, responseJSON: CustomType, xhr: XMLHttpRequest) => {}; - - opts.onValidate = (data, buttonContainer) => {}; - - opts.onValidateBatch = (fileOrBlobDataArray, buttonContaine) => {}; - } -} diff --git a/fine-uploader/test/camera.ts b/fine-uploader/test/camera.ts deleted file mode 100644 index b42a080778..0000000000 --- a/fine-uploader/test/camera.ts +++ /dev/null @@ -1,14 +0,0 @@ -function cameraTest() { - const cameraButton = new HTMLButtonElement(); - - const cameraOptions: qq.CameraOptions = { - button: cameraButton, - ios: false - }; - - const config: qq.BasicOptions = { - camera: cameraOptions - }; - - const uploader = new qq.FineUploaderBasic(config); -} diff --git a/fine-uploader/test/chunking.ts b/fine-uploader/test/chunking.ts deleted file mode 100644 index 386dd67738..0000000000 --- a/fine-uploader/test/chunking.ts +++ /dev/null @@ -1,26 +0,0 @@ -function chunkingTest() { - - const chunkingOptions: qq.ChunkingOptions = { - concurrent: { - enabled: false - }, - enabled: true, - mandatory: true, - partSize: 1000000, - paramNames: { - chunkSize: "chunkSize", - partByteOffset: "partByteOffset", - partIndex: "partIndex", - totalParts: "totalParts" - }, - success: { - endpoint: "/some/web/endpoint/yaySuccesss" - } - }; - - const config: qq.BasicOptions = { - chunking: chunkingOptions - }; - - const uploader = new qq.FineUploaderBasic(config); -} diff --git a/fine-uploader/test/core.ts b/fine-uploader/test/core.ts deleted file mode 100644 index dbc06e95d6..0000000000 --- a/fine-uploader/test/core.ts +++ /dev/null @@ -1,17 +0,0 @@ -function testCore() { - const button: HTMLElement = new HTMLButtonElement(); - - const config: qq.BasicOptions = { - autoUpload: true, - button, - debug: true, - disableCancelForFormUploads: true, - formatFileName: (rawFileName: string) => { - return "hi"; - }, - maxConnections: 10, - multiple: true - }; - - const uploader = new qq.FineUploaderBasic(config); -} diff --git a/fine-uploader/test/cors.ts b/fine-uploader/test/cors.ts deleted file mode 100644 index 771b210208..0000000000 --- a/fine-uploader/test/cors.ts +++ /dev/null @@ -1,13 +0,0 @@ -function corsTest() { - const corsOptions: qq.CorsOptions = { - allowXdr: true, - expected: true, - sendCredentials: true - }; - - const config: qq.BasicOptions = { - cors: corsOptions - }; - - const uploader = new qq.FineUploaderBasic(config); -} diff --git a/fine-uploader/test/deleteFile.ts b/fine-uploader/test/deleteFile.ts deleted file mode 100644 index 49c3e68890..0000000000 --- a/fine-uploader/test/deleteFile.ts +++ /dev/null @@ -1,28 +0,0 @@ -function deleteFileTest() { - interface CustomHeader { - myOption: string; - } - - interface CustomParams { - myParam: string; - } - - const deleteFileOptions: qq.DeleteFileOptions = { - customHeader: { - myOption: "ewwww" - }, - enabled: true, - endpoint: "/my/server/location/delete", - method: "POST", - params: { - myParam: "u" - } - }; - - - const config: qq.BasicOptions = { - deleteFile: deleteFileOptions - }; - - const uploader = new qq.FineUploaderBasic(config); -} diff --git a/fine-uploader/test/extraButtons.ts b/fine-uploader/test/extraButtons.ts deleted file mode 100644 index eef709bea8..0000000000 --- a/fine-uploader/test/extraButtons.ts +++ /dev/null @@ -1,23 +0,0 @@ -function extraButtons() { - interface Validation { - myValue: string; - } - - const element: HTMLElement = new HTMLElement(); - - const extraButtonOptions: qq.ExtraButtonsOptions = { - element, - fileInputTitle: "inputTitle", - folders: true, - multiple: false, - validation: { - myValue: "ew" - } - }; - - const config: qq.BasicOptions = { - extraButtons: extraButtonOptions - }; - - const uploader = new qq.FineUploaderBasic(config); -} diff --git a/fine-uploader/test/form.ts b/fine-uploader/test/form.ts deleted file mode 100644 index ccc08b69a1..0000000000 --- a/fine-uploader/test/form.ts +++ /dev/null @@ -1,13 +0,0 @@ -function formTest() { - const formOptions: qq.FormOptions = { - element: "qq-form", - autoUpload: true, - interceptSubmit: true - }; - - const config: qq.BasicOptions = { - form: formOptions - }; - - const uploader = new qq.FineUploaderBasic(config); -} diff --git a/fine-uploader/test/message.ts b/fine-uploader/test/message.ts deleted file mode 100644 index 726584bf7b..0000000000 --- a/fine-uploader/test/message.ts +++ /dev/null @@ -1,21 +0,0 @@ -function messageTest() { - const messageOptions: qq.MessagesOptions = { - emptyError: "emptyError", - maxHeightImageError: "maxHeightImageError", - maxWidthImageError: "error occurred", - minHeightImageError: "error occurred", - minWidthImageError: "error occurred", - minSizeError: "error occurred", - noFilesError: "error occurred", - onLeave: "error occurred", - retryFailTooManyItemsError: "error occurred", - typeError: "error occurred", - unsupportedBrowserIos8Safari: "error occurred" - }; - - const config: qq.BasicOptions = { - messages: messageOptions - }; - - const uploader = new qq.FineUploaderBasic(config); -} diff --git a/fine-uploader/test/method.ts b/fine-uploader/test/method.ts deleted file mode 100644 index 1adb13db81..0000000000 --- a/fine-uploader/test/method.ts +++ /dev/null @@ -1,140 +0,0 @@ -class TestMethods { - constructor(private uploader: qq.FineUploaderBasic) { - } - - testAddFiles() { - interface ParamType { - field: string; - } - - const params: ParamType = { - field: 'hiiiii' - }; - - this.uploader.addFiles( - new FileList(), - params, - "/my/happy/endpoint" - ); - } - - testAddInitialFiles() { - interface InitialFiles { - myField: number; - } - - const initialFiles: InitialFiles[] = [{ - myField: 1324 - }]; - - this.uploader.addInitialFiles(initialFiles); - } - - testDrawThumbnail() { - const promise: Promise = this.uploader.drawThumbnail( - 1234, - new HTMLElement(), - 1234565, - false, - (resizeInfo) => { - return new Promise(() => { - return new Blob(); - }); - } - ); - } - - testGetUploads() { - interface ResponseType { - hi: string; - } - const response: ResponseType | ResponseType[] = this.uploader.getUploads({ - status: "proggresssssssesees" - }); - } - - testSetCustomHeaders() { - interface CustomHeader { - customField: number; - } - - this.uploader.setCustomHeaders({ - customField: 1234 - }, 1234); - } - - testSetDeleteCustomHeaders() { - interface CustomHeader { - customField: number; - } - - this.uploader.setDeleteFileCustomHeaders({ - customField: 1234 - }, 1234); - } - - testSetDeleteFileParams() { - interface CustomParams { - paramField: boolean; - } - this.uploader.setDeleteFileParams({ - paramField: false - }, 1234); - } - - testSetParams() { - interface CustomParams { - customParams: number; - } - - this.uploader.setParams({ - customParams: 1234 - }, 1234); - } - - bulkTests() { - this.uploader.cancel(1); - this.uploader.cancelAll(); - this.uploader.clearStoredFiles(); - const shouldContinue: boolean = this.uploader.continueUpload(1234); - this.uploader.deleteFile(1234); - const elem: HTMLElement = this.uploader.getButton(1234); - const fileOrBlob: File | Blob = this.uploader.getFile(1234); - let num: number = this.uploader.getInProgress(); - let s: string = this.uploader.getName(1234); - num = this.uploader.getParentId(1234); - num = this.uploader.getRemainingAllowedItems(); - const resumables: qq.ResumableItem[] = this.uploader.getResumableFilesData(); - num = this.uploader.getSize(1234); - s = this.uploader.getUuid(1234); - this.uploader.log("why am i doing this?", "info"); - const b: boolean = this.uploader.pauseUpload(1234); - this.uploader.reset(); - this.uploader.retry(1234); - const blobPromise: Promise = this.uploader.scaleImage(1234, { - maxSize: 20, - orient: false, - type: "png", - quality: 10, - includeExif: false, - }); - this.uploader.setEndpoint("/my/path/is/my/own", 1234); - this.uploader.setEndpoint("/my/path/is/my/own", new HTMLElement()); - this.uploader.setDeleteFileEndpoint("/some/path", 1234); - this.uploader.setDeleteFileEndpoint("/some/path", new HTMLElement()); - this.uploader.setItemLimit(1234); - this.uploader.setForm(new HTMLFormElement()); - this.uploader.setForm("myFormElement"); - this.uploader.setName(1234, "myCustomName"); - this.uploader.setUuid(1234, "12341234"); - this.uploader.uploadStoredFiles(); - } - - uiTests() { - this.uploader.addExtraDropzone(new HTMLElement()); - let elem: HTMLElement = this.uploader.getDropTarget(1234); - const n: number = this.uploader.getId(elem); - elem = this.uploader.getItemByFileId(n); - this.uploader.removeExtraDropzone(elem); - } -} diff --git a/fine-uploader/test/paste.ts b/fine-uploader/test/paste.ts deleted file mode 100644 index 9b3c7d9007..0000000000 --- a/fine-uploader/test/paste.ts +++ /dev/null @@ -1,14 +0,0 @@ -function pasteTest() { - const targetElement: HTMLElement = new HTMLElement(); - - const pasteOptions: qq.PasteOptions = { - defaultName: "pasted_image", - targetElement - }; - - const config: qq.BasicOptions = { - paste: pasteOptions - }; - - const uploader = new qq.FineUploaderBasic(config); -} diff --git a/fine-uploader/test/request.ts b/fine-uploader/test/request.ts deleted file mode 100644 index 54b29c9be9..0000000000 --- a/fine-uploader/test/request.ts +++ /dev/null @@ -1,32 +0,0 @@ -function requestTest() { - interface CustomHeader { - customHeader: string; - } - - interface CustomParam { - customParam: boolean; - } - - const requestOptions: qq.RequestOptions = { - customHeaders: { - customHeader: "my custom header hehehehee" - }, - endpoint: "/my/custom/endpoint", - filenameParam: "newFilenameParam", - forceMultipart: true, - inputName: "filenameParamMapping", - method: "POST", - params: { - customParam: false - }, - paramsInBody: false, - uuid: "asdf123456", - totalFileSizeName: "totalFileSize" - }; - - const config: qq.BasicOptions = { - request: requestOptions - }; - - const uploader = new qq.FineUploaderBasic(config); -} \ No newline at end of file diff --git a/fine-uploader/test/resume.ts b/fine-uploader/test/resume.ts deleted file mode 100644 index dc588d19f5..0000000000 --- a/fine-uploader/test/resume.ts +++ /dev/null @@ -1,15 +0,0 @@ -function resumeTest() { - const resumeOptions: qq.ResumeOptions = { - recordsExpireIn: 10, - enabled: true, - paramNames: { - resuming: "ew you" - } - }; - - const config: qq.BasicOptions = { - resume: resumeOptions - }; - - const uploader = new qq.FineUploaderBasic(config); -} diff --git a/fine-uploader/test/retry.ts b/fine-uploader/test/retry.ts deleted file mode 100644 index 85c9f71af3..0000000000 --- a/fine-uploader/test/retry.ts +++ /dev/null @@ -1,15 +0,0 @@ -function retryTest() { - - const retryOptions: qq.RetryOptions = { - autoAttemptDelay: 1, - enableAuto: true, - maxAutoAttempts: 32, - preventRetryResponseProperty: "preventRetry" - }; - - const config: qq.BasicOptions = { - retry: retryOptions - }; - - const uploader = new qq.FineUploaderBasic(config); -} \ No newline at end of file diff --git a/fine-uploader/test/scaling.ts b/fine-uploader/test/scaling.ts deleted file mode 100644 index 5e8ff3dc51..0000000000 --- a/fine-uploader/test/scaling.ts +++ /dev/null @@ -1,29 +0,0 @@ -function scalingTest() { - const scalingOptions: qq.ScalingOptions = { - customResizer: (blob, height, image, sourceCanvas, targetCanvas, width) => { - const promise = new Promise(() => { - return blob; - }); - return promise; - }, - defaultQuality: 10, - defaultType: "JPEG", - failureText: "you have failed me for the last time", - includeExif: true, - orient: false, - sendOriginal: true, - sizes: [ - { - maxSize: 10, - name: "i am added to name", - type: "mime type" - } - ] - }; - - const config: qq.BasicOptions = { - scaling: scalingOptions - }; - - const uploader = new qq.FineUploaderBasic(config); -} diff --git a/fine-uploader/test/session.ts b/fine-uploader/test/session.ts deleted file mode 100644 index 7d8d6069b9..0000000000 --- a/fine-uploader/test/session.ts +++ /dev/null @@ -1,26 +0,0 @@ -function sessionTest() { - interface CustomHeader { - customHeader: string; - } - - interface CustomParam { - customParam: boolean; - } - - const sessionOptions: qq.SessionOptions = { - customHeaders: { - customHeader: "customHeader" - }, - endpoint: "/mysession/endpoint", - params: { - customParam: false - }, - refreshOnReset: false - }; - - const config: qq.BasicOptions = { - session: sessionOptions - }; - - const uploader = new qq.FineUploaderBasic(config); -} diff --git a/fine-uploader/test/text.ts b/fine-uploader/test/text.ts deleted file mode 100644 index e83ddb4bcf..0000000000 --- a/fine-uploader/test/text.ts +++ /dev/null @@ -1,13 +0,0 @@ -function textTest() { - const textOptions: qq.TextOptions = { - defaultResponseError: "you have failed me for the last time", - fileInputTitle: "file input title", - sizeSymbols: ['kb'] - }; - - const config: qq.BasicOptions = { - text: textOptions - }; - - const uploader = new qq.FineUploaderBasic(config); -} diff --git a/fine-uploader/test/validation.ts b/fine-uploader/test/validation.ts deleted file mode 100644 index 60324157f9..0000000000 --- a/fine-uploader/test/validation.ts +++ /dev/null @@ -1,22 +0,0 @@ -function validationTest() { - - const validationOptions: qq.ValidationOptions = { - acceptFiles: [new MimeType()], - allowedExtensions: ['csv, xls'], - itemLimit: 5, - sizeLimit: 10000000, - stopOnFirstInvalidFile: false, - image: { - maxHeight: 10, - maxWidth: 10, - minHeight: 1, - minWidth: 1 - } - }; - - const config: qq.BasicOptions = { - validation: validationOptions - }; - - const uploader = new qq.FineUploaderBasic(config); -} diff --git a/fine-uploader/test/workarounds.ts b/fine-uploader/test/workarounds.ts deleted file mode 100644 index 42fa5ceee7..0000000000 --- a/fine-uploader/test/workarounds.ts +++ /dev/null @@ -1,13 +0,0 @@ -function workaroundsTest() { - const workaroundOptions: qq.WorkaroundOptions = { - iosEmptyVideos: false, - ios8BrowserCrash: false, - ios8SafariUploads: false - }; - - const config: qq.BasicOptions = { - workarounds: workaroundOptions - }; - - const uploader = new qq.FineUploaderBasic(config); -} diff --git a/fine-uploader/tsconfig.json b/fine-uploader/tsconfig.json deleted file mode 100644 index c02e485091..0000000000 --- a/fine-uploader/tsconfig.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "files": [ - "index.d.ts", - "test/blobs.ts", - "test/camera.ts", - "test/chunking.ts", - "test/core.ts", - "test/cors.ts", - "test/deleteFile.ts", - "test/extraButtons.ts", - "test/form.ts", - "test/message.ts", - "test/paste.ts", - "test/resume.ts", - "test/retry.ts", - "test/request.ts", - "test/scaling.ts", - "test/session.ts", - "test/text.ts", - "test/validation.ts", - "test/workarounds.ts", - "test/method.ts", - "test/callbacks.ts" - ], - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - } -} \ No newline at end of file diff --git a/fix b/fix new file mode 100644 index 0000000000..e69de29bb2 diff --git a/fixed-data-table/fixed-data-table-tests.tsx b/fixed-data-table/fixed-data-table-tests.tsx index 7dfac22230..f57ff3d946 100644 --- a/fixed-data-table/fixed-data-table-tests.tsx +++ b/fixed-data-table/fixed-data-table-tests.tsx @@ -1,6 +1,3 @@ - -/// - import * as React from "react"; import {Table, Cell, Column, CellProps} from "fixed-data-table"; diff --git a/flickity/flickity-tests.ts b/flickity/flickity-tests.ts index b98315285f..b4ecf51997 100644 --- a/flickity/flickity-tests.ts +++ b/flickity/flickity-tests.ts @@ -4,11 +4,9 @@ // Definitions: https://github.com/clmcgrath/ /// -/// //jQuery tests - var $flickity: JQuery = $("#flickity-selector").flickity( { initialIndex: 0, @@ -105,15 +103,15 @@ flikty2.destroy(); flikty2.reloadCells(); //event handlers -flikty2.on(FlickityEvents.cellSelect, (evt, ele) => { +flikty2.on("cellSelect", (evt, ele) => { //do something }); -flikty2.off(FlickityEvents.cellSelect, (evt, ele, pntr, vctr) => { +flikty2.off("cellSelect", (evt, ele, pntr, vctr) => { //do something }); -flikty2.once(FlickityEvents.cellSelect, (evt, ele, pntr) => { +flikty2.once("cellSelect", (evt, ele, pntr) => { //do something }); diff --git a/flot/index.d.ts b/flot/index.d.ts index 20fadd0a47..e4fed6a246 100644 --- a/flot/index.d.ts +++ b/flot/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Flot // Project: http://www.flotcharts.org/ -// Definitions by: Matt Burland +// Definitions by: Matt Burland , Timo Mühlbach // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -21,16 +21,16 @@ declare namespace jquery.flot { } interface hooks { - processOptions: { (plot: plot, options: plotOptions): void; } []; - processRawData: { (plot: plot, series: dataSeries, data: any[], datapoints: datapoints): void; }[]; - processDatapoints: { (plot: plot, series: dataSeries, datapoints: datapoints): void; }[]; - processOffset: { (plot: plot, offset: canvasPoint): void; }[]; - drawBackground: { (plot: plot, context: CanvasRenderingContext2D): void; }[]; - drawSeries: { (plot: plot, context: CanvasRenderingContext2D, series: dataSeries): void; }[]; - draw: { (plot: plot, context: CanvasRenderingContext2D): void; }[]; - bindEvents: { (plot: plot, eventHolder: JQuery): void; }[]; - drawOverlay: { (plot: plot, context: CanvasRenderingContext2D): void; }[]; - shutdown: { (plot: plot, eventHolder: JQuery): void; }[]; + processOptions?: { (plot: plot, options: plotOptions): void; } []; + processRawData?: { (plot: plot, series: dataSeries, data: any[], datapoints: datapoints): void; }[]; + processDatapoints?: { (plot: plot, series: dataSeries, datapoints: datapoints): void; }[]; + processOffset?: { (plot: plot, offset: canvasPoint): void; }[]; + drawBackground?: { (plot: plot, context: CanvasRenderingContext2D): void; }[]; + drawSeries?: { (plot: plot, context: CanvasRenderingContext2D, series: dataSeries): void; }[]; + draw?: { (plot: plot, context: CanvasRenderingContext2D): void; }[]; + bindEvents?: { (plot: plot, eventHolder: JQuery): void; }[]; + drawOverlay?: { (plot: plot, context: CanvasRenderingContext2D): void; }[]; + shutdown?: { (plot: plot, eventHolder: JQuery): void; }[]; } interface interaction { diff --git a/forever-monitor/tsconfig.json b/forever-monitor/tsconfig.json index e0d7d1d5ee..363ce2c8a0 100644 --- a/forever-monitor/tsconfig.json +++ b/forever-monitor/tsconfig.json @@ -19,4 +19,4 @@ "index.d.ts", "forever-monitor-tests.ts" ] -} \ No newline at end of file +} diff --git a/foundation-sites/foundation-sites-tests.ts b/foundation-sites/foundation-sites-tests.ts index 4932f01624..2e90071c7d 100644 --- a/foundation-sites/foundation-sites-tests.ts +++ b/foundation-sites/foundation-sites-tests.ts @@ -1,11 +1,3 @@ -// Tests for type definitions for Foundation Sites v6.0.4 -// Project: http://foundation.zurb.com/ -// Definitions by: Sam Vloeberghs -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - - $(document).foundation(); $(document).foundation('method5'); $(document).foundation(['method', 'method2']); diff --git a/foundation/foundation-tests.ts b/foundation/foundation-tests.ts index 913bd0ee1b..33f8530589 100644 --- a/foundation/foundation-tests.ts +++ b/foundation/foundation-tests.ts @@ -1,6 +1,3 @@ -/// - - function empty_callback() : void {} function plugin_list() { diff --git a/from/from-tests.ts b/from/from-tests.ts index b46bdf66f1..e73a4915a0 100644 --- a/from/from-tests.ts +++ b/from/from-tests.ts @@ -1,6 +1,3 @@ - -/// - import from = require('from'); var rs: NodeJS.ReadableStream; diff --git a/fs-ext/fs-ext-tests.ts b/fs-ext/fs-ext-tests.ts index baba88f092..0c774589bc 100644 --- a/fs-ext/fs-ext-tests.ts +++ b/fs-ext/fs-ext-tests.ts @@ -1,19 +1,16 @@ - -/// - import fs = require('fs-ext'); var num:number; var str:string; -//from node.js 'fs' module +//from node.js 'fs' module fs.appendFileSync(str, "data"); -fs.flock(num, str, (err)=>{ +fs.flock(num, str, (err)=>{ }); fs.flockSync(num, str); -fs.fcntl(num, str, num, (err, res)=>{ +fs.fcntl(num, str, num, (err, res)=>{ }); fs.fcntl(num, str, (err, res)=>{ }); diff --git a/fs-extra-promise-es6/fs-extra-promise-es6-tests.ts b/fs-extra-promise-es6/fs-extra-promise-es6-tests.ts index 12623c54b1..46e623207a 100644 --- a/fs-extra-promise-es6/fs-extra-promise-es6-tests.ts +++ b/fs-extra-promise-es6/fs-extra-promise-es6-tests.ts @@ -1,5 +1,3 @@ -/// - import fs = require('fs-extra-promise-es6'); import stream = require('stream'); @@ -145,7 +143,7 @@ strArr = fs.readdirSync(path); fs.close(fd, errorCallback); fs.closeSync(fd); fs.open(path, flags, modeStr, (err: Error, fd: number) => { - + }); num = fs.openSync(path, flags, modeStr); fs.utimes(path, atime, mtime, errorCallback); diff --git a/fs-extra-promise/fs-extra-promise-tests.ts b/fs-extra-promise/fs-extra-promise-tests.ts index 112a27109c..28bdd26120 100644 --- a/fs-extra-promise/fs-extra-promise-tests.ts +++ b/fs-extra-promise/fs-extra-promise-tests.ts @@ -1,6 +1,3 @@ - -/// - import fs = require('fs-extra-promise'); import stream = require('stream'); diff --git a/fs-extra/fs-extra-tests.ts b/fs-extra/fs-extra-tests.ts index 896d6411f7..a6990cc75f 100644 --- a/fs-extra/fs-extra-tests.ts +++ b/fs-extra/fs-extra-tests.ts @@ -1,8 +1,5 @@ - -/// - import fs = require('fs-extra'); -import * as Path from 'path' +import * as Path from 'path'; var src: string; var dest: string; @@ -22,7 +19,7 @@ fs.copy(src, dest, { clobber: true, preserveTimestamps: true, - filter: (src: string) => {return false} + filter: (src: string) => { return false; } }, errorCallback ); @@ -43,7 +40,7 @@ fs.copySync(src, dest, { clobber: true, preserveTimestamps: true, - filter: (src: string) => {return false} + filter: (src: string) => { return false; } } ); fs.copySync(src, dest, @@ -102,35 +99,3 @@ fs.ensureSymlink(path, errorCallback); fs.ensureSymlinkSync(path); fs.emptyDir(path, errorCallback); fs.emptyDirSync(path); - -var items: string[]; -fs.walk("my-path") - .on('data', function (item) { - items.push(item.path); - }) - .on('end', function () { - console.dir(items); - }); - -const ignoreHiddenFiles = (item: string): boolean => { - const basename = Path.basename(item) - return basename === '.' || basename[0] !== '.' -} - -const sortPaths = (left: string, right: string) => left.localeCompare(right); - -const options = { - filter: ignoreHiddenFiles, - pathSorter: sortPaths -} - -fs.walk(path, options) - .on('readable', function (this: fs.PathEntryStream) { - let item: fs.PathEntry | undefined - while ((item = this.read())) { - items.push(item.path) - } - }) - .on('end', function () { - - }) diff --git a/fs-extra/index.d.ts b/fs-extra/index.d.ts index 2cc47724c8..57f4a6fb24 100644 --- a/fs-extra/index.d.ts +++ b/fs-extra/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for fs-extra +// Type definitions for fs-extra v2.0.0 // Project: https://github.com/jprichardson/node-fs-extra -// Definitions by: midknight41 +// Definitions by: midknight41 , Brendan Forster // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Imported from: https://github.com/soywiz/typescript-node-definitions/fs-extra.d.ts @@ -120,9 +120,6 @@ export type PathEntryStream = { read(): PathEntry | null } -export function walk(path: string, options?: WalkOptions): WalkEventEmitter; -export function walkSync(path: string): ReadonlyArray; - export interface CopyFilterFunction { (src: string): boolean } diff --git a/ftp/ftp-tests.ts b/ftp/ftp-tests.ts index 6e5e7d37a9..4d78104940 100644 --- a/ftp/ftp-tests.ts +++ b/ftp/ftp-tests.ts @@ -1,6 +1,3 @@ - -/// - import Client = require("ftp"); import fs = require("fs"); @@ -8,8 +5,8 @@ var c = new Client(); c.on('ready', (): void => { c.get('foo.txt', function(err: Error, stream: NodeJS.ReadableStream): void { if (err) throw err; - stream.once('close', function(): void { - c.end(); + stream.once('close', function(): void { + c.end(); }); stream.pipe(fs.createWriteStream('foo.local-copy.txt')); }); @@ -25,4 +22,4 @@ c.connect({ }); - + diff --git a/fullcalendar/fullcalendar-tests.ts b/fullcalendar/fullcalendar-tests.ts index 7640c85db6..63328a9cef 100644 --- a/fullcalendar/fullcalendar-tests.ts +++ b/fullcalendar/fullcalendar-tests.ts @@ -1,5 +1,4 @@ -/// -/// +/// import * as FullCalendar from 'fullcalendar'; import * as moment from 'moment'; diff --git a/fullcalendar/v1/fullcalendar-tests.ts b/fullcalendar/v1/fullcalendar-tests.ts index 56a9eb0024..ede55bc0b1 100644 --- a/fullcalendar/v1/fullcalendar-tests.ts +++ b/fullcalendar/v1/fullcalendar-tests.ts @@ -1,6 +1,4 @@ -/// -/// -/// +/// // All examples from http://arshaw.com/fullcalendar/docs/ diff --git a/gapi.auth2/gapi.auth2-tests.ts b/gapi.auth2/gapi.auth2-tests.ts index 621ca6f056..1d389d59e9 100644 --- a/gapi.auth2/gapi.auth2-tests.ts +++ b/gapi.auth2/gapi.auth2-tests.ts @@ -1,6 +1,6 @@ +/// - -function test_init(){ +function test_init() { var auth = gapi.auth2.init({ client_id: 'my-id', cookie_policy: 'single_host_origin', @@ -9,7 +9,7 @@ function test_init(){ }); } -function test_getAuthInstance(){ +function test_getAuthInstance() { gapi.auth2.init({ client_id: 'my-id', cookie_policy: 'single_host_origin', @@ -19,14 +19,14 @@ function test_getAuthInstance(){ var auth = gapi.auth2.getAuthInstance(); } -function test_signIn(){ +function test_signIn() { gapi.auth2.getAuthInstance().signIn({ scope: 'email profile', prompt: 'content' }); } -function test_signInOptionsBuild(){ +function test_signInOptionsBuild() { var options = new gapi.auth2.SigninOptionsBuilder(); options.setAppPackageName('com.example.app'); options.setFetchBasicProfile(true); @@ -35,13 +35,13 @@ function test_signInOptionsBuild(){ gapi.auth2.getAuthInstance().signIn(options); } -function test_getAuthResponse(){ +function test_getAuthResponse() { var user = gapi.auth2.getAuthInstance().currentUser.get(); var authResponse = user.getAuthResponse(); var authResponseWithAuth = user.getAuthResponse(true); } -function test_render(){ +function test_render() { var success = (googleUser: gapi.auth2.GoogleUser): void => { console.log(googleUser); }; @@ -59,3 +59,87 @@ function test_render(){ onfailure: failure }); } + +/* Example taken from https://developers.google.com/identity/sign-in/web/ */ +function onSignIn(googleUser: gapi.auth2.GoogleUser) { + // Useful data for your client-side scripts: + var profile = googleUser.getBasicProfile(); + console.log("ID: " + profile.getId()); // Don't send this directly to your server! + console.log('Full Name: ' + profile.getName()); + console.log('Given Name: ' + profile.getGivenName()); + console.log('Family Name: ' + profile.getFamilyName()); + console.log("Image URL: " + profile.getImageUrl()); + console.log("Email: " + profile.getEmail()); + + // The ID token you need to pass to your backend: + var id_token = googleUser.getAuthResponse().id_token; + console.log("ID Token: " + id_token); +}; + + +/* Example taken from https://github.com/google/google-api-javascript-client/blob/master/samples/authSample.html */ + +// Enter an API key from the Google API Console: +// https://console.developers.google.com/apis/credentials +var apiKey = 'YOUR_API_KEY'; +// Enter the API Discovery Docs that describes the APIs you want to +// access. In this example, we are accessing the People API, so we load +// Discovery Doc found here: https://developers.google.com/people/api/rest/ +var discoveryDocs = ["https://people.googleapis.com/$discovery/rest?version=v1"]; +// Enter a client ID for a web application from the Google API Console: +// https://console.developers.google.com/apis/credentials?project=_ +// In your API Console project, add a JavaScript origin that corresponds +// to the domain where you will be running the script. +var clientId = 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com'; +// Enter one or more authorization scopes. Refer to the documentation for +// the API or https://developers.google.com/people/v1/how-tos/authorizing +// for details. +var scopes = 'profile'; +var authorizeButton = document.getElementById('authorize-button'); +var signoutButton = document.getElementById('signout-button'); +function handleClientLoad() { + // Load the API client and auth2 library + gapi.load('client:auth2', initClient); +} +function initClient() { + gapi.client.init({ + apiKey: apiKey, + discoveryDocs: discoveryDocs, + clientId: clientId, + scope: scopes + }).then(function () { + // Listen for sign-in state changes. + gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus); + // Handle the initial sign-in state. + updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get()); + authorizeButton.onclick = handleAuthClick; + signoutButton.onclick = handleSignoutClick; + }); +} +function updateSigninStatus(isSignedIn: boolean) { + if (isSignedIn) { + authorizeButton.style.display = 'none'; + signoutButton.style.display = 'block'; + makeApiCall(); + } else { + authorizeButton.style.display = 'block'; + signoutButton.style.display = 'none'; + } +} +function handleAuthClick(event: MouseEvent) { + gapi.auth2.getAuthInstance().signIn(); +} +function handleSignoutClick(event: MouseEvent) { + gapi.auth2.getAuthInstance().signOut(); +} +// Load the API and make an API call. Display the results on the screen. +function makeApiCall() { + gapi.client.people.people.get({ + resourceName: 'people/me' + }).then(function(resp) { + var p = document.createElement('p'); + var name = resp.result.names[0].givenName; + p.appendChild(document.createTextNode('Hello, '+name+'!')); + document.getElementById('content').appendChild(p); + }); +} diff --git a/gapi.auth2/index.d.ts b/gapi.auth2/index.d.ts index 6146a87e28..402da68699 100644 --- a/gapi.auth2/index.d.ts +++ b/gapi.auth2/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Sign-In API +// Type definitions for Google Sign-In API 0.0 // Project: https://developers.google.com/identity/sign-in/web/ // Definitions by: Derek Lawless // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -21,7 +21,7 @@ declare namespace gapi.auth2 { * Calls the onInit function when the GoogleAuth object is fully initialized, or calls the onFailure function if * initialization fails. */ - then(onInit: () => any, onFailure: (reason: string) => any): any; + then(onInit: () => any, onFailure?: (reason: string) => any): any; /** * Signs in the user with the options specified to gapi.auth2.init(). @@ -58,7 +58,7 @@ declare namespace gapi.auth2 { onsuccess: (googleUser: GoogleUser) => any, onfailure: (reason: string) => any): any; } - export interface IsSignedIn{ + export interface IsSignedIn { /** * Returns whether the current user is currently signed in. */ diff --git a/gapi.calendar/gapi.calendar-tests.ts b/gapi.calendar/gapi.calendar-tests.ts new file mode 100644 index 0000000000..de335c6a15 --- /dev/null +++ b/gapi.calendar/gapi.calendar-tests.ts @@ -0,0 +1,152 @@ +/* Example taken from Google Calendar API JavaScript Quickstart https://developers.google.com/google-apps/calendar/quickstart/js */ + +{ + // Your Client ID can be retrieved from your project in the Google + // Developer Console, https://console.developers.google.com + var CLIENT_ID = ''; + + var SCOPES = ["https://www.googleapis.com/auth/calendar.readonly"]; + + /** + * Check if current user has authorized this application. + */ + function checkAuth() { + gapi.auth.authorize( + { + 'client_id': CLIENT_ID, + 'scope': SCOPES.join(' '), + 'immediate': true + }, handleAuthResult); + } + + /** + * Handle response from authorization server. + * + * @param {Object} authResult Authorization result. + */ + function handleAuthResult(authResult: GoogleApiOAuth2TokenObject) { + var authorizeDiv = document.getElementById('authorize-div')!; + if (authResult && !authResult.error) { + // Hide auth UI, then load client library. + authorizeDiv.style.display = 'none'; + loadCalendarApi(); + } else { + // Show auth UI, allowing the user to initiate authorization by + // clicking authorize button. + authorizeDiv.style.display = 'inline'; + } + } + + /** + * Initiate auth flow in response to user clicking authorize button. + * + * @param {Event} event Button click event. + */ + function handleAuthClick(event: MouseEvent) { + gapi.auth.authorize( + {client_id: CLIENT_ID, scope: SCOPES, immediate: false}, + handleAuthResult); + return false; + } + + /** + * Load Google Calendar client library. List upcoming events + * once client library is loaded. + */ + function loadCalendarApi() { + gapi.client.load('calendar', 'v3', listUpcomingEvents); + } + + /** + * Print the summary and start datetime/date of the next ten events in + * the authorized user's calendar. If no events are found an + * appropriate message is printed. + */ + function listUpcomingEvents() { + var request = gapi.client.calendar.events.list({ + 'calendarId': 'primary', + 'timeMin': (new Date()).toISOString(), + 'showDeleted': false, + 'singleEvents': true, + 'maxResults': 10, + 'orderBy': 'startTime' + }); + + request.execute(function(resp) { + var events = resp.items; + appendPre('Upcoming events:'); + + if (events.length > 0) { + for (let i = 0; i < events.length; i++) { + var event = events[i]; + var when = event.start.dateTime; + if (!when) { + when = event.start.date; + } + appendPre(event.summary + ' (' + when + ')') + } + } else { + appendPre('No upcoming events found.'); + } + + }); + } + + /** + * Append a pre element to the body containing the given message + * as its text node. + * + * @param {string} message Text to be placed in pre element. + */ + function appendPre(message: string) { + var pre = document.getElementById('output')!; + var textContent = document.createTextNode(message + '\n'); + pre.appendChild(textContent); + } +} + +/* Example taken from https://developers.google.com/google-apps/calendar/v3/reference/events/insert#examples */ + +{ + // Refer to the JavaScript quickstart on how to setup the environment: + // https://developers.google.com/google-apps/calendar/quickstart/js + // Change the scope to 'https://www.googleapis.com/auth/calendar' and delete any + // stored credentials. + + const event = { + 'summary': 'Google I/O 2015', + 'location': '800 Howard St., San Francisco, CA 94103', + 'description': 'A chance to hear more about Google\'s developer products.', + 'start': { + 'dateTime': '2015-05-28T09:00:00-07:00', + 'timeZone': 'America/Los_Angeles' + }, + 'end': { + 'dateTime': '2015-05-28T17:00:00-07:00', + 'timeZone': 'America/Los_Angeles' + }, + 'recurrence': [ + 'RRULE:FREQ=DAILY;COUNT=2' + ], + 'attendees': [ + {'email': 'lpage@example.com'}, + {'email': 'sbrin@example.com'} + ], + 'reminders': { + 'useDefault': false, + 'overrides': [ + {'method': 'email', 'minutes': 24 * 60}, + {'method': 'popup', 'minutes': 10} + ] + } + }; + + var request = gapi.client.calendar.events.insert({ + 'calendarId': 'primary', + 'resource': event + }); + + request.execute(function(event) { + appendPre('Event created: ' + event.htmlLink); + }); +} diff --git a/gapi.calendar/index.d.ts b/gapi.calendar/index.d.ts new file mode 100644 index 0000000000..bd0e3b0d17 --- /dev/null +++ b/gapi.calendar/index.d.ts @@ -0,0 +1,675 @@ +// Type definitions for Google Calendar API 3.0 +// Project: https://developers.google.com/google-apps/calendar/ +// Definitions by: Tanguy Krotoff +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace gapi.client.calendar { + export class freebusy { + static query(parameters: FreeBusyQueryParameters): HttpRequest; + } + + interface FreeBusyQueryParameters { + timeMin: datetime; + timeMax: datetime; + timeZone?: string; + groupExpansionMax?: integer; + calendarExpansionMax?: integer; + items: {id: string}[]; + } + + interface FreeBusy { + kind: 'calendar#freeBusy'; + timeMin: datetime; + timeMax: datetime; + groups: { + (key: string): { + errors?: { + domain: string; + reason: string; + }[]; + calendars: string[]; + } + }; + calendars: { + (key: string): { + errors?: { + domain: string; + reason: string; + }[]; + busy: { + start: datetime; + end: datetime; + }[]; + } + }; + } + + export class acl { + static insert(parameters: AclInsertParameters): HttpRequest; + static get(parameters: AclGetParameters): HttpRequest; + static update(parameters: AclUpdateParameters): HttpRequest; + static delete(parameters: AclDeleteParameters): HttpRequest; + } + + // The type of the scope. Possible values are: + type ScopeType = + // The public scope. This is the default value. + // Note: The permissions granted to the "default", or public, scope apply to any user, authenticated or not. + 'default' | + // Limits the scope to a single user. + 'user' | + // Limits the scope to a group. + 'group' | + // Limits the scope to a domain. + 'domain'; + + interface Acl { + kind: 'calendar#aclRule'; + etag: etag; + id: string; + scope: { + type: ScopeType; + value: string; + }; + role: AccessRole; + } + + interface AclInsertParameters { + calendarId: string; + + // Acl resource + role: AccessRole; + scope: { + type: ScopeType; + value?: string; + }; + } + + interface AclGetParameters { + calendarId: string; + ruleId: string; + } + + interface AclUpdateParameters extends AclInsertParameters { + ruleId: string; + } + + interface AclDeleteParameters extends AclGetParameters { + } + + export class calendarList { + static list(parameters?: CalendarListListParameters): HttpRequest; + static insert(parameters: CalendarListInsertParameters): HttpRequest; + } + + type AccessRoleWithoutNone = + // The user has read access to free/busy information. + 'freeBusyReader' | + // The user has read access to the calendar. Private events will appear to users with reader access, but event details will be hidden. + 'reader' | + // The user has read and write access to the calendar. Private events will appear to users with writer access, and event details will be visible. + 'writer' | + // The user has ownership of the calendar. This role has all of the permissions of the writer role with the additional ability to see and manipulate ACLs. + 'owner'; + + // The user's access role for this calendar. Read-only. Possible values are: + type AccessRole = + // The user has no access. + 'none' | + AccessRoleWithoutNone; + + interface CalendarListListParameters { + maxResults?: integer; + // The minimum access role for the user in the returned entries. Optional. The default is no restriction. Acceptable values are: + minAccessRole?: AccessRoleWithoutNone; + pageToken?: string; + showDeleted?: boolean; + showHidden?: boolean; + syncToken?: string; + } + + interface CalendarListInsertParameters { + // Parameters + // Optional query parameters + colorRgbFormat?: boolean; + + // CalendarList resource + resource: CalendarListInput; + } + + interface CalendarListInput { + // Required Properties + id: string; + + // Optional Properties + backgroundColor?: string; + colorId?: string; + defaultReminders?: { + method: ReminderMethod; + minutes: integer; + }[]; + foregroundColor?: string; + hidden?: boolean; + notificationSettings?: { + notifications: { + type: NotificationType; + method: string; + }[]; + }; + selected?: boolean; + summaryOverride?: string; + } + + interface CalendarList { + kind: 'calendar#calendarList'; + etag: etag; + + /** + * Token used to access the next page of this result. + * Omitted if no further results are available, in which case nextSyncToken is provided. + */ + nextPageToken?: string; + + /** + * Token used at a later point in time to retrieve only the entries that have changed since this result was returned. + * Omitted if further results are available, in which case nextPageToken is provided. + */ + nextSyncToken?: string; + + items: CalendarListEntry[]; + } + + // The type of notification. Possible values are: + type NotificationType = + // Notification sent when a new event is put on the calendar. + 'eventCreation' | + // Notification sent when an event is changed. + 'eventChange' | + // Notification sent when an event is cancelled. + 'eventCancellation' | + // Notification sent when an event is changed. + 'eventResponse' | + // An agenda with the events of the day (sent out in the morning). + 'agenda'; + + interface CalendarListEntry { + kind: 'calendar#calendarListEntry'; + etag: etag; + id: string; + summary: string; + description?: string; + location?: string; + timeZone?: string; + summaryOverride?: string; + colorId?: string; + backgroundColor?: string; + foregroundColor?: string; + hidden?: boolean; + selected?: boolean; + // The effective access role that the authenticated user has on the calendar. Read-only. + accessRole: AccessRoleWithoutNone; + defaultReminders: { + method: ReminderMethod; + minutes: integer; + }[]; + notificationSettings?: { + notifications: { + type: NotificationType; + method: string; + }[]; + }; + primary?: boolean; + deleted?: boolean; + } + + export class calendars { + static insert(parameters: CalendarsInsertParameters): HttpRequest; + static update(parameters: CalendarsUpdateParameters): HttpRequest; + static delete(parameters: CalendarsDeleteParameters): HttpRequest; + } + + interface CalendarsUpdateParameters { + calendarId: string; + + // Calendars resource + // Optional Properties + description?: string; + location?: string; + summary?: string; + timeZone?: string; + } + + interface CalendarsInsertParameters { + // Calendars resource + // Required Properties + summary: string; + + description?: string; + location?: string; + timeZone?: string; + } + + interface CalendarsDeleteParameters { + calendarId: string; + } + + interface Calendar { + kind: 'calendar#calendar'; + etag: etag; + id: string; + summary: string; + description?: string; + location?: string; + timeZone?: string; + } + + export class events { + static list(parameters: EventsListParameters): HttpRequest; + static insert(parameters: EventsInsertParameters): HttpRequest; + static update(parameters: EventsUpdateParameters): HttpRequest; + static get(parameters: EventsGetParameters): HttpRequest; + } + + interface EventsGetParameters { + calendarId: string; + eventId: string; + + alwaysIncludeEmail?: boolean; + maxAttendees?: integer; + timeZone?: string; + } + + interface EventsInsertParameters { + calendarId: string; + + maxAttendees?: integer; + sendNotifications?: boolean; + supportsAttachments?: boolean; + + // Event resource + resource: EventInput; + } + + interface EventsUpdateParameters { + calendarId: string; + eventId: string; + + alwaysIncludeEmail?: boolean; + maxAttendees?: integer; + sendNotifications?: boolean; + supportsAttachments?: boolean; + + // Event resource + resource: EventInput; + } + + interface EventInput { + // Required Properties + attachments?: { + fileUrl: string; + }[]; + attendees?: { + email: string; + displayName?: string; + optional?: boolean; + responseStatus?: AttendeeResponseStatus; + comment?: string; + additionalGuests?: integer; + }[]; + end: { + date?: date; + dateTime?: datetime; + timeZone?: string + }; + reminders?: { + overrides: { + method: string; + minutes: integer; + }[]; + useDefault: boolean; + }; + start: { + date?: date; + dateTime?: datetime; + timeZone: string; + }; + + // Optional Properties + anyoneCanAddSelf?: boolean; + colorId?: string; + description?: string; + extendedProperties?: { + private: { + (key: string): string + }; + shared: { + (key: string): string + } + }; + gadget?: { + display?: GadgetDisplayMode; + height: integer; + iconLink: string; + link: string; + preferences: { + (key: string): string + } + title: string; + type: string; + width: integer; + }; + guestsCanInviteOthers?: boolean; + guestsCanSeeOtherGuests?: boolean; + id?: string; + location?: string; + originalStartTime?: { + date: date; + dateTime: datetime; + timeZone: string + }; + recurrence?: string[]; + sequence?: integer; + source?: { + url: string; + title: string + }; + status?: EventStatus; + summary?: string; + transparency?: EventTransparency; + visibility?: EventVisibility; + } + + // The order of the events returned in the result. Optional. The default is an unspecified, stable order. + // Acceptable values are: + type EventsOrder = + // Order by the start date/time (ascending). This is only available when querying single events (i.e. the parameter singleEvents is True) + 'startTime' | + // Order by last modification time (ascending). + 'updated'; + + // Token obtained from the nextSyncToken field returned on the last page of results from the previous list request. + // It makes the result of this list request contain only entries that have changed since then. + // All events deleted since the previous list request will always be in the result set and it is not allowed to set showDeleted to False. + // There are several query parameters that cannot be specified together with nextSyncToken to ensure consistency of the client state. + // These are: + type SyncToken = + 'iCalUID' | + 'orderBy' | + 'privateExtendedProperty' | + 'q' | + 'sharedExtendedProperty' | + 'timeMin' | + 'timeMax' | + 'updatedMin'; + + interface EventsListParameters { + calendarId: string; + alwaysIncludeEmail?: boolean; + iCalUID?: string; + maxAttendees?: integer; + maxResults?: integer; + orderBy?: EventsOrder; + pageToken?: string; + privateExtendedProperty?: string; + q?: string; + sharedExtendedProperty?: string; + showDeleted?: boolean; + showHiddenInvitations?: boolean; + singleEvents?: boolean; + syncToken?: SyncToken; + timeMax?: datetime; + timeMin?: datetime; + timeZone?: string; + updatedMin?: datetime; + } + + interface Events { + kind: 'calendar#events'; + etag: etag; + summary: string; + description: string; + updated: datetime; + timeZone: string; + // The user's access role for this calendar. Read-only. Possible values are: + accessRole: AccessRole; + defaultReminders: { + method: ReminderMethod; + minutes: integer; + }[]; + nextPageToken?: string; + nextSyncToken?: string; + items: Event[]; + } + + type etag = string; + type datetime = string; + type date = string; + type integer = number; + + // The attendee's response status. Possible values are: + type AttendeeResponseStatus = + // The attendee has not responded to the invitation. + 'needsAction' | + // The attendee has declined the invitation. + 'declined' | + // The attendee has tentatively accepted the invitation. + 'tentative' | + // The attendee has accepted the invitation. + 'accepted'; + + // The gadget's display mode. Optional. Possible values are: + type GadgetDisplayMode = + // The gadget displays next to the event's title in the calendar view. + 'icon' | + // The gadget displays when the event is clicked. + 'chip'; + + // The method used by this reminder. Possible values are: + type ReminderMethod = + // Reminders are sent via email. + 'email' | + // Reminders are sent via SMS. These are only available for Google Apps for Work, Education, and Government customers. Requests to set SMS reminders for other account types are ignored. + 'sms' | + // Reminders are sent via a UI popup. + 'popup'; + + // Status of the event. Optional. Possible values are: + type EventStatus = + // The event is confirmed. This is the default status. + 'confirmed' | + // The event is tentatively confirmed. + 'tentative' | + // The event is cancelled. + 'cancelled'; + + // Whether the event blocks time on the calendar. Optional. Possible values are: + type EventTransparency = + // The event blocks time on the calendar. This is the default value. + 'opaque' | + // The event does not block time on the calendar. + 'transparent'; + + // Visibility of the event. Optional. Possible values are: + type EventVisibility = + // Uses the default visibility for events on the calendar. This is the default value. + 'default' | + // The event is public and event details are visible to all readers of the calendar. + 'public' | + // The event is private and only event attendees may view event details. + 'private' | + // The event is private. This value is provided for compatibility reasons. + 'confidential'; + + class Event { + kind: 'calendar#event'; + etag: etag; + id: string; + status?: EventStatus; + htmlLink: string; + created: datetime; + updated: datetime; + summary: string; + description: string; + location?: string; + colorId?: string; + + // The creator of the event. Read-only. + creator: { + // The creator's Profile ID, if available. + id?: string; + + // The creator's email address, if available. + email?: string; + + // The creator's name, if available. + displayName?: string; + + // Whether the creator corresponds to the calendar on which this copy of the event appears. Read-only. The default is False. + self?: boolean; + }; + + // The organizer of the event. + organizer: { + // The organizer's Profile ID, if available. + id?: string; + + // The organizer's email address, if available. + email?: string; + + // The organizer's name, if available. + displayName?: string; + + // Whether the organizer corresponds to the calendar on which this copy of the event appears. Read-only. The default is False. + self?: boolean; + }; + + // The (inclusive) start time of the event. For a recurring event, this is the start time of the first instance. + start: { + // The date, in the format "yyyy-mm-dd", if this is an all-day event. + date?: date; + + // The time, as a combined date-time value (formatted according to RFC3339). + // A time zone offset is required unless a time zone is explicitly specified in timeZone. + dateTime?: datetime; + + // The time zone in which the time is specified. (Formatted as an IANA Time Zone Database name, e.g. "Europe/Zurich".) + // For recurring events this field is required and specifies the time zone in which the recurrence is expanded. + // For single events this field is optional and indicates a custom time zone for the event start/end. + timeZone?: string; + }; + + // The (exclusive) end time of the event. For a recurring event, this is the end time of the first instance. + end: { + // The date, in the format "yyyy-mm-dd", if this is an all-day event. + date?: date; + + // The time, as a combined date-time value (formatted according to RFC3339). + // A time zone offset is required unless a time zone is explicitly specified in timeZone. + dateTime?: datetime; + + // The time zone in which the time is specified. (Formatted as an IANA Time Zone Database name, e.g. "Europe/Zurich".) + // For recurring events this field is required and specifies the time zone in which the recurrence is expanded. + // For single events this field is optional and indicates a custom time zone for the event start/end. + timeZone?: string; + }; + + // Whether the end time is actually unspecified. An end time is still provided for compatibility reasons, even if this attribute is set to True. + // The default is False. + endTimeUnspecified?: boolean; + + recurrence: string[]; + + // For an instance of a recurring event, this is the id of the recurring event to which this instance belongs. Immutable. + recurringEventId?: string; + + // Whether the organizer corresponds to the calendar on which this copy of the event appears. Read-only. The default is False. + originalStartTime?: { + date: date; + dateTime: datetime; + timeZone?: string; + }; + + transparency?: EventTransparency; + visibility?: EventVisibility; + iCalUID: string; + sequence: integer; + + // The attendees of the event. + attendees?: { + id: string; + email: string; + displayName?: string; + organizer: boolean; + self: boolean; + resource: boolean; + optional?: boolean; + responseStatus: AttendeeResponseStatus; + comment?: string; + additionalGuests?: integer; + }[]; + + attendeesOmitted?: boolean; + + // Extended properties of the event. + extendedProperties?: { + private: { + (key: string): string; + }; + shared: { + (key: string): string; + } + }; + + // An absolute link to the Google+ hangout associated with this event. Read-only. + hangoutLink?: string; + + // A gadget that extends this event. + gadget?: { + type: string; + title: string; + link: string; + iconLink: string; + width?: integer; + height?: integer; + display?: GadgetDisplayMode; + preferences: { + (key: string): string; + } + }; + + anyoneCanAddSelf?: boolean; + guestsCanInviteOthers?: boolean; + guestsCanModify?: boolean; + guestsCanSeeOtherGuests?: boolean; + privateCopy?: boolean; + + // Whether this is a locked event copy where no changes can be made to the main event fields "summary", "description", "location", "start", "end" or "recurrence". The default is False. Read-Only. + locked?: boolean; + + reminders: { + useDefault: boolean; + overrides?: { + method: ReminderMethod; + minutes: integer; + }[]; + }; + + // Source from which the event was created. For example, a web page, an email message or any document identifiable by an URL with HTTP or HTTPS scheme. + // Can only be seen or modified by the creator of the event. + source?: { + url: string; + title: string; + }; + + // File attachments for the event. Currently only Google Drive attachments are supported. + attachments?: { + fileUrl: string; + title: string; + mimeType: string; + iconLink: string; + fileId: string; + }[]; + } +} diff --git a/gapi.calendar/tsconfig.json b/gapi.calendar/tsconfig.json new file mode 100644 index 0000000000..7613ee5b3d --- /dev/null +++ b/gapi.calendar/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "module": "commonjs", + "lib": ["es6", "dom"], + "strictNullChecks": true, + "noImplicitAny": true, + "noImplicitThis": true, + "forceConsistentCasingInFileNames": true, + "noEmit": true + }, + "files": [ + "index.d.ts", + "gapi.calendar-tests.ts" + ] +} diff --git a/gapi.people/gapi.people-tests.ts b/gapi.people/gapi.people-tests.ts new file mode 100644 index 0000000000..65b6339765 --- /dev/null +++ b/gapi.people/gapi.people-tests.ts @@ -0,0 +1,99 @@ +/* Example taken from Google People API JavaScript Quickstart https://developers.google.com/people/quickstart/js */ + +{ + // Your Client ID can be retrieved from your project in the Google + // Developer Console, https://console.developers.google.com + var CLIENT_ID = ''; + + var SCOPES = ["https://www.googleapis.com/auth/contacts.readonly"]; + + /** + * Check if current user has authorized this application. + */ + function checkAuth() { + gapi.auth.authorize( + { + 'client_id': CLIENT_ID, + 'scope': SCOPES.join(' '), + 'immediate': true + }, handleAuthResult); + } + + /** + * Handle response from authorization server. + * + * @param {Object} authResult Authorization result. + */ + function handleAuthResult(authResult: GoogleApiOAuth2TokenObject) { + var authorizeDiv = document.getElementById('authorize-div')!; + if (authResult && !authResult.error) { + // Hide auth UI, then load client library. + authorizeDiv.style.display = 'none'; + loadPeopleApi(); + } else { + // Show auth UI, allowing the user to initiate authorization by + // clicking authorize button. + authorizeDiv.style.display = 'inline'; + } + } + + /** + * Initiate auth flow in response to user clicking authorize button. + * + * @param {Event} event Button click event. + */ + function handleAuthClick(event: MouseEvent) { + gapi.auth.authorize( + {client_id: CLIENT_ID, scope: SCOPES, immediate: false}, + handleAuthResult); + return false; + } + + /** + * Load Google People client library. List names if available + * of 10 connections. + */ + function loadPeopleApi() { + gapi.client.load('https://people.googleapis.com/$discovery/rest', 'v1', listConnectionNames); + } + + /** + * Print the display name if available for 10 connections. + */ + function listConnectionNames() { + var request = gapi.client.people.people.connections.list({ + 'resourceName': 'people/me', + 'pageSize': 10, + }); + + request.execute(function(resp) { + var connections = resp.connections; + appendPre('Connections:'); + + if (connections.length > 0) { + for (var i = 0; i < connections.length; i++) { + var person = connections[i]; + if (person.names && person.names.length > 0) { + appendPre(person.names[0].displayName) + } else { + appendPre("No display name found for connection."); + } + } + } else { + appendPre('No upcoming events found.'); + } + }); + } + + /** + * Append a pre element to the body containing the given message + * as its text node. + * + * @param {string} message Text to be placed in pre element. + */ + function appendPre(message: string) { + var pre = document.getElementById('output')!; + var textContent = document.createTextNode(message + '\n'); + pre.appendChild(textContent); + } +} diff --git a/gapi.people/index.d.ts b/gapi.people/index.d.ts new file mode 100644 index 0000000000..86bf930beb --- /dev/null +++ b/gapi.people/index.d.ts @@ -0,0 +1,246 @@ +// Type definitions for Google People API 1.0 +// Project: https://developers.google.com/people/ +// Definitions by: Tanguy Krotoff +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace gapi.client.people { + export namespace people { + + interface GetParameters { + resourceName: string; + + // Query parameters + requestMask?: RequestMask; + } + + function get(parameters: GetParameters): HttpRequest; + + interface GetBatchGetParameters { + // Query parameters + resourcesName?: string; + requestMask?: RequestMask; + } + + function getBatchGet(parameters: GetBatchGetParameters): HttpRequest; + + interface BatchGetResponse { + responses: PersonResponse[]; + } + + interface PersonResponse { + httpStatusCode: number; + person: Person; + requestedResourceName: string; + } + + namespace connections { + function list(parameters: ListParameters): HttpRequest; + + type SortOrder = 'LAST_MODIFIED_ASCENDING' | 'FIRST_NAME_ASCENDING' | 'LAST_NAME_ASCENDING'; + + interface ListParameters { + resourceName: string; + + // Query parameters + pageToken?: string; + pageSize?: number; + sortOrder?: SortOrder; + syncToken?: string; + requestMask?: RequestMask; + } + + interface Response { + connections: Person[]; + nextPageToken: string; + nextSyncToken: string; + } + } + } + + interface RequestMask { + includeField: string; + } + + type SourceType = 'SOURCE_TYPE_UNSPECIFIED' | 'ACCOUNT' | 'PROFILE' | 'DOMAIN_PROFILE' | 'CONTACT'; + + interface Source { + type: SourceType; + id: string; + etag: string; + resourceName: string; + } + + type ObjectType = 'OBJECT_TYPE_UNSPECIFIED' | 'PERSON' | 'PAGE'; + + interface PersonMetadata { + sources: Source[]; + previousResourceNames: string[]; + linkedPeopleResourceNames: string[]; + deleted: boolean; + objectType: ObjectType; + } + + interface FieldMetadata { + primary: boolean; + verified: boolean; + source: Source; + } + + interface Locale { + metadata: FieldMetadata; + value: string; + } + + interface Name { + metadata: FieldMetadata; + displayName: string; + displayNameLastFirst: string; + familyName: string; + givenName: string; + middleName: string; + honorificPrefix: string; + honorificSuffix: string; + phoneticFullName: string; + phoneticFamilyName: string; + phoneticGivenName: string; + phoneticMiddleName: string; + phoneticHonorificPrefix: string; + phoneticHonorificSuffix: string; + } + + type NicknameType = 'DEFAULT' | 'MAIDEN_NAME' | 'INITIALS' | 'GPLUS' | 'OTHER_NAME'; + + interface Nickname { + metadata: FieldMetadata; + value: string; + type: NicknameType; + } + + interface CoverPhoto { + } + + interface Photo { + } + + interface Gender { + } + + interface AgeRange { + } + + interface Birthday { + } + + interface Event { + } + + interface Address { + metadata: FieldMetadata; + formattedValue: string; + type: string; + formattedType: string; + poBox: string; + streetAddress: string; + extendedAddress: string; + city: string; + region: string; + postalCode: string; + country: string; + countryCode: string; + } + + interface Residence { + metadata: FieldMetadata; + value: string; + current: boolean; + } + + interface EmailAddress { + metadata: FieldMetadata; + value: string; + type: string; + formattedType: string; + displayName: string; + } + + interface PhoneNumber { + metadata: FieldMetadata; + value: string; + canonicalForm: string; + type: string; + formattedType: string; + } + + interface ImClient { + } + + interface Tagline { + } + + interface Biography { + } + + interface Url { + } + + interface Organization { + } + + interface Occupation { + } + + interface Interest { + } + + interface Skill { + } + + interface BraggingRights { + } + + interface Relation { + } + + interface RelationshipInterest { + } + + interface RelationshipStatus { + } + + interface Membership { + } + + interface Person { + resourceName: string; + etag: string; + metadata: PersonMetadata; + locales: Locale[]; + names: Name[]; + nicknames?: Nickname[]; + coverPhotos: CoverPhoto[]; + photos?: Photo[]; + genders?: Gender[]; + ageRange?: AgeRange; + birthdays?: Birthday[]; + events?: Event[]; + addresses?: Address[]; + residences?: Residence[]; + emailAddresses?: EmailAddress[]; + phoneNumbers?: PhoneNumber[]; + imClients?: ImClient[]; + taglines?: Tagline[]; + biographies?: Biography[]; + urls?: Url[]; + organizations?: Organization[]; + occupations?: Occupation[]; + interests?: Interest[]; + skills?: Skill[]; + BraggingRights?: BraggingRights[]; + relations?: Relation[]; + relationshipInterests?: RelationshipInterest[]; + relationshipStatuses?: RelationshipStatus[]; + memberships?: Membership[]; + } +} diff --git a/gapi.people/tsconfig.json b/gapi.people/tsconfig.json new file mode 100644 index 0000000000..93fcfc59b6 --- /dev/null +++ b/gapi.people/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "module": "commonjs", + "lib": ["es6", "dom"], + "strictNullChecks": true, + "noImplicitAny": true, + "noImplicitThis": true, + "forceConsistentCasingInFileNames": true, + "noEmit": true + }, + "files": [ + "index.d.ts", + "gapi.people-tests.ts" + ] +} diff --git a/gapi.plus/gapi.plus-tests.ts b/gapi.plus/gapi.plus-tests.ts new file mode 100644 index 0000000000..12368dd63c --- /dev/null +++ b/gapi.plus/gapi.plus-tests.ts @@ -0,0 +1,10 @@ +/* Example taken from https://developers.google.com/+/web/people/ */ + +gapi.client.load('plus','v1', function(){ + var request = gapi.client.plus.people.get({ + 'userId': 'me' + }); + request.execute(function(resp) { + console.log('Retrieved profile for:' + resp.displayName); + }); +}); diff --git a/gapi.plus/index.d.ts b/gapi.plus/index.d.ts new file mode 100644 index 0000000000..3e24b79ce1 --- /dev/null +++ b/gapi.plus/index.d.ts @@ -0,0 +1,111 @@ +// Type definitions for Google+ Platform API 1.0 +// Project: https://developers.google.com/+/web/people/ +// Definitions by: Tanguy Krotoff +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +// See Google+ REST API Reference https://developers.google.com/+/web/api/rest/latest/ +declare namespace gapi.client.plus { + export namespace people { + + interface GetParameters { + userId: string; + } + function get(parameters: GetParameters): HttpRequest; + + interface SearchParameters { + query: string; + language?: string; + maxResults?: number; + pageToken?: string; + } + function search(parameters: SearchParameters): HttpRequest; + + // Search response + interface PeopleFeed { + kind: 'plus#peopleFeed'; + etag: string; + selfLink: string; + title: string; + nextPageToken: string; + totalItems: number; + items: Person[]; + } + + interface Person { + kind: 'plus#person'; + etag: string; + nickname: string; + occupation: string; + skills: string; + birthday: string; + gender: string; + emails: { + value: string; + type: string; + }[]; + urls: { + value: string; + type: string; + label: string; + }[]; + objectType: string; + id: string; + displayName: string; + name: { + formatted: string; + familyName: string; + givenName: string; + middleName: string; + honorificPrefix: string; + honorificSuffix: string; + }; + tagline: string; + braggingRights: string; + aboutMe: string; + relationshipStatus: string; + url: string; + image: { + url: string; + }; + organizations: { + name: string; + department: string; + title: string; + type: string; + startDate: string; + endDate: string; + location: string; + description: string; + primary: boolean; + }[]; + placesLived: { + value: string; + primary: boolean; + }[]; + isPlusUser: boolean; + language: string; + ageRange: { + min: number; + max: number; + }; + plusOneCount: number; + circledByCount: number; + verified: boolean; + cover: { + layout: string; + coverPhoto: { + url: string; + height: number; + width: number; + }; + coverInfo: { + topImageOffset: number; + leftImageOffset: number; + } + }; + domain: string; + } + } +} diff --git a/gapi.plus/tsconfig.json b/gapi.plus/tsconfig.json new file mode 100644 index 0000000000..1fc2401de1 --- /dev/null +++ b/gapi.plus/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "module": "commonjs", + "lib": ["es6", "dom"], + "strictNullChecks": true, + "noImplicitAny": true, + "noImplicitThis": true, + "forceConsistentCasingInFileNames": true, + "noEmit": true + }, + "files": [ + "index.d.ts", + "gapi.plus-tests.ts" + ] +} diff --git a/gapi/gapi-tests.ts b/gapi/gapi-tests.ts new file mode 100644 index 0000000000..b16cade6bb --- /dev/null +++ b/gapi/gapi-tests.ts @@ -0,0 +1,97 @@ +/// +/// + +/* Examples taken from https://developers.google.com/api-client-library/javascript/start/start-js */ + +{ + function start1() { + // 2. Initialize the JavaScript client library. + gapi.client.init({ + 'apiKey': 'YOUR_API_KEY', + 'discoveryDocs': ['https://people.googleapis.com/$discovery/rest'], + // clientId and scope are optional if auth is not required. + 'clientId': 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com', + 'scope': 'profile', + }).then(function() { + // 3. Initialize and make the API request. + return gapi.client.people.people.get({ + resourceName: 'people/me' + }); + }).then(function(response) { + console.log(response.result); + }, function(reason) { + console.log('Error: ' + reason.result.error.message); + }); + }; + // 1. Load the JavaScript client library. + gapi.load('client', start1); +} + +{ + function start2() { + // 2. Initialize the JavaScript client library. + gapi.client.init({ + 'apiKey': 'YOUR_API_KEY', + // clientId and scope are optional if auth is not required. + 'clientId': 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com', + 'scope': 'profile', + }).then(function() { + // 3. Initialize and make the API request. + return gapi.client.request({ + 'path': 'https://people.googleapis.com/v1/people/me', + }) + }).then(function(response) { + console.log(response.result); + }, function(reason) { + console.log('Error: ' + reason.result.error.message); + }); + }; + // 1. Load the JavaScript client library. + gapi.load('client', start2); +} + + +/* Examples taken from https://developers.google.com/api-client-library/javascript/features/promises */ + +gapi.client.request({'path': '/plus/v1/people', 'params': {'query': 'John'}}).then(function(response) { + // Handle response +}, function(reason) { + // Handle error +}); + +gapi.client.load('plus', 'v1').then(function() { + gapi.client.plus.people.search({'query': ''}).then(response => { }); +}); + +var personFetcher = { + results: [], + + // Why this: any? Check https://github.com/Microsoft/TypeScript/issues/10835 + + fetch: function(this: any, name: string) { + gapi.client.request({path: '/plus/v1/people', params:{query: name}}).then(function(this: any, response) { + this.results.push(response.result); + }, function(reason) { + console.error(name, 'was not fetched:', reason.result.error.message); + }, this); + } +}; +personFetcher.fetch('John'); + +gapi.client.request({ + 'path': 'plus/v1/people', + 'params': {'query': name} +}).execute(function(resp, rawResp) { + processResponse(resp); +}); + +gapi.client.request({ + 'path': 'plus/v1/people', + 'params': {'query': name} +}).then(function(resp) { + processResponse(resp.result); +}); + +function processResponse(response: any) { + // Stub +} diff --git a/gapi/index.d.ts b/gapi/index.d.ts index 28d5c990bc..8f8e621fa3 100644 --- a/gapi/index.d.ts +++ b/gapi/index.d.ts @@ -1,8 +1,8 @@ -// Type definitions for Google API Client +// Type definitions for Google API Client 0.0 // Project: https://code.google.com/p/google-api-javascript-client/ // Definitions by: Frank M // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.1 /** * The OAuth 2.0 token object represents the OAuth 2.0 token and any associated data. @@ -38,7 +38,7 @@ declare namespace gapi { /** * Pragmatically initialize gapi class member. */ - export function load(object: string, fn: any) : any; + export function load(apiName: string, callback: () => void): void; } @@ -102,7 +102,7 @@ declare namespace gapi.auth { /** * A function in the global namespace, which is called when the sign-in button is rendered and also called after a sign-in flow completes. */ - callback?: Function; + callback?: () => void; /** * If true, all previously granted scopes remain granted in each incremental request, for incremental authorization. The default value true is correct for most use cases; use false only if employing delegated auth, where you pass the bearer token to a less-trusted component with lower programmatic authority. */ @@ -127,6 +127,30 @@ declare namespace gapi.auth { } declare namespace gapi.client { + /** + * Initializes the JavaScript client with API key, OAuth client ID, scope, and API discovery document(s). + * If OAuth client ID and scope are provided, this function will load the gapi.auth2 module to perform OAuth. + * The gapi.client.init function can be run multiple times, such as to set up more APIs, to change API key, or initialize OAuth lazily. + */ + export function init(args: { + /** + * The API Key to use. + */ + apiKey?: string; + /** + * An array of discovery doc URLs or discovery doc JSON objects. + */ + discoveryDocs?: string[]; + /** + * The app's client ID, found and created in the Google Developers Console. + */ + clientId?: string; + /** + * The scopes to request, as a space-delimited string. + */ + scope?: string + }): Promise; + interface RequestOptions { /** * The URL to handle the request @@ -155,43 +179,79 @@ declare namespace gapi.client { } /** - * Loads the client library interface to a particular API. If a callback is not provided, a promise is returned. - * @param name The name of the API to load. - * @param version The version of the API to load. - * @return promise The promise that get's resolved after the request is finished. - */ - export function load(name: string, version: string): Promise + * Loads the client library interface to a particular API. If a callback is not provided, a promise is returned. + * @param name The name of the API to load. + * @param version The version of the API to load. + * @return promise The promise that get's resolved after the request is finished. + */ + export function load(name: string, version: string): Promise; /** - * Loads the client library interface to a particular API. The new API interface will be in the form gapi.client.api.collection.method. - * @param name The name of the API to load. - * @param version The version of the API to load - * @param callback the function that is called once the API interface is loaded - * @param url optional, the url of your app - if using Google's APIs, don't set it - */ + * Loads the client library interface to a particular API. The new API interface will be in the form gapi.client.api.collection.method. + * @param name The name of the API to load. + * @param version The version of the API to load + * @param callback the function that is called once the API interface is loaded + * @param url optional, the url of your app - if using Google's APIs, don't set it + */ export function load(name: string, version: string, callback: () => any, url?: string): void; /** - * Creates a HTTP request for making RESTful requests. - * An object encapsulating the various arguments for this method. - */ + * Creates a HTTP request for making RESTful requests. + * An object encapsulating the various arguments for this method. + */ export function request(args: RequestOptions): HttpRequest; /** - * Creates an RPC Request directly. The method name and version identify the method to be executed and the RPC params are provided upon RPC creation. - * @param method The method to be executed. - * @param version The version of the API which defines the method to be executed. Defaults to v1 - * @param rpcParams A key-value pair of the params to supply to this RPC - */ + * Creates an RPC Request directly. The method name and version identify the method to be executed and the RPC params are provided upon RPC creation. + * @param method The method to be executed. + * @param version The version of the API which defines the method to be executed. Defaults to v1 + * @param rpcParams A key-value pair of the params to supply to this RPC + */ export function rpcRequest(method: string, version?: string, rpcParams?: any): RpcRequest; /** - * Sets the API key for the application. - * @param apiKey The API key to set - */ + * Sets the API key for the application. + * @param apiKey The API key to set + */ export function setApiKey(apiKey: string): void; + interface HttpRequestFulfilled { + result: T; + body: string; + headers?: any[]; + status?: number; + statusText?: string; + } + + interface HttpRequestRejected { + result: { + error: { + message: string; + } + }; + body: string; + headers?: any[]; + status?: number; + statusText?: string; + } + + /** + * HttpRequest supports promises. + * See Google API Client JavaScript Using Promises https://developers.google.com/api-client-library/javascript/features/promises + * + * TODO This should be updated when TypeScript 2.3 is released + * See https://github.com/Microsoft/TypeScript/issues/12409 + * See https://github.com/Microsoft/TypeScript/blob/65da012527937a3074c62655d60ee08fee809f7f/lib/lib.es5.d.ts#L1339 + */ + class HttpRequestPromise { + then( + opt_onFulfilled?: ((response: HttpRequestFulfilled) => void) | null, + opt_onRejected?: ((reason: HttpRequestRejected) => void) | null, + opt_context?: any + ): Promise; + } + /** * An object encapsulating an HTTP request. This object is not instantiated directly, rather it is returned by gapi.client.request. */ - export class HttpRequest { + export class HttpRequest extends HttpRequestPromise { /** * Executes the request and runs the supplied callback on response. * @param callback The callback function which executes when the request succeeds or fails. @@ -210,25 +270,9 @@ declare namespace gapi.client { status: number; statusText: string; } - ) => any):void; - /** - * HttpRequest supports promises. - */ - then(success:(response:{ - result:T; - body:string; - headers?: any[]; - status?: number; - statusText?: string - })=>void, - failure:(response:{ - result:T; - body:string; - headers?: any[]; - status?: number; - statusText?: string - })=>void): void; + ) => any): void; } + /** * Represents an HTTP Batch operation. Individual HTTP requests are added with the add method and the batch is executed using execute. */ @@ -244,16 +288,16 @@ declare namespace gapi.client { */ id: string; callback: ( - /** - * is the response for this request only. Its format is defined by the API method being called. - */ - individualResponse: any, - /** - * is the raw batch ID-response map as a string. It contains all responses to all requests in the batch. - */ - rawBatchResponse: any - ) => any - }):void; + /** + * is the response for this request only. Its format is defined by the API method being called. + */ + individualResponse: any, + /** + * is the raw batch ID-response map as a string. It contains all responses to all requests in the batch. + */ + rawBatchResponse: any + ) => any + }): void; /** * Executes all requests in the batch. The supplied callback is executed on success or failure. * @param callback The callback to execute when the batch returns. @@ -267,7 +311,7 @@ declare namespace gapi.client { * is the same response, but as an unparsed JSON-string. */ rawBatchResponse: string - ) => any):void; + ) => any): void; } /** @@ -288,7 +332,7 @@ declare namespace gapi.client { * is the same as jsonResp, except it is a raw string that has not been parsed. It is typically used when the response is not JSON. */ rawResp: string - ) => void ):void; + ) => void): void; } } diff --git a/gapi/tsconfig.json b/gapi/tsconfig.json index 27e01ecd7b..22f5738c1a 100644 --- a/gapi/tsconfig.json +++ b/gapi/tsconfig.json @@ -2,11 +2,12 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -16,6 +17,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "index.d.ts" + "index.d.ts", + "gapi-tests.ts" ] -} \ No newline at end of file +} diff --git a/gettext.js/gettext.js-tests.ts b/gettext.js/gettext.js-tests.ts new file mode 100644 index 0000000000..6e5b4448ae --- /dev/null +++ b/gettext.js/gettext.js-tests.ts @@ -0,0 +1,21 @@ +import * as Gettext from 'gettext.js'; + +const json: Gettext.JsonData = { + "": { + "locale": "fr", + "plural-forms": "nplurals=2; plural=n>1;" + }, + "Welcome": "Bienvenue", + "There is %1 apple": [ + "Il y a %1 pomme", + "Il y a %1 pommes" + ] +}; + +const instance: Gettext.Gettext = Gettext.i18n(); + +instance.loadJSON(json, 'messages'); +instance.setLocale('fr'); +if (instance.ngettext('There is %1 apple', 'There are %1 apples', 0) === 'Il y a %1 pomme') { + throw new Error('Failed test'); +} diff --git a/gettext.js/index.d.ts b/gettext.js/index.d.ts new file mode 100644 index 0000000000..5096490721 --- /dev/null +++ b/gettext.js/index.d.ts @@ -0,0 +1,45 @@ +// Type definitions for gettext.js 0.5 +// Project: https://github.com/guillaumepotier/gettext.js +// Definitions by: Julien Crouzet +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type PluralForm = (n: number) => number; + +export type GettextStatic = (options?: GettextOptions) => Gettext; + +export interface GettextOptions { + domain?: string; + locale?: string; + plural_func?: PluralForm; + ctxt_delimiter?: string; +} + +export interface JsonDataHeader { + locale: string; + "plural-forms": string; +} + +export interface JsonDataMessages { + [key: string]: string | string[] | JsonDataHeader; +} + +export interface JsonData extends JsonDataMessages { + "": JsonDataHeader; +} + +export interface Gettext { + setMessages: (domain: string, locale: string, messages: JsonDataMessages, plural_forms?: PluralForm) => Gettext; + loadJSON: (jsonData: JsonData, domain?: string) => Gettext; + setLocale: (locale: string) => Gettext; + getLocale: () => string; + textdomain: (domain?: string) => Gettext | string; + gettext: (msgid: string, ...args: any[]) => string; + ngettext: (msgid: string, msgid_plural: string, n: number, ...args: any[]) => string; + pgettext: (msgctxt: string, msgid: string, ...args: any[]) => string; + dcnpgettext: (domain: string, msgctxt: string, msgid: string, msgid_plural: string, n: number, ...args: any[]) => string; + __: (msgid: string, ...args: any[]) => string; + _n: (msgid: string, msgid_plural: string, n: number, ...args: any[]) => string; + _p: (msgctxt: string, msgid: string, ...args: any[]) => string; +} + +export const i18n: GettextStatic; diff --git a/gettext.js/tsconfig.json b/gettext.js/tsconfig.json new file mode 100644 index 0000000000..d01ec061ab --- /dev/null +++ b/gettext.js/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gettext.js-tests.ts" + ] +} diff --git a/gettext.js/tslint.json b/gettext.js/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/gettext.js/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/gijgo/gijgo-tests.ts b/gijgo/gijgo-tests.ts index 5731732295..6e624ad4f6 100644 --- a/gijgo/gijgo-tests.ts +++ b/gijgo/gijgo-tests.ts @@ -1,5 +1,4 @@ /// -/// // Grid $(() => { diff --git a/gldatepicker/gldatepicker-tests.ts b/gldatepicker/gldatepicker-tests.ts index d133a5f823..974c1da8a7 100644 --- a/gldatepicker/gldatepicker-tests.ts +++ b/gldatepicker/gldatepicker-tests.ts @@ -1,5 +1,3 @@ -/// - $('input').glDatePicker(); $('#example2').glDatePicker( { diff --git a/gm/gm-tests.ts b/gm/gm-tests.ts index debd18ecff..e8bf5787cd 100644 --- a/gm/gm-tests.ts +++ b/gm/gm-tests.ts @@ -1,6 +1,3 @@ - -/// - import gm = require('gm'); import stream = require('stream'); @@ -78,6 +75,7 @@ gm(src) .authenticate(password) .autoOrient() .backdrop() + .background(color) .bitdepth(bits) .blackThreshold(intensity) .blackThreshold(r, g, b) diff --git a/gm/index.d.ts b/gm/index.d.ts index 288ce150ce..7fd419ede3 100644 --- a/gm/index.d.ts +++ b/gm/index.d.ts @@ -108,6 +108,7 @@ declare namespace m { authenticate(password: string): State; autoOrient(): State; backdrop(): State; + background(color: string): State; bitdepth(bits: number): State; blackThreshold(intensity: number): State; blackThreshold(red: number, green: number, blue: number, opacity?: number): State; diff --git a/google-protobuf/google-protobuf-tests.ts b/google-protobuf/google-protobuf-tests.ts new file mode 100644 index 0000000000..76d4f19fcc --- /dev/null +++ b/google-protobuf/google-protobuf-tests.ts @@ -0,0 +1,139 @@ +import * as jspb from "google-protobuf"; + +/* This is a typescript version of a simple generated class from a proto file that is shown below. In order to make + this ES5 JS file into TypeScript there have been quite a few modifications, but the same calls are made to the library + classes. + + // FILE: simple.proto + syntax = "proto3"; + + package examplecom; + + message MySimple { + string my_string = 1; + bool my_bool = 2; + repeated string some_labels = 3; + } +*/ + +class MySimple extends jspb.Message { + constructor(opt_data?: any) { + super(); // This isn't actually called in the JS version of this file, but it's required by TS + jspb.Message.initialize(this, opt_data, 0, -1, MySimple.repeatedFields_, null); + }; + + static repeatedFields_ = [3]; + + toObject(opt_includeInstance: boolean): {} { + return MySimple.toObject(opt_includeInstance, this); + }; + + static toObject(includeInstance: boolean, msg: MySimple): {} { + const obj: {} = { + myString: jspb.Message.getFieldWithDefault(msg, 1, ""), + myBool: jspb.Message.getFieldWithDefault(msg, 2, false), + someLabelsList: jspb.Message.getField(msg, 3), + }; + + if (includeInstance) { + // This is commented out because it's not valid in TS, but it's a simple append to an object + // obj['$jspbMessageInstance'] = msg; + } + return obj; + }; + + static deserializeBinary(bytes: Uint8Array) { + const reader = new jspb.BinaryReader(bytes); + const msg = new MySimple(); + return MySimple.deserializeBinaryFromReader(msg, reader); + }; + + static deserializeBinaryFromReader(msg: MySimple, reader: jspb.BinaryReader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + const field = reader.getFieldNumber(); + switch (field) { + case 1: + const value1 = (reader.readString()); + msg.setMyString(value1); + break; + case 2: + const value2 = (reader.readBool()); + msg.setMyBool(value2); + break; + case 3: + const value3 = (reader.readString()); + msg.addSomeLabels(value3); + break; + default: + reader.skipField(); + break; + } + } + return msg; + }; + + serializeBinary(): Uint8Array { + const writer = new jspb.BinaryWriter(); + MySimple.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); + }; + + static serializeBinaryToWriter(message: MySimple, writer: jspb.BinaryWriter) { + let f1 = message.getMyString(); + if (f1.length > 0) { + writer.writeString( + 1, + f1, + ); + } + const f2 = message.getMyBool(); + if (f2) { + writer.writeBool( + 2, + f2, + ); + } + const f3 = message.getSomeLabelsList(); + if (f3.length > 0) { + writer.writeRepeatedString( + 3, + f3, + ); + } + } + + getMyString(): string { + return jspb.Message.getFieldWithDefault(this, 1, ""); + } + + setMyString(value: string) { + jspb.Message.setField(this, 1, value); + } + + getMyBool(): boolean { + return jspb.Message.getFieldWithDefault(this, 2, false); + } + + setMyBool(value: boolean) { + jspb.Message.setField(this, 2, value); + } + + getSomeLabelsList(): string[] { + return jspb.Message.getField(this, 3); + } + + setSomeLabelsList(value: string[]) { + jspb.Message.setField(this, 3, value || []); + } + + addSomeLabels(value: string, opt_index?: number) { + jspb.Message.addToRepeatedField(this, 3, value, opt_index); + } + + clearSomeLabelsList() { + this.setSomeLabelsList([]); + } +} diff --git a/google-protobuf/index.d.ts b/google-protobuf/index.d.ts new file mode 100644 index 0000000000..cf6a7e218a --- /dev/null +++ b/google-protobuf/index.d.ts @@ -0,0 +1,687 @@ +// Type definitions for google-protobuf 3.2 +// Project: https://github.com/google/google-protobuf +// Definitions by: Marcus Longmuir +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type ByteSource = ArrayBuffer|Uint8Array|number[]|string; +type ScalarFieldType = boolean|number|string; +type RepeatedFieldType = ScalarFieldType[] | Uint8Array[]; +type AnyFieldType = ScalarFieldType | RepeatedFieldType | Uint8Array; +type FieldValue = (string|number|boolean|Uint8Array|any/*This should be Array, but that isn't allowed*/|undefined) + +export abstract class Message { + getJsPbMessageId(): (string | undefined); + static initialize(msg: Message, + data: Message.MessageArray, + messageId: (string | number), + suggestedPivot: number, + repeatedFields: number[], + oneofFields?: number[][] | null): void; + static toObjectList(field: T[], + toObjectFn: (includeInstance: boolean, + data: T) => {}, + includeInstance?: boolean): {}[]; + static toObjectExtension(msg: Message, + obj: {}, + extensions: {[key: number]: ExtensionFieldInfo}, + getExtensionFn: (fieldInfo: ExtensionFieldInfo) => Message, + includeInstance?: boolean): void; + serializeBinaryExtensions(proto: Message, + writer: BinaryWriter, + extensions: {[key: number]: ExtensionFieldBinaryInfo}, + getExtensionFn: (fieldInfo: ExtensionFieldInfo) => T): void + readBinaryExtension(proto: Message, + reader: BinaryReader, + extensions: {[key: number]: ExtensionFieldBinaryInfo}, + setExtensionFn: (fieldInfo: ExtensionFieldInfo, + val: T) => void): void + static getField(msg: Message, + fieldNumber: number): FieldValue|null; + static getOptionalFloatingPointField(msg: Message, + fieldNumber: number): (number | undefined); + static getRepeatedFloatingPointField(msg: Message, + fieldNumber: number): number[]; + static bytesAsB64(bytes: Uint8Array): string; + static bytesAsU8(str: string): Uint8Array; + static bytesListAsB64(bytesList: Uint8Array[]): string[]; + static bytesListAsU8(strList: string[]): Uint8Array[]; + static getFieldWithDefault(msg: Message, + fieldNumber: number, + defaultValue: T): T; + static getMapField(msg: Message, + fieldNumber: number, + noLazyCreate: boolean, + valueCtor: typeof Message): Map; + static setField(msg: Message, + fieldNumber: number, + value: FieldValue): void; + static addToRepeatedField(msg: Message, + fieldNumber: number, + value: any, + index?: number): void; + static setOneofField(msg: Message, + fieldNumber: number, + oneof: number[], + value: FieldValue): void; + static computeOneofCase(msg: Message, + oneof: number[]): number; + static getWrapperField(msg: Message, + ctor: typeof Message, + fieldNumber: number, + required?: number): Message; + static getRepeatedWrapperField(msg: Message, + ctor: typeof Message, + fieldNumber: number): Message[]; + static setWrapperField(msg: Message, + fieldNumber: number, + value?: (Message|Map)): void; + static setOneofWrapperField(msg: Message, + fieldNumber: number, + oneof: number[], + value: any): void; + static setRepeatedWrapperField(msg: Message, + fieldNumber: number, + value: any): void; + static addToRepeatedWrapperField(msg: Message, + fieldNumber: number, + value: any, + ctor: typeof Message, + index: number): any; + static toMap(field: any[], + mapKeyGetterFn: (field: any) => string, + toObjectFn?: Message.StaticToObject, + includeInstance?: boolean): void; + toArray(): Message.MessageArray; + toString(): string; + getExtension(fieldInfo: ExtensionFieldInfo): T; + setExtension(fieldInfo: ExtensionFieldInfo, + value: T): void; + static difference(m1: T, + m2: T): T; + static equals(m1: Message, + m2: Message): boolean; + static compareExtensions(extension1: {}, + extension2: {}): boolean; + static compareFields(field1: any, + field2: any): boolean; + cloneMessage(): Message; + clone(): Message; + static clone(msg: T): T; + static cloneMessage(msg: T): T; + static copyInto(fromMessage: Message, + toMessage: Message): void; + static registerMessageType(id: number, + constructor: typeof Message): void; + + abstract serializeBinary(): Uint8Array; + abstract toObject(includeInstance?: boolean): {}; + + // These are `abstract static`, but that isn't allowed. Subclasses of Message will have these methods and properties + // and not having them on Message makes using this class for its intended purpose quite difficult. + static deserializeBinary(bytes: Uint8Array): Message; + static deserializeBinaryFromReader(message: Message, reader: BinaryReader): Message; + static serializeBinaryToWriter(message: Message, writer: BinaryWriter): void; + static toObject(includeInstance: boolean, msg: Message): {}; + static extensions: {[key: number]: ExtensionFieldInfo}; + static extensionsBinary: {[key: number]: ExtensionFieldBinaryInfo}; +} + +export namespace Message { + export type MessageArray = any[]; // This type needs to reference itself + interface StaticToObject { + (includeInstance: boolean, + msg: Message): {}; + } +} + +export class ExtensionFieldInfo { + fieldIndex: number; + fieldName: number; + ctor: typeof Message; + toObjectFn: Message.StaticToObject; + isRepeated: number; + constructor(fieldIndex: number, + fieldName: {[key: string]: number}, + ctor: typeof Message, + toObjectFn: Message.StaticToObject, + isRepeated: number); + isMessageType(): boolean; +} + +export class ExtensionFieldBinaryInfo { + fieldInfo: ExtensionFieldInfo; + binaryReaderFn: BinaryRead; + binaryWriterFn: BinaryWrite; + opt_binaryMessageSerializeFn: (msg: Message, + writer: BinaryWriter) => void; + opt_binaryMessageDeserializeFn: (msg: Message, + reader: BinaryReader) => Message; + opt_isPacked: boolean; + constructor(fieldInfo: ExtensionFieldInfo, + binaryReaderFn: BinaryRead, + binaryWriterFn: BinaryWrite, + opt_binaryMessageSerializeFn: (msg: Message, + writer: BinaryWriter) => void, + opt_binaryMessageDeserializeFn: (msg: Message, + reader: BinaryReader) => Message, + opt_isPacked: boolean); +} + +export class Map { + constructor(arr: Array<[K, V]>, + valueCtor?: {new(init: any): V}); + toArray(): Array<[K, V]>; + toObject(includeInstance: boolean, + valueToObject: (includeInstance: boolean) => any): Array<[K, V]>; + static fromObject(entries: Array<[K, V]>, + valueCtor: any, + valueFromObject: any): Map; + getLength(): number; + clear(): void; + del(key: K): boolean; + getEntryList(): Array<[K, V]>; + entries(): Map.Iterator<[K, V]>; + keys(): Map.Iterator; + forEach(callback: (entry: V, + key: K) => void, + thisArg?: {}): void; + set(key: K, + value: V): void; + get(key: K): (V | undefined); + has(key: K): boolean; +} + +export namespace Map { + // This is implemented by jspb.Map.ArrayIteratorIterable_, but that class shouldn't be exported + interface Iterator { + next(): IteratorResult; + } + type IteratorResult = { + done: boolean, + value: T, + } +} + +interface BinaryReadReader { + (msg: any, + binaryReader: BinaryReader): void; +} + +interface BinaryRead { + (msg: any, + reader: BinaryReadReader): void; +} + +interface BinaryWriteCallback { + (value: any, + binaryWriter: BinaryWriter): void; +} + +interface BinaryWrite { + (fieldNumber: number, + value: any, + writerCallback: BinaryWriteCallback): void; +} + +export class BinaryReader { + constructor(bytes?: ByteSource, + start?: number, + length?: number); + static alloc(bytes?: ByteSource, + start?: number, + length?: number): BinaryReader; + alloc(bytes?: ByteSource, + start?: number, + length?: number): BinaryReader; + free(): void; + getFieldCursor(): number; + getCursor(): number; + getBuffer(): Uint8Array; + getFieldNumber(): number; + getWireType(): BinaryConstants.WireType; + isEndGroup(): boolean; + getError(): boolean; + setBlock(bytes?: ByteSource, + start?: number, + length?: number): void; + reset(): void; + advance(count: number): void; + nextField(): boolean; + unskipHeader(): void; + skipMatchingFields(): void; + skipVarintField(): void; + skipDelimitedField(): void; + skipFixed32Field(): void; + skipFixed64Field(): void; + skipGroup(): void; + skipField(): void; + registerReadCallback(callbackName: string, + callback: (binaryReader: BinaryReader) => any): void; + runReadCallback(callbackName: string): any; + readAny(fieldType: BinaryConstants.FieldType): AnyFieldType; + readMessage: BinaryRead; + readGroup(field: number, + message: Message, + reader: BinaryReadReader): void; + getFieldDecoder(): BinaryDecoder; + readInt32(): number; + readInt32String(): string; + readInt64(): number; + readInt64String(): string; + readUint32(): number; + readUint32String(): string; + readUint64(): number; + readUint64String(): string; + readSint32(): number; + readSint64(): number; + readSint64String(): string; + readFixed32(): number; + readFixed64(): number; + readFixed64String(): string; + readSfixed32(): number; + readSfixed32String(): string; + readSfixed64(): number; + readSfixed64String(): string; + readFloat(): number; + readDouble(): number; + readBool(): boolean; + readEnum(): number; + readString(): string; + readBytes(): Uint8Array; + readVarintHash64(): string; + readFixedHash64(): string; + readPackedInt32(): number[]; + readPackedInt32String(): string[]; + readPackedInt64(): number[]; + readPackedInt64String(): string[]; + readPackedUint32(): number[]; + readPackedUint32String(): string[]; + readPackedUint64(): number[]; + readPackedUint64String(): string[]; + readPackedSint32(): number[]; + readPackedSint64(): number[]; + readPackedSint64String(): string[]; + readPackedFixed32(): number[]; + readPackedFixed64(): number[]; + readPackedFixed64String(): string[]; + readPackedSfixed32(): number[]; + readPackedSfixed64(): number[]; + readPackedSfixed64String(): string[]; + readPackedFloat(): number[]; + readPackedDouble(): number[]; + readPackedBool(): boolean[]; + readPackedEnum(): number[]; + readPackedVarintHash64(): string[]; + readPackedFixedHash64(): string[]; +} + +export class BinaryWriter { + constructor(); + writeSerializedMessage(bytes: Uint8Array, + start: number, + end: number): void; + maybeWriteSerializedMessage(bytes?: Uint8Array, + start?: number, + end?: number): void; + reset(): void; + getResultBuffer(): Uint8Array; + getResultBase64String(): string; + beginSubMessage(field: number): void; + endSubMessage(field: number): void; + writeAny(fieldType: BinaryConstants.FieldType, + field: number, + value: AnyFieldType): void; + writeInt32(field: number, + value?: number): void; + writeInt32String(field: number, + value?: string): void; + writeInt64(field: number, + value?: number): void; + writeInt64String(field: number, + value?: string): void; + writeUint32(field: number, + value?: number): void; + writeUint32String(field: number, + value?: string): void; + writeUint64(field: number, + value?: number): void; + writeUint64String(field: number, + value?: string): void; + writeSint32(field: number, + value?: number): void; + writeSint64(field: number, + value?: number): void; + writeSint64String(field: number, + value?: string): void; + writeFixed32(field: number, + value?: number): void; + writeFixed64(field: number, + value?: number): void; + writeFixed64String(field: number, + value?: string): void; + writeSfixed32(field: number, + value?: number): void; + writeSfixed64(field: number, + value?: number): void; + writeSfixed64String(field: number, + value?: string): void; + writeFloat(field: number, + value?: number): void; + writeDouble(field: number, + value?: number): void; + writeBool(field: number, + value?: boolean): void; + writeEnum(field: number, + value?: number): void; + writeString(field: number, + value?: string): void; + writeBytes(field: number, + value?: ByteSource): void; + writeMessage: BinaryWrite; + writeGroup(field: number, + value: any, + writeCallback: BinaryWriteCallback): void; + writeFixedHash64(field: number, + value?: string): void; + writeVarintHash64(field: number, + value?: string): void; + writeRepeatedInt32(field: number, + value?: number[]): void; + writeRepeatedInt32String(field: number, + value?: string[]): void; + writeRepeatedInt64(field: number, + value?: number[]): void; + writeRepeatedInt64String(field: number, + value?: string[]): void; + writeRepeatedUint32(field: number, + value?: number[]): void; + writeRepeatedUint32String(field: number, + value?: string[]): void; + writeRepeatedUint64(field: number, + value?: number[]): void; + writeRepeatedUint64String(field: number, + value?: string[]): void; + writeRepeatedSint32(field: number, + value?: number[]): void; + writeRepeatedSint64(field: number, + value?: number[]): void; + writeRepeatedSint64String(field: number, + value?: string[]): void; + writeRepeatedFixed32(field: number, + value?: number[]): void; + writeRepeatedFixed64(field: number, + value?: number[]): void; + writeRepeatedFixed64String(field: number, + value?: string[]): void; + writeRepeatedSfixed32(field: number, + value?: number[]): void; + writeRepeatedSfixed64(field: number, + value?: number[]): void; + writeRepeatedSfixed64String(field: number, + value?: string[]): void; + writeRepeatedFloat(field: number, + value?: number[]): void; + writeRepeatedDouble(field: number, + value?: number[]): void; + writeRepeatedBool(field: number, + value?: boolean[]): void; + writeRepeatedEnum(field: number, + value?: number[]): void; + writeRepeatedString(field: number, + value?: string[]): void; + writeRepeatedBytes(field: number, + value?: ByteSource[]): void; + writeRepeatedMessage(field: number, + value: Message[], + writerCallback: BinaryWriteCallback): void; + writeRepeatedGroup(field: number, + value: Message[], + writerCallback: BinaryWriteCallback): void; + writeRepeatedFixedHash64(field: number, + value?: string[]): void; + writeRepeatedVarintHash64(field: number, + value?: string[]): void; + writePackedInt32(field: number, + value?: number[]): void; + writePackedInt32String(field: number, + value?: string[]): void; + writePackedInt64(field: number, + value?: number[]): void; + writePackedInt64String(field: number, + value?: string[]): void; + writePackedUint32(field: number, + value?: number[]): void; + writePackedUint32String(field: number, + value?: string[]): void; + writePackedUint64(field: number, + value?: number[]): void; + writePackedUint64String(field: number, + value?: string[]): void; + writePackedSint32(field: number, + value?: number[]): void; + writePackedSint64(field: number, + value?: number[]): void; + writePackedSint64String(field: number, + value?: string[]): void; + writePackedFixed32(field: number, + value?: number[]): void; + writePackedFixed64(field: number, + value?: number[]): void; + writePackedFixed64String(field: number, + value?: string[]): void; + writePackedSfixed32(field: number, + value?: number[]): void; + writePackedSfixed64(field: number, + value?: number[]): void; + writePackedSfixed64String(field: number, + value?: string[]): void; + writePackedFloat(field: number, + value?: number[]): void; + writePackedDouble(field: number, + value?: number[]): void; + writePackedBool(field: number, + value?: boolean[]): void; + writePackedEnum(field: number, + value?: number[]): void; + writePackedFixedHash64(field: number, + value?: string[]): void; + writePackedVarintHash64(field: number, + value?: string[]): void; +} + +export class BinaryEncoder { + constructor(); + length(): number; + end(): number[]; + writeSplitVarint64(lowBits: number, + highBits: number): void; + writeSplitFixed64(lowBits: number, + highBits: number): void; + writeUnsignedVarint32(value: number): void; + writeSignedVarint32(value: number): void; + writeUnsignedVarint64(value: number): void; + writeSignedVarint64(value: number): void; + writeZigzagVarint32(value: number): void; + writeZigzagVarint64(value: number): void; + writeZigzagVarint64String(value: string): void; + writeUint8(value: number): void; + writeUint16(value: number): void; + writeUint32(value: number): void; + writeUint64(value: number): void; + writeInt8(value: number): void; + writeInt16(value: number): void; + writeInt32(value: number): void; + writeInt64(value: number): void; + writeInt64String(value: string): void; + writeFloat(value: number): void; + writeDouble(value: number): void; + writeBool(value: boolean): void; + writeEnum(value: number): void; + writeBytes(bytes: Uint8Array): void; + writeVarintHash64(hash: string): void; + writeFixedHash64(hash: string): void; + writeString(value: string): number; +} + +export class BinaryDecoder { + constructor(bytes?: ByteSource, + start?: number, + length?: number) + static alloc(bytes?: ByteSource, + start?: number, + length?: number): BinaryDecoder; + free(): void; + clone(): BinaryDecoder; + clear(): void; + getBuffer(): Uint8Array; + setBlock(data: ByteSource, + start?: number, + length?: number): void; + getEnd(): number; + setEnd(end: number): void; + reset(): void; + getCursor(): number; + setCursor(cursor: number): void; + advance(count: number): void; + atEnd(): boolean; + pastEnd(): boolean; + getError(): boolean; + skipVarint(): void; + unskipVarint(value: number): void; + readUnsignedVarint32(): number; + readSignedVarint32(): number; + readUnsignedVarint32String(): number; + readSignedVarint32String(): number; + readZigzagVarint32(): number; + readUnsignedVarint64(): number; + readUnsignedVarint64String(): number; + readSignedVarint64(): number; + readSignedVarint64String(): number; + readZigzagVarint64(): number; + readZigzagVarint64String(): number; + readUint8(): number; + readUint16(): number; + readUint32(): number; + readUint64(): number; + readUint64String(): string; + readInt8(): number; + readInt16(): number; + readInt32(): number; + readInt64(): number; + readInt64String(): string; + readFloat(): number; + readDouble(): number; + readBool(): boolean; + readEnum(): number; + readString(length: number): string; + readStringWithLength(): string; + readBytes(length: number): Uint8Array; + readVarintHash64(): string; + readFixedHash64(): string; +} + +export class BinaryIterator { + constructor(decoder?: BinaryDecoder, + next?: () => number|boolean|string|null, + elements?: Array) + static alloc(decoder?: BinaryDecoder, + next?: () => number|boolean|string|null, + elements?: Array): BinaryIterator; + free(): void; + clear(): void; + get(): (ScalarFieldType | null); + atEnd(): boolean; + next(): (ScalarFieldType | null); +} + +export namespace BinaryConstants { + export enum FieldType { + INVALID = -1, + DOUBLE = 1, + FLOAT = 2, + INT64 = 3, + UINT64 = 4, + INT32 = 5, + FIXED64 = 6, + FIXED32 = 7, + BOOL = 8, + STRING = 9, + GROUP = 10, + MESSAGE = 11, + BYTES = 12, + UINT32 = 13, + ENUM = 14, + SFIXED32 = 15, + SFIXED64 = 16, + SINT32 = 17, + SINT64 = 18, + FHASH64 = 30, + VHASH64 = 31, + } + + export enum WireType { + INVALID = -1, + VARINT = 0, + FIXED64 = 1, + DELIMITED = 2, + START_GROUP = 3, + END_GROUP = 4, + FIXED32 = 5, + } + + const FieldTypeToWireType: (fieldType: FieldType) => WireType; + + const INVALID_FIELD_NUMBER: number; + const FLOAT32_EPS: number; + const FLOAT32_MIN: number; + const FLOAT32_MAX: number; + const FLOAT64_EPS: number; + const FLOAT64_MIN: number; + const FLOAT64_MAX: number; + const TWO_TO_20: number; + const TWO_TO_23: number; + const TWO_TO_31: number; + const TWO_TO_32: number; + const TWO_TO_52: number; + const TWO_TO_63: number; + const TWO_TO_64: number; + const ZERO_HASH: string; +} + +export namespace arith { + export class UInt64 { + lo: number; + hi: number; + constructor(lo: number, + hi: number); + cmp(other: UInt64): number; + rightShift(): UInt64; + leftShift(): UInt64; + msb(): boolean; + lsb(): boolean; + zero(): boolean; + add(other: UInt64): UInt64; + sub(other: UInt64): UInt64; + static mul32x32(a: number, + b: number): UInt64; + mul(a: number): UInt64; + div(divisor: number): [UInt64, UInt64]; + toString(): string; + static fromString(str: string): UInt64; + clone(): UInt64; + } + + export class Int64 { + lo: number; + hi: number; + constructor(lo: number, + hi: number); + add(other: Int64): Int64; + sub(other: Int64): Int64; + clone(): Int64; + toString(): string; + static fromString(str: string): Int64; + } +} + +// jspb.utils package excluded as it likely shouldn't be called by user code \ No newline at end of file diff --git a/google-protobuf/tsconfig.json b/google-protobuf/tsconfig.json new file mode 100644 index 0000000000..269fec20d9 --- /dev/null +++ b/google-protobuf/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "google-protobuf-tests.ts" + ] +} \ No newline at end of file diff --git a/google-protobuf/tslint.json b/google-protobuf/tslint.json new file mode 100644 index 0000000000..fdc7cdc370 --- /dev/null +++ b/google-protobuf/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} \ No newline at end of file diff --git a/google.analytics/google.analytics-tests.ts b/google.analytics/google.analytics-tests.ts index 6b7962899b..32df930cc9 100644 --- a/google.analytics/google.analytics-tests.ts +++ b/google.analytics/google.analytics-tests.ts @@ -1,5 +1,5 @@ - -/// +declare function describe(desc: string, fn: () => void): void; +declare function it(desc: string, fn: () => void): void; describe("tester Google Analytics Tracker _gat object", () => { it("can set ga script element", () => { diff --git a/google.fonts/google.fonts-tests.ts b/google.fonts/google.fonts-tests.ts new file mode 100644 index 0000000000..7d63cd77fd --- /dev/null +++ b/google.fonts/google.fonts-tests.ts @@ -0,0 +1,16 @@ +function test(list: google.fonts.WebfontList) { + + var f = list.items[0]; + + var info = [ + f.category, + f.family, + f.kind, + f.subsets.length, + f.version + ]; + + var urls = f.variants.map( + v => f.files[v] + ); +} diff --git a/google.fonts/index.d.ts b/google.fonts/index.d.ts new file mode 100644 index 0000000000..959447b198 --- /dev/null +++ b/google.fonts/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for Google Fonts API 1.0 +// Project: https://developers.google.com/fonts/ +// Definitions by: Dan Marshall +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace google.fonts { + + export interface WebfontList { + kind: string; + items: WebfontFamily[]; + } + + export interface WebfontFamily { + category?: string; + kind: string; + family: string; + subsets: string[]; + variants: string[]; + version: string; + lastModified: string; + files: { [variant: string]: string }; + } +} diff --git a/pixi-spine/tsconfig.json b/google.fonts/tsconfig.json similarity index 93% rename from pixi-spine/tsconfig.json rename to google.fonts/tsconfig.json index 8351a9fd60..2df5048a3b 100644 --- a/pixi-spine/tsconfig.json +++ b/google.fonts/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "pixi-spine-tests.ts" + "google.fonts-tests.ts" ] } \ No newline at end of file diff --git a/google.fonts/tslint.json b/google.fonts/tslint.json new file mode 100644 index 0000000000..fdc7cdc370 --- /dev/null +++ b/google.fonts/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} \ No newline at end of file diff --git a/googlemaps/index.d.ts b/googlemaps/index.d.ts index 06eba68a94..e8d6d8dc2b 100644 --- a/googlemaps/index.d.ts +++ b/googlemaps/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Google Maps JavaScript API 3.26 // Project: https://developers.google.com/maps/ -// Definitions by: Folia A/S , Chris Wrench , Kiarash Ghiaseddin , Grant Hutchins , Denis Atyasov +// Definitions by: Folia A/S , Chris Wrench , Kiarash Ghiaseddin , Grant Hutchins , Denis Atyasov , Michael McMullin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /* @@ -371,7 +371,7 @@ declare namespace google.maps { setControlPosition(controlPosition: ControlPosition): void; setControls(controls: string[]): void; setDrawingMode(drawingMode: string): void; - setMap(map: Map): void; + setMap(map: Map | null): void; setStyle(style: Data.StylingFunction|Data.StyleOptions): void; toGeoJson(callback: (feature: Object) => void): void; } @@ -835,7 +835,7 @@ declare namespace google.maps { getVisible(): boolean; setDraggable(draggable: boolean): void; setEditable(editable: boolean): void; - setMap(map: Map): void; + setMap(map: Map | null): void; setOptions(options: PolylineOptions): void; setPath(path: MVCArray|LatLng[]|LatLngLiteral[]): void; // MVCArray|Array setVisible(visible: boolean): void; @@ -873,7 +873,7 @@ declare namespace google.maps { getVisible(): boolean; setDraggable(draggable: boolean): void; setEditable(editable: boolean): void; - setMap(map: Map): void; + setMap(map: Map | null): void; setOptions(options: PolygonOptions): void; setPath(path: MVCArray|LatLng[]|LatLngLiteral[]): void; setPaths(paths: MVCArray): void; @@ -959,7 +959,7 @@ declare namespace google.maps { setBounds(bounds: LatLngBounds|LatLngBoundsLiteral): void; setDraggable(draggable: boolean): void; setEditable(editable: boolean): void; - setMap(map: Map): void; + setMap(map: Map | null): void; setOptions(options: RectangleOptions): void; setVisible(visible: boolean): void; } @@ -992,7 +992,7 @@ declare namespace google.maps { setCenter(center: LatLng|LatLngLiteral): void; setDraggable(draggable: boolean): void; setEditable(editable: boolean): void; - setMap(map: Map): void; + setMap(map: Map | null): void; setOptions(options: CircleOptions): void; setRadius(radius: number): void; setVisible(visible: boolean): void; @@ -1036,7 +1036,7 @@ declare namespace google.maps { getMap(): Map; getOpacity(): number; getUrl(): string; - setMap(map: Map): void; + setMap(map: Map | null): void; setOpacity(opacity: number): void; } @@ -1053,7 +1053,7 @@ declare namespace google.maps { getProjection(): MapCanvasProjection; onAdd(): void; onRemove(): void; - setMap(map: Map|StreetViewPanorama): void; + setMap(map: Map | StreetViewPanorama | null): void; } export interface MapPanes { @@ -1144,7 +1144,7 @@ declare namespace google.maps { getPanel(): Element; getRouteIndex(): number; setDirections(directions: DirectionsResult): void; - setMap(map: Map): void; + setMap(map: Map | null): void; setOptions(options: DirectionsRendererOptions): void; setPanel(panel: Element): void; setRouteIndex(routeIndex: number): void; @@ -1624,13 +1624,13 @@ declare namespace google.maps { export class BicyclingLayer extends MVCObject { constructor(); getMap(): Map; - setMap(map: Map): void; + setMap(map: Map | null): void; } export class FusionTablesLayer extends MVCObject { constructor(options: FusionTablesLayerOptions); getMap(): Map; - setMap(map: Map): void; + setMap(map: Map | null): void; setOptions(options: FusionTablesLayerOptions): void; } @@ -1701,7 +1701,7 @@ declare namespace google.maps { getStatus(): KmlLayerStatus; getUrl(): string; getZIndex(): number; - setMap(map: Map): void; + setMap(map: Map | null): void; setUrl(url: string): void; setZIndez(zIndex: number): void; } @@ -1760,7 +1760,7 @@ declare namespace google.maps { export class TrafficLayer extends MVCObject { constructor(opts?: TrafficLayerOptions); getMap(): Map; - setMap(map: Map): void; + setMap(map: Map | null): void; setOptions(options: TrafficLayerOptions): void; } @@ -1772,7 +1772,7 @@ declare namespace google.maps { export class TransitLayer extends MVCObject { constructor(); getMap(): void; - setMap(map: Map): void; + setMap(map: Map | null): void; } /***** Street View *****/ @@ -1904,7 +1904,7 @@ declare namespace google.maps { export class StreetViewCoverageLayer extends MVCObject { getMap(): Map; - setMap(map: Map): void; + setMap(map: Map | null): void; } /***** Events *****/ @@ -2155,7 +2155,7 @@ declare namespace google.maps { setBorderColor(borderColor: string): void; setChannelNumber(channelNumber: string): void; setFormat(format: AdFormat): void; - setMap(map: Map): void; + setMap(map: Map | null): void; setPosition(position: ControlPosition): void; setTextColor(textColor: string): void; setTitleColor(titleColor: string): void; @@ -2211,6 +2211,8 @@ declare namespace google.maps { export interface AutocompleteOptions { bounds?: LatLngBounds|LatLngBoundsLiteral; componentRestrictions?: ComponentRestrictions; + placeIdOnly?: boolean; + strictBounds?: boolean; types?: string[]; } @@ -2222,6 +2224,22 @@ declare namespace google.maps { types: string[]; } + export interface OpeningHours { + open_now: boolean, + periods: OpeningPeriod[], + weekday_text: string[] + } + + export interface OpeningPeriod { + open: OpeningHoursTime, + close?: OpeningHoursTime + } + + export interface OpeningHoursTime { + day: number, + time: string + } + export interface PredictionTerm { offset: number; value: string; @@ -2288,6 +2306,7 @@ declare namespace google.maps { icon: string; international_phone_number: string; name: string; + opening_hours: OpeningHours; permanently_closed: boolean; photos: PlacePhoto[]; place_id: string; @@ -2402,7 +2421,7 @@ declare namespace google.maps { getDrawingMode(): OverlayType; getMap(): Map; setDrawingMode(drawingMode: OverlayType): void; - setMap(map: Map): void; + setMap(map: Map | null): void; setOptions(options: DrawingManagerOptions): void; } @@ -2451,7 +2470,7 @@ declare namespace google.maps { getZIndex(): number; setLayerId(layerId: string): void; setLayerKey(layerKey: string): void; - setMap(map: Map): void; + setMap(map: Map | null): void; setMapId(mapId: string): void; setOpacity(opacity: number): void; setOptions(options: MapsEngineLayerOptions): void; @@ -2495,7 +2514,7 @@ declare namespace google.maps { setData(data: MVCArray): void; setData(data: LatLng[]): void; setData(data: WeightedLocation[]): void; - setMap(map: Map): void; + setMap(map: Map | null): void; } export interface HeatmapLayerOptions { diff --git a/graphite-udp/graphite-udp-tests.ts b/graphite-udp/graphite-udp-tests.ts new file mode 100644 index 0000000000..c61ad172cd --- /dev/null +++ b/graphite-udp/graphite-udp-tests.ts @@ -0,0 +1,43 @@ +import graphite = require('graphite-udp'); + +// Test creation of client directly. +let client = new graphite.Client(); +client.put('test', 1); +client.add('test', 1); +client.close(); + +// Create client with helper +let client2 = graphite.createClient(); +client2.put('test2', 1); +client2.add('test2', 1); +client2.close(); + +// Test creation with options. +graphite.createClient({ + host: '127.0.0.1', + port: 2003, + type: 'udp4', + maxPacketSize: 4096, + prefix: 'prefix', + suffix: 'suffix', + interval: 60 * 1000, + verbose: true, + callback: (error: Error, metrics: any): void => { + + } +}); + +// Test creation options with class directly. +new graphite.Client({ + host: '127.0.0.1', + port: 2003, + type: 'udp4', + maxPacketSize: 4096, + prefix: 'prefix', + suffix: 'suffix', + interval: 60 * 1000, + verbose: true, + callback: (error: Error, metrics: any): void => { + + } +}); diff --git a/graphite-udp/index.d.ts b/graphite-udp/index.d.ts new file mode 100644 index 0000000000..218888b39a --- /dev/null +++ b/graphite-udp/index.d.ts @@ -0,0 +1,97 @@ +// Type definitions for graphite-udp 1.2 +// Project: https://github.com/fermads/graphite-udp +// Definitions by: Eric Byers +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +interface ClientOptions { + /** + * graphite server host or ip + * Defaults to 127.0.0.1 + */ + host?: string; + + /** + * graphite server udp port + * Defaults to 2003 + */ + port?: number; + + /** + * udp type (udp4 or udp6) + * Defaults to udp4 + */ + type?: 'udp4' | 'udp6'; + + /** + * split into smaller UDP packets + * Defaults to 4096 + */ + maxPacketSize?: number; + + /** + * Prefix for each metric name + * Defaults to '' + */ + prefix?: string; + + /** + * Suffix for each metrtic name + * Defaults to '' + */ + suffix?: string; + + /** + * Interval to group metrics by in milliseconds + * Defaults to 5000 (5s) + */ + interval?: number; + + /** + * log messages to console + * Defaults to false + */ + verbose?: boolean; + + /** + * called when metrics are sent + * Defaults to null + * + * @param {error} Error + * @param {metrics} + * @return void + */ + callback?: (error: Error, metrics: any) => void; +} + +export class Client { + + constructor(clientOptions?: ClientOptions); + + /** + * During the interval time option, if 2 or more metrics with the same name are sent, metrics will be added (summed) + * + * @param {name} + * @param {value} number + * @return void + */ + add(name: string, value: number): void; + + /** + * During the interval time option, if 2 or more metrics with the same name are sent, the last one will be used + * + * @param {name} metric name (my.test.metric) + * @param {value} number + * @return void + */ + put(name: string, value: number): void; + + /** + * Close the underlying UDP client socket + * + * @return void + */ + close(): void; +} + +export function createClient(clientOptions?: ClientOptions): Client; diff --git a/graphite-udp/tsconfig.json b/graphite-udp/tsconfig.json new file mode 100644 index 0000000000..50f3e17459 --- /dev/null +++ b/graphite-udp/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "graphite-udp-tests.ts" + ] +} diff --git a/graphite-udp/tslint.json b/graphite-udp/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/graphite-udp/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/greensock/index.d.ts b/greensock/index.d.ts deleted file mode 100644 index 65f7ee52e7..0000000000 --- a/greensock/index.d.ts +++ /dev/null @@ -1,352 +0,0 @@ -// Type definitions for GreenSock Animation Platform 1.15.1 -// Project: http://www.greensock.com/get-started-js/ -// Definitions by: Robert S -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -// JavaScript Docs http://api.greensock.com/js/ -// Version 1.15.1 (TypeScript 1.4) - -interface IDispatcher { - addEventListener(type:string, callback:Function, scope?:Object, useParam?:boolean, priority?:number):void; - removeEventListener(type:string, callback:Function):void; -} - -declare type Tween = TweenLite | TweenMax; -declare type Timeline = SimpleTimeline | TimelineLite | TimelineMax; -declare type TweenConfig = { - [tweenProp: string]: any; - delay?: number; - ease?: Ease; - repeat?: number; - repeatDelay?: number; - yoyo?: boolean; - paused?: boolean; - overwrite?: string|number; - onComplete?: Function; - immediateRender?: boolean; - onCompleteParams?: any[]; - onCompleteScope?: Object; - onRepeat?: Function; - onRepeatScope?: Object; - onReverseComplete?: Function; - onReverseCompleteParams?: any[]; - onReverseCompleteScope?: Object; - onStart?: Function; - onStartParams?: any[]; - onStartScope?: Object; - onUpdate?: Function; - onUpdateParams?: any[]; - onUpdateScope?: Object; - startAt?: Object; - useFrames?: boolean; - lazy?: boolean; - onOverwrite?: Function; - autoCSS?: boolean; - callbackScope?: Object; -} - -//com.greensock.core -declare class Animation { - static ticker: IDispatcher; - data: any; - timeline: SimpleTimeline; - vars: Object; - - constructor(duration?: number, vars?: Object); - - delay(): number; - delay(value: number): Animation; - duration(): number; - duration(value: number): Animation; - eventCallback(type: string): Function; - eventCallback(type: string, callback: Function, params?: any[], scope?: any): Animation; - invalidate(): Animation; - isActive(): boolean; - kill(vars?: Object, target?: Object): Animation; - pause(atTime?: any, suppressEvents?: boolean): Animation; - paused(): boolean; - paused(value: boolean): Animation; - play(from?: any, suppressEvents?: boolean): Animation; - progress(): number; - progress(value: number, supressEvents?: boolean): Animation; - restart(includeDelay?: boolean, suppressEvents?: boolean): Animation; - resume(from?: any, suppressEvents?: boolean): Animation; - reverse(from?: any, suppressEvents?: boolean): Animation; - reversed(): boolean; - reversed(value: boolean): Animation; - seek(time: any, suppressEvents?: boolean): Animation; - startTime(): number; - startTime(value: number): Animation; - time(): number; - time(value: number, suppressEvents?: boolean): Animation; - timeScale(): number; - timeScale(value: number): Animation; - totalDuration(): number; - totalDuration(value: number): Animation; - totalProgress(): number; - totalProgress(value: number): Animation; - totalTime(): number; - totalTime(time: number, suppressEvents?: boolean): Animation; -} - -declare class SimpleTimeline extends Animation { - autoRemoveChildren: boolean; - smoothChildTiming: boolean; - - constructor(vars?: Object); - - add(value: any, position?: any, align?: string, stagger?: number): SimpleTimeline; - render(time: number, suppressEvents?: boolean, force?: boolean): void; -} - -//com.greensock -declare class TweenLite extends Animation { - static defaultEase: Ease; - static defaultOverwrite: string; - static selector: any; - target: Object; - - constructor(target: Object, duration: number, vars: Object); - - static delayedCall(delay: number, callback: Function, params?: any[], scope?: any, useFrames?: boolean): TweenLite; - endTime(includeRepeats?: boolean): number; - static from(target: Object | Object[], duration: number, vars: Object): TweenLite; - static fromTo(target: Object | Object[], duration: number, fromVars: Object, toVars: Object): TweenLite; - static getTweensOf(target: Object, onlyActive: boolean): Tween[]; - static killDelayedCallsTo(func: Function): void; - static killTweensOf(target: Object, onlyActive?: boolean, vars?: Object): void; - static lagSmoothing(threshold: number, adjustedLag: number): void; - static set(target: Object, vars: Object): TweenLite; - static to(target: Object, duration: number, vars: TweenConfig): TweenLite; -} - -declare class TweenMax extends TweenLite { - constructor(target: Object, duration: number, vars: Object); - - static delayedCall(delay: number, callback: Function, params?: any[], scope?: Object, useFrames?: boolean): TweenMax; - static from(target: Object, duration: number, vars: Object): TweenMax; - static fromTo(target: Object, duration: number, fromVars: Object, toVars: Object): TweenMax; - static getAllTweens(includeTimelines?: boolean): Tween[]; - static getTweensOf(target: Object): Tween[]; - static isTweening(target: Object): boolean; - static killAll(complete?: boolean, tweens?: boolean, delayedCalls?: boolean, timelines?: boolean): void; - static killChildTweensOf(parent: any, complete?: boolean): void; - static killDelayedCallsTo(func: Function): void; - static killTweensOf(target: Object, vars?: Object): void; - static pauseAll(tweens?: boolean, delayedCalls?: boolean, timelines?: boolean): void; - repeat(): number; - repeat(value: number): TweenMax; - repeatDelay(): number; - repeatDelay(value: number): TweenMax; - static resumeAll(tweens?: boolean, delayedCalls?: boolean, timelines?: boolean): void; - static set(target: Object, vars: Object): TweenMax; - static staggerFrom(targets: any, duration: number, vars: Object, stagger: number, onCompleteAll?: Function, onCompleteAllParams?: any[], onCompleteAllScope?: any): any[]; - static staggerFromTo(targets: any, duration: number, fromVars: Object, toVars: Object, stagger: number, onCompleteAll?: Function, onCompleteAllParams?: any[], onCompleteAllScope?: any): any[]; - static staggerTo(targets: any, duration: number, vars: Object, stagger: number, onCompleteAll?: Function, onCompleteAllParams?: any[], onCompleteAllScope?: any): any[]; - static to(target:Object, duration:number, vars:TweenConfig):TweenMax; - updateTo(vars: Object, resetDuration?: boolean): TweenMax; - yoyo(): boolean; - yoyo(value?: boolean): TweenMax; -} - -declare class TimelineLite extends SimpleTimeline { - constructor(vars?: Object); - - add(value: any, position?: any, align?: string, stagger?: number): TimelineLite; - addLabel(label: string, position: any): TimelineLite; - addPause(position?: any, callback?: Function, params?: any[], scope?: any): TimelineLite; - call(callback: Function, params?: any[], scope?: any, position?: any): TimelineLite; - clear(labels?: boolean): TimelineLite; - endTime(includeRepeats?: boolean): number; - static exportRoot(vars?: Object, omitDelayedCalls?: boolean): TimelineLite; - from(target: Object, duration: number, vars: Object, position?: any): TimelineLite; - fromTo(target: Object, duration: number, fromVars: Object, toVars: Object, position?: any): TimelineLite; - getChildren(nested?: boolean, tweens?: boolean, timelines?: boolean, ignoreBeforeTime?: number): (Tween | Timeline)[]; - getLabelTime(label: string): number; - getTweensOf(target: Object, nested?: boolean): Tween[]; - recent(): Animation; - remove(value: any): TimelineLite; - removeLabel(label: string): any; - set(target: Object, vars: Object, position?: any): TimelineLite; - shiftChildren(amount: number, adjustLabels?: boolean, ignoreBeforeTime?: number): TimelineLite; - staggerFrom(targets: any, duration: number, vars: Object, stagger?: number, position?: any, onCompleteAll?: Function, onCompleteAllParams?: any[], onCompleteScope?: any): TimelineLite; - staggerFromTo(targets: any, duration: number, fromVars: Object, toVars: Object, stagger?: number, position?: any, onCompleteAll?: Function, onCompleteAllParams?: any[], onCompleteAllScope?: any): TimelineLite; - staggerTo(targets: any, duration: number, vars: Object, stagger: number, position?: any, onCompleteAll?: Function, onCompleteAllParams?: any[], onCompleteAllScope?: any): TimelineLite; - to(target: Object, duration: number, vars: Object, position?: any): TimelineLite; - usesFrames(): boolean; -} - -declare class TimelineMax extends TimelineLite { - constructor(vars?: Object); - - addCallback(callback: Function, position: any, params?: any[], scope?: any): TimelineMax; - currentLabel(): string; - currentLabel(value: string): TimelineMax; - getActive(nested?: boolean, tweens?: boolean, timelines?: boolean): Tween | Timeline[]; - getLabelAfter(time: number): string; - getLabelBefore(time: number): string; - getLabelsArray(): {name: string; time: number;}[]; - removeCallback(callback: Function, timeOrLabel?: any): TimelineMax; - removePause(position: any): TimelineMax; - repeat(): number; - repeat(value: number): TimelineMax; - repeatDelay(): number; - repeatDelay(value: number): TimelineMax; - tweenFromTo(fromPosition: any, toPosition: any, vars?: Object): TweenLite; - tweenTo(position: any, vars?: Object): TweenLite; - yoyo(): boolean; - yoyo(value: boolean): TimelineMax; -} - -//com.greensock.easing -declare class Ease { - constructor(func:Function, extraParams:any[], type:number, power:number); - public getRatio(p: number): number; -} - -declare class EaseLookup { - public static find(name: string): Ease; -} - -declare class Back extends Ease { - public static easeIn: Back; - public static easeInOut: Back; - public static easeOut: Back; - public config(overshoot: number): Elastic; - -} -declare class Bounce extends Ease { - public static easeIn: Bounce; - public static easeInOut: Bounce; - public static easeOut: Bounce; -} -declare class Circ extends Ease { - public static easeIn: Circ; - public static easeInOut: Circ; - public static easeOut: Circ; -} -declare class Cubic extends Ease { - public static easeIn: Cubic; - public static easeInOut: Cubic; - public static easeOut: Cubic; -} - -declare class Elastic extends Ease { - public static easeIn: Elastic; - public static easeInOut: Elastic; - public static easeOut: Elastic; - public config(amplitude: number, period: number): Elastic; -} - -declare class Expo extends Ease { - public static easeIn: Expo; - public static easeInOut: Expo; - public static easeOut: Expo; -} - -declare class Linear extends Ease { - public static ease: Linear; - public static easeIn: Linear; - public static easeInOut: Linear; - public static easeNone: Linear; - public static easeOut: Linear; -} - -declare class Quad extends Ease { - public static easeIn: Quad; - public static easeInOut: Quad; - public static easeOut: Quad; -} - -declare class Quart extends Ease { - public static easeIn: Quart; - public static easeInOut: Quart; - public static easeOut: Quart; -} - -declare class Quint extends Ease { - public static easeIn: Quint; - public static easeInOut: Quint; - public static easeOut: Quint; -} - -declare class Sine extends Ease { - public static easeIn: Sine; - public static easeInOut: Sine; - public static easeOut: Sine; -} - -declare class SlowMo extends Ease { - public static ease: SlowMo; - public config(linearRatio: number, power: number, yoyoMode: boolean): SlowMo; -} - -declare class SteppedEase extends Ease { - constructor(staps: number); - public config(steps: number): SteppedEase; -} - -declare type RoughEaseConfig = { - clamp?: boolean; - points?: number; - randomize?: boolean; - strength?: number; - taper?: string; /* one of "in" | "out" | "both" | "none" */ - template?: Ease; -} - -declare class RoughEase extends Ease { - public static ease: RoughEase; - constructor(vars: RoughEaseConfig); - public config(steps: number): SteppedEase; -} - -//com.greensock.plugins -interface BezierPlugin extends TweenPlugin { - bezierThrough(values:any[], curviness?:number, quadratic?:boolean, correlate?:string, prepend?:Object, calcDifs?:boolean):Object; - cubicToQuadratic(a:number, b:number, c:number, d:number):any[]; - quadraticToCubic(a:number, b:number, c:number):Object; -} -interface ColorPropsPlugin extends TweenPlugin { - -} -interface CSSPlugin extends TweenPlugin { - -} -interface CSSRulePlugin extends TweenPlugin { - getRule(selector:string):Object; -} -interface EaselPlugin extends TweenPlugin { - -} -interface RaphaelPlugin extends TweenPlugin { - -} -interface RoundPropsPlugin extends TweenPlugin { - -} -interface ScrollToPlugin extends TweenPlugin { - -} -interface TweenPlugin { - activate(plugins:any[]):boolean; -} - -//com.greensock.easing -declare var Power0: typeof Linear; -declare var Power1: typeof Quad; -declare var Power2: typeof Cubic; -declare var Power3: typeof Quart; -declare var Power4: typeof Quint; -declare var Strong: typeof Quint; - -//com.greensock.plugins -declare var BezierPlugin:BezierPlugin; -declare var ColorPropsPlugin:ColorPropsPlugin; -declare var CSSPlugin:CSSPlugin; -declare var CSSRulePlugin:CSSRulePlugin; -declare var EaselPlugin:EaselPlugin; -declare var RaphaelPlugin:RaphaelPlugin; -declare var RoundPropsPlugin:RoundPropsPlugin; -declare var ScrollToPlugin:ScrollToPlugin; -declare var TweenPlugin:TweenPlugin; diff --git a/gregorian-calendar/gregorian-calendar-tests.ts b/gregorian-calendar/gregorian-calendar-tests.ts index a7b11cf21d..096933ed2b 100644 --- a/gregorian-calendar/gregorian-calendar-tests.ts +++ b/gregorian-calendar/gregorian-calendar-tests.ts @@ -1,9 +1,6 @@ -/// - import GregorianCalendar = require('gregorian-calendar'); import GregorianCalendarFormat = require('gregorian-calendar-format'); - let cal = new GregorianCalendar(); cal.set(2016, 7, 27, 0, 0, 0, 0); diff --git a/griddle-react/griddle-react-tests.tsx b/griddle-react/griddle-react-tests.tsx new file mode 100644 index 0000000000..5f241feeb5 --- /dev/null +++ b/griddle-react/griddle-react-tests.tsx @@ -0,0 +1,78 @@ +/* +Licensed under the MIT License (MIT) + +Copyright (c) 2016 David Hara +*/ + +import * as React from 'react'; +import { render } from 'react-dom'; +import Griddle, { CustomColumnComponentProps } from 'griddle-react'; +import CustomColumnComponentGrid from './test/CustomColumnComponent'; +import CustomHeaderComponentGrid from './test/CustomHeaderComponent'; +import CustomFilterComponentGrid from './test/CustomFilterComponent'; + +interface MyCustomResult { + name: string, + test: string +} + +class LinkComponent extends React.Component, any> { + render() { + var url = "speakers/" + this.props.rowData.test + "/" + this.props.data; + return {this.props.data} + } +} + +const StatelessFunctionComponent = (props: CustomColumnComponentProps) => { + var url = "speakers/" + props.rowData.test + "/" + props.data; + return {props.data} +}; + +var columnMeta = [ + { + columnName: "name", + order: 1, + locked: false, + visible: true, + customComponent: StatelessFunctionComponent + }]; + +var results: MyCustomResult[] = [ + { + name: 'David Hara', + test: 'blah' + }, + { + name: 'Hara, David', + test: 'blah2' + } +]; + +var rowMetaData = { + bodyCssClassName: (rowData: MyCustomResult) => { + return rowData.test; + } +}; + +type TypedGriddle = new () => Griddle; +const TypedGriddle = Griddle as TypedGriddle; + +render( +

    +

    Custom Column Component Grid

    + +

    Custom Header Component Grid

    + +

    Custom Filter Component Grid

    + + } + sortDescendingComponent={} + customRowComponent={LinkComponent} + /> +
    , + document.getElementById('root') +); diff --git a/griddle-react/index.d.ts b/griddle-react/index.d.ts new file mode 100644 index 0000000000..e5d3e560bb --- /dev/null +++ b/griddle-react/index.d.ts @@ -0,0 +1,170 @@ +// Type definitions for griddle-react 0.7 +// Project: https://github.com/griddlegriddle/griddle +// Definitions by: David Hara +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/* +The MIT License (MIT) + +Copyright (c) 2016 David Hara + +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. +*/ + +import * as React from 'react'; + +type ReactClass = React.ComponentClass | React.StatelessComponent + +export interface CustomColumnComponentProps { + data: any; + rowData: T; + metaData: ColumnMetaData; +} + +export interface CustomRowComponentProps { + data: T; +} + +export interface CustomGridComponentProps { + data: T[]; +} + +export interface CustomPagerComponentProps { + currentPage: number; + maxPage: number; + nextText: string; + previousText: string; + next(): void; + previous(): void; + setPage(number: number): void; +} + +export interface CustomHeaderComponentProps { + filterByColumn?(filter: string, columnName: string): void; + columnName: string; + displayName: string; +} + +export interface CustomFilterComponentProps { + placeholderText?: string; + changeFilter(val: any): void; +} + +export interface ColumnMetaData { + columnName: string; + cssClassName?: string; + customComponent?: ReactClass>; + customHeaderComponent?: ReactClass; + customHeaderComponentProps?: {}; + displayName?: string; + locked?: boolean; + order?: number; + sortable?: boolean; + visible?: boolean; +} + +export interface BodyCssClassNameFunction { + (rowData: T): string; +} + +export interface RowMetaData { + bodyCssClassName?: BodyCssClassNameFunction | string; +} + +export interface GriddleProps { + columns?: string[]; + columnMetadata?: ColumnMetaData[]; + rowMetadata?: RowMetaData; + results?: T[]; + resultsPerPage?: number; + initialSort?: string; + initialSortAscending?: boolean; + gridClassName?: string; + tableClassName?: string; + customFormatClassName?: string; + settingsText?: string; + filterPlaceholderText?: string; + nextText?: string; + previousText?: string; + maxRowsText?: string; + enableCustomFormatText?: string; + childrenColumnName?: string; + metadataColumns?: string[]; + showFilter?: boolean; + showSettings?: boolean; + useCustomRowComponent?: boolean; + useCustomGridComponent?: boolean; + useCustomPagerComponent?: boolean; + useCustomFilterer?: boolean; + useCustomFilterComponent?: boolean; + useGriddleStyles?: boolean; + customRowComponent?: ReactClass> + customGridComponent?: ReactClass> + customPagerComponent?: ReactClass + customFilterComponent?: ReactClass + customFilterer?(items: T[], query: any): T[]; + enableToggleCustom?: boolean; + noDataMessage?: string; + noDataClassName?: string; + customNoDataComponent?: ReactClass + showTableHeading?: boolean; + showPager?: boolean; + useFixedHeader?: boolean; + useExternal?: boolean; + externalSetPage?(index: number): void; + externalChangeSort?(sort: string, sortAscending: boolean): void; + externalSetFilter?(filter: string): void; + externalSetPageSize?(size: number): void; + externalMaxPage?: number; + externalCurrentPage?: number; + externalSortColumn?: string; + externalSortAscending?: boolean; + externalLoadingComponent?: ReactClass + externalIsLoading?: boolean; + enableInfiniteScroll?: boolean; + bodyHeight?: number; + paddingHeight?: number; + rowHeight?: number; + infiniteScrollLoadTreshold?: number; + useFixedLayout?: boolean; + isSubGriddle?: boolean; + enableSort?: boolean; + sortAscendingClassName?: string; + sortDescendingClassName?: string; + parentRowCollapsedClassName?: string; + parentRowExpandedClassName?: string; + settingsToggleClassName?: string; + nextClassName?: string; + previousClassName?: string; + sortAscendingComponent?: string | React.ReactElement; + sortDescendingComponent?: string | React.ReactElement; + sortDefaultComponent?: string | React.ReactElement; + parentRowCollapsedComponent?: string | React.ReactElement; + parentRowExpandedComponent?: string | React.ReactElement; + settingsIconComponent?: string | React.ReactElement; + nextIconComponent?: string | React.ReactElement; + previousIconComponent?: string | React.ReactElement; + onRowClick?(): void; +} + +declare class Griddle extends React.Component, any> { +} + +export default Griddle; diff --git a/griddle-react/test/CustomColumnComponent.tsx b/griddle-react/test/CustomColumnComponent.tsx new file mode 100644 index 0000000000..83adc8f05a --- /dev/null +++ b/griddle-react/test/CustomColumnComponent.tsx @@ -0,0 +1,70 @@ +/* +Licensed under the MIT License (MIT) + +Copyright (c) 2016 David Hara +*/ + +import * as React from 'react'; +import Griddle, { CustomColumnComponentProps } from 'griddle-react'; + +interface MyCustomResult { + name: string, + test: string +} + +class LinkComponent extends React.Component, any> { + render() { + var url = "speakers/" + this.props.rowData.test + "/" + this.props.data; + return {this.props.data} + } +} + +const StatelessFunctionComponent = (props: CustomColumnComponentProps) => { + var url = "speakers/" + props.rowData.test + "/" + props.data; + return {props.data} +}; + +var columnMeta = [ + { + columnName: "name", + order: 1, + locked: false, + visible: true, + customComponent: StatelessFunctionComponent + }]; + +var results: MyCustomResult[] = [ + { + name: 'David Hara', + test: 'blah' + }, + { + name: 'Hara, David', + test: 'blah2' + } +]; + +var rowMetaData = { + bodyCssClassName: (rowData: MyCustomResult) => { + return rowData.test; + } +}; + +class CustomColumnComponentGrid extends React.Component { + render() { + type TypedGriddle = new () => Griddle; + const TypedGriddle = Griddle as TypedGriddle; + + return ( + } + sortDescendingComponent={} + customRowComponent={LinkComponent} /> + ); + }; +} + +export default CustomColumnComponentGrid; \ No newline at end of file diff --git a/griddle-react/test/CustomFilterComponent.tsx b/griddle-react/test/CustomFilterComponent.tsx new file mode 100644 index 0000000000..e7508887f5 --- /dev/null +++ b/griddle-react/test/CustomFilterComponent.tsx @@ -0,0 +1,91 @@ +/* +Licensed under the MIT License (MIT) + +Copyright (c) 2016 David Hara +*/ + +import * as _ from 'lodash'; +import * as React from 'react'; +import Griddle, { CustomFilterComponentProps } from 'griddle-react'; + +const CustomFilterFunction = (items: ResultType[], query: string): ResultType[] => { + return _.filter(items, (item) => { + + let match = false; + _.forIn(item, (value, key) => { + if (String(value).toLowerCase().indexOf(query.toLowerCase()) >= 0) { + match = true; + return; + } + }); + + return match; + }); +}; + +class CustomFilterComponent extends React.Component { + query: string = ''; + + searchChange(event: React.FormEvent) { + this.query = event.currentTarget.value; + this.props.changeFilter(this.query); + } + + render() { + return ( +
    + +
    + ); + } +} + +interface ResultType { + id: number; + name: string; + city: string; + state: string; + country: string; + company: string; + favoriteNumber: number; +} + +var someData: ResultType[] = [ + { + "id": 0, + "name": "Mayer Leonard", + "city": "Kapowsin", + "state": "Hawaii", + "country": "United Kingdom", + "company": "Ovolo", + "favoriteNumber": 7 + }, + { + "id": 1, + "name": "Koch Becker", + "city": "Johnsonburg", + "state": "New Jersey", + "country": "Madagascar", + "company": "Eventage", + "favoriteNumber": 2 + } +]; + +class CustomFilterComponentGrid extends React.Component { + render() { + + type TypedGriddle = new () => Griddle; + const TypedGriddle = Griddle as TypedGriddle; + + return ( + + ); + } +} + +export default CustomFilterComponentGrid; diff --git a/griddle-react/test/CustomHeaderComponent.tsx b/griddle-react/test/CustomHeaderComponent.tsx new file mode 100644 index 0000000000..aed7d348aa --- /dev/null +++ b/griddle-react/test/CustomHeaderComponent.tsx @@ -0,0 +1,95 @@ +/* +Licensed under the MIT License (MIT) + +Copyright (c) 2016 David Hara +*/ + +import * as React from 'react'; +import Griddle, { ColumnMetaData, CustomHeaderComponentProps } from 'griddle-react'; + +interface MoreCustomHeaderComponentProps extends CustomHeaderComponentProps { + color: string; +} + +class HeaderComponent extends React.Component { + textOnClick(e: React.FormEvent) { + e.stopPropagation(); + } + + filterText(e: React.FormEvent) { + this.props.filterByColumn(e.currentTarget.value, this.props.columnName) + } + + render() { + return ( + +
    {this.props.displayName}
    + +
    + ); + } +} + +interface ResultType { + id: number; + name: string; + city: string; + state: string; + country: string; + company: string; + favoriteNumber: number; +} + +var someData: ResultType[] = [ + { + "id": 0, + "name": "Mayer Leonard", + "city": "Kapowsin", + "state": "Hawaii", + "country": "United Kingdom", + "company": "Ovolo", + "favoriteNumber": 7 + }, + { + "id": 1, + "name": "Koch Becker", + "city": "Johnsonburg", + "state": "New Jersey", + "country": "Madagascar", + "company": "Eventage", + "favoriteNumber": 2 + } +]; + +var columnMeta: ColumnMetaData[] = [ + { + columnName: 'name', + order: 1, + sortable: false, + visible: true, + }, + { + columnName: 'city', + customHeaderComponent: HeaderComponent, + customHeaderComponentProps: {color: 'red'} + }, + { + columnName: 'state', + customHeaderComponent: HeaderComponent, + customHeaderComponentProps: {color: 'blue'} + } +]; + +class CustomHeaderComponentGrid extends React.Component { + render() { + + type TypedGriddle = new () => Griddle; + const TypedGriddle = Griddle as TypedGriddle; + + return ( + + ); + } +} + +export default CustomHeaderComponentGrid; diff --git a/griddle-react/tsconfig.json b/griddle-react/tsconfig.json new file mode 100644 index 0000000000..5dd6f9d98b --- /dev/null +++ b/griddle-react/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "jsx": "preserve", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "griddle-react-tests.tsx", + "test/CustomColumnComponent.tsx", + "test/CustomFilterComponent.tsx", + "test/CustomHeaderComponent.tsx" + ] +} diff --git a/griddle-react/tslint.json b/griddle-react/tslint.json new file mode 100644 index 0000000000..f9e30021f4 --- /dev/null +++ b/griddle-react/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} diff --git a/gridfs-stream/gridfs-stream-tests.ts b/gridfs-stream/gridfs-stream-tests.ts index 1ed4e97006..8086245722 100644 --- a/gridfs-stream/gridfs-stream-tests.ts +++ b/gridfs-stream/gridfs-stream-tests.ts @@ -1,7 +1,3 @@ - - -/// - // Samples from: // https://github.com/aheckmann/gridfs-stream diff --git a/gridstack/index.d.ts b/gridstack/index.d.ts index 75056999e2..12c3600f6a 100644 --- a/gridstack/index.d.ts +++ b/gridstack/index.d.ts @@ -181,61 +181,61 @@ interface IGridstackOptions { /** * if true the resizing handles are shown even if the user is not hovering over the widget (default: false) */ - alwaysShowResizeHandle: boolean; + alwaysShowResizeHandle?: boolean; /** * turns animation on (default: true) */ - animate: boolean; + animate?: boolean; /** * if false gridstack will not initialize existing items (default: true) */ - auto: boolean; + auto?: boolean; /** * one cell height (default: 60) */ - cellHeight: number; + cellHeight?: number; /** * allows to override jQuery UI draggable options. (default: { handle: '.grid-stack-item-content', scroll: true, appendTo: 'body' }) */ - draggable: {}; + draggable?: {}; /** * draggable handle selector (default: '.grid-stack-item-content') */ - handle: string; + handle?: string; /** * maximum rows amount.Default is 0 which means no maximum rows */ - height: number; + height?: number; /** * enable floating widgets (default: false) See example */ - float: boolean; + float?: boolean; /** * widget class (default: 'grid-stack-item') */ - itemClass: string; + itemClass?: string; /** * minimal width.If window width is less, grid will be shown in one - column mode (default: 768) */ - minWidth: number; + minWidth?: number; /** * class for placeholder (default: 'grid-stack-placeholder') */ - placeholderClass: string; + placeholderClass?: string; /** * allows to override jQuery UI resizable options. (default: { autoHide: true, handles: 'se' }) */ - resizable: {}; + resizable?: {}; /** * makes grid static (default false).If true widgets are not movable/ resizable.You don't even need jQueryUI draggable/resizable. A CSS class grid-stack-static is also added to the container. */ - staticGrid: boolean; + staticGrid?: boolean; /** * vertical gap size (default: 20) */ - verticalMargin: number; + verticalMargin?: number; /** * amount of columns (default: 12) */ - width: number; + width?: number; } diff --git a/gsap/Animation.d.ts b/gsap/Animation.d.ts new file mode 100644 index 0000000000..3c58f9b12a --- /dev/null +++ b/gsap/Animation.d.ts @@ -0,0 +1,90 @@ +declare namespace gsap { + export class Animation { + /** Base class for all TweenLite, TweenMax, TimelineLite, and TimelineMax classes, providing core methods/properties/() => voidality, but there is no reason to create an instance of this class directly. */ + constructor(duration?: number, vars?: any); + + /** A place to store any data you want (initially populated with vars.data if it exists). */ + data: any; + + /** [Read-only] Parent timeline. */ + timeline: SimpleTimeline; + + /** The vars object passed into the constructor which stores configuration variables like onComplete, onUpdate, etc. */ + vars: {}; + + /** Gets or sets the animation's initial delay which is the length of time in seconds (or frames for frames-based tweens) before the animation should begin. */ + delay(): number; + delay(value: number): Animation; + + /** Gets or sets the animation's duration, not including any repeats or repeatDelays (which are only available in TweenMax and TimelineMax). */ + duration(): number; + duration(value: number): Animation; + + /** Gets or sets an event callback like "onComplete", "onUpdate", "onStart", "onReverseComplete" or "onRepeat" (onRepeat only applies to TweenMax or TimelineMax instances) along with any parameters that should be passed to that callback. */ + eventCallback(type: string): () => void; + eventCallback(type: string, callback: () => void, params?: any[], scope?: any): Animation; + + /** Clears any initialization data (like starting/ending values in tweens) which can be useful if, for example, you want to restart a tween without reverting to any previously recorded starting values. */ + invalidate(): Animation; + + /** Indicates whether or not the animation is currently active (meaning the virtual playhead is actively moving across this instance's time span and it is not paused, nor are any of its ancestor timelines). */ + isActive(): boolean; + + /** Kills the animation entirely or in part depending on the parameters. */ + kill(vars?: {}, target?: {}): Animation; + + /** Pauses the instance, optionally jumping to a specific time. */ + pause(atTime?: any, suppressEvents?: boolean): Animation; + + /** Gets or sets the animation's paused state which indicates whether or not the animation is currently paused. */ + paused(): boolean; + paused(value: boolean): Animation; + + /** Begins playing forward, optionally from a specific time (by default playback begins from wherever the playhead currently is). */ + play(from?: any, suppressEvents?: boolean): Animation; + + /** Gets or sets the animations's progress which is a value between 0 and 1 indicating the position of the virtual playhead (excluding repeats) where 0 is at the beginning, 0.5 is at the halfway point, and 1 is at the end (complete). */ + progress(): number; + progress(value: number, suppressEvents?: boolean): Animation; + + /** Restarts and begins playing forward from the beginning. */ + restart(includeDelay?: boolean, suppressEvents?: boolean): Animation; + + /** Resumes playing without altering direction (forward or reversed), optionally jumping to a specific time first. */ + resume(from?: any, suppressEvents?: boolean): Animation; + + /** Reverses playback so that all aspects of the animation are oriented backwards including, for example, a tween's ease. */ + reverse(from?: any, suppressEvents?: boolean): Animation; + + /** Gets or sets the animation's reversed state which indicates whether or not the animation should be played backwards. */ + reversed(): boolean; + reversed(value: boolean): Animation; + + /** Jumps to a specific time without affecting whether or not the instance is paused or reversed. */ + seek(time: any, suppressEvents?: boolean): Animation; + + /** Gets or sets the time at which the animation begins on its parent timeline (after any delay that was defined). */ + startTime(): number; + startTime(value: number): Animation; + + /** Gets or sets the local position of the playhead (essentially the current time), described in seconds (or frames for frames-based animations) which will never be less than 0 or greater than the animation's duration. */ + time(): number; + time(value: number, suppressEvents?: boolean): Animation; + + /** Factor that's used to scale time in the animation where 1 = normal speed (the default), 0.5 = half speed, 2 = double speed, etc. */ + timeScale(): number; + timeScale(value: number): Animation; + + /** Gets or sets the animation's total duration including any repeats or repeatDelays (which are only available in TweenMax and TimelineMax). */ + totalDuration(): number; + totalDuration(value: number): Animation; + + /** Gets or sets the animation's total progress which is a value between 0 and 1 indicating the position of the virtual playhead (including repeats) where 0 is at the beginning, 0.5 is at the halfway point, and 1 is at the end (complete). */ + totalProgress(): number; + totalProgress(value: number, suppressEvents?: boolean): Animation; + + /** Gets or sets the position of the playhead according to the totalDuration which includes any repeats and repeatDelays (only available in TweenMax and TimelineMax). */ + totalTime(): number; + totalTime(time: number, suppressEvents?: boolean): Animation; + } +} diff --git a/gsap/Core.d.ts b/gsap/Core.d.ts deleted file mode 100644 index 30b07a3e19..0000000000 --- a/gsap/Core.d.ts +++ /dev/null @@ -1,179 +0,0 @@ -declare class Animation { - /** Base class for all TweenLite, TweenMax, TimelineLite, and TimelineMax classes, providing core methods/properties/functionality, but there is no reason to create an instance of this class directly. */ - constructor(duration?: number, vars?: any); - - /** A place to store any data you want (initially populated with vars.data if it exists). */ - data: any; - - /** [Read-only] Parent timeline. */ - timeline: SimpleTimeLine; - - /** The vars object passed into the constructor which stores configuration variables like onComplete, onUpdate, etc. */ - vars: any; - - /** Gets or sets the animation's initial delay which is the length of time in seconds (or frames for frames-based tweens) before the animation should begin. */ - delay(): number; - delay(value: number): Animation; - - /** Gets or sets the animation's duration, not including any repeats or repeatDelays (which are only available in TweenMax and TimelineMax). */ - duration(): number; - duration(value: number): Animation; - - /** Gets or sets an event callback like "onComplete", "onUpdate", "onStart", "onReverseComplete" or "onRepeat" (onRepeat only applies to TweenMax or TimelineMax instances) along with any parameters that should be passed to that callback. */ - eventCallback(type: string): Function; - eventCallback(type: string, callback: Function, params?: any[], scope?: any): Animation; - - /** Clears any initialization data (like starting/ending values in tweens) which can be useful if, for example, you want to restart a tween without reverting to any previously recorded starting values. */ - invalidate(): Animation; - - /** Indicates whether or not the animation is currently active (meaning the virtual playhead is actively moving across this instance's time span and it is not paused, nor are any of its ancestor timelines). */ - isActive(): boolean; - - /** Kills the animation entirely or in part depending on the parameters. */ - kill(vars?: any, target?: any): Animation; - - /** Pauses the instance, optionally jumping to a specific time. */ - pause(atTime?: any, suppressEvents?: boolean): Animation; - - /** Gets or sets the animation's paused state which indicates whether or not the animation is currently paused. */ - paused(): boolean; - paused(value: boolean): Animation; - - /** Begins playing forward, optionally from a specific time (by default playback begins from wherever the playhead currently is). */ - play(from?: any, suppressEvents?: boolean): Animation; - - /** Gets or sets the animations's progress which is a value between 0 and 1 indicating the position of the virtual playhead (excluding repeats) where 0 is at the beginning, 0.5 is at the halfway point, and 1 is at the end (complete). */ - progress(): number; - progress(value: number, suppressEvents?: boolean): Animation; - - /** Restarts and begins playing forward from the beginning. */ - restart(includeDelay?: boolean, suppressEvents?: boolean): Animation; - - /** Resumes playing without altering direction (forward or reversed), optionally jumping to a specific time first. */ - resume(from?: any, suppressEvents?: boolean): Animation; - - /** Reverses playback so that all aspects of the animation are oriented backwards including, for example, a tween's ease. */ - reverse(from?: any, suppressEvents?: boolean): Animation; - - /** Gets or sets the animation's reversed state which indicates whether or not the animation should be played backwards. */ - reversed(): boolean; - reversed(value: boolean): Animation; - - /** Jumps to a specific time without affecting whether or not the instance is paused or reversed. */ - seek(time: any, suppressEvents?: boolean): Animation; - - /** Gets or sets the time at which the animation begins on its parent timeline (after any delay that was defined). */ - startTime(): number; - startTime(value: number): Animation; - - /** Gets or sets the local position of the playhead (essentially the current time), described in seconds (or frames for frames-based animations) which will never be less than 0 or greater than the animation's duration. */ - time(): number; - time(value: number, suppressEvents?: boolean): Animation; - - /** Factor that's used to scale time in the animation where 1 = normal speed (the default), 0.5 = half speed, 2 = double speed, etc. */ - timeScale(): number; - timeScale(value: number): Animation; - - /** Gets or sets the animation's total duration including any repeats or repeatDelays (which are only available in TweenMax and TimelineMax). */ - totalDuration(): number; - totalDuration(value: number): Animation; - - /** Gets or sets the animation's total progress which is a value between 0 and 1 indicating the position of the virtual playhead (including repeats) where 0 is at the beginning, 0.5 is at the halfway point, and 1 is at the end (complete). */ - totalProgress(): number; - totalProgress(value: number, suppressEvents?: boolean): Animation; - - /** Gets or sets the position of the playhead according to the totalDuration which includes any repeats and repeatDelays (only available in TweenMax and TimelineMax). */ - totalTime(): number; - totalTime(time: number, suppressEvents?: boolean): Animation; -} - -declare class SimpleTimeLine extends Animation { - /** SimpleTimeline is the base class for TimelineLite and TimelineMax, providing the most basic timeline functionality and it is used for the root timelines in TweenLite but is only intended for internal use in the GreenSock tweening platform. It is meant to be very fast and lightweight. */ - constructor(vars?: any); - - /** If true, child tweens/timelines will be removed as soon as they complete. */ - autoRemoveChildren: boolean; - - /** Controls whether or not child tweens/timelines are repositioned automatically (changing their startTime) in order to maintain smooth playback when properties are changed on-the-fly. */ - smoothChildTiming: boolean; - - /** Adds a TweenLite, TweenMax, TimelineLite, or TimelineMax instance to the timeline at a specific time. */ - add(child: any, position?: any, align?: string, stagger?: number): SimpleTimeLine; - - /** renders */ - render(time: number, suppressEvents?: boolean, force?: boolean): SimpleTimeLine; - - // INHERITANCE FROM ANIMATION - - /** Gets or sets the animation's initial delay which is the length of time in seconds (or frames for frames-based tweens) before the animation should begin. */ - delay(): number; - delay(value: number): SimpleTimeLine; - - /** Gets or sets the animation's duration, not including any repeats or repeatDelays (which are only available in TweenMax and TimelineMax). */ - duration(): number; - duration(value: number): SimpleTimeLine; - - /** Gets or sets an event callback like "onComplete", "onUpdate", "onStart", "onReverseComplete" or "onRepeat" (onRepeat only applies to TweenMax or TimelineMax instances) along with any parameters that should be passed to that callback. */ - eventCallback(type: string): Function; - eventCallback(type: string, callback: Function, params?: any[], scope?: any): SimpleTimeLine; - - /** Clears any initialization data (like starting/ending values in tweens) which can be useful if, for example, you want to restart a tween without reverting to any previously recorded starting values. */ - invalidate(): SimpleTimeLine; - - /** Kills the animation entirely or in part depending on the parameters. */ - kill(vars?: any, target?: any): SimpleTimeLine; - - /** Pauses the instance, optionally jumping to a specific time. */ - pause(atTime?: any, suppressEvents?: boolean): SimpleTimeLine; - - /** Gets or sets the animation's paused state which indicates whether or not the animation is currently paused. */ - paused(): boolean; - paused(value: boolean): SimpleTimeLine; - - /** Begins playing forward, optionally from a specific time (by default playback begins from wherever the playhead currently is). */ - play(from?: any, suppressEvents?: boolean): SimpleTimeLine; - - /** Gets or sets the animations's progress which is a value between 0 and 1 indicating the position of the virtual playhead (excluding repeats) where 0 is at the beginning, 0.5 is at the halfway point, and 1 is at the end (complete). */ - progress(): number; - progress(value: number, suppressEvents?: boolean): SimpleTimeLine; - - /** Restarts and begins playing forward from the beginning. */ - restart(includeDelay?: boolean, suppressEvents?: boolean): SimpleTimeLine; - - /** Resumes playing without altering direction (forward or reversed), optionally jumping to a specific time first. */ - resume(from?: any, suppressEvents?: boolean): SimpleTimeLine; - - /** Reverses playback so that all aspects of the animation are oriented backwards including, for example, a tween's ease. */ - reverse(from?: any, suppressEvents?: boolean): SimpleTimeLine; - - /** Gets or sets the animation's reversed state which indicates whether or not the animation should be played backwards. */ - reversed(): boolean; - reversed(value: boolean): SimpleTimeLine; - - /** Jumps to a specific time without affecting whether or not the instance is paused or reversed. */ - seek(time: any, suppressEvents?: boolean): SimpleTimeLine; - - /** Gets or sets the time at which the animation begins on its parent timeline (after any delay that was defined). */ - startTime(): number; - startTime(value: number): SimpleTimeLine; - - /** Gets or sets the local position of the playhead (essentially the current time), described in seconds (or frames for frames-based animations) which will never be less than 0 or greater than the animation's duration. */ - time(): number; - time(value: number, suppressEvents?: boolean): SimpleTimeLine; - - /** Factor that's used to scale time in the animation where 1 = normal speed (the default), 0.5 = half speed, 2 = double speed, etc. */ - timeScale(): number; - timeScale(value: number): SimpleTimeLine; - - /** Gets or sets the animation's total duration including any repeats or repeatDelays (which are only available in TweenMax and TimelineMax). */ - totalDuration(): number; - totalDuration(value: number): SimpleTimeLine; - - /** Gets or sets the animation's total progress which is a value between 0 and 1 indicating the position of the virtual playhead (including repeats) where 0 is at the beginning, 0.5 is at the halfway point, and 1 is at the end (complete). */ - totalProgress(): number; - totalProgress(value: number, suppressEvents?: boolean): SimpleTimeLine; - - /** Gets or sets the position of the playhead according to the totalDuration which includes any repeats and repeatDelays (only available in TweenMax and TimelineMax). */ - totalTime(): number; - totalTime(time: number, suppressEvents?: boolean): SimpleTimeLine; -} \ No newline at end of file diff --git a/gsap/Ease.d.ts b/gsap/Ease.d.ts index 932222ff56..ea2d7e1d84 100644 --- a/gsap/Ease.d.ts +++ b/gsap/Ease.d.ts @@ -1,6 +1,113 @@ -declare class Ease { - constructor(func?: Function, extraParams?: any[], type?: number, power?: number); +declare namespace gsap { + export class Ease { + constructor(func?: () => void, extraParams?: any[], type?: number, power?: number); - /** Translates the tween's progress ratio into the corresponding ease ratio. */ - getRatio(p: number): number; -} \ No newline at end of file + /** Translates the tween's progress ratio into the corresponding ease ratio. */ + getRatio(p: number): number; + } + + export class EaseLookup { + static find(name: string): Ease; + } + + export class Back extends Ease { + static easeIn: Back; + static easeInOut: Back; + static easeOut: Back; + config(overshoot: number): Elastic; + + } + export class Bounce extends Ease { + static easeIn: Bounce; + static easeInOut: Bounce; + static easeOut: Bounce; + } + export class Circ extends Ease { + static easeIn: Circ; + static easeInOut: Circ; + static easeOut: Circ; + } + export class Cubic extends Ease { + static easeIn: Cubic; + static easeInOut: Cubic; + static easeOut: Cubic; + } + + export class Elastic extends Ease { + static easeIn: Elastic; + static easeInOut: Elastic; + static easeOut: Elastic; + config(amplitude: number, period: number): Elastic; + } + + export class Expo extends Ease { + static easeIn: Expo; + static easeInOut: Expo; + static easeOut: Expo; + } + + export class Linear extends Ease { + static ease: Linear; + static easeIn: Linear; + static easeInOut: Linear; + static easeNone: Linear; + static easeOut: Linear; + } + + export class Quad extends Ease { + static easeIn: Quad; + static easeInOut: Quad; + static easeOut: Quad; + } + + export class Quart extends Ease { + static easeIn: Quart; + static easeInOut: Quart; + static easeOut: Quart; + } + + export class Quint extends Ease { + static easeIn: Quint; + static easeInOut: Quint; + static easeOut: Quint; + } + + export class Sine extends Ease { + static easeIn: Sine; + static easeInOut: Sine; + static easeOut: Sine; + } + + export class SlowMo extends Ease { + static ease: SlowMo; + config(linearRatio: number, power: number, yoyoMode: boolean): SlowMo; + } + + export class SteppedEase extends Ease { + constructor(staps: number); + config(steps: number): SteppedEase; + } + + export interface RoughEaseConfig { + clamp?: boolean; + points?: number; + randomize?: boolean; + strength?: number; + taper?: 'in' | 'out' | 'both' | 'none'; + template?: Ease; + } + + export class RoughEase extends Ease { + static ease: RoughEase; + constructor(vars: RoughEaseConfig); + config(steps?: number): RoughEase; + } + + + export var Power0: typeof Linear; + export var Power1: typeof Quad; + export var Power2: typeof Cubic; + export var Power3: typeof Quart; + export var Power4: typeof Quint; + export var Strong: typeof Quint; +} diff --git a/gsap/Plugins.d.ts b/gsap/Plugins.d.ts new file mode 100644 index 0000000000..d7ceca7bf8 --- /dev/null +++ b/gsap/Plugins.d.ts @@ -0,0 +1,15 @@ +declare namespace gsap { + export interface BezierPlugin extends TweenPlugin { + bezierThrough(values: any[], curviness?: number, quadratic?: boolean, correlate?: string, prepend?: {}, calcDifs?: boolean): {}; + cubicToQuadratic(a: number, b: number, c: number, d: number): any[]; + quadraticToCubic(a: number, b: number, c: number): {}; + } + + export interface CSSRulePlugin extends TweenPlugin { + getRule(selector: string): {}; + } + + export interface TweenPlugin { + activate(plugins: any[]): boolean; + } +} diff --git a/gsap/Timeline.d.ts b/gsap/Timeline.d.ts new file mode 100644 index 0000000000..9d14b2d4c5 --- /dev/null +++ b/gsap/Timeline.d.ts @@ -0,0 +1,119 @@ +declare namespace gsap { + export type Timeline = SimpleTimeline | TimelineLite | TimelineMax; + + export class SimpleTimeline extends Animation { + /** SimpleTimeline is the base class for TimelineLite and TimelineMax, providing the most basic timeline () => voidality and it is used for the root timelines in TweenLite but is only intended for internal use in the GreenSock tweening platform. It is meant to be very fast and lightweight. */ + constructor(vars?: any); + + /** If true, child tweens/timelines will be removed as soon as they complete. */ + autoRemoveChildren: boolean; + + /** Controls whether or not child tweens/timelines are repositioned automatically (changing their startTime) in order to maintain smooth playback when properties are changed on-the-fly. */ + smoothChildTiming: boolean; + + /** Adds a TweenLite, TweenMax, TimelineLite, or TimelineMax instance to the timeline at a specific time. */ + add(child: any, position?: any, align?: string, stagger?: number): SimpleTimeline; + + /** renders */ + render(time: number, suppressEvents?: boolean, force?: boolean): SimpleTimeline; + } + + export class TimelineLite extends SimpleTimeline { + constructor(vars?: {}); + + /** Adds a tween, timeline, callback, or label (or an array of them) to the timeline. */ + add(value: any, position?: any, align?: string, stagger?: number): TimelineLite; + + /** Adds a label to the timeline, making it easy to mark important positions/times. */ + addLabel(label: string, position: any): TimelineLite; + + /** Inserts a special callback that pauses playback of the timeline at a particular time or label. */ + addPause(position?: any, callback?: () => void, params?: any[], scope?: any): TimelineLite; + + /** Adds a callback to the end of the timeline (or elsewhere using the "position" parameter) - this is a convenience method that accomplishes exactly the same thing as add( TweenLite.delayedCall(...) ) but with less code. */ + call(callback: () => void, params?: any[], scope?: any, position?: any): TimelineLite; + + /** Empties the timeline of all tweens, timelines, and callbacks (and optionally labels too). */ + clear(labels?: boolean): TimelineLite; + + /** Returns the time at which the animation will finish according to the parent timeline's local time. */ + endTime(includeRepeats?: boolean): number; + + /** Seamlessly transfers all tweens, timelines, and [optionally] delayed calls from the root timeline into a new TimelineLite so that you can perform advanced tasks on a seemingly global basis without affecting tweens/timelines that you create after the export. */ + static exportRoot(vars?: {}, omitDelayedCalls?: boolean): TimelineLite; + + /** Adds a TweenLite.from() tween to the end of the timeline (or elsewhere using the "position" parameter) - this is a convenience method that accomplishes exactly the same thing as add( TweenLite.from(...) ) but with less code. */ + from(target: {}, duration: number, vars: {}, position?: any): TimelineLite; + + /** Adds a TweenLite.fromTo() tween to the end of the timeline - this is a convenience method that accomplishes exactly the same thing as add( TweenLite.fromTo(...) ) but with less code. */ + fromTo(target: {}, duration: number, fromVars: {}, toVars: {}, position?: any): TimelineLite; + + /** Returns an array containing all the tweens and/or timelines nested in this timeline. */ + getChildren(nested?: boolean, tweens?: boolean, timelines?: boolean, ignoreBeforeTime?: number): Array; + + /** Returns the time associated with a particular label. */ + getLabelTime(label: string): number; + + /** Returns the tweens of a particular object that are inside this timeline. */ + getTweensOf(target: {}, nested?: boolean): Tween[]; + + /** Clears any initialization data (like starting/ending values in tweens) which can be useful if, for example, you want to restart a tween without reverting to any previously recorded starting values. */ + invalidate(): TimelineLite; + + /** Returns the most recently added child tween/timeline/callback regardless of its position in the timeline. */ + recent(): Animation; + + /** Removes a tween, timeline, callback, or label (or array of them) from the timeline. */ + remove(value: any): TimelineLite; + + /** Removes a label from the timeline and returns the time of that label. */ + removeLabel(label: string): any; + + /** Jumps to a specific time (or label) without affecting whether or not the instance is paused or reversed. */ + seek(position: string | number, supressEvents: boolean): TimelineLite; + + /** Adds a zero-duration tween to the end of the timeline (or elsewhere using the "position" parameter) that sets values immediately (when the virtual playhead reaches that position on the timeline) - this is a convenience method that accomplishes exactly the same thing as add( TweenLite.to(target, 0, {...}) ) but with less code. */ + set(target: {}, vars: {}, position?: any): TimelineLite; + + /** Shifts the startTime of the timeline's children by a certain amount and optionally adjusts labels too. */ + shiftChildren(amount: number, adjustLabels?: boolean, ignoreBeforeTime?: number): TimelineLite; + + /** Tweens an array of targets from a common set of destination values (using the current values as the destination), but staggers their start times by a specified amount of time, creating an evenly-spaced sequence with a surprisingly small amount of code. */ + staggerFrom(targets: any, duration: number, vars: {}, stagger?: number, position?: any, onCompleteAll?: () => void, onCompleteAllParams?: any[], onCompleteScope?: any): TimelineLite; + + /** Tweens an array of targets from and to a common set of values, but staggers their start times by a specified amount of time, creating an evenly-spaced sequence with a surprisingly small amount of code. */ + staggerFromTo(targets: any, duration: number, fromVars: {}, toVars: {}, stagger?: number, position?: any, onCompleteAll?: () => void, onCompleteAllParams?: any[], onCompleteAllScope?: any): TimelineLite; + + /** Tweens an array of targets to a common set of destination values, but staggers their start times by a specified amount of time, creating an evenly-spaced sequence with a surprisingly small amount of code. */ + staggerTo(targets: any, duration: number, vars: {}, stagger: number, position?: any, onCompleteAll?: () => void, onCompleteAllParams?: any[], onCompleteAllScope?: any): TimelineLite; + + /** Adds a TweenLite.to() tween to the end of the timeline (or elsewhere using the "position" parameter) - this is a convenience method that accomplishes exactly the same thing as add( TweenLite.to(...) ) but with less code. */ + to(target: {}, duration: number, vars: {}, position?: any): TimelineLite; + usesFrames(): boolean; + + /** If true, the timeline's timing mode is frames-based instead of seconds. */ + useFrames(): boolean; + } + + export class TimelineMax extends TimelineLite { + constructor(vars?: {}); + + addCallback(callback: () => void, position: any, params?: any[], scope?: any): TimelineMax; + currentLabel(): string; + currentLabel(value: string): TimelineMax; + getActive(nested?: boolean, tweens?: boolean, timelines?: boolean): Tween | Timeline[]; + getLabelAfter(time: number): string; + getLabelBefore(time: number): string; + getLabelsArray(): Array<{ name: string; time: number; }>; + removeCallback(callback: () => void, timeOrLabel?: any): TimelineMax; + removePause(position: any): TimelineMax; + repeat(): number; + repeat(value: number): TimelineMax; + repeatDelay(): number; + repeatDelay(value: number): TimelineMax; + tweenFromTo(fromPosition: any, toPosition: any, vars?: {}): TweenLite; + tweenTo(position: any, vars?: {}): TweenLite; + yoyo(): boolean; + yoyo(value: boolean): TimelineMax; + } +} diff --git a/gsap/Tween.d.ts b/gsap/Tween.d.ts new file mode 100644 index 0000000000..b11260ef4c --- /dev/null +++ b/gsap/Tween.d.ts @@ -0,0 +1,127 @@ +declare namespace gsap { + export type Tween = TweenLite | TweenMax; + export class TweenLite extends Animation { + constructor(target: any, duration: number, vars: any); + + /** Provides An easy way to change the default easing equation. */ + static defaultEase: Ease; + + /** Provides An easy way to change the default overwrite mode. */ + static defaultOverwrite: string; + + /** The selector engine (like jQuery) that should be used when a tween receives a string as its target, like TweenLite.to("#myID", 1, {x:"100px"}). */ + static selector: (query: string) => any; + + /** Target object (or array of objects) whose properties the tween affects. */ + readonly target: any; + + /** The object that dispatches a "tick" event each time the engine updates, making it easy for you to add your own listener(s) to run custom logic after each update (great for game developers). */ + static ticker: any; + + /** Provides a simple way to call a () => void after a set amount of time (or frames). */ + static delayedCall(delay: number, callback: () => void, params?: any[], scope?: any, useFrames?: boolean): TweenLite; + + /** Static method for creating a TweenLite instance that tweens backwards - you define the BEGINNING values and the current values are used as the destination values which is great for doing things like animating objects onto the screen because you can set them up initially the way you want them to look at the end of the tween and then animate in from elsewhere. */ + static from(target: any, duration: number, vars: any): TweenLite; + + /** Static method for creating a TweenLite instance that allows you to define both the starting and ending values (as opposed to to() and from() tweens which are based on the target's current values at one end or the other). */ + static fromTo(target: any, duration: number, fromVars: any, toVars: any): TweenLite; + + /** Returns an array containing all the tweens of a particular target (or group of targets) that have not been released for garbage collection yet which typically happens within a few seconds after the tween completes. */ + static getTweensOf(target: any, onlyActive?: boolean): TweenLite[]; + + /** [override] Clears any initialization data (like starting/ending values in tweens) which can be useful if, for example, you want to restart a tween without reverting to any previously recorded starting values. */ + invalidate(): TweenLite; + + /** Immediately kills all of the delayedCalls to a particular () => void. */ + static killDelayedCallsTo(func: () => void): void; + + /** Kills all the tweens (or specific tweening properties) of a particular object or delayedCalls to a particular () => void. */ + static killTweensOf(target: any, onlyActive?: boolean, vars?: any): void; + + /** Permits you to control what happens when too much time elapses between two ticks (updates) of the engine, adjusting the core timing mechanism to compensate and avoid "jumps". */ + static lagSmoothing(threshold: number, adjustedLag: number): void; + + /** Forces a render of all active tweens which can be useful if, for example, you set up a bunch of from() tweens and then you need to force an immediate render (even of "lazy" tweens) to avoid a brief delay before things render on the very next tick. */ + static render(): void; + + /** Immediately sets properties of the target accordingly - essentially a zero-duration to() tween with a more intuitive name. */ + static set(target: any, vars: any): TweenLite; + + /** Static method for creating a TweenLite instance that animates to the specified destination values (from the current values). */ + static to(target: any, duration: number, vars: any): TweenLite; + } + + export class TweenMax extends TweenLite { + constructor(target: {}, duration: number, vars: {}); + + /** Provides a simple way to call a () => void after a set amount of time (or frames). */ + static delayedCall(delay: number, callback: () => void, params?: any[], scope?: {}, useFrames?: boolean): TweenMax; + + /** Static method for creating a TweenMax instance that tweens backwards - you define the BEGINNING values and the current values are used as the destination values which is great for doing things like animating objects onto the screen because you can set them up initially the way you want them to look at the end of the tween and then animate in from elsewhere. */ + static from(target: {}, duration: number, vars: {}): TweenMax; + + /** Static method for creating a TweenMax instance that allows you to define both the starting and ending values (as opposed to to() and from() tweens which are based on the target's current values at one end or the other). */ + static fromTo(target: {}, duration: number, fromVars: {}, toVars: {}): TweenMax; + + /** Returns an array containing all tweens (and optionally timelines too, excluding the root timelines). */ + static getAllTweens(includeTimelines?: boolean): Tween[]; + + /** Returns an array containing all the tweens of a particular target (or group of targets) that have not been released for garbage collection yet which typically happens within a few seconds after the tween completes. */ + static getTweensOf(target: {}): Tween[]; + + /** Gets or sets the global timeScale which is a multiplier that affects ALL animations equally. This is a great way to globally speed up or slow down all animations at once. */ + static globalTimeScale(value: number): void; + + /** Reports whether or not a particular object is actively tweening. */ + static isTweening(target: {}): boolean; + + /** Kills all tweens and/or delayedCalls/callbacks, and/or timelines, optionally forcing them to completion first. */ + static killAll(complete?: boolean, tweens?: boolean, delayedCalls?: boolean, timelines?: boolean): void; + + /** Kills all tweens of the children of a particular DOM element, optionally forcing them to completion first. */ + static killChildTweensOf(parent: any, complete?: boolean): void; + + /** Immediately kills all of the delayedCalls to a particular () => void. */ + static killDelayedCallsTo(func: () => void): void; + + /** Kills all the tweens (or specific tweening properties) of a particular object or the delayedCalls to a particular () => void. */ + static killTweensOf(target: {}, vars?: {}): void; + + /** Pauses all tweens and/or delayedCalls/callbacks and/or timelines. */ + static pauseAll(tweens?: boolean, delayedCalls?: boolean, timelines?: boolean): void; + + /** Gets or sets the tween's progress which is a value between 0 and 1 indicating the position of the virtual playhead (excluding repeats) where 0 is at the beginning, 0.5 is halfway complete, and 1 is complete. */ + repeat(): number; + repeat(value: number): TweenMax; + + /** Gets or sets the amount of time in seconds (or frames for frames-based tweens) between repeats. */ + repeatDelay(): number; + repeatDelay(value: number): TweenMax; + + /** Resumes all paused tweens and/or delayedCalls/callbacks and/or timelines. */ + static resumeAll(tweens?: boolean, delayedCalls?: boolean, timelines?: boolean): void; + + /** Immediately sets properties of the target accordingly - essentially a zero-duration to() tween with a more intuitive name. */ + static set(target: {}, vars: {}): TweenMax; + + /** Tweens an array of targets from a common set of destination values (using the current values as the destination), but staggers their start times by a specified amount of time, creating an evenly-spaced sequence with a surprisingly small amount of code. */ + static staggerFrom(targets: any, duration: number, vars: {}, stagger: number, onCompleteAll?: () => void, onCompleteAllParams?: any[], onCompleteAllScope?: any): any[]; + + /** Tweens an array of targets from a common set of destination values to a common set of destination values, but staggers their start times by a specified amount of time, creating an evenly-spaced sequence with a surprisingly small amount of code. */ + static staggerFromTo(targets: any, duration: number, fromVars: {}, toVars: {}, stagger: number, onCompleteAll?: () => void, onCompleteAllParams?: any[], onCompleteAllScope?: any): any[]; + + /** Tweens an array of targets to a common set of destination values, but staggers their start times by a specified amount of time, creating an evenly-spaced sequence with a surprisingly small amount of code. */ + static staggerTo(targets: any, duration: number, vars: {}, stagger: number, onCompleteAll?: () => void, onCompleteAllParams?: any[], onCompleteAllScope?: any): any[]; + + /** Static method for creating a TweenMax instance that animates to the specified destination values (from the current values). */ + static to(target: {}, duration: number, vars: TweenConfig): TweenMax; + + /** Updates tweening values on the fly so that they appear to seamlessly change course even if the tween is in-progress. */ + updateTo(vars: {}, resetDuration?: boolean): TweenMax; + + /** Gets or sets the tween's yoyo state, where true causes the tween to go back and forth, alternating backward and forward on each repeat. */ + yoyo(): boolean; + yoyo(value?: boolean): TweenMax; + } +} diff --git a/gsap/TweenConfig.d.ts b/gsap/TweenConfig.d.ts new file mode 100644 index 0000000000..59c472bea2 --- /dev/null +++ b/gsap/TweenConfig.d.ts @@ -0,0 +1,82 @@ +declare namespace gsap { + export interface TweenConfig { + + /** Amount of delay in seconds (or frames for frames-based tweens) before the animation should begin.*/ + delay?: number; + + /** Ease (or () => void or String) - You can choose from various eases to control the rate of change during the animation, giving it a specific "feel". */ + ease?: Ease; + + yoyo?: boolean; + + /** If true, the tween will pause itself immediately upon creation. */ + paused?: boolean; + + /** Controls how (and if) other tweens of the same target are overwritten. There are several modes to choose from, but "auto" is the default (although you can change the default mode using theTweenLite.defaultOverwrite property) */ + overwrite?: string | number; + + /** A () => void that should be called when the animation has completed. */ + onComplete?: () => void; + + /** An Array of parameters to pass the onComplete () => void */ + onCompleteParams?: any[]; + + /** Defines the scope of the onComplete () => void (what "this" refers to inside that () => void). */ + onCompleteScope?: {}; + + /** Normally when you create a tween, it begins rendering on the very next frame (update cycle) unless you specify a delay. However, if you prefer to force the tween to render immediately when it is created, setimmediateRender to true. Or to prevent a from() from rendering immediately, set immediateRender to false. By default, from() tweens set immediateRender to true. */ + immediateRender?: boolean; + + /** A () => void that should be called when the tween has reached its beginning again from the reverse direction. */ + onReverseComplete?: () => void; + + /** An Array of parameters to pass the onReverseComplete () => void. */ + onReverseCompleteParams?: any[]; + + /** Defines the scope of the onReverseComplete () => void (what "this" refers to inside that () => void). */ + onReverseCompleteScope?: {}; + + /** A () => void that should be called when the tween begins (when its time changes from 0 to some other value which can happen more than once if the tween is restarted multiple times). */ + onStart?: () => void; + + /** An Array of parameters to pass the onStart () => void. */ + onStartParams?: any[]; + + /** Defines the scope of the onStart () => void (what "this" refers to inside that () => void). */ + onStartScope?: {}; + + /** A () => void that should be called every time the animation updates (on every frame while the animation is active). */ + onUpdate?: () => void; + + /** An Array of parameters to pass the onUpdate () => void. */ + onUpdateParams?: any[]; + + /** Defines the scope of the onUpdate () => void (what "this" refers to inside that () => void). */ + onUpdateScope?: {}; + + /** If useFrames is true, the tweens's timing will be based on frames instead of seconds because it is intially added to the root frames-based timeline. This causes both its duration and delay to be based on frames. An animations's timing mode is always determined by its parent timeline. */ + useFrames?: boolean; + + /** When a tween renders for the very first time and reads its starting values, GSAP will automatically "lazy render" that particular tick by default, meaning it will try to delay the rendering (writing of values) until the very end of the "tick" cycle which can improve performance because it avoids the read/write/read/write layout thrashing that some browsers do. If you would like to disable lazy rendering for a particular tween, you can set lazy:false. Or, since zero-duration tweens do not lazy-render by default, you can specifically give it permission to lazy-render by setting lazy:true like TweenLite.set(element, {opacity:0, lazy:true});. In most cases, you won't need to set lazy. */ + lazy?: boolean; + + /** A () => void that should be called when the tween gets overwritten by another tween. */ + onOverwrite?: () => void; + + /** If true atuomatically populates the css property for tween on DOM elements */ + autoCSS?: boolean; + + /** The scope to be used for all of the callbacks (onStart, onUpdate, onComplete, etc.). The scope is what "this" refers to inside any of the callbacks. */ + callbackScope?: {}; + + startAt?: {}; + + repeat?: number; + + repeatDelay?: number; + + onRepeat?: () => void; + + onRepeatScope?: {}; + } +} diff --git a/gsap/TweenLite.d.ts b/gsap/TweenLite.d.ts deleted file mode 100644 index 21150acf22..0000000000 --- a/gsap/TweenLite.d.ts +++ /dev/null @@ -1,122 +0,0 @@ -declare class TweenLite { - constructor(target: any, duration: number, vars: any); - - /** Provides An easy way to change the default easing equation. */ - static defaultEase: Ease; - - /** Provides An easy way to change the default overwrite mode. */ - static defaultOverwrite: string; - - /** The selector engine (like jQuery) that should be used when a tween receives a string as its target, like TweenLite.to("#myID", 1, {x:"100px"}). */ - static selector: (query: string) => any; - - /** [READ-ONLY] Target object (or array of objects) whose properties the tween affects. */ - target: any; - - /** The object that dispatches a "tick" event each time the engine updates, making it easy for you to add your own listener(s) to run custom logic after each update (great for game developers). */ - static ticker: any; - - /** Provides a simple way to call a function after a set amount of time (or frames). */ - static delayedCall(delay: number, callback: Function, params?: any[], scope?: any, useFrames?: boolean): TweenLite; - - /** Static method for creating a TweenLite instance that tweens backwards - you define the BEGINNING values and the current values are used as the destination values which is great for doing things like animating objects onto the screen because you can set them up initially the way you want them to look at the end of the tween and then animate in from elsewhere. */ - static from(target: any, duration: number, vars: any): TweenLite; - - /** Static method for creating a TweenLite instance that allows you to define both the starting and ending values (as opposed to to() and from() tweens which are based on the target's current values at one end or the other). */ - static fromTo(target: any, duration: number, fromVars: any, toVars: any): TweenLite; - - /** Returns an array containing all the tweens of a particular target (or group of targets) that have not been released for garbage collection yet which typically happens within a few seconds after the tween completes. */ - static getTweensOf(target: any, onlyActive?: boolean): TweenLite[]; - - /** [override] Clears any initialization data (like starting/ending values in tweens) which can be useful if, for example, you want to restart a tween without reverting to any previously recorded starting values. */ - invalidate(): TweenLite; - - /** Immediately kills all of the delayedCalls to a particular function. */ - static killDelayedCallsTo(func: Function): void; - - /** Kills all the tweens (or specific tweening properties) of a particular object or delayedCalls to a particular function. */ - static killTweensOf(target: any, onlyActive?: boolean, vars?: any): void; - - /** Permits you to control what happens when too much time elapses between two ticks (updates) of the engine, adjusting the core timing mechanism to compensate and avoid "jumps". */ - static lagSmoothing(threshold: number, adjustedLag: number): void; - - /** Forces a render of all active tweens which can be useful if, for example, you set up a bunch of from() tweens and then you need to force an immediate render (even of "lazy" tweens) to avoid a brief delay before things render on the very next tick. */ - static render(): void; - - /** Immediately sets properties of the target accordingly - essentially a zero-duration to() tween with a more intuitive name. */ - static set(target: any, vars: any): TweenLite; - - /** Static method for creating a TweenLite instance that animates to the specified destination values (from the current values). */ - static to(target: any, duration: number, vars: any): TweenLite; - - // INHERITANCE FROM ANIMATION - - /** Gets or sets the animation's initial delay which is the length of time in seconds (or frames for frames-based tweens) before the animation should begin. */ - delay(): number; - delay(value: number): TweenLite; - - /** Gets or sets the animation's duration, not including any repeats or repeatDelays (which are only available in TweenMax and TimelineMax). */ - duration(): number; - duration(value: number): TweenLite; - - /** Gets or sets an event callback like "onComplete", "onUpdate", "onStart", "onReverseComplete" or "onRepeat" (onRepeat only applies to TweenMax or TimelineMax instances) along with any parameters that should be passed to that callback. */ - eventCallback(type: string): Function; - eventCallback(type: string, callback: Function, params?: any[], scope?: any): TweenLite; - - /** Kills the animation entirely or in part depending on the parameters. */ - kill(vars?: any, target?: any): TweenLite; - - /** Pauses the instance, optionally jumping to a specific time. */ - pause(atTime?: any, suppressEvents?: boolean): TweenLite; - - /** Gets or sets the animation's paused state which indicates whether or not the animation is currently paused. */ - paused(): boolean; - paused(value: boolean): TweenLite; - - /** Begins playing forward, optionally from a specific time (by default playback begins from wherever the playhead currently is). */ - play(from?: any, suppressEvents?: boolean): TweenLite; - - /** Gets or sets the animations's progress which is a value between 0 and 1 indicating the position of the virtual playhead (excluding repeats) where 0 is at the beginning, 0.5 is at the halfway point, and 1 is at the end (complete). */ - progress(): number; - progress(value: number, suppressEvents?: boolean): TweenLite; - - /** Restarts and begins playing forward from the beginning. */ - restart(includeDelay?: boolean, suppressEvents?: boolean): TweenLite; - - /** Resumes playing without altering direction (forward or reversed), optionally jumping to a specific time first. */ - resume(from?: any, suppressEvents?: boolean): TweenLite; - - /** Reverses playback so that all aspects of the animation are oriented backwards including, for example, a tween's ease. */ - reverse(from?: any, suppressEvents?: boolean): TweenLite; - - /** Gets or sets the animation's reversed state which indicates whether or not the animation should be played backwards. */ - reversed(): boolean; - reversed(value: boolean): TweenLite; - - /** Jumps to a specific time without affecting whether or not the instance is paused or reversed. */ - seek(time: any, suppressEvents?: boolean): TweenLite; - - /** Gets or sets the time at which the animation begins on its parent timeline (after any delay that was defined). */ - startTime(): number; - startTime(value: number): TweenLite; - - /** Gets or sets the local position of the playhead (essentially the current time), described in seconds (or frames for frames-based animations) which will never be less than 0 or greater than the animation's duration. */ - time(): number; - time(value: number, suppressEvents?: boolean): TweenLite; - - /** Factor that's used to scale time in the animation where 1 = normal speed (the default), 0.5 = half speed, 2 = double speed, etc. */ - timeScale(): number; - timeScale(value: number): TweenLite; - - /** Gets or sets the animation's total duration including any repeats or repeatDelays (which are only available in TweenMax and TimelineMax). */ - totalDuration(): number; - totalDuration(value: number): TweenLite; - - /** Gets or sets the animation's total progress which is a value between 0 and 1 indicating the position of the virtual playhead (including repeats) where 0 is at the beginning, 0.5 is at the halfway point, and 1 is at the end (complete). */ - totalProgress(): number; - totalProgress(value: number, suppressEvents?: boolean): TweenLite; - - /** Gets or sets the position of the playhead according to the totalDuration which includes any repeats and repeatDelays (only available in TweenMax and TimelineMax). */ - totalTime(): number; - totalTime(time: number, suppressEvents?: boolean): TweenLite; -} \ No newline at end of file diff --git a/gsap/gsap-tests.ts b/gsap/gsap-tests.ts index 49d5ce19d0..f811ac1089 100644 --- a/gsap/gsap-tests.ts +++ b/gsap/gsap-tests.ts @@ -1,8 +1,8 @@ - +import { TweenLite } from 'gsap'; var tween = TweenLite .to(document.getElementById('some-div'), 1, { width: '200px', height: '200px' }) - .seek(0.5); \ No newline at end of file + .seek(0.5); diff --git a/gsap/index.d.ts b/gsap/index.d.ts index eb493dc9ec..cebefcf1c9 100644 --- a/gsap/index.d.ts +++ b/gsap/index.d.ts @@ -1,10 +1,15 @@ -// Type definitions for GSAP v1.19 +// Type definitions for GSAP 1.19 // Project: http://greensock.com/ -// Definitions by: VILIC VANE +// Definitions by: VILIC VANE , Robert S , Richard Fox // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /// -/// +/// +/// +/// +/// -export = TweenLite; +declare module 'gsap' { + export = gsap; +} diff --git a/gsap/tslint.json b/gsap/tslint.json new file mode 100644 index 0000000000..0b14fdec0d --- /dev/null +++ b/gsap/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "no-single-declare-module": false + } +} diff --git a/gulp-babel/gulp-babel-tests.ts b/gulp-babel/gulp-babel-tests.ts index b705c68850..4cd6ff0467 100644 --- a/gulp-babel/gulp-babel-tests.ts +++ b/gulp-babel/gulp-babel-tests.ts @@ -1,5 +1,3 @@ -/// - import babel = require('gulp-babel'); var x: NodeJS.ReadWriteStream = babel(); diff --git a/gulp-batch/gulp-batch-tests.ts b/gulp-batch/gulp-batch-tests.ts new file mode 100644 index 0000000000..a1e305c03b --- /dev/null +++ b/gulp-batch/gulp-batch-tests.ts @@ -0,0 +1,8 @@ +import * as gulp from "gulp"; +import * as batch from "gulp-batch"; + +gulp.task('default', function() { + gulp.watch([ 'lib/**', 'test/**' ], batch((events: any, cb: any) => { + events.on('data', console.log).on('end', cb); + })); +}); diff --git a/gulp-batch/index.d.ts b/gulp-batch/index.d.ts new file mode 100644 index 0000000000..a3be8e252e --- /dev/null +++ b/gulp-batch/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for gulp-batch 1.0 +// Project: https://github.com/floatdrop/gulp-batch +// Definitions by: Alvaro Menezes , Vinicius Salomao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function batch(opts?: any, cb?: any, errorHandler?: any): (event: any) => void; +declare namespace batch { } +export = batch; diff --git a/gulp-batch/tsconfig.json b/gulp-batch/tsconfig.json new file mode 100644 index 0000000000..eb09ea4f9c --- /dev/null +++ b/gulp-batch/tsconfig.json @@ -0,0 +1,22 @@ +{ + "files": [ + "index.d.ts", + "gulp-batch-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} \ No newline at end of file diff --git a/gulp-batch/tslint.json b/gulp-batch/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/gulp-batch/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/gulp-cheerio/gulp-cheerio-tests.ts b/gulp-cheerio/gulp-cheerio-tests.ts index 464abccead..e2d3bfe267 100644 --- a/gulp-cheerio/gulp-cheerio-tests.ts +++ b/gulp-cheerio/gulp-cheerio-tests.ts @@ -1,7 +1,3 @@ - - -/// - import cheerio = require('gulp-cheerio'); import gulp = require('gulp'); import Vinyl = require('vinyl'); diff --git a/gulp-dtsm/gulp-dtsm-tests.ts b/gulp-dtsm/gulp-dtsm-tests.ts index 54e12eff6a..dafc6b3468 100644 --- a/gulp-dtsm/gulp-dtsm-tests.ts +++ b/gulp-dtsm/gulp-dtsm-tests.ts @@ -1,6 +1,3 @@ - -/// - import * as dtsm from 'gulp-dtsm'; import * as gulp from 'gulp'; diff --git a/gulp-help/gulp-help-tests.ts b/gulp-help/gulp-help-tests.ts index 5d11bc23b7..ae7d0846e7 100644 --- a/gulp-help/gulp-help-tests.ts +++ b/gulp-help/gulp-help-tests.ts @@ -1,7 +1,3 @@ -/// - -'use strict'; - import gulpHelp = require('gulp-help'); var gulp = gulpHelp(require('gulp')); diff --git a/gulp-html-replace/gulp-html-replace-tests.ts b/gulp-html-replace/gulp-html-replace-tests.ts index 568fb481fd..9a21a53b84 100644 --- a/gulp-html-replace/gulp-html-replace-tests.ts +++ b/gulp-html-replace/gulp-html-replace-tests.ts @@ -1,7 +1,3 @@ - - -/// - import * as gulp from 'gulp'; import * as htmlreplace from 'gulp-html-replace'; diff --git a/gulp-useref/gulp-useref-tests.ts b/gulp-useref/gulp-useref-tests.ts index 1f1a152be0..9f2bd409d5 100644 --- a/gulp-useref/gulp-useref-tests.ts +++ b/gulp-useref/gulp-useref-tests.ts @@ -1,5 +1,3 @@ -/// - import * as gulp from 'gulp'; import * as useref from 'gulp-useref'; diff --git a/gulp/index.d.ts b/gulp/index.d.ts index 89b1a5dfa5..9f3e7d96ba 100644 --- a/gulp/index.d.ts +++ b/gulp/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Gulp v3.8.x +// Type definitions for Gulp v4.0.x // Project: http://gulpjs.com -// Definitions by: Drew Noakes +// Definitions by: Drew Noakes , Juan Arroyave // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -11,6 +11,8 @@ import Orchestrator = require("orchestrator"); import VinylFile = require("vinyl"); +declare type Strings = string|string[]; + declare namespace gulp { interface Gulp extends Orchestrator { /** @@ -24,6 +26,28 @@ declare namespace gulp { * */ task: Orchestrator.AddMethod; + /** + * Takes a number of task names or functions and returns a function of the composed tasks or functions + * When the returned function is executed, the tasks or functions will be executed in series, + * each waiting for the prior to finish. If an error occurs, execution will stop. + * @param A task name, a function or an array of either. + *
      + *
    • Take in a callback
    • + *
    • Return a stream or a promise
    • + *
    + */ + series: SeriesMethod; + /** + * Takes a number of task names or functions and returns a function of the composed tasks or functions + * When the returned function is executed, the tasks or functions will be executed in parallel, + * all being executed at the same time. If an error occurs, all execution will complete. + * @param A task name, a function or an array of either. + *
      + *
    • Take in a callback
    • + *
    • Return a stream or a promise
    • + *
    + */ + parallel: ParallelMethod; /** * Emits files matching provided glob or an array of globs. Returns a stream of Vinyl files that can be piped to plugins. * @param glob Glob or array of globs to read. @@ -105,6 +129,51 @@ declare namespace gulp { */ (glob: string|string[], opt?: SrcOptions): NodeJS.ReadWriteStream; } + interface SeriesMethod { + /** + * Takes a number of task names or functions and returns a function of the composed tasks or functions. + * When using task names, the task should already be registered. + * When the returned function is executed, the tasks or functions will be executed in series, + * each waiting for the prior to finish. If an error occurs, execution will stop. + * @param tasks, string, function or array of both. + */ + (...tasks: string[]): NodeJS.EventEmitter; + + (...tasks: Function[]): NodeJS.EventEmitter; + + (task: string|string[], ...fn: Function[]): NodeJS.EventEmitter; + + //TODO: TypeScript cannot express varargs followed by callback as a last argument... + (task1: Strings, task2: Strings, cb?: (error?: any) => any): Function; + (task1: Strings, task2: Strings, task3: Strings, cb?: (error?: any) => any): NodeJS.EventEmitter; + (task1: Strings, task2: Strings, task3: Strings, task4: Strings, cb?: (error?: any) => any): NodeJS.EventEmitter; + (task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, cb?: (error?: any) => any): NodeJS.EventEmitter; + (task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, task6: Strings, cb?: (error?: any) => any): NodeJS.EventEmitter; + + } + + interface ParallelMethod { + /** + * Takes a number of task names or functions and returns a function of the composed tasks or functions. + * When using task names, the task should already be registered. + * When the returned function is executed, the tasks or functions will be executed in parallel, + * all being executed at the same time. If an error occurs, all execution will complete. + * @param tasks, string, function or array of both. + */ + (...tasks: string[]): NodeJS.EventEmitter; + + (...tasks: Function[]): NodeJS.EventEmitter; + + (task: string|string[], ...fn: Function[]): NodeJS.EventEmitter; + + //TODO: TypeScript cannot express varargs followed by callback as a last argument... + (task1: Strings, task2: Strings, cb?: (error?: any) => any): Function; + (task1: Strings, task2: Strings, task3: Strings, cb?: (error?: any) => any): NodeJS.EventEmitter; + (task1: Strings, task2: Strings, task3: Strings, task4: Strings, cb?: (error?: any) => any): NodeJS.EventEmitter; + (task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, cb?: (error?: any) => any): NodeJS.EventEmitter; + (task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, task6: Strings, cb?: (error?: any) => any): NodeJS.EventEmitter; + + } /** * Options to pass to node-glob through glob-stream. diff --git a/hammerjs/v1/hammerjs-tests.ts b/hammerjs/v1/hammerjs-tests.ts index bb006241fe..60d990c0bd 100644 --- a/hammerjs/v1/hammerjs-tests.ts +++ b/hammerjs/v1/hammerjs-tests.ts @@ -1,6 +1,3 @@ -/// - - // plugin check if (!Hammer.HAS_TOUCHEVENTS && !Hammer.HAS_POINTEREVENTS) { Hammer.plugins.fakeMultitouch(); diff --git a/handlebars/index.d.ts b/handlebars/index.d.ts index 96b0491040..d3ab2c80e3 100644 --- a/handlebars/index.d.ts +++ b/handlebars/index.d.ts @@ -10,6 +10,9 @@ declare namespace Handlebars { export function registerPartial(name: string, str: any): void; export function unregisterHelper(name: string): void; export function unregisterPartial(name: string): void; + export function registerDecorator(name: string, fn: Function): void; + export function unregisterDecorator(name: string): void; + export function K(): void; export function createFrame(object: any): any; export function Exception(message: string): void; @@ -26,7 +29,9 @@ declare namespace Handlebars { export var Utils: typeof hbs.Utils; export var logger: Logger; export var templates: HandlebarsTemplates; - export var helpers: any; + export var helpers: { [name: string]: Function }; + export var partials: { [name: string]: any }; + export var decorators: { [name: string]: Function }; export function registerDecorator(name: string, fn: Function): void; export function registerDecorator(obj: {[name: string] : Function}): void; diff --git a/handsontable/handsontable-tests.ts b/handsontable/handsontable-tests.ts index eb48441244..f744c10483 100644 --- a/handsontable/handsontable-tests.ts +++ b/handsontable/handsontable-tests.ts @@ -16,7 +16,7 @@ function test_HandsontableInit() { autoWrapRow: true, bindRowsWithHeaders: 'foo', cell: [], - cells: function() {}, + cells: () => { return; }, checkedTemplate: true, className: [], colHeaders: true, @@ -99,7 +99,7 @@ function test_HandsontableInit() { selectOptions: [], skipColumnOnPaste: true, sortByRelevance: true, - sortFunction: function() {}, + sortFunction: () => { return; }, sortIndicator: true, source: [], startCols: 123, @@ -114,7 +114,7 @@ function test_HandsontableInit() { type: 'foo', uncheckedTemplate: true, undo: true, - validator: function() {}, + validator: () => {return; }, viewportColumnRenderingOffset: 123, viewportRowRenderingOffset: 123, visibleRows: 123, @@ -122,86 +122,86 @@ function test_HandsontableInit() { wordWrap: true, // Hooks - afterAutofillApplyValues: function() {}, - afterCellMetaReset: function() {}, - afterChange: function() {}, - afterChangesObserved: function() {}, - afterColumnMove: function() {}, - afterColumnResize: function() {}, - afterColumnSort: function() {}, - afterContextMenuDefaultOptions: function() {}, - afterContextMenuHide: function() {}, - afterContextMenuShow: function() {}, - afterCopyLimit: function() {}, - afterCreateCol: function() {}, - afterCreateRow: function() {}, - afterDeselect: function() {}, - afterDestroy: function() {}, - afterDocumentKeyDown: function() {}, - afterFilter: function() {}, - afterGetCellMeta: function() {}, - afterGetColHeader: function() {}, - afterGetColumnHeaderRenderers: function() {}, - afterGetRowHeader: function() {}, - afterGetRowHeaderRenderers: function() {}, - afterInit: function() {}, - afterLoadData: function() {}, - afterMomentumScroll: function() {}, - afterOnCellCornerMouseDown: function() {}, - afterOnCellMouseDown: function() {}, - afterOnCellMouseOver: function() {}, - afterRemoveCol: function() {}, - afterRemoveRow: function() {}, - afterRender: function() {}, - afterRenderer: function() {}, - afterRowMove: function() {}, - afterRowResize: function() {}, - afterScrollHorizontally: function() {}, - afterScrollVertically: function() {}, - afterSelection: function() {}, - afterSelectionByProp: function() {}, - afterSelectionEnd: function() {}, - afterSelectionEndByProp: function() {}, - afterSetCellMeta: function() {}, - afterUpdateSettings: function() {}, - afterValidate: function() {}, - beforeAutofill: function() {}, - beforeCellAlignment: function() {}, - beforeChange: function() {}, - beforeChangeRender: function() {}, - beforeColumnMove: function() {}, - beforeColumnResize: function() {}, - beforeColumnSort: function() {}, - beforeDrawBorders: function() {}, - beforeFilter: function() {}, - beforeGetCellMeta: function() {}, - beforeInit: function() {}, - beforeInitWalkontable: function() {}, - beforeKeyDown: function() {}, - beforeOnCellMouseDown: function() {}, - beforeRemoveCol: function() {}, - beforeRemoveRow: function() {}, - beforeRender: function() {}, - beforeRenderer: function() {}, - beforeRowMove: function() {}, - beforeRowResize: function() {}, - beforeSetRangeEnd: function() {}, - beforeStretchingColumnWidth: function() {}, - beforeTouchScroll: function() {}, - beforeValidate: function() {}, - construct: function() {}, - init: function() {}, - modifyCol: function() {}, - modifyColHeader: function() {}, - modifyColWidth: function() {}, - modifyCopyableRange: function() {}, - modifyRow: function() {}, - modifyRowHeader: function() {}, - modifyRowHeight: function() {}, - persistentStateLoad: function() {}, - persistentStateReset: function() {}, - persistentStateSave: function() {}, - unmodifyCol: function() {} + afterAutofillApplyValues: () => {return; }, + afterCellMetaReset: () => {return; }, + afterChange: () => {return; }, + afterChangesObserved: () => {return; }, + afterColumnMove: () => {return; }, + afterColumnResize: () => {return; }, + afterColumnSort: () => {return; }, + afterContextMenuDefaultOptions: () => {return; }, + afterContextMenuHide: () => {return; }, + afterContextMenuShow: () => {return; }, + afterCopyLimit: () => {return; }, + afterCreateCol: () => {return; }, + afterCreateRow: () => {return; }, + afterDeselect: () => {return; }, + afterDestroy: () => {return; }, + afterDocumentKeyDown: () => {return; }, + afterFilter: () => {return; }, + afterGetCellMeta: () => {return; }, + afterGetColHeader: () => {return; }, + afterGetColumnHeaderRenderers: () => {return; }, + afterGetRowHeader: () => {return; }, + afterGetRowHeaderRenderers: () => {return; }, + afterInit: () => {return; }, + afterLoadData: () => {return; }, + afterMomentumScroll: () => {return; }, + afterOnCellCornerMouseDown: () => {return; }, + afterOnCellMouseDown: () => {return; }, + afterOnCellMouseOver: () => {return; }, + afterRemoveCol: () => {return; }, + afterRemoveRow: () => {return; }, + afterRender: () => {return; }, + afterRenderer: () => {return; }, + afterRowMove: () => {return; }, + afterRowResize: () => {return; }, + afterScrollHorizontally: () => {return; }, + afterScrollVertically: () => {return; }, + afterSelection: () => {return; }, + afterSelectionByProp: () => {return; }, + afterSelectionEnd: () => {return; }, + afterSelectionEndByProp: () => {return; }, + afterSetCellMeta: () => {return; }, + afterUpdateSettings: () => {return; }, + afterValidate: () => {return; }, + beforeAutofill: () => {return; }, + beforeCellAlignment: () => {return; }, + beforeChange: () => {return; }, + beforeChangeRender: () => {return; }, + beforeColumnMove: () => {return; }, + beforeColumnResize: () => {return; }, + beforeColumnSort: () => {return; }, + beforeDrawBorders: () => {return; }, + beforeFilter: () => {return; }, + beforeGetCellMeta: () => {return; }, + beforeInit: () => {return; }, + beforeInitWalkontable: () => {return; }, + beforeKeyDown: () => {return; }, + beforeOnCellMouseDown: () => {return; }, + beforeRemoveCol: () => {return; }, + beforeRemoveRow: () => {return; }, + beforeRender: () => {return; }, + beforeRenderer: () => {return; }, + beforeRowMove: () => {return; }, + beforeRowResize: () => {return; }, + beforeSetRangeEnd: () => {return; }, + beforeStretchingColumnWidth: () => {return; }, + beforeTouchScroll: () => {return; }, + beforeValidate: () => {return; }, + construct: () => {return; }, + init: () => {return; }, + modifyCol: () => {return; }, + modifyColHeader: () => {return; }, + modifyColWidth: () => {return; }, + modifyCopyableRange: () => {return; }, + modifyRow: () => {return; }, + modifyRowHeader: () => {return; }, + modifyRowHeight: () => {return; }, + persistentStateLoad: () => {return; }, + persistentStateReset: () => {return; }, + persistentStateSave: () => {return; }, + unmodifyCol: () => {return; } }); } @@ -269,10 +269,10 @@ function test_HandsontableMethods() { hot.propToCol('foo'); hot.propToCol(123); hot.removeCellMeta(123, 123, 'foo'); - hot.removeHook('foo', function() {}); + hot.removeHook('foo', () => {return; }); hot.render(); hot.rowOffset(); - hot.runHooks('foo', 123, 'foo', true, {}, [], function() {}); + hot.runHooks('foo', 123, 'foo', true, {}, [], () => {return; }); hot.selectCell(123, 123, 123, 123, true, true); hot.selectCellByProp(123, 'foo', 123, 'foo', true); hot.setCellMeta(123, 123, 'foo', 'foo'); @@ -281,11 +281,21 @@ function test_HandsontableMethods() { hot.setDataAtRowProp(123, 'foo', 'foo', 'foo'); hot.spliceCol(123, 123, 123, 'foo'); hot.spliceRow(123, 123, 123, 'foo'); + hot.toPhysicalRow(123); + hot.toPhysicalColumn(123); + hot.toVisualRow(123); + hot.toVisualColumn(123); hot.unlisten(); hot.updateSettings({}, true); - hot.validateCells(function() {}); - + hot.validateCells(() => {return; }); + Handsontable.renderers.NumericRenderer(hot, new HTMLTableDataCellElement(), 0, 0, "prop", 1.235, {}); Handsontable.renderers.TextRenderer(hot, new HTMLTableDataCellElement(), 0, 0, "prop", 1.235, {}); - Handsontable.Dom.addEvent(new HTMLElement(), "eventName", () => {}); + Handsontable.Dom.addEvent(new HTMLElement(), "eventName", () => { return; }); } + +class MyCustomHotPlugin extends Handsontable.plugins.BasePlugin { + isEnabled(): boolean { + return !!this.hot.getSettings().manualRowMove; + } +} \ No newline at end of file diff --git a/handsontable/index.d.ts b/handsontable/index.d.ts index eeef57394e..e569ee58f7 100644 --- a/handsontable/index.d.ts +++ b/handsontable/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Handsontable 0.24.3 +// Type definitions for Handsontable 0.30 // Project: https://handsontable.com/ // Definitions by: Handsoncode sp. z o.o. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\ @@ -251,7 +251,7 @@ declare namespace ht { getSchema(): Object; getSelected(): any[]; getSelectedRange(): Range; - getSettings(): Object; + getSettings(): Options; getSourceData(r?: number, c?: number, r2?: number, c2?: number): any[]; getSourceDataAtCell(row: number, column: number): any; getSourceDataAtCol(column: number): any[]; @@ -280,8 +280,12 @@ declare namespace ht { setDataAtRowProp(row: number|any[], prop: string, value: string, source?: string): void; spliceCol(col: number, index: number, amount: number, elements?: any): void; spliceRow(row: number, index: number, amount: number, elements?: any): void; + toPhysicalRow(row: number): number; + toPhysicalColumn(column: number): number; + toVisualRow(row: number): number; + toVisualColumn(column: number): number; unlisten(): void; - updateSettings(settings: Object, init: boolean): void; + updateSettings(settings: Object, init?: boolean): void; validateCells(callback: Function): void; } @@ -302,61 +306,215 @@ declare namespace ht { } interface ColumnProperties extends CellProperties { - data?: string; - editor?: string; + data?: string | number; + title?: string; + editor?: string | EditorConstructor; selectOptions?: any[]; + width?: number; + } interface CellProperties { - renderer?: ( - instance: Methods, - td: HTMLTableDataCellElement, - row: number, - col: number, - prop: string, - value: any, - tdCellProperties: Object) => void; + renderer?: CellRenderer; type?: string; readOnly?: boolean; language?: string; format?: string; - validator?: (value: string, callback: (condition: boolean) => void) => void; + validator?: Validator; + allowInvalid?: boolean; + className?: string; } interface CellPosition { row: number; col: number; } + + // so that you can write custom plugins in typescript + interface BasePlugin { + init(): void; + enablePlugin(): void; + disablePlugin(): void; + addHook(name: string, callback: Function): void; + removeHooks(name: string): void; + clearHooks(): void; + callOnPluginsReady(callback: Function): void; + updatePlugin(): void; + destroy(): void; + enabled: boolean; + hot: Methods; + } + + interface PluginConstructor { + new (hotInstance: Methods): BasePlugin; + } + + interface ContextMenuPluginConstructor extends PluginConstructor { + SEPARATOR: string; + } + + interface Plugins { + AutoColumnSize: PluginConstructor; + AutoRowSizeAutoRowSize: PluginConstructor; + BasePlugin: PluginConstructor; + BindRowsWithHeaders: PluginConstructor; + CollapsibleColumns: PluginConstructor; + ColumnSorting: PluginConstructor; + ColumnSummary: PluginConstructor; + Comments: PluginConstructor; + ContextMenu: ContextMenuPluginConstructor; + ContextMenuCopyPaste: PluginConstructor; + DragToScroll: PluginConstructor; + DropdownMenu: PluginConstructor; + ExportFile: PluginConstructor; + Filters: PluginConstructor; + Formulas: PluginConstructor; + GanttChart: PluginConstructor; + HeaderTooltips: PluginConstructor; + HiddenColumns: PluginConstructor; + HiddenRows: PluginConstructor; + ManualColumnFreeze: PluginConstructor; + ManualColumnMove: PluginConstructor; + ManualColumnResize: PluginConstructor; + ManualRowMove: PluginConstructor; + ManualRowResize: PluginConstructor; + MultipleSelectionHandles: PluginConstructor; + NestedHeaders: PluginConstructor; + NestedRows: PluginConstructor; + ObserveChanges: PluginConstructor; + TouchScroll: PluginConstructor; + TrimRows: PluginConstructor; + registerPlugin(pluginName: string, PluginClass: PluginConstructor): void; + } + + interface Hooks { + register(key: string): void; + run(instace: ht.Methods, hookName: string, key?: any, value?: any): any; + } + + interface Dom { + addEvent(element: HTMLElement, eventName: string, callback: Function): void; + addClass(element: HTMLElement, className: string | string[]): void; + removeClass(element: HTMLElement, className: string | string[]): void; + offset(element: HTMLElement): any; + getWindowScrollLeft(): number; + getWindowScrollTop(): number; + outerHeight(element: HTMLElement): number; + hasClass(element: HTMLElement, className: string): boolean | undefined; + } + + interface ArrayMapper { + clearMap(): void; + getIndexByValue(value: any): number; + getValueByIndex(index: number): any; + insertItems(index: number, amount?: number): number[]; + removeItems(index: number | number[], amount?: number): number[]; + unshiftItems(index: number | number[], amount?: number): void; + shiftItems(index: number, amount?: number): void; + } + + interface Utils { + arrayMapper: ArrayMapper; + } + + interface Helper { + arrayFilter(array: any[], predicate: Function): any[]; + arrayEach(array: any[], predicate: Function): void; + arrayMap(array: any[], predicate: Function): any[]; + arrayReduce(array: any[], predicate: Function, initialValue?: any): any; + objectEach(obj: any, predicate: Function): void; + rangeEach(rangeFrom: number, rangeTo: number | Function, iteratee?: Function): void; + mixin(Base: any, ...mixins: any[]): void; + isNumeric(number: any): boolean; + createSpreadsheetData(rows: number, columns: number): any; + } + + type CellRenderer = ( + instance: Methods, + td: HTMLTableCellElement, + row: number, + col: number, + prop: string, + value: any, + cellProperties: any) => void; + + interface Editor { + open(): void; + } + + interface EditorConstructor { + new (instance: Methods): Editor; + } + + interface Editors { + TextEditor: EditorConstructor; + } + + type Validator = (value: string, callback: (condition: boolean) => void) => void; + + interface Renderers { + TextRenderer: CellRenderer; + NumericRenderer: CellRenderer; + AutocompleteRenderer: CellRenderer; + } + + type AsyncAutocompleteSourceFunction = (query: string, process: (values: any[]) => void) => void; + + interface AutocompleteColumn extends ColumnProperties { + source?: any[] | AsyncAutocompleteSourceFunction; + strict?: boolean; + trimDropdown?: boolean; + } + + interface DateColumn extends ColumnProperties { + dateFormat?: string; + correctFormat?: boolean; + } + + interface NumericColumn extends ColumnProperties { + format?: string; + language?: string; + } + + interface CheckboxColumnLabel { + position?: 'before' | 'after'; + property?: string; + value: string; + } + + interface CheckboxColumn extends ColumnProperties { + checkedTemplate?: any; + uncheckedTemplate?: any; + label?: CheckboxColumnLabel; + } + + type CellMetaFunction = (row: number, column: number, prop: string) => void; + + type DropdownColumn = AutocompleteColumn; } - declare var Handsontable: { - new (element: Element, options: ht.Options): ht.Methods; - renderers: { - TextRenderer( - instance: any, - td: HTMLTableCellElement, - row: number, - col: number, - prop: string, - value: any, - cellProperties: any): void; - NumericRenderer( - instance: any, - td: HTMLTableCellElement, - row: number, - col: number, - prop: string, - value: any, - cellProperties: any): void; - } - Dom: { - addEvent(element: HTMLElement, eventName: string, callback: Function): void; - } + new (element: Element, options: ht.Options): ht.Methods; + plugins: ht.Plugins; + hooks: ht.Hooks; + Dom: ht.Dom; + dom: ht.Dom; + helper: ht.Helper; + utils: ht.Utils; + renderers: ht.Renderers; + editors: ht.Editors; }; declare module "handsontable" { export var Handsontable: { new (element: Element, options: ht.Options): ht.Methods; + plugins: ht.Plugins; + hooks: ht.Hooks; + Dom: ht.Dom; + dom: ht.Dom; + helper: ht.Helper; + utils: ht.Utils; + renderers: ht.Renderers; + editors: ht.Editors; }; } diff --git a/handsontable/tslint.json b/handsontable/tslint.json new file mode 100644 index 0000000000..14c6526bd1 --- /dev/null +++ b/handsontable/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false, + "no-single-declare-module": false + } +} \ No newline at end of file diff --git a/hapi-auth-jwt2/tsconfig.json b/hapi-auth-jwt2/tsconfig.json index 3bbd249dc8..727deb9122 100644 --- a/hapi-auth-jwt2/tsconfig.json +++ b/hapi-auth-jwt2/tsconfig.json @@ -19,4 +19,4 @@ "index.d.ts", "hapi-auth-jwt2-tests.ts" ] -} \ No newline at end of file +} diff --git a/har-format/har-format-tests.ts b/har-format/har-format-tests.ts new file mode 100644 index 0000000000..9a226d150c --- /dev/null +++ b/har-format/har-format-tests.ts @@ -0,0 +1,101 @@ +import * as harFormat from "har-format"; + +const testCreator: harFormat.Creator = { + name: "WebInspector", + version: "537.36" +}; + +const testPageTiming: harFormat.PageTiming = { + onContentLoad: 1995.6460000003062, + onLoad: 4262.566999999763 +}; + +const testPage: harFormat.Page = { + startedDateTime: "2017-02-11T09:36:22.868Z", + id: "page_1", + title: "https://github.com/", + pageTimings: testPageTiming +}; + +const testHeader: harFormat.Header = { + name: "Accept", + value: "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" +}; + +const testRequest: harFormat.Request = { + method: "GET", + url: "https://github.com/", + httpVersion: "HTTP/1.1", + headers: [testHeader], + queryString: [], + cookies: [], + headersSize: 425, + bodySize: 0 +}; + +const testHeaders: harFormat.Header = { + name: "Content-Encoding", + value: "gzip" +}; + +const testCookie: harFormat.Cookie = { + name: "logged_in", + value: "no", + path: "/", + domain: ".github.com", + expires: "2037-02-11T09:36:23.000Z", + httpOnly: true, + secure: true +}; + +const testContent: harFormat.Content = { + size: 26915, + mimeType: "text/html", + compression: 18635 +}; + +const testResponse: harFormat.Response = { + status: 200, + statusText: "OK", + httpVersion: "HTTP/1.1", + headers: [testHeaders], + cookies: [testCookie], + content: testContent, + redirectURL: "", + headersSize: 2084, + bodySize: 8280, + _transferSize: 10364 +}; + +const testTimings: harFormat.Timings = { + blocked: 0.439999999798602, + dns: 39.6150000005946, + connect: 483.8799999997718, + send: 0.06899999971199122, + wait: 287.516999999753, + receive: 5.289000000629585, + ssl: 244.02999999983808 +}; + +const testEntry: harFormat.Entry = { + startedDateTime: "2017-02-11T09:36:22.868Z", + time: 816.8100000002596, + request: testRequest, + response: testResponse, + cache: {}, + timings: testTimings, + serverIPAddress: "192.30.253.113", + connection: "26487", + pageref: "page_1" +}; + +const testLog: harFormat.Log = { + version: "1.2", + creator: testCreator, + pages: [testPage], + entries: [testEntry] +}; + +const harFile: harFormat.Har = { + log: testLog +}; diff --git a/har-format/index.d.ts b/har-format/index.d.ts new file mode 100644 index 0000000000..7aaf479891 --- /dev/null +++ b/har-format/index.d.ts @@ -0,0 +1,811 @@ +// Type definitions for HAR 1.2 +// Project: https://w3c.github.io/web-performance/specs/HAR/Overview.html +// Definitions by: Michael Mrowetz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +/** + * HTTP Archive 1.2 + * + * http://www.softwareishard.com/blog/har-12-spec + */ +export interface Har { + /** This object represents the root of exported data. */ + "log": Log; +} +/** + * This object (`log`) represents the root of exported data. + * + * http://www.softwareishard.com/blog/har-12-spec/#log + */ +export interface Log { + /** + * Version number of the format. + * + * _If empty, string "1.1" is assumed by default._ + */ + version: string; + /** Name and version info of the log creator application. */ + creator: Creator; + /** Name and version info of used browser. */ + browser?: Browser; + /** + * List of all exported (tracked) pages. + * + * _Leave out this field if the application + * does not support grouping by pages._ + * + * There is one `` object for every exported web page and one + * `` object for every HTTP request. + * In case when an HTTP trace tool isn't able to group requests by a page, + * the `` object is empty and individual requests doesn't have a + * parent page. + */ + pages?: Page[]; + /** List of all exported (tracked) requests. */ + entries: Entry[]; + /** A comment provided by the user or the application. */ + comment?: string; +} +/** + * Infos about application/browser used to export the log. + * + * `Creator` and `Browser` objects share the same structure. + * + * http://www.softwareishard.com/blog/har-12-spec/#creator + */ +export interface Creator { + /** Name of the application/browser used to export the log. */ + name: string; + /** Version of the application/browser used to export the log. */ + version: string; + /** A comment provided by the user or the application. */ + comment?: string; +} +/** + * Infos about application/browser used to export the log. + * + * `Browser` and `Creator` objects share the same structure. + * + * http://www.softwareishard.com/blog/har-12-spec/#browser + */ +export interface Browser { + /** Name of the application/browser used to export the log. */ + name: string; + /** Version of the application/browser used to export the log. */ + version: string; + /** A comment provided by the user or the application. */ + comment?: string; +} +/** + * This object represents list of exported pages. + * + * http://www.softwareishard.com/blog/har-12-spec/#pages + */ +export interface Page { + /** Date and time stamp for the beginning of the page load + * + * (ISO 8601 - `YYYY-MM-DDThh:mm:ss.sTZD`, + * e.g. `2009-07-24T19:20:30.45+01:00`). + */ + startedDateTime: string; + /** + * Unique identifier of a page within the `` (HAR doc). + * Entries use it to refer the parent page. + */ + id: string; + /** Page title. */ + title: string; + /** Detailed timing info about page load */ + pageTimings: PageTiming; + /** A comment provided by the user or the application */ + comment?: string; + /** _non-standard_ */ + /** _non-standard_ */ + _adult_site?: number; + /** _non-standard_ */ + _aft?: number; + /** _non-standard_ */ + _base_page_cdn?: string; + /** _non-standard_ */ + _base_page_redirects?: number; + /** _non-standard_ */ + _base_page_ttfb?: number; + /** _non-standard_ */ + _browser_main_memory_kb?: number; + /** _non-standard_ */ + _browser_name?: string; + /** _non-standard_ */ + _browser_other_private_memory_kb?: number; + /** _non-standard_ */ + _browser_process_count?: number; + /** _non-standard_ */ + _browser_version?: string; + /** _non-standard_ */ + _browser_working_set_kb?: number; + /** _non-standard_ */ + _bytesIn?: number; + /** _non-standard_ */ + _bytesInDoc?: number; + /** _non-standard_ */ + _bytesOut?: number; + /** _non-standard_ */ + _bytesOutDoc?: number; + /** _non-standard_ */ + _cached?: number; + /** _non-standard_ */ + _certificate_bytes?: number; + /** _non-standard_ */ + _connections?: number; + /** _non-standard_ */ + _date?: number; + /** _non-standard_ */ + _docCPUms?: number; + /** _non-standard_ */ + _docCPUpct?: number; + /** _non-standard_ */ + _docTime?: number; + /** _non-standard_ */ + _domContentLoadedEventEnd?: number; + /** _non-standard_ */ + _domContentLoadedEventStart?: number; + /** _non-standard_ */ + _domElements?: number; + /** _non-standard_ */ + _domInteractive?: number; + /** _non-standard_ */ + _domLoading?: number; + /** _non-standard_ */ + _domTime?: number; + /** _non-standard_ */ + _effectiveBps?: number; + /** _non-standard_ */ + _effectiveBpsDoc?: number; + /** _non-standard_ */ + _eventName?: string; + /** _non-standard_ */ + _firstPaint?: number; + /** _non-standard_ */ + _fixed_viewport?: number; + /** _non-standard_ */ + _fullyLoaded?: number; + /** _non-standard_ */ + _fullyLoadedCPUms?: number; + /** _non-standard_ */ + _fullyLoadedCPUpct?: number; + /** _non-standard_ */ + _gzip_savings?: number; + /** _non-standard_ */ + _gzip_total?: number; + /** _non-standard_ */ + _image_savings?: number; + /** _non-standard_ */ + _image_total?: number; + /** _non-standard_ */ + _isResponsive?: number; + /** _non-standard_ */ + _lastVisualChange?: number; + /** _non-standard_ */ + _loadEventEnd?: number; + /** _non-standard_ */ + _loadEventStart?: number; + /** _non-standard_ */ + _loadTime?: number; + /** _non-standard_ */ + _minify_savings?: number; + /** _non-standard_ */ + _minify_total?: number; + /** _non-standard_ */ + _optimization_checked?: number; + /** _non-standard_ */ + _pageSpeedVersion?: string; + /** _non-standard_ */ + _render?: number; + /** _non-standard_ */ + _requests?: number; + /** _non-standard_ */ + _requestsDoc?: number; + /** _non-standard_ */ + _requestsFull?: number; + /** _non-standard_ */ + _responses_200?: number; + /** _non-standard_ */ + _responses_404?: number; + /** _non-standard_ */ + _responses_other?: number; + /** _non-standard_ */ + _result?: number; + /** _non-standard_ */ + _run?: number; + /** _non-standard_ */ + _score_cache?: number; + /** _non-standard_ */ + _score_cdn?: number; + /** _non-standard_ */ + _score_combine?: number; + /** _non-standard_ */ + _score_compress?: number; + /** _non-standard_ */ + _score_cookies?: number; + /** _non-standard_ */ + _score_etags?: number; + /** _non-standard_ */ + _score_gzip?: number; + /** _non-standard_ */ + "_score_keep-alive"?: number; + /** _non-standard_ */ + _score_minify?: number; + /** _non-standard_ */ + _score_progressive_jpeg?: number; + /** _non-standard_ */ + _server_count?: number; + /** _non-standard_ */ + _server_rtt?: number; + /** _non-standard_ */ + _SpeedIndex?: number; + /** _non-standard_ */ + _step?: number; + /** _non-standard_ */ + _title?: string; + /** _non-standard_ */ + _titleTime?: number; + /** _non-standard_ */ + _TTFB?: number; + /** _non-standard_ */ + _URL?: string; + /** _non-standard_ */ + _visualComplete?: number; +} +/** + * This object describes timings for various events (states) fired during the + * page load. + * + * All times are specified in milliseconds. + * + * If a time info is not available appropriate field is set to `-1`. + * + * http://www.softwareishard.com/blog/har-12-spec/#pageTimings + */ +export interface PageTiming { + /** Content of the page loaded. Number of milliseconds since page load + * started (`page.startedDateTime`). + * + * Use `-1` if the timing does not apply to the current request. + */ + onContentLoad?: number; + /** Page is loaded (`onLoad` event fired). Number of milliseconds since + * page load started (`page.startedDateTime`). + * + * Use `-1` if the timing does not apply to the current request. + */ + onLoad?: number; + /** A comment provided by the user or the application */ + comment?: string; + _startRender?: number; +} +/** + * This object represents an array with all exported HTTP requests. Sorting + * entries by `startedDateTime` (starting from the oldest) is preferred way how + * to export data since it can make importing faster. + * However the reader application should always make sure the array is sorted + * (if required for the import). + * + * http://www.softwareishard.com/blog/har-12-spec/#entries + */ +export interface Entry { + /** + * Reference to the parent page. Leave out this field if the application + * does not support grouping by pages. + */ + pageref?: string; + /** + * Date and time stamp of the request start + * + * (ISO 8601 - `YYYY-MM-DDThh:mm:ss.sTZD`). + */ + startedDateTime: string; + /** + * Total elapsed time of the request in milliseconds. + * + * This is the sum of all timings available in the timings object + * (i.e. not including `-1` values). + */ + time: number; + /** Detailed info about the request. */ + request: Request; + /** Detailed info about the response. */ + response: Response; + /** Info about cache usage. */ + cache: Cache; + /** Detailed timing info about request/response round trip. */ + timings: Timings; + /** + * IP address of the server that was connected + * (result of DNS resolution). + */ + serverIPAddress?: string; + /** + * Unique ID of the parent TCP/IP connection, can be the client or server + * port number. + * + * Note that a port number doesn't have to be unique identifier + * in cases where the port is shared for more connections. + * + * If the port isn't available for the application, any other unique + * connection ID can be used instead (e.g. connection index). Leave out + * this field if the application doesn't support this info. + */ + connection?: string; + /** A comment provided by the user or the application */ + comment?: string; + /** _non-standard_ */ + _all_end?: number | string; + /** _non-standard_ */ + _all_ms?: number | string; + /** _non-standard_ */ + _all_start?: number | string; + /** _non-standard_ */ + _bytesIn?: number | string; + /** _non-standard_ */ + _bytesOut?: number | string; + /** _non-standard_ */ + _cacheControl?: string; + /** _non-standard_ */ + _cache_time?: number | string; + /** _non-standard_ */ + _cdn_provider?: string; + /** _non-standard_ */ + _certificate_bytes?: number | string; + /** _non-standard_ */ + _client_port?: number | string; + /** _non-standard_ */ + _connect_end?: number | string; + /** _non-standard_ */ + _connect_ms?: number | string; + /** _non-standard_ */ + _connect_start?: number | string; + /** _non-standard_ */ + _contentEncoding?: string; + /** _non-standard_ */ + _contentType?: string; + /** _non-standard_ */ + _dns_end?: number | string; + /** _non-standard_ */ + _dns_ms?: number | string; + /** _non-standard_ */ + _dns_start?: number | string; + /** _non-standard_ */ + _download_end?: number | string; + /** _non-standard_ */ + _download_ms?: number | string; + /** _non-standard_ */ + _download_start?: number | string; + /** _non-standard_ */ + _expires?: string; + /** _non-standard_ */ + _full_url?: string; + /** _non-standard_ */ + _gzip_save?: number | string; + /** _non-standard_ */ + _gzip_total?: number | string; + /** _non-standard_ */ + _host?: string; + /** _non-standard_ */ + _http2_stream_dependency?: number | string; + /** _non-standard_ */ + _http2_stream_exclusive?: number | string; + /** _non-standard_ */ + _http2_stream_id?: number | string; + /** _non-standard_ */ + _http2_stream_weight?: number | string; + /** _non-standard_ */ + _image_save?: number | string; + /** _non-standard_ */ + _image_total?: number | string; + /** _non-standard_ */ + _index?: number; + /** _non-standard_ */ + _initiator?: string; + /** _non-standard_ */ + _initiator_column?: string; + /** _non-standard_ */ + _initiator_detail?: string; + /** _non-standard_ */ + _initiator_function?: string; + /** _non-standard_ */ + _initiator_line?: string; + /** _non-standard_ */ + _initiator_type?: string; + /** _non-standard_ */ + _ip_addr?: string; + /** _non-standard_ */ + _is_secure?: number | string; + /** _non-standard_ */ + _jpeg_scan_count?: number | string; + /** _non-standard_ */ + _load_end?: number | string; + /** _non-standard_ */ + _load_ms?: number | string; + /** _non-standard_ */ + _load_start?: number | string; + /** _non-standard_ */ + _method?: string; + /** _non-standard_ */ + _minify_save?: number | string; + /** _non-standard_ */ + _minify_total?: number | string; + /** _non-standard_ */ + _number?: number; + /** _non-standard_ */ + _objectSize?: number | string; + /** _non-standard_ */ + _objectSizeUncompressed?: number | string; + /** _non-standard_ */ + _priority?: string; + /** _non-standard_ */ + _protocol?: number | string; + /** _non-standard_ */ + _request_id?: number | string; + /** _non-standard_ */ + _responseCode?: number | string; + /** _non-standard_ */ + _score_cache?: number | string; + /** _non-standard_ */ + _score_cdn?: number | string; + /** _non-standard_ */ + _score_combine?: number | string; + /** _non-standard_ */ + _score_compress?: number | string; + /** _non-standard_ */ + _score_cookies?: number | string; + /** _non-standard_ */ + _score_etags?: number | string; + /** _non-standard_ */ + _score_gzip?: number | string; + /** _non-standard_ */ + "_score_keep-alive"?: number | string; + /** _non-standard_ */ + _score_minify?: number | string; + /** _non-standard_ */ + _score_progressive_jpeg?: number; + /** _non-standard_ */ + _server_count?: number | string; + /** _non-standard_ */ + _server_rtt?: number | string; + /** _non-standard_ */ + _socket?: number | string; + /** _non-standard_ */ + _ssl_end?: number | string; + /** _non-standard_ */ + _ssl_ms?: number | string; + /** _non-standard_ */ + _ssl_start?: number | string; + /** _non-standard_ */ + _ttfb_end?: number | string; + /** _non-standard_ */ + _ttfb_ms?: number | string; + /** _non-standard_ */ + _ttfb_start?: number | string; + /** _non-standard_ */ + _type?: number | string; + /** _non-standard_ */ + _url?: string; + /** _non-standard_ */ + _was_pushed?: number | string; + /** _non-standard_ */ + _initialPriority?: string; +} +/** + * This object contains detailed info about performed request. + * + * http://www.softwareishard.com/blog/har-12-spec/#request + */ +export interface Request { + /** Request method (`GET`, `POST`, ...). */ + method: string; + /** Absolute URL of the request (fragments are not included). */ + url: string; + /** Request HTTP Version. */ + httpVersion: string; + /** List of cookie objects. */ + cookies: Cookie[]; + /** List of header objects. */ + headers: Header[]; + /** List of query parameter objects. */ + queryString: QueryString[]; + /** Posted data info. */ + postData?: PostData; + /** + * Total number of bytes from the start of the HTTP request message until + * (and including) the double CRLF before the body. + * + * Set to `-1` if the info is not available. + */ + headersSize: number; + /** + * Size of the request body (POST data payload) in bytes. + * + * Set to `-1` if the info is not available. + */ + bodySize: number; + /** A comment provided by the user or the application */ + comment?: string; +} +/** + * This object contains detailed info about the response. + * + * http://www.softwareishard.com/blog/har-12-spec/#response + */ +export interface Response { + /** Response status. */ + status: number; + /** Response status description. */ + statusText: string; + /** Response HTTP Version. */ + httpVersion: string; + /** List of cookie objects. */ + cookies: Cookie[]; + /** List of header objects. */ + headers: Header[]; + /** Details about the response body. */ + content: Content; + /** Redirection target URL from the Location response header. */ + redirectURL: string; + /** + * Total number of bytes from the start of the HTTP response message until + * (and including) the double CRLF before the body. + * + * Set to `-1` if the info is not available. + * + * _The size of received response-headers is computed only from headers + * that are really received from the server. Additional headers appended by + * the browser are not included in this number, but they appear in the list + * of header objects._ + */ + headersSize: number; + /** Size of the received response body in bytes. + * + * - Set to zero in case of responses coming from the cache (`304`). + * - Set to `-1` if the info is not available. + */ + bodySize: number; + /** A comment provided by the user or the application */ + comment?: string; + /** _non-standard_ */ + _transferSize?: number; +} +/** + * This object contains list of all cookies (used in `request` and `response` + * objects). + * + * http://www.softwareishard.com/blog/har-12-spec/#cookies + */ +export interface Cookie { + /** The name of the cookie. */ + name: string; + /** The cookie value. */ + value: string; + /** The path pertaining to the cookie. */ + path?: string; + /** The host of the cookie. */ + domain?: string; + /** + * Cookie expiration time. + * (ISO 8601 - `YYYY-MM-DDThh:mm:ss.sTZD`, + * e.g. `2009-07-24T19:20:30.123+02:00`). + */ + expires?: string | Date | null; + /** Set to true if the cookie is HTTP only, false otherwise. */ + httpOnly?: boolean; + /** True if the cookie was transmitted over ssl, false otherwise. */ + secure?: boolean; + /** A comment provided by the user or the application */ + comment?: string; +} + +/** + * This object represents a headers (used in `request` and `response` objects). + * + * http://www.softwareishard.com/blog/har-12-spec/#headers + */ +export interface Header { + name: string; + value: string; + /** A comment provided by the user or the application */ + comment?: string; +} +/** + * This object represents a parameter & value parsed from a query string, + * if any (embedded in `request` object). + * + * http://www.softwareishard.com/blog/har-12-spec/#queryString + */ +export interface QueryString { + name: string; + value: string; + /** A comment provided by the user or the application */ + comment?: string; +} +/** + * This object describes posted data, if any (embedded in `request` object). + * + * http://www.softwareishard.com/blog/har-12-spec/#postData + */ +export interface PostData { + /** Mime type of posted data. */ + mimeType: string; + /** List of posted parameters (in case of URL encoded parameters). + * + * _`text` and `params` fields are mutually exclusive._ + */ + params: Param[]; + /** Plain text posted data + * + * _`params` and `text` fields are mutually exclusive._ + */ + text: string; + /** A comment provided by the user or the application */ + comment?: string; +} +/** + * List of posted parameters, if any (embedded in `postData` object). + * + * http://www.softwareishard.com/blog/har-12-spec/#params + */ +export interface Param { + /** name of a posted parameter. */ + name: string; + /** value of a posted parameter or content of a posted file */ + value?: string; + /** name of a posted file. */ + fileName?: string; + /** content type of a posted file. */ + contentType?: string; + /** A comment provided by the user or the application */ + comment?: string; +} +/** + * This object describes details about response content + * (embedded in `response` object). + * + * http://www.softwareishard.com/blog/har-12-spec/#content + */ +export interface Content { + /** + * Length of the returned content in bytes. + * + * Should be equal to `response.bodySize` if there is no compression and + * bigger when the content has been compressed. + */ + size: number; + /** + * Number of bytes saved. Leave out this field if the information is not + * available. + */ + compression?: number; + /** + * MIME type of the response text (value of the Content-Type response + * header). + * + * The charset attribute of the MIME type is included (if available). + */ + mimeType: string; + /** + * Response body sent from the server or loaded from the browser cache. + * + * This field is populated with textual content only. + * + * The text field is either HTTP decoded text or a encoded (e.g. `base64`) + * representation of the response body. + * + * Leave out this field if the information is not available. + */ + text?: string; + /** + * Encoding used for response text field e.g `base64`. + * + * Leave out this field if the text field is HTTP decoded + * (decompressed & unchunked), than trans-coded from its original character + * set into UTF-8. + */ + encoding?: string; + /** A comment provided by the user or the application */ + comment?: string; +} +/** + * This objects contains info about a request coming from browser cache. + * + * http://www.softwareishard.com/blog/har-12-spec/#cache + */ +export interface Cache { + /** + * State of a cache entry before the request. + * + * Leave out this field if the information is not available. + */ + beforeRequest?: CacheDetails; + /** + * State of a cache entry after the request. + * + * Leave out this field if the information is not available. + */ + afterRequest?: CacheDetails; + /** A comment provided by the user or the application */ + comment?: string; +} +export interface CacheDetails { + /** Expiration time of the cache entry. + * + * _(Format not documente but assumingly ISO 8601 - + * `YYYY-MM-DDThh:mm:ss.sTZD`)_ + */ + expires?: string; + /** The last time the cache entry was opened. + * * + * _(Format not documente but assumingly ISO 8601 - + * `YYYY-MM-DDThh:mm:ss.sTZD`)_ + */ + lastAccess: string; + /** Etag */ + eTag: string; + /** The number of times the cache entry has been opened. */ + hitCount: number; + /** A comment provided by the user or the application */ + comment?: string; +} +/** + * This object describes various phases within request-response round trip. + * + * All times are specified in milliseconds. + * + * http://www.softwareishard.com/blog/har-12-spec/#timings + */ +export interface Timings { + /** + * Time spent in a queue waiting for a network connection. + * + * Use `-1` if the timing does not apply to the current request. + */ + blocked?: number; + /** + * DNS resolution time. The time required to resolve a host name. + * + * Use `-1` if the timing does not apply to the current request. + */ + dns?: number; + /** + * Time required to create TCP connection. + * + * Use `-1` if the timing does not apply to the current request. + */ + connect?: number; + /** + * Time required to send HTTP request to the server. + * + * _Not optional and must have non-negative values._ + */ + send?: number; + /** + * Waiting for a response from the server. + * + * _Not optional and must have non-negative values._ + */ + wait: number; + /** + * Time required to read entire response from the server (or cache). + * + * _Not optional and must have non-negative values._ + */ + receive: number; + /** + * Time required for SSL/TLS negotiation. + * + * If this field is defined then the time is also included in the connect + * field (to ensure backward compatibility with HAR 1.1). + * + * Use `-1` if the timing does not apply to the current request. + */ + ssl?: number; + /** A comment provided by the user or the application */ + comment?: string; +} diff --git a/har-format/tsconfig.json b/har-format/tsconfig.json new file mode 100644 index 0000000000..7a22f7eb17 --- /dev/null +++ b/har-format/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "har-format-tests.ts" + ] +} \ No newline at end of file diff --git a/har-format/tslint.json b/har-format/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/har-format/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/helmet/index.d.ts b/helmet/index.d.ts index 9e5f30f554..1dc8882608 100644 --- a/helmet/index.d.ts +++ b/helmet/index.d.ts @@ -81,7 +81,7 @@ declare namespace helmet { } export interface IHelmetHstsConfiguration { - maxAge: number; + maxAge?: number; includeSubdomains?: boolean; preload?: boolean; setIf?: IHelmetSetIfFunction, diff --git a/highcharts/index.d.ts b/highcharts/index.d.ts index 58f2a97a5e..968b5975fb 100644 --- a/highcharts/index.d.ts +++ b/highcharts/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Highcharts 4.2.7 +// Type definitions for Highcharts 4.2 // Project: http://www.highcharts.com/ -// Definitions by: Damiano Gambarotto , Dan Lewi Harkestad +// Definitions by: Damiano Gambarotto , Dan Lewi Harkestad , Albert Ozimek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace Highcharts { @@ -799,7 +799,7 @@ declare namespace Highcharts { * @since 2.1.5 */ y?: number; - } + }; /** * For datetime axes, this decides where to put the tick between weeks. 0 = Sunday, 1 = Monday. * @default 1 @@ -813,8 +813,8 @@ declare namespace Highcharts { */ startOnTick?: boolean; /** - * Solid gauge series only. Color stops for the solid gauge. - * Use this in cases where a linear gradient between a minColor and maxColor is not sufficient. + * Solid gauge series only. Color stops for the solid gauge. + * Use this in cases where a linear gradient between a minColor and maxColor is not sufficient. * The stops is an array of tuples, where the first item is a float between 0 and 1 assigning the relative position in the gradient, and the second item is the color. */ stops?: [number, string][]; @@ -2059,7 +2059,7 @@ declare namespace Highcharts { * @since 3.0.8 */ theme?: ButtonStatesTheme; - } + }; /** * An array of series configurations for the drill down. Each series configuration uses the same syntax as the * series option set. These drilldown series are hidden by default. The drilldown series is linked to the parent @@ -4585,7 +4585,7 @@ declare namespace Highcharts { * Options for the hovered series */ hover?: BarStates; - } + }; } interface LineChart extends SeriesChart { @@ -4897,7 +4897,7 @@ declare namespace Highcharts { * Options for the hovered series */ hover?: BarStates; - } + }; } interface WaterFallChart extends BarChart { diff --git a/highcharts/modules/map/index.d.ts b/highcharts/modules/map/index.d.ts new file mode 100644 index 0000000000..9818729a62 --- /dev/null +++ b/highcharts/modules/map/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for Highmaps 4.2.7 +// Project: http://www.highcharts.com/products/highmaps +// Definitions by: Albert Ozimek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Static } from 'highcharts'; + +declare module 'highcharts' { + export interface Static { + mapChart(renderTo: string | HTMLElement, options: Options, callback?: (chart: ChartObject) => void): ChartObject; + } +} + diff --git a/highcharts/tsconfig.json b/highcharts/tsconfig.json index 3526f42da7..93645d284b 100644 --- a/highcharts/tsconfig.json +++ b/highcharts/tsconfig.json @@ -18,6 +18,7 @@ }, "files": [ "index.d.ts", + "modules/map/index.d.ts", "modules/boost.d.ts", "modules/exporting.d.ts", "modules/no-data-to-display.d.ts", @@ -32,4 +33,4 @@ "test/no-data-to-display.ts", "test/offline-exporting.ts" ] -} \ No newline at end of file +} diff --git a/highcharts/tslint.json b/highcharts/tslint.json new file mode 100644 index 0000000000..6fb4f705cf --- /dev/null +++ b/highcharts/tslint.json @@ -0,0 +1,10 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false, + "unified-signatures": false, + "array-type": false, + "no-empty-interface": false, + "dt-header": false + } +} diff --git a/history.js/index.d.ts b/history.js/index.d.ts index 5a24bd5d73..13d66b8cf6 100644 --- a/history.js/index.d.ts +++ b/history.js/index.d.ts @@ -20,9 +20,11 @@ interface Historyjs { enabled: boolean; - pushState(data: any, title: string, url: string): void; - replaceState(data: any, title: string, url: string): void; - getState(): HistoryState; + pushState(data: any, title: string, url: string, queue?: boolean): boolean; + replaceState(data: any, title: string, url: string, queue?: boolean): boolean; + getState(friendly?: boolean, create?: boolean): HistoryState; + getStateId (passedState: HistoryState): string; + getStateById (id: string): HistoryState; getStateByIndex(index: number): HistoryState; getCurrentIndex(): number; getHash(): string; @@ -37,12 +39,30 @@ interface Historyjs { debug(...messages: any[]): void; options: HistoryOptions; + + /** + * History.setTitle(title) + * Applies the title to the document + * @param {HistoryState} newState + * @return {Boolean} + */ + setTitle (newState: HistoryState): boolean + clearQueue(): Historyjs; + clearAllIntervals(): void; + getRootUrl(): string; + + emulated: { + hashChange?: any; + pushState?: any; + } } interface HistoryState { data?: any; title?: string; url: string; + hashedUrl?: string; + cleanUrl?: string; } interface HistoryOptions { @@ -56,6 +76,4 @@ interface HistoryOptions { initialTitle?: string; html4Mode?: boolean; delayInit?: number; - - } diff --git a/history/v2/index.d.ts b/history/v2/index.d.ts index 6b61fa1b77..c2278d07fa 100644 --- a/history/v2/index.d.ts +++ b/history/v2/index.d.ts @@ -75,10 +75,10 @@ export namespace History { export type LocationDescriptor = LocationDescriptorObject | Path; export type LocationKey = string; export type LocationListener = (location: Location) => void; - export type LocationState = Object; + export type LocationState = any; export type Path = string // Pathname + QueryString; export type Pathname = string; - export type Query = Object; + export type Query = any; export type QueryString = string; export type Search = string; export type TransitionHook = (location: Location, callback: (result: any) => void) => any diff --git a/htmlhint/htmlhint-tests.ts b/htmlhint/htmlhint-tests.ts new file mode 100644 index 0000000000..1a44c78888 --- /dev/null +++ b/htmlhint/htmlhint-tests.ts @@ -0,0 +1,17 @@ +import { HTMLHint, RuleSet } from "htmlhint"; + +const htmlHintRules: RuleSet = { + "tagname-lowercase": true, + "attr-lowercase": true, + "attr-value-double-quotes": true, + "doctype-first": true, + "tag-pair": true, + "spec-char-escape": true, + "id-unique": true, + "src-not-empty": true, + "attr-no-duplication": true, + "title-require": true +}; + +const result = HTMLHint.verify('', htmlHintRules); +const formatted = HTMLHint.format(result, { indent: 2 }); diff --git a/htmlhint/index.d.ts b/htmlhint/index.d.ts new file mode 100644 index 0000000000..7908eaaddb --- /dev/null +++ b/htmlhint/index.d.ts @@ -0,0 +1,32 @@ +// Type definitions for HTMLHint 0.9 +// Project: https://github.com/yaniswang/HTMLHint +// Definitions by: Alan Agius +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface LintResult { + evidence: string; + line: number; + col: number; + message: string; + rule: Rule; +} + +export interface FormatOptions { + indent?: number; + colors?: boolean; +} + +export interface Rule { + id: string; + description: string; + link: string; +} + +export interface RuleSet { + [id: string]: boolean; +} + +export namespace HTMLHint { + function verify(fileContent: string, ruleSet?: RuleSet): LintResult[]; + function format(arrMessages: LintResult[], options?: FormatOptions): string[]; +} diff --git a/htmlhint/tsconfig.json b/htmlhint/tsconfig.json new file mode 100644 index 0000000000..1ae3c23f81 --- /dev/null +++ b/htmlhint/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "htmlhint-tests.ts" + ] +} diff --git a/hystrixjs/hystrixjs-tests.ts b/hystrixjs/hystrixjs-tests.ts index b7f10a27d8..676015be06 100644 --- a/hystrixjs/hystrixjs-tests.ts +++ b/hystrixjs/hystrixjs-tests.ts @@ -1,6 +1,3 @@ - -/// - import hystrixjs = require('hystrixjs'); import q = require('q'); diff --git a/i18next-browser-languagedetector/i18next-browser-languagedetector-tests.ts b/i18next-browser-languagedetector/i18next-browser-languagedetector-tests.ts index bca7aee3b7..9f36a7d538 100644 --- a/i18next-browser-languagedetector/i18next-browser-languagedetector-tests.ts +++ b/i18next-browser-languagedetector/i18next-browser-languagedetector-tests.ts @@ -1,5 +1,3 @@ -/// - import * as i18next from 'i18next'; import LngDetector from 'i18next-browser-languagedetector'; diff --git a/i18next-xhr-backend/i18next-xhr-backend-tests.ts b/i18next-xhr-backend/i18next-xhr-backend-tests.ts index b4e71467f1..9c12809271 100644 --- a/i18next-xhr-backend/i18next-xhr-backend-tests.ts +++ b/i18next-xhr-backend/i18next-xhr-backend-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as i18next from 'i18next'; import XHR from 'i18next-xhr-backend'; diff --git a/ibm-mobilefirst/ibm-mobilefirst-tests.ts b/ibm-mobilefirst/ibm-mobilefirst-tests.ts index 92dbee824d..498c9c3d7f 100644 --- a/ibm-mobilefirst/ibm-mobilefirst-tests.ts +++ b/ibm-mobilefirst/ibm-mobilefirst-tests.ts @@ -1,5 +1,3 @@ -/// - // Tests // Test WL.Client @@ -126,7 +124,7 @@ WL.SimpleDialog.show( WL.Logger.debug("First button pressed"); } }]); - + // Test WL.TabBar // iOS var creditTab = WL.TabBar.addItem("CREDIT", function() { diff --git a/imagemagick-native/imagemagick-native-tests.ts b/imagemagick-native/imagemagick-native-tests.ts index c872634ab2..94d8fd05bb 100644 --- a/imagemagick-native/imagemagick-native-tests.ts +++ b/imagemagick-native/imagemagick-native-tests.ts @@ -1,6 +1,3 @@ - -/// - import imagemagick = require('imagemagick-native'); import fs = require('fs'); diff --git a/imagemagick/imagemagick-tests.ts b/imagemagick/imagemagick-tests.ts index 87ead6307a..5bc9d9cc93 100644 --- a/imagemagick/imagemagick-tests.ts +++ b/imagemagick/imagemagick-tests.ts @@ -1,6 +1,3 @@ - -/// - import imagemagick = require('imagemagick'); import child_process = require('child_process'); diff --git a/imagesloaded/imagesloaded-tests.ts b/imagesloaded/imagesloaded-tests.ts index 3f5ead2831..385df7b052 100644 --- a/imagesloaded/imagesloaded-tests.ts +++ b/imagesloaded/imagesloaded-tests.ts @@ -1,5 +1,3 @@ - - function test_ctor() { // element imagesLoaded(document.querySelector('#container'), function(instance) { @@ -12,6 +10,14 @@ function test_ctor() { // multiple elements var posts = document.querySelectorAll('.post'); imagesLoaded(posts, function() { console.log('all images are loaded'); }); + + // options + imagesLoaded('#container', { background: true }, function() { + console.log('all images are loaded'); + }); + imagesLoaded('#container', { background: '.item' }, function() { + console.log('all images are loaded'); + }); } function test_events_basic() { @@ -25,6 +31,8 @@ function test_events_basic() { imgLoad.on('always', onAlways); // unbind with .off() imgLoad.off('always', onAlways); + // bind once with .once() + imgLoad.once('always', onAlways); } function test_events_full() { diff --git a/imagesloaded/index.d.ts b/imagesloaded/index.d.ts index 507f082367..9a48a18e19 100644 --- a/imagesloaded/index.d.ts +++ b/imagesloaded/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for imagesLoaded 3.1.8 +// Type definitions for imagesLoaded 4.1.1 // Project: https://github.com/desandro/imagesloaded -// Definitions by: Chris Charabaruk +// Definitions by: Chris Charabaruk , Cameron Little // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace ImagesLoaded { type ElementSelector = Element | NodeList | Array | string; @@ -30,14 +30,21 @@ declare namespace ImagesLoaded { // event listeners on(event: string, listener: ImagesLoadedListener): void; off(event: string, listener: ImagesLoadedListener): void; + once(event: string, listener: ImagesLoadedListener): void; + } + + interface ImagesLoadedOptions { + background: true | string; } interface ImagesLoadedConstructor { /** * Creates a new ImagesLoaded object with the provided callback * @param elem Element, NodeList, Element array, or selector string for images to watch + * @param options object that can tell imagesloaded to watch background images as well * @param callback function triggered after all images have been loaded */ + (elem: ElementSelector, options: ImagesLoadedOptions, callback?: ImagesLoadedCallback): ImagesLoaded; (elem: ElementSelector, callback?: ImagesLoadedCallback): ImagesLoaded; } } diff --git a/intro.js/index.d.ts b/intro.js/index.d.ts index d7893018c2..b0925cd41a 100644 --- a/intro.js/index.d.ts +++ b/intro.js/index.d.ts @@ -21,6 +21,8 @@ declare namespace IntroJs { prevLabel?: string; skipLabel?: string; doneLabel?: string; + hidePrev?: boolean; + hideNext?: boolean; tooltipPosition?: string; tooltipClass?: string; highlightClass?: string; @@ -33,10 +35,12 @@ declare namespace IntroJs { showProgress?: boolean; scrollToElement?: boolean; overlayOpacity?: number; + scrollPadding?: number; positionPrecedence?: string[]; disableInteraction?: boolean; hintPosition?: string; hintButtonLabel?: string; + hintAnimation?: boolean; steps?: Step[]; hints?: Hint[]; } diff --git a/intro.js/intro.js-tests.ts b/intro.js/intro.js-tests.ts index 0d79c1bd21..19267a94a3 100644 --- a/intro.js/intro.js-tests.ts +++ b/intro.js/intro.js-tests.ts @@ -8,6 +8,10 @@ intro.setOption('doneLabel', 'Next page'); intro.setOption('overlayOpacity', 50); intro.setOption('showProgress', true); intro.setOptions({ + hidePrev: true, + hideNext: false, + scrollPadding: 30, + hintAnimation: false, steps: [ { intro: "Hello world!" diff --git a/is-array/is-array-tests.ts b/is-array/is-array-tests.ts index 9a8e252e05..327c2ea3d0 100644 --- a/is-array/is-array-tests.ts +++ b/is-array/is-array-tests.ts @@ -7,7 +7,7 @@ isArray(true); isArray([]); isArray({}); -var x = {} +var x = {}; if (isArray(x)) { x.push(0); } diff --git a/isbn-utils/index.d.ts b/isbn-utils/index.d.ts new file mode 100644 index 0000000000..fe2ac4dae9 --- /dev/null +++ b/isbn-utils/index.d.ts @@ -0,0 +1,35 @@ +// Type definitions for isbn-utils 1.1 +// Project: https://github.com/GitbookIO/isbn-utils +// Definitions by: Jørgen Elgaard Larsen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +type IGroups = any; + +export class ISBNcodes { + readonly source: string; + readonly prefix: string; + readonly group: string; + readonly publisher: string; + readonly article: string; + readonly check: string; + readonly check10: string; + readonly check13: string; + readonly groupname: string; +} + +export class ISBN { + constructor(val: string, groups: IGroups); + asIsbn10(hyphenate?: boolean): string; + asIsbn13(hyphenate?: boolean): string; + codes: ISBNcodes; + isIsbn10(): boolean; + isIsbn13(): boolean; + isValid(): boolean; +} + +export function asIsbn10(isbn: string, hyphenate?: boolean): string; +export function asIsbn13(isbn: string, hyphenate?: boolean): string; +export function parse(isbn: string, groups?: IGroups): ISBN|null; +export function hyphenate(isbn: string): string; +export function isValid(isbn: string, groups?: IGroups): boolean; diff --git a/isbn-utils/isbn-utils-tests.ts b/isbn-utils/isbn-utils-tests.ts new file mode 100644 index 0000000000..91f72a0359 --- /dev/null +++ b/isbn-utils/isbn-utils-tests.ts @@ -0,0 +1,36 @@ +import * as isbn from 'isbn-utils'; + + +const isbn10a: isbn.ISBN|null = isbn.parse('4873113369'); +let b: boolean; +let s: string; + +if (isbn10a !== null) { + b = isbn10a.isIsbn10(); + b = isbn10a.isIsbn13(); + s = isbn10a.asIsbn10(); + s = isbn10a.asIsbn10(true); + s = isbn10a.asIsbn13(); + s = isbn10a.asIsbn13(true); + s = isbn10a.codes.source; + s = isbn10a.codes.prefix; + s = isbn10a.codes.group; + s = isbn10a.codes.publisher; + s = isbn10a.codes.article; + s = isbn10a.codes.check; + s = isbn10a.codes.check10; + s = isbn10a.codes.check13; + s = isbn10a.codes.groupname; +} + +const bad: isbn.ISBN|null = isbn.parse('invalid format'); +if (bad === null) { + s = 'Bummer.'; +} + +s = isbn.asIsbn13('4-87311-336-9'); +s = isbn.asIsbn13('4-87311-336-9', true); +s = isbn.asIsbn10('978-4-87311-336-4'); +s = isbn.asIsbn10('978-4-87311-336-4', true); + +s = isbn.hyphenate('9784873113364'); diff --git a/isbn-utils/tsconfig.json b/isbn-utils/tsconfig.json new file mode 100644 index 0000000000..b061bf6192 --- /dev/null +++ b/isbn-utils/tsconfig.json @@ -0,0 +1,23 @@ +{ + "files": [ + "index.d.ts", + "isbn-utils-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/isbn-utils/tslint.json b/isbn-utils/tslint.json new file mode 100644 index 0000000000..f9e30021f4 --- /dev/null +++ b/isbn-utils/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} diff --git a/jasmine-data_driven_tests/index.d.ts b/jasmine-data_driven_tests/index.d.ts index a2a7415093..827539a3a9 100644 --- a/jasmine-data_driven_tests/index.d.ts +++ b/jasmine-data_driven_tests/index.d.ts @@ -2,6 +2,38 @@ // Project: https://github.com/gburghardt/jasmine-data_driven_tests // Definitions by: Anthony MacKinnon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 -declare function all(description: string, dataset: any[], assertion: (...args: any[]) => void): void; -declare function xall(description: string, dataset: any[], assertion: (...args: any[]) => void): void; \ No newline at end of file +declare var all: JasmineDataDrivenTest; +declare var xall: JasmineDataDrivenTest; + +interface JasmineDataDrivenTest { + ( + description: string, + dataset: Array<[T, U, V, W, X, Y, Z]>, + assertion: (arg0: T, arg1: U, arg2: V, arg3: W, arg4: X, arg5: Y, arg6: Z, done: () => void) => void): void; + ( + description: string, + dataset: Array<[T, U, V, W, X, Y]>, + assertion: (arg0: T, arg1: U, arg2: V, arg3: W, arg4: X, arg5: Y, done: () => void) => void): void; + ( + description: string, + dataset: Array<[T, U, V, W, X]>, + assertion: (arg0: T, arg1: U, arg2: V, arg3: W, arg4: X, done: () => void) => void): void; + ( + description: string, + dataset: Array<[T, U, V, W]>, + assertion: (arg0: T, arg1: U, arg2: V, arg3: W, done: () => void) => void): void; + ( + description: string, + dataset: Array<[T, U, V]>, + assertion: (arg0: T, arg1: U, arg2: V, done: () => void) => void): void; + ( + description: string, + dataset: Array<[T, U]>, + assertion: (arg0: T, arg1: U, done: () => void) => void): void; + ( + description: string, + dataset: T[], + assertion: (value: T, done: () => void) => void): void; +} diff --git a/jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts b/jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts index 27509d7383..727c253ad3 100644 --- a/jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts +++ b/jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts @@ -1,9 +1,8 @@ - /// all("A data driven test is a suite with multiple specs", ['a', 'b', 'c'], - (value: string) => { + value => { expect(value).not.toBe('d'); } ); @@ -13,7 +12,7 @@ all("A data driven test can have many arguments", [1, 2, 3], [2, 4, 6] ], - (a: number, b: number, c: number) => { + (a, b, c) => { expect(c - (a + b)).toBe(0); } ); @@ -23,7 +22,7 @@ all("A data driven test can be asynchronous", [3, 1], [5, 2] ], - (a: number, b: number, done: () => void) => { + (a, b, done) => { setTimeout(() => { expect(a - b > 0).toBe(true); done(); @@ -33,7 +32,7 @@ all("A data driven test can be asynchronous", xall("A data driven test can be pending", [1, 2, 3], - (value: number) => { + value => { expect(value < 4).toBe(true); } ); @@ -47,7 +46,7 @@ describe("A suite", () => { all("can contain data driven tests", [1, 2, 3], - (b: number) => { + b => { expect(a - b > 0).toBe(true); } ); diff --git a/jasmine-expect/index.d.ts b/jasmine-expect/index.d.ts index 25a21d49d5..ca5c2dbfc3 100644 --- a/jasmine-expect/index.d.ts +++ b/jasmine-expect/index.d.ts @@ -1,93 +1,154 @@ -// Type definitions for jasmine-expect 2.0 +// Type definitions for jasmine-expect 3.6.0 // Project: https://github.com/JamieMason/Jasmine-Matchers -// Definitions by: UserPixel +// Definitions by: GeneralCss // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 /// declare namespace jasmine { - interface Matchers { - // These functions are written in the order defined in the src directory of jasmine-matchers - // The type system is used smartly whenever it can provide value (by looking at the code of every matcher) - toBeAfter(otherDate: Date): boolean; // - toBeArray(): boolean; // - toBeArrayOfBooleans(): boolean; // - toBeArrayOfNumbers(): boolean; - toBeArrayOfObjects(): boolean; - toBeArrayOfSize(size: number): boolean; - toBeArrayOfStrings(): boolean; - toBeBefore(otherDate: Date): boolean; // - toBeBoolean(): boolean; - toBeCalculable(): boolean; - toBeDate(): boolean; - toBeEmptyArray(): boolean; - toBeEmptyObject(): boolean; - toBeEmptyString(): boolean; - toBeEvenNumber(): boolean; - toBeFalse(): boolean; - toBeFunction(): boolean; - toBeHtmlString(): boolean; - toBeIso8601(): boolean; - toBeJsonString(): boolean; - toBeLongerThan(other: string): boolean; - toBeNonEmptyArray(): boolean; - toBeNonEmptyObject(): boolean; - toBeNonEmptyString(): boolean; - toBeNumber(): boolean; - toBeObject(): boolean; - toBeOddNumber(): boolean; - toBeSameLengthAs(other: string): boolean; - toBeShorterThan(other: string): boolean; - toBeString(): boolean; - toBeTrue(): boolean; - toBeWhitespace(): boolean; - toBeWholeNumber(): boolean; - toBeWithinRange(floor: number, ceiling: number): boolean; + interface Matchers { + // toBe + toBeArray(): boolean; + toBeArrayOfBooleans(): boolean; + toBeArrayOfNumbers(): boolean; + toBeArrayOfObjects(): boolean; + toBeArrayOfSize(size: number): boolean; + toBeArrayOfStrings(): boolean; + toBeEmptyArray(): boolean; + toBeNonEmptyArray(): boolean; - toEndWith(subString: string): boolean; + // Booleans + toBeBoolean(): boolean; + toBeFalse(): boolean; + toBeTrue(): boolean; - toHaveArray(key: string): boolean; - toHaveArrayOfBooleans(key: string): boolean; - toHaveArrayOfNumbers(key: string): boolean; - toHaveArrayOfObjects(key: string): boolean; - toHaveArrayOfSize(key: string, size?: number): boolean; - toHaveArrayOfStrings(key: string): boolean; - toHaveBoolean(key: string): boolean; - toHaveCalculable(key: string): boolean; - toHaveDate(key: string): boolean; - toHaveDateAfter(key: string, otherDate: Date): boolean; - toHaveDateBefore(key: string, otherDate: Date): boolean; - toHaveEmptyArray(key: string): boolean; - toHaveEmptyObject(key: string): boolean; - toHaveEmptyString(key: string): boolean; - toHaveEvenNumber(key: string): boolean; - toHaveFalse(key: string): boolean; - toHaveHtmlString(key: string): boolean; - toHaveIso8601(key: string): boolean; - toHaveJsonString(key: string): boolean; - toHaveMember(key: string): boolean; - toHaveMethod(key: string): boolean; - toHaveNonEmptyArray(key: string): boolean; - toHaveNonEmptyObject(key: string): boolean; - toHaveNonEmptyString(key: string): boolean; - toHaveNumber(key: string): boolean; - toHaveNumberWithinRange(key: string, floor: number, ceiling: number): boolean; - toHaveObject(key: string): boolean; - toHaveOddNumber(key: string): boolean; - toHaveString(key: string): boolean; - toHaveStringLongerThan(key: string, other: string): boolean; - toHaveStringSameLengthAs(key: string, other: string): boolean; - toHaveStringShorterThan(key: string, other: string): boolean; - toHaveTrue(key: string): boolean; - toHaveWhitespaceString(key: string): boolean; - toHaveWholeNumber(key: string): boolean; + // Dates + toBeAfter(date: Date): boolean + toBeBefore(date: Date): boolean + toBeDate(): boolean; + toBeValidDate(): boolean; - toImplement(api: {}): boolean; + // Functions + toBeFunction(): boolean; + toThrowAnyError(): boolean; + toThrowErrorOfType(constructorName: string): boolean - toStartWith(subString: string): boolean; + // Numbers + toBeCalculable(): boolean; + toBeEvenNumber(): boolean; + toBeGreaterThanOrEqualTo(number: number): boolean; + toBeLessThanOrEqualTo(number: number): boolean; + toBeNear(number: number, epsilon: number): boolean; + toBeNumber(): boolean; + toBeOddNumber(): boolean + toBeWholeNumber(): boolean; + toBeWithinRange(floor: number, ceiling: number): boolean; - toThrowAnyError(): boolean; - toThrowErrorOfType(type: string): boolean; - } + // Strings + toBeEmptyString(): boolean; + toBeHtmlString(): boolean; + toBeIso8601(): boolean; + toBeJsonString(): boolean; + toBeLongerThan(string: string): boolean; + toBeNonEmptyString(): boolean; + toBeSameLengthAs(string: string): boolean; + toBeShorterThan(string: string): boolean; + toBeString(): boolean; + toBeWhitespace(): boolean; + toEndWith(string: string): boolean; + toStartWith(string: string): boolean; + + // Objects + toBeEmptyObject(): boolean; + toBeNonEmptyObject(): boolean; + toBeObject(): boolean; + + // Regular Expression + toBeRegExp(): boolean; + + // Members, Properties, Methods + toHaveArray(memberName: string): boolean; + toHaveArrayOfBooleans(memberName: string): boolean; + toHaveArrayOfNumbers(memberName: string): boolean; + toHaveArrayOfObjects(memberName: string): boolean; + toHaveArrayOfSize(memberName: string, size: number): boolean; + toHaveArrayOfStrings(memberName: string): boolean; + toHaveBoolean(memberName: string): boolean; + toHaveCalculable(memberName: string): boolean; + toHaveDate(memberName: string): boolean; + toHaveDateAfter(memberName: string, date: Date): boolean; + toHaveDateBefore(memberName: string, date: Date): boolean; + toHaveEmptyArray(memberName: string): boolean; + toHaveEmptyObject(memberName: string): boolean; + toHaveEmptyString(memberName: string): boolean; + toHaveEvenNumber(memberName: string): boolean; + toHaveFalse(memberName: string): boolean; + toHaveHtmlString(memberName: string): boolean; + toHaveIso8601(memberName: string): boolean; + toHaveJsonString(memberName: string): boolean; + toHaveMember(memberName: string): boolean; + toHaveMethod(memberName: string): boolean; + toHaveNonEmptyArray(memberName: string): boolean; + toHaveNonEmptyObject(memberName: string): boolean; + toHaveNonEmptyString(memberName: string): boolean; + toHaveNumber(memberName: string): boolean; + toHaveNumberWithinRange(memberName: string, floor: number, ceiling: number): boolean; + toHaveObject(memberName: string): boolean; + toHaveOddNumber(memberName: string): boolean; + toHaveString(memberName: string): boolean; + toHaveStringLongerThan(memberName: string, string: string): boolean; + toHaveStringSameLengthAs(memberName: string, string: string): boolean; + toHaveStringShorterThan(memberName: string, string: string): boolean; + toHaveTrue(memberName: string): boolean; + toHaveUndefined(memberName: string): boolean; + toHaveWhitespaceString(memberName: string): boolean; + toHaveWholeNumber(memberName: string): boolean; + } + + interface AssymetricMatchers { + + // Arrays + arrayOfBooleans(): boolean; + arrayOfNumbers(): boolean; + arrayOfObjects(): boolean; + arrayOfSize(number: number): boolean; + arrayOfStrings(): boolean; + emptyArray(): boolean; + nonEmptyArray(): boolean; + + // Dates + after(date: Date): boolean; + before(date: Date): boolean; + + // Numbers + calculable(): boolean; + evenNumber(): boolean; + greaterThanOrEqualTo(number: number): boolean; + lessThanOrEqualTo(number: number): boolean; + oddNumber(): boolean; + wholeNumber(): boolean; + withinRange(floor: number, ceiling: number): boolean; + + // Strings + endingWith(string: string): boolean; + iso8601(): boolean; + jsonString(): boolean; + longerThan(string: string): boolean; + nonEmptyString(string: string): boolean; + sameLengthAs(string: string): boolean; + shorterThan(string: string): boolean; + startingWith(string: string): boolean; + whitespace(): boolean; + + //Objects + emptyObject(): boolean; + nonEmptyObject(): boolean; + + // Regular expressions + regExp(): boolean; + } } + +declare var any: jasmine.AssymetricMatchers; + diff --git a/jasmine-expect/jasmine-expect-tests.ts b/jasmine-expect/jasmine-expect-tests.ts index 7753cc7381..4a8cbb3855 100644 --- a/jasmine-expect/jasmine-expect-tests.ts +++ b/jasmine-expect/jasmine-expect-tests.ts @@ -1,6 +1,3 @@ -/// - - // Taken directly from the test directory of the original repo declare var describeWhenNotArray: (arr: string) => void; @@ -873,9 +870,11 @@ describe('toHaveArrayOfSize', function() { describeToHaveArrayX('toHaveArrayOfSize', function() { describe('when number of expected items does not match', function() { it('should deny', function() { - expect({ + var xpToFail = expect; + xpToFail({ memberName: '' }).not.toHaveArrayOfSize('memberName'); + expect({ memberName: ['bar'] }).not.toHaveArrayOfSize('memberName', 0); @@ -1877,40 +1876,6 @@ describe('toHaveWholeNumber', function() { }); }); -describe('toImplement', function() { - describe('when invoked', function() { - describe('when subject IS an Object containing all of the supplied members', function() { - it('should confirm', function() { - expect({ - a: 1, - b: 2 - }).toImplement({ - a: 1, - b: 2 - }); - expect({ - a: 1, - b: 2 - }).toImplement({ - a: 1 - }); - }); - }); - describe('when subject is NOT an Object containing all of the supplied members', function() { - it('should deny', function() { - expect({ - a: 1 - }).not.toImplement({ - c: 3 - }); - expect(null).not.toImplement({ - a: 1 - }); - }); - }); - }); -}); - describe('toStartWith', function() { describe('when invoked', function() { describe('when subject is NOT an undefined or empty string', function() { diff --git a/jasmine-fixture/index.d.ts b/jasmine-fixture/index.d.ts index 8ea5956f1e..9a8c7b98b2 100644 --- a/jasmine-fixture/index.d.ts +++ b/jasmine-fixture/index.d.ts @@ -2,10 +2,14 @@ // Project: https://github.com/searls/jasmine-fixture // Definitions by: Craig Brett // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 -/** Affixes the given jquery selectors into the body and will be removed after each spec -* @param {string} selector The JQuery selector to be added to the dom -*/ +/// + +/** + * Affixes the given jquery selectors into the body and will be removed after each spec + * @param {string} selector The JQuery selector to be added to the dom + */ declare function affix(selector: string): JQuery; interface JQuery { diff --git a/jasmine-fixture/jasmine-fixture-tests.ts b/jasmine-fixture/jasmine-fixture-tests.ts index b0ec42d512..74eb750590 100644 --- a/jasmine-fixture/jasmine-fixture-tests.ts +++ b/jasmine-fixture/jasmine-fixture-tests.ts @@ -1,8 +1,6 @@ -/// /// /// - describe("Jasmine fixture extension", () => { describe("Affixes dom elements to body", () => { it("Inserts a new element on affix", () => { diff --git a/jasmine-jquery/jasmine-jquery-tests.ts b/jasmine-jquery/jasmine-jquery-tests.ts index 9d51a3775b..40aa9e8f88 100644 --- a/jasmine-jquery/jasmine-jquery-tests.ts +++ b/jasmine-jquery/jasmine-jquery-tests.ts @@ -1,7 +1,3 @@ -/// -/// - - describe("Jasmine jQuery extension", () => { it("Adds jQuery matchers", () => { expect($('
    ')).toBe($('div')); diff --git a/jasmine-matchers/jasmine-matchers-tests.ts b/jasmine-matchers/jasmine-matchers-tests.ts index dc92e809dc..4ef032062d 100644 --- a/jasmine-matchers/jasmine-matchers-tests.ts +++ b/jasmine-matchers/jasmine-matchers-tests.ts @@ -14,9 +14,6 @@ The above copyright notice and this permission notice shall be included in all c 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. */ -/// - - describe('toBeArray', function () { describe('matches', function () { it('should pass for []', function () { diff --git a/jasmine/index.d.ts b/jasmine/index.d.ts index 03c1e30c78..cb19aa7cd8 100644 --- a/jasmine/index.d.ts +++ b/jasmine/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Jasmine 2.5 +// Type definitions for Jasmine 2.5.2 // Project: http://jasmine.github.io/ // Definitions by: Boris Yankov , Theodore Brown , David Pärsson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -39,6 +39,8 @@ interface DoneFn extends Function { declare function spyOn(object: T, method: keyof T): jasmine.Spy; +declare function spyOnProperty(object: T, property: keyof T, accessType: string): jasmine.Spy; + declare function runs(asyncMethod: Function): void; declare function waitsFor(latchMethod: () => boolean, failureMessage?: string, timeout?: number): void; declare function waits(timeout?: number): void; @@ -468,6 +470,7 @@ declare namespace jasmine { addBeforesAndAftersToQueue(): void; explodes(): void; spyOn(obj: any, methodName: string, ignoreMethodDoesntExist: boolean): Spy; + spyOnProperty(object: any, property: string, accessType: string): Spy; removeAllSpies(): void; throwOnExpectationFailure: boolean; } diff --git a/jasmine/package.json b/jasmine/package.json deleted file mode 100644 index 7e47d54c61..0000000000 --- a/jasmine/package.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "dependencies": { - "typescript": ">=2.1.4" - } -} \ No newline at end of file diff --git a/jest/index.d.ts b/jest/index.d.ts old mode 100644 new mode 100755 index 9f945ba426..595a42ea2b --- a/jest/index.d.ts +++ b/jest/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Jest 18.1.0 +// Type definitions for Jest 19.2.0 // Project: http://facebook.github.io/jest/ -// Definitions by: Asana , Ivo Stratev , jwbay , Alexey Svetliakov +// Definitions by: Asana , Ivo Stratev , jwbay , Alexey Svetliakov , Alex Jover Morales // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -77,6 +77,8 @@ declare namespace jest { function runTimersToTime(msToRun: number): typeof jest; /** Explicitly supplies the mock object that the module system should return for the specified module. */ function setMock(moduleName: string, moduleExports: T): typeof jest; + /** Creates a mock function similar to jest.fn but also tracks calls to object[methodName] */ + function spyOn(object: T, method: M): SpyInstance; /** Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module). */ function unmock(moduleName: string): typeof jest; /** Instructs Jest to use fake versions of the standard timer functions. */ @@ -158,19 +160,19 @@ declare namespace jest { * @param {any} actual The value to apply matchers against. */ (actual: any): Matchers; - anything(): void; + anything(): any; /** Matches anything that was created with the given constructor. You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value. */ - any(classType: any): void; + any(classType: any): any; /** Matches any array made up entirely of elements in the provided array. You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value. */ - arrayContaining(arr: any[]): void; + arrayContaining(arr: any[]): any; /** Verifies that a certain number of assertions are called during a test. This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called. */ assertions(num: number): void; /** You can use `expect.extend` to add your own matchers to Jest. */ extend(obj: ExpectExtendMap): void; /** Matches any object that recursively matches the provided keys. This is often handy in conjunction with other asymmetric matchers. */ - objectContaining(obj: {}): void; + objectContaining(obj: {}): any; /** Matches any string that contains the exact provided string */ - stringMatching(str: string | RegExp): void; + stringMatching(str: string | RegExp): any; } interface Matchers { @@ -229,7 +231,7 @@ declare namespace jest { /** This ensures that a value matches the most recent snapshot. Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information. */ toMatchSnapshot(snapshotName?: string): void; /** Used to test that a function throws when it is called. */ - toThrow(): void; + toThrow(error?: string | Constructable | RegExp): void; /** If you want to test that a specific error is thrown inside a function. */ toThrowError(error?: string | Constructable | RegExp): void; /** Used to test that a function throws a error matching the most recent snapshot when it is called. */ @@ -245,6 +247,10 @@ declare namespace jest { (...args: any[]): any; } + interface SpyInstance extends MockInstance { + mockRestore(): void; + } + /** * Wrap module with mock definitions * @example diff --git a/jest/jest-tests.ts b/jest/jest-tests.ts index a3d84a09e3..d951153842 100644 --- a/jest/jest-tests.ts +++ b/jest/jest-tests.ts @@ -160,17 +160,21 @@ describe('toThrow API', function () { it('throws', function () { expect(throwTypeError()).toThrow(); + expect(throwTypeError()).toThrowError(); }); it('throws TypeError', function () { + expect(throwTypeError()).toThrow(TypeError); expect(throwTypeError()).toThrowError(TypeError); }); it('throws \'Definition was out of date\'', function () { + expect(throwTypeError()).toThrow(/Definition was out of date/); expect(throwTypeError()).toThrowError(/Definition was out of date/); }); it('throws \'toThorow Definition was out of date\'', function () { + expect(throwTypeError()).toThrow('toThrow Definition was out of date'); expect(throwTypeError()).toThrowError('toThrow Definition was out of date'); }); }); @@ -199,6 +203,19 @@ describe('Assymetric matchers', function () { })); expect.assertions(4); + + interface Test { + a: number; + b: string; + } + + // It's useful to create expected objects before the test call for refactoring purposes + // Assymetric matchers must return any in this case to constrain the required type + const test: Test = { + a: expect.any(Number), + b: expect.anything() + } + expect(callback).toHaveBeenCalledWith(test); }); }); diff --git a/jimp/jimp-tests.ts b/jimp/jimp-tests.ts index 180ce27d7f..a312cd4586 100644 --- a/jimp/jimp-tests.ts +++ b/jimp/jimp-tests.ts @@ -1,7 +1,7 @@ -import Jimp = require('jimp') +import Jimp = require('jimp'); // All code below is from node-jimp document -Jimp.read("lenna.png", function (err, data) { +Jimp.read("lenna.png", (err, data) => { if (err) throw err; data.resize(256, 256) // resize .quality(60) // set JPEG quality @@ -9,93 +9,98 @@ Jimp.read("lenna.png", function (err, data) { .write("lena-small-bw.jpg"); // save }); -Jimp.read("lenna.png").then(function (lenna) { +Jimp.read("lenna.png").then(lenna => { lenna.resize(256, 256) // resize .quality(60) // set JPEG quality .greyscale() // set greyscale .write("lena-small-bw.jpg"); // save -}).catch(function (err) { +}).catch(err => { console.error(err); }); -Jimp.read("./path/to/image.jpg", function (err, image) { +Jimp.read("./path/to/image.jpg", (err, image) => { // do stuff with the image (if no exception) }); -Jimp.read("./path/to/image.jpg").then(function (image) { +Jimp.read("./path/to/image.jpg").then(image => { // do stuff with the image -}).catch(function (err) { +}).catch(err => { // handle an exception }); -Jimp.read(new Buffer(''), function (err, image) { +Jimp.read(new Buffer(''), (err, image) => { // do stuff with the image (if no exception) }); -Jimp.read("http://www.example.com/path/to/lenna.jpg", function (err, image) { +Jimp.read("http://www.example.com/path/to/lenna.jpg", (err, image) => { // do stuff with the image (if no exception) }); -var image = new Jimp(1, 2) -var w = 0 -var h = 0 -var x = 0 -var y = 0 -var f = 0 -var src = '' -var horz = Jimp.HORIZONTAL_ALIGN_CENTER -var vert = Jimp.VERTICAL_ALIGN_BOTTOM -var deg = 90 -var val = 0.5 -var hex = 0xFFFFFFFF -var r = 0 -var n = 1 +var image = new Jimp(1, 2); +var w = 0; +var h = 0; +var x = 0; +var y = 0; +var f = 0; +var src = ''; +var horz = Jimp.HORIZONTAL_ALIGN_CENTER; +var vert = Jimp.VERTICAL_ALIGN_BOTTOM; +var deg = 90; +var val = 0.5; +var hex = 0xFFFFFFFF; +var r = 0; +var n = 1; /* Resize */ -image.contain( w, h); // scale the image to the given width and height, some parts of the image may be letter boxed -image.cover( w, h); // scale the image to the given width and height, some parts of the image may be clipped -image.resize( w, h); // resize the image. Jimp.AUTO can be passed as one of the values. -image.scale(f ); // scale the image by the factor f -image.scaleToFit( w, h ); // scale the image to the largest size that fits inside the given width and height +image.contain(w, h); // scale the image to the given width and height, some parts of the image may be letter boxed +image.cover(w, h); // scale the image to the given width and height, some parts of the image may be clipped +image.resize(w, h); // resize the image. Jimp.AUTO can be passed as one of the values. +image.scale(f); // scale the image by the factor f +image.scaleToFit(w, h); // scale the image to the largest size that fits inside the given width and height // An optional resize mode can be passed with all resize methods. /* Crop */ image.autocrop(); // automatically crop same-color borders from image (if any) -image.crop( x, y, w, h ); // crop to the given region +image.crop(x, y, w, h); // crop to the given region /* Composing */ -image.blit( src, x, y ); +image.blit(src, x, y); // blit the image with another Jimp image at x, y, optionally cropped. -image.composite( src, x, y ); // composites another Jimp image over this image at x, y -image.mask( src, x, y ); // masks the image with another Jimp image at x, y using average pixel value +image.composite(src, x, y); // composites another Jimp image over this image at x, y +image.mask(src, x, y); // masks the image with another Jimp image at x, y using average pixel value /* Flip and rotate */ -image.flip( horz, vert ); // flip the image horizontally or vertically -image.mirror( horz, vert ); // an alias for flip -image.rotate( deg ); // rotate the image clockwise by a number of degrees. Optionally, a resize mode can be passed. If `false` is passed as the second parameter, the image width and height will not be resized. +image.flip(horz, vert); // flip the image horizontally or vertically +image.mirror(horz, vert); // an alias for flip + +// rotate the image clockwise by a number of degrees. +// Optionally, a resize mode can be passed. +// If `false` is passed as the second parameter, +// the image width and height will not be resized. +image.rotate(deg); // JPEG images with EXIF orientation data will be automatically re-orientated as appropriate. /* Colour */ -image.brightness( val ); // adjust the brighness by a value -1 to +1 -image.contrast( val ); // adjust the contrast by a value -1 to +1 +image.brightness(val); // adjust the brighness by a value -1 to +1 +image.contrast(val); // adjust the contrast by a value -1 to +1 image.dither565(); // ordered dithering of the image and reduce color space to 16-bits (RGB565) image.greyscale(); // remove colour from the image image.invert(); // invert the image colours image.normalize(); // normalize the channels in an image /* Alpha channel */ -image.fade( f ); // an alternative to opacity, fades the image by a factor 0 - 1. 0 will haven no effect. 1 will turn the image -image.opacity( f ); // multiply the alpha channel by each pixel by the factor f, 0 - 1 +image.fade(f); // an alternative to opacity, fades the image by a factor 0 - 1. 0 will haven no effect. 1 will turn the image +image.opacity(f); // multiply the alpha channel by each pixel by the factor f, 0 - 1 image.opaque(); // set the alpha channel on every pixel to fully opaque -image.background( hex ); // set the default new pixel colour (e.g. 0xFFFFFFFF or 0x00000000) for by some operations (e.g. image.contain and +image.background(hex); // set the default new pixel colour (e.g. 0xFFFFFFFF or 0x00000000) for by some operations (e.g. image.contain and /* Blurs */ -image.gaussian( r ); // Gaussian blur the image by r pixels (VERY slow) -image.blur( r ); // fast blur the image by r pixels +image.gaussian(r); // Gaussian blur the image by r pixels (VERY slow) +image.blur(r); // fast blur the image by r pixels /* Effects */ -image.posterize( n ); // apply a posterization effect with n level +image.posterize(n); // apply a posterization effect with n level image.sepia(); // apply a sepia wash to the image image.clone(); // returns a clone of the image @@ -107,50 +112,50 @@ image.resize(250, 250, Jimp.RESIZE_BEZIER); image.contain(250, 250, Jimp.HORIZONTAL_ALIGN_LEFT | Jimp.VERTICAL_ALIGN_TOP); -var path = '' -var str = '' -var width = 0 -Jimp.loadFont( path ).then(function (font) { // load font from .fnt file +var path = ''; +var str = ''; +var width = 0; +Jimp.loadFont(path).then(font => { // load font from .fnt file image.print(font, x, y, str); // print a message on an image image.print(font, x, y, str, width); // print a message on an image with text wrapped at width }); -var cb = (err: Error, data: any) => {} -Jimp.loadFont( path, cb ); // using a callback pattern +var cb = (err: Error, data: any) => {}; +Jimp.loadFont(path, cb); // using a callback pattern -Jimp.loadFont(Jimp.FONT_SANS_32_BLACK).then(function (font) { +Jimp.loadFont(Jimp.FONT_SANS_32_BLACK).then(font => { image.print(font, 10, 10, "Hello world!"); }); -image.write( path, cb ); // Node-style callback will be fired when write is successful +image.write(path, cb); // Node-style callback will be fired when write is successful var file = "new_name." + image.getExtension(); -image.write(file) +image.write(file); -var mime = 'image/png' -image.getBuffer( mime, cb ); // Node-style callback will be fired with result -image.getBase64( mime, cb ); // Node-style callback will be fired with result -image.quality( n ); // set the quality of saved JPEG, 0 - 100 +var mime = 'image/png'; +image.getBuffer(mime, cb); // Node-style callback will be fired with result +image.getBase64(mime, cb); // Node-style callback will be fired with result +image.quality(n); // set the quality of saved JPEG, 0 - 100 -var bool = true -var number = 0 -image.rgba( bool ); // set whether PNGs are saved as RGBA (true, default) or RGB (false) -image.filterType( number ); // set the filter type for the saved PNG -image.deflateLevel( number ); // set the deflate level for the saved PNG -Jimp.deflateStrategy( number ); // set the deflate for the saved PNG (0-3) +var bool = true; +var number = 0; +image.rgba(bool); // set whether PNGs are saved as RGBA (true, default) or RGB (false) +image.filterType(number); // set the filter type for the saved PNG +image.deflateLevel(number); // set the deflate level for the saved PNG +Jimp.deflateStrategy(number); // set the deflate for the saved PNG (0-3) image.color([ { apply: 'hue', params: [ -90 ] }, { apply: 'lighten', params: [ 50 ] }, { apply: 'xor', params: [ '#06D' ] } ]); - image.convolution([ - [-2,-1, 0], +image.convolution([ + [-2, -1, 0], [-1, 1, 1], [ 0, 1, 2] - ]) -image.scan(0, 0, image.bitmap.width, image.bitmap.height, function (x, y, idx) { +]); +image.scan(0, 0, image.bitmap.width, image.bitmap.height, function(x, y, idx) { // x, y is the position of this pixel on the image // idx is the position start position of this rgba tuple in the bitmap Buffer // this is the image @@ -166,28 +171,28 @@ image.scan(0, 0, image.bitmap.width, image.bitmap.height, function (x, y, idx) { image.getPixelColor(x, y); // returns the colour of that pixel e.g. 0xFFFFFFFF image.setPixelColor(hex, x, y); // sets the colour of that pixel -var g = 0 -var b = 0 -var a = 0 +var g = 0; +var b = 0; +var a = 0; Jimp.rgbaToInt(r, g, b, a); // e.g. converts 255, 255, 255, 255 to 0xFFFFFFFF Jimp.intToRGBA(hex); // e.g. converts 0xFFFFFFFF to {r: 255, g: 255, b: 255, a:255} -var image = new Jimp(256, 256, function (err, image) { +var image = new Jimp(256, 256, (err, image) => { // this image is 256 x 256, every pixel is set to 0x00000000 }); -var image = new Jimp(256, 256, 0xFF0000FF, function (err, image) { +var image = new Jimp(256, 256, 0xFF0000FF, (err, image) => { // this image is 256 x 256, every pixel is set to 0xFF0000FF }); image.hash(); // aHgG4GgoFjA image.hash(2); // 1010101011010000101010000100101010010000011001001001010011100100 -var image1 = new Jimp(0, 1) -var image2 = new Jimp(0, 1) +var image1 = new Jimp(0, 1); +var image2 = new Jimp(0, 1); Jimp.distance(image1, image2); // returns a number 0-1, where 0 means the two images are perceived to be identical -var threshold = 0 +var threshold = 0; var diff = Jimp.diff(image1, image2, threshold); // threshold ranges 0-1 (default: 0.1) diff.image; // a Jimp image showing differences diff.percent; // the proportion of different pixels (0-1), where 0 means the images are pixel identical @@ -202,13 +207,13 @@ if (distance < 0.15 || diff.percent < 0.15) { // not a match } -Jimp.read("lenna.png", function (err, image) { +Jimp.read("lenna.png", function(err, image) { this.greyscale().scale(0.5).write("lena-half-bw.png"); }); -Jimp.read("lenna.png", function (err, image) { - image.greyscale(function(err, image) { - image.scale(0.5, function (err, image) { +Jimp.read("lenna.png", (err, image) => { + image.greyscale((err, image) => { + image.scale(0.5, (err, image) => { image.write("lena-half-bw.png"); }); }); diff --git a/jmespath/index.d.ts b/jmespath/index.d.ts new file mode 100644 index 0000000000..a460fd6a4d --- /dev/null +++ b/jmespath/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for jmespath 0.15 +// Project: https://github.com/jmespath/jmespath.js +// Definitions by: Jeffery Grajkowski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Take a JSON document and transform it into another JSON document + * through a JMESPath expression. See: http://jmespath.org/ + * @param jsonDoc the document to transform + * @param query a JMESPath expression + * @return the transformed document + */ +export function search(jsonDoc: any, query: string): any; diff --git a/jmespath/jmespath-tests.ts b/jmespath/jmespath-tests.ts new file mode 100644 index 0000000000..04034acf67 --- /dev/null +++ b/jmespath/jmespath-tests.ts @@ -0,0 +1,6 @@ +import jmespath = require("jmespath"); + +const a = jmespath.search({foo: {bar: {baz: [0, 1, 2, 3, 4]}}}, "foo.bar.baz[2]"); +const b = jmespath.search({foo: {bar: {baz: [0, 1, 2, 3, 4]}}}, "foo.bar") +const c = jmespath.search({"foo": [{"first": "a", "last": "b"}, {"first": "c", "last": "d"}]}, "foo[*].first"); +const d = jmespath.search({"foo": [{"age": 20}, {"age": 25}, {"age": 30}, {"age": 35}, {"age": 40}]}, "foo[?age > `30`]"); diff --git a/jmespath/tsconfig.json b/jmespath/tsconfig.json new file mode 100644 index 0000000000..7db8ecc248 --- /dev/null +++ b/jmespath/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jmespath-tests.ts" + ] +} diff --git a/jmespath/tslint.json b/jmespath/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/jmespath/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/joi/index.d.ts b/joi/index.d.ts index 55e6b9c75f..fe1f0e39f8 100644 --- a/joi/index.d.ts +++ b/joi/index.d.ts @@ -91,6 +91,12 @@ export interface IpOptions { cidr?: string; } +export type GuidVersions = 'uuidv1' | 'uuidv2' | 'uuidv3' | 'uuidv4' | 'uuidv5' + +export interface GuidOptions { + version: GuidVersions[] | GuidVersions +} + export interface UriOptions { /** * Specifies one or more acceptable Schemes, should only include the scheme name. @@ -443,7 +449,7 @@ export interface StringSchema extends AnySchema { /** * Requires the string value to be a valid GUID. */ - guid(): StringSchema; + guid(options?: GuidOptions): StringSchema; /** * Requires the string value to be a valid hexadecimal string. diff --git a/joi/joi-tests.ts b/joi/joi-tests.ts index 59eb446b2f..3a222ff832 100644 --- a/joi/joi-tests.ts +++ b/joi/joi-tests.ts @@ -691,6 +691,8 @@ strSchema = strSchema.ip(ipOpts); strSchema = strSchema.uri(); strSchema = strSchema.uri(uriOpts); strSchema = strSchema.guid(); +strSchema = strSchema.guid({version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5']}); +strSchema = strSchema.guid({version: 'uuidv4'}); strSchema = strSchema.hex(); strSchema = strSchema.hostname(); strSchema = strSchema.isoDate(); diff --git a/joi/v6/joi-tests.ts b/joi/v6/joi-tests.ts index 265bbd045c..03ca5ffac0 100644 --- a/joi/v6/joi-tests.ts +++ b/joi/v6/joi-tests.ts @@ -1,4 +1,3 @@ -/// /// import Joi = require('joi'); diff --git a/jointjs/index.d.ts b/jointjs/index.d.ts index c8ef9ae302..95e2b2b7e3 100644 --- a/jointjs/index.d.ts +++ b/jointjs/index.d.ts @@ -156,6 +156,15 @@ declare namespace joint { findView(paper: Paper): ElementView; isElement(): boolean; scale(scaleX: number, scaleY: number, origin?: Point, options?: any): this; + addPort(port: any, opt?: any): this; + addPorts(ports: any[], opt?: any): this; + removePort(port: any, opt?: any): this; + hasPorts(): boolean; + hasPort(id: string): boolean; + getPorts(): any[]; + getPort(id: string): any; + getPortIndex(port: any): number; + portProp(portId: string, path: any, value?: any, opt?: any): joint.dia.Element; } interface CSSSelector { @@ -511,6 +520,7 @@ declare namespace joint { polyline?: ShapeAttrs; } class Polyline extends Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class Image extends Generic { constructor(attributes?: GenericAttributes, options?: Object); @@ -539,28 +549,40 @@ declare namespace joint { namespace chess { class KingWhite extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class KingBlack extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class QueenWhite extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class QueenBlack extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class RookWhite extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class RookBlack extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class BishopWhite extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class BishopBlack extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class KnightWhite extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class KnightBlack extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class PawnWhite extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class PawnBlack extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } } @@ -582,23 +604,28 @@ declare namespace joint { removeInPort(port: string, opt?: any): this; } class Coupled extends Model { + constructor(attributes?: ModelAttributes, options?: Object); } class Atomic extends Model { + constructor(attributes?: ModelAttributes, options?: Object); } class Link extends dia.Link { + constructor(attributes?: dia.LinkAttributes, options?: Object); } } namespace erd { class Entity extends basic.Generic { - constructor(attributes?: GenericAttributes, options?: Object); + constructor(attributes?: GenericAttributes, options?: Object); } class WeakEntity extends Entity { + constructor(attributes?: GenericAttributes, options?: Object); } class Relationship extends dia.Element { constructor(attributes?: GenericAttributes, options?: Object); } class IdentifyingRelationship extends Relationship { + constructor(attributes?: GenericAttributes, options?: Object); } interface AttributeAttrs extends dia.TextAttrs { ellipse?: ShapeAttrs; @@ -607,12 +634,16 @@ declare namespace joint { constructor(attributes?: GenericAttributes, options?: Object); } class Multivalued extends Attribute { + constructor(attributes?: GenericAttributes, options?: Object); } class Derived extends Attribute { + constructor(attributes?: GenericAttributes, options?: Object); } class Key extends Attribute { + constructor(attributes?: GenericAttributes, options?: Object); } class Normal extends Attribute { + constructor(attributes?: GenericAttributes, options?: Object); } interface ISAAttrs extends dia.Element { polygon?: ShapeAttrs; @@ -621,19 +652,23 @@ declare namespace joint { constructor(attributes?: GenericAttributes, options?: Object); } class Line extends dia.Link { + constructor(attributes?: dia.LinkAttributes, options?: Object); cardinality(value: string | number): void; } } namespace fsa { class State extends basic.Circle { + constructor(attributes?: GenericAttributes, options?: Object); } class StartState extends dia.Element { constructor(attributes?: GenericAttributes, options?: Object); } class EndState extends dia.Element { + constructor(attributes?: GenericAttributes, options?: Object); } class Arrow extends dia.Link { + constructor(attributes?: dia.LinkAttributes, options?: Object); } } @@ -655,14 +690,19 @@ declare namespace joint { constructor(attributes?: GenericAttributes, options?: Object); } class IO extends Gate { + constructor(attributes?: GenericAttributes, options?: Object); } class Input extends IO { + constructor(attributes?: GenericAttributes, options?: Object); } class Output extends IO { + constructor(attributes?: GenericAttributes, options?: Object); } class Gate11 extends Gate { + constructor(attributes?: GenericAttributes, options?: Object); } class Gate21 extends Gate { + constructor(attributes?: GenericAttributes, options?: Object); } interface Image { 'xlink:href'?: string; @@ -720,11 +760,13 @@ declare namespace joint { constructor(attributes?: GenericAttributes, options?: Object); } class Arrow extends dia.Link { + constructor(attributes?: dia.LinkAttributes, options?: Object); } } namespace pn { class Place extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class PlaceView extends dia.ElementView { renderTokens(): void; @@ -733,6 +775,7 @@ declare namespace joint { constructor(attributes?: GenericAttributes, options?: Object); } class Link extends dia.Link { + constructor(attributes?: dia.LinkAttributes, options?: Object); } } @@ -750,36 +793,49 @@ declare namespace joint { class ClassView extends dia.ElementView { } class Abstract extends Class { + constructor(attributes?: ClassAttributes, options?: Object); } class AbstractView extends ClassView { + constructor(attributes?: ClassAttributes, options?: Object); } class Interface extends Class { + constructor(attributes?: ClassAttributes, options?: Object); } class InterfaceView extends ClassView { + constructor(attributes?: ClassAttributes, options?: Object); } class Generalization extends dia.Link { + constructor(attributes?: dia.LinkAttributes, options?: Object); } class Implementation extends dia.Link { + constructor(attributes?: dia.LinkAttributes, options?: Object); } class Aggregation extends dia.Link { + constructor(attributes?: dia.LinkAttributes, options?: Object); } class Composition extends dia.Link { + constructor(attributes?: dia.LinkAttributes, options?: Object); } class Association extends dia.Link { + constructor(attributes?: dia.LinkAttributes, options?: Object); } interface StateAttributes extends GenericAttributes { events?: string[]; } class State extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); updateName(): void; updateEvents(): void; updatePath(): void; } class StartState extends basic.Circle { + constructor(attributes?: GenericAttributes, options?: Object); } class EndState extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class Transition extends dia.Link { + constructor(attributes?: dia.LinkAttributes, options?: Object); } } } @@ -833,7 +889,7 @@ declare namespace joint { setLinkVertices?: (link: dia.Link, vertices: Position[]) => void; } - class DirectedGraph { + export class DirectedGraph { static layout(graph: dia.Graph | dia.Cell[], options?: LayoutOptions): dia.BBox; } } diff --git a/jqgrid/jqgrid-tests.ts b/jqgrid/jqgrid-tests.ts index 7354f527dc..832a94d909 100644 --- a/jqgrid/jqgrid-tests.ts +++ b/jqgrid/jqgrid-tests.ts @@ -2,8 +2,6 @@ // Definitions by: Lokesh Peta // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - var mydata: any[] = []; $('#jqGrid') diff --git a/jqrangeslider/jqrangeslider-tests.ts b/jqrangeslider/jqrangeslider-tests.ts index 1af815806f..cb6b417656 100644 --- a/jqrangeslider/jqrangeslider-tests.ts +++ b/jqrangeslider/jqrangeslider-tests.ts @@ -1,5 +1,3 @@ -/// - // Arrows $("#arrowsExample").rangeSlider({ arrows: false }); $("#arrowsExample").editRangeSlider({ arrows: false }); @@ -133,7 +131,7 @@ $("#rulersExample").rangeSlider({ next: function(val){ return val + 10; }, stop: function(val){ return false; }, label: function(val){ return val; }, - format: function(tickContainer, tickStart, tickEnd){ + format: function(tickContainer, tickStart, tickEnd){ tickContainer.addClass("myCustomClass"); } }, @@ -179,7 +177,7 @@ $("#rangeExample").dateRangeSlider({ // Symmetric Positionning $("#symmetricExample").rangeSlider({ symmetricPositionning: true, - range: {min: 0} + range: {min: 0} }); // Type $("#typeExample").editRangeSlider({type: "number"}); diff --git a/jquery-ajax-chain/jquery-ajax-chain-tests.ts b/jquery-ajax-chain/jquery-ajax-chain-tests.ts index e5cbb8a26f..56ea354543 100644 --- a/jquery-ajax-chain/jquery-ajax-chain-tests.ts +++ b/jquery-ajax-chain/jquery-ajax-chain-tests.ts @@ -1,6 +1,3 @@ -/// -/// - function test_public_methods(): void { let ajaxChain: ajaxChain.JQueryAjaxChain, @@ -171,7 +168,7 @@ function test_optional_parameters(): void { }, hasCache: function (xmlResponse): XMLDocument { - + let $tempXmlResponse: JQuery, itemId: String; diff --git a/jquery-alertable/jquery-alertable-tests.ts b/jquery-alertable/jquery-alertable-tests.ts index a61dca01b4..61d6e2c06c 100644 --- a/jquery-alertable/jquery-alertable-tests.ts +++ b/jquery-alertable/jquery-alertable-tests.ts @@ -1,6 +1,3 @@ -/// -/// - // // Examples from https://github.com/claviska/jquery-alertable // diff --git a/jquery-backstretch/jquery-backstretch-tests.ts b/jquery-backstretch/jquery-backstretch-tests.ts index 7220458769..22835b4e43 100644 --- a/jquery-backstretch/jquery-backstretch-tests.ts +++ b/jquery-backstretch/jquery-backstretch-tests.ts @@ -1,5 +1,3 @@ -/// - var backstretch = jQuery.backstretch(['image.png'], { centeredX: false, centeredY: false, diff --git a/jquery-cropbox/jquery-cropbox-tests.ts b/jquery-cropbox/jquery-cropbox-tests.ts index ddc5389625..eadb754088 100644 --- a/jquery-cropbox/jquery-cropbox-tests.ts +++ b/jquery-cropbox/jquery-cropbox-tests.ts @@ -1,5 +1,3 @@ -/// - var cropboxWithDefaultSettings = $("#element").cropbox(); var cropboxOptions: jQueryCropBox.CropboxOptions = { @@ -38,7 +36,7 @@ cropboxWithOptions.getBlob(); cropboxWithOptions.remove(); cropboxWithOptions.on("cropbox",(e: Event, data: any, img: jQueryCropBox.Cropbox) => { - - //DoStuff - + + //DoStuff + }); diff --git a/jquery-easy-loading/jquery-easy-loading-tests.ts b/jquery-easy-loading/jquery-easy-loading-tests.ts index 7a59d3d617..ece98fd6d0 100644 --- a/jquery-easy-loading/jquery-easy-loading-tests.ts +++ b/jquery-easy-loading/jquery-easy-loading-tests.ts @@ -1,6 +1,3 @@ - -/// - function test_options() { const jqElement: JQuery = $("body").loading({ diff --git a/jquery-handsontable/jquery-handsontable-tests.ts b/jquery-handsontable/jquery-handsontable-tests.ts index 267ab30d8a..a2e10b4827 100644 --- a/jquery-handsontable/jquery-handsontable-tests.ts +++ b/jquery-handsontable/jquery-handsontable-tests.ts @@ -1,6 +1,3 @@ -/// - - var data = [ ["", "Maserati", "Mazda", "Mercedes", "Mini", "Mitsubishi"], ["2009", 0, 2941, 4303, 354, 5814], diff --git a/jquery-jsonrpcclient/jquery-jsonrpcclient-tests.ts b/jquery-jsonrpcclient/jquery-jsonrpcclient-tests.ts index f680dbb688..0e42508202 100644 --- a/jquery-jsonrpcclient/jquery-jsonrpcclient-tests.ts +++ b/jquery-jsonrpcclient/jquery-jsonrpcclient-tests.ts @@ -1,5 +1,3 @@ -/// - var foo = new $.JsonRpcClient({ ajaxUrl: '/backend/jsonrpc' }); foo.call( 'bar', ['A parameter', 'B parameter'], diff --git a/jquery-mockjax/jquery-mockjax-tests.ts b/jquery-mockjax/jquery-mockjax-tests.ts index 7688645f8e..3090a1c3cc 100644 --- a/jquery-mockjax/jquery-mockjax-tests.ts +++ b/jquery-mockjax/jquery-mockjax-tests.ts @@ -1,4 +1,3 @@ -/// /// class Tests { diff --git a/jquery-steps/index.d.ts b/jquery-steps/index.d.ts index 6abe640417..7670245480 100644 --- a/jquery-steps/index.d.ts +++ b/jquery-steps/index.d.ts @@ -1,8 +1,9 @@ // Type definitions for jQuery Steps v1.1.1 // Project: http://www.jquery-steps.com/ -// Definitions by: Joseph Blank +// Definitions by: Joseph Blank , Nicholas Wong // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Updated by: Nicholas Wong + +/// interface JQuery { steps(param?: JQuerySteps.Settings): JQuerySteps.JQuerySteps; diff --git a/jquery-steps/jquery-steps-tests.ts b/jquery-steps/jquery-steps-tests.ts index 35346d1f7b..6659212e20 100644 --- a/jquery-steps/jquery-steps-tests.ts +++ b/jquery-steps/jquery-steps-tests.ts @@ -1,6 +1,3 @@ -/// -/// - var labels: JQuerySteps.LabelSettings = { cancel: 'Cancel', current: 'Current:', diff --git a/jquery-timeentry/jquery-timeentry-tests.ts b/jquery-timeentry/jquery-timeentry-tests.ts index ccfe0794a3..8910487c65 100644 --- a/jquery-timeentry/jquery-timeentry-tests.ts +++ b/jquery-timeentry/jquery-timeentry-tests.ts @@ -1,5 +1,3 @@ -/// - var selector = '#example'; // basic diff --git a/jquery-toastmessage-plugin/index.d.ts b/jquery-toastmessage-plugin/index.d.ts new file mode 100644 index 0000000000..2666ecbd0b --- /dev/null +++ b/jquery-toastmessage-plugin/index.d.ts @@ -0,0 +1,57 @@ +// Type definitions for jquery-toastmessage-plugin 0.2 +// Project: https://github.com/akquinet/jquery-toastmessage-plugin +// Definitions by: Joe Skeen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare interface JQuery { + toastmessage: JQueryToastmessage.ToastmessageStatic; +} + +/** jQuery Toastmessage (http://akquinet.github.io/jquery-toastmessage-plugin/) */ +declare namespace JQueryToastmessage { + interface ToastmessageStatic { + /* shows a toast message of the specified type */ + (command: ShowToastCommand, message: string): JQuery; + /** shows a custom toast */ + (command: 'showToast', toastOpts: ToastOptions): JQuery; + /** removes the specified toast and returns it */ + (command: 'removeToast', toast: JQuery, closeOpts?: ToastOptions): void; + /** configures the default toast options */ + (toastOpts: ToastOptions): void; + } + + type ShowToastCommand = 'showNoticeToast' | 'showSuccessToast' | 'showWarningToast' | 'showErrorToast'; + type ToastType = 'notice' | 'warning' | 'error' | 'success'; + type ToastPosition = 'top-left' | 'top-center' | 'top-right' | 'middle-left' | 'middle-center' | 'middle-right'; + + interface ToastOptions { + /** in effect duration in miliseconds @default 600 */ + inEffectDuration?: number; + /** + * time in miliseconds before the item has to disappear @default 3000 */ + stayTime?: number; + /** content of the item @default '' */ + text?: string; + /** should the toast item sticky or not? @default false */ + sticky?: boolean; + /** the type of toast @default 'notice' */ + type?: ToastType; + /** + * Position of the toast container holding different toast. + * Position can be set only once at the very first call, + * changing the position after the first call does nothing + * @default 'top-right' + */ + position?: ToastPosition; + /** + * text which will be shown as close button, + * set to '' when you want to introduce an image via css + * @default '' + */ + closeText?: string; + /** callback function when the toastmessage is closed @default null */ + close?: () => void; + } +} \ No newline at end of file diff --git a/jquery-toastmessage-plugin/jquery-toastmessage-plugin-tests.ts b/jquery-toastmessage-plugin/jquery-toastmessage-plugin-tests.ts new file mode 100644 index 0000000000..d1feba15ce --- /dev/null +++ b/jquery-toastmessage-plugin/jquery-toastmessage-plugin-tests.ts @@ -0,0 +1,88 @@ +/// + + +/* code examples from documentation */ + +$().toastmessage('showNoticeToast', 'some message here'); +$().toastmessage('showSuccessToast', "some message here"); +$().toastmessage('showWarningToast', "some message here"); +$().toastmessage('showErrorToast', "some message here"); + +// user configured toastmessage: +const toastObject = $().toastmessage('showToast', { + text : 'Hello World', + sticky : true, + position : 'top-right', + type : 'success', + close : function () {console.log("toast is closed ...");} +}); + +$().toastmessage('removeToast', toastObject); + +// reconfiguring the toasts as sticky +$().toastmessage({sticky : true}); + +// saving the newly created toast into a variable +var myToast = $().toastmessage('showNoticeToast', 'some message here'); + +// removing the toast +$().toastmessage('removeToast', myToast); + +// user configuration of all toastmessages to come: +$().toastmessage({ + text : 'Hello World', + sticky : true, + position : 'top-right', + type : 'success', + close : function () {console.log("toast is closed ...");} +}); + +$().toastmessage({ + inEffectDuration: 600, // in effect duration in miliseconds + stayTime: 3000, // time in miliseconds before the item has to disappear + text: '', // content of the item + sticky: false, // should the toast item sticky or not? + type: 'notice', // notice, warning, error, success + position: 'top-right', // top-left, top-center, top-right, middle-left, middle-center, middle-right + // Position of the toast container holding different toast. + // Position can be set only once at the very first call, + // changing the position after the first call does nothing + closeText: '', // text which will be shown as close button, + // set to '' when you want to introduce an image via css + close: undefined // callback function when the toastmessage is closed +}); + +/* code examples from tests */ + +$('.toast-container').remove(); + +$().toastmessage('showSuccessToast', "SUCCESS"); +$().toastmessage('showNoticeToast', "NOTICE"); +$().toastmessage('showWarningToast', "WARNING"); +$().toastmessage('showErrorToast', "ERROR"); +$().toastmessage({ + sticky : true, + position : 'top-right', + closeText: '' +}); +$().toastmessage('showToast', { + text : 'Success Dialog', + type : 'success' +}); +$().toastmessage('showToast', { + text : 'Success Dialog', + sticky : true, + position : 'top-right', + type : 'success', + closeText: '', + close : () => {} +}); +var toast = $().toastmessage('showToast', { + text : 'Success Dialog', + sticky : true, + position : 'top-right', + type : 'success', + closeText: '', + close : () => {} +}); +$().toastmessage('removeToast', toast, { close : () => {} }); diff --git a/jquery-toastmessage-plugin/tsconfig.json b/jquery-toastmessage-plugin/tsconfig.json new file mode 100644 index 0000000000..193619fa0a --- /dev/null +++ b/jquery-toastmessage-plugin/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "lib": ["es6", "dom"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jquery-toastmessage-plugin-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery-toastmessage-plugin/tslint.json b/jquery-toastmessage-plugin/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/jquery-toastmessage-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/jquery-urlparam/jquery-urlparam-tests.ts b/jquery-urlparam/jquery-urlparam-tests.ts index a8ca144bb3..8d855e0e35 100644 --- a/jquery-urlparam/jquery-urlparam-tests.ts +++ b/jquery-urlparam/jquery-urlparam-tests.ts @@ -1,4 +1 @@ -/// - - console.log($.urlParam('variable')); diff --git a/jquery.ajaxfile/jquery.ajaxfile-tests.ts b/jquery.ajaxfile/jquery.ajaxfile-tests.ts index 364220325a..73bc6662dc 100644 --- a/jquery.ajaxfile/jquery.ajaxfile-tests.ts +++ b/jquery.ajaxfile/jquery.ajaxfile-tests.ts @@ -1,7 +1,3 @@ - -/// -/// - function testRawApi(){ var inputElement:HTMLInputElement = null; var resultPromise = AjaxFile.send({ diff --git a/jquery.are-you-sure/jquery.are-you-sure-tests.ts b/jquery.are-you-sure/jquery.are-you-sure-tests.ts index cd400f90c1..37cb487602 100644 --- a/jquery.are-you-sure/jquery.are-you-sure-tests.ts +++ b/jquery.are-you-sure/jquery.are-you-sure-tests.ts @@ -1,10 +1,3 @@ -// Type definitions for jquery.are-you-sure.js -// Project: https://github.com/codedance/jquery.AreYouSure -// Definitions by: Jon Egerton -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - //Use defaults $("test").areYouSure(); diff --git a/jquery.base64/jquery.base64-tests.ts b/jquery.base64/jquery.base64-tests.ts index 447a917620..c9c6955716 100644 --- a/jquery.base64/jquery.base64-tests.ts +++ b/jquery.base64/jquery.base64-tests.ts @@ -1,6 +1,3 @@ -/// - - var encoded = $.base64.encode(""); $.base64.decode(encoded); diff --git a/jquery.cleditor/jquery.cleditor-tests.ts b/jquery.cleditor/jquery.cleditor-tests.ts index 7fe997c4c5..b4f4917551 100644 --- a/jquery.cleditor/jquery.cleditor-tests.ts +++ b/jquery.cleditor/jquery.cleditor-tests.ts @@ -1,5 +1,3 @@ -/// - // cribbed from http://premiumsoftware.net/CLEditor/GettingStarted $(document).ready(function () { $("#input").cleditor(); }); diff --git a/jquery.color/jquery.color-tests.ts b/jquery.color/jquery.color-tests.ts index c94a1cffed..e1439f4cd4 100644 --- a/jquery.color/jquery.color-tests.ts +++ b/jquery.color/jquery.color-tests.ts @@ -1,5 +1,3 @@ -/// - var color = $.Color("rgba(255, 255, 255, 0.4)"); var color1 = $.Color({red: 255, green: 255, blue: 255}); var color2 = $.Color({hue: 359, saturation: 0.5, lightness: 0.5}); diff --git a/jquery.colorbox/jquery.colorbox-tests.ts b/jquery.colorbox/jquery.colorbox-tests.ts index 66d54240db..3c05f213c9 100644 --- a/jquery.colorbox/jquery.colorbox-tests.ts +++ b/jquery.colorbox/jquery.colorbox-tests.ts @@ -1,5 +1,3 @@ -/// - //Image gallery var gallery : JQuery = $('a.gallery').colorbox({ rel: 'gal' }); diff --git a/jquery.cookie/jquery.cookie-tests.ts b/jquery.cookie/jquery.cookie-tests.ts index e93d29110c..998d7bf2df 100644 --- a/jquery.cookie/jquery.cookie-tests.ts +++ b/jquery.cookie/jquery.cookie-tests.ts @@ -1,5 +1,3 @@ -/// - class TestObject { text: string; value: number; diff --git a/jquery.customselect/jquery.customselect-tests.ts b/jquery.customselect/jquery.customselect-tests.ts index b0dc9554a9..5cb28a9f05 100644 --- a/jquery.customselect/jquery.customselect-tests.ts +++ b/jquery.customselect/jquery.customselect-tests.ts @@ -1,6 +1,3 @@ -/// - - class CustomSelectOptions implements JQueryCustomSelectOption { "customClass": string; "mapClass": boolean; diff --git a/jquery.cycle/jquery.cycle-tests.ts b/jquery.cycle/jquery.cycle-tests.ts index e93be101f6..df8ed24b22 100644 --- a/jquery.cycle/jquery.cycle-tests.ts +++ b/jquery.cycle/jquery.cycle-tests.ts @@ -1,5 +1,3 @@ -/// - // As basic as it can be $('#element').cycle(); @@ -284,7 +282,7 @@ $('#s2').cycle({ $('#slideshow2').cycle({ fx: 'scrollLeft,scrollDown,scrollRight,scrollUp', randomizeEffects: false, - easing: 'easeInBack' // easing supported via the easing plugin + easing: 'easeInBack' // easing supported via the easing plugin }); // Another Advanced "pager" Demo @@ -294,7 +292,7 @@ $('#slideshow').cycle({ timeout: 0, pager: '#nav', pagerAnchorBuilder: function (idx, slide) { - // return selector string for existing anchor + // return selector string for existing anchor return '#nav li:eq(' + idx + ') a'; } }); @@ -304,7 +302,7 @@ $('#slideshow').cycle({ slideExpr: 'img' }); // Defeating IE's ClearType bug $('#slideshow').cycle({ - cleartype: false // disable cleartype corrections + cleartype: false // disable cleartype corrections }); // Using the 'nowrap' option (manual slideshow) diff --git a/jquery.cycle2/jquery.cycle2-tests.ts b/jquery.cycle2/jquery.cycle2-tests.ts index 0e16629a3e..9d88e92532 100644 --- a/jquery.cycle2/jquery.cycle2-tests.ts +++ b/jquery.cycle2/jquery.cycle2-tests.ts @@ -1,5 +1,3 @@ -/// - // basic $('#element').cycle(); diff --git a/jquery.fancytree/index.d.ts b/jquery.fancytree/index.d.ts index 5533e89cb7..c5e84d69f7 100644 --- a/jquery.fancytree/index.d.ts +++ b/jquery.fancytree/index.d.ts @@ -21,18 +21,21 @@ interface JQuery { declare namespace Fancytree { interface Fancytree { $div: JQuery; - + widget: any; //JQueryUI.Widget; rootNode: FancytreeNode; + $container: JQuery; + focusNode: FancytreeNode; + options: FancytreeOptions; /** Activate node with a given key and fire focus and - * activate events. A prevously activated node will be + * activate events. A previously activated node will be * deactivated. If activeVisible option is set, all parents * will be expanded as necessary. Pass key = false, to deactivate * the current node only. * * @returns {FancytreeNode} activate node (null, if not found) */ - activateKey(key: string): FancytreeNode; + activateKey(key: string | boolean): FancytreeNode; /** (experimental) * @@ -199,7 +202,7 @@ declare namespace Fancytree { /** Display name (may contain HTML) */ title: string; /** Contains all extra data that was passed on node creation */ - data: Object; + data: any; /** Array of child nodes. For lazy nodes, null or undefined means 'not yet loaded'. Use an empty array to define a node that has no children. */ children: FancytreeNode[]; /** Use isExpanded(), setExpanded() to access this property. */ @@ -214,6 +217,10 @@ declare namespace Fancytree { lazy: boolean; /** Alternative description used as hover banner */ tooltip: string; + /** Outer element of single nodes */ + span: HTMLElement; + /** Outer element of single nodes for table extension */ + tr: HTMLElement; //#endregion //#region Methods @@ -639,7 +646,7 @@ declare namespace Fancytree { /** The tree instance */ tree: Fancytree; /** The jQuery UI tree widget */ - widget: Object; + widget: any; // JQueryUI.Widget; /** Shortcut to tree.options */ options: FancytreeOptions; /** The jQuery Event that initially triggered this call */ @@ -773,7 +780,7 @@ declare namespace Fancytree { /** Add tabindex='0' to node title span, so it can receive keyboard focus */ titlesTabbable?: boolean; /** Animation options, false:off (default: { effect: "blind", options: {direction: "vertical", scale: "box"}, duration: 200 }) */ - toggleEffect?: Object; + toggleEffect?: JQueryUI.EffectOptions; } /** Data object passed to FancytreeNode() constructor. Note: typically these attributes are accessed by meber methods, e.g. `node.isExpanded()` and `node.setSelected(false)`. */ diff --git a/jquery.finger/jquery.finger-tests.ts b/jquery.finger/jquery.finger-tests.ts index 3f35e7322c..c4734610b2 100644 --- a/jquery.finger/jquery.finger-tests.ts +++ b/jquery.finger/jquery.finger-tests.ts @@ -1,5 +1,3 @@ -/// - $.Finger.doubleTapInterval = 400; $.Finger.flickDuration = 250; $.Finger.pressDuration = 100; diff --git a/jquery.flagstrap/jquery.flagstrap-tests.ts b/jquery.flagstrap/jquery.flagstrap-tests.ts index 3bfcf0294e..6d262dc17f 100644 --- a/jquery.flagstrap/jquery.flagstrap-tests.ts +++ b/jquery.flagstrap/jquery.flagstrap-tests.ts @@ -1,14 +1,11 @@ -/// -/// - class TestObject { - + } $(function () { - // basic test - // written in according to basic example from documentation - var htmlSelect = '
    ' + + // basic test + // written in according to basic example from documentation + var htmlSelect = '' + '
    ' + '
    ' + '
    ' + @@ -21,7 +18,7 @@ $(function () { console.log('characters count: ' + $('#flagstrap').html().length + '\n' + $('#flagstrap').html()); // options test - // options -> data attributes + // options -> data attributes // written in according to options -> data attributes example from documentation htmlSelect = '' + '
    ' + @@ -42,7 +39,7 @@ $(function () { console.log('\n\ncharacters count: ' + $('#flagstrap2').html().length + '\n' + $('#flagstrap2').html()); // options test - // options -> instance options + // options -> instance options // written in according to options -> instance options example from documentation htmlSelect = '' + '
    ' + diff --git a/jquery.form/jquery.form-tests.ts b/jquery.form/jquery.form-tests.ts index f115a97f57..c4d3d636bf 100644 --- a/jquery.form/jquery.form-tests.ts +++ b/jquery.form/jquery.form-tests.ts @@ -1,5 +1,3 @@ -/// - // Basic usage jQuery('#myFormId').ajaxForm(); @@ -30,112 +28,112 @@ jQuery.fn.ajaxSubmit.debug = true; // ajaxForm -// bind form using 'ajaxForm' +// bind form using 'ajaxForm' $('#myForm1').ajaxForm({ - target: '#output1', // target element(s) to be updated with server response + target: '#output1', // target element(s) to be updated with server response beforeSubmit: function (formData, jqForm, options) { // pre-submit callback - // formData is an array; here we use $.param to convert it to a string to display it - // but the form plugin does this for you automatically when it submits the data + // formData is an array; here we use $.param to convert it to a string to display it + // but the form plugin does this for you automatically when it submits the data var queryString = $.param(formData); - // jqForm is a jQuery object encapsulating the form element. To access the - // DOM element for the form do this: - // var formElement = jqForm[0]; + // jqForm is a jQuery object encapsulating the form element. To access the + // DOM element for the form do this: + // var formElement = jqForm[0]; alert('About to submit: \n\n' + queryString); - // here we could return false to prevent the form from being submitted; - // returning anything other than false will allow the form submit to continue + // here we could return false to prevent the form from being submitted; + // returning anything other than false will allow the form submit to continue return true; }, success: function (responseText, statusText, xhr) { // post-submit callback - // for normal html responses, the first argument to the success callback - // is the XMLHttpRequest object's responseText property - - // if the ajaxForm method was passed an Options Object with the dataType - // property set to 'xml' then the first argument to the success callback - // is the XMLHttpRequest object's responseXML property - - // if the ajaxForm method was passed an Options Object with the dataType - // property set to 'json' then the first argument to the success callback - // is the json data object returned by the server - + // for normal html responses, the first argument to the success callback + // is the XMLHttpRequest object's responseText property + + // if the ajaxForm method was passed an Options Object with the dataType + // property set to 'xml' then the first argument to the success callback + // is the XMLHttpRequest object's responseXML property + + // if the ajaxForm method was passed an Options Object with the dataType + // property set to 'json' then the first argument to the success callback + // is the json data object returned by the server + alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + '\n\nThe output div should have already been updated with the responseText.'); } - // other available options: - //url: url // override for form's 'action' attribute - //type: type // 'get' or 'post', override for form's 'method' attribute - //dataType: null // 'xml', 'script', or 'json' (expected server response type) - //clearForm: true // clear all form fields after successful submit - //resetForm: true // reset the form after successful submit + // other available options: + //url: url // override for form's 'action' attribute + //type: type // 'get' or 'post', override for form's 'method' attribute + //dataType: null // 'xml', 'script', or 'json' (expected server response type) + //clearForm: true // clear all form fields after successful submit + //resetForm: true // reset the form after successful submit - // $.ajax options can be used here too, for example: - //timeout: 3000 + // $.ajax options can be used here too, for example: + //timeout: 3000 }); // ajaxSubmit $('#myForm2').ajaxSubmit({ - target: '#output2', // target element(s) to be updated with server response + target: '#output2', // target element(s) to be updated with server response beforeSubmit: function (formData, jqForm, options) { // pre-submit callback - // formData is an array; here we use $.param to convert it to a string to display it - // but the form plugin does this for you automatically when it submits the data + // formData is an array; here we use $.param to convert it to a string to display it + // but the form plugin does this for you automatically when it submits the data var queryString = $.param(formData); - // jqForm is a jQuery object encapsulating the form element. To access the - // DOM element for the form do this: - // var formElement = jqForm[0]; + // jqForm is a jQuery object encapsulating the form element. To access the + // DOM element for the form do this: + // var formElement = jqForm[0]; alert('About to submit: \n\n' + queryString); - // here we could return false to prevent the form from being submitted; - // returning anything other than false will allow the form submit to continue + // here we could return false to prevent the form from being submitted; + // returning anything other than false will allow the form submit to continue return true; }, success: function showResponse(responseText, statusText, xhr) { // post-submit callback - // for normal html responses, the first argument to the success callback - // is the XMLHttpRequest object's responseText property + // for normal html responses, the first argument to the success callback + // is the XMLHttpRequest object's responseText property - // if the ajaxSubmit method was passed an Options Object with the dataType - // property set to 'xml' then the first argument to the success callback - // is the XMLHttpRequest object's responseXML property + // if the ajaxSubmit method was passed an Options Object with the dataType + // property set to 'xml' then the first argument to the success callback + // is the XMLHttpRequest object's responseXML property - // if the ajaxSubmit method was passed an Options Object with the dataType - // property set to 'json' then the first argument to the success callback - // is the json data object returned by the server + // if the ajaxSubmit method was passed an Options Object with the dataType + // property set to 'json' then the first argument to the success callback + // is the json data object returned by the server alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + '\n\nThe output div should have already been updated with the responseText.'); } - // other available options: - //url: url // override for form's 'action' attribute - //type: type // 'get' or 'post', override for form's 'method' attribute - //dataType: null // 'xml', 'script', or 'json' (expected server response type) - //clearForm: true // clear all form fields after successful submit - //resetForm: true // reset the form after successful submit + // other available options: + //url: url // override for form's 'action' attribute + //type: type // 'get' or 'post', override for form's 'method' attribute + //dataType: null // 'xml', 'script', or 'json' (expected server response type) + //clearForm: true // clear all form fields after successful submit + //resetForm: true // reset the form after successful submit - // $.ajax options can be used here too, for example: - //timeout: 3000 + // $.ajax options can be used here too, for example: + //timeout: 3000 }); // Validation $('#myForm2').ajaxForm({ beforeSubmit: function (formData, jqForm, options) { - // formData is an array of objects representing the name and value of each field - // that will be sent to the server; it takes the following form: - // - // [ - // { name: username, value: valueOfUsernameInput }, - // { name: password, value: valueOfPasswordInput } - // ] - // - // To validate, we can examine the contents of this array to see if the - // username and password fields have values. If either value evaluates - // to false then we return false from this method. + // formData is an array of objects representing the name and value of each field + // that will be sent to the server; it takes the following form: + // + // [ + // { name: username, value: valueOfUsernameInput }, + // { name: password, value: valueOfPasswordInput } + // ] + // + // To validate, we can examine the contents of this array to see if the + // username and password fields have values. If either value evaluates + // to false then we return false from this method. for (var i = 0; i < formData.length; i++) { if (!formData[i].value) { @@ -150,13 +148,13 @@ $('#myForm2').ajaxForm({ // JSON $('#jsonForm').ajaxForm({ - // dataType identifies the expected content type of the server response + // dataType identifies the expected content type of the server response dataType: 'json', - // success identifies the function to invoke when the server response - // has been received + // success identifies the function to invoke when the server response + // has been received success: function (data) { - // 'data' is the json object returned from the server + // 'data' is the json object returned from the server alert(data.message); } }); @@ -164,14 +162,14 @@ $('#jsonForm').ajaxForm({ // XML $('#xmlForm').ajaxForm({ - // dataType identifies the expected content type of the server response + // dataType identifies the expected content type of the server response dataType: 'xml', - // success identifies the function to invoke when the server response - // has been received + // success identifies the function to invoke when the server response + // has been received success: function (responseXML) { - // 'responseXML' is the XML document returned by the server; we use - // jQuery to extract the content of the message node from the XML doc + // 'responseXML' is the XML document returned by the server; we use + // jQuery to extract the content of the message node from the XML doc var message = $('message', responseXML).text(); alert(message); } @@ -180,11 +178,11 @@ $('#xmlForm').ajaxForm({ // HTML $('#htmlForm').ajaxForm({ - // target identifies the element(s) to update with the server response + // target identifies the element(s) to update with the server response target: '#htmlExampleTarget', - // success identifies the function to invoke when the server response - // has been received; here we apply a fade-in effect to the new content + // success identifies the function to invoke when the server response + // has been received; here we apply a fade-in effect to the new content success: function () { $('#htmlExampleTarget').fadeIn('slow'); } diff --git a/jquery.jnotify/jquery.jnotify-tests.ts b/jquery.jnotify/jquery.jnotify-tests.ts index b5ad3927e2..f38a99760a 100644 --- a/jquery.jnotify/jquery.jnotify-tests.ts +++ b/jquery.jnotify/jquery.jnotify-tests.ts @@ -1,5 +1,3 @@ -/// - $(document).ready(function () { $('#StatusBar').jnotifyInizialize({ oneAtTime: true diff --git a/jquery.joyride/jquery.joyride-tests.ts b/jquery.joyride/jquery.joyride-tests.ts index f0a51b5270..c7324dd6c9 100644 --- a/jquery.joyride/jquery.joyride-tests.ts +++ b/jquery.joyride/jquery.joyride-tests.ts @@ -1,6 +1,3 @@ -/// - - var options: JoyrideOptions; options.autoStart = true; options.postStepCallback = (index, tip)=> { diff --git a/jquery.jsignature/jquery.jsignature-tests.ts b/jquery.jsignature/jquery.jsignature-tests.ts index 5ec4bc486d..58d73fe24b 100644 --- a/jquery.jsignature/jquery.jsignature-tests.ts +++ b/jquery.jsignature/jquery.jsignature-tests.ts @@ -1,8 +1,6 @@ -/// - /* * Taken from the tests section on jSignature - */ + */ $(document).ready(function () { var $sigdiv = $('#signature'); @@ -10,7 +8,7 @@ $(document).ready(function () { $sigdiv.jSignature(); $sigdiv.jSignature("reset"); - + var data = $sigdiv.jSignature("getData", "svgbase64"); $sigdiv.jSignature("setData", "data:" + data); diff --git a/jquery.leanmodal/jquery.leanmodal-tests.ts b/jquery.leanmodal/jquery.leanmodal-tests.ts index fb6c4ae344..1884cb25d9 100644 --- a/jquery.leanmodal/jquery.leanmodal-tests.ts +++ b/jquery.leanmodal/jquery.leanmodal-tests.ts @@ -1,6 +1,3 @@ -/// - - class LeanModalOptions implements JQueryLeanModalOption { top : number; overlay : number; diff --git a/jquery.livestampjs/jquery.livestampjs-tests.ts b/jquery.livestampjs/jquery.livestampjs-tests.ts index dc713819c9..6b5bd01835 100644 --- a/jquery.livestampjs/jquery.livestampjs-tests.ts +++ b/jquery.livestampjs/jquery.livestampjs-tests.ts @@ -1,4 +1,3 @@ -/// import * as moment from 'moment'; $('#test1').livestamp(new Date('June 18, 1987')); diff --git a/jquery.menuaim/jquery.menuaim-tests.ts b/jquery.menuaim/jquery.menuaim-tests.ts index e2a1b36aff..01baa59e03 100644 --- a/jquery.menuaim/jquery.menuaim-tests.ts +++ b/jquery.menuaim/jquery.menuaim-tests.ts @@ -1,5 +1,3 @@ -/// - $('div').menuAim({ activate: function () { }, deactivate: function () { }, diff --git a/jquery.mmenu/jquery.mmenu-tests.ts b/jquery.mmenu/jquery.mmenu-tests.ts index 385f479507..a08f4371ec 100644 --- a/jquery.mmenu/jquery.mmenu-tests.ts +++ b/jquery.mmenu/jquery.mmenu-tests.ts @@ -1,7 +1,3 @@ -/// -/// - - // -------------------------------------------------------- // ---------------- TEST DEFAULT OPTIONS ------------------ // -------------------------------------------------------- diff --git a/jquery.payment/index.d.ts b/jquery.payment/index.d.ts index 341e695a9a..88ecd255a5 100644 --- a/jquery.payment/index.d.ts +++ b/jquery.payment/index.d.ts @@ -3,6 +3,8 @@ // Definitions by: Eric J. Smith , John Rutherford // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + declare namespace JQueryPayment { interface Payment { diff --git a/jquery.payment/jquery.payment-tests.ts b/jquery.payment/jquery.payment-tests.ts index db02b96d90..9eaad853cb 100644 --- a/jquery.payment/jquery.payment-tests.ts +++ b/jquery.payment/jquery.payment-tests.ts @@ -1,6 +1,3 @@ -/// -/// - $.payment.cards.push({ // Card type, as returned by $.payment.cardType. type: 'mastercard', diff --git a/jquery.pjax.falsandtru/jquery.pjax.falsandtru-tests.ts b/jquery.pjax.falsandtru/jquery.pjax.falsandtru-tests.ts index 8bfb91a27e..b215b02b35 100644 --- a/jquery.pjax.falsandtru/jquery.pjax.falsandtru-tests.ts +++ b/jquery.pjax.falsandtru/jquery.pjax.falsandtru-tests.ts @@ -1,6 +1,3 @@ - -/// - function test_pjax() { $.pjax(); } diff --git a/jquery.pjax/jquery.pjax-tests.ts b/jquery.pjax/jquery.pjax-tests.ts index 25422922d8..91cc9391a2 100644 --- a/jquery.pjax/jquery.pjax-tests.ts +++ b/jquery.pjax/jquery.pjax-tests.ts @@ -1,6 +1,3 @@ - -/// - function test_fn_pjax() { $(document).pjax("a"); $(document).pjax("a", "#pjax-container"); diff --git a/jquery.placeholder/jquery.placeholder-tests.ts b/jquery.placeholder/jquery.placeholder-tests.ts index edaf3ea111..04c526b352 100644 --- a/jquery.placeholder/jquery.placeholder-tests.ts +++ b/jquery.placeholder/jquery.placeholder-tests.ts @@ -1,5 +1,3 @@ -/// - $('input').placeholder(); // specify custom class diff --git a/jquery.pnotify/jquery.pnotify-tests.ts b/jquery.pnotify/jquery.pnotify-tests.ts index 41cd7d3fda..f1b8ffb73e 100644 --- a/jquery.pnotify/jquery.pnotify-tests.ts +++ b/jquery.pnotify/jquery.pnotify-tests.ts @@ -1,6 +1,3 @@ -/// - - function test_pnotify() { diff --git a/jquery.prettyphoto/jquery.prettyphoto-tests.ts b/jquery.prettyphoto/jquery.prettyphoto-tests.ts index 4fcbf9ecdf..888d68ada4 100644 --- a/jquery.prettyphoto/jquery.prettyphoto-tests.ts +++ b/jquery.prettyphoto/jquery.prettyphoto-tests.ts @@ -1,8 +1,3 @@ -// Tests for prettyPhoto library - -/// - - // JQUERY $('#id').prettyPhoto(); diff --git a/jquery.qrcode/jquery.qrcode-tests.ts b/jquery.qrcode/jquery.qrcode-tests.ts index a634bd6f07..d007b203da 100644 --- a/jquery.qrcode/jquery.qrcode-tests.ts +++ b/jquery.qrcode/jquery.qrcode-tests.ts @@ -1,5 +1,3 @@ -/// - // Examples from website (note: the examples use color instead of fill, which is not supported) $('.container').qrcode(); diff --git a/jquery.rowgrid/jquery.rowgrid-tests.ts b/jquery.rowgrid/jquery.rowgrid-tests.ts index ba3e5f822d..3f1427c94a 100644 --- a/jquery.rowgrid/jquery.rowgrid-tests.ts +++ b/jquery.rowgrid/jquery.rowgrid-tests.ts @@ -1,12 +1,10 @@ -/// - /* * Test different options */ var options = { - minMargin: 10, - maxMargin: 35, + minMargin: 10, + maxMargin: 35, itemSelector: ".item" }; diff --git a/jquery.scrollto/jquery.scrollto-tests.ts b/jquery.scrollto/jquery.scrollto-tests.ts index 303ce0cd01..fcdc2f50bb 100644 --- a/jquery.scrollto/jquery.scrollto-tests.ts +++ b/jquery.scrollto/jquery.scrollto-tests.ts @@ -1,5 +1,3 @@ -/// - $('div').scrollTo(340); $('div').scrollTo('+=340px', { axis: 'y' }); diff --git a/jquery.simplemodal/jquery.simplemodal-tests.ts b/jquery.simplemodal/jquery.simplemodal-tests.ts index 8e73e057cc..0784f0eeeb 100644 --- a/jquery.simplemodal/jquery.simplemodal-tests.ts +++ b/jquery.simplemodal/jquery.simplemodal-tests.ts @@ -1,7 +1,5 @@ // Tests taken from documentation: http://www.ericmmartin.com/projects/simplemodal/ -/// - // Chained call with no options $("#sample").modal(); diff --git a/jquery.simplepagination/jquery.simplepagination-tests.ts b/jquery.simplepagination/jquery.simplepagination-tests.ts index b35a6f42a0..075fe02628 100644 --- a/jquery.simplepagination/jquery.simplepagination-tests.ts +++ b/jquery.simplepagination/jquery.simplepagination-tests.ts @@ -1,5 +1,3 @@ -/// - var selector = '#elementId'; $(function () { diff --git a/jquery.slimscroll/jquery.slimscroll-tests.ts b/jquery.slimscroll/jquery.slimscroll-tests.ts index 0d4be5af94..a0368d07e9 100644 --- a/jquery.slimscroll/jquery.slimscroll-tests.ts +++ b/jquery.slimscroll/jquery.slimscroll-tests.ts @@ -1,5 +1,3 @@ -/// - $("div").slimScroll(); $("div").slimScroll({ diff --git a/jquery.tagsmanager/jquery.tagsmanager-tests.ts b/jquery.tagsmanager/jquery.tagsmanager-tests.ts index 33af6a8b7b..26a75e8310 100644 --- a/jquery.tagsmanager/jquery.tagsmanager-tests.ts +++ b/jquery.tagsmanager/jquery.tagsmanager-tests.ts @@ -1,6 +1,3 @@ -/// - - var options: ITagsManagerOptions = { prefilled: ["Pisa", "Rome"], CapitalizeFirstLetter: true, diff --git a/jquery.timeago/jquery.timeago-tests.ts b/jquery.timeago/jquery.timeago-tests.ts index 2a852331be..f77b40b121 100644 --- a/jquery.timeago/jquery.timeago-tests.ts +++ b/jquery.timeago/jquery.timeago-tests.ts @@ -1,5 +1,3 @@ -/// - // Basic usage var jQueryElement: JQuery = jQuery("abbr.timeago").timeago(); diff --git a/jquery.timepicker/jquery.timepicker-tests.ts b/jquery.timepicker/jquery.timepicker-tests.ts index cbb14dfe7c..52329cf11a 100644 --- a/jquery.timepicker/jquery.timepicker-tests.ts +++ b/jquery.timepicker/jquery.timepicker-tests.ts @@ -1,5 +1,3 @@ -/// - var beforeShowCallback, onSelectCallback, onCloseCallback, onHourShow, onMinuteShow; $('#timepicker').timepicker({ timeSeparator: ':', diff --git a/jquery.timer/jquery.timer-tests.ts b/jquery.timer/jquery.timer-tests.ts index e5d1cdaa3a..1c6653bfdb 100644 --- a/jquery.timer/jquery.timer-tests.ts +++ b/jquery.timer/jquery.timer-tests.ts @@ -1,31 +1,28 @@ -/// +// Create the timer +$("body").timer( + function () { + console.log("This function just got called"); + }, 10000, true +); +$("body").timer.set({ time: 5000 }); // Change the time from 10000 millseconds to 5000 milliseconds +$("body").timer.toggle(false); // Reset the timer +$("body").timer.stop(); // Stop the timer +$("body").timer.play(); // Start / play the timer - // Create the timer - $("body").timer( - function () { - console.log("This function just got called"); - }, 10000, true - ); +// #region Outputting if timer is active or not +var isTimerActive = $("body").timer.isActive; // Define boolean isActive as isTimerActive +if (isTimerActive == true){ + console.log("Timer is active!"); +} +else{ + console.log("Timer is not active!"); +} +// #endregion - $("body").timer.set({ time: 5000 }); // Change the time from 10000 millseconds to 5000 milliseconds - $("body").timer.toggle(false); // Reset the timer - $("body").timer.stop(); // Stop the timer - $("body").timer.play(); // Start / play the timer +// #region Get time remaining +console.log("Time remaining on timer: " + $("body").timer.remaining.toString); +// #endregion - // #region Outputting if timer is active or not - var isTimerActive = $("body").timer.isActive; // Define boolean isActive as isTimerActive - if (isTimerActive == true){ - console.log("Timer is active!"); - } - else{ - console.log("Timer is not active!"); - } - // #endregion - - // #region Get time remaining - console.log("Time remaining on timer: " + $("body").timer.remaining.toString); - // #endregion - - $("body").timer.stop(); // Stop the timer once more for the purpose of the tests (to test once()) - $("body").timer.once(1000); // Run the timer ONCE in 1 second \ No newline at end of file +$("body").timer.stop(); // Stop the timer once more for the purpose of the tests (to test once()) +$("body").timer.once(1000); // Run the timer ONCE in 1 second \ No newline at end of file diff --git a/jquery.tipsy/jquery.tipsy-tests.ts b/jquery.tipsy/jquery.tipsy-tests.ts index e307e5d364..09ba7f2d68 100644 --- a/jquery.tipsy/jquery.tipsy-tests.ts +++ b/jquery.tipsy/jquery.tipsy-tests.ts @@ -1,5 +1,3 @@ -/// - // basic $('#example-1').tipsy(); diff --git a/jquery.tools/jquery.tools-tests.ts b/jquery.tools/jquery.tools-tests.ts index f8a4e39f90..443425e76b 100644 --- a/jquery.tools/jquery.tools-tests.ts +++ b/jquery.tools/jquery.tools-tests.ts @@ -1,5 +1,3 @@ -/// - /* from documentation at http://jquerytools.github.io/documentation/overlay/index.html */ $("img[rel]").overlay(); @@ -40,7 +38,7 @@ $("#prompt form").submit(function(this: JQuery, e: JQueryEventObject) {   // close the overlay triggers.eq(1).overlay().close(); - //or more straightforward: + // or more straightforward: triggers.data('overlay').close();   // get user input @@ -53,7 +51,7 @@ $("#prompt form").submit(function(this: JQuery, e: JQueryEventObject) { return e.preventDefault(); }); -$.tools.overlay.addEffect('', function() {}, function() {}); +$.tools.overlay.addEffect('', () => {}, () => {}); /* custom effects */ $.tools.overlay.addEffect("myEffect", function(position, done) { @@ -101,8 +99,7 @@ $(function() { mask: 'darkred', effect: 'apple',   - onBeforeLoad: function() { -  + onBeforeLoad() { // grab wrapper element inside content var wrap = this.getOverlay().find(".contentWrap");   @@ -113,7 +110,7 @@ $(function() { }); }); -$(function() { +$(() => { // positions for each overlay var positions = [ [0, 530], @@ -169,7 +166,7 @@ $.tools.overlay.addEffect("drop", function(css, done) { /* closing animation */ }, function(done) { this.getOverlay().animate( - {top:'-=55', opacity:0, width:'-=20'}, 300, 'drop', + { top: '-=55', opacity: 0, width: '-=20' }, 300, 'drop', function(this: JQuery) { $(this).hide(); done.call(null); diff --git a/jquery.total-storage/jquery.total-storage-tests.ts b/jquery.total-storage/jquery.total-storage-tests.ts index 0a23dd67cf..37ebb1ca73 100644 --- a/jquery.total-storage/jquery.total-storage-tests.ts +++ b/jquery.total-storage/jquery.total-storage-tests.ts @@ -1,10 +1,3 @@ -// Type definitions for jQueryTotalStorage 1.1.2 -// Project: https://github.com/Upstatement/jquery-total-storage -// Definitions by: Jeremy Brooks -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - //direct call $.totalStorage("test_key1", "test_value"); var val1:string = $.totalStorage("test_key"); diff --git a/jquery.transit/jquery.transit-tests.ts b/jquery.transit/jquery.transit-tests.ts index 2a672ec979..4f3b41f228 100644 --- a/jquery.transit/jquery.transit-tests.ts +++ b/jquery.transit/jquery.transit-tests.ts @@ -1,5 +1,3 @@ -/// - class TransitOptions implements JQueryTransitOptions { opacity: number; duration: number; diff --git a/jquery.ui.datetimepicker/jquery.ui.datetimepicker-tests.ts b/jquery.ui.datetimepicker/jquery.ui.datetimepicker-tests.ts index 44996637da..00ba4fe297 100644 --- a/jquery.ui.datetimepicker/jquery.ui.datetimepicker-tests.ts +++ b/jquery.ui.datetimepicker/jquery.ui.datetimepicker-tests.ts @@ -1,9 +1,6 @@ -/// - - // basic no options $('#datetimepicker').datetimepicker({ - + }); // basic with some options diff --git a/jquery.validation/jquery.validation-tests.ts b/jquery.validation/jquery.validation-tests.ts index 0b2de520f2..68062d6e1c 100644 --- a/jquery.validation/jquery.validation-tests.ts +++ b/jquery.validation/jquery.validation-tests.ts @@ -1,6 +1,4 @@ -/// -/// - +/// function test_validate() { $("#commentForm").validate(); @@ -264,4 +262,3 @@ function test_static_methods() { jQuery.validator.format('{0} {1}', 'a', 2); jQuery.validator.format('{0} {1}', ['a', 2]); } - \ No newline at end of file diff --git a/jquery.watermark/jquery.watermark-tests.ts b/jquery.watermark/jquery.watermark-tests.ts index 225ba0a482..e92ec0df11 100644 --- a/jquery.watermark/jquery.watermark-tests.ts +++ b/jquery.watermark/jquery.watermark-tests.ts @@ -1,5 +1,3 @@ -/// - $('#inputId').watermark('Required information'); $('#inputId').watermark('Required information', { className: 'myClassName' }); $('#inputId').watermark('Search', { useNative: false }); diff --git a/jquery.window/jquery.window-tests.ts b/jquery.window/jquery.window-tests.ts index 4b1b9b6eb2..15021cad7d 100644 --- a/jquery.window/jquery.window-tests.ts +++ b/jquery.window/jquery.window-tests.ts @@ -1,5 +1,3 @@ -/// - function example_1() { $.window({ title: "Cyclops Studio", @@ -20,13 +18,13 @@ function example_2() { function example_3() { // prepare customerized static attributes, see static attributes - // Note: you should call this method before starting to create window instances, or windows might display wrong. + // Note: you should call this method before starting to create window instances, or windows might display wrong. $.window.prepare({ dock: 'bottom', // change the dock direction: 'left', 'right', 'top', 'bottom' animationSpeed: 200, // set animation speed minWinLong: 180 // set minimized window long dimension width in pixel }); - + // limit window within body $.window({ icon: 'http://www.fstoke.me/favicon.ico', @@ -51,7 +49,7 @@ function example_3() { x: 80, y: 80 }); - + // assign the dock area $.window.prepare({ dock: 'bottom', // change the dock direction: 'left', 'right', 'top', 'bottom' diff --git a/jquery/index.d.ts b/jquery/index.d.ts index 3a785530aa..0a47546193 100644 --- a/jquery/index.d.ts +++ b/jquery/index.d.ts @@ -1166,25 +1166,28 @@ interface JQueryStatic { * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. * * @param collection The object or array to iterate over. - * @param callback The function that will be executed on every object. + * @param callback The function that will be executed on every object. Will break the loop by returning false. + * @returns the first argument, the object that is iterated. * @see {@link https://api.jquery.com/jQuery.each/#jQuery-each-array-callback} */ each( collection: T[], - callback: (indexInArray: number, valueOfElement: T) => any - ): any; + callback: (indexInArray: number, valueOfElement: T) => boolean | void + ): T[]; /** * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. * * @param collection The object or array to iterate over. - * @param callback The function that will be executed on every object. + * @param callback The function that will be executed on every object. Will break the loop by returning false. + * @returns the first argument, the object that is iterated. * @see {@link https://api.jquery.com/jQuery.each/#jQuery-each-object-callback} */ - each( - collection: any, - callback: (indexInArray: any, valueOfElement: any) => any - ): any; + each( + collection: T, + // TODO: `(keyInObject: keyof T, valueOfElement: T[keyof T])`, when TypeScript 2.1 allowed in repository + callback: (keyInObject: string, valueOfElement: any) => boolean | void + ): T; /** * Merge the contents of two or more objects together into the first object. @@ -1240,7 +1243,7 @@ interface JQueryStatic { * @param obj Object to test whether or not it is an array. * @see {@link https://api.jquery.com/jQuery.isArray/} */ - isArray(obj: any): boolean; + isArray(obj: any): obj is Array; /** * Check to see if an object is empty (contains no enumerable properties). * @@ -1254,7 +1257,7 @@ interface JQueryStatic { * @param obj Object to test whether or not it is a function. * @see {@link https://api.jquery.com/jQuery.isFunction/} */ - isFunction(obj: any): boolean; + isFunction(obj: any): obj is Function; /** * Determines whether its argument is a number. * @@ -1275,7 +1278,7 @@ interface JQueryStatic { * @param obj Object to test whether or not it is a window. * @see {@link https://api.jquery.com/jQuery.isWindow/} */ - isWindow(obj: any): boolean; + isWindow(obj: any): obj is Window; /** * Check to see if a DOM node is within an XML document (or is an XML document). * @@ -1360,7 +1363,7 @@ interface JQueryStatic { * @param obj Object to get the internal JavaScript [[Class]] of. * @see {@link https://api.jquery.com/jQuery.type/} */ - type(obj: any): string; + type(obj: any): "array" | "boolean" | "date" | "error" | "function" | "null" | "number" | "object" | "regexp" | "string" | "symbol" | "undefined"; /** * Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers. @@ -1368,7 +1371,7 @@ interface JQueryStatic { * @param array The Array of DOM elements. * @see {@link https://api.jquery.com/jQuery.unique/} */ - unique(array: Element[]): Element[]; + unique(array: T[]): T[]; /** * Parses a string into an array of DOM nodes. @@ -3301,10 +3304,10 @@ interface JQuery { /** * Iterate over a jQuery object, executing a function for each matched element. * - * @param func A function to execute for each matched element. + * @param func A function to execute for each matched element. Can stop the loop by returning false. * @see {@link https://api.jquery.com/each/} */ - each(func: (index: number, elem: Element) => any): JQuery; + each(func: (index: number, elem: Element) => boolean | void): JQuery; /** * Retrieve one of the elements matched by the jQuery object. @@ -3457,7 +3460,7 @@ interface JQuery { * @param func A function used as a test for each element in the set. this is the current DOM element. * @see {@link https://api.jquery.com/filter/#filter-function} */ - filter(func: (index: number, element: Element) => any): JQuery; + filter(func: (index: number, element: Element) => boolean): JQuery; /** * Reduce the set of matched elements to those that match the selector or pass the function's test. * diff --git a/jquery/jquery-tests.ts b/jquery/jquery-tests.ts index e11a8b806f..d2d58aa2a2 100644 --- a/jquery/jquery-tests.ts +++ b/jquery/jquery-tests.ts @@ -100,16 +100,18 @@ function test_ajax() { if (getAllResponseHeaders()) { return getAllResponseHeaders(); } - var allHeaders = ""; - $(["Cache-Control", "Content-Language", "Content-Type", - "Expires", "Last-Modified", "Pragma"]).each(function (i, header_name) { - if (xhr.getResponseHeader(header_name)) { - allHeaders += header_name + ": " + xhr.getResponseHeader(header_name) + "\n"; - } - return allHeaders; - }); + var allHeaders = ""; + var headersFieldNames = ["Cache-Control", "Content-Language", "Content-Type", + "Expires", "Last-Modified", "Pragma"]; + $(headersFieldNames).each(function (i, header_name) { + if (xhr.getResponseHeader(header_name)) { + allHeaders += header_name + ": " + xhr.getResponseHeader(header_name) + "\n"; + } + }); + return allHeaders; }; + return xhr; }; $.ajax({ @@ -1392,9 +1394,24 @@ function test_detach() { } function test_each() { - $.each([52, 97], function (index, value) { + var numArray: number[]; + numArray = $.each([1, 2, 3, 4], function (index: number, value: number) { alert(index + ': ' + value); }); + numArray = $.each([1, 2, 3, 4], function (index: number, value: number) { + alert(index + ': ' + value); + return value < 2; + }); + + var res: {one: number, 2: string}; + res = $.each({ one: 1, 2: "two" }, function(key: string, value: any) { + alert(key + ': ' + value); + }); + res = $.each({ one: 1, 2: "two" }, function(key: string, value: any) { + alert(key + ': ' + value); + return key === "2"; + }); + var map = { 'flammable': 'inflammable', 'duh': 'no duh' @@ -1404,8 +1421,7 @@ function test_each() { }); var arr = ["one", "two", "three", "four", "five"]; var obj = { one: 1, two: 2, three: 3, four: 4, five: 5 }; - // TODO: Should not need explicit type annotation https://github.com/Microsoft/TypeScript/issues/10072 - jQuery.each(arr, function () { + jQuery.each(arr, function () { $("#" + this).text("Mine is " + this + "."); return (this != "three"); }); @@ -1482,9 +1498,10 @@ function test_error() { $(this).hide(); }) .attr("src", "missing.png"); + jQuery.error("Oups"); jQuery.error = (message?: string) => { console.error(message); return this; - } + }; } function test_eventParams() { @@ -1516,7 +1533,7 @@ function test_eventParams() { function propStopped(e) { var msg = ""; if (e.isPropagationStopped()) { - msg = "called" + msg = "called"; } else { msg = "not called"; } @@ -1703,11 +1720,11 @@ function test_fadeToggle() { function test_filter() { $('li').filter(':even').css('background-color', 'red'); $('li').filter(function (index) { - return index % 3 == 2; + return index % 3 === 2; }).css('background-color', 'red'); $("div").css("background", "#b4b0da") .filter(function (index) { - return index == 1 || $(this).attr("id") == "fourth"; + return index === 1 || $(this).attr("id") === "fourth"; }) .css("border", "3px double red"); $("div").filter(document.getElementById("unique")); @@ -1879,7 +1896,7 @@ function test_getJSON() { function (data) { $.each(data.items, function (i, item) { $("").attr("src", item.media.m).appendTo("#images"); - if (i == 3) return false; + if (i === "3") return false; }); }); $.getJSON("test.js", function (json) { @@ -2524,6 +2541,17 @@ function test_is() { }); } +function test_isTypeGuards() { + var foo: number[] | ((x: string) => number) | Window; + if (jQuery.isArray(foo)) { + foo.push(1515); + } else if (jQuery.isWindow(foo)) { + foo.close(); + } else if (jQuery.isFunction(foo)) { + foo("hello world"); + } +} + function test_isArray() { $("b").append("" + $.isArray([])); } @@ -2582,6 +2610,16 @@ function test_isXMLDoc() { jQuery.isXMLDoc(document.body); } +function test_unique() { + jQuery.unique($('div.foo, div.bar').get()); + jQuery.unique($('div.foo, div.bar').toArray()); + + var divs: HTMLDivElement[]; + var unique: HTMLDivElement[]; + unique = jQuery.unique(divs); + unique = jQuery.unique(divs); +} + function test_jQuery() { $('div.foo'); $('div.foo').click(function () { diff --git a/jquerymobile/jquerymobile-tests.ts b/jquerymobile/jquerymobile-tests.ts index 105edc3f88..e7fbf3bfff 100644 --- a/jquerymobile/jquerymobile-tests.ts +++ b/jquerymobile/jquerymobile-tests.ts @@ -1,6 +1,3 @@ -/// - - function test_api() { $.mobile.changePage("about/us.html", { transition: "slideup" }); $.mobile.changePage("searchresults.php", { diff --git a/jqueryui/jqueryui-tests.ts b/jqueryui/jqueryui-tests.ts index 2cce742f86..5755738622 100644 --- a/jqueryui/jqueryui-tests.ts +++ b/jqueryui/jqueryui-tests.ts @@ -1,6 +1,3 @@ -/// - - function test_draggable() { $("#draggable").draggable({ axis: "y" }); diff --git a/js-quantities/js-quantities-tests.ts b/js-quantities/js-quantities-tests.ts index 95819381b5..ed69816dc3 100644 --- a/js-quantities/js-quantities-tests.ts +++ b/js-quantities/js-quantities-tests.ts @@ -1,6 +1,21 @@ -/// import Qty from "js-quantities"; +declare function describe(desc: string, fn: () => void): void; +declare function it(desc: string, fn: () => void): void; +interface Expect { + not: this; + toBe(y: T): void; + toEqual(y: T): void; + toBeTruthy(): void; + toBeNull(): void; + toBeCloseTo(this: Expect, x: number, sigFigs: number): void; + toThrow(this: Expect<() => void>, msg?: string): void; + toContain(this: Expect, x: U): void; +}; +declare function expect(x: T): Expect; +declare function beforeEach(f: () => void): void; +declare function afterEach(f: () => void): void; + // From project readme let qty: Qty; diff --git a/jsonschema/index.d.ts b/jsonschema/index.d.ts deleted file mode 100644 index 8d182b50b9..0000000000 --- a/jsonschema/index.d.ts +++ /dev/null @@ -1,104 +0,0 @@ -// Type definitions for jsonschema -// Project: https://github.com/tdegrunt/jsonschema -// Definitions by: Vlado Tešanovic , kinesivan -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "jsonschema" { - - export interface IJSONSchemaResult { - errors: Array; - instance: any; - arguments: Array<{}>; - propertyPath: string; - name: string; - schema: {}; - valid: boolean; - throwError: any; - disableFormat: boolean; - } - - export interface IJSONSchemaValidationError { - message: string; - property: string; - stack: string; - schema: {}; - name: string; - instance: any; - argument: {}; - } - - export interface IJSONSchemaOptions { - propertyName?: string; - base?: string; - } - - /** - * How to; - * - * const v: Validator = new Validator(); - * - * const schema: {} = { - * "type": "object", - * "properties": { - * "key": { - * "type": "string", - * "required": true - * }, - * "value": { - * "type": "string", - * "required": true - * } - * } - * }; - * - * const validationResults: { errors: Array } = - * v.validate({ key: "Name", value: "A10" }, {"type": "string"}); - * - */ - export class Validator { - - /** - * Creates a new Validator object - * @name Validator - * @constructor - */ - new(): this; - - /** - * Validates instance against the provided schema - * @param instance - * @param schema - * @param [options] - * @param [ctx] - * @return {Array} - */ - validate(instance: any, schema: {}, options?: IJSONSchemaOptions, ctx?: {}): IJSONSchemaResult; - - /** - * Adds a schema with a certain urn to the Validator instance. - * @param schema - * @param urn - * @return {Object} - */ - addSchema(schema: {}, urn: string): {}; - - /** - * Add Sub schema to existing one - * @param baseuri - * @param schema - */ - addSubSchema(baseuri: string, schema: {}): {} - - /** - * Sets all the schemas of the Validator instance. - * @param schemas - */ - setSchemas (schemas: Array<{}>): void; - - /** - * Returns the schema of a certain urn - * @param urn - */ - getSchema(urn: string): {}; - } -} - diff --git a/jsonschema/jsonschema-tests.ts b/jsonschema/jsonschema-tests.ts deleted file mode 100644 index 83e81b2027..0000000000 --- a/jsonschema/jsonschema-tests.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { Validator, IJSONSchemaValidationError } from "jsonschema"; - -const v: Validator = new Validator(); - -const validationResults: { errors: Array } = v.validate("Smith", {"type": "string"}); diff --git a/jsonwebtoken/jsonwebtoken-tests.ts b/jsonwebtoken/jsonwebtoken-tests.ts index 4a939becbc..e591f31159 100644 --- a/jsonwebtoken/jsonwebtoken-tests.ts +++ b/jsonwebtoken/jsonwebtoken-tests.ts @@ -1,10 +1,8 @@ -/** - * Test suite created by Maxime LUCE - * +/** + * Test suite created by Maxime LUCE + * * Created by using code samples from https://github.com/auth0/node-jsonwebtoken. - */ - -/// + */ import jwt = require("jsonwebtoken"); import fs = require("fs"); @@ -49,7 +47,7 @@ jwt.verify(token, 'shhhhh', function(err, decoded) { // invalid token jwt.verify(token, 'wrong-secret', function(err, decoded) { - // err + // err // decoded undefined }); diff --git a/jsrender/jsrender-tests.ts b/jsrender/jsrender-tests.ts index d728f968ae..7b5bf5a525 100644 --- a/jsrender/jsrender-tests.ts +++ b/jsrender/jsrender-tests.ts @@ -1,5 +1,3 @@ -/// - $.views.converters("upper", function(val) { return val.toUpperCase(); }); diff --git a/jsx-chai/jsx-chai-tests.ts b/jsx-chai/jsx-chai-tests.ts index d421ae0874..48c49e7b25 100644 --- a/jsx-chai/jsx-chai-tests.ts +++ b/jsx-chai/jsx-chai-tests.ts @@ -1,5 +1,3 @@ -/// - import chai = require('chai'); import jsxChai = require('jsx-chai'); diff --git a/kafka-node/index.d.ts b/kafka-node/index.d.ts index 018b1a6f9e..a9992ccc52 100644 --- a/kafka-node/index.d.ts +++ b/kafka-node/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for kafka-node 1.3.3 // Project: https://github.com/SOHU-Co/kafka-node/ -// Definitions by: Daniel Imrie-Situnayake +// Definitions by: Daniel Imrie-Situnayake , Bill // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -9,22 +9,26 @@ export declare class Client { constructor(connectionString: string, clientId: string, options?: ZKOptions); close(callback?: Function): void; topicExists(topics: Array, callback: Function): void; + refreshMetadata(topics: Array, cb?: (error: any, data: any) => any): void; + close(cb: (error: any) => any): void; } export declare class Producer { - constructor(client: Client); + constructor(client: Client, options?: any, customPartitioner?: any); on(eventName: string, cb: () => any): void; on(eventName: string, cb: (error: any) => any): void; send(payloads: Array, cb: (error: any, data: any) => any): void; createTopics(topics: Array, async: boolean, cb?: (error: any, data: any) => any): void; + close(cb: (error: any) => any): void; } export declare class HighLevelProducer { - constructor(client: Client, options?: any); + constructor(client: Client, options?: any, customPartitioner?: any); on(eventName: string, cb: () => any): void; on(eventName: string, cb: (error: any) => any): void; send(payloads: Array, cb: (error: any, data: any) => any): void; createTopics(topics: Array, async: boolean, cb?: (error: any, data: any) => any): void; + close(cb: (error: any) => any): void; } export declare class Consumer { @@ -96,7 +100,7 @@ export interface ZKOptions { export interface ProduceRequest { topic: string; messages: any; // Array | Array | string | KeyedMessage - key?: string; + key?: any; partition?: number; attributes?: number; } diff --git a/kendo-ui/index.d.ts b/kendo-ui/index.d.ts index ecdbffae66..86f9624227 100644 --- a/kendo-ui/index.d.ts +++ b/kendo-ui/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Kendo UI Professional v2016.3.1029 +// Type definitions for Kendo UI Professional v2017.1.118 // Project: http://www.telerik.com/kendo-ui // Definitions by: Telerik // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -678,8 +678,8 @@ declare namespace kendo.data { static fields: DataSourceSchemaModelFields; id: any; - predecessorId: any; - successorId: any; + predecessorId: number; + successorId: number; type: number; static define(options: DataSourceSchemaModelWithFieldsObject): typeof GanttDependency; @@ -1135,7 +1135,7 @@ declare namespace kendo.data { interface DataSourceFilters extends DataSourceFilter { logic?: string; - filters?: DataSourceFilter[]; + filters?: DataSourceFilter[]; } interface DataSourceGroupItemAggregate { @@ -1656,6 +1656,7 @@ declare namespace kendo.ui { interface AutoCompleteOptions { name?: string; animation?: boolean|AutoCompleteAnimation; + autoWidth?: boolean; dataSource?: any|any|kendo.data.DataSource; clearButton?: boolean; dataTextField?: string; @@ -1790,6 +1791,7 @@ declare namespace kendo.ui { interface CalendarMonth { content?: string; + weekNumber?: string; empty?: string; } @@ -1804,6 +1806,7 @@ declare namespace kendo.ui { max?: Date; min?: Date; month?: CalendarMonth; + weekNumber?: boolean; start?: string; value?: Date; change?(e: CalendarEvent): void; @@ -1898,6 +1901,7 @@ declare namespace kendo.ui { interface ColorPickerOptions { name?: string; buttons?: boolean; + clearButton?: boolean; columns?: number; tileSize?: ColorPickerTileSize; messages?: ColorPickerMessages; @@ -2000,6 +2004,7 @@ declare namespace kendo.ui { name?: string; animation?: ComboBoxAnimation; autoBind?: boolean; + autoWidth?: boolean; cascadeFrom?: string; cascadeFromField?: string; clearButton?: boolean; @@ -2022,6 +2027,7 @@ declare namespace kendo.ui { placeholder?: string; popup?: ComboBoxPopup; suggest?: boolean; + syncValueAndText?: boolean; headerTemplate?: string|Function; template?: string|Function; text?: string; @@ -2159,6 +2165,7 @@ declare namespace kendo.ui { name?: string; alignToAnchor?: boolean; animation?: boolean|ContextMenuAnimation; + appendTo?: string|JQuery; closeOnClick?: boolean; dataSource?: any|any; direction?: string; @@ -2263,6 +2270,7 @@ declare namespace kendo.ui { interface DatePickerMonth { content?: string; + weekNumber?: string; empty?: string; } @@ -2279,6 +2287,7 @@ declare namespace kendo.ui { max?: Date; min?: Date; month?: DatePickerMonth; + weekNumber?: boolean; parseFormats?: any; start?: string; value?: Date; @@ -2353,6 +2362,7 @@ declare namespace kendo.ui { interface DateTimePickerMonth { content?: string; + weekNumber?: string; empty?: string; } @@ -2370,6 +2380,7 @@ declare namespace kendo.ui { max?: Date; min?: Date; month?: DateTimePickerMonth; + weekNumber?: boolean; parseFormats?: any; start?: string; timeFormat?: string; @@ -2558,6 +2569,7 @@ declare namespace kendo.ui { name?: string; animation?: boolean|DropDownListAnimation; autoBind?: boolean; + autoWidth?: boolean; cascadeFrom?: string; cascadeFromField?: string; dataSource?: any|any|kendo.data.DataSource; @@ -2986,6 +2998,7 @@ declare namespace kendo.ui { tooltip?: string; exec?: Function; items?: EditorToolItem[]; + palette?: string|any; template?: string; } @@ -3065,6 +3078,9 @@ declare namespace kendo.ui { clear?: string; filter?: string; info?: string; + additionalValue?: string; + additionalOperator?: string; + logic?: string; isFalse?: string; isTrue?: string; or?: string; @@ -3625,6 +3641,7 @@ declare namespace kendo.ui { } interface GridColumnCommandItem { + visible?: Function; name?: string; text?: GridColumnCommandItemText; className?: string; @@ -3659,6 +3676,7 @@ declare namespace kendo.ui { interface GridColumnSortable { compare?: Function; + initialDirection?: string; } interface GridColumn { @@ -3666,6 +3684,7 @@ declare namespace kendo.ui { attributes?: any; columns?: any; command?: GridColumnCommandItem[]; + editable?: Function; encoded?: boolean; field?: string; filterable?: boolean|GridColumnFilterable; @@ -3680,6 +3699,7 @@ declare namespace kendo.ui { hidden?: boolean; locked?: boolean; lockable?: boolean; + minResizableWidth?: number; minScreenWidth?: number; sortable?: boolean|GridColumnSortable; template?: string|Function; @@ -3779,8 +3799,8 @@ declare namespace kendo.ui { interface GridFilterable { extra?: boolean; messages?: GridFilterableMessages; - operators?: GridFilterableOperators; mode?: string; + operators?: GridFilterableOperators; } interface GridGroupableMessages { @@ -3873,6 +3893,7 @@ declare namespace kendo.ui { interface GridSortable { allowUnsort?: boolean; + initialDirection?: string; mode?: string; } @@ -4428,6 +4449,7 @@ declare namespace kendo.ui { animation?: boolean|MultiSelectAnimation; autoBind?: boolean; autoClose?: boolean; + autoWidth?: boolean; clearButton?: boolean; dataSource?: any|any|kendo.data.DataSource; dataTextField?: string; @@ -4797,15 +4819,30 @@ declare namespace kendo.ui { expand?: PanelBarAnimationExpand; } + interface PanelBarMessages { + loading?: string; + requestFailed?: string; + retry?: string; + } + interface PanelBarOptions { name?: string; animation?: boolean|PanelBarAnimation; + autoBind?: boolean; contentUrls?: any; - dataSource?: any|any; + dataImageUrlField?: string; + dataSource?: any|any|kendo.data.HierarchicalDataSource; + dataSpriteCssClassField?: string; + dataTextField?: string|any; + dataUrlField?: string; expandMode?: string; + loadOnDemand?: boolean; + messages?: PanelBarMessages; + template?: string|Function; activate?(e: PanelBarActivateEvent): void; collapse?(e: PanelBarCollapseEvent): void; contentLoad?(e: PanelBarContentLoadEvent): void; + dataBound?(e: PanelBarDataBoundEvent): void; error?(e: PanelBarErrorEvent): void; expand?(e: PanelBarExpandEvent): void; select?(e: PanelBarSelectEvent): void; @@ -4829,6 +4866,10 @@ declare namespace kendo.ui { contentElement?: Element; } + interface PanelBarDataBoundEvent extends PanelBarEvent { + node?: JQuery; + } + interface PanelBarErrorEvent extends PanelBarEvent { xhr?: JQueryXHR; status?: string; @@ -5629,6 +5670,7 @@ declare namespace kendo.ui { eventTemplate?: string|Function; footer?: boolean|SchedulerFooter; group?: SchedulerGroup; + groupHeaderTemplate?: string|Function; height?: number|string; majorTick?: number; majorTimeHeaderTemplate?: string|Function; @@ -5647,7 +5689,6 @@ declare namespace kendo.ui { timezone?: string; toolbar?: SchedulerToolbarItem[]; views?: SchedulerView[]; - groupHeaderTemplate?: string|Function; width?: number|string; workDayStart?: Date; workDayEnd?: Date; @@ -6021,6 +6062,9 @@ declare namespace kendo.ui { activeSheet(): kendo.spreadsheet.Sheet; activeSheet(sheet?: kendo.spreadsheet.Sheet): void; + cellContextMenu(): kendo.ui.ContextMenu; + rowHeaderContextMenu(): kendo.ui.ContextMenu; + colHeaderContextMenu(): kendo.ui.ContextMenu; sheets(): any; fromFile(blob: Blob): JQueryPromise; fromFile(blob: File): JQueryPromise; @@ -6040,6 +6084,17 @@ declare namespace kendo.ui { } + interface SpreadsheetDefaultCellStyle { + background?: string; + color?: string; + fontFamily?: string; + fontSize?: string; + Italic?: boolean; + bold?: boolean; + underline?: boolean; + wrap?: boolean; + } + interface SpreadsheetExcel { fileName?: string; forceProxy?: boolean; @@ -6209,6 +6264,7 @@ declare namespace kendo.ui { activeSheet?: string; columnWidth?: number; columns?: number; + defaultCellStyle?: SpreadsheetDefaultCellStyle; headerHeight?: number; headerWidth?: number; excel?: SpreadsheetExcel; @@ -6218,6 +6274,20 @@ declare namespace kendo.ui { sheets?: SpreadsheetSheet[]; sheetsbar?: boolean; toolbar?: boolean|SpreadsheetToolbar; + insertSheet?(e: SpreadsheetInsertSheetEvent): void; + removeSheet?(e: SpreadsheetRemoveSheetEvent): void; + renameSheet?(e: SpreadsheetRenameSheetEvent): void; + selectSheet?(e: SpreadsheetSelectSheetEvent): void; + unhideColumn?(e: SpreadsheetUnhideColumnEvent): void; + unhideRow?(e: SpreadsheetUnhideRowEvent): void; + hideColumn?(e: SpreadsheetHideColumnEvent): void; + hideRow?(e: SpreadsheetHideRowEvent): void; + deleteColumn?(e: SpreadsheetDeleteColumnEvent): void; + deleteRow?(e: SpreadsheetDeleteRowEvent): void; + insertColumn?(e: SpreadsheetInsertColumnEvent): void; + insertRow?(e: SpreadsheetInsertRowEvent): void; + select?(e: SpreadsheetSelectEvent): void; + changeFormat?(e: SpreadsheetChangeFormatEvent): void; change?(e: SpreadsheetChangeEvent): void; render?(e: SpreadsheetRenderEvent): void; excelExport?(e: SpreadsheetExcelExportEvent): void; @@ -6230,6 +6300,70 @@ declare namespace kendo.ui { isDefaultPrevented(): boolean; } + interface SpreadsheetInsertSheetEvent extends SpreadsheetEvent { + } + + interface SpreadsheetRemoveSheetEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + } + + interface SpreadsheetRenameSheetEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + newSheetName?: string; + } + + interface SpreadsheetSelectSheetEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + } + + interface SpreadsheetUnhideColumnEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetUnhideRowEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetHideColumnEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetHideRowEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetDeleteColumnEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetDeleteRowEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetInsertColumnEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetInsertRowEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetSelectEvent extends SpreadsheetEvent { + range?: kendo.spreadsheet.Range; + } + + interface SpreadsheetChangeFormatEvent extends SpreadsheetEvent { + range?: kendo.spreadsheet.Range; + } + interface SpreadsheetChangeEvent extends SpreadsheetEvent { range?: kendo.spreadsheet.Range; } @@ -6616,6 +6750,7 @@ declare namespace kendo.ui { options: TooltipOptions; + popup: kendo.ui.Popup; element: JQuery; wrapper: JQuery; @@ -6774,6 +6909,7 @@ declare namespace kendo.ui { interface TouchSwipeEvent extends TouchEvent { touch?: kendo.mobile.ui.TouchEventOptions; event?: JQueryEventObject; + direction?: string; } interface TouchGesturestartEvent extends TouchEvent { @@ -6873,6 +7009,7 @@ declare namespace kendo.ui { interface TreeListColumnCommandItem { className?: string; + imageClass?: string; click?: Function; name?: string; text?: string; @@ -7344,15 +7481,16 @@ declare namespace kendo.ui { clearAllFiles(): void; - clearFile(): void; + clearFile(callback: Function): void; clearFileByUid(uid: string): void; destroy(): void; disable(): void; enable(enable?: boolean): void; + focus(): void; getFiles(): any; removeAllFiles(): void; - removeFile(): void; - removeFileByUid(): void; + removeFile(callback: Function): void; + removeFileByUid(uid: string): void; toggle(enable: boolean): void; upload(): void; @@ -7412,6 +7550,7 @@ declare namespace kendo.ui { template?: string|Function; validation?: UploadValidation; cancel?(e: UploadCancelEvent): void; + clear?(e: UploadClearEvent): void; complete?(e: UploadEvent): void; error?(e: UploadErrorEvent): void; progress?(e: UploadProgressEvent): void; @@ -7427,39 +7566,43 @@ declare namespace kendo.ui { } interface UploadCancelEvent extends UploadEvent { - files?: UploadFile[]; + files?: any[]; + } + + interface UploadClearEvent extends UploadEvent { + e?: any; } interface UploadErrorEvent extends UploadEvent { - files?: UploadFile[]; + files?: any[]; operation?: string; XMLHttpRequest?: any; } interface UploadProgressEvent extends UploadEvent { - files?: UploadFile[]; + files?: any[]; percentComplete?: number; } interface UploadRemoveEvent extends UploadEvent { - files?: UploadFile[]; + files?: any[]; data?: any; } interface UploadSelectEvent extends UploadEvent { e?: any; - files?: UploadFile[]; + files?: any[]; } interface UploadSuccessEvent extends UploadEvent { - files?: UploadFile[]; + files?: any[]; operation?: string; response?: any; XMLHttpRequest?: any; } interface UploadUploadEvent extends UploadEvent { - files?: UploadFile[]; + files?: any[]; data?: any; formData?: any; XMLHttpRequest?: any; @@ -7496,6 +7639,7 @@ declare namespace kendo.ui { rules?: any; validateOnBlur?: boolean; validate?(e: ValidatorValidateEvent): void; + validateInput?(e: ValidatorValidateInputEvent): void; } interface ValidatorEvent { sender: Validator; @@ -7507,6 +7651,11 @@ declare namespace kendo.ui { valid?: boolean; } + interface ValidatorValidateInputEvent extends ValidatorEvent { + input?: JQuery; + valid?: boolean; + } + class Window extends kendo.ui.Widget { @@ -7629,6 +7778,274 @@ declare namespace kendo.ui { } +} +declare namespace kendo.geometry { + class Arc extends Observable { + + + options: ArcOptions; + + anticlockwise: boolean; + center: kendo.geometry.Point; + endAngle: number; + radiusX: number; + radiusY: number; + startAngle: number; + + constructor(center: any|kendo.geometry.Point, options?: ArcOptions); + + + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + getAnticlockwise(): boolean; + getCenter(): kendo.geometry.Point; + getEndAngle(): number; + getRadiusX(): number; + getRadiusY(): number; + getStartAngle(): number; + pointAt(angle: number): kendo.geometry.Point; + setAnticlockwise(value: boolean): kendo.geometry.Arc; + setCenter(value: kendo.geometry.Point): kendo.geometry.Arc; + setEndAngle(value: number): kendo.geometry.Arc; + setRadiusX(value: number): kendo.geometry.Arc; + setRadiusY(value: number): kendo.geometry.Arc; + setStartAngle(value: number): kendo.geometry.Arc; + + } + + interface ArcOptions { + name?: string; + } + interface ArcEvent { + sender: Arc; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Circle extends Observable { + + + options: CircleOptions; + + center: kendo.geometry.Point; + radius: number; + + constructor(center: any|kendo.geometry.Point, radius: number); + + + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + clone(): kendo.geometry.Circle; + equals(other: kendo.geometry.Circle): boolean; + getCenter(): kendo.geometry.Point; + getRadius(): number; + pointAt(angle: number): kendo.geometry.Point; + setCenter(value: kendo.geometry.Point): kendo.geometry.Point; + setCenter(value: any): kendo.geometry.Point; + setRadius(value: number): kendo.geometry.Circle; + + } + + interface CircleOptions { + name?: string; + } + interface CircleEvent { + sender: Circle; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Matrix extends Observable { + + + options: MatrixOptions; + + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; + + + static rotate(angle: number, x: number, y: number): kendo.geometry.Matrix; + static scale(scaleX: number, scaleY: number): kendo.geometry.Matrix; + static translate(x: number, y: number): kendo.geometry.Matrix; + static unit(): kendo.geometry.Matrix; + + clone(): kendo.geometry.Matrix; + equals(other: kendo.geometry.Matrix): boolean; + round(digits: number): kendo.geometry.Matrix; + multiplyCopy(matrix: kendo.geometry.Matrix): kendo.geometry.Matrix; + toArray(digits: number): any; + toString(digits: number, separator: string): string; + + } + + interface MatrixOptions { + name?: string; + } + interface MatrixEvent { + sender: Matrix; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Point extends Observable { + + + options: PointOptions; + + x: number; + y: number; + + constructor(x: number, y: number); + + static create(x: number, y: number): kendo.geometry.Point; + static create(x: any, y: number): kendo.geometry.Point; + static create(x: kendo.geometry.Point, y: number): kendo.geometry.Point; + static min(): kendo.geometry.Point; + static max(): kendo.geometry.Point; + static minPoint(): kendo.geometry.Point; + static maxPoint(): kendo.geometry.Point; + + clone(): kendo.geometry.Point; + distanceTo(point: kendo.geometry.Point): number; + equals(other: kendo.geometry.Point): boolean; + getX(): number; + getY(): number; + move(x: number, y: number): kendo.geometry.Point; + rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Point; + rotate(angle: number, center: any): kendo.geometry.Point; + round(digits: number): kendo.geometry.Point; + scale(scaleX: number, scaleY: number): kendo.geometry.Point; + scaleCopy(scaleX: number, scaleY: number): kendo.geometry.Point; + setX(value: number): kendo.geometry.Point; + setY(value: number): kendo.geometry.Point; + toArray(digits: number): any; + toString(digits: number, separator: string): string; + transform(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; + transformCopy(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; + translate(dx: number, dy: number): kendo.geometry.Point; + translateWith(vector: kendo.geometry.Point): kendo.geometry.Point; + translateWith(vector: any): kendo.geometry.Point; + + } + + interface PointOptions { + name?: string; + } + interface PointEvent { + sender: Point; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Rect extends Observable { + + + options: RectOptions; + + origin: kendo.geometry.Point; + size: kendo.geometry.Size; + + constructor(origin: kendo.geometry.Point|any, size: kendo.geometry.Size|any); + + static fromPoints(pointA: kendo.geometry.Point, pointB: kendo.geometry.Point): kendo.geometry.Rect; + static union(rectA: kendo.geometry.Rect, rectB: kendo.geometry.Rect): kendo.geometry.Rect; + + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + bottomLeft(): kendo.geometry.Point; + bottomRight(): kendo.geometry.Point; + center(): kendo.geometry.Point; + clone(): kendo.geometry.Rect; + equals(other: kendo.geometry.Rect): boolean; + getOrigin(): kendo.geometry.Point; + getSize(): kendo.geometry.Size; + height(): number; + setOrigin(value: kendo.geometry.Point): kendo.geometry.Rect; + setOrigin(value: any): kendo.geometry.Rect; + setSize(value: kendo.geometry.Size): kendo.geometry.Rect; + setSize(value: any): kendo.geometry.Rect; + topLeft(): kendo.geometry.Point; + topRight(): kendo.geometry.Point; + width(): number; + + } + + interface RectOptions { + name?: string; + } + interface RectEvent { + sender: Rect; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Size extends Observable { + + + options: SizeOptions; + + width: number; + height: number; + + + static create(width: number, height: number): kendo.geometry.Size; + static create(width: any, height: number): kendo.geometry.Size; + static create(width: kendo.geometry.Size, height: number): kendo.geometry.Size; + + clone(): kendo.geometry.Size; + equals(other: kendo.geometry.Size): boolean; + getWidth(): number; + getHeight(): number; + setWidth(value: number): kendo.geometry.Size; + setHeight(value: number): kendo.geometry.Size; + + } + + interface SizeOptions { + name?: string; + } + interface SizeEvent { + sender: Size; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Transformation extends Observable { + + + options: TransformationOptions; + + + + + clone(): kendo.geometry.Transformation; + equals(other: kendo.geometry.Transformation): boolean; + matrix(): kendo.geometry.Matrix; + multiply(transformation: kendo.geometry.Transformation): kendo.geometry.Transformation; + rotate(angle: number, center: any): kendo.geometry.Transformation; + rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Transformation; + scale(scaleX: number, scaleY: number): kendo.geometry.Transformation; + translate(x: number, y: number): kendo.geometry.Transformation; + + } + + interface TransformationOptions { + name?: string; + } + interface TransformationEvent { + sender: Transformation; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + } declare namespace kendo.drawing { class Arc extends kendo.drawing.Element { @@ -8419,274 +8836,6 @@ declare namespace kendo.drawing { -} -declare namespace kendo.geometry { - class Arc extends Observable { - - - options: ArcOptions; - - anticlockwise: boolean; - center: kendo.geometry.Point; - endAngle: number; - radiusX: number; - radiusY: number; - startAngle: number; - - constructor(center: any|kendo.geometry.Point, options?: ArcOptions); - - - bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; - getAnticlockwise(): boolean; - getCenter(): kendo.geometry.Point; - getEndAngle(): number; - getRadiusX(): number; - getRadiusY(): number; - getStartAngle(): number; - pointAt(angle: number): kendo.geometry.Point; - setAnticlockwise(value: boolean): kendo.geometry.Arc; - setCenter(value: kendo.geometry.Point): kendo.geometry.Arc; - setEndAngle(value: number): kendo.geometry.Arc; - setRadiusX(value: number): kendo.geometry.Arc; - setRadiusY(value: number): kendo.geometry.Arc; - setStartAngle(value: number): kendo.geometry.Arc; - - } - - interface ArcOptions { - name?: string; - } - interface ArcEvent { - sender: Arc; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Circle extends Observable { - - - options: CircleOptions; - - center: kendo.geometry.Point; - radius: number; - - constructor(center: any|kendo.geometry.Point, radius: number); - - - bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; - clone(): kendo.geometry.Circle; - equals(other: kendo.geometry.Circle): boolean; - getCenter(): kendo.geometry.Point; - getRadius(): number; - pointAt(angle: number): kendo.geometry.Point; - setCenter(value: kendo.geometry.Point): kendo.geometry.Point; - setCenter(value: any): kendo.geometry.Point; - setRadius(value: number): kendo.geometry.Circle; - - } - - interface CircleOptions { - name?: string; - } - interface CircleEvent { - sender: Circle; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Matrix extends Observable { - - - options: MatrixOptions; - - a: number; - b: number; - c: number; - d: number; - e: number; - f: number; - - - static rotate(angle: number, x: number, y: number): kendo.geometry.Matrix; - static scale(scaleX: number, scaleY: number): kendo.geometry.Matrix; - static translate(x: number, y: number): kendo.geometry.Matrix; - static unit(): kendo.geometry.Matrix; - - clone(): kendo.geometry.Matrix; - equals(other: kendo.geometry.Matrix): boolean; - round(digits: number): kendo.geometry.Matrix; - multiplyCopy(matrix: kendo.geometry.Matrix): kendo.geometry.Matrix; - toArray(digits: number): any; - toString(digits?: number, separator?: string): string; - - } - - interface MatrixOptions { - name?: string; - } - interface MatrixEvent { - sender: Matrix; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Point extends Observable { - - - options: PointOptions; - - x: number; - y: number; - - constructor(x: number, y: number); - - static create(x: number, y: number): kendo.geometry.Point; - static create(x: any, y: number): kendo.geometry.Point; - static create(x: kendo.geometry.Point, y: number): kendo.geometry.Point; - static min(): kendo.geometry.Point; - static max(): kendo.geometry.Point; - static minPoint(): kendo.geometry.Point; - static maxPoint(): kendo.geometry.Point; - - clone(): kendo.geometry.Point; - distanceTo(point: kendo.geometry.Point): number; - equals(other: kendo.geometry.Point): boolean; - getX(): number; - getY(): number; - move(x: number, y: number): kendo.geometry.Point; - rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Point; - rotate(angle: number, center: any): kendo.geometry.Point; - round(digits: number): kendo.geometry.Point; - scale(scaleX: number, scaleY: number): kendo.geometry.Point; - scaleCopy(scaleX: number, scaleY: number): kendo.geometry.Point; - setX(value: number): kendo.geometry.Point; - setY(value: number): kendo.geometry.Point; - toArray(digits: number): any; - toString(digits?: number, separator?: string): string; - transform(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; - transformCopy(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; - translate(dx: number, dy: number): kendo.geometry.Point; - translateWith(vector: kendo.geometry.Point): kendo.geometry.Point; - translateWith(vector: any): kendo.geometry.Point; - - } - - interface PointOptions { - name?: string; - } - interface PointEvent { - sender: Point; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Rect extends Observable { - - - options: RectOptions; - - origin: kendo.geometry.Point; - size: kendo.geometry.Size; - - constructor(origin: kendo.geometry.Point|any, size: kendo.geometry.Size|any); - - static fromPoints(pointA: kendo.geometry.Point, pointB: kendo.geometry.Point): kendo.geometry.Rect; - static union(rectA: kendo.geometry.Rect, rectB: kendo.geometry.Rect): kendo.geometry.Rect; - - bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; - bottomLeft(): kendo.geometry.Point; - bottomRight(): kendo.geometry.Point; - center(): kendo.geometry.Point; - clone(): kendo.geometry.Rect; - equals(other: kendo.geometry.Rect): boolean; - getOrigin(): kendo.geometry.Point; - getSize(): kendo.geometry.Size; - height(): number; - setOrigin(value: kendo.geometry.Point): kendo.geometry.Rect; - setOrigin(value: any): kendo.geometry.Rect; - setSize(value: kendo.geometry.Size): kendo.geometry.Rect; - setSize(value: any): kendo.geometry.Rect; - topLeft(): kendo.geometry.Point; - topRight(): kendo.geometry.Point; - width(): number; - - } - - interface RectOptions { - name?: string; - } - interface RectEvent { - sender: Rect; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Size extends Observable { - - - options: SizeOptions; - - width: number; - height: number; - - - static create(width: number, height: number): kendo.geometry.Size; - static create(width: any, height: number): kendo.geometry.Size; - static create(width: kendo.geometry.Size, height: number): kendo.geometry.Size; - - clone(): kendo.geometry.Size; - equals(other: kendo.geometry.Size): boolean; - getWidth(): number; - getHeight(): number; - setWidth(value: number): kendo.geometry.Size; - setHeight(value: number): kendo.geometry.Size; - - } - - interface SizeOptions { - name?: string; - } - interface SizeEvent { - sender: Size; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Transformation extends Observable { - - - options: TransformationOptions; - - - - - clone(): kendo.geometry.Transformation; - equals(other: kendo.geometry.Transformation): boolean; - matrix(): kendo.geometry.Matrix; - multiply(transformation: kendo.geometry.Transformation): kendo.geometry.Transformation; - rotate(angle: number, center: any): kendo.geometry.Transformation; - rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Transformation; - scale(scaleX: number, scaleY: number): kendo.geometry.Transformation; - translate(x: number, y: number): kendo.geometry.Transformation; - - } - - interface TransformationOptions { - name?: string; - } - interface TransformationEvent { - sender: Transformation; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - } declare namespace kendo.dataviz.ui { class Barcode extends kendo.ui.Widget { @@ -9681,6 +9830,7 @@ declare namespace kendo.dataviz.ui { margin?: ChartSeriesItemLabelsMargin; padding?: ChartSeriesItemLabelsPadding; position?: string|Function; + rotation?: string|number; template?: string|Function; visible?: boolean|Function; visual?: Function; @@ -9833,6 +9983,7 @@ declare namespace kendo.dataviz.ui { aggregate?: string|Function; axis?: string; border?: ChartSeriesItemBorder; + categoryAxis?: string; categoryField?: string; closeField?: string; color?: string|Function; @@ -10009,6 +10160,7 @@ declare namespace kendo.dataviz.ui { format?: string; margin?: ChartSeriesDefaultsLabelsMargin; padding?: ChartSeriesDefaultsLabelsPadding; + rotation?: string|number; template?: string|Function; visible?: boolean; visual?: Function; @@ -14295,7 +14447,7 @@ declare namespace kendo.dataviz.ui { inactiveItems?: StockChartLegendInactiveItems; } - interface StockChartNavigatorCategoryAxisItemAutoBaseUnitSteps { + interface StockChartNavigatorCategoryAxisAutoBaseUnitSteps { seconds?: any; minutes?: any; hours?: any; @@ -14305,45 +14457,45 @@ declare namespace kendo.dataviz.ui { years?: any; } - interface StockChartNavigatorCategoryAxisItemCrosshairTooltipBorder { + interface StockChartNavigatorCategoryAxisCrosshairTooltipBorder { color?: string; dashType?: string; width?: number; } - interface StockChartNavigatorCategoryAxisItemCrosshairTooltipPadding { + interface StockChartNavigatorCategoryAxisCrosshairTooltipPadding { bottom?: number; left?: number; right?: number; top?: number; } - interface StockChartNavigatorCategoryAxisItemCrosshairTooltip { + interface StockChartNavigatorCategoryAxisCrosshairTooltip { background?: string; - border?: StockChartNavigatorCategoryAxisItemCrosshairTooltipBorder; + border?: StockChartNavigatorCategoryAxisCrosshairTooltipBorder; color?: string; font?: string; format?: string; - padding?: StockChartNavigatorCategoryAxisItemCrosshairTooltipPadding; + padding?: StockChartNavigatorCategoryAxisCrosshairTooltipPadding; template?: string|Function; visible?: boolean; } - interface StockChartNavigatorCategoryAxisItemCrosshair { + interface StockChartNavigatorCategoryAxisCrosshair { color?: string; opacity?: number; - tooltip?: StockChartNavigatorCategoryAxisItemCrosshairTooltip; + tooltip?: StockChartNavigatorCategoryAxisCrosshairTooltip; visible?: boolean; width?: number; } - interface StockChartNavigatorCategoryAxisItemLabelsBorder { + interface StockChartNavigatorCategoryAxisLabelsBorder { color?: string; dashType?: string; width?: number; } - interface StockChartNavigatorCategoryAxisItemLabelsDateFormats { + interface StockChartNavigatorCategoryAxisLabelsDateFormats { days?: string; hours?: string; months?: string; @@ -14351,31 +14503,31 @@ declare namespace kendo.dataviz.ui { years?: string; } - interface StockChartNavigatorCategoryAxisItemLabelsMargin { + interface StockChartNavigatorCategoryAxisLabelsMargin { bottom?: number; left?: number; right?: number; top?: number; } - interface StockChartNavigatorCategoryAxisItemLabelsPadding { + interface StockChartNavigatorCategoryAxisLabelsPadding { bottom?: number; left?: number; right?: number; top?: number; } - interface StockChartNavigatorCategoryAxisItemLabels { + interface StockChartNavigatorCategoryAxisLabels { background?: string; - border?: StockChartNavigatorCategoryAxisItemLabelsBorder; + border?: StockChartNavigatorCategoryAxisLabelsBorder; color?: string; culture?: string; - dateFormats?: StockChartNavigatorCategoryAxisItemLabelsDateFormats; + dateFormats?: StockChartNavigatorCategoryAxisLabelsDateFormats; font?: string; format?: string; - margin?: StockChartNavigatorCategoryAxisItemLabelsMargin; + margin?: StockChartNavigatorCategoryAxisLabelsMargin; mirror?: boolean; - padding?: StockChartNavigatorCategoryAxisItemLabelsPadding; + padding?: StockChartNavigatorCategoryAxisLabelsPadding; rotation?: number; skip?: number; step?: number; @@ -14383,14 +14535,14 @@ declare namespace kendo.dataviz.ui { visible?: boolean; } - interface StockChartNavigatorCategoryAxisItemLine { + interface StockChartNavigatorCategoryAxisLine { color?: string; dashType?: string; visible?: boolean; width?: number; } - interface StockChartNavigatorCategoryAxisItemMajorGridLines { + interface StockChartNavigatorCategoryAxisMajorGridLines { color?: string; dashType?: string; visible?: boolean; @@ -14399,7 +14551,7 @@ declare namespace kendo.dataviz.ui { skip?: number; } - interface StockChartNavigatorCategoryAxisItemMajorTicks { + interface StockChartNavigatorCategoryAxisMajorTicks { color?: string; size?: number; visible?: boolean; @@ -14408,7 +14560,7 @@ declare namespace kendo.dataviz.ui { skip?: number; } - interface StockChartNavigatorCategoryAxisItemMinorGridLines { + interface StockChartNavigatorCategoryAxisMinorGridLines { color?: string; dashType?: string; visible?: boolean; @@ -14417,7 +14569,7 @@ declare namespace kendo.dataviz.ui { skip?: number; } - interface StockChartNavigatorCategoryAxisItemMinorTicks { + interface StockChartNavigatorCategoryAxisMinorTicks { color?: string; size?: number; visible?: boolean; @@ -14426,28 +14578,28 @@ declare namespace kendo.dataviz.ui { skip?: number; } - interface StockChartNavigatorCategoryAxisItemNotesDataItemIconBorder { + interface StockChartNavigatorCategoryAxisNotesDataItemIconBorder { color?: string; width?: number; } - interface StockChartNavigatorCategoryAxisItemNotesDataItemIcon { + interface StockChartNavigatorCategoryAxisNotesDataItemIcon { background?: string; - border?: StockChartNavigatorCategoryAxisItemNotesDataItemIconBorder; + border?: StockChartNavigatorCategoryAxisNotesDataItemIconBorder; size?: number; type?: string; visible?: boolean; } - interface StockChartNavigatorCategoryAxisItemNotesDataItemLabelBorder { + interface StockChartNavigatorCategoryAxisNotesDataItemLabelBorder { color?: string; dashType?: string; width?: number; } - interface StockChartNavigatorCategoryAxisItemNotesDataItemLabel { + interface StockChartNavigatorCategoryAxisNotesDataItemLabel { background?: string; - border?: StockChartNavigatorCategoryAxisItemNotesDataItemLabelBorder; + border?: StockChartNavigatorCategoryAxisNotesDataItemLabelBorder; color?: string; font?: string; template?: string|Function; @@ -14458,42 +14610,42 @@ declare namespace kendo.dataviz.ui { position?: string; } - interface StockChartNavigatorCategoryAxisItemNotesDataItemLine { + interface StockChartNavigatorCategoryAxisNotesDataItemLine { width?: number; color?: string; length?: number; } - interface StockChartNavigatorCategoryAxisItemNotesDataItem { + interface StockChartNavigatorCategoryAxisNotesDataItem { value?: any; position?: string; - icon?: StockChartNavigatorCategoryAxisItemNotesDataItemIcon; - label?: StockChartNavigatorCategoryAxisItemNotesDataItemLabel; - line?: StockChartNavigatorCategoryAxisItemNotesDataItemLine; + icon?: StockChartNavigatorCategoryAxisNotesDataItemIcon; + label?: StockChartNavigatorCategoryAxisNotesDataItemLabel; + line?: StockChartNavigatorCategoryAxisNotesDataItemLine; } - interface StockChartNavigatorCategoryAxisItemNotesIconBorder { + interface StockChartNavigatorCategoryAxisNotesIconBorder { color?: string; width?: number; } - interface StockChartNavigatorCategoryAxisItemNotesIcon { + interface StockChartNavigatorCategoryAxisNotesIcon { background?: string; - border?: StockChartNavigatorCategoryAxisItemNotesIconBorder; + border?: StockChartNavigatorCategoryAxisNotesIconBorder; size?: number; type?: string; visible?: boolean; } - interface StockChartNavigatorCategoryAxisItemNotesLabelBorder { + interface StockChartNavigatorCategoryAxisNotesLabelBorder { color?: string; dashType?: string; width?: number; } - interface StockChartNavigatorCategoryAxisItemNotesLabel { + interface StockChartNavigatorCategoryAxisNotesLabel { background?: string; - border?: StockChartNavigatorCategoryAxisItemNotesLabelBorder; + border?: StockChartNavigatorCategoryAxisNotesLabelBorder; color?: string; font?: string; template?: string|Function; @@ -14503,87 +14655,87 @@ declare namespace kendo.dataviz.ui { position?: string; } - interface StockChartNavigatorCategoryAxisItemNotesLine { + interface StockChartNavigatorCategoryAxisNotesLine { width?: number; color?: string; length?: number; } - interface StockChartNavigatorCategoryAxisItemNotes { + interface StockChartNavigatorCategoryAxisNotes { position?: string; - icon?: StockChartNavigatorCategoryAxisItemNotesIcon; - label?: StockChartNavigatorCategoryAxisItemNotesLabel; - line?: StockChartNavigatorCategoryAxisItemNotesLine; - data?: StockChartNavigatorCategoryAxisItemNotesDataItem[]; + icon?: StockChartNavigatorCategoryAxisNotesIcon; + label?: StockChartNavigatorCategoryAxisNotesLabel; + line?: StockChartNavigatorCategoryAxisNotesLine; + data?: StockChartNavigatorCategoryAxisNotesDataItem[]; } - interface StockChartNavigatorCategoryAxisItemPlotBand { + interface StockChartNavigatorCategoryAxisPlotBand { color?: string; from?: number; opacity?: number; to?: number; } - interface StockChartNavigatorCategoryAxisItemTitleBorder { + interface StockChartNavigatorCategoryAxisTitleBorder { color?: string; dashType?: string; width?: number; } - interface StockChartNavigatorCategoryAxisItemTitleMargin { + interface StockChartNavigatorCategoryAxisTitleMargin { bottom?: number; left?: number; right?: number; top?: number; } - interface StockChartNavigatorCategoryAxisItemTitlePadding { + interface StockChartNavigatorCategoryAxisTitlePadding { bottom?: number; left?: number; right?: number; top?: number; } - interface StockChartNavigatorCategoryAxisItemTitle { + interface StockChartNavigatorCategoryAxisTitle { background?: string; - border?: StockChartNavigatorCategoryAxisItemTitleBorder; + border?: StockChartNavigatorCategoryAxisTitleBorder; color?: string; font?: string; - margin?: StockChartNavigatorCategoryAxisItemTitleMargin; - padding?: StockChartNavigatorCategoryAxisItemTitlePadding; + margin?: StockChartNavigatorCategoryAxisTitleMargin; + padding?: StockChartNavigatorCategoryAxisTitlePadding; position?: string; rotation?: number; text?: string; visible?: boolean; } - interface StockChartNavigatorCategoryAxisItem { - autoBaseUnitSteps?: StockChartNavigatorCategoryAxisItemAutoBaseUnitSteps; + interface StockChartNavigatorCategoryAxis { + autoBaseUnitSteps?: StockChartNavigatorCategoryAxisAutoBaseUnitSteps; axisCrossingValue?: any|Date|any; background?: string; baseUnit?: string; baseUnitStep?: any; categories?: any; color?: string; - crosshair?: StockChartNavigatorCategoryAxisItemCrosshair; + crosshair?: StockChartNavigatorCategoryAxisCrosshair; field?: string; justified?: boolean; - labels?: StockChartNavigatorCategoryAxisItemLabels; - line?: StockChartNavigatorCategoryAxisItemLine; - majorGridLines?: StockChartNavigatorCategoryAxisItemMajorGridLines; - majorTicks?: StockChartNavigatorCategoryAxisItemMajorTicks; + labels?: StockChartNavigatorCategoryAxisLabels; + line?: StockChartNavigatorCategoryAxisLine; + majorGridLines?: StockChartNavigatorCategoryAxisMajorGridLines; + majorTicks?: StockChartNavigatorCategoryAxisMajorTicks; max?: any; maxDateGroups?: number; min?: any; - minorGridLines?: StockChartNavigatorCategoryAxisItemMinorGridLines; - minorTicks?: StockChartNavigatorCategoryAxisItemMinorTicks; - plotBands?: StockChartNavigatorCategoryAxisItemPlotBand[]; + minorGridLines?: StockChartNavigatorCategoryAxisMinorGridLines; + minorTicks?: StockChartNavigatorCategoryAxisMinorTicks; + plotBands?: StockChartNavigatorCategoryAxisPlotBand[]; reverse?: boolean; roundToBaseUnit?: boolean; - title?: StockChartNavigatorCategoryAxisItemTitle; + title?: StockChartNavigatorCategoryAxisTitle; visible?: boolean; weekStartDay?: number; - notes?: StockChartNavigatorCategoryAxisItemNotes; + notes?: StockChartNavigatorCategoryAxisNotes; } interface StockChartNavigatorHint { @@ -14781,7 +14933,7 @@ declare namespace kendo.dataviz.ui { } interface StockChartNavigator { - categoryAxis?: StockChartNavigatorCategoryAxisItem[]; + categoryAxis?: StockChartNavigatorCategoryAxis; dataSource?: any; autoBind?: boolean; dateField?: string; @@ -16959,6 +17111,27 @@ declare namespace kendo { } + namespace date { + function setDayOfWeek(targetDate: Date, dayOfWeek: number, direction: number): void; + function dayOfWeek(targetDate: Date, dayOfWeek: number, direction: number): Date; + function weekInYear(date: Date, weekStart?: Date): number; + function getDate(date: Date): Date; + function isInDateRange(targetDate: Date, lowerLimitDate: Date, upperLimitDate: Date): boolean; + function isInTimeRange(targetDate: Date, lowerLimitDate: Date, upperLimitDate: Date): boolean; + function isToday(targetDate: Date): boolean; + function nextDay(targetDate: Date): Date; + function previousDay(targetDate: Date): Date; + function toUtcTime(targetDate: Date): number; + function setTime(targetDate: Date, millisecondsToAdd: number, ignoreDST: boolean): void; + function setHours(targetDate: Date, sourceDate: number): Date; + function addDays(targetDate: Date, numberOfDaysToAdd: number): Date; + function today(): Date; + function toInvariantTime(targetDate: Date): Date; + function firstDayOfMonth(targetDate: Date): Date; + function lastDayOfMonth(targetDate: Date): Date; + function getMilliseconds(targetDate: Date): Date; + } + namespace drawing { function align(elements: any, rect: kendo.geometry.Rect, alignment: string): void; function drawDOM(element: JQuery, options: any): JQueryPromise; @@ -17022,6 +17195,22 @@ declare namespace kendo { function defineFont(map: any): void; } + namespace timezone { + function offset(utcTime: Date, timezone: string): number; + function offset(utcTime: number, timezone: string): number; + function convert(targetDate: Date, fromOffset: number, toOffset: number): Date; + function convert(targetDate: Date, fromOffset: number, toOffset: string): Date; + function convert(targetDate: Date, fromOffset: string, toOffset: number): Date; + function convert(targetDate: Date, fromOffset: string, toOffset: string): Date; + function apply(targetDate: Date, offset: number): Date; + function apply(targetDate: Date, offset: string): Date; + function remove(targetDate: Date, offset: number): Date; + function remove(targetDate: Date, offset: string): Date; + function abbr(targetDate: Date, timezone: string): string; + function toLocalDate(targetDate: Date): Date; + function toLocalDate(targetDate: number): Date; + } + } declare namespace kendo.spreadsheet { class CustomFilter extends Observable { @@ -18306,7 +18495,7 @@ declare namespace kendo.ooxml { interface WorkbookSheetRow { cells?: WorkbookSheetRowCell[]; index?: number; - height?: number; + height?: number; type?: "header" | "footer" | "group-header" | "group-footer" | "data"; } @@ -18337,6 +18526,268 @@ declare namespace kendo.ooxml { } +declare namespace kendo.dataviz.geometry { + class Arc extends Observable { + + + options: ArcOptions; + + anticlockwise: boolean; + center: kendo.geometry.Point; + endAngle: number; + radiusX: number; + radiusY: number; + startAngle: number; + + constructor(center: any|kendo.geometry.Point, options?: ArcOptions); + + + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + getAnticlockwise(): boolean; + getCenter(): kendo.geometry.Point; + getEndAngle(): number; + getRadiusX(): number; + getRadiusY(): number; + getStartAngle(): number; + pointAt(angle: number): kendo.geometry.Point; + setAnticlockwise(value: boolean): kendo.geometry.Arc; + setCenter(value: kendo.geometry.Point): kendo.geometry.Arc; + setEndAngle(value: number): kendo.geometry.Arc; + setRadiusX(value: number): kendo.geometry.Arc; + setRadiusY(value: number): kendo.geometry.Arc; + setStartAngle(value: number): kendo.geometry.Arc; + + } + + interface ArcOptions { + name?: string; + } + interface ArcEvent { + sender: Arc; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Circle extends Observable { + + + options: CircleOptions; + + center: kendo.geometry.Point; + radius: number; + + constructor(center: any|kendo.geometry.Point, radius: number); + + + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + clone(): kendo.geometry.Circle; + equals(other: kendo.geometry.Circle): boolean; + getCenter(): kendo.geometry.Point; + getRadius(): number; + pointAt(angle: number): kendo.geometry.Point; + setCenter(value: kendo.geometry.Point): kendo.geometry.Point; + setCenter(value: any): kendo.geometry.Point; + setRadius(value: number): kendo.geometry.Circle; + + } + + interface CircleOptions { + name?: string; + } + interface CircleEvent { + sender: Circle; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Matrix extends Observable { + + + options: MatrixOptions; + + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; + + + static rotate(angle: number, x: number, y: number): kendo.geometry.Matrix; + static scale(scaleX: number, scaleY: number): kendo.geometry.Matrix; + static translate(x: number, y: number): kendo.geometry.Matrix; + static unit(): kendo.geometry.Matrix; + + clone(): kendo.geometry.Matrix; + equals(other: kendo.geometry.Matrix): boolean; + round(digits: number): kendo.geometry.Matrix; + multiplyCopy(matrix: kendo.geometry.Matrix): kendo.geometry.Matrix; + toArray(digits: number): any; + toString(digits: number, separator: string): string; + + } + + interface MatrixOptions { + name?: string; + } + interface MatrixEvent { + sender: Matrix; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Point extends Observable { + + + options: PointOptions; + + x: number; + y: number; + + constructor(x: number, y: number); + + static create(x: number, y: number): kendo.geometry.Point; + static create(x: any, y: number): kendo.geometry.Point; + static create(x: kendo.geometry.Point, y: number): kendo.geometry.Point; + static min(): kendo.geometry.Point; + static max(): kendo.geometry.Point; + static minPoint(): kendo.geometry.Point; + static maxPoint(): kendo.geometry.Point; + + clone(): kendo.geometry.Point; + distanceTo(point: kendo.geometry.Point): number; + equals(other: kendo.geometry.Point): boolean; + getX(): number; + getY(): number; + move(x: number, y: number): kendo.geometry.Point; + rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Point; + rotate(angle: number, center: any): kendo.geometry.Point; + round(digits: number): kendo.geometry.Point; + scale(scaleX: number, scaleY: number): kendo.geometry.Point; + scaleCopy(scaleX: number, scaleY: number): kendo.geometry.Point; + setX(value: number): kendo.geometry.Point; + setY(value: number): kendo.geometry.Point; + toArray(digits: number): any; + toString(digits: number, separator: string): string; + transform(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; + transformCopy(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; + translate(dx: number, dy: number): kendo.geometry.Point; + translateWith(vector: kendo.geometry.Point): kendo.geometry.Point; + translateWith(vector: any): kendo.geometry.Point; + + } + + interface PointOptions { + name?: string; + } + interface PointEvent { + sender: Point; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Rect extends Observable { + + + options: RectOptions; + + origin: kendo.geometry.Point; + size: kendo.geometry.Size; + + constructor(origin: kendo.geometry.Point|any, size: kendo.geometry.Size|any); + + static fromPoints(pointA: kendo.geometry.Point, pointB: kendo.geometry.Point): kendo.geometry.Rect; + static union(rectA: kendo.geometry.Rect, rectB: kendo.geometry.Rect): kendo.geometry.Rect; + + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + bottomLeft(): kendo.geometry.Point; + bottomRight(): kendo.geometry.Point; + center(): kendo.geometry.Point; + clone(): kendo.geometry.Rect; + equals(other: kendo.geometry.Rect): boolean; + getOrigin(): kendo.geometry.Point; + getSize(): kendo.geometry.Size; + height(): number; + setOrigin(value: kendo.geometry.Point): kendo.geometry.Rect; + setOrigin(value: any): kendo.geometry.Rect; + setSize(value: kendo.geometry.Size): kendo.geometry.Rect; + setSize(value: any): kendo.geometry.Rect; + topLeft(): kendo.geometry.Point; + topRight(): kendo.geometry.Point; + width(): number; + + } + + interface RectOptions { + name?: string; + } + interface RectEvent { + sender: Rect; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Size extends Observable { + + + options: SizeOptions; + + width: number; + height: number; + + + static create(width: number, height: number): kendo.geometry.Size; + static create(width: any, height: number): kendo.geometry.Size; + static create(width: kendo.geometry.Size, height: number): kendo.geometry.Size; + + clone(): kendo.geometry.Size; + equals(other: kendo.geometry.Size): boolean; + getWidth(): number; + getHeight(): number; + setWidth(value: number): kendo.geometry.Size; + setHeight(value: number): kendo.geometry.Size; + + } + + interface SizeOptions { + name?: string; + } + + class Transformation extends Observable { + + + options: TransformationOptions; + + + + + clone(): kendo.geometry.Transformation; + equals(other: kendo.geometry.Transformation): boolean; + matrix(): kendo.geometry.Matrix; + multiply(transformation: kendo.geometry.Transformation): kendo.geometry.Transformation; + rotate(angle: number, center: any): kendo.geometry.Transformation; + rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Transformation; + scale(scaleX: number, scaleY: number): kendo.geometry.Transformation; + translate(x: number, y: number): kendo.geometry.Transformation; + + } + + interface TransformationOptions { + name?: string; + } + interface TransformationEvent { + sender: Transformation; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + +} declare namespace kendo.dataviz.drawing { class Arc extends kendo.drawing.Element { @@ -19126,274 +19577,6 @@ declare namespace kendo.dataviz.drawing { -} -declare namespace kendo.dataviz.geometry { - class Arc extends Observable { - - - options: ArcOptions; - - anticlockwise: boolean; - center: kendo.geometry.Point; - endAngle: number; - radiusX: number; - radiusY: number; - startAngle: number; - - constructor(center: any|kendo.geometry.Point, options?: ArcOptions); - - - bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; - getAnticlockwise(): boolean; - getCenter(): kendo.geometry.Point; - getEndAngle(): number; - getRadiusX(): number; - getRadiusY(): number; - getStartAngle(): number; - pointAt(angle: number): kendo.geometry.Point; - setAnticlockwise(value: boolean): kendo.geometry.Arc; - setCenter(value: kendo.geometry.Point): kendo.geometry.Arc; - setEndAngle(value: number): kendo.geometry.Arc; - setRadiusX(value: number): kendo.geometry.Arc; - setRadiusY(value: number): kendo.geometry.Arc; - setStartAngle(value: number): kendo.geometry.Arc; - - } - - interface ArcOptions { - name?: string; - } - interface ArcEvent { - sender: Arc; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Circle extends Observable { - - - options: CircleOptions; - - center: kendo.geometry.Point; - radius: number; - - constructor(center: any|kendo.geometry.Point, radius: number); - - - bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; - clone(): kendo.geometry.Circle; - equals(other: kendo.geometry.Circle): boolean; - getCenter(): kendo.geometry.Point; - getRadius(): number; - pointAt(angle: number): kendo.geometry.Point; - setCenter(value: kendo.geometry.Point): kendo.geometry.Point; - setCenter(value: any): kendo.geometry.Point; - setRadius(value: number): kendo.geometry.Circle; - - } - - interface CircleOptions { - name?: string; - } - interface CircleEvent { - sender: Circle; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Matrix extends Observable { - - - options: MatrixOptions; - - a: number; - b: number; - c: number; - d: number; - e: number; - f: number; - - - static rotate(angle: number, x: number, y: number): kendo.geometry.Matrix; - static scale(scaleX: number, scaleY: number): kendo.geometry.Matrix; - static translate(x: number, y: number): kendo.geometry.Matrix; - static unit(): kendo.geometry.Matrix; - - clone(): kendo.geometry.Matrix; - equals(other: kendo.geometry.Matrix): boolean; - round(digits: number): kendo.geometry.Matrix; - multiplyCopy(matrix: kendo.geometry.Matrix): kendo.geometry.Matrix; - toArray(digits: number): any; - toString(digits?: number, separator?: string): string; - - } - - interface MatrixOptions { - name?: string; - } - interface MatrixEvent { - sender: Matrix; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Point extends Observable { - - - options: PointOptions; - - x: number; - y: number; - - constructor(x: number, y: number); - - static create(x: number, y: number): kendo.geometry.Point; - static create(x: any, y: number): kendo.geometry.Point; - static create(x: kendo.geometry.Point, y: number): kendo.geometry.Point; - static min(): kendo.geometry.Point; - static max(): kendo.geometry.Point; - static minPoint(): kendo.geometry.Point; - static maxPoint(): kendo.geometry.Point; - - clone(): kendo.geometry.Point; - distanceTo(point: kendo.geometry.Point): number; - equals(other: kendo.geometry.Point): boolean; - getX(): number; - getY(): number; - move(x: number, y: number): kendo.geometry.Point; - rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Point; - rotate(angle: number, center: any): kendo.geometry.Point; - round(digits: number): kendo.geometry.Point; - scale(scaleX: number, scaleY: number): kendo.geometry.Point; - scaleCopy(scaleX: number, scaleY: number): kendo.geometry.Point; - setX(value: number): kendo.geometry.Point; - setY(value: number): kendo.geometry.Point; - toArray(digits: number): any; - toString(digits: number, separator: string): string; - transform(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; - transformCopy(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; - translate(dx: number, dy: number): kendo.geometry.Point; - translateWith(vector: kendo.geometry.Point): kendo.geometry.Point; - translateWith(vector: any): kendo.geometry.Point; - - } - - interface PointOptions { - name?: string; - } - interface PointEvent { - sender: Point; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Rect extends Observable { - - - options: RectOptions; - - origin: kendo.geometry.Point; - size: kendo.geometry.Size; - - constructor(origin: kendo.geometry.Point|any, size: kendo.geometry.Size|any); - - static fromPoints(pointA: kendo.geometry.Point, pointB: kendo.geometry.Point): kendo.geometry.Rect; - static union(rectA: kendo.geometry.Rect, rectB: kendo.geometry.Rect): kendo.geometry.Rect; - - bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; - bottomLeft(): kendo.geometry.Point; - bottomRight(): kendo.geometry.Point; - center(): kendo.geometry.Point; - clone(): kendo.geometry.Rect; - equals(other: kendo.geometry.Rect): boolean; - getOrigin(): kendo.geometry.Point; - getSize(): kendo.geometry.Size; - height(): number; - setOrigin(value: kendo.geometry.Point): kendo.geometry.Rect; - setOrigin(value: any): kendo.geometry.Rect; - setSize(value: kendo.geometry.Size): kendo.geometry.Rect; - setSize(value: any): kendo.geometry.Rect; - topLeft(): kendo.geometry.Point; - topRight(): kendo.geometry.Point; - width(): number; - - } - - interface RectOptions { - name?: string; - } - interface RectEvent { - sender: Rect; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Size extends Observable { - - - options: SizeOptions; - - width: number; - height: number; - - - static create(width: number, height: number): kendo.geometry.Size; - static create(width: any, height: number): kendo.geometry.Size; - static create(width: kendo.geometry.Size, height: number): kendo.geometry.Size; - - clone(): kendo.geometry.Size; - equals(other: kendo.geometry.Size): boolean; - getWidth(): number; - getHeight(): number; - setWidth(value: number): kendo.geometry.Size; - setHeight(value: number): kendo.geometry.Size; - - } - - interface SizeOptions { - name?: string; - } - interface SizeEvent { - sender: Size; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Transformation extends Observable { - - - options: TransformationOptions; - - - - - clone(): kendo.geometry.Transformation; - equals(other: kendo.geometry.Transformation): boolean; - matrix(): kendo.geometry.Matrix; - multiply(transformation: kendo.geometry.Transformation): kendo.geometry.Transformation; - rotate(angle: number, center: any): kendo.geometry.Transformation; - rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Transformation; - scale(scaleX: number, scaleY: number): kendo.geometry.Transformation; - translate(x: number, y: number): kendo.geometry.Transformation; - - } - - interface TransformationOptions { - name?: string; - } - interface TransformationEvent { - sender: Transformation; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - } interface HTMLElement { diff --git a/kendo-ui/kendo-ui-tests.ts b/kendo-ui/kendo-ui-tests.ts index d1cc528edb..0b79f87954 100644 --- a/kendo-ui/kendo-ui-tests.ts +++ b/kendo-ui/kendo-ui-tests.ts @@ -1,6 +1,3 @@ -/// - - var is = { string: (msg: string) => { return true; diff --git a/keytar/index.d.ts b/keytar/index.d.ts index 12dbd63316..5a27c0c984 100644 --- a/keytar/index.d.ts +++ b/keytar/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for keytar 3.0.0 +// Type definitions for keytar 3.0.2 // Project: http://atom.github.io/node-keytar/ -// Definitions by: Milan Burda +// Definitions by: Milan Burda , Brendan Forster // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -12,7 +12,7 @@ * * @returns the string password or null on failures. */ -export declare function getPassword(service: string, account: string): string; +export declare function getPassword(service: string, account: string): string | null; /** * Add the password for the service and account to the keychain. @@ -31,9 +31,9 @@ export declare function addPassword(service: string, account: string, password: * @param service The string service name. * @param account The string account name. * - * @returns the string password or null on failures. + * @returns true on success, false on failure */ -export declare function deletePassword(service: string, account: string): string; +export declare function deletePassword(service: string, account: string): boolean; /** * Replace the password for the service and account in the keychain. @@ -56,4 +56,4 @@ export declare function replacePassword(service: string, account: string, passwo * * @returns the string password or null on failures. */ -export declare function findPassword(service: string): string; +export declare function findPassword(service: string): string | null; diff --git a/keytar/keytar-tests.ts b/keytar/keytar-tests.ts index 91a43ebbe9..d523050650 100644 --- a/keytar/keytar-tests.ts +++ b/keytar/keytar-tests.ts @@ -1,8 +1,13 @@ import keytar = require('keytar'); -keytar.addPassword('keytar-tests', 'username', 'password'); -keytar.deletePassword('keytar-tests', 'username'); -keytar.findPassword('keytar-tests'); -keytar.getPassword('keytar-tests', 'username'); -keytar.replacePassword('keytar-tests', 'username', 'password'); +let success: boolean = false; + +success = keytar.addPassword('keytar-tests', 'username', 'password'); +success = keytar.deletePassword('keytar-tests', 'username'); +success = keytar.replacePassword('keytar-tests', 'username', 'password'); + +let password: string = ''; + +password = keytar.findPassword('keytar-tests'); +password = keytar.getPassword('keytar-tests', 'username'); diff --git a/kii-cloud-sdk/index.d.ts b/kii-cloud-sdk/index.d.ts index 26decd07a0..8dec3a94c8 100644 --- a/kii-cloud-sdk/index.d.ts +++ b/kii-cloud-sdk/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Kii Cloud SDK v2.4.6 +// Type definitions for Kii Cloud SDK v2.4.9 // Project: http://en.kii.com/ // Definitions by: Kii Consortium // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -10,6 +10,9 @@ declare namespace KiiCloud { KiiACLBucketActionDropBucket, KiiACLObjectActionRead, KiiACLObjectActionWrite, + KiiACLBucketActionReadObjects, + KiiACLSubscribeToTopic, + KiiACLSendMessageToTopic, } export enum KiiSite { @@ -44,7 +47,7 @@ declare namespace KiiCloud { } | { oauth_token: string, oauth_token_secret: string - } + }; interface KiiSocialAccountInfo { createdAt: number; @@ -195,6 +198,12 @@ declare namespace KiiCloud { portWSS: number; } + interface KiiError { + status: number; + code: string; + message: string; + } + /** * The main SDK class */ @@ -245,7 +254,9 @@ declare namespace KiiCloud { * @example * Kii.setAccessTokenExpiration(3600); */ - static setAccessTokenExpiration(expiresIn: number): void; + static setAccessTokenExpiration( + expiresIn: number + ): void; /** * Returns access token lifetime in seconds. @@ -266,7 +277,9 @@ declare namespace KiiCloud { * @param appID The application ID found in your Kii developer console * @param appKey The application key found in your Kii developer console * @param site Can be one of the constants KiiSite.US, KiiSite.JP, KiiSite.CN or KiiSite.SG depending on your location. - * @param analyticsOption An object used for initializing KiiAnalytics, If not provided or invalid object provided, KiiAnalytics won't be initialized. If provided, it can be empty object or with analyticsOption.deviceId.
    If provided, but deviceId is not provided, SDK generates a new deviceId and use it when upload events. It can be retrieved by {@link KiiAnalytics.getDeviceId()}. It is recommended to retrieve the deviceId and store it to identify the device properly. + * @param analyticsOption An object used for initializing KiiAnalytics, If not provided or invalid object provided, KiiAnalytics won't be initialized. If provided, it can be empty object or + * with analyticsOption.deviceId.
    If provided, but deviceId is not provided, SDK generates a new deviceId and use it when upload events. It can be retrieved by {@link + * KiiAnalytics.getDeviceId()}. It is recommended to retrieve the deviceId and store it to identify the device properly. * * @example * // Disable KiiAnalytics @@ -279,7 +292,12 @@ declare namespace KiiCloud { * // Enable KiiAnalytics without deviceId * Kii.initializeWithSite("my-app-id", "my-app-key", KiiSite.JP, {}); */ - static initializeWithSite(appID: string, appKey: string, site: KiiSite, analyticsOption?: any): void; + static initializeWithSite( + appID: string, + appKey: string, + site: KiiSite, + analyticsOption?: any + ): void; /** * Initialize the Kii SDK @@ -289,7 +307,9 @@ declare namespace KiiCloud { * * @param appID The application ID found in your Kii developer console * @param appKey The application key found in your Kii developer console - * @param analyticsOption An object used for initializing KiiAnalytics, If not provided or invalid object provided, KiiAnalytics won't be initialized. If provided, it can be empty object or with analyticsOption.deviceId.
    If provided, but deviceId is not provided, SDK generates a new deviceId and use it when upload events. It can be retrieved by {@link KiiAnalytics.getDeviceId()}. It is recommended to retrieve the deviceId and store it to identify the device properly. + * @param analyticsOption An object used for initializing KiiAnalytics, If not provided or invalid object provided, KiiAnalytics won't be initialized. If provided, it can be empty object or + * with analyticsOption.deviceId.
    If provided, but deviceId is not provided, SDK generates a new deviceId and use it when upload events. It can be retrieved by {@link + * KiiAnalytics.getDeviceId()}. It is recommended to retrieve the deviceId and store it to identify the device properly. * * @example * // Disable KiiAnalytics @@ -302,7 +322,11 @@ declare namespace KiiCloud { * // Enable KiiAnalytics without deviceId * Kii.initialize("my-app-id", "my-app-key", {}); */ - static initialize(appID: string, appKey: string, analyticsOption?: any): void; + static initialize( + appID: string, + appKey: string, + analyticsOption?: any + ): void; /** * Creates a reference to a bucket for this app @@ -316,7 +340,9 @@ declare namespace KiiCloud { * @example * var bucket = Kii.bucketWithName("myBucket"); */ - static bucketWithName(bucketName: string): KiiBucket; + static bucketWithName( + bucketName: string + ): KiiBucket; /** * Creates a reference to a encrypted bucket for this app @@ -330,7 +356,9 @@ declare namespace KiiCloud { * @example * var bucket = Kii.encryptedBucketWithName("myBucket"); */ - static encryptedBucketWithName(bucketName: string): KiiBucket; + static encryptedBucketWithName( + bucketName: string + ): KiiBucket; /** * Creates a reference to a group with the given name @@ -342,7 +370,9 @@ declare namespace KiiCloud { * @example * var group = new Kii.groupWithName("myGroup"); */ - static groupWithName(groupName: string): KiiGroup; + static groupWithName( + groupName: string + ): KiiGroup; /** * Creates a reference to a group with the given name and a list of default members @@ -355,7 +385,10 @@ declare namespace KiiCloud { * @example * var group = new KiiGroup.groupWithName("myGroup", members); */ - static groupWithNameAndMembers(groupName: string, members: KiiUser[]): KiiGroup; + static groupWithNameAndMembers( + groupName: string, + members: KiiUser[] + ): KiiGroup; /** * Authenticate as app admin. @@ -405,7 +438,11 @@ declare namespace KiiCloud { * } * ); */ - static authenticateAsAppAdmin(clientId: string, clientSecret: string, callbacks?: { success(adminContext: KiiAppAdminContext): any; failure(error: string, statusCode: number): any; }): Promise; + static authenticateAsAppAdmin( + clientId: string, + clientSecret: string, + callbacks?: { success(adminContext: KiiAppAdminContext): any; failure(error: string, statusCode: number): any; } + ): Promise; /** * Instantiate KiiServerCodeEntry with specified entry name. @@ -422,7 +459,9 @@ declare namespace KiiCloud { * @example * var entry = Kii.serverCodeEntry("main"); */ - static serverCodeEntry(entryName: string): KiiServerCodeEntry; + static serverCodeEntry( + entryName: string + ): KiiServerCodeEntry; /** * Instantiate serverCodeEntryWithVersion with specified entry name and version. @@ -440,7 +479,10 @@ declare namespace KiiCloud { * @example * var entry = Kii.serverCodeEntryWithVersion("main", "gulsdf6ful8jvf8uq6fe7vjy6"); */ - static serverCodeEntryWithVersion(entryName: string, version: string): KiiServerCodeEntry; + static serverCodeEntryWithVersion( + entryName: string, + version: string + ): KiiServerCodeEntry; /** * Instantiate topic belongs to application. @@ -449,13 +491,16 @@ declare namespace KiiCloud { * * @return topic instance. */ - static topicWithName(topicName: string): KiiTopic; + static topicWithName( + topicName: string + ): KiiTopic; /** * Gets a list of topics in app scope * * @param callbacks An object with callback methods defined - * @param paginationKey You can specify the pagination key with the nextPaginationKey passed by callbacks.success or fullfill callback of promise. If empty string or no string object is provided, this API regards no paginationKey specified. + * @param paginationKey You can specify the pagination key with the nextPaginationKey passed by callbacks.success or fullfill callback of promise. If empty string or no string object is + * provided, this API regards no paginationKey specified. * * @return return promise object. *
      @@ -513,7 +558,10 @@ declare namespace KiiCloud { * } * ); */ - static listTopics(callbacks?: { success(topicList: KiiTopic[], nextPaginationKey: string): any; failure(anErrorString: string): any; }, paginationKey?: string): Promise<[KiiTopic[], string]>; + static listTopics( + callbacks?: { success(topicList: KiiTopic[], nextPaginationKey: string): any; failure(anErrorString: string): any; }, + paginationKey?: string + ): Promise<[KiiTopic[], string]>; /** * Authenticate as Thing. @@ -562,7 +610,11 @@ declare namespace KiiCloud { * } * ); */ - static authenticateAsThing(vendorThingID: string, password: string, callbacks?: { success(thingAuthContext: KiiThingContext): any; failure(error: Error): any; }): Promise; + static authenticateAsThing( + vendorThingID: string, + password: string, + callbacks?: { success(thingAuthContext: KiiThingContext): any; failure(error: Error): any; } + ): Promise; /** * Create a KiiThingContext reference @@ -611,7 +663,11 @@ declare namespace KiiCloud { * } * ); */ - static authenticateAsThingWithToken(thingID: string, token: string, callbacks?: { success(thingContext: KiiThingContext): any; failure(error: Error): any; }): Promise; + static authenticateAsThingWithToken( + thingID: string, + token: string, + callbacks?: { success(thingContext: KiiThingContext): any; failure(error: Error): any; } + ): Promise; } /** @@ -666,10 +722,13 @@ declare namespace KiiCloud { * // do something with the error response * }); */ - listACLEntries(callbacks?: { success(theACL: KiiACL, theEntries: KiiACLEntry[]): any; failure(theACL: KiiACL, anErrorString: string): any; }): Promise<[KiiACL, KiiACLEntry[]]>; + listACLEntries( + callbacks?: { success(theACL: KiiACL, theEntries: KiiACLEntry[]): any; failure(theACL: KiiACL, anErrorString: string): any; } + ): Promise<[KiiACL, KiiACLEntry[]]>; /** - * Add a KiiACLEntry to the local object, if not already present. This does not explicitly grant any permissions, which should be done through the KiiACLEntry itself. This method simply adds the entry to the local ACL object so it can be saved to the server. + * Add a KiiACLEntry to the local object, if not already present. This does not explicitly grant any permissions, which should be done through the KiiACLEntry itself. This method simply adds + * the entry to the local ACL object so it can be saved to the server. * * @param entry The KiiACLEntry to add * @@ -680,10 +739,13 @@ declare namespace KiiCloud { * var acl = . . .; // a KiiACL object * acl.putACLEntry(aclEntry); */ - putACLEntry(entry: KiiACLEntry): void; + putACLEntry( + entry: KiiACLEntry + ): void; /** - * Remove a KiiACLEntry to the local object. This does not explicitly revoke any permissions, which should be done through the KiiACLEntry itself. This method simply removes the entry from the local ACL object and will not be saved to the server. + * Remove a KiiACLEntry to the local object. This does not explicitly revoke any permissions, which should be done through the KiiACLEntry itself. This method simply removes the entry from the + * local ACL object and will not be saved to the server. * * @param entry The KiiACLEntry to remove * @@ -694,7 +756,9 @@ declare namespace KiiCloud { * var acl = . . .; // a KiiACL object * acl.removeACLEntry(aclEntry); */ - removeACLEntry(entry: KiiACLEntry): void; + removeACLEntry( + entry: KiiACLEntry + ): void; /** * Save the list of ACLEntry objects associated with this ACL object to the server @@ -737,7 +801,9 @@ declare namespace KiiCloud { * // do something with the error response * }); */ - save(callbacks?: { success(theSavedACL: KiiACL): any; failure(theACL: KiiACL, anErrorString: string): any; }): Promise; + save( + callbacks?: { success(theSavedACL: KiiACL): any; failure(theACL: KiiACL, anErrorString: string): any; } + ): Promise; } /** @@ -760,7 +826,9 @@ declare namespace KiiCloud { * * @throws If the value is not one of the permitted values */ - setAction(value: KiiACLAction): void; + setAction( + value: KiiACLAction + ): void; /** * Get the action that is being permitted/restricted in this entry @@ -776,7 +844,9 @@ declare namespace KiiCloud { * * @throws If the value is not one of the permitted values */ - setSubject(subject: KiiACLSubject): void; + setSubject( + subject: KiiACLSubject + ): void; /** * Get the subject that is being permitted/restricted in this entry @@ -792,7 +862,9 @@ declare namespace KiiCloud { * * @throws If the value is not a boolean type */ - setGrant(value: boolean): void; + setGrant( + value: boolean + ): void; /** * Get whether or not the action is being permitted to the subject @@ -817,7 +889,10 @@ declare namespace KiiCloud { * @throws If specified subject is invalid. * @throws If the specified action is invalid. */ - static entryWithSubject(Subject: KiiACLSubject, action: KiiACLAction): KiiACLEntry; + static entryWithSubject( + Subject: KiiACLSubject, + action: KiiACLAction + ): KiiACLEntry; } /** @@ -839,7 +914,8 @@ declare namespace KiiCloud { static getAppKey(): string; /** - * Get the deviceId. If deviceId has not specified while initialization, it returns SDK generated deviceId.It is recommended to retrieve the deviceId and store it to identify the device properly. + * Get the deviceId. If deviceId has not specified while initialization, it returns SDK generated deviceId.It is recommended to retrieve the deviceId and store it to identify the device + * properly. * * @return deviceId. */ @@ -862,7 +938,9 @@ declare namespace KiiCloud { * @example * KiiAnalytics.setLogging(true); */ - static setLogging(True: boolean): void; + static setLogging( + True: boolean + ): void; /** * @@ -874,7 +952,8 @@ declare namespace KiiCloud { * @param appID The application ID found in your Kii developer console * @param appKey The application key found in your Kii developer console * @param site Can be one of the constants KiiAnalyticsSite.US, KiiAnalyticsSite.JP, KiiAnalyticsSite.CN, KiiAnalyticsSite.CN3 or KiiAnalyticsSite.SG depending on your location. - * @param deviceid If deviceId is not provided, SDK generates a new deviceId and use it when upload events.deviceId can be retrieved by {@link KiiAnalytics.getDeviceId()}.It is recommended to retrieve the deviceId and store it to identify the device properly. + * @param deviceid If deviceId is not provided, SDK generates a new deviceId and use it when upload events.deviceId can be retrieved by {@link KiiAnalytics.getDeviceId()}.It is recommended to + * retrieve the deviceId and store it to identify the device properly. * * @example * // initialize without deviceId @@ -882,7 +961,12 @@ declare namespace KiiCloud { * // initialize with deviceId * Kii.initializeWithSite("my-app-id", "my-app-key", KiiAnalyticsSite.JP, "my-device-id"); */ - static initializeWithSite(appID: string, appKey: string, site: KiiAnalyticsSite, deviceid: string): void; + static initializeWithSite( + appID: string, + appKey: string, + site: KiiAnalyticsSite, + deviceid: string + ): void; /** * @@ -893,7 +977,8 @@ declare namespace KiiCloud { * * @param appID The application ID found in your Kii developer console * @param appKey The application key found in your Kii developer console - * @param deviceid If deviceId is not provided, SDK generates a new deviceId and use it when upload events. deviceId can be retrieved by {@link KiiAnalytics.getDeviceId()}.It is recommended to retrieve the deviceId and store it to identify the device properly. + * @param deviceid If deviceId is not provided, SDK generates a new deviceId and use it when upload events. deviceId can be retrieved by {@link KiiAnalytics.getDeviceId()}.It is recommended to + * retrieve the deviceId and store it to identify the device properly. * * @example * // initialize without deviceId @@ -901,7 +986,11 @@ declare namespace KiiCloud { * // initialize with deviceId * Kii.initializeWithSite("my-app-id", "my-app-key", KiiAnalyticsSite.JP, "my-device-id"); */ - static initialize(appID: string, appKey: string, deviceid: string): void; + static initialize( + appID: string, + appKey: string, + deviceid: string + ): void; /** * Utilize the KiiAnalytics logger to track SDK-specific actions @@ -913,7 +1002,9 @@ declare namespace KiiCloud { * @example * KiiAnalytics.logger("My message"); */ - static logger(message: string): void; + static logger( + message: string + ): void; /** * Log a single event to be uploaded to KiiAnalytics @@ -932,7 +1023,9 @@ declare namespace KiiCloud { * *
    */ - static trackEvent(eventName: string): Promise; + static trackEvent( + eventName: string + ): Promise; /** * Log a single event to be uploaded to KiiAnalytics @@ -955,7 +1048,10 @@ declare namespace KiiCloud { * * */ - static trackEventWithExtras(eventName: string, extras: any): Promise; + static trackEventWithExtras( + eventName: string, + extras: any + ): Promise; /** * Log a single event to be uploaded to KiiAnalytics @@ -979,7 +1075,11 @@ declare namespace KiiCloud { * * */ - static trackEventWithExtrasAndCallbacks(eventName: string, extras: any, callbacks?: { success(): any; failure(error: Error): any; }): Promise; + static trackEventWithExtrasAndCallbacks( + eventName: string, + extras: any, + callbacks?: { success(): any; failure(error: Error): any; } + ): Promise; /** * @@ -988,7 +1088,9 @@ declare namespace KiiCloud { * * @param url A string containing the desired endpoint */ - static setBaseURL(url: string): void; + static setBaseURL( + url: string + ): void; /** * @@ -1054,7 +1156,9 @@ declare namespace KiiCloud { * } * }); */ - bucketWithName(bucketName: string): KiiBucket; + bucketWithName( + bucketName: string + ): KiiBucket; /** * Creates a reference to a encrypted bucket operated by app admin. @@ -1075,7 +1179,9 @@ declare namespace KiiCloud { * } * }); */ - encryptedBucketWithName(bucketName: string): KiiBucket; + encryptedBucketWithName( + bucketName: string + ): KiiBucket; /** * Creates a reference to a group operated by app admin. @@ -1099,7 +1205,9 @@ declare namespace KiiCloud { * } * }); */ - groupWithName(group: string): KiiGroup; + groupWithName( + group: string + ): KiiGroup; /** * Creates a reference to a user operated by app admin. @@ -1119,7 +1227,9 @@ declare namespace KiiCloud { * } * }); */ - userWithID(user: string): KiiUser; + userWithID( + user: string + ): KiiUser; /** * Creates a reference to an object operated by app admin using object`s URI. @@ -1130,7 +1240,9 @@ declare namespace KiiCloud { * * @throws If the URI is null, empty or does not have correct format. */ - objectWithURI(object: string): KiiObject; + objectWithURI( + object: string + ): KiiObject; /** * Creates a reference to a group operated by app admin using group's ID. @@ -1157,7 +1269,9 @@ declare namespace KiiCloud { * } * }); */ - groupWithID(group: string): KiiGroup; + groupWithID( + group: string + ): KiiGroup; /** * Register new group own by specified user on Kii Cloud with specified ID. @@ -1216,7 +1330,13 @@ declare namespace KiiCloud { * } * ); */ - registerGroupWithOwnerAndID(groupID: string, groupName: string, user: string, members: KiiUser[], callbacks?: { success(adminContext: KiiAppAdminContext): any; failure(theGroup: KiiGroup, anErrorString: string, addMembersArray: KiiUser[], removeMembersArray: KiiUser[]): any; }): Promise; + registerGroupWithOwnerAndID( + groupID: string, + groupName: string, + user: string, + members: KiiUser[], + callbacks?: { success(adminContext: KiiAppAdminContext): any; failure(theGroup: KiiGroup, anErrorString: string, addMembersArray: KiiUser[], removeMembersArray: KiiUser[]): any; } + ): Promise; /** * Creates a reference to a group operated by app admin using group's URI. @@ -1243,7 +1363,9 @@ declare namespace KiiCloud { * } * }); */ - groupWithURI(group: string): KiiGroup; + groupWithURI( + group: string + ): KiiGroup; /** * Find registered KiiUser with the email.
    @@ -1317,7 +1439,10 @@ declare namespace KiiCloud { * } * ); */ - findUserByEmail(email: string, callbacks?: { success(adminContext: KiiAppAdminContext, theMatchedUser: KiiUser): any; failure(adminContext: KiiAppAdminContext, anErrorString: string): any; }): Promise<[KiiAppAdminContext, KiiUser]>; + findUserByEmail( + email: string, + callbacks?: { success(adminContext: KiiAppAdminContext, theMatchedUser: KiiUser): any; failure(adminContext: KiiAppAdminContext, anErrorString: string): any; } + ): Promise<[KiiAppAdminContext, KiiUser]>; /** * Find registered KiiUser with the phone.
    @@ -1391,7 +1516,10 @@ declare namespace KiiCloud { * } * ); */ - findUserByPhone(phone: string, callbacks?: { success(adminContext: KiiAppAdminContext, theMatchedUser: KiiUser): any; failure(adminContext: KiiAppAdminContext, anErrorString: string): any; }): Promise<[KiiAppAdminContext, KiiUser]>; + findUserByPhone( + phone: string, + callbacks?: { success(adminContext: KiiAppAdminContext, theMatchedUser: KiiUser): any; failure(adminContext: KiiAppAdminContext, anErrorString: string): any; } + ): Promise<[KiiAppAdminContext, KiiUser]>; /** * Find registered KiiUser with the user name.
    @@ -1463,7 +1591,10 @@ declare namespace KiiCloud { * } * ); */ - findUserByUsername(username: string, callbacks?: { success(adminContext: KiiAppAdminContext, theMatchedUser: KiiUser): any; failure(adminContext: KiiAppAdminContext, anErrorString: string): any; }): Promise<[KiiAppAdminContext, KiiUser]>; + findUserByUsername( + username: string, + callbacks?: { success(adminContext: KiiAppAdminContext, theMatchedUser: KiiUser): any; failure(adminContext: KiiAppAdminContext, anErrorString: string): any; } + ): Promise<[KiiAppAdminContext, KiiUser]>; /** * Register thing by app admin. @@ -1533,7 +1664,10 @@ declare namespace KiiCloud { * } * ); */ - registerThing(fields: KiiThingFields, callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; }): Promise; + registerThing( + fields: KiiThingFields, + callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; } + ): Promise; /** * Creates a reference to a thing operated by app admin. @@ -1546,7 +1680,9 @@ declare namespace KiiCloud { * // Assume you already have adminContext instance. * adminContext.thingWithID(thingID); */ - thingWithID(thing: string): KiiThing; + thingWithID( + thing: string + ): KiiThing; /** * Register user/group as owner of specified thing by app admin. @@ -1599,7 +1735,11 @@ declare namespace KiiCloud { * } * ); */ - registerOwnerWithThingID(thingID: string, owner: T, callbacks?: { success(group: T): any; failure(error: Error): any; }): Promise; + registerOwnerWithThingID( + thingID: string, + owner: T, + callbacks?: { success(group: T): any; failure(error: Error): any; } + ): Promise; /** * Register user/group as owner of specified thing by app admin. @@ -1651,7 +1791,11 @@ declare namespace KiiCloud { * } * ); */ - registerOwnerWithVendorThingID(vendorThingID: string, owner: T, callbacks?: { success(group: T): any; failure(error: Error): any; }): Promise; + registerOwnerWithVendorThingID( + vendorThingID: string, + owner: T, + callbacks?: { success(group: T): any; failure(error: Error): any; } + ): Promise; /** * Load thing with vendor thing ID by app admin. @@ -1698,7 +1842,10 @@ declare namespace KiiCloud { * } * ); */ - loadThingWithVendorThingID(vendorThingID: string, callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; }): Promise; + loadThingWithVendorThingID( + vendorThingID: string, + callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; } + ): Promise; /** * Load thing with thing ID by app admin. @@ -1745,7 +1892,10 @@ declare namespace KiiCloud { * } * ); */ - loadThingWithThingID(thingID: string, callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; }): Promise; + loadThingWithThingID( + thingID: string, + callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; } + ): Promise; /** * Creates a reference to a topic operated by app admin @@ -1754,13 +1904,16 @@ declare namespace KiiCloud { * * @return topic instance. */ - topicWithName(topicName: string): KiiTopic; + topicWithName( + topicName: string + ): KiiTopic; /** * Gets a list of topics in app scope * * @param callbacks An object with callback methods defined - * @param paginationKey You can specify the pagination key with the nextPaginationKey passed by callbacks.success. If empty string or no string object is provided, this API regards no paginationKey specified. + * @param paginationKey You can specify the pagination key with the nextPaginationKey passed by callbacks.success. If empty string or no string object is provided, this API regards no + * paginationKey specified. * * @return return promise object. *
      @@ -1821,7 +1974,10 @@ declare namespace KiiCloud { * } * ); */ - listTopics(callbacks?: { success(topicList: KiiTopic[], nextPaginationKey: string): any; failure(anErrorString: string): any; }, paginationKey?: string): Promise<[KiiTopic[], string]>; + listTopics( + callbacks?: { success(topicList: KiiTopic[], nextPaginationKey: string): any; failure(anErrorString: string): any; }, + paginationKey?: string + ): Promise<[KiiTopic[], string]>; } /** @@ -1851,7 +2007,8 @@ declare namespace KiiCloud { /** * Create a KiiObject within the current bucket, with type * - *

      The object will not be created on the server until the KiiObject is explicitly saved. This method simply returns an empty working KiiObject with a specified type. The type allows for better indexing and improved query results. It is recommended to use this method - but for lazy creation, the createObject method is also available. + *

      The object will not be created on the server until the KiiObject is explicitly saved. This method simply returns an empty working KiiObject with a specified type. The type allows + * for better indexing and improved query results. It is recommended to use this method - but for lazy creation, the createObject method is also available. * * @param type A string representing the desired object type * @@ -1861,7 +2018,9 @@ declare namespace KiiCloud { * var bucket = . . .; // a KiiBucket * var object = bucket.createObjectWithType("scores"); */ - createObjectWithType(type: string): KiiObject; + createObjectWithType( + type: string + ): KiiObject; /** * Create a KiiObject within the current bucket, specifying its ID. @@ -1883,7 +2042,9 @@ declare namespace KiiCloud { * var bucket = . . .; // KiiBucket * var object = bucket.createObjectWithID('__OBJECT_ID_'); */ - createObjectWithID(objectID: string): KiiObject; + createObjectWithID( + objectID: string + ): KiiObject; /** * Get the ACL handle for this bucket @@ -1985,7 +2146,10 @@ declare namespace KiiCloud { * } * ); */ - executeQuery(query: KiiQuery, callbacks?: { success(queryPerformed: KiiQuery, resultSet: T[], nextQuery: KiiQuery): any; failure(bucket: KiiBucket, anErrorString: string): any; }): Promise<[KiiQuery, T[], KiiQuery]>; + executeQuery( + query: KiiQuery, + callbacks?: { success(queryPerformed: KiiQuery, resultSet: T[], nextQuery: KiiQuery): any; failure(bucket: KiiBucket, anErrorString: string): any; } + ): Promise<[KiiQuery, T[], KiiQuery]>; /** * Execute count aggregation of specified query on current bucket. @@ -2048,7 +2212,10 @@ declare namespace KiiCloud { * } * ); */ - countWithQuery(query: KiiQuery, callbacks?: { success(bucket: KiiBucket, query: KiiQuery, count: number): any; failure(bucket: KiiBucket, errorString: string): any; }): Promise<[KiiBucket, KiiQuery, number]>; + countWithQuery( + query: KiiQuery, + callbacks?: { success(bucket: KiiBucket, query: KiiQuery, count: number): any; failure(bucket: KiiBucket, errorString: string): any; } + ): Promise<[KiiBucket, KiiQuery, number]>; /** * Execute count aggregation of all clause query on current bucket. @@ -2105,7 +2272,9 @@ declare namespace KiiCloud { * } * ); */ - count(callbacks?: { success(bucket: KiiBucket, query: KiiQuery, count: number): any; failure(bucket: KiiBucket, errorString: string): any; }): Promise<[KiiBucket, KiiQuery, number]>; + count( + callbacks?: { success(bucket: KiiBucket, query: KiiQuery, count: number): any; failure(bucket: KiiBucket, errorString: string): any; } + ): Promise<[KiiBucket, KiiQuery, number]>; /** * Delete the given bucket from the server @@ -2155,7 +2324,9 @@ declare namespace KiiCloud { * } * ); */ - delete(callbacks?: { success(deletedBucket: KiiBucket): any; failure(bucketToDelete: KiiBucket, anErrorString: string): any; }): Promise; + delete( + callbacks?: { success(deletedBucket: KiiBucket): any; failure(bucketToDelete: KiiBucket, anErrorString: string): any; } + ): Promise; } /** @@ -2170,17 +2341,36 @@ declare namespace KiiCloud { * @example * KiiClause clause = KiiClause.and(clause1, clause2, clause3, . . .) */ - static and(...A: KiiClause[]): KiiClause; + static and( + ...A: KiiClause[] + ): KiiClause; /** * Create a KiiClause with the OR operator concatenating multiple KiiClause objects + *

      + * Note: + * Query performance will be worse as the number of objects in bucket increases, so we recommend you avoid the OR clause if possible. * * @param A variable-length list of KiiClause objects to concatenate * * @example * KiiClause clause = KiiClause.or(clause1, clause2, clause3, . . .) */ - static or(...A: KiiClause[]): KiiClause; + static or( + ...A: KiiClause[] + ): KiiClause; + + /** + * Create a KiiClause with the NOT operator concatenating a KiiClause object + *

      + * Note: + * Query performance will be worse as the number of objects in bucket increases, so we recommend you avoid the NOT clause if possible. + * + * @param clause KiiClause object to negate + */ + static not( + clause: KiiClause + ): KiiClause; /** * Create an expression of the form (key == value) @@ -2188,7 +2378,10 @@ declare namespace KiiCloud { * @param key The key to compare * @param value the value to compare */ - static equals(key: string, value: any): KiiClause; + static equals( + key: string, + value: any + ): KiiClause; /** * Create an expression of the form (key != value) @@ -2196,7 +2389,10 @@ declare namespace KiiCloud { * @param key The key to compare * @param value the value to compare */ - static notEquals(key: string, value: any): KiiClause; + static notEquals( + key: string, + value: any + ): KiiClause; /** * Create an expression of the form (key > value) @@ -2204,7 +2400,10 @@ declare namespace KiiCloud { * @param key The key to compare * @param value the value to compare */ - static greaterThan(key: string, value: any): KiiClause; + static greaterThan( + key: string, + value: any + ): KiiClause; /** * Create an expression of the form (key >= value) @@ -2212,7 +2411,10 @@ declare namespace KiiCloud { * @param key The key to compare * @param value the value to compare */ - static greaterThanOrEqual(key: string, value: any): KiiClause; + static greaterThanOrEqual( + key: string, + value: any + ): KiiClause; /** * Create an expression of the form (key < value) @@ -2220,7 +2422,10 @@ declare namespace KiiCloud { * @param key The key to compare * @param value the value to compare */ - static lessThan(key: string, value: any): KiiClause; + static lessThan( + key: string, + value: any + ): KiiClause; /** * Create an expression of the form (key <= value) @@ -2228,7 +2433,10 @@ declare namespace KiiCloud { * @param key The key to compare * @param value the value to compare */ - static lessThanOrEqual(key: string, value: any): KiiClause; + static lessThanOrEqual( + key: string, + value: any + ): KiiClause; /** * Create an expression of the form (key in values) @@ -2236,7 +2444,10 @@ declare namespace KiiCloud { * @param key The key to compare * @param values to compare */ - static inClause(key: string, values: any[]): KiiClause; + static inClause( + key: string, + values: any[] + ): KiiClause; /** * Create an expression of the form (key STARTS WITH value) @@ -2244,7 +2455,10 @@ declare namespace KiiCloud { * @param key The key to compare * @param value the value to compare */ - static startsWith(key: string, value: any): KiiClause; + static startsWith( + key: string, + value: any + ): KiiClause; /** * Create a clause of geo distance. This clause inquires objects in the specified circle. @@ -2287,7 +2501,12 @@ declare namespace KiiCloud { * }; * bucket.executeQuery(query, queryCallback); */ - static geoDistance(key: string, center: KiiGeoPoint, radius: number, putDistanceInto: string): KiiClause; + static geoDistance( + key: string, + center: KiiGeoPoint, + radius: number, + putDistanceInto: string + ): KiiClause; /** * Create a clause of geo box. This clause inquires objects in the specified rectangle. @@ -2302,7 +2521,54 @@ declare namespace KiiCloud { * @throws
    • Specified key is not a string or is an empty string.
    • *
    • northEast or southWest is not a reference of KiiGeoPoint.
    • */ - static geoBox(key: string, northEast: KiiGeoPoint, southWest: KiiGeoPoint): KiiClause; + static geoBox( + key: string, + northEast: KiiGeoPoint, + southWest: KiiGeoPoint + ): KiiClause; + + /** + * Create an expression to returns all entities that have a specified field and type. + * + * @param key name of the specified field. + * @param fieldType The type of the content of the field. The type of the content of the field must be provided, possible values are "STRING", "INTEGER", "DECIMAL" and "BOOLEAN". + */ + static hasField( + key: string, + fieldType: string + ): KiiClause; + } + + /** + * A Parser for error string or error object returned by SDK. + */ + export class KiiErrorParser { + /** + * Parse an error string or error object returned by SDK. + * + * @param error An error string or error object + * + * @return return parsed error object. + * + * @example + * var err = KiiErrorParser.parse(errorString); + * var httpStatus = err.status; + * if (httpStatus == 0) { + * // NetworkError + * } else if (httpStatus == -1) { + * // Error is not related the http error. eg. argument error, illegal state error, etc. + * } else if (httpStatus == -2) { + * // Unknown error is detected. + * // Please confirm that you are using the latest version of SDK. + * } else if (httpStatus >= 400 && httpStatus < 600) { + * // Http error + * } + * var errorCode = err.code; + * var errorMessage = err.message; + */ + static parse( + error: T + ): KiiError; } /** @@ -2332,7 +2598,10 @@ declare namespace KiiCloud { * @example * var point = KiiGeoPoint.geoPoint(35.07, 139.02); */ - static geoPoint(latitude: number, longitude: number): KiiGeoPoint; + static geoPoint( + latitude: number, + longitude: number + ): KiiGeoPoint; } /** @@ -2445,7 +2714,12 @@ declare namespace KiiCloud { * // do something with the error response * }); */ - static registerGroupWithID(groupID: string, groupName: string, members: KiiUser[], callbacks?: { success(theSavedGroup: KiiGroup): any; failure(theGroup: KiiGroup, anErrorString: string, addMembersArray: KiiUser[], removeMembersArray: KiiUser[]): any; }): Promise; + static registerGroupWithID( + groupID: string, + groupName: string, + members: KiiUser[], + callbacks?: { success(theSavedGroup: KiiGroup): any; failure(theGroup: KiiGroup, anErrorString: string, addMembersArray: KiiUser[], removeMembersArray: KiiUser[]): any; } + ): Promise; /** * Creates a reference to a bucket for this group @@ -2460,7 +2734,9 @@ declare namespace KiiCloud { * var group = . . .; // a KiiGroup * var bucket = group.bucketWithName("myBucket"); */ - bucketWithName(bucketName: string): KiiBucket; + bucketWithName( + bucketName: string + ): KiiBucket; /** * Creates a reference to a encrypted bucket for this group @@ -2475,7 +2751,9 @@ declare namespace KiiCloud { * var group = . . .; // a KiiGroup * var bucket = group.encryptedBucketWithName("myBucket"); */ - encryptedBucketWithName(bucketName: string): KiiBucket; + encryptedBucketWithName( + bucketName: string + ): KiiBucket; /** * Adds a user to the given group @@ -2490,7 +2768,9 @@ declare namespace KiiCloud { * group.addUser(user); * group.save(callbacks); */ - addUser(member: KiiUser): void; + addUser( + member: KiiUser + ): void; /** * Removes a user from the given group @@ -2505,7 +2785,9 @@ declare namespace KiiCloud { * group.removeUser(user); * group.save(callbacks); */ - removeUser(member: KiiUser): void; + removeUser( + member: KiiUser + ): void; /** * Gets a list of all current members of a group @@ -2560,7 +2842,9 @@ declare namespace KiiCloud { * } * ); */ - getMemberList(callbacks?: { success(theGroup: KiiGroup, memberList: KiiUser[]): any; failure(theGroup: KiiGroup, anErrorString: string): any; }): Promise<[KiiGroup, KiiUser[]]>; + getMemberList( + callbacks?: { success(theGroup: KiiGroup, memberList: KiiUser[]): any; failure(theGroup: KiiGroup, anErrorString: string): any; } + ): Promise<[KiiGroup, KiiUser[]]>; /** * Updates the group name on the server @@ -2603,12 +2887,16 @@ declare namespace KiiCloud { * } * ); */ - changeGroupName(newName: string, callbacks?: { success(theRenamedGroup: KiiGroup): any; failure(theGroup: KiiGroup, anErrorString: string): any; }): Promise; + changeGroupName( + newName: string, + callbacks?: { success(theRenamedGroup: KiiGroup): any; failure(theGroup: KiiGroup, anErrorString: string): any; } + ): Promise; /** * Saves the latest group values to the server * - *

      If the group does not yet exist, it will be created. If the group already exists, the members that have changed will be updated accordingly. If the group already exists and there is no updates of members, it will allways succeed but does not execute update. To change the name of group, use {@link #changeGroupName}. + *

      If the group does not yet exist, it will be created. If the group already exists, the members that have changed will be updated accordingly. If the group already exists and there is + * no updates of members, it will allways succeed but does not execute update. To change the name of group, use {@link #changeGroupName}. * * @param callbacks An object with callback methods defined * @@ -2652,13 +2940,16 @@ declare namespace KiiCloud { * // do something with the error response * }); */ - save(callbacks?: { success(theSavedGroup: KiiGroup): any; failure(theGroup: KiiGroup, anErrorString: string, addMembersArray: KiiUser[], removeMembersArray: KiiUser[]): any; }): Promise; + save( + callbacks?: { success(theSavedGroup: KiiGroup): any; failure(theGroup: KiiGroup, anErrorString: string, addMembersArray: KiiUser[], removeMembersArray: KiiUser[]): any; } + ): Promise; /** * Saves the latest group values to the server with specified owner. * This method can be used only by the group owner or app admin. * - *

      If the group does not yet exist, it will be created. If the group already exists, the members and owner that have changed will be updated accordingly. If the group already exists and there is no updates of members and owner, it will allways succeed but does not execute update. To change the name of group, use {@link #changeGroupName}. + *

      If the group does not yet exist, it will be created. If the group already exists, the members and owner that have changed will be updated accordingly. If the group already exists + * and there is no updates of members and owner, it will allways succeed but does not execute update. To change the name of group, use {@link #changeGroupName}. * * @param user id of owner * @param callbacks An object with callback methods defined @@ -2703,7 +2994,10 @@ declare namespace KiiCloud { * // do something with the error response * }); */ - saveWithOwner(user: string, callbacks?: { success(theSavedGroup: KiiGroup): any; failure(theGroup: KiiGroup, anErrorString: string, addMembersArray: KiiUser[], removeMembersArray: KiiUser[]): any; }): Promise; + saveWithOwner( + user: string, + callbacks?: { success(theSavedGroup: KiiGroup): any; failure(theGroup: KiiGroup, anErrorString: string, addMembersArray: KiiUser[], removeMembersArray: KiiUser[]): any; } + ): Promise; /** * Updates the local group's data with the group data on the server @@ -2747,7 +3041,9 @@ declare namespace KiiCloud { * } * ); */ - refresh(callbacks?: { success(theRefreshedGroup: KiiGroup): any; failure(theGroup: KiiGroup, anErrorString: string): any; }): Promise; + refresh( + callbacks?: { success(theRefreshedGroup: KiiGroup): any; failure(theGroup: KiiGroup, anErrorString: string): any; } + ): Promise; /** * Delete the group from the server @@ -2795,7 +3091,9 @@ declare namespace KiiCloud { * } * ); */ - delete(callbacks?: { success(theDeletedGroup: KiiGroup): any; failure(theGroup: KiiGroup, anErrorString: string): any; }): Promise; + delete( + callbacks?: { success(theDeletedGroup: KiiGroup): any; failure(theGroup: KiiGroup, anErrorString: string): any; } + ): Promise; /** * Gets the owner of the associated group @@ -2844,7 +3142,9 @@ declare namespace KiiCloud { * } * ); */ - getOwner(callbacks?: { success(theGroup: KiiGroup, theOwner: KiiUser): any; failure(theGroup: KiiGroup, anErrorString: string): any; }): Promise<[KiiGroup, KiiUser]>; + getOwner( + callbacks?: { success(theGroup: KiiGroup, theOwner: KiiUser): any; failure(theGroup: KiiGroup, anErrorString: string): any; } + ): Promise<[KiiGroup, KiiUser]>; /** * Creates a reference to a group with the given name @@ -2860,7 +3160,9 @@ declare namespace KiiCloud { * @example * var group = new KiiGroup.groupWithName("myGroup"); */ - static groupWithName(groupName: string): KiiGroup; + static groupWithName( + groupName: string + ): KiiGroup; /** * Creates a reference to a group with the given name and a list of default members @@ -2877,7 +3179,10 @@ declare namespace KiiCloud { * @example * var group = new KiiGroup.groupWithName("myGroup", members); */ - static groupWithNameAndMembers(groupName: string, members: KiiUser[]): KiiGroup; + static groupWithNameAndMembers( + groupName: string, + members: KiiUser[] + ): KiiGroup; /** * Instantiate KiiGroup that refers to existing group which has specified ID. @@ -2895,7 +3200,9 @@ declare namespace KiiCloud { * @example * var group = new KiiUser.groupWithID("__GROUP_ID__"); */ - static groupWithID(groupId: string): KiiGroup; + static groupWithID( + groupId: string + ): KiiGroup; /** * Generate a new KiiGroup based on a given URI @@ -2913,7 +3220,9 @@ declare namespace KiiCloud { * @example * var group = new KiiGroup.groupWithURI("kiicloud://myuri"); */ - static groupWithURI(uri: string): KiiGroup; + static groupWithURI( + uri: string + ): KiiGroup; /** * Instantiate topic belongs to this group. @@ -2922,13 +3231,16 @@ declare namespace KiiCloud { * * @return topic instance. */ - topicWithName(topicName: string): KiiTopic; + topicWithName( + topicName: string + ): KiiTopic; /** * Gets a list of topics in this group scope * * @param callbacks An object with callback methods defined - * @param paginationKey You can specify the pagination key with the nextPaginationKey passed by callbacks.success. If empty string or no string object is provided, this API regards no paginationKey specified. + * @param paginationKey You can specify the pagination key with the nextPaginationKey passed by callbacks.success. If empty string or no string object is provided, this API regards no + * paginationKey specified. * * @return return promise object. *
        @@ -2989,7 +3301,10 @@ declare namespace KiiCloud { * } * ); */ - listTopics(callbacks?: { success(topicList: KiiTopic[], nextPaginationKey: string): any; failure(anErrorString: string): any; }, paginationKey?: string): Promise<[KiiTopic[], string]>; + listTopics( + callbacks?: { success(topicList: KiiTopic[], nextPaginationKey: string): any; failure(anErrorString: string): any; }, + paginationKey?: string + ): Promise<[KiiTopic[], string]>; } /** @@ -3048,7 +3363,8 @@ declare namespace KiiCloud { * The reason is: *
      • Will dramatically improve the performance of bucket query.
      • *
      • Bucket query does not support the mixed result of integer and floating point. - * ex.) If you use same key for integer and floating point and inquire object with the integer value, objects which has floating point value with the key would not be evaluated in the query. (and vice versa)
      • + * ex.) If you use same key for integer and floating point and inquire object with the integer value, objects which has floating point value with the key would not be evaluated in the + * query. (and vice versa) * * @param key The key to set. * if null, empty string or string prefixed with '_' is specified, silently ignored and have no effect. @@ -3060,7 +3376,10 @@ declare namespace KiiCloud { * var obj = . . .; // a KiiObject * obj.set("score", 4298); */ - set(key: string, value: any): void; + set( + key: string, + value: any + ): void; /** * Gets the value associated with the given key @@ -3073,7 +3392,38 @@ declare namespace KiiCloud { * var obj = . . .; // a KiiObject * var score = obj.get("score"); */ - get(key: string): T; + get( + key: string + ): T; + + /** + * Gets the array object that contains all keys of custom field. + * The array of keys from local cache will be returned. + * To get the latest array of keys from cloud, calling refresh() is necessary prior calling this method. + * The returned array object does not include reserved keys such as _created, _modified, etc. + * + * @return keys An array of all keys of custom field. + * + * @example + * var obj = . . .; // a KiiObject + * for(var key of obj.keys()) { + * } + */ + getKeys(): string[]; + + /** + * Removes a pair of key/value from this object. + * This pair is also removed from server when saveAllFields() is succeeded. + * + * @param key The key to be removed + * + * @example + * var obj = . . .; // a KiiObject + * obj.remove("score"); + */ + remove( + key: string + ): void; /** * Set Geo point to this object with the specified key. @@ -3083,7 +3433,10 @@ declare namespace KiiCloud { * * @throws Specified kiiGeoPint is not an instance of KiiGeoPoint. */ - setGeoPoint(key: string, KiiGeoPoint: KiiGeoPoint): void; + setGeoPoint( + key: string, + KiiGeoPoint: KiiGeoPoint + ): void; /** * Gets the geo point associated with the given key. @@ -3092,7 +3445,9 @@ declare namespace KiiCloud { * * @return KiiGeoPoint tied to the key. null if null exists. */ - getGeoPoint(key: string): KiiGeoPoint; + getGeoPoint( + key: string + ): KiiGeoPoint; /** * Get the ACL handle for this file @@ -3175,7 +3530,10 @@ declare namespace KiiCloud { * } * ); */ - saveAllFields(callbacks?: { success(theSavedObject: KiiObject): any; failure(theObject: KiiObject, anErrorString: string): any; }, overwrite?: boolean): Promise; + saveAllFields( + callbacks?: { success(theSavedObject: KiiObject): any; failure(theObject: KiiObject, anErrorString: string): any; }, + overwrite?: boolean + ): Promise; /** * Create or update the KiiObject on KiiCloud. @@ -3233,7 +3591,10 @@ declare namespace KiiCloud { * } * ); */ - save(callbacks?: { success(theSavedObject: KiiObject): any; failure(theObject: KiiObject, anErrorString: string): any; }, overwrite?: boolean): Promise; + save( + callbacks?: { success(theSavedObject: KiiObject): any; failure(theObject: KiiObject, anErrorString: string): any; }, + overwrite?: boolean + ): Promise; /** * Updates the local object's data with the user data on the server @@ -3277,7 +3638,9 @@ declare namespace KiiCloud { * } * ); */ - refresh(callbacks?: { success(theRefreshedObject: KiiObject): any; failure(theObject: KiiObject, anErrorString: string): any; }): Promise; + refresh( + callbacks?: { success(theRefreshedObject: KiiObject): any; failure(theObject: KiiObject, anErrorString: string): any; } + ): Promise; /** * Delete the object from the server @@ -3319,7 +3682,9 @@ declare namespace KiiCloud { * } * ); */ - delete(callbacks?: { success(theDeletedObject: KiiObject): any; failure(theObject: KiiObject, anErrorString: string): any; }): Promise; + delete( + callbacks?: { success(theDeletedObject: KiiObject): any; failure(theObject: KiiObject, anErrorString: string): any; } + ): Promise; /** * Generate a new KiiObject based on a given URI @@ -3333,7 +3698,9 @@ declare namespace KiiCloud { * @example * var group = new KiiObject.objectWithURI("kiicloud://myuri"); */ - static objectWithURI(uri: string): KiiObject; + static objectWithURI( + uri: string + ): KiiObject; /** * Move KiiObject body from an object to another object. @@ -3392,7 +3759,10 @@ declare namespace KiiCloud { * } * ); */ - moveBody(targetObjectUri: string, callbacks?: { success(theSrcObject: KiiObject, theTgtObjectUri: string): any; failure(theSrcObject: KiiObject, theTgtObjectUri: string, anErrorString: string): any; }): Promise<[KiiObject, string]>; + moveBody( + targetObjectUri: string, + callbacks?: { success(theSrcObject: KiiObject, theTgtObjectUri: string): any; failure(theSrcObject: KiiObject, theTgtObjectUri: string, anErrorString: string): any; } + ): Promise<[KiiObject, string]>; /** * Upload body data of this object.
        @@ -3472,7 +3842,10 @@ declare namespace KiiCloud { * } * ); */ - uploadBody(srcDataBlob: Blob, callbacks?: { success(obj: KiiObject): any; failure(obj: KiiObject, anErrorString: string): any; }): Promise; + uploadBody( + srcDataBlob: Blob, + callbacks?: { success(obj: KiiObject): any; failure(obj: KiiObject, anErrorString: string): any; } + ): Promise; /** * Download body data of this object.
        @@ -3547,7 +3920,9 @@ declare namespace KiiCloud { * } * ); */ - downloadBody(callbacks?: { success(obj: KiiObject, bodyBlob: Blob): any; failure(obj: KiiObject, anErrorString: string): any; }): Promise<[KiiObject, Blob]>; + downloadBody( + callbacks?: { success(obj: KiiObject, bodyBlob: Blob): any; failure(obj: KiiObject, anErrorString: string): any; } + ): Promise<[KiiObject, Blob]>; /** * Publish object body.
        @@ -3600,7 +3975,9 @@ declare namespace KiiCloud { * } * ); */ - publishBody(callbacks?: { success(obj: KiiObject, publishedUrl: string): any; failure(obj: KiiObject, anErrorString: string): any; }): Promise<[KiiObject, string]>; + publishBody( + callbacks?: { success(obj: KiiObject, publishedUrl: string): any; failure(obj: KiiObject, anErrorString: string): any; } + ): Promise<[KiiObject, string]>; /** * Publish object body with expiration date.
        @@ -3656,7 +4033,10 @@ declare namespace KiiCloud { * } * ); */ - publishBodyExpiresAt(expiresAt: Date, callbacks?: { success(obj: KiiObject, publishedUrl: string): any; failure(obj: KiiObject, anErrorString: string): any; }): Promise<[KiiObject, string]>; + publishBodyExpiresAt( + expiresAt: Date, + callbacks?: { success(obj: KiiObject, publishedUrl: string): any; failure(obj: KiiObject, anErrorString: string): any; } + ): Promise<[KiiObject, string]>; /** * Publish object body with expiration duration.
        @@ -3712,7 +4092,10 @@ declare namespace KiiCloud { * } * ); */ - publishBodyExpiresIn(expiresIn: number, callbacks?: { success(obj: KiiObject, publishedUrl: string): any; failure(obj: KiiObject, anErrorString: string): any; }): Promise<[KiiObject, string]>; + publishBodyExpiresIn( + expiresIn: number, + callbacks?: { success(obj: KiiObject, publishedUrl: string): any; failure(obj: KiiObject, anErrorString: string): any; } + ): Promise<[KiiObject, string]>; /** * Delete the object body from the server.
        @@ -3757,7 +4140,9 @@ declare namespace KiiCloud { * } * ); */ - deleteBody(callbacks?: { success(theDeletedObject: KiiObject): any; failure(obj: KiiObject, anErrorString: string): any; }): Promise; + deleteBody( + callbacks?: { success(theDeletedObject: KiiObject): any; failure(obj: KiiObject, anErrorString: string): any; } + ): Promise; /** * Check if given ID is valid for object ID. @@ -3767,7 +4152,9 @@ declare namespace KiiCloud { * * @return true if given ID is valid, false otherwise. */ - static isValidObjectID(objectID: string): boolean; + static isValidObjectID( + objectID: string + ): boolean; } /** @@ -3798,7 +4185,11 @@ declare namespace KiiCloud { * @example * */ - installGcm(installationRegistrationID: string, development: boolean, callbacks?: { success(response: KiiGcmInstallationResponse): any; failure(error: Error): any; }): Promise; + installGcm( + installationRegistrationID: string, + development: boolean, + callbacks?: { success(response: KiiGcmInstallationResponse): any; failure(error: Error): any; } + ): Promise; /** * Register a MQTT installation to the Kii cloud for current logged in user. @@ -3824,7 +4215,10 @@ declare namespace KiiCloud { * @example * */ - installMqtt(development: boolean, callbacks?: { success(response: KiiMqttInstallationResponse): any; failure(error: Error): any; }): Promise; + installMqtt( + development: boolean, + callbacks?: { success(response: KiiMqttInstallationResponse): any; failure(error: Error): any; } + ): Promise; /** * Get MQTT endpoint. @@ -3862,7 +4256,10 @@ declare namespace KiiCloud { * @example * */ - getMqttEndpoint(installationID: string, callbacks?: { success(response: KiiMqttEndpoint): any; failure(error: Error): any; }): Promise; + getMqttEndpoint( + installationID: string, + callbacks?: { success(response: KiiMqttEndpoint): any; failure(error: Error): any; } + ): Promise; /** * Unregister the push settings by the id(issued by push provider) that is used for installation. @@ -3884,7 +4281,11 @@ declare namespace KiiCloud { * @example * */ - uninstall(installationRegistrationID: string, deviceType: string, callbacks?: { success(): any; failure(error: Error): any; }): Promise; + uninstall( + installationRegistrationID: string, + deviceType: string, + callbacks?: { success(): any; failure(error: Error): any; } + ): Promise; /** * Unregister the push settings by the id(issued by KiiCloud) that is used for installation. @@ -3905,7 +4306,10 @@ declare namespace KiiCloud { * @example * */ - uninstallByInstallationID(installationID: string, callbacks?: { success(): any; failure(error: Error): any; }): Promise; + uninstallByInstallationID( + installationID: string, + callbacks?: { success(): any; failure(error: Error): any; } + ): Promise; } /** @@ -3922,7 +4326,9 @@ declare namespace KiiCloud { * * @param data sent to all push channels (gcm, apns, jpush, mqtt). */ - constructor(data: any); + constructor( + data: any + ); /** * build push message. @@ -3939,7 +4345,9 @@ declare namespace KiiCloud { * * @return builder instance. */ - setSendToDevelopment(flag: boolean): KiiPushMessageBuilder; + setSendToDevelopment( + flag: boolean + ): KiiPushMessageBuilder; /** * Indicate whether send this message to production environment. @@ -3949,7 +4357,9 @@ declare namespace KiiCloud { * * @return builder instance. */ - setSendToProduction(flag: boolean): KiiPushMessageBuilder; + setSendToProduction( + flag: boolean + ): KiiPushMessageBuilder; /** * Enable/ Disable message distribution via GCM. @@ -3959,7 +4369,9 @@ declare namespace KiiCloud { * * @return builder instance. */ - enableGcm(enable: boolean): KiiPushMessageBuilder; + enableGcm( + enable: boolean + ): KiiPushMessageBuilder; /** * Enable/ Disable message distribution via APNS. @@ -3969,7 +4381,9 @@ declare namespace KiiCloud { * * @return builder instance. */ - enableApns(enable: boolean): KiiPushMessageBuilder; + enableApns( + enable: boolean + ): KiiPushMessageBuilder; /** * Enable/ Disable message distribution via JPush. @@ -3979,7 +4393,9 @@ declare namespace KiiCloud { * * @return builder instance. */ - enableJpush(enable: boolean): KiiPushMessageBuilder; + enableJpush( + enable: boolean + ): KiiPushMessageBuilder; /** * Enable/ Disable message distribution via MQTT. @@ -3989,7 +4405,9 @@ declare namespace KiiCloud { * * @return builder instance. */ - enableMqtt(enable: boolean): KiiPushMessageBuilder; + enableMqtt( + enable: boolean + ): KiiPushMessageBuilder; /** * Set specific data for GCM subscribers. @@ -4002,7 +4420,9 @@ declare namespace KiiCloud { * * @return builder instance. */ - gcmData(data: { [key: string]: string }): KiiPushMessageBuilder; + gcmData( + data: { [key: string]: string } + ): KiiPushMessageBuilder; /** * Set collapse_key for GCM subscribers. @@ -4013,7 +4433,9 @@ declare namespace KiiCloud { * * @return builder instance. */ - gcmCollapseKey(collapseKey: string): KiiPushMessageBuilder; + gcmCollapseKey( + collapseKey: string + ): KiiPushMessageBuilder; /** * Set delay_while_idle for GCM subscribers. @@ -4024,7 +4446,9 @@ declare namespace KiiCloud { * * @return builder instance. */ - gcmDelayWhileIdle(delayWhileIdle: boolean): KiiPushMessageBuilder; + gcmDelayWhileIdle( + delayWhileIdle: boolean + ): KiiPushMessageBuilder; /** * Set time_to_live for GCM subscribers. @@ -4035,7 +4459,9 @@ declare namespace KiiCloud { * * @return builder instance. */ - gcmTimeToLive(timeToLive: number): KiiPushMessageBuilder; + gcmTimeToLive( + timeToLive: number + ): KiiPushMessageBuilder; /** * Set restricted_package_name for GCM subscribers. @@ -4046,7 +4472,9 @@ declare namespace KiiCloud { * * @return builder instance. */ - gcmRestrictedPackageName(restrictedPackageName: string): KiiPushMessageBuilder; + gcmRestrictedPackageName( + restrictedPackageName: string + ): KiiPushMessageBuilder; /** * Set specific data for APNS subscribers. @@ -4059,7 +4487,9 @@ declare namespace KiiCloud { * * @return builder instance. */ - apnsData(data: { [key: string]: string | number | boolean }): KiiPushMessageBuilder; + apnsData( + data: { [key: string]: string | number | boolean } + ): KiiPushMessageBuilder; /** * Set alert for APNS subscribers. @@ -4070,7 +4500,9 @@ declare namespace KiiCloud { * * @return builder instance. */ - apnsAlert(alert: string | APNSAlert): KiiPushMessageBuilder; + apnsAlert( + alert: string | APNSAlert + ): KiiPushMessageBuilder; /** * Set sound for APNS subscribers. @@ -4081,7 +4513,9 @@ declare namespace KiiCloud { * * @return builder instance. */ - apnsSound(sound: string): KiiPushMessageBuilder; + apnsSound( + sound: string + ): KiiPushMessageBuilder; /** * Set badge for APNS subscribers. @@ -4092,7 +4526,9 @@ declare namespace KiiCloud { * * @return builder instance. */ - apnsBadge(badge: number): KiiPushMessageBuilder; + apnsBadge( + badge: number + ): KiiPushMessageBuilder; /** * Set content-available for APNS subscribers. @@ -4104,7 +4540,9 @@ declare namespace KiiCloud { * * @return builder instance. */ - apnsContentAvailable(contentAvailable: number): KiiPushMessageBuilder; + apnsContentAvailable( + contentAvailable: number + ): KiiPushMessageBuilder; /** * Set category for APNS subscribers. @@ -4115,7 +4553,9 @@ declare namespace KiiCloud { * * @return builder instance. */ - apnsCategory(category: string): KiiPushMessageBuilder; + apnsCategory( + category: string + ): KiiPushMessageBuilder; /** * Set specific data for JPush subscribers. @@ -4128,7 +4568,9 @@ declare namespace KiiCloud { * * @return builder instance. */ - jpushData(data: { [name: string]: string | number | boolean }): KiiPushMessageBuilder; + jpushData( + data: { [name: string]: string | number | boolean } + ): KiiPushMessageBuilder; /** * Set specific data for MQTT subscribers. @@ -4141,7 +4583,9 @@ declare namespace KiiCloud { * * @return builder instance. */ - mqttData(data: { [key: string]: string }): KiiPushMessageBuilder; + mqttData( + data: { [key: string]: string } + ): KiiPushMessageBuilder; } /** @@ -4197,7 +4641,10 @@ declare namespace KiiCloud { * } * ); */ - subscribe(target: T, callbacks?: { success(subscription: KiiPushSubscription, topic: T): any; failure(error: Error): any; }): Promise<[KiiPushSubscription, T]>; + subscribe( + target: T, + callbacks?: { success(subscription: KiiPushSubscription, topic: T): any; failure(error: Error): any; } + ): Promise<[KiiPushSubscription, T]>; /** * Unsubscribe to bucket or topic. @@ -4248,7 +4695,10 @@ declare namespace KiiCloud { * } * ); */ - unsubscribe(target: T, callbacks?: { success(subscription: KiiPushSubscription, topic: T): any; failure(error: Error): any; }): Promise<[KiiPushSubscription, T]>; + unsubscribe( + target: T, + callbacks?: { success(subscription: KiiPushSubscription, topic: T): any; failure(error: Error): any; } + ): Promise<[KiiPushSubscription, T]>; /** * Check subscription of bucket, topic. @@ -4311,7 +4761,10 @@ declare namespace KiiCloud { * } * ); */ - isSubscribed(target: T, callbacks?: { success(subscription: KiiPushSubscription, topic: T, isSubscribed: boolean): any; failure(error: Error): any; }): Promise<[KiiPushSubscription, T, boolean]>; + isSubscribed( + target: T, + callbacks?: { success(subscription: KiiPushSubscription, topic: T, isSubscribed: boolean): any; failure(error: Error): any; } + ): Promise<[KiiPushSubscription, T, boolean]>; } /** @@ -4332,7 +4785,9 @@ declare namespace KiiCloud { * * @throws InvalidLimitException */ - setLimit(value: number): void; + setLimit( + value: number + ): void; /** * Create a KiiQuery object based on a KiiClause @@ -4341,7 +4796,9 @@ declare namespace KiiCloud { * * @param clause The KiiClause to be executed with the query */ - static queryWithClause(clause: KiiClause): KiiQuery; + static queryWithClause( + clause: KiiClause + ): KiiQuery; /** * Set the query to sort by a field in descending order @@ -4350,7 +4807,9 @@ declare namespace KiiCloud { * * @param field The key that should be used to sort */ - sortByDesc(field: string): void; + sortByDesc( + field: string + ): void; /** * Set the query to sort by a field in ascending order @@ -4359,7 +4818,9 @@ declare namespace KiiCloud { * * @param field The key that should be used to sort */ - sortByAsc(field: string): void; + sortByAsc( + field: string + ): void; } /** @@ -4432,7 +4893,12 @@ declare namespace KiiCloud { * } * ); */ - execute(argument: T, callbacks?: { success(entry: KiiServerCodeEntry, argument: T, execResult: KiiServerCodeExecResult): any; failure(entry: KiiServerCodeEntry, argument: T, execResult: KiiServerCodeExecResult, anErrorString: string): any; }): Promise<[KiiServerCodeEntry, T, KiiServerCodeExecResult]>; + execute( + argument: T, + callbacks?: { + success(entry: KiiServerCodeEntry, argument: T, execResult: KiiServerCodeExecResult): any; + failure(entry: KiiServerCodeEntry, argument: T, execResult: KiiServerCodeExecResult, anErrorString: string): any; } + ): Promise<[KiiServerCodeEntry, T, KiiServerCodeExecResult]>; /** * Get the entryName of this server code entry. @@ -4592,7 +5058,12 @@ declare namespace KiiCloud { * * @throws For details refer to the table above */ - static setupNetwork(networkName: KiiSocialNetworkName, apiKey: string, apiSecret: string, extras: any): void; + static setupNetwork( + networkName: KiiSocialNetworkName, + apiKey: string, + apiSecret: string, + extras: any + ): void; /** * Log a user into the social network provided @@ -4761,12 +5232,17 @@ declare namespace KiiCloud { * } * ); */ - static logIn(networkName: KiiSocialNetworkName, options: KiiSocialConnectOptions, callbacks?: { success(user: KiiUser, network: KiiSocialNetworkName): any; failure(user: KiiUser, network: KiiSocialNetworkName, anErrorString: string): any; }): Promise<[KiiUser, KiiSocialNetworkName]>; + static logIn( + networkName: KiiSocialNetworkName, + options: KiiSocialConnectOptions, + callbacks?: { success(user: KiiUser, network: KiiSocialNetworkName): any; failure(user: KiiUser, network: KiiSocialNetworkName, anErrorString: string): any; } + ): Promise<[KiiUser, KiiSocialNetworkName]>; /** * Link the currently logged in user with a social network * - * This will initiate the login process for the given network, which for SSO-enabled services like Facebook, will send the user to the Facebook site for authentication. There must be a currently authenticated KiiUser. Otherwise, you can use the logIn: method to create and log in a KiiUser using a network. The network must already be set up via setupNetwork
        + * This will initiate the login process for the given network, which for SSO-enabled services like Facebook, will send the user to the Facebook site for authentication. There must be a + * currently authenticated KiiUser. Otherwise, you can use the logIn: method to create and log in a KiiUser using a network. The network must already be set up via setupNetwork
        * If there is not logged-in user to link with, callbacks.failure or reject callback of promise will be called.
        * If the opitons is invalid, callbacks.failure or reject callback of promise will be called.
        * @@ -4927,7 +5403,11 @@ declare namespace KiiCloud { * } * ); */ - static linkCurrentUserWithNetwork(networkName: KiiSocialNetworkName, options: KiiSocialConnectOptions, callbacks?: { success(user: KiiUser, network: KiiSocialNetworkName): any; failure(user: KiiUser, network: KiiSocialNetworkName, anErrorString: string): any; }): Promise<[KiiUser, KiiSocialNetworkName]>; + static linkCurrentUserWithNetwork( + networkName: KiiSocialNetworkName, + options: KiiSocialConnectOptions, + callbacks?: { success(user: KiiUser, network: KiiSocialNetworkName): any; failure(user: KiiUser, network: KiiSocialNetworkName, anErrorString: string): any; } + ): Promise<[KiiUser, KiiSocialNetworkName]>; /** * Unlink the currently logged in user with a social network @@ -4978,7 +5458,10 @@ declare namespace KiiCloud { * } * ); */ - static unLinkCurrentUserFromNetwork(networkName: KiiSocialNetworkName, callbacks?: { success(user: KiiUser, network: KiiSocialNetworkName): any; failure(user: KiiUser, network: KiiSocialNetworkName, anErrorString: string): any; }): Promise<[KiiUser, KiiSocialNetworkName]>; + static unLinkCurrentUserFromNetwork( + networkName: KiiSocialNetworkName, + callbacks?: { success(user: KiiUser, network: KiiSocialNetworkName): any; failure(user: KiiUser, network: KiiSocialNetworkName, anErrorString: string): any; } + ): Promise<[KiiUser, KiiSocialNetworkName]>; /** * Retrieve the current user's access token from a social network @@ -4990,7 +5473,9 @@ declare namespace KiiCloud { * * @return The current access token, null if unavailable */ - static getAccessTokenForNetwork(networkName: KiiSocialNetworkName): string; + static getAccessTokenForNetwork( + networkName: KiiSocialNetworkName + ): string; /** * Retrieve the current user's access token expiration date from a social network @@ -5003,7 +5488,9 @@ declare namespace KiiCloud { * * @return The current access token expiration date, null if unavailable */ - static getAccessTokenExpirationForNetwork(networkName: KiiSocialNetworkName): string; + static getAccessTokenExpirationForNetwork( + networkName: KiiSocialNetworkName + ): string; /** * Retrieve the current user's access token object from a social network @@ -5038,7 +5525,9 @@ declare namespace KiiCloud { * * @return tokenObject The current access token object, null if unavailable. */ - static getAccessTokenObjectForNetwork(networkName: KiiSocialNetworkName): any; + static getAccessTokenObjectForNetwork( + networkName: KiiSocialNetworkName + ): any; } /** @@ -5176,7 +5665,10 @@ declare namespace KiiCloud { * } * ); */ - static register(fields: KiiThingFields, callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; }): Promise; + static register( + fields: KiiThingFields, + callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; } + ): Promise; /** * Retrieve the latest thing information from KiiCloud. @@ -5222,7 +5714,9 @@ declare namespace KiiCloud { * } * ); */ - refresh(callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; }): Promise; + refresh( + callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; } + ): Promise; /** * Update registered thing information in Kii Cloud @@ -5280,7 +5774,9 @@ declare namespace KiiCloud { * } * ); */ - update(callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; }): Promise; + update( + callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; } + ): Promise; /** * Delete registered thing in Kii Cloud. @@ -5330,7 +5826,9 @@ declare namespace KiiCloud { * } * ); */ - deleteThing(callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; }): Promise; + deleteThing( + callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; } + ): Promise; /** * Check if user/ group is owner of the thing. @@ -5396,7 +5894,10 @@ declare namespace KiiCloud { * } * ); */ - isOwner(owner: T, callbacks?: { success(thing: KiiThing, user: T, isOwner: boolean): any; failure(error: Error): any; }): Promise<[KiiThing, T, boolean]>; + isOwner( + owner: T, + callbacks?: { success(thing: KiiThing, user: T, isOwner: boolean): any; failure(error: Error): any; } + ): Promise<[KiiThing, T, boolean]>; /** * Register user/group as owner of this thing. @@ -5450,7 +5951,10 @@ declare namespace KiiCloud { * } * ); */ - registerOwner(owner: T, callbacks?: { success(thing: KiiThing, group: T): any; failure(error: Error): any; }): Promise<[KiiThing, T]>; + registerOwner( + owner: T, + callbacks?: { success(thing: KiiThing, group: T): any; failure(error: Error): any; } + ): Promise<[KiiThing, T]>; /** * Register user/group as owner of specified thing. @@ -5502,7 +6006,11 @@ declare namespace KiiCloud { * } * ); */ - static registerOwnerWithThingID(thingID: string, owner: T, callbacks?: { success(group: T): any; failure(error: Error): any; }): Promise; + static registerOwnerWithThingID( + thingID: string, + owner: T, + callbacks?: { success(group: T): any; failure(error: Error): any; } + ): Promise; /** * Register user/group as owner of specified thing. @@ -5553,7 +6061,11 @@ declare namespace KiiCloud { * } * ); */ - static registerOwnerWithVendorThingID(vendorThingID: string, owner: T, callbacks?: { success(group: T): any; failure(error: Error): any; }): Promise; + static registerOwnerWithVendorThingID( + vendorThingID: string, + owner: T, + callbacks?: { success(group: T): any; failure(error: Error): any; } + ): Promise; /** * Remove ownership of thing from specified user/group. @@ -5606,7 +6118,10 @@ declare namespace KiiCloud { * } * ); */ - unregisterOwner(owner: T, callbacks?: { success(thing: KiiThing, group: T): any; failure(error: Error): any; }): Promise<[KiiThing, T]>; + unregisterOwner( + owner: T, + callbacks?: { success(thing: KiiThing, group: T): any; failure(error: Error): any; } + ): Promise<[KiiThing, T]>; /** * Disable the thing. @@ -5657,7 +6172,9 @@ declare namespace KiiCloud { * } * ); */ - disable(callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; }): Promise; + disable( + callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; } + ): Promise; /** * Enable the thing. @@ -5708,7 +6225,9 @@ declare namespace KiiCloud { * } * ); */ - enable(callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; }): Promise; + enable( + callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; } + ): Promise; /** * Load thing with given vendor thing id. @@ -5752,7 +6271,10 @@ declare namespace KiiCloud { * } * ); */ - static loadWithVendorThingID(vendorThingID: string, callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; }): Promise; + static loadWithVendorThingID( + vendorThingID: string, + callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; } + ): Promise; /** * Load thing with thing id given by Kii Cloud. @@ -5798,7 +6320,10 @@ declare namespace KiiCloud { * } * ); */ - static loadWithThingID(thingID: string, callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; }): Promise; + static loadWithThingID( + thingID: string, + callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; } + ): Promise; /** * Instantiate bucket belongs to this thing. @@ -5807,7 +6332,9 @@ declare namespace KiiCloud { * * @return bucket instance. */ - bucketWithName(bucketName: string): KiiBucket; + bucketWithName( + bucketName: string + ): KiiBucket; /** * Creates a reference to a encrypted bucket for this thing @@ -5822,7 +6349,9 @@ declare namespace KiiCloud { * var thing = . . .; // a KiiThing * var bucket = thing.encryptedBucketWithName("myBucket"); */ - encryptedBucketWithName(bucketName: string): KiiBucket; + encryptedBucketWithName( + bucketName: string + ): KiiBucket; /** * Instantiate topic belongs to this thing. @@ -5831,13 +6360,16 @@ declare namespace KiiCloud { * * @return topic instance. */ - topicWithName(topicName: string): KiiTopic; + topicWithName( + topicName: string + ): KiiTopic; /** * Gets a list of topics in this thing scope * * @param callbacks An object with callback methods defined - * @param paginationKey You can specify the pagination key with the nextPaginationKey passed by callbacks.success. If empty string or no string object is provided, this API regards no paginationKey specified. + * @param paginationKey You can specify the pagination key with the nextPaginationKey passed by callbacks.success. If empty string or no string object is provided, this API regards no + * paginationKey specified. * * @return return promise object. *
          @@ -5898,7 +6430,10 @@ declare namespace KiiCloud { * } * ); */ - listTopics(callbacks?: { success(topicList: KiiTopic[], nextPaginationKey: string): any; failure(anErrorString: string): any; }, paginationKey?: string): Promise<[KiiTopic[], string]>; + listTopics( + callbacks?: { success(topicList: KiiTopic[], nextPaginationKey: string): any; failure(anErrorString: string): any; }, + paginationKey?: string + ): Promise<[KiiTopic[], string]>; /** * Instantiate push subscription for this thing. @@ -5929,7 +6464,9 @@ declare namespace KiiCloud { * } * }); */ - bucketWithName(bucketName: string): KiiBucket; + bucketWithName( + bucketName: string + ): KiiBucket; /** * Creates a reference to a encrypted bucket in App scope operated by thing. @@ -5949,7 +6486,9 @@ declare namespace KiiCloud { * } * }); */ - encryptedBucketWithName(bucketName: string): KiiBucket; + encryptedBucketWithName( + bucketName: string + ): KiiBucket; /** * Creates a reference to an object operated by thing using object`s URI. @@ -5960,7 +6499,9 @@ declare namespace KiiCloud { * * @throws If the URI is null, empty or does not have correct format. */ - objectWithURI(object: string): KiiObject; + objectWithURI( + object: string + ): KiiObject; /** * Creates a reference to a topic in App scope operated by thing. @@ -5970,13 +6511,16 @@ declare namespace KiiCloud { * * @return topic instance. */ - topicWithName(topicName: string): KiiTopic; + topicWithName( + topicName: string + ): KiiTopic; /** * Gets a list of topics in app scope * * @param callbacks An object with callback methods defined - * @param paginationKey You can specify the pagination key with the nextPaginationKey passed by callbacks.success. If empty string or no string object is provided, this API regards no paginationKey specified. + * @param paginationKey You can specify the pagination key with the nextPaginationKey passed by callbacks.success. If empty string or no string object is provided, this API regards no + * paginationKey specified. * * @return return promise object. *
            @@ -6037,7 +6581,10 @@ declare namespace KiiCloud { * } * ); */ - listTopics(callbacks?: { success(topicList: KiiTopic[], nextPaginationKey: string): any; failure(anErrorString: string): any; }, paginationKey?: string): Promise<[KiiTopic[], string]>; + listTopics( + callbacks?: { success(topicList: KiiTopic[], nextPaginationKey: string): any; failure(anErrorString: string): any; }, + paginationKey?: string + ): Promise<[KiiTopic[], string]>; /** * Gets authenticated KiiThing instance. @@ -6105,7 +6652,9 @@ declare namespace KiiCloud { * // Handle error. * }); */ - exists(callbacks?: { success(existed: boolean): any; failure(error: Error): any; }): Promise; + exists( + callbacks?: { success(existed: boolean): any; failure(error: Error): any; } + ): Promise; /** * Save this topic on Kii Cloud. @@ -6147,7 +6696,9 @@ declare namespace KiiCloud { * } * ); */ - save(callbacks?: { success(topic: KiiTopic): any; failure(error: Error): any; }): Promise; + save( + callbacks?: { success(topic: KiiTopic): any; failure(error: Error): any; } + ): Promise; /** * Send message to the topic. @@ -6202,7 +6753,10 @@ declare namespace KiiCloud { * } * ); */ - sendMessage(message: T, callbacks?: { success(topic: KiiTopic, message: T): any; failure(error: Error): any; }): Promise<[KiiTopic, T]>; + sendMessage( + message: T, + callbacks?: { success(topic: KiiTopic, message: T): any; failure(error: Error): any; } + ): Promise<[KiiTopic, T]>; /** * Delete the topic. @@ -6243,7 +6797,9 @@ declare namespace KiiCloud { * } * ); */ - deleteTopic(callbacks?: { success(topic: KiiTopic): any; failure(error: Error): any; }): Promise; + deleteTopic( + callbacks?: { success(topic: KiiTopic): any; failure(error: Error): any; } + ): Promise; /** * Get ACL object of this topic. @@ -6305,7 +6861,9 @@ declare namespace KiiCloud { * * @throws If the displayName is not a valid format */ - setDisplayName(value: string): void; + setDisplayName( + value: string + ): void; /** * Get whether or not the user is pseudo user. @@ -6368,7 +6926,9 @@ declare namespace KiiCloud { * * @throws If the country code is not a valid format */ - setCountry(value: string): void; + setCountry( + value: string + ): void; /** * Get the locale associated with this user @@ -6387,7 +6947,9 @@ declare namespace KiiCloud { * * @param value The locale to set. */ - setLocale(value: string): void; + setLocale( + value: string + ): void; /** * Get the server's creation date of this user @@ -6488,7 +7050,10 @@ declare namespace KiiCloud { * var user = . . .; // a KiiUser * user.set("score", 4298); */ - set(key: string, value: any): void; + set( + key: string, + value: any + ): void; /** * Gets the value associated with the given key @@ -6501,7 +7066,9 @@ declare namespace KiiCloud { * var user = . . .; // a KiiUser * var score = user.get("score"); */ - get(key: string): T; + get( + key: string + ): T; /** * The currently authenticated user @@ -6516,7 +7083,8 @@ declare namespace KiiCloud { /** * Create a user object to prepare for registration with credentials pre-filled * - *

            Creates an pre-filled user object for manipulation. This user will not be authenticated until one of the authentication methods are called on it. It can be treated as any other KiiObject before it is authenticated. + *

            Creates an pre-filled user object for manipulation. This user will not be authenticated until one of the authentication methods are called on it. It can be treated as any other + * KiiObject before it is authenticated. * * @param username The user's desired username. Must be between 3 and 64 characters, which can include alphanumeric characters as well as underscores '_', dashes '-' and periods '.' * @param password The user's password. Must be between 4-50 characters, made up of ascii characters excludes control characters. @@ -6529,12 +7097,16 @@ declare namespace KiiCloud { * @example * var user = KiiUser.userWithUsername("myusername", "mypassword"); */ - static userWithUsername(username: string, password: string): KiiUser; + static userWithUsername( + username: string, + password: string + ): KiiUser; /** * Create a user object to prepare for registration with credentials pre-filled * - *

            Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before it is registered. + *

            Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before + * it is registered. * * @param phoneNumber The user's phone number * @param password The user's password. Must be at least 4 characters, made up of alphanumeric and/or: @,#,$,%,^,& @@ -6547,12 +7119,16 @@ declare namespace KiiCloud { * @example * var user = KiiUser.userWithPhoneNumber("+874012345678", "mypassword"); */ - static userWithPhoneNumber(phoneNumber: string, password: string): KiiUser; + static userWithPhoneNumber( + phoneNumber: string, + password: string + ): KiiUser; /** * Create a user object to prepare for registration with credentials pre-filled * - *

            Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before it is registered. + *

            Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before + * it is registered. * * @param phoneNumber The user's phone number * @param username The user's desired username. Must be between 3 and 64 characters, which can include alphanumeric characters as well as underscores '_', dashes '-' and periods '.' @@ -6567,12 +7143,17 @@ declare namespace KiiCloud { * @example * var user = KiiUser.userWithPhoneNumberAndUsername("+874012345678", "johndoe", "mypassword"); */ - static userWithPhoneNumberAndUsername(phoneNumber: string, username: string, password: string): KiiUser; + static userWithPhoneNumberAndUsername( + phoneNumber: string, + username: string, + password: string + ): KiiUser; /** * Create a user object to prepare for registration with credentials pre-filled * - *

            Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before it is registered. + *

            Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before + * it is registered. * * @param emailAddress The user's email address * @param password The user's password. Must be at least 4 characters, made up of alphanumeric and/or: @,#,$,%,^,& @@ -6585,12 +7166,16 @@ declare namespace KiiCloud { * @example * var user = KiiUser.userWithEmailAddress("johndoe@example.com", "mypassword"); */ - static userWithEmailAddress(emailAddress: string, password: string): KiiUser; + static userWithEmailAddress( + emailAddress: string, + password: string + ): KiiUser; /** * Create a user object to prepare for registration with credentials pre-filled * - *

            Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before it is registered. + *

            Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before + * it is registered. * * @param emailAddress The user's email address * @param username The user's desired username. Must be between 3 and 64 characters, which can include alphanumeric characters as well as underscores '_', dashes '-' and periods '.' @@ -6605,12 +7190,17 @@ declare namespace KiiCloud { * @example * var user = KiiUser.userWithEmailAddressAndUsername("johndoe@example.com", "johndoe", "mypassword"); */ - static userWithEmailAddressAndUsername(emailAddress: string, username: string, password: string): KiiUser; + static userWithEmailAddressAndUsername( + emailAddress: string, + username: string, + password: string + ): KiiUser; /** * Create a user object to prepare for registration with credentials pre-filled * - *

            Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before it is registered. + *

            Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before + * it is registered. * * @param emailAddress The user's email address * @param phoneNumber The user's phone number @@ -6625,12 +7215,17 @@ declare namespace KiiCloud { * @example * var user = KiiUser.userWithEmailAddressAndPhoneNumber("johndoe@example.com", "+874012345678", "mypassword"); */ - static userWithEmailAddressAndPhoneNumber(emailAddress: string, phoneNumber: string, password: string): KiiUser; + static userWithEmailAddressAndPhoneNumber( + emailAddress: string, + phoneNumber: string, + password: string + ): KiiUser; /** * Create a user object to prepare for registration with credentials pre-filled * - *

            Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before it is registered. + *

            Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before + * it is registered. * * @param emailAddress The user's email address * @param phoneNumber The user's phone number @@ -6647,7 +7242,12 @@ declare namespace KiiCloud { * @example * var user = KiiUser.userWithCredentials("johndoe@example.com", "+874012345678", "johndoe", "mypassword"); */ - static userWithCredentials(emailAddress: string, phoneNumber: string, username: string, password: string): KiiUser; + static userWithCredentials( + emailAddress: string, + phoneNumber: string, + username: string, + password: string + ): KiiUser; /** * Instantiate KiiUser that refers to existing user which has specified ID. @@ -6665,7 +7265,9 @@ declare namespace KiiCloud { * @example * var user = new KiiUser.userWithID("__USER_ID__"); */ - static userWithID(userID: string): KiiUser; + static userWithID( + userID: string + ): KiiUser; /** * Generate a new KiiUser based on a given URI @@ -6679,7 +7281,9 @@ declare namespace KiiCloud { * @example * var user = new KiiUser.userWithURI("kiicloud://myuri"); */ - static userWithURI(uri: string): KiiUser; + static userWithURI( + uri: string + ): KiiUser; /** * Creates a reference to a bucket for this user @@ -6694,7 +7298,9 @@ declare namespace KiiCloud { * var user = . . .; // a KiiUser * var bucket = user.bucketWithName("myBucket"); */ - bucketWithName(bucketName: string): KiiBucket; + bucketWithName( + bucketName: string + ): KiiBucket; /** * Creates a reference to a encrypted bucket for this user @@ -6709,7 +7315,9 @@ declare namespace KiiCloud { * var user = . . .; // a KiiUser * var bucket = user.encryptedBucketWithName("myBucket"); */ - encryptedBucketWithName(bucketName: string): KiiBucket; + encryptedBucketWithName( + bucketName: string + ): KiiBucket; /** * Authenticates a user with the server. @@ -6756,7 +7364,11 @@ declare namespace KiiCloud { * } * ); */ - static authenticate(userIdentifier: string, password: string, callbacks?: { success(theAuthenticatedUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; + static authenticate( + userIdentifier: string, + password: string, + callbacks?: { success(theAuthenticatedUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; } + ): Promise; /** * Asynchronously authenticates a user with the server using specified access token. @@ -6822,7 +7434,11 @@ declare namespace KiiCloud { * } * ); */ - static authenticateWithToken(accessToken: string, callbacks?: { success(theAuthenticatedUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }, expiresAt?: Date): Promise; + static authenticateWithToken( + accessToken: string, + callbacks?: { success(theAuthenticatedUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }, + expiresAt?: Date + ): Promise; /** * Registers a user with the server @@ -6866,7 +7482,9 @@ declare namespace KiiCloud { * } * ); */ - register(callbacks?: { success(theAuthenticatedUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; + register( + callbacks?: { success(theAuthenticatedUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; } + ): Promise; /** * Registers a user as pseudo user with the server @@ -6909,7 +7527,10 @@ declare namespace KiiCloud { * } * ); */ - static registerAsPseudoUser(callbacks?: { success(theAuthenticatedUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }, userFields?: any): Promise; + static registerAsPseudoUser( + callbacks?: { success(theAuthenticatedUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }, + userFields?: any + ): Promise; /** * Sets credentials data and custom fields to pseudo user. @@ -6975,7 +7596,13 @@ declare namespace KiiCloud { * } * ); */ - putIdentity(identityData: identityData, password: string, callbacks?: { success(user: KiiUser): any; failure(user: KiiUser, errorString: string): any; }, userFields?: any, removeFields?: string[]): Promise; + putIdentity( + identityData: identityData, + password: string, + callbacks?: { success(user: KiiUser): any; failure(user: KiiUser, errorString: string): any; }, + userFields?: any, + removeFields?: string[] + ): Promise; /** * Update user attributes. @@ -7037,7 +7664,12 @@ declare namespace KiiCloud { * } * ); */ - update(identityData: identityData, callbacks?: { success(user: KiiUser): any; failure(user: KiiUser, errorString: string): any; }, userFields?: any, removeFields?: string[]): Promise; + update( + identityData: identityData, + callbacks?: { success(user: KiiUser): any; failure(user: KiiUser, errorString: string): any; }, + userFields?: any, + removeFields?: string[] + ): Promise; /** * Update a user's password on the server @@ -7083,12 +7715,17 @@ declare namespace KiiCloud { * } * ); */ - updatePassword(fromPassword: string, toPassword: string, callbacks?: { success(theUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; + updatePassword( + fromPassword: string, + toPassword: string, + callbacks?: { success(theUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; } + ): Promise; /** * Reset a user's password on the server * - *

            Reset a user's password on the server. The user is determined by the specified userIdentifier - which is an email address that has already been associated with an account. Reset instructions will be sent to that identifier. + *

            Reset a user's password on the server. The user is determined by the specified userIdentifier - which is an email address that has already been associated with an account. Reset + * instructions will be sent to that identifier. *

            Please Note: This will reset the user's access token, so if they are currently logged in - their session will no longer be valid. * * @param userIdentifier The user's email address @@ -7126,7 +7763,10 @@ declare namespace KiiCloud { * } * ); */ - static resetPassword(userIdentifier: string, callbacks?: { success(): any; failure(anErrorString: string): any; }): Promise; + static resetPassword( + userIdentifier: string, + callbacks?: { success(): any; failure(anErrorString: string): any; } + ): Promise; /** * Reset the password of user
            @@ -7136,7 +7776,12 @@ declare namespace KiiCloud { * @param userIdentifier should be valid email address, * global phone number or user identifier obtained by {@link #getID}. * @param notificationMethod specify the destination of message include link - * of resetting password. must be "EMAIL" or "SMS". + * of resetting password. must one of "EMAIL", "SMS" or "SMS_PIN". + * - "EMAIL": Send email include link URL to reset password or password. + * (Contents are depends on 'Password Reset Flow' setting in app's + * Security settings.) + * - "SMS" : Send SMS include link URL to reset password. + * - "SMS_PIN" : Send SMS include PIN Code for reset password. * different type of identifier and destination can be used * as long as user have verified email, phone. * (ex. User registers both email and phone. Identifier is email and @@ -7174,7 +7819,65 @@ declare namespace KiiCloud { * } * ); */ - static resetPasswordWithNotificationMethod(userIdentifier: string, notificationMethod: string, callbacks?: { success(): any; failure(errString: string): any; }): Promise; + static resetPasswordWithNotificationMethod( + userIdentifier: string, + notificationMethod: string, + callbacks?: { success(): any; failure(errString: string): any; } + ): Promise; + + /** + * Reset password with the PIN code in receipt SMS + * After {@link KiiUser.resetPasswordWithNotificationMethod} is called with + * "SMS_PIN", SMS includes the PIN code will be sent to the user's phone. + * User can request the new password for login with the PIN code. + * Need to call method for authentication after the new password is determined. + * + * @param userIdentifier should be valid email address, + * global phone number or user identifier obtained by {@link #getID}. + * @param pinCode Received PIN code. + * @param newPassword New password for login. + * If the 'Password Reset Flow' in app's security setting is set to + * 'Generate password', it would be ignored and null can be passed. + * In this case, new password is generated on Kii Cloud and sent to user's + * phone. Otherwise valid password is required. + * @param callbacks object includes callback functions. + * + * @return return promise object. + *
              + *
            • fulfill callback function: function(). No parameter used.
            • + *
            • reject callback function: function(error). error is an Error instance. + *
                + *
              • error.message
              • + *
              + *
            • + *
            + * + * @example + * // Example using callback + * KiiUser.completeResetPassword("john.doe@kii.com", "new-password", "223789", + * { + * success: function() { + * // Succeeded. + * }, + * failure: function(error) { + * // Handle error here. + * } + * }); + * + * // Example using Promise + * KiiUser.completeResetPassword( + * "john.doe@kii.com", "new-password", "223789").then(function() { + * // Succeeded. + * }).catch(function(error) { + * // Handle error here. + * }); + */ + static completeResetPassword( + userIdentifier: string, + pinCode: string, + newPassword?: string, + callbacks?: { success(): any; failure(error: Error): any; } + ): Promise; /** * Verify the current user's phone number @@ -7230,7 +7933,10 @@ declare namespace KiiCloud { * } * ); */ - verifyPhoneNumber(verificationCode: string, callbacks?: { success(theUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; + verifyPhoneNumber( + verificationCode: string, + callbacks?: { success(theUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; } + ): Promise; /** * Resend the email verification code to the user @@ -7274,7 +7980,9 @@ declare namespace KiiCloud { * } * ); */ - resendEmailVerification(callbacks?: { success(theUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; + resendEmailVerification( + callbacks?: { success(theUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; } + ): Promise; /** * Resend the SMS verification code to the user @@ -7318,7 +8026,9 @@ declare namespace KiiCloud { * } * ); */ - resendPhoneNumberVerification(callbacks?: { success(theUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; + resendPhoneNumberVerification( + callbacks?: { success(theUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; } + ): Promise; /** * Retrieve a list of groups which the user is a member of @@ -7373,7 +8083,9 @@ declare namespace KiiCloud { * } * ); */ - memberOfGroups(callbacks?: { success(theUser: KiiUser, groupList: KiiGroup[]): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise<[KiiUser, KiiGroup[]]>; + memberOfGroups( + callbacks?: { success(theUser: KiiUser, groupList: KiiGroup[]): any; failure(theUser: KiiUser, anErrorString: string): any; } + ): Promise<[KiiUser, KiiGroup[]]>; /** * Retrieve the groups owned by this user. Group in the groupList @@ -7430,7 +8142,9 @@ declare namespace KiiCloud { * } * ); */ - ownerOfGroups(callbacks?: { success(theUser: KiiUser, groupList: KiiGroup[]): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise<[KiiUser, KiiGroup[]]>; + ownerOfGroups( + callbacks?: { success(theUser: KiiUser, groupList: KiiGroup[]): any; failure(theUser: KiiUser, anErrorString: string): any; } + ): Promise<[KiiUser, KiiGroup[]]>; /** * Change phone number of logged in user. @@ -7478,7 +8192,10 @@ declare namespace KiiCloud { * } * ); */ - changePhone(newPhoneNumber: string, callbacks?: { success(theUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; + changePhone( + newPhoneNumber: string, + callbacks?: { success(theUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; } + ): Promise; /** * Change email of logged in user. @@ -7526,7 +8243,10 @@ declare namespace KiiCloud { * } * ); */ - changeEmail(newEmail: string, callbacks?: { success(theUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; + changeEmail( + newEmail: string, + callbacks?: { success(theUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; } + ): Promise; /** * Saves the latest user values to the server @@ -7570,7 +8290,9 @@ declare namespace KiiCloud { * } * ); */ - save(callbacks?: { success(theSavedUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; + save( + callbacks?: { success(theSavedUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; } + ): Promise; /** * Updates the local user's data with the user data on the server @@ -7614,7 +8336,9 @@ declare namespace KiiCloud { * } * ); */ - refresh(callbacks?: { success(theRefreshedUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; + refresh( + callbacks?: { success(theRefreshedUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; } + ): Promise; /** * Delete the user from the server @@ -7656,7 +8380,9 @@ declare namespace KiiCloud { * } * ); */ - delete(callbacks?: { success(theDeletedUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; + delete( + callbacks?: { success(theDeletedUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; } + ): Promise; /** * Logs the currently logged-in user out of the KiiSDK @@ -7723,7 +8449,10 @@ declare namespace KiiCloud { * } * ); */ - static findUserByEmail(email: string, callbacks?: { success(theMatchedUser: KiiUser): any; failure(anErrorString: string): any; }): Promise; + static findUserByEmail( + email: string, + callbacks?: { success(theMatchedUser: KiiUser): any; failure(anErrorString: string): any; } + ): Promise; /** * Find registered KiiUser with the phone.
            @@ -7772,7 +8501,10 @@ declare namespace KiiCloud { * } * ); */ - static findUserByPhone(phone: string, callbacks?: { success(theMatchedUser: KiiUser): any; failure(anErrorString: string): any; }): Promise; + static findUserByPhone( + phone: string, + callbacks?: { success(theMatchedUser: KiiUser): any; failure(anErrorString: string): any; } + ): Promise; /** * Find registered KiiUser with the user name.
            @@ -7820,7 +8552,10 @@ declare namespace KiiCloud { * } * ); */ - static findUserByUsername(username: string, callbacks?: { success(theMatchedUser: KiiUser): any; failure(anErrorString: string): any; }): Promise; + static findUserByUsername( + username: string, + callbacks?: { success(theMatchedUser: KiiUser): any; failure(anErrorString: string): any; } + ): Promise; /** * Instantiate topic belongs to this user. @@ -7829,13 +8564,16 @@ declare namespace KiiCloud { * * @return topic instance. */ - topicWithName(topicName: string): KiiTopic; + topicWithName( + topicName: string + ): KiiTopic; /** * Gets a list of topics in this user scope * * @param callbacks An object with callback methods defined - * @param paginationKey You can specify the pagination key with the nextPaginationKey passed by callbacks.success. If empty string or no string object is provided, this API regards no paginationKey specified. + * @param paginationKey You can specify the pagination key with the nextPaginationKey passed by callbacks.success. If empty string or no string object is provided, this API regards no + * paginationKey specified. * * @return return promise object. *
              @@ -7896,7 +8634,10 @@ declare namespace KiiCloud { * } * ); */ - listTopics(callbacks?: { success(topicList: KiiTopic[], nextPaginationKey: string): any; failure(anErrorString: string): any; }, paginationKey?: string): Promise<[KiiTopic[], string]>; + listTopics( + callbacks?: { success(topicList: KiiTopic[], nextPaginationKey: string): any; failure(anErrorString: string): any; }, + paginationKey?: string + ): Promise<[KiiTopic[], string]>; /** * Instantiate push subscription for this user. @@ -7943,7 +8684,10 @@ declare namespace KiiCloud { * @throws If the password is not in the * proper format */ - static builderWithIdentifier(identifier: string, password: string): KiiUserBuilder; + static builderWithIdentifier( + identifier: string, + password: string + ): KiiUserBuilder; /** * Create KiiUser builder with email address @@ -7960,7 +8704,10 @@ declare namespace KiiCloud { * @throws If the password is not in the * proper format */ - static builderWithEmailAddress(emailAddress: string, password: string): KiiUserBuilder; + static builderWithEmailAddress( + emailAddress: string, + password: string + ): KiiUserBuilder; /** * Create KiiUser builder with global phone number @@ -7974,7 +8721,10 @@ declare namespace KiiCloud { * * @throws If the phone number is not in the proper format */ - static builderWithGlobalPhoneNumber(phoneNumber: string, password: string): KiiUserBuilder; + static builderWithGlobalPhoneNumber( + phoneNumber: string, + password: string + ): KiiUserBuilder; /** * Create KiiUser builder with local phone number @@ -7993,7 +8743,11 @@ declare namespace KiiCloud { * @throws If the password is not in the * proper format */ - static builderWithLocalPhoneNumber(phoneNumber: string, country: string, password: string): KiiUserBuilder; + static builderWithLocalPhoneNumber( + phoneNumber: string, + country: string, + password: string + ): KiiUserBuilder; /** * Create KiiUser builder with user name @@ -8010,7 +8764,10 @@ declare namespace KiiCloud { * @throws If the password is not in the * proper format */ - static builderWithUsername(username: string, password: string): KiiUserBuilder; + static builderWithUsername( + username: string, + password: string + ): KiiUserBuilder; /** * Set user name. @@ -8025,7 +8782,9 @@ declare namespace KiiCloud { * @throws If the username is not in the * proper format */ - setUsername(username: string): KiiUserBuilder; + setUsername( + username: string + ): KiiUserBuilder; /** * Set email address. @@ -8040,7 +8799,9 @@ declare namespace KiiCloud { * @throws If the email address is not in the * proper format */ - setEmailAddress(emailAddress: string): KiiUserBuilder; + setEmailAddress( + emailAddress: string + ): KiiUserBuilder; /** * Set global phone number. @@ -8055,7 +8816,9 @@ declare namespace KiiCloud { * @throws If the phone number is not * in the proper format */ - setGlobalPhoneNumber(phoneNumber: string): KiiUserBuilder; + setGlobalPhoneNumber( + phoneNumber: string + ): KiiUserBuilder; /** * Set local phone number. @@ -8072,7 +8835,10 @@ declare namespace KiiCloud { * in the proper format * @throws If the country code is not a valid format */ - setLocalPhoneNumber(phoneNumber: string, country: string): KiiUserBuilder; + setLocalPhoneNumber( + phoneNumber: string, + country: string + ): KiiUserBuilder; /** * Build KiiUser object. @@ -8098,6 +8864,7 @@ import KiiAnyAuthenticatedUser = KiiCloud.KiiAnyAuthenticatedUser; import KiiAppAdminContext = KiiCloud.KiiAppAdminContext; import KiiBucket = KiiCloud.KiiBucket; import KiiClause = KiiCloud.KiiClause; +import KiiErrorParser = KiiCloud.KiiErrorParser; import KiiGeoPoint = KiiCloud.KiiGeoPoint; import KiiGroup = KiiCloud.KiiGroup; import KiiObject = KiiCloud.KiiObject; diff --git a/kii-cloud-sdk/kii-cloud-sdk-tests.ts b/kii-cloud-sdk/kii-cloud-sdk-tests.ts index 97f4d40512..40abd1e8d4 100644 --- a/kii-cloud-sdk/kii-cloud-sdk-tests.ts +++ b/kii-cloud-sdk/kii-cloud-sdk-tests.ts @@ -18,11 +18,11 @@ function main() { }); user.register() - .then(function (user: KiiUser) { + .then((user: KiiUser) => { }); user.pushInstallation().getMqttEndpoint("") - .then(function (endpoint: KiiCloud.KiiMqttEndpoint) { + .then((endpoint: KiiCloud.KiiMqttEndpoint) => { endpoint.installationID; }); @@ -41,16 +41,16 @@ function main() { var query = KiiQuery.queryWithClause(clause3); bucket.executeQuery(query, { - success: function (query: KiiQuery, - results: KiiObject[], - nextQuery: KiiQuery) { + success: (query: KiiQuery, + results: KiiObject[], + nextQuery: KiiQuery) => { }, - failure: function (bucket: KiiBucket, message: string) { + failure: (bucket: KiiBucket, message: string) => { } }); bucket.executeQuery(query) - .then(function (params: [KiiQuery, KiiObject[], KiiQuery]) { + .then((params: [KiiQuery, KiiObject[], KiiQuery]) => { var [query, results, nextQuery] = params; }); @@ -61,39 +61,43 @@ function main() { object.save(); KiiGroup.registerGroupWithID("Group ID", "Group Name", [user], { - success: function(theSavedGroup: KiiGroup) { + success: (theSavedGroup: KiiGroup) => { theSavedGroup.saveWithOwner("user ID"); }, - failure: function(theGroup: KiiGroup, - anErrorString: String, - addMembersArray: KiiUser[], - removeMembersArray: KiiUser[]) { + failure: (theGroup: KiiGroup, + anErrorString: string, + addMembersArray: KiiUser[], + removeMembersArray: KiiUser[]) => { } }); Kii.authenticateAsThing("thing id", "password", { - success: function (thingAuthContext: KiiThingContext) { + success: (thingAuthContext: KiiThingContext) => { thingAuthContext.bucketWithName(""); }, - failure: function (error) { + failure: (error) => { } }) - .then(function (thingAuthContext: KiiThingContext) { + .then((thingAuthContext: KiiThingContext) => { }); Kii.authenticateAsThingWithToken("thing id", "token", { - success: function (thingAuthContext: KiiThingContext) { + success: (thingAuthContext: KiiThingContext) => { thingAuthContext.bucketWithName(""); }, - failure: function (error) { + failure: (error) => { } }) - .then(function (thingAuthContext: KiiThingContext) { + .then((thingAuthContext: KiiThingContext) => { }); KiiThing.loadWithVendorThingID("thing ID") - .then(function (thing) { + .then((thing) => { var isOnline: boolean = thing.isOnline(); var onlineStatusModifiedAt: Date = thing.getOnlineStatusModifiedAt(); }); + + var error = KiiErrorParser.parse(""); + + error.code.toLowerCase(); } diff --git a/kii-cloud-sdk/tslint.json b/kii-cloud-sdk/tslint.json new file mode 100644 index 0000000000..ad51895c20 --- /dev/null +++ b/kii-cloud-sdk/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "dt-header": false + } +} diff --git a/klaw-sync/index.d.ts b/klaw-sync/index.d.ts new file mode 100644 index 0000000000..d344879e1a --- /dev/null +++ b/klaw-sync/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for klaw-sync 1.1 +// Project: https://github.com/manidlou/node-klaw-sync +// Definitions by: Brendan Forster +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as fs from "fs" + +interface Item { + path: string + stats: fs.Stats +} + +interface Options { + /** + * any paths or `micromatch` patterns to ignore. + * + * For more information on micromatch patterns: https://github.com/jonschlinkert/micromatch#features + */ + ignore?: string | string[] + /** + * True to only return files (ignore directories). + * + * Defaults to false if not specified. + */ + nodir?: boolean + /** + * True to only return directories (ignore files). + * + * Defaults to false if not specified. + */ + nofile?: boolean +} + +export function klawSync(root: string, options?: Options): ReadonlyArray + diff --git a/klaw-sync/klaw-sync-tests.ts b/klaw-sync/klaw-sync-tests.ts new file mode 100644 index 0000000000..5c2b806108 --- /dev/null +++ b/klaw-sync/klaw-sync-tests.ts @@ -0,0 +1,20 @@ +import { klawSync, Item } from "klaw-sync" +import * as path from "path" + +const outputMessage = (result: Item) => { + console.log(`file: ${result.path} has size '${result.stats.size}'`) +} + +klawSync('/some/dir').forEach(outputMessage) + +const defaultOptions = { } + +klawSync('/some/dir', defaultOptions).forEach(outputMessage) + +const options = { + ignore: [ '.exe' ], + nodir: true, + nofile: false +} + +klawSync('/some/dir', options).forEach(outputMessage) diff --git a/klaw-sync/tsconfig.json b/klaw-sync/tsconfig.json new file mode 100644 index 0000000000..ca120a7ba3 --- /dev/null +++ b/klaw-sync/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "klaw-sync-tests.ts" + ] +} diff --git a/klaw-sync/tslint.json b/klaw-sync/tslint.json new file mode 100644 index 0000000000..7cf0e1c353 --- /dev/null +++ b/klaw-sync/tslint.json @@ -0,0 +1,9 @@ +{ + "extends": "../tslint.json", + "rules": { + "semicolon": [ + true, + "never" + ] + } +} diff --git a/klaw/klaw-tests.ts b/klaw/klaw-tests.ts index 312af220ff..acd8b2fcbf 100644 --- a/klaw/klaw-tests.ts +++ b/klaw/klaw-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as klaw from "klaw"; const path = require('path'); diff --git a/knex/index.d.ts b/knex/index.d.ts index 3e7dc595f4..15ff365756 100644 --- a/knex/index.d.ts +++ b/knex/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Knex.js // Project: https://github.com/tgriesser/knex -// Definitions by: Qubo +// Definitions by: Qubo , Baronfel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -25,7 +25,7 @@ interface Knex extends Knex.QueryInterface { transaction: (transactionScope: ((trx: Knex.Transaction) => void)) => Promise; destroy(callback: Function): void; destroy(): Promise; - + batchInsert(tableName : TableName, data: any[], chunkSize : number) : Knex.QueryBuilder; schema: Knex.SchemaBuilder; client: any; @@ -165,7 +165,7 @@ declare namespace Knex { interface Join { (raw: Raw): QueryBuilder; - (tableName: string, columns: { [key: string]: string | Raw }): QueryBuilder; + (tableName: string, columns: { [key: string]: string | number | Raw }): QueryBuilder; (tableName: string, callback: Function): QueryBuilder; (tableName: TableName, raw: Raw): QueryBuilder; (tableName: TableName, column1: string, column2: string): QueryBuilder; @@ -472,6 +472,7 @@ declare namespace Knex { domain?: string; instanceName?: string; debug?: boolean; + requestTimeout?: number; } // Config object for mariasql: https://github.com/mscdex/node-mariasql#client-methods diff --git a/knex/knex-tests.ts b/knex/knex-tests.ts index 420aafd724..6e49702faf 100644 --- a/knex/knex-tests.ts +++ b/knex/knex-tests.ts @@ -188,6 +188,10 @@ knex('users') .join('contacts', 'users.id', '=', 'contacts.user_id') .select('users.id', 'contacts.phone'); +knex('users') + .join('contacts', { 'users.id': 12355 }) + .select('users.id', 'contacts.phone'); + knex('users') .join('contacts', 'users.id', 'contacts.user_id') .select('users.id', 'contacts.phone'); @@ -281,6 +285,8 @@ knex('books') .returning('id') .insert([{title: 'Great Gatsby'}, {title: 'Fahrenheit 451'}]); +knex.batchInsert('books', [{title:'Great Gatsby'}, {title: 'Fahrenheit 451'}], 200); + knex('books').where('published_date', '<', 2000).update({status: 'archived'}); knex('books').where('published_date', '<', 2000).update({status: 'archived'}, 'id'); knex('books').where('published_date', '<', 2000).update({status: 'archived'}, ['id', 'title']); diff --git a/knockout-amd-helpers/knockout-amd-helpers-tests.ts b/knockout-amd-helpers/knockout-amd-helpers-tests.ts index d2773dee12..5b9c2983b5 100644 --- a/knockout-amd-helpers/knockout-amd-helpers-tests.ts +++ b/knockout-amd-helpers/knockout-amd-helpers-tests.ts @@ -1,8 +1,5 @@ // Tests for knockout.projections.d.ts -/// - - //The baseDir is used in building the path to use in the require statement. If your modules live in the modules directory, then you can specify it globally here. ko.bindingHandlers.module.baseDir = "blub"; diff --git a/knockout-transformations/knockout-transformations-tests.ts b/knockout-transformations/knockout-transformations-tests.ts index c8e93fc20e..6725f4f209 100644 --- a/knockout-transformations/knockout-transformations-tests.ts +++ b/knockout-transformations/knockout-transformations-tests.ts @@ -1,6 +1,3 @@ -/// - - // Test map var sourceItems: KnockoutObservableArray = ko.observableArray([1, 2, 3, 4, 5]); var squares: KnockoutObservableArray = sourceItems.map(function (x) { return x * x; }); diff --git a/knockout.kogrid/knockout.kogrid-tests.ts b/knockout.kogrid/knockout.kogrid-tests.ts index 8abe83d36d..ba36e78e9f 100644 --- a/knockout.kogrid/knockout.kogrid-tests.ts +++ b/knockout.kogrid/knockout.kogrid-tests.ts @@ -1,33 +1,27 @@ -/// +export interface IGridItem { + name: string; +} +export class Tests { + public items: KnockoutObservableArray; + public selectedItems: KnockoutObservableArray; + public gridOptionsAlarms: kg.GridOptions; -namespace KoGridTests -{ - export interface IGridItem { - name: string; - } + constructor() { + this.items = ko.observableArray(); + this.selectedItems = ko.observableArray(); + this.gridOptionsAlarms = this.createDefaultGridOptions(this.items, this.selectedItems); + } - export class Tests { - public items: KnockoutObservableArray; - public selectedItems: KnockoutObservableArray; - public gridOptionsAlarms: kg.GridOptions; - - constructor() { - this.items = ko.observableArray(); - this.selectedItems = ko.observableArray(); - this.gridOptionsAlarms = this.createDefaultGridOptions(this.items, this.selectedItems); - } - - public createDefaultGridOptions(dataArray: KnockoutObservableArray, selectedItems: KnockoutObservableArray): kg.GridOptions { - return { - data: dataArray, - displaySelectionCheckbox: false, - footerVisible: false, - multiSelect: false, - showColumnMenu: false, - plugins: null, - selectedItems: selectedItems - }; - } - } + public createDefaultGridOptions(dataArray: KnockoutObservableArray, selectedItems: KnockoutObservableArray): kg.GridOptions { + return { + data: dataArray, + displaySelectionCheckbox: false, + footerVisible: false, + multiSelect: false, + showColumnMenu: false, + plugins: null, + selectedItems: selectedItems + }; + } } diff --git a/knockout.mapping/knockout.mapping-tests.ts b/knockout.mapping/knockout.mapping-tests.ts index 7b1a9aca8d..6262f36275 100644 --- a/knockout.mapping/knockout.mapping-tests.ts +++ b/knockout.mapping/knockout.mapping-tests.ts @@ -1,6 +1,3 @@ - -/// - var inputJSON = '{ name: "foo" }'; var inputData = { name: 'foo' }; var inputModel = { name: 'bar' }; diff --git a/knockout.projections/knockout.projections-tests.ts b/knockout.projections/knockout.projections-tests.ts index c0899c81ee..bc8a505484 100644 --- a/knockout.projections/knockout.projections-tests.ts +++ b/knockout.projections/knockout.projections-tests.ts @@ -1,8 +1,3 @@ -// Tests for knockout.projections.d.ts - -/// - - // Test map var sourceItems = ko.observableArray([1, 2, 3, 4, 5]); var squares = sourceItems.map(function (x) { return x * x; }); diff --git a/knockout.punches/knockout.punches-tests.ts b/knockout.punches/knockout.punches-tests.ts index 1de89ca570..2eccd25d37 100644 --- a/knockout.punches/knockout.punches-tests.ts +++ b/knockout.punches/knockout.punches-tests.ts @@ -1,6 +1,3 @@ -/// - - function test_enable() { ko.punches.enableAll(); } diff --git a/knockout/index.d.ts b/knockout/index.d.ts index a28d06a220..570d0ee830 100644 --- a/knockout/index.d.ts +++ b/knockout/index.d.ts @@ -658,7 +658,7 @@ declare namespace KnockoutComponentTypes { } interface Loader { - getConfig? (componentName: string, callback: (result: ComponentConfig) => void): void; + getConfig? (componentName: string, callback: (result: ComponentConfig | null) => void): void; loadComponent? (componentName: string, config: ComponentConfig, callback: (result: Definition) => void): void; loadTemplate? (componentName: string, templateConfig: any, callback: (result: Node[]) => void): void; loadViewModel? (componentName: string, viewModelConfig: any, callback: (result: any) => void): void; diff --git a/knockout/test/templatingBehaviors.ts b/knockout/test/templatingBehaviors.ts index 7052b716f5..b69cb080f8 100644 --- a/knockout/test/templatingBehaviors.ts +++ b/knockout/test/templatingBehaviors.ts @@ -1,12 +1,31 @@ -/// /// +// Jasmine definitions +declare function describe(desc: string, f: () => void): void; +declare function it(desc: string, f: () => void): void; +declare function beforeEach(action: (done: DoneFn) => void, timeout?: number): void; +declare function expect(spy: Function): jasmine.Matchers; +declare function expect(actual: any): jasmine.Matchers; + +interface DoneFn extends Function { + (): void; + + /** fails the spec and indicates that it has completed. If the message is an Error, Error.message is used */ + fail: (message?: Error|string) => void; +} + declare namespace jasmine { interface Matchers { + toEqual(expected: any, expectationFailOutput?: any): boolean; + toBeDefined(expectationFailOutput?: any): boolean; + toBeNull(expectationFailOutput?: any): boolean; toContainHtml(expected: string): boolean; toContainText(expected: string): boolean; + not: Matchers; } } +//End Jasmine definitions + var dummyTemplateEngine = function (templates?) { var inMemoryTemplates = templates || {}; diff --git a/knockstrap/knockstrap-tests.ts b/knockstrap/knockstrap-tests.ts index 2033252de2..2fb58fbaf7 100644 --- a/knockstrap/knockstrap-tests.ts +++ b/knockstrap/knockstrap-tests.ts @@ -1,9 +1,3 @@ -/// -/// -/// - - - // test unique id var adaskoUnitqueId: string = ko.utils.uniqueId('adaskothebeast'); diff --git a/knuddels-userapps-api/index.d.ts b/knuddels-userapps-api/index.d.ts new file mode 100644 index 0000000000..52183f832f --- /dev/null +++ b/knuddels-userapps-api/index.d.ts @@ -0,0 +1,2692 @@ +// Type definitions for Knuddels UserApps API 1.0 +// Project: https://developer.knuddels.de +// Definitions by: Knuddels GmbH & Co. KG +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// JSON definition +interface Json { + [x: string]: string | number | boolean | Date | Json | JsonArray; +} +interface JsonArray extends Array { } +// serializable objects (for persistence) +type KnuddelsSerializable = string | number | boolean | User | BotUser; +interface KnuddelsJson { + [x: string]: string | number | boolean | Date | KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable; +} +interface KnuddelsJsonArray extends Array { } +// "data" that may be send between apps and between server and client +type KnuddelsEvent = string | Json | KnuddelsEventArray; +interface KnuddelsEventArray extends Array { } +/** + * App ist die abstrakte Klasse einer konkreten App, die ein Entwickler schreiben kann. + * Im eigenen Javascript-Code muss eine Variable mit dem Namen App vorhanden sein, damit eine App lauffähig ist. + */ +declare interface App { + /** + * Dieses Methode wird aufgerufen, sobald ein Nutzer versucht den Channel zu betreten. + * Die App kann nun entscheiden, ob der Nutzer den Channel betreten darf. + * + * Hinweis: Um ein responsives User Interface für den Nutzer, + * der den Channel betreten möchte zu garantieren, muss die App innerhalb von einer Sekunde auf diese Anfrage reagieren, + * damit ihre Antwort in das Ergebnis einfliesst. + * + * Mit bestimmten Smileyfeatures ist es derzeit trotzdem möglich, den Channel zu betreten. + * Diese Nutzer können nicht ausgesperrt werden: + *
                + *
              • Channelbesitzer
              • + *
              • Channelmoderatoren und HZAs
              • + *
              • Admins (sofern notwendig)
              • + *
              • Sysadmins
              • + *
              • User Apps Team (Mitarbeiter von Knuddels)
              • + *
              + * + * Ist der Channel mit einem Passwort geschützt und der Nutzer, der versucht den Channel zu betreten kennt das Passwort, + * so kann er nicht aus dem Channel ausgeschlossen werden. + */ + mayJoinChannel?(user: User): ChannelJoinPermission; + /** + * Diese Methode wird jedes Mal aufgerufen, sobald ein Nutzer versucht eine öffentliche Nachricht zu senden. + * Die App kann nun entscheiden, ob die Nachricht veröffentlicht werden darf. + * + * Laufen mehrere Apps im selben Channel, so wird die Nachricht veröffentlicht, sofern alle Apps es erlauben. + * + * Dauert das Fragen aller Apps nach Erlaubnis länger als 10 Sekunden, so wird die Antwort genutzt, die bis dahin + * gegeben wurde. + */ + mayShowPublicMessage?(publicMessage: PublicMessage): boolean; + /** + * Diese Methode wird jedes Mal aufgerufen, sobald ein Nutzer versucht eine öffentliche Handlung auszuführen. + * Die App kann nun entscheiden, ob die Handlung ausgeführt werden darf. + * + * Laufen mehrere Apps im selben Channel, so wird die Handlung ausgeführt, sofern alle Apps es erlauben. + * + * Dauert das Fragen aller Apps nach Erlaubnis länger als 10 Sekunden, so wird die Antwort genutzt, die bis dahin + * gegeben wurde. + */ + mayShowPublicActionMessage?(publicActionMessage: PublicActionMessage): boolean; + /** + * Diese Methode wird aufgerufen, sobald die App startet. + * Dies ist der beste Zeipunkt um Werte zu initialisieren und aus der Persistenz zu lesen. + */ + onAppStart?(): void; + /** + * Diese Methode wird aufgerufen, wenn ein User Knuddel an den BotUser gesendet hat. + * Es ist die Aufgabe der App in dieser Methode zu entscheiden, ob sie die Knuddel annimmt oder ablehnt. + * Wird diese Methode von der App nicht implementiert, so werden Knuddel automatisch akzeptiert. + * Ist diese Methode implementiert und es treten Fehler (Exceptions, Timeout,...) auf oder der Entwickler entscheidet nicht, + * was mit den Knuddel geschehen soll, so werden diese vom App-System automatisch an den Absender zurück geschickt. + *
              + * Wichtig: Zum Zeitpunkt des Aufrufs dieser Methode wurden die Knuddel noch nicht an den BotUser übertragen. + */ + onBeforeKnuddelReceived?(knuddelTransfer: KnuddelTransfer): void; + /** + * Diese Methode wird aufgerufen, sobald ein BotUser Knuddel von einem User erhalten hat. + */ + onKnuddelReceived?(sender: User, receiver: BotUser, knuddelAmount: KnuddelAmount, transferReason: string): void; + /** + * Diese Methode wird aufgerufen, wenn die App sich darauf vorbereiten soll heruntergefahren zu werden. + * Als Parameter wird die geschätzte Zeit übergeben, die die App noch hat, bis sie heruntergefahren wird + * und der Aufruf App/onShutdown:event folgt. + * + * App/onPrepareShutdown:event kann dazu benutzt werden das Nutzererlebnis zu verbessern, + * sofern eine App heruntergefahren werden muss (bsp. für Updates). + * Eine Spiele-App könnte z.B. entscheiden, dass sie keine weiteren Spiele eröffnet und den Spielern offener Spiele + * die Information anzeigt, wie lange das Spiel noch läuft, bevor es unentschieden endet. + * + *

              Achtung: Die Methode kann im Lebenszyklus einer App mehrfach aufgerufen werden. + */ + onPrepareShutdown?(secondsTillShutdown: number): void; + /** + * Diese Methode wird aufgerufen, wenn ein BotUser privat angeschrieben wird. + */ + onPrivateMessage?(privateMessage: PrivateMessage): void; + /** + * Diese Methode wird aufgerufen, wenn im Channel der App + * eine öffentliche Nachricht geschrieben wird. + * Für Nachrichten von BotUsern wird diese Methode nicht aufgerufen. + */ + onPublicMessage?(publicMessage: PublicMessage): void; + /** + * Diese Methode wird aufgerufen, wenn im Channel der App + * eine Event-Nachricht veröffentlicht wird. + * Für Nachrichten von BotUsern wird diese Methode nicht aufgerufen. + */ + onPublicEventMessage?(publicEventMessage: PublicEventMessage): void; + /** + * Diese Methode wird aufgerufen, wenn im Channel der App + * eine öffentliche Handlung durchgeführt wird. + * Für Handlungen von BotUsern wird diese Methode nicht aufgerufen. + */ + onPublicActionMessage?(publicActionMessage: PublicActionMessage): void; + /** + * Diese Methode wird aufgerufen, wenn eine App beendet wird. + * Sobald diese Methode aufgerufen wird, steht nur noch ein begrenzter Teil der API zur Verfügung. + * Die App sollte den kompletten Zustand in der Persistenz speichern, sodass der Zustand + * beim nächsten App/onAppStart:event wiederhergestellt werden kann. + * + * Während des Shutdowns können asynchrone each-Methoden, wie UserPersistenceNumbers/each:method + * und UserAccess/eachAccessibleUser:method nicht zuverlässig genutzt werden. + */ + onShutdown?(): void; + /** + * Diese Methode wird aufgerufen, wenn ein User im Channel der App + * über die Systemfunktionen (/dice, /diceo) würfelt. + * Die App kann auf das Ergebnis zugreifen und die Daten für die Auswertung und Entscheidungen nutzen. + */ + onUserDiced?(diceEvent: DiceEvent): void; + /** + * Diese Methode wird aufgerufen, wenn ein User den Channel der App betritt. + */ + onUserJoined?(user: User): void; + /** + * Diese Methode wird aufgerufen, wenn ein User den Channel der App verlässt. + */ + onUserLeft?(user: User): void; + /** + * Diese Methode wird aufgerufen, wenn aus einer anderen App ein Event mit sendAppEvent versendet wurde. + */ + onAppEventReceived?(appInstance: AppInstance, type: string, data: KnuddelsEvent): void; + /** + * Diese Methode wird aufgerufen, wenn aus dem HTML User Interface ein Event mit + * sendEvent() gesendet wurde. + */ + onEventReceived?(user: User, type: string, data: KnuddelsEvent, appContentSession: AppContentSession): void; + /** + * Diese Methode wird aufgerufen, wenn ein User Knuddel in seinen KnuddelAccount + * eingezahlt hat. + */ + onAccountReceivedKnuddel?(sender: User, receiver: BotUser, knuddelAmount: KnuddelAmount, transferReason: string, knuddelAccount: KnuddelAccount): void; + /** + * Diese Methode wird aufgerufen, wenn sich die Anzahl der Knuddel auf einem KnuddelAccount eines User + * geändert hat. + */ + onAccountChangedKnuddelAmount?(user: User, knuddelAccount: KnuddelAccount, oldKnuddelAmount: KnuddelAmount, newKnuddelAmount: KnuddelAmount): void; + /** + * Ermöglicht das Registrieren eigener Chatbefehle. + * In einem Channel kann nur eine App laufen, die einen bestimmten Chatbefehl nutzt. + * Versucht eine zweite App einen Chatbefehl zu registrieren, den eine andere + * App bereits nutzt, so wird ein Fehler geloggt und die App startet nicht bzw. fährt herunter. + * + * Die Struktur eines registrierten Chatbefehls ist: + * commandName: function (user, params, command) {} + * + * + *
                + *
              • commandName ist der Name der Funktion, wie sie aufgerufen wird (beispielsweise /commandname)
              • + *
              • user ist der Nutzer, der die Funktion aufgerufen hat
              • + *
              • params sind die Parameter, die der Nutzer hinter dem Befehl eingegeben hat (beispielsweise /commandname params)
              • + *
              • command ist der Name des Befehl selbst (beispielsweise commandName)
              • + *
              + */ + chatCommands?: { [commandName: string]: (user: User, params: string, command: string) => void }; +} + +/** + * Ermöglicht Zugriff auf Informationen zu Apps und Events zwischeneinander. + * + * Die Instanz von AppAccess erhält man über den KnuddelsServer + * mit KnuddelsServer.getAppAccess() + */ +declare class AppAccess { + /** + * Liefert die Instanz der eigenen App. + */ + getOwnInstance(): AppInstance; + /** + * Liefert die Instanzen aller anderen Apps, die gerade in diesem Channel laufen. + * @since AppServer 82904 + */ + getAllRunningAppsInChannel(includeSelf?: boolean): AppInstance[]; + /** + * Liefert die Instanzen aller anderen Apps, die gerade in diesem Channel laufen. + * @since AppServer 82904 + */ + getRunningAppInChannel(appId: string): (AppInstance|null); +} + +/** + * Repräsentiert den visuellen Inhalt einer Applikation, der Usern angezeigt werden soll. + */ +declare class AppContent { + /** + * Liefert den AppViewMode. + */ + getAppViewMode(): AppViewMode; + /** + * Liefert das HTMLFile, das beim Anlegen des AppContents + * genutzt wurde. + */ + getHTMLFile(): HTMLFile; + /** + * Liefert die Breite des AppContent. + */ + getWidth(): number; + /** + * Liefert die Höhe des AppContent. + */ + getHeight(): number; + /** + * Liefert die LoadConfiguration, mit der die Optik beim Laden des HTML User Interface beeinflusst werden kann. + */ + getLoadConfiguration(): LoadConfiguration; + /** + * Liefert einen AppContent, der das HTMLFile als Overlay oben rechts im Channel anzeigt. + */ + static overlayContent(htmlFile: HTMLFile, width: number, height: number): AppContent; + /** + * Liefert einen AppContent, der das HTMLFile als Overlay (200x350) oben rechts im Channel anzeigt. + */ + static overlayContent(htmlFile: HTMLFile): AppContent; + /** + * Liefert einen AppContent, der das HTMLFile im Applet/HTML-Chat + * als Popup (300x400) und auf Android als Fullscreen-View anzeigt. + */ + static popupContent(htmlFile: HTMLFile): AppContent; + /** + * Liefert einen AppContent, der das HTMLFile im Applet/HTML-Chat + * als Popup und auf Android als Fullscreen-View anzeigt. + */ + static popupContent(htmlFile: HTMLFile, width: number, height: number): AppContent; + /** + * Sendet Daten an alle Nutzer, die diesen AppContent geöffnet haben. + */ + sendEvent(type: string, data?: KnuddelsEvent): void; + /** + * Liefert eine Liste aller User, die diesen AppContent + * geöffnet haben. + */ + getUsers(): User[]; + /** + * Liefert eine Liste aller AppContentSessions, die dieses AppContent, + * die User gerade geöffnet haben. + */ + getSessions(): AppContentSession[]; + /** + * Ersetzt den AppContent, bei allen Usern, die diesen AppContent + * geöffnet haben durch den neuen AppContent. + * + *

              Hinweis: Es können nur AppContent mit demselben AppViewMode + * zum Ersetzen genutzt werden. + */ + replaceWithAppContent(newAppContent: AppContent): void; + /** + * Entfernt diesen AppContent, bei allen Usern, die diesen AppContent + * geöffnet haben. + */ + remove(): void; + /** + * Fügt einen Listener hinzu, der aufgerufen wird, wenn jemand den AppContent schließt. + */ + addCloseListener(callback: { user: User; appContent: AppContent; }): void; +} + +/** + * Repräsentiert den visuellen Inhalt einer App, der einem User angezeigt wird. + */ +declare class AppContentSession { + /** + * Sendet Daten an den verbundenen Client. + */ + sendEvent(type: string, data?: KnuddelsEvent): void; + /** + * Liefert den AppViewMode. + */ + getAppViewMode(): AppViewMode; + /** + * Entfernt die AppContentSession beim verbundenen User. + */ + remove(): void; + /** + * Liefert den User. + */ + getUser(): User; + /** + * Liefert den verbundenen AppContent. + */ + getAppContent(): AppContent; +} + +/** + * Die Instanz von AppInfo zur laufenden App erhält man über die AppInstance + * mit appInstance.getAppInfo() + */ +declare class AppInfo { + /** + * Liefert die AppUid. + * Diese ist für jede Sub-Channel Instanz der App unterschiedlich. + * Wenn RootAppUid == AppUid dann ist dies die Root-App-Instanz. + */ + getAppUid(): number; + /** + * Liefert die RootAppUid. + * Diese ist für jede Sub-Channel Instanz der App gleich. + * Wenn RootAppUid == AppUid dann ist dies die Root-App-Instanz. + * + * Sie wird für den Link für Auszahlungen aus einem Knuddel-Account benötigt: /knuddelaccount payout:<RootAppUid>:<BETRAG> + */ + getRootAppUid(): number; + /** + * Liefert den in der Konfiguration eingestellten Namen der App. + */ + getAppName(): string; + /** + * Liefert die Version der App, die in der Konfiguration eingestellt wurde. + */ + getAppVersion(): string; + /** + * Liefert die eindeutige Id der App. + * Die appId setzt sich zusammen aus + *
                + *
              • id des Entwicklungsservers
              • + *
              • FTP-Nutzername
              • + *
              • Ordnername der App -> appKey
              • + *
              + */ + getAppId(): string; + /** + * Liefert den eindeutigen Key der App. + * Der appKey ist der Ordnername, in dem die App liegt. + */ + getAppKey(): string; + /** + * Liefert den Entwickler der App, falls die serverId knuddelsDE oder knuddelsDEV ist, ansonsten null. + */ + getAppDeveloper(): User; + /** + * Liefert die Liste der AppManager für diese App. Die Channelbesitzer zählen automatisch auch als AppManager. + */ + getAppManagers(): User[]; + /** + * Liefert den Steuersatz, der bei Auszahlung bereits genutzer Knuddel von einem + * KnuddelAccount an einen User + * anfällt. Die anfallenden Steuern werden bei Auszahlung vom BotUser + * abgezogen. + */ + getTaxRate(): number; + /** + * Liefert den KnuddelAmount, der an Steuern anfallen würde, + * wenn alle User jetzt all ihre Knuddel aus ihrem + * KnuddelAccount abheben würden. + */ + getTotalTaxKnuddelAmount(): KnuddelAmount; + /** + * Liefert den KnuddelAmount, der jetzt noch vom + * BotUser an KnuddelAccounts + * übertragen werden kann, so dass für alle Knuddel noch die Steuern bezahlt werden können. + */ + getMaxPayoutKnuddelAmount(): KnuddelAmount; +} + +/** + * Repräsentiert die Instanz einer App. + * + * Die eigene Instanz von AppInstance erhält man über das AppAccess-Objekt + * mit appAccess.getOwnInstance() + */ +declare class AppInstance { + /** + * Liefert die AppInfo. + */ + getAppInfo(): AppInfo; + /** + * Sendet ein App-Event an diese App-Instanz. + */ + sendAppEvent(type: string, data: KnuddelsEvent): void; + /** + * Informiert, ob die aktuelle AppInstanz eine Root-Instanz ist. + */ + isRootInstance(): boolean; + /** + * Liefert die Root-Instanz der aktuellen App-Instanz. + */ + getRootInstance(): RootAppInstance; + /** + * Liefert alle App-Instanzen dieser App in diesem Channel und Subchannels. + * Mit includeSelf = false kann man die eigene Instanz ausschließen. + */ + getAllInstances(includeSelf?: boolean): AppInstance[]; + /** + * Liefert den Startzeitpunkt dieser AppInstance. + */ + getStartDate(): Date; + /** + * Liefert die Namen der ChatCommands, die diese AppInstnce derzeit registriert hat. + */ + getRegisteredChatCommandNames(): (string[]|null); + /** + * Liefert den Namen des Channels in dem diese AppInstance läuft. + */ + getChannelName(): string; +} + +/** + * Jede App besitzt eine AppPersistence in der global für diese App + * Informationen gespeichert werden können. An die Instanz der AppPersistence gelangt man durch den Aufruf + * KnuddelsServer.getPersistence();. + */ +declare class AppPersistence extends Persistence { +} + +/** + * Eine Instanz eines AppProfileEntry repräsentiert einen von einer App erzeugen Profileintrag in Profilen von Usern. + */ +declare class AppProfileEntry { + /** + * Liefert den key für den die Topliste, die den Profileintrag erzeugt angelegt wurde. + */ + getKey(): string; + /** + * Liefert den getDisplayType + */ + getDisplayType(): ToplistDisplayType; + /** + * Liefert das Toplist-Objekt. + */ + getToplist(): Toplist; +} + +/** + * Mit einer Instanz von AppProfileEntryAccess kann eine App + * AppProfileEntry-Objekte (Profileinträge) erzeugen und verwalten. + * + * Die Instanz für die AppProfileEntryAccess erhält man über das KnuddelsServer-Objekt + * mit KnuddelsServer.getAppProfileEntryAccess() + * + *

              Achtung: Derzeit darf eine App bis zu fünf AppProfileEntries haben. + *

              Achtung: Profileinträge werden nur dann angezeigt, wenn der Channel sichtbar ist. + */ +declare class AppProfileEntryAccess { + /** + * Liefert die Liste aller AppProfileEntry-Objekte, die diese App erzeugt hat. + */ + getAllProfileEntries(): AppProfileEntry[]; + /** + * Liefert den AppProfileEntry für den übergebenen userPersistenceNumberKey. + */ + getAppProfileEntry(userPersistenceNumberKey: string): AppProfileEntry; + /** + * Erzeugt oder aktualisiert ein AppProfileEntry anhand der übergebenen Toplist + * und dem ToplistDisplayType und liefert den AppProfileEntry im Anschluss zurück. + * + * Profileinträge, die erzeugt werden, sind nur sichtbar, solange die App läuft und werden im Profil ausgeblendet, sofern die App aus ist. + */ + createOrUpdateEntry(toplist: Toplist, toplistDisplayType: ToplistDisplayType): AppProfileEntry; + /** + * Löscht den übergebenen AppProfileEntry. + */ + removeEntry(appProfileEntry: AppProfileEntry): void; +} + +/** + * Liefert Informationen über einen AppServer. + * + * Die Instanz von AppServerInfo erhält man über den KnuddelsServer + * mit KnuddelsServer.getAppServerInfo() + */ +declare class AppServerInfo extends ServerInfo { +} + +/** + * null + */ +declare class AppViewMode { + /** + * + */ + static readonly Overlay: AppViewMode; + /** + * Zum Öffnen eines Popups durch das HTML User Interface + */ + static readonly Popup: AppViewMode; +} + +/** + * Ein BotUser repräsentiert einen Nutzer, der für die App als Nutzer im Channel interagieren kann. + * + * Die Instanz für den Standard-BotUser erhält man über das KnuddelsServer-Objekt + * mit KnuddelsServer.getDefaultBotUser() + */ +declare class BotUser extends User { + /** + * Sendet eine öffentliche Nachricht in den Channel. + */ + sendPublicMessage(message: string): void; + /** + * Sendet eine öffentliche Handlung in den Channel. + * Dies funktioniert so, als ob der BotUser /me TEXT im Chat eingeben würde. + */ + sendPublicActionMessage(actionMessage: string): void; + /** + * Sendet eine private Nachricht an bestimmte Nutzer. + */ + sendPrivateMessage(message: string, users?: User[]): void; + /** + * Sendet eine persistente Nachricht an einen bestimmten Nutzer. + */ + sendPostMessage(topic: string, text: string, receivingUser?: User): void; + /** + * Transferiert eine bestimmte Anzahl Knuddel an einen Zielnutzer oder KnuddelAccount.

              + * Wichtiger Hinweis: Sollte die App versuchen mehr Knuddel zu transferieren, + * als sie besitzt, so wird der onError-Callback aufgerufen und die App transferiert so viele Knuddel, wie möglich. + * Zudem werden die Schulden für den Channelbesitzer gemerkt. Sobald sich der Channelbesitzer einloggt, erhält er einen Hinweis über offene Schulden + * und sollte diese direkt begleichen. + * Hat ein Channelbesitzer eine gewisse Menge Schulden angesammelt, so schalten wir alle Apps in diesem Channel ab. + *
              Es können nur Knuddel transferiert werden zu Nutzern mit UserType.Human. + */ + transferKnuddel(receivingUserOrAccount: (User|KnuddelAccount), knuddelAmount: KnuddelAmount, + parameters?: { displayReasonText?: string; transferDisplayType?: KnuddelTransferDisplayType; + onSuccess?: () => void; onError?: (message: string) => void; }): void; +} + +/** + * Ein Channel ist ein Raum in dem die App läuft. + * + * Die Instanz für den Channel erhält man über das KnuddelsServer-Objekt + * mit KnuddelsServer.getChannel() + */ +declare class Channel { + /** + * Gibt Zugriff auf das ChannelConfiguration-Objekt des Channels. + */ + getChannelConfiguration(): ChannelConfiguration; + /** + * Gibt Zugriff auf das ChannelRestrictions-Objekt des Channels. + */ + getChannelRestrictions(): ChannelRestrictions; + /** + * Gibt Zugriff auf das ChannelDesign-Objekt des Channels. + * @since AppServer 87470, ChatServer 87470 + */ + getChannelDesign(): ChannelDesign; + /** + * Gibt Zugriff auf Nutzer, die gerade im Channel online sind. + */ + getOnlineUsers(...userType: UserType[]): User[]; + /** + * Liefert die Information, ob in diesem Channel Videos gestreamt werden können. + */ + isVideoChannel(): boolean; + /** + * Liefert die VideoChannelData des Channels. + */ + getVideoChannelData(): VideoChannelData; + /** + * Liefert den Namen des Channels. + */ + getChannelName(): string; + /** + * Liefert den Namen des Root-Channels (nur relevant, falls die App Tochterchannel haben kann). + */ + getRootChannelName(): string; + /** + * Liefert den ChannelTalkMode, in dem sich der Channel gerade befindet. + */ + getTalkMode(): ChannelTalkMode; + /** + * Liefert alle User, die bestimmte ChannelTalkPermissions haben. + */ + getAllUsersWithTalkPermission(...channelTalkPermission: ChannelTalkPermission[]): User[]; + /** + * Liefert die Information, ob der Channel sichtbar (true) oder unsichtbar (false) ist. + * @since AppServer 82202 + */ + isVisible(): boolean; +} + +/** + * Eine ChannelConfiguration erlaubt Zugriff auf verschiedene Details + * der Konfiguration des Channels, in dem die App läuft. + * + * Die Instanz für die ChannelConfiguration erhält man über das Channel-Objekt + * mit channel.getChannelConfiguration() + */ +declare class ChannelConfiguration { + /** + * Liefert das ChannelRights-Objekt des Channels. + */ + getChannelRights(): ChannelRights; + /** + * Liefert das ChannelInformation-Objekt des Channels. + */ + getChannelInformation(): ChannelInformation; +} + +/** + * Ermöglicht Zugriff auf Designeinstellungen des Channels. + * @since AppServer 87470, ChatServer 87470 + */ +declare class ChannelDesign { + /** + * Liefert die eingestellte Standard-Schriftgröße des Channels. + * @since AppServer 87470, ChatServer 87470 + */ + getDefaultFontSize(): number; + /** + * Liefert die eingestellte Standard-Schriftfarbe des Channels. + * @since AppServer 87470, ChatServer 87470 + */ + getDefaultFontColor(): Color; + /** + * Liefert die eingestellte Hintergrundfarbe des Channels. + * @since AppServer 87470, ChatServer 87470 + */ + getBackgroundColor(): Color; +} + +/** + * Ermöglicht Zugriff auf textuelle Channelinformationen und persistente Änderungen. + */ +declare class ChannelInformation { + /** + * Liefert das eingestellte Thema des Channels. + */ + getTopic(): string; + /** + * Aktualisiert das Thema das Channels. + */ + setTopic(topic: string, showMessage: boolean): void; +} + +/** + * Eine Instanz der Klasse ChannelJoinPermission wird als Rückgabewert + * der Methode App.mayJoinChannel(user) benötigt. + * + * Hiermit wird bestimmt, ob der anfragende Nutzer den Channel betreten darf. + * + * Erlauben mit ChannelJoinPermission.accepted() + * Verbieten mit ChannelJoinPermission.denied(denyReason) + */ +declare class ChannelJoinPermission { + /** + * Erzeugt ein ChannelJoinPermission-Objekt, das den Zugriff in den Channel erlaubt. + */ + static accepted(): ChannelJoinPermission; + /** + * Erzeugt ein ChannelJoinPermission-Objekt, das den Zugriff in den Channel verbietet. + */ + static denied(denyReason: string): ChannelJoinPermission; +} + +/** + * Eine Instanz von ChannelRestrictions ermöglicht es, aktuelle Informationen über Nutzungsbeschränkungen im Channel zu erhalten. + * + * Die Instanz für die ChannelRestrictions erhält man über das Channel-Objekt + * mit channel.getChannelRestrictions() + */ +declare class ChannelRestrictions { + /** + * Liefert alle User die im Channel derzeit für das Schreiben öffentlicher Nachrichten gesperrt sind. + */ + getMutedUsers(): User[]; + /** + * Liefert alle User die im Channel derzeit für das Nutzen + * von Farben, Textformatierung und Smileys in öffentlichen Nachrichten gesperrt sind. + */ + getColorMutedUsers(): User[]; + /** + * Liefert alle User die für das Betreten des Channel derzeit gesperrt sind. + */ + getLockedUsers(): User[]; +} + +/** + * Die Instanz für die ChannelRights erhält man über das ChannelConfiguration-Objekt + * mit channelConfiguration.getChannelRights() + */ +declare class ChannelRights { + /** + * Liefert die Liste aller Channelbesitzer. In öffentlichen Channels sind dies alle hauptzuständigen betreuenden Mitglieder. (HZA/HZE) + */ + getChannelOwners(): User[]; + /** + * Liefert die Liste aller Channel-Moderatoren. + */ + getChannelModerators(): User[]; + /** + * Liefert die Liste aller Event-Moderatoren. + */ + getEventModerators(): User[]; +} + +/** + * ChannelTalkMode repräsentiert das den Gesprächsmodus im Channel. + * + * Die Instanz für die ChannelTalkMode erhält man über das Channel-Objekt + * mit channel.getTalkMode() + */ +declare class ChannelTalkMode { + /** + * Jeder darf gerade im Channel schreiben. + */ + static readonly Everyone: ChannelTalkMode; + /** + * Nur Personen, die besondere Rederechte haben dürfen gerade im Channel schreiben. + */ + static readonly OnlyWithTalkPermission: ChannelTalkMode; + /** + * Nur Personen, die besondere Rederechte haben dürfen gerade im Channel schreiben. + * Die Nachrichten aller anderen Nutzer werden gefiltert und ggf. von den Moderatoren zugelassen. + */ + static readonly FilteredByModerators: ChannelTalkMode; +} + +/** + * ChannelTalkPermission repräsentiert das Rederecht eines User + * im Channel. + */ +declare class ChannelTalkPermission { + /** + * Der User ist gerade nicht im Channel, + * daher ist die ChannelTalkPermission nicht bekannnt. + */ + static readonly NotInChannel: ChannelTalkPermission; + /** + * Der User hat keine speziellen Rederechte. + * Beim ChannelTalkMode Default können diese User + * Nachrichten verfassen: + */ + static readonly Default: ChannelTalkPermission; + /** + * Der User kann eine öffentliche Nachricht verfassen. Danach wechselt die + * ChannelTalkPermission automatisch auf Default. + */ + static readonly TalkOnce: ChannelTalkPermission; + /** + * Der User kann permanent öffentliche Nachrichten verfassen. + */ + static readonly TalkPermanent: ChannelTalkPermission; + /** + * Der User ist VIP und kann öffentliche Nachrichten verfassen, + * die farbig und groß dargestellt werden. + */ + static readonly VIP: ChannelTalkPermission; + /** + * Der User ist VIP und kann öffentliche Nachrichten verfassen, + * die farbig und groß dargestellt werden. Moderatoren haben zudem weitere Möglichkeiten, die in der + * Anleitung zum Moderationssystem + * nachgelesen werden können. + */ + static readonly Moderator: ChannelTalkPermission; +} + +/** + * Liefert Informationen über einen ChatServer. + * + * Die Instanz von ChatServerInfo erhält man über den KnuddelsServer + * mit KnuddelsServer.getChatServerInfo() + */ +declare class ChatServerInfo extends ServerInfo { + /** + * Liefert die Information, ob dieser Chat-Server ein Test-System ist. + */ + isTestSystem(): boolean; +} + +/** + * Klasse, die es ermöglicht den Client innerhalb des HTML User Interface zu steuern und Daten an den Server zu senden. + */ +declare class Client { + /** + * Schließt das HTML User Interface. + */ + static close(): void; + /** + * Sendet ein Event zum Server, das mit dem AppHook onEventReceived in der App + * abgefangen werden kann. + */ + static sendEvent(type: string, data: KnuddelsEvent): void; + /** + * Sagt dem Chatserver, dass dieser Befehl für den Nutzer, der das HTML User Interface sieht, ausgeführt werden soll. + * Ist der Befehl auf einer Whitelist vom Server, so wird er sofort ausgeführt. Im anderen Falle sieht der Nutzer einen + * Link zum Bestätigen, mit dem er die Aktion starten kann. + * + * Derzeit sind diese Befehle auf der Whitelist: w, info, wc, top, h, dice, d, diceo, w2, serverpp, knuddelaccount, + * /tf-insert, /tf-inserts, /tf-insertb, /tf-insertsb, /tf-override, /tf-overrides, /tf-overrideb, /tf-overridesb, /autotype + */ + static executeSlashCommand(command: string): void; + /** + * Bindet eine Javascript-Datei ein und sorgt dafür, dass immer die aktuellste Version vom Server geladen wird. + */ + static includeJS(...files: string[]): void; + /** + * Registriert sich für ein bestimmtes Event, das vom Server mittels User/sendEvent:method oder vom Client via Client/dispatchEvent:method verschickt wurde. + */ + static addEventListener(type: string, callback: (event: {type: string, data: KnuddelsEvent}) => void): void; + /** + * Sendet ein bestimmtes Event, so dass alle mit Client/addEventListener:method registrierten Listener aufgerufen werden. + */ + static dispatchEvent(event: Client.Event): void; + /** + * Entfernt alle Event-Listener für einen bestimmten Event-Typ. + */ + static removeEventListener(type: string): void; + /** + * Bindet eine CSS-Datei ein und sorgt dafür, dass immer die aktuellste Version vom Server geladen wird. + */ + static includeCSS(...files: string[]): void; + /** + * Spielt einen Sound ab. Der angegebene Dateiname kann hierbei entweder absolut oder relativ zur angezeigten HTML-Datei sein. + * Bisher können nur Dateien mit Wave-Format zuverlässig abgespielt werden. + */ + static playSound(fileName: string): void; + /** + * Lädt einen Sound herunter, damit die Datei später ohne Wartezeit abgespielt werden kann. + * (Android only) + * Der angegebene Dateiname kann hierbei entweder absolut oder relativ zur angezeigten HTML-Datei sein. + */ + static prefetchSound(fileName: string): void; + /** + * Gibt einen Sound wieder frei, der in nächster Zeit vom Client nicht mehr gebraucht wird. + * (Android only) + * Der angegebene Dateiname kann hierbei entweder absolut oder relativ zur angezeigten HTML-Datei sein. + */ + static freeSound(fileName: string): void; + /** + * Liefert den HostFrame des aktuellen Inhalts. + */ + static getHostFrame(): Client.HostFrame; + /** + * Liefert den Nicknamen des Users, der gerade dieses HTML User Interface angezeigt bekommt. + */ + static getNick(): string; + /** + * Liefert den aktuellen ClientType des Nutzers, der gerade dieses HTML User Interface angezeigt bekommt. + */ + static getClientType(): ClientType; + /** + * Liefert die Id, die beim Laden von Skripten und Stylesheets an die URL angehängt wird, um sicherzustellen, dass eine neue Version + * der Datei vom Server geholt wird, statt die Datei aus dem Cache zu laden. + * + * Diese Id kann beim Einbinden eigener Ressourcen zum selben Zweck genutzt werden. + */ + static getCacheInvalidationId(): string; + /** + * Beinhaltet die JSON-Daten, die beim Erstellen des HTMLFile übergeben wurden. + */ + static pageData: Json; +} + +/** + * Klasse, mit der clientseitige Farbobjekte erstellt werden können. + */ +declare module Client { + export class Color { + /** + * Erzeugt ein Color-Objekt mit RGB-Werten. + */ + static fromRGB(red: number, green: number, blue: number): Color; + /** + * Erzeugt ein Color-Objekt aus einem HexString. + */ + static fromHexString(colorString: string): Color; + /** + * Liefert den Rot-Anteil der Farbe als Zahl zwischen 0 und 255. + */ + getRed(): number; + /** + * Liefert den Grün-Anteil der Farbe als Zahl zwischen 0 und 255. + */ + getGreen(): number; + /** + * Liefert den Blau-Anteil der Farbe als Zahl zwischen 0 und 255. + */ + getBlue(): number; + /** + * Liefert die Farbe als in CSS nutzbaren HexString. + */ + asHexString(): string; + } +} + +/** + * Klasse, die es ermöglicht ein Event via Client/dispatchEvent:method zu versenden. + */ +declare module Client { + export class Event { + /** + * Erzeugt ein Event. + */ + constructor(type: string, data: KnuddelsEvent); + } +} + +/** + * Klasse, die es ermöglicht den Inhalte zu steuern, die im Bereich liegen, der das HTML User Interface hostet. + */ +declare module Client { + export class HostFrame { + /** + * Setzt den Titel der Seite im gezoomten Modus (nur Android). + */ + setTitle(newTitle: string): void; + /** + * Ändert die sichtbare Hintergrundfarbe des Hostframes animiert. (Android-only) + */ + setBackgroundColor(newColor: Color, durationMillis?: number): void; + /** + * Setzt die Icons, die als Fenster-Icon angezeigt werden sollen. (Applet-only, nur mit AppViewMode.Popup) + * Die Bilder müssen von groß nach klein sortiert sein. Die größeren Bilder werden (je nach System) automatisch dann eingesetzt, + * wenn größere Bilder benötigt werden (z.B. in der Task-Leiste, oder beim Alt+Tab Fenster-Wechsel). + * @since Applet: 9.0bwj, AppServer: 84904 + */ + setIcons(...path: string[]): void; + /** + * Setzt, ob das Fenster resizable ist. (Applet-only, nur mit AppViewMode.Popup) + */ + setResizable(resizable: boolean): void; + /** + * Bringt das Fenster der App (App-Popup bzw. Chat-Fenster) in den Vordergrund. (Applet-only) + * @since Applet: 9.0bwj, AppServer: 84904 + */ + focus(): void; + /** + * Ändert die Größe des App-Fensters (AppViewMode.Popup) bzw. App-Overlays (AppViewMode.Overlay). + * @since Applet: 9.0bwj, AppServer: 84516 + */ + setSize(width: number, height: number): void; + } +} + +/** + * ClientType repräsentiert die Art der Chat-Verbindung des Users. + * + * Eine Instanz von ClientType erhält man über das User-Objekt + * mit user.getClientType() + */ +declare class ClientType { + /** + * Der User ist mit dem Java Applet im Chat. + */ + static readonly Applet: ClientType; + /** + * Der User ist mit dem Browser im Chat (Mini-Chat, HTML-Chat). + */ + static readonly Browser: ClientType; + /** + * Der User ist mit der Android-App im Chat. + */ + static readonly Android: ClientType; + /** + * Der User ist mit der iOS-App im Chat. + */ + static readonly IOS: ClientType; + /** + * Der User ist nicht im Chat. + */ + static readonly Offline: ClientType; +} + +/** + * Klasse, mit der serverseitige Farbobjekte erstellt werden können. + */ +declare class Color { + /** + * Erzeugt ein serverseitiges Color-Objekt mit RGB-Werten. + * Als Alpha-Wert wird automatisch 255 genutzt. + */ + static fromRGB(red: number, green: number, blue: number): Color; + /** + * Erzeugt ein serverseitiges Color-Objekt mit RGBA-Werten. + */ + static fromRGBA(red: number, green: number, blue: number, alpha: number): Color; + /** + * Liefert den Alpha-Wert der Farbe als Zahl zwischen 0 und 255. + */ + getAlpha(): number; + /** + * Liefert den Blau-Anteil der Farbe als Zahl zwischen 0 und 255. + */ + getBlue(): number; + /** + * Liefert den Grün-Anteil der Farbe als Zahl zwischen 0 und 255. + */ + getGreen(): number; + /** + * Liefert den Rot-Anteil der Farbe als Zahl zwischen 0 und 255. + */ + getRed(): number; + /** + * Liefert die Farbe als KCode zurück. + */ + toKCode(): string; + /** + * Liefert die numerische Repräsentation der Farbe zurück. + */ + asNumber(): number; + /** + * Erzeugt ein serverseitiges Color-Objekt aus der numerischen Repräsentation einer Farbe. + */ + static fromNumber(value: number): Color; +} + +/** + * Eine Instanz von Dice repräsentiert die Anzahl an Würfeln von einerm bestimmten Typ. + */ +declare class Dice { + /** + * Erzeugt ein Dice-Objekt mit der übergebenen Anzahl Würfel und Augenzahl. + */ + constructor(count: number /* optional */, value: number); + /** + * Liefert die Anzahl der Würfel. + */ + getAmount(): number; + /** + * Liefert die Anzahl der Seiten der Würfel. + */ + getNumberOfSides(): number; +} + +/** + * Eine Instanz von DiceConfiguration repräsentiert eindeutig eine Konfiguration zum würfeln. + * Wurde gewürfelt, so können die Konfigurationen verglichen werden, um zu prüfen, ob exakt die Würfel + * gewürfelt wurden, die gewürfelt werden sollten. + */ +declare class DiceConfiguration { + /** + * Informiert, ob es sich um einen offenen Würfelwurf handelt. + * Offene Würfelwürfe sind speziell. Falls die Augenzahl des Würfels die Maximalsumme zeigt, + * so wird noch einmal gewürfelt und die neue Zahl dazu addiert, solange bis der Würfel + * nicht mehr die Maximalsumme zeigt. + * + * Beispiel: /diceo 1w4 -> 4 -> 4 -> 3 = 11 + */ + isUsingOpenThrow(): boolean; + /** + * Informiert darüber, ob die Würfel privat geworfen worden sind. + * Würfelwürfe zählen als privat, wenn am Ende des Würfelbefehls ein Ausrufezeichen steht. + * Beispiel: /dice 10w2! + */ + isUsingPrivateThrow(): boolean; + /** + * Liefert ein Array mit Würfeln, mit denen gewürfelt wurde. + */ + getDices(): Dice[]; + /** + * Vergleicht, ob zwei Konfigurationen inhaltlich identisch sind + */ + equals(diceConfiguration: DiceConfiguration): boolean; + /** + * Liefert den Befehl, der im Chat eingegeben werden kann, um einen Wurf auszuführen, + * der zur DiceConfiguration passt. + * @since AppServer 82248 + */ + getChatCommand(): string; +} + +/** + * Eine Instanz einer DiceConfigurationFactory kann zur Unterstützung genutzt werden, um eine + * DiceConfiguration zu erzeugen. + */ +declare class DiceConfigurationFactory { + /** + * Fügt der Konfiguration einen Würfel hinzu. + */ + addDice(dice: Dice): void; + /** + * Liefert die Anzahl der Würfel, die zur Konfiguration gehören. + */ + computeCurrentDiceCount(): number; + /** + * Setzt die Information, ob ein offener Wurf oder ein normaler Wurf stattfinden soll. + * Offene Würfelwürfe sind speziell. Falls die Augenzahl des Würfels die Maximalsumme zeigt, + * so wird noch einmal gewürfelt und die neue Zahl dazu addiert, solange bis der Würfel + * nicht mehr die Maximalsumme zeigt. + * + * Beispiel: /diceo 1w4 -> 4 -> 4 -> 3 = 11 + */ + setUseOpenThrow(shouldUseOpenThrow: boolean): void; + /** + * Setzt die Information, ob der Würfelwurf privat stattfinden soll. + */ + setShouldUsePrivateThrow(shouldUsePrivateThrow: boolean): void; + /** + * Liefert die erzeugte Würfelkonfiguration. + */ + getDiceConfiguration(): DiceConfiguration; + /** + * Erzeugt eine Würfelkonfiguration. + */ + static fromString(diceConfigurationString: string): DiceConfiguration; +} + +/** + * Wird in der App die Methode onUserDiced überschrieben, so erhält diese bei jedem Würfelwurf ein DiceEvent. + * Ein DiceEvent ermöglicht einem detaillierte Informationen rund um diesen Würfelwurf in Erfahrung zu bringen. + */ +declare class DiceEvent { + /** + * Liefert den Nutzer, der gewürfelt hat. + */ + getUser(): User; + /** + * Liefert das DiceResult des Würfelwurfs. + */ + getDiceResult(): DiceResult; +} + +/** + * Ein DiceResult beinhaltet konkrete Informationen über einen Würfelwurf. + */ +declare class DiceResult { + /** + * Liefert die Konfiguration mit der gewürfelt wurde. + */ + getDiceConfiguration(): DiceConfiguration; + /** + * Liefert ein Array mit Details zu den einzelnen Ergebnissen pro Würfeltyp. + */ + getSingleDiceResults(): SingleDiceResult[]; + /** + * Liefert die Summe der Augenzahlen aller Würfel + */ + totalSum(): number; +} + +/** + * Die Instanz einer Domain beinhaltet alle relevanten Informationen zur Domain. + */ +declare class Domain { + /** + * Liefert ein den Domain-Namen der aktuellen Domain. + */ + getDomainName(): string; +} + +/** + * Die Instanz von ExternalServerAccess erhält man über die KnuddelsServer.getExternalServerAccess(). + * Damit der Zugriff auf einen externern Server funktioniert, muss auf dem Server eine Datei knuddelsAccess.txt abgelegt werden, die die FTP-User-ID des Entwicklers enthält. + */ +declare class ExternalServerAccess { + /** + * Liefert eine Liste aller zugreifbaren Domains + */ + getAllAccessibleDomains(): Domain[]; + /** + * Prüft den Zugriff auf eine bestimmte URL. Wird je Kombination von "Protokoll + Host + Port" geprüft.
              + * Beispiel: http://www.example.de:8080 + */ + canAccessURL(urlString: string): boolean; + /** + * Macht einen GET-Request auf die übergebene URL und liefert den Inhalt zurück. + * Diese Methode ist eine Convenience-Methode für externalServerAccess.callURL(). + */ + getURL(urlString: string, parameters?: { onSuccess?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + onFailure?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; }): void; + /** + * Macht einen POST-Request auf die übergebene URL und liefert den Inhalt zurück. + * Diese Methode ist eine Convenience-Methode für externalServerAccess.callURL(). + */ + postURL(urlString: string, parameters?: { onSuccess?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + onFailure?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; data?: Json; }): void; + /** + * Macht einen GET-Request auf die übergebene URL. Im Gegensatz zum GET-Request wird der Inhalt der Webseite wird nicht ausgelesen. + * Aus diesem Grund ist diese Methode schneller. + * Diese Methode ist eine Convenience-Methode für externalServerAccess.callURL(). + */ + touchURL(urlString: string, parameters?: { onSuccess?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + onFailure?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; }): void; + /** + * Macht einen Request auf die übergebene URL. + */ + callURL(urlString: string, parameters?: { onSuccess?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + onFailure?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; method?: ("GET" | "POST"); data?: Json; }): void; +} + +/** + * Die Instanz von ExternalServerResponse erhält in den onSuccess- und onFailure-Callbacks der Methoden von + * ExternalServerAccess. Es enthält alle notwendigen Daten zum Verarbeiten. + */ +declare class ExternalServerResponse { + /** + * Liefert die abgefragte URL. + */ + getURLString(): string; + /** + * Liefert den HTTP-Statuscode der Seite. + */ + getResponseCode(): number; + /** + * Liefert ein Objekt, das die Headerdaten der Antwort enthält. + */ + getHeaderFields(): { [key: string]: string[] }; +} + +/** + * Gender repräsentiert das Geschlecht eines User. + */ +declare class Gender { + /** + * Das Geschlecht ist männlich. + */ + static readonly Male: Gender; + /** + * Das Geschlecht ist weiblich. + */ + static readonly Female: Gender; + /** + * Das Geschlecht ist nicht bekannt. + */ + static readonly Unknown: Gender; +} + +/** + * Repräsentiert eine HTML-Datei, die auf dem Server im Ordner /www liegt. + */ +declare class HTMLFile { + /** + * + */ + constructor(assetPath: string, pageData?: Json); + /** + * Liefert den Pfad, der beim Anlegen der HTMLFile-Instanz genutzt wurde. + */ + getAssetPath(): string; + /** + * Liefert die pageData, die beim Anlegen der HTMLFile-Instanz genutzt wurden. + */ + getPageData(): Json; +} + +/** + * Eine Instanz von KnuddelAccount ermöglicht den Zugriff auf die freigegebenen Knuddel + * eines bestimmten User. Knuddel können abgezogen und addiert werden. + */ +declare class KnuddelAccount { + /** + * Liefert den KnuddelAmount eines Users, + * über den die App gerade frei verfügen kann. + */ + getKnuddelAmount(): KnuddelAmount; + /** + * Liefert den KnuddelAmount aus dem KnuddelAccount, + * der bereits von der App genutzt wurde. + * Beim Auszahlen dieser Knuddel aus dem KnuddelAccount an den + * User fallen Steuern an. + */ + getKnuddelAmountUsed(): KnuddelAmount; + /** + * Liefert den KnuddelAmount aus dem KnuddelAccount, + * der noch nicht von der App genutzt wurde. + * Beim Auszahlen dieser Knuddel aus dem KnuddelAccount an den + * User fallen keine Steuern an. + */ + getKnuddelAmountUnused(): KnuddelAmount; + /** + * Liefert die Summe aller Transfers, die die App an diesen KnuddelAccount bzw. User überwiesen hat. + */ + getTotalKnuddelAmountAppToUser(): KnuddelAmount; + /** + * Liefert die Summe aller Transfers, die die App von diesem KnuddelAccount bzw. User abgebucht/erhalten hat. + */ + getTotalKnuddelAmountUserToApp(): KnuddelAmount; + /** + * Liefert die Information, ob in diesem Moment genug Knuddel verfügbar sind. + */ + hasEnough(knuddelAmount: KnuddelAmount): boolean; + /** + * Liefert den Nutzer, dem der KnuddelAccount gehört. + */ + getUser(): User; + /** + * Versucht eine bestimmte Menge Knuddel zu verwenden. Dies ist nur möglich, wenn der User auf seinem KnuddelAccount + * genug Knuddel besitzt und online im Channel ist. + * Vom KnuddelAccount des Besitzer des Channel können Knuddel auch abgebucht werden, wenn dieser nicht im Channel online ist. + * + * Ist das Event App.onBeforeKnuddelReceived implementiert, so wird diese direkt nach dem use aufgerufen, + * um zu entscheiden, ob die Knuddel angenommen werden sollen. + * + *

              Hinweis: Knuddel an einen Nutzer senden kannst du mit der Methode BotUser/transferKnuddel:method. + */ + use(knuddelAmount: KnuddelAmount, displayReasonText: string, parameters?: { transferReason?: string; onError?: (message: string) => void; onSuccess?: () => void; }): void; +} + +/** + * Eine Instanz von KnuddelAmount repräsentiert eine bestimmte Anzahl von Knuddel. + */ +declare class KnuddelAmount { + /** + * Erzeugt eine Instanz von KnuddelAmount mit der Anzahl Knuddel. + */ + constructor(knuddel: number); + /** + * Erzeugt eine Instanz von KnuddelAmount mit einer bestimmten Cent-Anzahl. + */ + static fromCents(knuddel: number): KnuddelAmount; + /** + * Erzeugt eine Instanz von KnuddelAmount mit einer bestimmten Knuddel-Anzahl. + */ + static fromKnuddel(knuddel: number): KnuddelAmount; + /** + * Liefert die Anzahl der Knuddel in KnuddelCent zurück. + */ + getKnuddelCents(): number; + /** + * Gibt den Wert der Knuddel als Zahl zurück. + */ + asNumber(): number; + /** + * Liefert eine negierte Kopie des KnuddelAmount zurück. + */ + negate(): KnuddelAmount; + /** + * Liefert die Information, ob der Knuddelwert unter 0 ist. + */ + isNegative(): boolean; +} + +/** + * Repräsentiert einen KnuddelPot. + * Ein KnuddelPot kann nur durch Factory-Methoden des KnuddelsServer erzeugt werden: + * KnuddelsServer/createKnuddelPot:method. + * + * Wird die App heruntergefahren, so werden alle KnuddelPots, die nicht gesealt sind automatisch refunded. + */ +declare class KnuddelPot { + /** + * Liefert die id des KnuddelPot. + */ + getId(): number; + /** + * Liefert den Status des KnuddelPot. + */ + getState(): KnuddelPotState; + /** + * Liefert den beim Kreieren des KnuddelPots festgelegten KnuddelAmount, den jeder Teilnehmer zahlen muss. + */ + getKnuddelAmountPerParticipant(): KnuddelAmount; + /** + * Liefert den KnuddelAmount, der bisher insgesamt in den KnuddelPot eingezahlt wurde. + */ + getKnuddelAmountTotal(): KnuddelAmount; + /** + * Liefert die Liste der Teilnehmer, die bisher in den KnuddelPot eingezahlt haben. + */ + getParticipants(): User[]; + /** + * Liefert den höchsten Multiplikator, der gültig ist. + */ + getMaxFeeMultiplier(): number; + /** + * Setzt den BotUser, der den Anteil der Einzahlungen nach dem Spiel erhält + * und den Anteil, vom Gesamtpot, den er erhalten soll. + */ + setFee(feeUser: BotUser, feeMultiplier: number): void; + /** + * Liefert den mit KnuddelPot/setFee:method gesetzten BotUser an den die Gebühr ausbezahlt wird. + */ + getFeeUser(): User; + /** + * Liefert den mit KnuddelPot/setFee:method gesetzten Multiplikator der Gebühr. + */ + getFeeMultiplier(): number; + /** + * Versiegelt den KnuddelPot, sodass keine weiteren Einzahlungen vorgenommen + * werden können und Gewinne ausgeschüttet werden können. + */ + seal(): void; + /** + * Bezahlt alle Einsätze an die Teilnehmer zurück und informiert mit dem übergeben Text über den Grund. + */ + refund(reason?: string): void; + /** + * Fügt einen Gewinner in die Liste der Gewinner hinzu. + * Der zweite Parameter ist die Gewichtung mit der ausgezahlt werden soll. + * Wird der Parameter weggelassen, so ist er automatisch 1. + */ + addWinner(user: User, weight?: number): void; + /** + * Zahlt den KnuddelPot an die mit addWinner gesetzten Gewinner aus. + */ + payout(text?: string): void; +} + +/** + * Repräsentiert den Status eines KnuddelPot. + */ +declare class KnuddelPotState { + /** + * Der KnuddelPot ist geöffnet und kann neue Teilnehmer annehmen. + */ + static readonly Open: KnuddelPotState; + /** + * Der KnuddelPot ist versiegelt und kann keine neuen Teilnehmer annehmen. + */ + static readonly Sealed: KnuddelPotState; + /** + * Der KnuddelPot ist beendet und die Knuddel bereits ausgezahlt. + */ + static readonly Closed: KnuddelPotState; +} + +/** + * Ein KnuddelTransfer ist ein Container-Objekt für die Daten, die bei einer Knuddel-Transaktion von einem User + * an eine App anfallen. + * + * Implementiert man den App-Hook onBeforeKnuddelReceived, so kann man dort entscheiden, ob man den KnuddelTransfer + * annimmt oder ablehnt. + */ +declare class KnuddelTransfer { + /** + * Liefert den User, der den KnuddelTransfer ausgelöst hat. + */ + getSender(): User; + /** + * Liefert den BotUser, der die Knuddel des KnuddelTransfer erhält, + * wenn dieser mit accept() angenommen wurde. + */ + getReceiver(): BotUser; + /** + * Liefert die Anzahl der Knuddel, die mit diesem Transfer überwiesen werden. + */ + getKnuddelAmount(): KnuddelAmount; + /** + * Liefert den Grund für den Transfer, der bei der Überweisung angegeben wurde mit + * /appknuddel BOTNICK:KNUDDEL:GRUND. + */ + getTransferReason(): string; + /** + * Lehnt die Knuddel aus dem KnuddelTransfer ab und sendet sie zurück an den Absender. + * Als Grund sieht der Absender den übergebenen reason. + * + * Diese Methode wirft eine Exception, wenn sie auf einen bereits verarbeiteten Transfer aufgerufen wird. + * Sie kann nur erfolgreich aus dem AppHook onBeforeKnuddelReceived aufgerufen werden. + * + * In der Methode onBeforeKnuddelReceived kann genau ein Aufruf einer dieser drei Methoden gemacht werden: + * KnuddelTransfer/accept:method, + * KnuddelTransfer/addToPot:method, + * KnuddelTransfer/reject:method + */ + reject(reason: string): void; + /** + * Nimmt die Knuddel aus dem KnuddelTransfer an und übergibt sie an den BotUser, + * der mit getReceiver() abgefragt werden kann. + * + * Diese Methode wirft eine Exception, wenn sie auf einen bereits verarbeiteten Transfer aufgerufen wird. + * Sie kann nur erfolgreich aus dem AppHook onBeforeKnuddelReceived aufgerufen werden. + * In der Methode onBeforeKnuddelReceived kann genau ein Aufruf einer dieser drei Methoden gemacht werden: + * + * KnuddelTransfer/accept:method, + * KnuddelTransfer/addToPot:method, + * KnuddelTransfer/reject:method + */ + accept(): void; + /** + * Liefert die Information, ob ein bestimmter KnuddelTransfer zu einem KnuddelPot hinzugefügt werden kann. + */ + canAddToPot(pot: KnuddelPot): boolean; + /** + * Nimmt die Knuddel aus dem KnuddelTransfer an und übergibt sie an den übergebenen KnuddelPot. + * + * Diese Methode funktioniert analog zu KnuddelTransfer/accept:method, nur dass die Knuddel im KnuddelPot statt beim BotUser landen. + * + * Diese Methode wirft eine Exception, wenn sie auf einen bereits verarbeiteten Transfer aufgerufen wird. + * Sie kann nur erfolgreich aus dem AppHook onBeforeKnuddelReceived aufgerufen werden. + * + * In der Methode onBeforeKnuddelReceived kann genau ein Aufruf einer dieser drei Methoden gemacht werden: + * KnuddelTransfer/accept:method, + * KnuddelTransfer/addToPot:method, + * KnuddelTransfer/reject:method + */ + addToPot(knuddelPot: KnuddelPot): void; + /** + * Liefert die Information, ob der KnuddelTransfer bereits verarbeitet wurde. + * Falls die Methode false zurückliefert muss noch entschieden werden, ob der + * KnuddelTransfer angenommen oder abgelehnt wird. + */ + isProcessed(): boolean; +} + +/** + * KnuddelTransferDisplayType repräsentiert die Art der Darstellung einer Knuddel-Überweisung. + */ +declare class KnuddelTransferDisplayType { + /** + * Nachricht wird öffentlich angezeigt. + */ + static readonly Public: KnuddelTransferDisplayType; + /** + * Nachricht wird privat angezeigt. + */ + static readonly Private: KnuddelTransferDisplayType; + /** + * Nachricht wird als /m zugestellt. + */ + static readonly Post: KnuddelTransferDisplayType; +} + +/** + * KnuddelsServer ist die 'Einstiegsklasse'. Mit den statischen Methoden des KnuddelsServer erhält man Zugriff auf viele + * Objekte und Klassen, die im Verlauf der App-Entwicklung benötigt werden. + */ +declare class KnuddelsServer { + /** + * Liefert den BotUser, der standardmäßig zur App gehört. + */ + static getDefaultBotUser(): BotUser; + /** + * Liefert die AppPersistence, mit der sich Zahlen, Strings und Javascript-Objekte langfristig und über die Session einer App hinaus gespeichert werden können. + */ + static getPersistence(): AppPersistence; + /** + * Liefert den Channel in dem die App läuft. + */ + static getChannel(): Channel; + /** + * Liefert das UserAccess-Objekt, über das + * User zugreifbar werden. + */ + static getUserAccess(): UserAccess; + /** + * Liefert ein ExternalServerAccess-Objekt, mit dem + * andere Server angesteuert werden können. + */ + static getExternalServerAccess(): ExternalServerAccess; + /** + * Aktualisiert die Liste der genutzten Hooks. Werden zur Laufzeit chatCommands oder App-Hooks (wie mayJoinChannel) dynamisch erzeugt oder gelöscht, so muss danach refreshHooks() + * aufgerufen werden, damit diese Änderung wirksam wird. + */ + static refreshHooks(): void; + /** + * Liefert den Standard-Logger für diese App. Alles, was geloggt wird, wird vom Nutzer "App-Logs" als private Nachricht zugestellt. + */ + static getDefaultLogger(): Logger; + /** + * Liefert den Pfad eines Bildes zur Integration in der eigenen App. + * Alle Bilder, die im Ordner /www in der App abgelegt werden können hier referenziert werden. + */ + static getFullImagePath(imageName: string): string; + /** + * Liefert den Pfad eines Systembildes zur Integration in der eigenen App. + * Alle Bilder, die unter http://apps4.knuddels.biz/kimg/ + * erreichbar sind können hier referenziert werden. + */ + static getFullSystemImagePath(imageName: string): string; + /** + * Liefert die Informationen über den ChatServer auf dem die App läuft. + */ + static getChatServerInfo(): ChatServerInfo; + /** + * Liefert die Informationen über den AppServer auf dem die App läuft. + */ + static getAppServerInfo(): AppServerInfo; + /** + * Liefert das AppAccess-Object. + */ + static getAppAccess(): AppAccess; + /** + * Erzeugt einen KnuddelPot. + * + * Ist ein KnuddelPot 30 Minuten nach dem Erzeugen noch nicht gesealt, + * so wird vom Server automatisch ein KnuddelPot/refund:method ausgelöst. + */ + static createKnuddelPot(knuddelAmount: KnuddelAmount, params?: { payoutTimeoutMinutes?: number; shouldSealPot?: (pot: KnuddelPot) => boolean; onPotSealed?: (pot: KnuddelPot) => void; }): KnuddelPot; + /** + * Liefert den KnuddelPot mit der angegeben id. + */ + static getKnuddelPot(id: number): (KnuddelPot|null); + /** + * Liefert alle für die App noch verwaltbaren KnuddelPot-Objekte. + */ + static getAllKnuddelPots(): KnuddelPot[]; + /** + * Liefert das ToplistAccess-Objekt, über das + * Toplisten erzeugt und verwaltet werden können. + */ + static getToplistAccess(): ToplistAccess; + /** + * Liefert das AppProfileEntryAccess-Objekt, über das + * App-Profileinträge erzeugt und verwaltet werden können. + */ + static getAppProfileEntryAccess(): AppProfileEntryAccess; +} + +/** + * Mit einer Instanz einer LoadConfiguration kann gestaltet werden, wie der Inhalt des HTML User Interface aussieht, bevor es fertig geladen ist. + */ +declare class LoadConfiguration { + /** + * Setzt die Farbe des Hintergrundes vom Loading-View, der angezeigt wird, während das HTML User Interface lädt. (standardmäßig weiß) + */ + setBackgroundColor(color: Color): void; + /** + * Setzt das Hintergrundbild vom Loading-View, das angezeigt wird, während das HTML User Interface lädt. (standardmäßig nicht gesetzt) + */ + setBackgroundImage(imageUrl: string): void; + /** + * Setzt den Text des Ladehinweiseses im Loading-View, der angezeigt wird, während das HTML User Interface lädt. (standardmäßig "Lädt...") + * Hinweis: Wird mit setLoadingIndicatorImage ein Loaading-Indicator-Bild gesetzt, so wird der mit setText gesetzte Texte ignoriert. + */ + setText(text: string): void; + /** + * Setzt ein Loading-Indicator-Bild im Loading-View, das angezeigt wird, während das HTML User Interface lädt. (standardmäßig nicht gesetzt) + * Hinweis: Wird mit setLoadingIndicatorImage ein Loaading-Indicator-Bild gesetzt, so wird der mit setText gesetzte Texte ignoriert. + */ + setLoadingIndicatorImage(imageUrl: string): void; + /** + * Setzt die Farbe des Textes im Loading-View, der angezeigt wird, während das HTML User Interface lädt. (standardmäßig schwarz) + */ + setForegroundColor(color: Color): void; + /** + * Aktiviert/Deaktiviert die Nutzung vom Loading-View. (standardmäßig aktiviert) + * Es kann sinnvoll sein, den Loading-View zu deaktivieren, wenn man selbst einen komplett eigenen Loading-View in seine App einbauen möchte. + */ + setEnabled(enabled: boolean): void; +} + +/** + * Eine Instanz eines Logger ermöglicht das Loggen von Inhalten. + * + * Diese erhält man über das KnuddelsServer-Objekt + * mit KnuddelsServer.getDefaultLogger() + * + * Die Log-Einträge werden je nach Einstellungen im /apps-Fenster an den Besitzer des Channels, + * die App-Manager und den App-Entwickler zugestellt. + */ +declare class Logger { + /** + * Logge einen Text mit Level DEBUG. Dieser wird im Chat allen dafür registrierten AppManagern per /p vom App-Logs-User zugestellt. Siehe: /apps, Tab: Logs. + * + * Die Methode erwartet beliebig viele Strings als Parameter. Diese werden vor dem Logging mit einem Leerzeichen gejoint. + */ + debug(...msg: any[]): void; + /** + * Logge einen Text mit Level INFO. Dieser wird im Chat allen dafür registrierten AppManagern per /p vom App-Logs-User zugestellt. Siehe: /apps, Tab: Logs. + * + * Die Methode erwartet beliebig viele Strings als Parameter. Diese werden vor dem Logging mit einem Leerzeichen gejoint. + */ + info(...msg: any[]): void; + /** + * Logge einen Text mit Level WARN. Dieser wird im Chat allen dafür registrierten AppManagern per /p vom App-Logs-User zugestellt, sowie im /apps Fenster im Log angezeigt. Siehe: /apps, Tab: Logs. + * + * Die Methode erwartet beliebig viele Strings als Parameter. Diese werden vor dem Logging mit einem Leerzeichen gejoint. + */ + warn(...msg: any[]): void; + /** + * Logge einen Text mit Level ERROR. Dieser wird im Chat allen dafür registrierten AppManagern per /p vom App-Logs-User zugestellt, sowie im /apps Fenster im Log angezeigt. Siehe: /apps, Tab: Logs. + * + * Die Methode erwartet beliebig viele Strings als Parameter. Diese werden vor dem Logging mit einem Leerzeichen gejoint. + */ + error(...msg: any[]): void; + /** + * Logge einen Text mit Level FATAL. Dieser wird im Chat allen dafür registrierten AppManagern per /p vom App-Logs-User zugestellt, sowie im /apps Fenster im Log angezeigt. Siehe: /apps, Tab: Logs. + * + * Die Methode erwartet beliebig viele Strings als Parameter. Diese werden vor dem Logging mit einem Leerzeichen gejoint. + */ + fatal(...msg: any[]): void; +} + +/** + * Message ist eine abstrakte Klasse und repräsentiert eine Nachricht im Chat. + */ +declare class Message { + /** + * Liefert den User, der die Nachricht verfasst hat. + */ + getAuthor(): User; + /** + * Liefert den Inhalt der Nachricht. + */ + getText(): string; + /** + * Liefert den genauen Zeitpunkt, zu dem die Nachricht erstellt wurde. + */ + getCreationDate(): Date; +} + +/** + * Repräsentiert die Instanz der konkreten App, auf die dieser Code Zugriff hat. + * + * Die Instanz von OwnAppInstance erhält man über das AppAccess-Objekt + * mit appAccess.getOwnInstance() + */ +declare class OwnAppInstance { + /** + * Gibt Zugriff auf Nutzer, die gerade im Channel dieser AppInstance online sind. + * @since AppServer 82560 + */ + getOnlineUsers(otherAppInstance: AppInstance, ...userType: UserType[]): User[]; +} + +/** + * Eine Instanz von Persistence ermöglicht die persistente Speicherung von Zahlen, Zeichenketten und JSON-Objekten. + * Es gibt die zwei Arten AppPersistence und UserPersistence + * + * Jeder eigene Datentyp hat seinen eigenen Namensraum. + * So kann derselbe key für eine Zahl, Zeichenkette und auch JSON-Objekt genutzt werden. + * + *

              Hinweis: Mit der Persistence gespeicherte Informationen überleben + * sogar die Deinstallation und Neuinstallation der App. + */ +declare class Persistence { + /** + * Informiert darüber, ob unter dem key ein String abgespeichert ist. + */ + hasString(key: string): boolean; + /** + * Setzt die Zeichenkette value für den key. + * Falls bereits eine Zeichenkette für den key existiert, so wird diese überschrieben. + */ + setString(key: string, value: string): void; + /** + * Liefert die Zeichenkette, die für den key gespeichert ist. + * Falls für key keine Zeichenkette gespeichert ist, so gibt die Methode + * den defaultValue zurück. + */ + getString(key: string, defaultValue?: string): string; + /** + * Löscht die Zeichenkette, die unter key gespeichert ist. + */ + deleteString(key: string): void; + /** + * Informiert darüber, ob unter dem key eine Zahl abgespeichert ist. + */ + hasNumber(key: string): boolean; + /** + * Setzt die Zahl value für den key. + * Falls bereits eine Zahl für den key existiert, so wird diese überschrieben. + */ + setNumber(key: string, value: number): void; + /** + * Addiert den übergebenen value auf die unter dem Key key vorhandenen Wert drauf. + * Value kann auch negativ sein um eine Subtraktion durchzuführen. + * Falls keine Zahl für den key existiert, so wird der value für key gespeichert. + */ + addNumber(key: string, value: number): number; + /** + * Liefert die Zahl, die für den key gespeichert ist. + * Falls für key keine Zahl gespeichert ist, so gibt die Methode + * den defaultValue zurück. + */ + getNumber(key: string, defaultValue?: number): number; + /** + * Löscht die Zahl, die unter key gespeichert ist. + */ + deleteNumber(key: string): void; + /** + * Informiert darüber, ob unter dem key ein Objekt abgespeichert ist. + */ + hasObject(key: string): boolean; + /** + * Setzt das Objekt value für den key. + * Falls bereits ein Objekt für den key existiert, so wird dieses überschrieben. + * Das als JSON serialisierte Objekt darf maximal 100kb groß sein. + */ + setObject(key: string, object: (KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable)): void; + /** + * Liefert das Objekt, das für den key gespeichert ist. + * Falls für key kein Objekt gespeichert ist, so gibt die Methode + * den defaultValue zurück. + */ + getObject(key: string, defaultValue?: (KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable)): (KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable); + /** + * Löscht das Objekt, das unter key gespeichert ist. + */ + deleteObject(key: string): void; +} + +/** + * Eine Instanz von PrivateMessage repräsentiert eine private Nachricht im Chat. + * Die App erhält sämtliche private Nachrichten, die an einen ihrer BotUser + * geschickt werden. + * + *

              Hinweis: Eine App hat keinen Zugriff auf private Nachrichten, + * die Nutzer untereinander schreiben, ohne dass ein BotUser als Empfänger involviert ist. + */ +declare class PrivateMessage extends Message { + /** + * Liefert die Liste der Empfänger der Nachricht. + */ + getReceivingUsers(): User[]; + /** + * Sendet eine private Nachricht an alle Beteiligten des Gespräches. + */ + sendReply(text: string): void; +} + +/** + * Eine Instanz von PublicActionMessage repräsentiert eine öffentliche Handlung im Chat. + * Die App erhält die öffentlichen Handlungen. + */ +declare class PublicActionMessage extends Message { +} + +/** + * Eine Instanz von PublicEventMessage repräsentiert ein öffentliches Event im Chat. + * Die App erhält die öffentlichen Events. + */ +declare class PublicEventMessage extends Message { +} + +/** + * Eine Instanz von PublicMessage repräsentiert eine öffentliche Nachricht im Chat. + * Die App erhält die öffentlichen Nachrichten, die geschrieben werden. + */ +declare class PublicMessage extends Message { +} + +/** + * Eine Quest ist eine konkrete Aufgabe, die ein User in der App zu erledigen hat. + * + * Im Blog findest du Informationen darüber, wie man eine Quest für seine App erhält: + * https://blog.developer.knuddels.de/2015/10/29/how-to-get-a-quest/ + */ +declare class Quest { + /** + * Löst ein Quest-Event aus. + * @since AppServer 82290, ChatServer 82290 + */ + setSolved(count?: number): void; + /** + * Liefert den Key der Quest. + * @since AppServer 82290, ChatServer 82290 + */ + getQuestKey(): string; +} + +/** + * Ein QuestAccess-Objekt ermöglicht den Zugriff auf die Quests, die ein Nutzer des Chats, für die laufende App hat. + * + * Im Blog findest du Informationen darüber, wie man eine Quest für seine App erhält: + * https://blog.knuddels.de/2015/10/29/how-to-get-a-quest/ + */ +declare class QuestAccess { + /** + * Liefert die Quests + * für diesen Nutzer in dieser App. + * @since AppServer 82290, ChatServer 82290 + */ + getQuests(): Quest[]; + /** + * Liefert die Information, ob eine bestimmte Quest offen ist. + * @since AppServer 82290, ChatServer 82290 + */ + hasQuest(questKey: string): boolean; + /** + * Liefert eine bestimmte Quest, falls vorhanden. + * @since AppServer 82290, ChatServer 82290 + */ + getQuest(questKey: string): (Quest|null); + /** + * Liefert den User, der zu diesem QuestAccess-Objekt gehört. + * @since AppServer 82290, ChatServer 82290 + */ + getUser(): User; +} + +/** + * RandomOperations bietet eine Sammlung verschiedener Zufallsoperationen, die man für Glücksspiele und Ähnliches nutzen kann. + */ +declare class RandomOperations { + /** + * Liefert eine Zufallszahl zwischen minValue (inklusiv) und maxValue (exklusiv). + */ + static nextInt(minValue: number /* optional */, maxValue: number): number; + /** + * Liefert ein Array mit Zufallszahlen zwischen minValue (inklusiv) und n (exklusiv). + */ + static nextInts(minValue: number /* optional */, maxValue: number, count: number, onlyDifferentNumbers: boolean): number[]; + /** + * Liefert true in truePropability/1 Fällen + */ + static flipTrue(truePropability: number): boolean; + /** + * Liefert ein zufälliges Objekt aus einem Array. + * Falls das Array leer ist, wird null zurückgeliefert. + */ + static getRandomObject(objects: T[]): T; + /** + * Mischt das Array der übergebenen Objekte und liefert es zurück. + */ + static shuffleObjects(objects: T[]): T[]; + /** + * Liefert einen zufälligen String zurück. + * @since AppServer 92699 + */ + static getRandomString(length: number, allowedCharacters?: string): string; +} + +/** + * Repräsentiert die Root-Instanz einer App, die im Hauptchannel läuft. + * + * Die Instanz für die RootAppInstance erhält man über das AppInstance-Objekt + * mit appInstance.getRootInstance() + */ +declare class RootAppInstance extends AppInstance { + /** + * Aktualisiert diese App im Channel (und ggf. vorhandenen Tochterchanneln) auf die neueste Version. + */ + updateApp(message: string /* optional */, logMessage?: string): void; + /** + * Stoppt diese App. + */ + stopApp(message: string /* optional */, logMessage?: string): void; +} + +/** + * Liefert Informationen über einen Server. + */ +declare class ServerInfo { + /** + * Liefert die interne ServerId des Servers. + */ + getServerId(): string; + /** + * Liefert die Code-Revision des Servers. + */ + getRevision(): number; +} + +/** + * Ein SingleDiceResult enthält das Ergebnis aller Würfel desselben Typs. + * Würfelt man beispielsweise mit der Konfiguration "1w2 + 10w5" so gibt es im DiceResult + * zwei SingleDiceResult-Objekte. Eines für "1w2" und eines für "10w5". + */ +declare class SingleDiceResult { + /** + * Liefert den Würfel zurück, durch den dieses SingleDiceResult erzeugt wurde. + */ + getDice(): Dice; + /** + * Liefert die Ziffern, die gewürfelt wurden. + */ + valuesRolled(): number[]; + /** + * Liefert die Summe der Augenzahlen des SingleDiceResult. + */ + sum(): number; +} + +/** + * Diese Dokumentation beschreibt, welche Erweiterungen am serverseitigen String-Objekt vorgenommen wurden. + */ +declare interface String { + /** + * Die Methode liefert den String zurück, auf dem sie aufgerufen wurde mit KCode escaped. + */ + escapeKCode(): string; + /** + * Entfernt jeglichen KCode aus dem String und gibt ihn zurück. + */ + stripKCode(): string; + /** + * Diese Methode liefert die Information, ob der String auf dem die Methode aufgerufen wurde + * mit einem bestimmten Prefix beginnt. + */ + startsWith(prefix: string): boolean; + /** + * Diese Methode liefert die Information, ob der String auf dem die Methode aufgerufen wurde + * mit einem bestimmten Suffix endet. + */ + endsWith(suffix: string): boolean; + /** + * Liefert die Breite des Strings in der Schriftart Arial mit der gegeben Schriftgröße und Information, ob Text fett dargestellt werden soll. + */ + getPixelWidth(fontSize: number, isBold: boolean): number; + /** + * Liefert einen String, der in der Schriftart Arial mit der gegeben Schriftgröße und Information, ob Text fett dargestellt werden soll + * maximal maxPixelWidth breit ist. Wird der Text dafür gekürzt, so wird an das Ende abbreviationMarker angehangen. + * Falls abbreviationMarker nicht übergeben wurde, so ist es automatisch '...'. + */ + limitString(fontSize: number, isBold: boolean, maxPixelWidth: number, abbreviationMarker?: string): string; + /** + * Liefert die Information, ob ein bestimmter String in diesem String vorhanden ist. + */ + contains(needle: string): boolean; + /** + * Liefert die Levenshtein-Distanz zum übergebenen String. + * Levenshtein-Distanz: Minimale Anzahl von Einfüge-, Lösch- und Ersetz-Operationen, um die erste Zeichenkette in die zweite umzuwandeln. + * @since AppServer 82271 + */ + minimalConversionCost(otherString: string): number; + /** + * Liefert die Information, ob der String nur aus Zeichen besteht, die in einem Nicknamen + * vorkommen dürfen. + * @since AppServer 82271 + */ + hasOnlyNicknameCharacters(): boolean; + /** + * Liefert die Information, ob der String nur aus Zeichen besteht, die Nummern sind. + * @since AppServer 82271 + */ + hasOnlyDigits(): boolean; + /** + * Liefert die Information, ob der String nur aus Zeichen besteht, die alphanumerisch + Whitespaces sind. + * @since AppServer 82271 + */ + hasOnlyAlphanumericalAndWhitespaceCharacters(): boolean; + /** + * Liefert die Information, ob der String leer oder null ist. + * @since AppServer 92695 + */ + isEmpty(): boolean; + /** + * Liefert den String in CamelCase. + * @since AppServer 92695 + */ + toCamelCase(): string; + /** + * Liefert den String mit dem ersten Buchstaben als Großbuchstaben. + * @since AppServer 92695 + */ + capitalize(): string; + /** + * Erstellt eine Kopie des String, in dem alle Vorkommnisse des String search in replacement + * ersetzt werden und liefert diesen zurück. + */ + replaceAll(search: string | RegExp, replacement: string): string; + /** + * Prüft primitiv, ob der String laut Knuddels-Filterregeln ok ist. + * @since ChatServer 82262, AppServer 82262 + */ + isOk(): boolean; +} + +/** + * Eine Instanz einer Toplist repräsentiert eine eigene Topliste für einen bestimmten userPersistenceNumberKey. + */ +declare class Toplist { + /** + * Liefert den userPersistenceNumberKey mit dem die Topliste erzeugt wurde. + */ + getUserPersistenceNumberKey(): string; + /** + * Liefert den Anzeigenamen der Topliste. + */ + getDisplayName(): string; + /** + * Liefert den Befehl, der im Chat eingegeben werden kann, um diese Topliste zu öffnen. + * Wird ein User oder eine userId übergeben, so öffnet sich die Topliste mit diesem Nutzer im Fokus. + */ + getChatCommand(user_or_userId?: (User|number)): string; + /** + * Liefert den Anzeigenamen für den übergebenen User oder eine userId. + */ + getLabel(user_or_userId: (User|number)): string; + /** + * Legt einen Change-Listener an, der jedes mal aufgerufen wird, wenn ein User + * einen neuen Anzeigenamen erhält. + */ + addLabelChangeListener(listener: (labelChangeEvent: ToplistLabelChangeEvent) => void): void; + /** + * Löscht einen LabelChangeListener, der mit Toplist/addLabelChangeListener:method erzeugt wurde. + */ + removeLabelChangeListener(listener: (labelChangeEvent: ToplistLabelChangeEvent) => void): void; + /** + * Legt einen Change-Listener an, der jedes mal aufgerufen wird, wenn ein sich der Rang User eines Nutzers ändert. + */ + addRankChangeListener(listener: (rankChangeEvent: ToplistRankChangeEvent) => void): void; + /** + * Löscht einen RankChangeListener, der mit Toplist/addRankChangeListener:method erzeugt wurde. + */ + removeRankChangeListener(listener: (rankChangeEvent: ToplistRankChangeEvent) => void): void; +} + +/** + * Mit einer Instanz von ToplistAccess kann eine App + * Toplist erzeugen und verwalten. + * + * Die Instanz für die ToplistAccess erhält man über das KnuddelsServer-Objekt + * mit KnuddelsServer.getToplistAccess() + */ +declare class ToplistAccess { + /** + * Liefert die Liste aller Toplisten, die diese App erzeugt hat. + */ + getAllToplists(): Toplist[]; + /** + * Liefert die Toplist mit dem Persistenz-Key zurück. + */ + getToplist(userPersistenceNumberKey: string): Toplist; + /** + * Löscht die übergebene Toplist oder die Toplist mit dem Persistenz-Key. + */ + removeToplist(toplist: Toplist): void; + /** + * Erzeugt oder aktualisiert die Toplist für den übergebenen userPersistenceNumberKey. + */ + createOrUpdateToplist(userPersistenceNumberKey: string, displayName: string, parameters?: { labelMapping?: { [minValue: string]: string }; ascending?: boolean; }): Toplist; +} + +/** + * ToplistDisplayType repräsentiert den Anzeigetyp eines Toplisteneintrags im Profil vonUsern. + */ +declare class ToplistDisplayType { + /** + * Nur Anzeigename anzeigen. + */ + static readonly Label: ToplistDisplayType; + /** + * Gespeicherten Wert anzeigen. + */ + static readonly Value: ToplistDisplayType; + /** + * Anzeigename und Rang anzeigen. + */ + static readonly LabelAndRank: ToplistDisplayType; + /** + * Wert und Rang anzeigen. + */ + static readonly ValueAndRank: ToplistDisplayType; +} + +/** + * ToplistLabelChangeEvents erhalten EventListener die bei einer + * Toplist mit der Methode Toplist/addLabelChangeListener:method + * erzeugt wurden, nachdem sich der Anzeigename für einen User geändert hat. + * + * Das ToplistLabelChangeEvent enthält alle wichtigen Daten, um auf die Änderung zu reagieren + * und dem User beispielsweise für den Aufstieg zu gratulieren. + */ +declare class ToplistLabelChangeEvent { + /** + * Liefert die zugehörige Toplist. + */ + getToplist(): Toplist; + /** + * Liefert den vorherigen Anzeigenamen. Hatte der User vorher keinen + * Anzeigenamen, so ist dieser Wert null. + */ + getOldLabel(): string; + /** + * Liefert den neuen Anzeigenamen. Hatte der User nun keinen + * Anzeigenamen mehr, so ist dieser Wert null. + */ + getNewLabel(): string; + /** + * Liefert den User für den das Event ausgelöst wurde. + */ + getUser(): User; + /** + * Liefert den Wert, der vor der Änderung gespeichert war. + */ + getOldValue(): number; + /** + * Liefert den neuen Wert. + */ + getNewValue(): number; +} + +/** + * ToplistRankChangeEvents erhalten EventListener die bei einer + * Toplist mit der Methode Toplist/addRankChangeListener:method + * erzeugt wurden, nachdem sich der Rang für einen User geändert hat. + * + * Das ToplistRankChangeEvent enthält alle wichtigen Daten, um auf die Änderung zu reagieren + * und den überholten Usern eine Nachricht zu senden. + */ +declare class ToplistRankChangeEvent { + /** + * Liefert die zugehörige Toplist. + */ + getToplist(): Toplist; + /** + * Liefert den Toplisten-Rang, den der User vor der Änderung hatte. + */ + getOldRank(): number; + /** + * Liefert den neuen Toplisten-Rang, des Users. + */ + getNewRank(): number; + /** + * Liefert den User für den das Event ausgelöst wurde. + */ + getUser(): User; + /** + * Liefert die User, die bei dieser Änderung überholt worden sind. + *

              Achtung: Wenn mehr als 10 User + * überholt wurden, so liefert die Methode die besten 10 überholten User. + */ + getUsersOvertook(): User[]; + /** + * Liefert den Wert, der vor der Änderung gespeichert war. + */ + getOldValue(): number; + /** + * Liefert den neuen Wert. + */ + getNewValue(): number; +} + +/** + * Ein User ist ein Nutzer des Chats, in dem die App läuft. + */ +declare class User { + /** + * Liefert die eindeutige Nutzerkennung des Nutzers. + */ + getUserId(): number; + /** + * Liefert den Nicknamen des Nutzers. + */ + getNick(): string; + /** + * Liefert das Alter des Nutzers. Bei Nutzern, die bereits sehr lange in der Plattform sind kann es vorkommen, dass kein Alter angegeben wurde. In diesem Fall ist das Alter 0. + */ + getAge(): number; + /** + * Liefert das Geschlecht des Nutzers. + */ + getGender(): Gender; + /** + * Liefert den Zeitpunkt der Registrierung des Nutzers. + */ + getRegDate(): Date; + /** + * Liefert den UserStatus des Nutzers. + */ + getUserStatus(): UserStatus; + /** + * Liefert den UserType des Nutzers. + */ + getUserType(): UserType; + /** + * Liefert den aktuellen ClientType des Nutzers oder Offline wenn er nicht im Chat online ist. + */ + getClientType(): ClientType; + /** + * Prüft ob der Client des Users den übergebenen AppViewMode (für User/sendAppContent:method) anzeigen kann. + */ + canShowAppViewMode(mode: AppViewMode): boolean; + /** + * Prüft ob der Client des User's den übergebenen AppContent anzeigen kann. + */ + canSendAppContent(appContent: AppContent): boolean; + /** + * Prüft, ob der User in dem angegebenen Team ist. + * Dies funktioniert derzeit nur für Teams, die eine eigene /fa haben. + * + * Achtung: Bei Nutzern, die neu in ein Team kommen, funktioniert die Abfrage erst dann korrekt, + * wenn er sich neu in den Channel eingeloggt hat. + */ + isInTeam(teamName: string, subTeamName?: string): boolean; + /** + * Liefert ein UserPersistence-Objekt für diesen Nutzer. Mit diesem Objekt kann eine App sich Dinge über diesen speziellen Nutzer merken. + */ + getPersistence(): UserPersistence; + /** + * Shortcut-Funktion um mit dem DefaultBotUser eine private Nachricht zu versenden. + */ + sendPrivateMessage(message: string): void; + /** + * Shortcut-Funktion um mit dem DefaultBotUser eine /m zu versenden. + */ + sendPostMessage(topic: string, text: string): void; + /** + * Liefert die Information, ob dieser Nutzer Channelbesitzer im Channel der App ist. + */ + isChannelOwner(): boolean; + /** + * Liefert die Information, ob der Channel der App + * ein Lieblingschannel des Nutzers ist. + */ + isLikingChannel(): boolean; + /** + * Liefert die Information, ob der Nutzer im harten Kern des Channels der App ist. + * @since AppServer 92701, ChatServer 92701 + */ + isChannelCoreUser(): boolean; + /** + * Liefert die Information, ob dieser Nutzer ein AppManager für diese App ist. Die Channelbesitzer zählen automatisch auch als AppManager. + */ + isAppManager(): boolean; + /** + * Liefert Information, ob dieser Nutzer derzeit für das Schreiben öffentlicher Nachrichten im Channel gesperrt ist. + */ + isMuted(): boolean; + /** + * Liefert Information, ob dieser Nutzer beim Schreiben öffentlicher Nachrichten im Channel + * derzeit für die Verwendung von Textformatierungen, Farben und Smileys gesperrt ist. + */ + isColorMuted(): boolean; + /** + * Liefert Information, ob dieser Nutzer derzeit für das Betreten des Channel gesperrt ist. + */ + isLocked(): boolean; + /** + * Liefert Information, ob dieser Nutzer Channelmoderator im Channel der App ist. + */ + isChannelModerator(): boolean; + /** + * Liefert Information, ob dieser Nutzer Eventmoderator im Channel der App ist. + */ + isEventModerator(): boolean; + /** + * Liefert Information, ob dieser Nutzers der Entwickler der App ist. + */ + isAppDeveloper(): boolean; + /** + * Liefert einen Link zum Profil des Nutzers, den man im Chat anzeigen kann. + */ + getProfileLink(displayText?: string): string; + /** + * Liefert die Information, ob der Nutzer online im Channel der App ist. + */ + isOnlineInChannel(): boolean; + /** + * Liefert die Anzahl der Knuddel, die der Nutzer besitzt. + */ + getKnuddelAmount(): KnuddelAmount; + /** + * Liefert die Information, ob der Nutzer irgendwo im Chat online ist. + */ + isOnline(): boolean; + /** + * Liefert die Readme des Nutzers, die er mit /readme TEXT in sein Profil gesetzt hat. + */ + getReadme(): string; + /** + * Liefert die vom Nutzer verbrachte Zeit im gesamten Chatsystem In Minuten. + * Hinweis: Die Minutenzahl wird derzeit immer nur zu dem Zeitpunkt aktualisiert, + * wenn der Nutzer offline geht. + */ + getOnlineMinutes(): number; + /** + * Liefert die Information, ob der Nutzer sich mittels /away-Funktion kurz abgemeldet hat. + */ + isAway(): boolean; + /** + * Liefert die Information, ob der Nutzer ein Profilfoto hat. + */ + hasProfilePhoto(): boolean; + /** + * (Er)setzt den übergebenen AppContent beim Nutzer. + */ + sendAppContent(appContent: AppContent): AppContentSession; + /** + * Liefert alle AppContentSession, die der User + * aktuell geöffnet hat. + */ + getAppContentSessions(): AppContentSession[]; + /** + * Liefert die AppContentSession, die der User + * mit einem bestimmten AppViewMode aktuell geöffnet hat. + */ + getAppContentSession(appViewMode: AppViewMode): AppContentSession; + /** + * Vergleicht den übergebenen Nutzer und liefert true, falls der übergebene Nutzer + * identisch ist mit dem aktuellen Nutzer. + */ + equals(user: User): boolean; + /** + * Liefert die URL zum Profilfoto des Nutzers. Die übergebene Breite und Höhe + * liefern dem Server einen Anhaltswert, um das bestmögliche Foto zu finden, + * sind aber keine Garantie, dass das Foto diese Ausmaße haben wird. + */ + getProfilePhoto(width: number, height: number): string; + /** + * Liefert das QuestAccess-Objekt + * für diesen Nutzer in dieser App. + * @since AppServer 82290, ChatServer 82290 + */ + getQuestAccess(): QuestAccess; + /** + * Liefert die Information, ob der Nutzer gerade sein Video streamt. + */ + isStreamingVideo(): boolean; + /** + * Liefert den KnuddelAccount des Nutzers. + */ + getKnuddelAccount(): KnuddelAccount; + /** + * Liefert die ChannelTalkPermission für diesen Nutzer in diesem + * Channel. + */ + getChannelTalkPermission(): ChannelTalkPermission; + /** + * Liefert die Information, ob der User ein verifiziertes Profilbild hat. + */ + isProfilePhotoVerified(): boolean; + /** + * Liefert die Information, ob das Alter des Users verifiziert ist. + */ + isAgeVerified(): boolean; + /** + * Setzt dem Nutzer ein Icon in die Nickliste, das auf der rechten Seite seines Nicks angezeigt wird. + * Der Eintrag wird automatisch entfernt, sobald der Nutzer den Channel verlässt, + * kann aber auch mit User/removeNicklistIcon:method + * entfernt werden. + */ + addNicklistIcon(imagePath: string, imageWidth: number): void; + /** + * Entfernt dem Nutzer ein über die API gesetztes Icon in die Nickliste. + */ + removeNicklistIcon(imagePath: string): void; + /** + * Startet einen Würfelwurf für den Nutzer, falls er online im Channel ist und er nicht gemuted ist. + * @since AppServer 89159, ChatServer 89159 + */ + triggerDice(diceConfiguration: DiceConfiguration): void; +} + +/** + * Mit einer Instanz von UserAccess kann eine App + * auf User zugreifen, die bereits einmal im Channel waren, + * als die App lief. Für alle nicht zugreifbaren User kann man via UserAccess den korrekt geschriebenen Nicknamen erhalten. + * + * Die Instanz für die UserAccess erhält man über das KnuddelsServer-Objekt + * mit KnuddelsServer.getUserAccess() + */ +declare class UserAccess { + /** + * Liefert die userId des Nutzers mit dem übergebenen Nicknamen. + */ + getUserId(nick: string): number; + /** + * Informiert darüber, ob ein Nutzer mit dem übergebenen Nicknamen existiert. + */ + exists(nick: string): boolean; + /** + * Informiert darüber, ob der Nutzer mit der übergebenen userId geladen werden darf. Neben dem AppDeveloper können nur Nutzer geladen werden, die sich einmal im Channel befanden, als die App + * lief. + */ + mayAccess(userId: number): boolean; + /** + * Liefert den Nutzer mit der übergebenen userId. Neben dem AppDeveloper können nur Nutzer geladen werden, die sich einmal im Channel befanden, als die App lief. Es wird empfohlen vor der + * Abfrage von getUserById(userId) mit UserAccess/mayAccess:method abzufragen, ob dies funktionieren wird. + */ + getUserById(userId: number): User; + /** + * Liefert den Nicknamen des Nutzers mit der übergebenen userId in der korrekten Schreibweise. + */ + getNick(userId: number): string; + /** + * Loopt über alle zugreifbaren User sortiert nach Registrierzeitpunkt und + * führt für jeden User das übergebene Callback aus. + */ + eachAccessibleUser(callback: (user: User, index: number, accessibleUserCount: number, key?: string) => boolean, + parameters?: { onStart?: (accessibleUserCount: number, key?: string) => void; + onEnd?: (accessibleUserCount: number, key?: string) => void; }): void; +} + +/** + * Für jeden User kann eine UserPersistence angefordert werden, um sich + * für einen bestimmten Nutzer Dinge persistent zu merken. + */ +declare class UserPersistence extends Persistence { + /** + * Löscht alle Zahlenwerte, die in dieser UserPersistence gespeichert sind. + * @since AppServer 88569 + */ + deleteAllNumbers(): number; + /** + * Löscht alle Objekte, die in dieser UserPersistence gespeichert sind. + * @since AppServer 88569 + */ + deleteAllObjects(): number; + /** + * Löscht alle Zeichenketten, die in dieser UserPersistence gespeichert sind. + * @since AppServer 88569 + */ + deleteAllStrings(): number; + /** + * Löscht alle Daten, die in dieser UserPersistence gespeichert sind. + * @since AppServer 88569 + */ + deleteAll(): number; +} + +/** + * Diese Klasse repräsentiert einen Eintrag der Persistenz. + */ +declare class UserPersistenceNumberEntry { + /** + * Liefert den Nutzer. + */ + getUser(): User; + /** + * Liefert den Wert. + */ + getValue(): number; + /** + * Liefert den Rang des Elements in der Persistenz. + */ + getRank(): number; + /** + * Liefert die Position des Elements in der Persistenz. + */ + getPosition(): number; +} + +/** + * Mit dieser Klasse ist es möglich nicht User-spezifische Abfragen auf die UserPersistence auszuführen. + */ +declare class UserPersistenceNumbers { + /** + * Liefert die Summe aller via UserPersistence gespeicherten Zahlen für den übergebenen key. + */ + static getSum(key: string): number; + /** + * Löscht alle gespeicherten Zahlen-Werte für den übergebenen key. + */ + static deleteAll(key: string): number; + /** + * Liefert die Anzahl aller unterschiedlichen Nutzer, die Werte für einen bestimmten key gespeichert haben. + * Hierbei kann optional der Wertebereich über die parameters eingegrenzt werden. + */ + static getCount(key: string, parameters?: { minimumValue?: number; maximumValue?: number; }): number; + /** + * Ändert einen bestimmten key bei allen UserPersistence. + */ + static updateKey(oldKeyName: string, newKeyName: string): number; + /** + * Ändert alle Werte für einen bestimmten key, die vorher einen bestimmten anderen Wert hatten in der UserPersistence. + *
              Hinweis: Da diese Methode ein Batch-Update ist werden keine Change-Listener (ToplistRankChangeEvent, ToplistLabelChangeEvent) ausgelöst. + */ + static updateValue(key: string, oldValue: number, newValue: number): number; + /** + * Addiert einen Wert für Einträge mit einem bestimmten key in der UserPersistence. + *
              Hinweis: Da diese Methode ein Batch-Update ist werden keine Change-Listener (ToplistRankChangeEvent, ToplistLabelChangeEvent) ausgelöst. + */ + static addNumber(key: string, value: number, parameters?: { minimumValue?: number; maximumValue?: number; targetUsers?: User[]; }): number; + /** + * Liefert ein Array mit UserPersistenceNumberEntry-Objekten für einen bestimmten key. + * Hierdurch kann beispielsweise eine blätterbare Topliste abgebildet werden. + */ + static getSortedEntries(key: string, parameters?: { ascending?: boolean; count?: number; page?: number; minimumValue?: number; maximumValue?: number; }): UserPersistenceNumberEntry[]; + /** + * Liefert ein Array mit UserPersistenceNumberEntry-Objekten für einen bestimmten key. Hierbei werden die nähesten Elemente gewählt, + * die am übergebenen User/UserId liegen. + * + * Beispiel: Der Nutzer ist in der Liste auf Position 20, dann werden die Resultate von 14-24 bei einem Count von 10 ausgegeben. + * Beispiel: Der Nutzer ist in der Liste auf Position 3, dann werden die Resultate von 1-10 bei einem Count von 10 ausgegeben. + */ + static getSortedEntriesAdjacent(key: string, user_or_userId: (User|number), parameters?: { ascending?: boolean; count?: number; }): UserPersistenceNumberEntry[]; + /** + * Liefert die absolute Position des Nutzers in der Liste. Die Position ist im Gegensatz zum Rang immer eindeutig. + * + * Bei gleichem Wert hat der Nutzer die höhere Position, der zuerst einen Eintrag in der Persistenz hatte. + * + * Mit der Methode UserPersistenceNumbers/getRank:method kann man den Rang des Nutzers herausfinden. Dieser ist identisch, wenn + * unterschiedliche Nutzer denselben Wert haben. + */ + static getPosition(key: string, user_or_userId: (User|number), parameters?: { ascending?: boolean; minimumValue?: number; }): number; + /** + * Liefert den Rang des Nutzers. Der Rang ist nicht eindeutig. Bei gleicher Punktzahl haben Nutzer denselben Rang. + * Mit der Methode UserPersistenceNumbers/getPosition:method kann man die Position eindeutige Position, statt des Ranges herausfinden. + */ + static getRank(key: string, user_or_userId: (User|number), parameters?: { ascending?: boolean; minimumValue?: number; }): number; + /** + * Ruft eine Funktion für alle Nutzer auf, die einen bestimmten key in der UserPersistence gesetzt haben. + * Hierbei greifen die übergebenen Filter. + */ + static each(key: string, callback: { user: User; value: number; index: number; totalCount: number; key: string; }, + parameters?: { ascending?: boolean; minimumValue?: number; maximumValue?: number; maximumCount?: number; + onStart?: (totalCount: number, key: string) => void; onEnd?: (totalCount: number, key: string) => void; }): void; + /** + * Liefert alle keys, die für User in der Persistence + * gespeichert wurden. + * @since AppServer 82483 + */ + static getAllKeys(filterKey?: string): string[]; +} + +/** + * Mit dieser Klasse ist es möglich nicht User-spezifische Abfragen auf die UserPersistence auszuführen. + */ +declare class UserPersistenceObjects { + /** + * Löscht alle gespeicherten Objekte für den übergebenen key. + * @since AppServer 82478 + */ + static deleteAll(key: string): number; + /** + * Liefert alle keys, die für User in der Persistence + * gespeichert wurden. + * @since AppServer 82483 + */ + static getAllKeys(filterKey?: string): string[]; +} + +/** + * Mit dieser Klasse ist es möglich nicht User-spezifische Abfragen auf die UserPersistence auszuführen. + */ +declare class UserPersistenceStrings { + /** + * Liefert die Information, ob für einen bestimmten key und value bei einem beliebigen Nutzer eine Paarung existiert. + * @since AppServer 88571 + */ + static exists(key: string, value: string, ignoreCase?: boolean): boolean; + /** + * Löscht alle gespeicherten Strings für den übergebenen key. + * @since AppServer 82478 + */ + static deleteAll(key: string): number; + /** + * Liefert alle keys, die für User in der Persistence + * gespeichert wurden. + * @since AppServer 82483 + */ + static getAllKeys(filterKey?: string): string[]; +} + +/** + * Repräsentiert den Status eines User. + */ +declare class UserStatus { + /** + * Liefert den numerischen Wert das UserStatus. + */ + getNumericStatus(): number; + /** + * Liefert die Information ob der aktuelle UserStatus mindestens so hoch ist, wie der übergebene UserStatus. + */ + isAtLeast(otherUserStatus: UserStatus): boolean; + /** + * + */ + static readonly Newbie: UserStatus; + /** + * + */ + static readonly Family: UserStatus; + /** + * + */ + static readonly Stammi: UserStatus; + /** + * + */ + static readonly HonoryMember: UserStatus; + /** + * + */ + static readonly Admin: UserStatus; + /** + * + */ + static readonly SystemBot: UserStatus; + /** + * + */ + static readonly Sysadmin: UserStatus; +} + +/** + * Repräsentiert den Typ eines User. + */ +declare class UserType { + /** + * Bot der App. + */ + static readonly AppBot: UserType; + /** + * Bot des Knuddels-Chatsystems. + */ + static readonly SystemBot: UserType; + /** + * Menschlicher User. + */ + static readonly Human: UserType; +} + +/** + * VideoChannelData hält Informationen zu laufenden Video-Streams im Channel bereit. + */ +declare class VideoChannelData { + /** + * Liefert alle User die im Channel derzeit ihr Video streamen. + */ + getStreamingVideoUsers(): User[]; +} + diff --git a/knuddels-userapps-api/knuddels-userapps-api-tests.ts b/knuddels-userapps-api/knuddels-userapps-api-tests.ts new file mode 100644 index 0000000000..1faaa193e5 --- /dev/null +++ b/knuddels-userapps-api/knuddels-userapps-api-tests.ts @@ -0,0 +1,137 @@ +/// + +class Server implements App { + + private usersPlaying: { [nick: string]: number } = {}; + private isShuttingDown: boolean = false; + + private htmlFile: HTMLFile = new HTMLFile('start.html'); + private appContent: AppContent = AppContent.overlayContent(this.htmlFile, 243, 266); + + onAppStart() { + KnuddelsServer.getChannel() + .getOnlineUsers(UserType.Human) + .forEach((user) => { + this.onUserJoined(user) + }); + }; + + onUserJoined(user: User) { + const botNick = KnuddelsServer.getDefaultBotUser() + .getNick() + .escapeKCode(); + user.sendPrivateMessage('Lust auf ne Runde Ziegenphobie? Mit nur _°BB>_h1 Knuddel|/appknuddel ' + botNick + '<°°°_ bist du dabei!'); + }; + + onUserLeft(user: User) { + if (this.usersPlaying[user.getNick()] == 1) { + KnuddelsServer.getDefaultBotUser() + .transferKnuddel(user, new KnuddelAmount(1), 'Du hast den Channel verlassen.'); + + delete this.usersPlaying[user.getNick()]; + } + }; + + onPrepareShutdown() { + if (!this.isShuttingDown) { + this.isShuttingDown = true; + + for (let key in this.usersPlaying) { + const userId = KnuddelsServer.getUserAccess() + .getUserId(key); + const user = KnuddelsServer.getUserAccess() + .getUserById(userId); + + KnuddelsServer.getDefaultBotUser() + .transferKnuddel(user, new KnuddelAmount(1), 'Die App fährt gleich herunter.'); + user.getAppContentSessions() + .forEach((session: AppContentSession) => { + session.remove(); + }); + + delete this.usersPlaying[key]; + } + } + } + + onBeforeKnuddelReceived(knuddelTransfer: KnuddelTransfer) { + const sender = knuddelTransfer.getSender(); + + if (!sender.canSendAppContent(this.appContent)) { + knuddelTransfer.reject('Sorry, mit diesem Gerät kannst du gerade nicht spielen.'); + } else if (sender.isChannelOwner() && knuddelTransfer.getKnuddelAmount() + .asNumber() != 1) { + knuddelTransfer.accept(); + } else if (this.isShuttingDown) { + knuddelTransfer.reject('Du App nimmt gerade keine neuen Spieler an.'); + } else if (this.usersPlaying[sender.getNick()]) { + knuddelTransfer.reject('Du spielst bereits.'); + } else if (knuddelTransfer.getKnuddelAmount() + .asNumber() != 1) { + const botNick = KnuddelsServer.getDefaultBotUser() + .getNick() + .escapeKCode(); + knuddelTransfer.reject('Du musst genau _°BB>_h1 Knuddel senden|/appknuddel ' + botNick + '<°°°_...'); + } else { + knuddelTransfer.accept(); + } + }; + + onKnuddelReceived(user: User, receiver: User, knuddelAmount: KnuddelAmount) { + if (knuddelAmount.asNumber() == 1) { + this.usersPlaying[user.getNick()] = 1; + user.sendAppContent(this.appContent); + } else { + user.sendPrivateMessage('Vielen Dank für die Einzahlung.'); + } + }; + + onEventReceived(user: User, key: string, data: string) { + if (key == 'selectedEntry' && this.usersPlaying[user.getNick()] == 1) { + this.usersPlaying[user.getNick()] = 2; + + setTimeout(() => { + + let doorNumber = parseInt(data[data.length - 1], 10); + + let winningDoorNumber = RandomOperations.nextInt(0, 2) + 1; + + let hasWon = winningDoorNumber == doorNumber; + + let text = hasWon + ? 'Richtig getippt' + : 'Knapp daneben'; + + user.getAppContentSession(AppViewMode.Overlay) + .getAppContent() + .sendEvent('openDoor', { + 'door': doorNumber, + 'winningDoor': winningDoorNumber, + 'text': text, + }); + + if (hasWon) { + KnuddelsServer.getDefaultBotUser() + .transferKnuddel(user, new KnuddelAmount(2), 'Richtig getippt...'); + } + + setTimeout(() => { + const botNick = KnuddelsServer.getDefaultBotUser() + .getNick() + .escapeKCode(); + user.sendPrivateMessage('Na, Lust auf _°BB>_hnoch eine Runde|/appknuddel ' + botNick + '<°°°_?'); + user.getAppContentSessions() + .forEach((session: AppContentSession) => { + session.remove(); + }); + delete this.usersPlaying[user.getNick()]; + }, 4000); + }, 1500); + } + }; + +} + +declare let App: Server; // tell the compiler that "App" will be available + +App = new Server(); diff --git a/knuddels-userapps-api/tsconfig.json b/knuddels-userapps-api/tsconfig.json new file mode 100644 index 0000000000..21fec51518 --- /dev/null +++ b/knuddels-userapps-api/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "knuddels-userapps-api-tests.ts" + ] +} \ No newline at end of file diff --git a/knuddels-userapps-api/tslint.json b/knuddels-userapps-api/tslint.json new file mode 100644 index 0000000000..785a601162 --- /dev/null +++ b/knuddels-userapps-api/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} \ No newline at end of file diff --git a/ko.plus/ko.plus-tests.ts b/ko.plus/ko.plus-tests.ts index cbb86d3122..d3472c0d82 100644 --- a/ko.plus/ko.plus-tests.ts +++ b/ko.plus/ko.plus-tests.ts @@ -1,30 +1,9 @@ - -/// - -// Tests for ko.plus.d.ts -// Project: https://github.com/stevegreatrex/ko.plus -// Definitions by: Howard Richards -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/* - Version 1.0 - initial commit - - Version 1.1 - added test for makeEditable - - Version 1.2 - amended callback on commmand.fail() method - accepts response, - status and message values - - Note: Typescript version 1.4 or higher is required for union types - and type declarations -*/ - function CommandTests() { - // initalize command with an execute method var cmd1 = ko.command(() => { return "Hello cmd1"; }); - + // initialize command and add done and fail callbacks var cmd2 = ko.command(() => { return "Hello cmd2"; @@ -56,7 +35,7 @@ function CommandTests() { // test execute the command cmd1(); - + // test properties of the commmand var isRunning = cmd1.isRunning(); var failed = cmd1.failed(); @@ -75,7 +54,7 @@ function EditableTests() { var edit3 = ko.editable({ test: true }); // with anything var edit4 = ko.editable(1); // with union types - var edit5 = ko.editable("test"); + var edit5 = ko.editable("test"); ko.editable.makeEditable(this); @@ -119,7 +98,7 @@ function EditableArrayTests() { function SortableTests() { - // sorting is added via an extender, there are no .d.ts + // sorting is added via an extender, there are no .d.ts // types for this at present var sort1 = ko.observableArray([1, 2, 3]).extend({ sortable: true }); diff --git a/koa-logger/koa-logger-tests.ts b/koa-logger/koa-logger-tests.ts index f2d17ba090..502c33255d 100644 --- a/koa-logger/koa-logger-tests.ts +++ b/koa-logger/koa-logger-tests.ts @@ -1,5 +1,3 @@ -/// - import * as koa from 'koa'; import * as logger from 'koa-logger'; diff --git a/koa/index.d.ts b/koa/index.d.ts index 99e2c04498..0fd2b73edd 100644 --- a/koa/index.d.ts +++ b/koa/index.d.ts @@ -280,34 +280,6 @@ declare interface ContextDelegatedRequest { get(field: string): string; } -declare interface BaseRequest extends ContextDelegatedRequest { - /** - * Get the charset when present or undefined. - */ - charset: string; - - /** - * Return parsed Content-Length when present. - */ - length: number; - - /** - * Return the request mime type void of - * parameters such as "charset". - */ - type: string; - - /** - * Inspect implementation. - */ - inspect(): any; - - /** - * Return JSON representation. - */ - toJSON(): any; -} - declare interface ContextDelegatedResponse { /** * Get/Set response status code. @@ -444,120 +416,14 @@ declare interface ContextDelegatedResponse { flushHeaders(): void; } -declare interface BaseResponse extends ContextDelegatedResponse { - /** - * Return the request socket. - * - * @return {Connection} - * @api public - */ - socket: Socket; - - /** - * Return response header. - */ - header: any; - - /** - * Return response header, alias as response.header - */ - headers: any; - - /** - * Check whether the response is one of the listed types. - * Pretty much the same as `this.request.is()`. - * - * @param {String|Array} types... - * @return {String|false} - * @api public - */ - // is(): string; - is(...types: string[]): string; - is(types: string[]): string; - - /** - * Return response header. - * - * Examples: - * - * this.get('Content-Type'); - * // => "text/plain" - * - * this.get('content-type'); - * // => "text/plain" - */ - get(field: string): string; - - /** - * Inspect implementation. - */ - inspect(): any; - - /** - * Return JSON representation. - */ - toJSON(): any; -} - - -declare interface BaseContext extends ContextDelegatedRequest, ContextDelegatedResponse { - /** - * util.inspect() implementation, which - * just returns the JSON output. - */ - inspect(): any; - - /** - * Return JSON representation. - * - * Here we explicitly invoke .toJSON() on each - * object, as iteration will otherwise fail due - * to the getters and cause utilities such as - * clone() to fail. - */ - toJSON(): any; - - /** - * Similar to .throw(), adds assertion. - * - * this.assert(this.user, 401, 'Please login!'); - * - * See: https://github.com/jshttp/http-assert - */ - assert: typeof httpAssert; - - /** - * Throw an error with `msg` and optional `status` - * defaulting to 500. Note that these are user-level - * errors, and the message may be exposed to the client. - * - * this.throw(403) - * this.throw('name required', 400) - * this.throw(400, 'name required') - * this.throw('something exploded') - * this.throw(new Error('invalid'), 400); - * this.throw(400, new Error('invalid')); - * - * See: https://github.com/jshttp/http-errors - */ - throw(message: string, code?: number, properties?: {}): never; - throw(status: number): never; - throw(...properties: Array): never; - - /** - * Default error handling. - */ - onerror(err: Error): void; -} - declare class Application extends EventEmitter { proxy: boolean; middleware: Application.Middleware[]; subdomainOffset: number; env: string; - context: BaseContext; - request: BaseRequest; - response: BaseResponse; + context: Application.BaseContext; + request: Application.BaseRequest; + response: Application.BaseResponse; silent: boolean; keys: Keygrip | string[]; @@ -623,6 +489,139 @@ declare class Application extends EventEmitter { declare namespace Application { type Middleware = compose.Middleware; + interface BaseRequest extends ContextDelegatedRequest { + /** + * Get the charset when present or undefined. + */ + charset: string; + + /** + * Return parsed Content-Length when present. + */ + length: number; + + /** + * Return the request mime type void of + * parameters such as "charset". + */ + type: string; + + /** + * Inspect implementation. + */ + inspect(): any; + + /** + * Return JSON representation. + */ + toJSON(): any; + } + + interface BaseResponse extends ContextDelegatedResponse { + /** + * Return the request socket. + * + * @return {Connection} + * @api public + */ + socket: Socket; + + /** + * Return response header. + */ + header: any; + + /** + * Return response header, alias as response.header + */ + headers: any; + + /** + * Check whether the response is one of the listed types. + * Pretty much the same as `this.request.is()`. + * + * @param {String|Array} types... + * @return {String|false} + * @api public + */ + // is(): string; + is(...types: string[]): string; + is(types: string[]): string; + + /** + * Return response header. + * + * Examples: + * + * this.get('Content-Type'); + * // => "text/plain" + * + * this.get('content-type'); + * // => "text/plain" + */ + get(field: string): string; + + /** + * Inspect implementation. + */ + inspect(): any; + + /** + * Return JSON representation. + */ + toJSON(): any; + } + + interface BaseContext extends ContextDelegatedRequest, ContextDelegatedResponse { + /** + * util.inspect() implementation, which + * just returns the JSON output. + */ + inspect(): any; + + /** + * Return JSON representation. + * + * Here we explicitly invoke .toJSON() on each + * object, as iteration will otherwise fail due + * to the getters and cause utilities such as + * clone() to fail. + */ + toJSON(): any; + + /** + * Similar to .throw(), adds assertion. + * + * this.assert(this.user, 401, 'Please login!'); + * + * See: https://github.com/jshttp/http-assert + */ + assert: typeof httpAssert; + + /** + * Throw an error with `msg` and optional `status` + * defaulting to 500. Note that these are user-level + * errors, and the message may be exposed to the client. + * + * this.throw(403) + * this.throw('name required', 400) + * this.throw(400, 'name required') + * this.throw('something exploded') + * this.throw(new Error('invalid'), 400); + * this.throw(400, new Error('invalid')); + * + * See: https://github.com/jshttp/http-errors + */ + throw(message: string, code?: number, properties?: {}): never; + throw(status: number): never; + throw(...properties: Array): never; + + /** + * Default error handling. + */ + onerror(err: Error): void; + } + interface Request extends BaseRequest { app: Application; req: IncomingMessage; @@ -652,6 +651,10 @@ declare namespace Application { cookies: Cookies; accept: accepts.Accepts; state: any; + /** + * To bypass Koa's built-in response handling, you may explicitly set `ctx.respond = false;` + */ + respond?: boolean; } } diff --git a/kolite/kolite-tests.ts b/kolite/kolite-tests.ts index 539c284861..2ce3cbd0f0 100644 --- a/kolite/kolite-tests.ts +++ b/kolite/kolite-tests.ts @@ -1,6 +1,3 @@ -/// -/// - function test_activityDefaults() { ko.bindingHandlers.activity.defaultOptions = { activityClass: 'fa fa-spinner fa-spin', diff --git a/kramed/index.d.ts b/kramed/index.d.ts new file mode 100644 index 0000000000..41984f9dc5 --- /dev/null +++ b/kramed/index.d.ts @@ -0,0 +1,160 @@ +// Type definitions for Kramed 0.5 +// Project: https://github.com/GitbookIO/kramed +// Definitions by: Matthew Wilkes +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface KramedStatic { + /** + * Compiles kramdown to HTML. + * + * @param src String of kramdown source to be compiled + * @param callback Function called when the kramdownString has been fully parsed when using async highlighting + * @return String of compiled HTML + */ + (src: string, callback: () => void): string; + + /** + * Compiles kramdown to HTML. + * + * @param src String of kramdown source to be compiled + * @param options Hash of options + * @param callback Function called when the kramdownString has been fully parsed when using async highlighting + * @return String of compiled HTML + */ + (src: string, options?: KramedOptions, callback?: () => void): string; + + /** + * @param src String of kramdown source to be compiled + * @param options Hash of options + */ + lexer(src: string, options?: KramedOptions): any[]; + + /** + * Compiles kramdown to HTML. + * + * @param src String of kramdown source to be compiled + * @param callback Function called when the kramdownString has been fully parsed when using async highlighting + * @return String of compiled HTML + */ + parse(src: string, callback: () => void): string; + + /** + * Compiles kramdown to HTML. + * + * @param src String of kramdown source to be compiled + * @param options Hash of options + * @param callback Function called when the kramdownString has been fully parsed when using async highlighting + * @return String of compiled HTML + */ + parse(src: string, options?: KramedOptions, callback?: () => void): string; + + /** + * @param options Hash of options + */ + parser(src: any[], options?: KramedOptions): string; + + /** + * Sets the default options. + * + * @param options Hash of options + */ + setOptions(options: KramedOptions): KramedStatic; + + Renderer: { + new(): KramedRenderer; + }; + + Parser: { + new(options: KramedOptions): KramedParser; + }; +} + +export interface KramedRenderer { + code(code: string, language: string): string; + blockquote(quote: string): string; + html(html: string): string; + heading(text: string, level: number, raw: string): string; + hr(): string; + list(body: string, ordered: boolean): string; + listitem(text: string): string; + paragraph(text: string): string; + table(header: string, body: string): string; + tablerow(content: string): string; + tablecell(content: string, flags: { + header: boolean, + align: string + }): string; + strong(text: string): string; + em(text: string): string; + codespan(code: string): string; + br(): string; + del(text: string): string; + link(href: string, title: string, text: string): string; + image(href: string, title: string, text: string): string; + text(text: string): string; +} + +export interface KramedParser { + parse(source: any[]): string; +} + +export interface KramedOptions { + /** + * Type: object Default: new Renderer() + * + * An object containing functions to render tokens to HTML. + */ + renderer?: KramedRenderer; + + /** + * Enable GitHub flavored kramdown. + */ + gfm?: boolean; + + /** + * Enable GFM tables. This option requires the gfm option to be true. + */ + tables?: boolean; + + /** + * Enable GFM line breaks. This option requires the gfm option to be true. + */ + breaks?: boolean; + + /** + * Conform to obscure parts of kramdown.pl as much as possible. Don't fix any of the original kramdown bugs or poor behavior. + */ + pedantic?: boolean; + + /** + * Sanitize the output. Ignore any HTML that has been input. + */ + sanitize?: boolean; + + /** + * Use smarter list behavior than the original kramdown. May eventually be default with the old behavior moved into pedantic. + */ + smartLists?: boolean; + + /** + * Shows an HTML error message when rendering fails. + */ + silent?: boolean; + + /** + * A function to highlight code blocks. The function takes three arguments: code, lang, and callback. + */ + highlight?(code: string, lang: string, callback?: () => void): string; + + /** + * Set the prefix for code block classes. + */ + langPrefix?: string; + + /** + * Use "smart" typograhic punctuation for things like quotes and dashes. + */ + smartypants?: boolean; +} + +export declare var kramed: KramedStatic; \ No newline at end of file diff --git a/kramed/kramed-tests.ts b/kramed/kramed-tests.ts new file mode 100644 index 0000000000..0782742234 --- /dev/null +++ b/kramed/kramed-tests.ts @@ -0,0 +1,43 @@ + +import { KramedOptions, kramed, KramedParser, KramedStatic, KramedRenderer } from 'kramed'; + +var options: KramedOptions = { + gfm: true, + tables: true, + breaks: false, + pedantic: false, + sanitize: true, + smartLists: true, + silent: false, + highlight: function (code: string, lang: string) { + return ''; + }, + langPrefix: 'lang-', + smartypants: false, + renderer: new kramed.Renderer() +}; + +function callback() { + console.log('callback called'); +} + +kramed.setOptions(options); + +console.log(kramed('i am using __kramdown__.')); +console.log(kramed('i am using __kramdown__.', options)); +console.log(kramed('i am using __kramdown__.', callback)); +console.log(kramed('i am using __kramdown__.', options, callback)); + +console.log(kramed.parse('i am using __kramdown__.')); +console.log(kramed.parse('i am using __kramdown__.', options)); +console.log(kramed.parse('i am using __kramdown__.', callback)); +console.log(kramed.parse('i am using __kramdown__.', options, callback)); + +var text = 'something'; +var tokens = kramed.lexer(text, options); +console.log(kramed.parser(tokens)); + +var renderer = new kramed.Renderer(); +renderer.heading = function(text, level, raw) { + return text + level.toString() + raw; +}; diff --git a/kramed/tsconfig.json b/kramed/tsconfig.json new file mode 100644 index 0000000000..50f51102f7 --- /dev/null +++ b/kramed/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "kramed-tests.ts" + ] +} diff --git a/kramed/tslint.json b/kramed/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/kramed/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/kue/kue-tests.ts b/kue/kue-tests.ts index a66dc4384c..aa61ff2f6a 100644 --- a/kue/kue-tests.ts +++ b/kue/kue-tests.ts @@ -1,5 +1,3 @@ -/// - import kue = require('kue'); // create our job queue diff --git a/leaflet-curve/leaflet-curve-tests.ts b/leaflet-curve/leaflet-curve-tests.ts index ec2461cbd2..3d8b319e63 100644 --- a/leaflet-curve/leaflet-curve-tests.ts +++ b/leaflet-curve/leaflet-curve-tests.ts @@ -1,5 +1,3 @@ -/// - var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', osmAttrib = '© OpenStreetMap contributors', osm = L.tileLayer(osmUrl, {maxZoom: 18, attribution: osmAttrib}), diff --git a/leaflet-draw/index.d.ts b/leaflet-draw/index.d.ts index 9668940c3a..3e2963f18b 100644 --- a/leaflet-draw/index.d.ts +++ b/leaflet-draw/index.d.ts @@ -349,4 +349,17 @@ declare namespace L { handler: string; } } + + namespace GeometryUtil { + + /** + * Returns the area of a polygon drawn with leaflet.draw + */ + export function geodesicArea(coordinates: L.LatLngLiteral[]): number; + + /** + * Returns a readable area string in yards or metric + */ + export function readableArea(area: number, isMetric: boolean): string; + } } diff --git a/leaflet-draw/leaflet-draw-tests.ts b/leaflet-draw/leaflet-draw-tests.ts index 4260eac263..8ad6e2a804 100644 --- a/leaflet-draw/leaflet-draw-tests.ts +++ b/leaflet-draw/leaflet-draw-tests.ts @@ -1,5 +1,3 @@ -/// - var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', osmAttrib = '© OpenStreetMap contributors', osm = L.tileLayer(osmUrl, {maxZoom: 18, attribution: osmAttrib}), @@ -44,3 +42,7 @@ map.on('draw:created', (e: any) => { drawnItems.addLayer(layer); }); + +let examplePolygon: L.LatLngLiteral[] = [{lng: 0, lat: 0}, {lng: 10, lat: 0}, {lng: 10, lat: 10}, {lng: 0, lat: 10}, {lng: 0, lat: 0}]; +let examplePolygonArea: number = L.GeometryUtil.geodesicArea(examplePolygon); +L.GeometryUtil.readableArea(examplePolygonArea, true); diff --git a/leaflet-markercluster/index.d.ts b/leaflet-markercluster/index.d.ts index ab8b6d9431..88fe0edd72 100644 --- a/leaflet-markercluster/index.d.ts +++ b/leaflet-markercluster/index.d.ts @@ -105,7 +105,7 @@ declare namespace L { /* * Function used to create the cluster icon */ - iconCreateFunction?: ((cluster: L.MarkerCluster) => L.Icon); + iconCreateFunction?: ((cluster: L.MarkerCluster) => L.Icon | L.DivIcon); /* * Boolean to split the addLayers processing in to small intervals so that the page does not freeze. diff --git a/leaflet-markercluster/leaflet-markercluster-tests.ts b/leaflet-markercluster/leaflet-markercluster-tests.ts index 7488a4e132..7aca02c090 100644 --- a/leaflet-markercluster/leaflet-markercluster-tests.ts +++ b/leaflet-markercluster/leaflet-markercluster-tests.ts @@ -28,6 +28,10 @@ markerClusterGroupOptions = { chunkDelay: 100 }; +markerClusterGroupOptions.iconCreateFunction = (cluster: L.MarkerCluster) => { + return L.divIcon(); +}; + let markerClusterGroup: L.MarkerClusterGroup; markerClusterGroup = L.markerClusterGroup(); markerClusterGroup = L.markerClusterGroup(markerClusterGroupOptions); diff --git a/leaflet/index.d.ts b/leaflet/index.d.ts index de463ae997..7f57c1dfd9 100644 --- a/leaflet/index.d.ts +++ b/leaflet/index.d.ts @@ -1466,7 +1466,7 @@ declare namespace L { export function divIcon(options?: DivIconOptions): DivIcon; export interface MarkerOptions extends InteractiveLayerOptions { - icon?: Icon; + icon?: Icon | DivIcon; clickable?: boolean; draggable?: boolean; keyboard?: boolean; @@ -1483,7 +1483,7 @@ declare namespace L { getLatLng(): LatLng; setLatLng(latlng: LatLngExpression): this; setZIndexOffset(offset: number): this; - setIcon(icon: Icon): this; + setIcon(icon: Icon | DivIcon): this; setOpacity(opacity: number): this; getElement(): HTMLElement; diff --git a/leaflet/leaflet-tests.ts b/leaflet/leaflet-tests.ts index cce5565851..dcdba8a6e8 100644 --- a/leaflet/leaflet-tests.ts +++ b/leaflet/leaflet-tests.ts @@ -448,6 +448,17 @@ L.marker([1, 2], { }) }).bindPopup('

              Hi

              '); +L.marker([1, 2], { + icon: L.divIcon({ + className: 'my-icon-class' + }) +}).setIcon(L.icon({ + iconUrl: 'my-icon.png' +})).setIcon(L.divIcon({ + className: 'my-div-icon' +}));; + + L.Util.extend({}); L.Util.create({}); L.Util.bind(() => {}, {}); @@ -466,3 +477,4 @@ L.Util.indexOf([], {}); L.Util.requestAnimFrame(() => {}); L.Util.cancelAnimFrame(1); L.Util.emptyImageUrl; + diff --git a/leven/index.d.ts b/leven/index.d.ts new file mode 100644 index 0000000000..baea8fa6b4 --- /dev/null +++ b/leven/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for leven 2.1 +// Project: https://github.com/sindresorhus/leven +// Definitions by: Jan Alonzo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function leven(a: string, b: string): number; + +export = leven; diff --git a/leven/leven-tests.ts b/leven/leven-tests.ts new file mode 100644 index 0000000000..4e87d3d90e --- /dev/null +++ b/leven/leven-tests.ts @@ -0,0 +1,8 @@ + +import leven = require('leven'); + +leven('baz', 'bar'); +// => "1" + +leven('foo', 'bar'); +// => "3" \ No newline at end of file diff --git a/leven/tsconfig.json b/leven/tsconfig.json new file mode 100644 index 0000000000..cddcbe652b --- /dev/null +++ b/leven/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "leven-tests.ts" + ] +} \ No newline at end of file diff --git a/leven/tslint.json b/leven/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/leven/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/libpq/index.d.ts b/libpq/index.d.ts index 1e9e38dd5c..fc502bdd74 100644 --- a/libpq/index.d.ts +++ b/libpq/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/brianc/node-libpq#readme // Definitions by: Vlad Rindevich // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/libpq/libpq-tests.ts b/libpq/libpq-tests.ts index 8a9aced3c3..5736577e67 100644 --- a/libpq/libpq-tests.ts +++ b/libpq/libpq-tests.ts @@ -1,4 +1,3 @@ -/// /// import {Buffer} from 'buffer'; diff --git a/line-by-line/index.d.ts b/line-by-line/index.d.ts new file mode 100644 index 0000000000..69fbacf728 --- /dev/null +++ b/line-by-line/index.d.ts @@ -0,0 +1,56 @@ +// Type definitions for line-by-line 0.1 +// Project: https://github.com/Osterjour/line-by-line +// Definitions by: Evgeny Tomsen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +import { EventEmitter } from "events"; + +export = LineByLineReader; + +interface LineByLineReader extends EventEmitter { + /** + * subscribe to an event emitted by reader + * @param event {@link LineByLineReaderEvent} + * @param listener A void function with one param + */ + on(event: LineByLineReaderEvent, listener: (value: any) => void): this; + /** + * Pauses the reader + */ + pause(): void; + /** + * Resumes the reader + */ + resume(): void; + /** + * Finishes the reader + */ + end(): void; + /** + * Closes the file stream + */ + close(): void; +} + +interface LineByLineReaderOptions { + encoding?: string; + skipEmptyLines?: boolean; + start?: number +} + +interface LineByLineReaderConstructor { + /** + * Constructs a new LineByLineReader object + * @param filename filename to read + * @param options Optional. {@link LineByLineReaderOptions} + */ + new (filename: string, options?: LineByLineReaderOptions): LineByLineReader; + readonly prototype: LineByLineReader; +} + +type LineByLineReaderEvent = "line" | "end" | "error"; + +declare const LineByLineReader: LineByLineReaderConstructor; \ No newline at end of file diff --git a/line-by-line/line-by-line-tests.ts b/line-by-line/line-by-line-tests.ts new file mode 100644 index 0000000000..37631beead --- /dev/null +++ b/line-by-line/line-by-line-tests.ts @@ -0,0 +1,12 @@ +import * as LineByLineReader from "line-by-line"; + +let reader: LineByLineReader = new LineByLineReader("index.d.ts"); +reader.on("line", (line: any) => { + console.log(line); +}); +reader.on("end", () => { + console.log("end"); +}); +reader.on("error", (err: any) => { + throw("Error reading file"); +}); \ No newline at end of file diff --git a/datatables-buttons/tsconfig.json b/line-by-line/tsconfig.json similarity index 92% rename from datatables-buttons/tsconfig.json rename to line-by-line/tsconfig.json index 0793cd2eb3..a0f6fb9b81 100644 --- a/datatables-buttons/tsconfig.json +++ b/line-by-line/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "datatables-buttons-tests.ts" + "line-by-line-tests.ts" ] } \ No newline at end of file diff --git a/line-by-line/tslint.json b/line-by-line/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/line-by-line/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/linq4js/index.d.ts b/linq4js/index.d.ts new file mode 100644 index 0000000000..e6b9084ea3 --- /dev/null +++ b/linq4js/index.d.ts @@ -0,0 +1,283 @@ +// Type definitions for Linq4JS 2.1 +// Project: https://github.com/morrisjdev/Linq4JS +// Definitions by: Morris Janatzek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Linq4JS { + class GeneratedEntity { + _GeneratedId_: number; + Id: number; + } +} +declare namespace Linq4JS { + class Helper { + private static ConvertStringFunction(functionString); + static ConvertFunction(testFunction: string | T): T; + static OrderCompareFunction(valueSelector: (item: T) => any, a: T, b: T, invert: boolean): number; + } +} +interface Array { + Order: Linq4JS.OrderEntry[]; + GroupValue: any; + /** + * Creates a copy of the array + */ + Clone(): T[]; + /** + * Gets the index of the first item found by a filter + * @param filter A function (or function-string) that returns a boolean when matching element was found + */ + FindIndex(filter: ((item: T) => boolean) | string): number; + /** + * Gets the index of the last item found by a filter + * @param filter A function (or function-string) that returns a boolean when matching element was found + */ + FindLastIndex(filter: ((item: T) => boolean) | string): number; + /** + * Gets the item with the index + * @param index Item index + */ + Get(index: number): T; + /** + * Executes a method for each item in the array + * @param action A function (or function-string) that gets executed for each element. If it returns false the loop stops. + */ + ForEach(action: ((item: T, index?: number) => boolean | any) | string): T[]; + /** + * Updates an object in the array + * @param object The object to update + * @param primaryKeySelector A selector-function (or function-string) to define a property to indentify object in array + */ + Update(object: T, primaryKeySelector?: ((item: T) => any) | string): T[]; + /** + * Updates objects in the array + * @param objects The array of objects to update + * @param primaryKeySelector A selector-function (or function-string) to define a property to indentify object in array + */ + UpdateRange(objects: T[], primaryKeySelector?: ((item: T) => any) | string): T[]; + /** + * Removes an object from the array + * @param object The object to remove + * @param primaryKeySelector A selector-function (or function-string) to define a property to indentify object in array + */ + Remove(object: T, primaryKeySelector?: ((item: T) => any) | string): T[]; + /** + * Removes objects from the array + * @param objects The array of objects to remove + * @param primaryKeySelector A selector-function (or function-string) to define a property to indentify object in array + */ + RemoveRange(objects: T[], primaryKeySelector?: ((item: T) => any) | string): T[]; + /** + * Adds an object to the array + * @param object The object to add + * @param generateId Auto-generate a property to identify object in later processes + */ + Add(object: T, generateId?: boolean): T[]; + /** + * Adds objects to the array + * @param objects The array of objects to add + */ + AddRange(objects: T[], generateId?: boolean): T[]; + /** + * Inserts an entry at a specific position + * @param object The object to insert + * @param index The position to insert + */ + Insert(object: T, index: number): T[]; + /** + * Searches for all items in array that match the given filter + * @param filter A function (or function-string) that returns a boolean when matching element was found + */ + Where(filter: ((item: T, index?: number) => boolean) | string): T[]; + /** + * Takes items in a specific range + * @param start The start position + * @param length The number of elements to take + */ + Range(start: number, length: number): T[]; + /** + * Repeats an object in the array + * @param object The object to repeat + * @param count The count of repeats + */ + Repeat(object: T, count: number): T[]; + /** + * Returns the length of the array + * @param filter If set the function returns count of elements matched by the condition + */ + Count(filter?: ((item: T) => boolean) | string): number; + /** + * Tests if all items in the array match the condition + * @param filter A function (or function-string) that returns a boolean when matching element was found + */ + All(filter: ((item: T) => boolean) | string): boolean; + /** + * Tests if any item is in the array + * @param filter If set the function tests if any item in the array matches the condition + */ + Any(filter?: ((item: T) => boolean) | string): boolean; + /** + * Returns the first item of the array - Throws an exception if no item was found + * @param filter If set the function returns the first item that matches the filter + */ + First(filter?: ((item: T) => boolean) | string): T; + /** + * Returns the first item of the array - returns `null` if no suitable item was found + * @param filter If set the function returns the first item that matches the filter + */ + FirstOrDefault(filter?: ((item: T) => boolean) | string): (T | null); + /** + * Returns the last item of the array - Throws an exception if no item was found + * @param filter If set the function returns the last item that matches the filter + */ + Last(filter?: ((item: T) => boolean) | string): T; + /** + * Returns the last item of the array - returns `null` if no suitable item was found + * @param filter If set the function returns the last item that matches the filter + */ + LastOrDefault(filter?: ((item: T) => boolean) | string): (T | null); + /** + * Select the properties for a new array + * @param selector A function (or a function-string) that returns a new object + */ + Select(selector: ((item: T) => any) | string): any[]; + /** + * Limits the number of entries taken + * @param count The count of elements taken + */ + Take(count: number): T[]; + /** + * Takes entries as long as a condition is true + * @param condition The condition-function (or function-string) that returns a boolean. All elements until a false gets thrown are taken + * @param initial A initial-function (or function-string) that gets executed once at the start of the loop + * @param after A function that gets executed after every element-iteration after the condition-function was evaluated + */ + TakeWhile(condition: ((item: T, storage?: any) => boolean) | string, initial?: ((storage: any) => void) | string, after?: ((item: T, storage: any) => void) | string): T[]; + /** + * Skips entries + * @param count The count of elements skipped + */ + Skip(count: number): T[]; + /** + * Orders array by property or value in ascending direction + * @param valueSelector The selector-function (or function-string) that selects the property for sorting + */ + OrderBy(valueSelector: ((item: T) => any) | string): T[]; + /** + * Orders array by additional properties in ascending direction in combination with OrderBy/OrderByDescending + * @param valueSelector The selector-function (or function-string) that selects the property for sorting + */ + ThenBy(valueSelector: ((item: T) => any) | string): T[]; + /** + * Orders array by property or value in descending direction + * @param valueSelector The selector-function (or function-string) that selects the property for sorting + */ + OrderByDescending(valueSelector: ((item: T) => any) | string): T[]; + /** + * Orders array by additional properties in descending direction in combination with OrderBy/OrderByDescending + * @param valueSelector The selector-function (or function-string) that selects the property for sorting + */ + ThenByDescending(valueSelector: ((item: T) => any) | string): T[]; + /** + * Returns the smallest element in array + * @param valueSelector The selector-function (or function-string) that selects the property for comparison + */ + Min(valueSelector?: ((item: T) => any) | string): (T | null); + /** + * Returns the greates element in array + * @param valueSelector The selector-function (or function-string) that selects the property for comparison + */ + Max(valueSelector?: ((item: T) => any) | string): (T | null); + /** + * Groups array by property + * @param selector The selector-function (or function-string) that selects the property for grouping + */ + GroupBy(selector: ((item: T) => any) | string): T[][]; + /** + * Moves an item from one index to another + * @param oldIndex The current position of the item + * @param newIndex The new position of the item + */ + Move(oldIndex: number, newIndex: number): T[]; + /** + * Makes all values unique + * @param valueSelector A selector-function (or function-string) to select property for comparison and distinction + */ + Distinct(valueSelector?: ((item: T) => any) | string): T[]; + /** + * Tests if array contains specific object + * @param object The object to test for + */ + Contains(object: T): boolean; + /** + * Combines two arrays + * @param array The array to combine + */ + Concat(array: T[]): T[]; + /** + * Combines two arrays but only applies values that are in both arrays + * @param array The array to combine + */ + Intersect(array: T[]): T[]; + /** + * Joins the entries by a given char + * @param character The character for joining + * @param selector A selector-function (or function-string) to select property for joining + */ + Join(character: string, selector?: ((item: T) => any) | string): string; + /** + * Combines the entries using a custom function + * @param method A function (or function-string) for aggregation + * @param startVal The value to start aggregation + */ + Aggregate(method: ((result: any, item: T) => any) | string, startVal?: any): string; + /** + * Reverses the array + */ + Reverse(): T[]; + /** + * Computes the average of the elements + * @param selector A selector-function (or function-string) to select property for average computing + * @param filter If set the function computes the average of elements that match the filter + */ + Average(selector?: ((item: T) => any) | string, filter?: ((item: T) => boolean) | string): number; + /** + * Computes the sum of the elements + * @param selector A selector-function (or function-string) to select property for adding + * @param filter If set the function computes the sum of elements that match the filter + */ + Sum(selector?: ((item: T) => any) | string, filter?: ((item: T) => boolean) | string): number; + /** + * Compares to sequences of objects + * @param array The array to compare + */ + SequenceEqual(array: T[]): boolean; + /** + * Combines the entries of two arrays using a custom function + * @param array The array to combine + * @param result The function (or function-string) to combine elements + */ + Zip(array: X[], result: ((first: T, second: X) => any) | string): any[]; + /** + * Combines two arrays without duplicates + * @param array The array to combine + */ + Union(array: T[]): T[]; + /** + * Converts the array to a dictionary + * @param keySelector The selector-function (or function-string) to select property for key + * @param valueSelector A selector-function (or function-string) to select property for value + */ + ToDictionary(keySelector: ((item: T) => any) | string, valueSelector?: ((item: T) => any) | string): any; +} +declare namespace Linq4JS { + class OrderEntry { + Direction: OrderDirection; + ValueSelector: (item: any) => any; + constructor(_direction: OrderDirection, _valueSelector: (item: any) => any); + } + enum OrderDirection { + Ascending = 0, + Descending = 1, + } +} diff --git a/linq4js/linq4js-tests.ts b/linq4js/linq4js-tests.ts new file mode 100644 index 0000000000..9e0bbe7be5 --- /dev/null +++ b/linq4js/linq4js-tests.ts @@ -0,0 +1,5 @@ +import "linq4js"; + +let array: Array = ["test", "test2", "test3", "test4", "test5"]; + +array.Add("test6").Remove("test3").Insert("test3", 2).Distinct().OrderBy(x => x).OrderByDescending(x => x).Select(x => x.length).Average(); \ No newline at end of file diff --git a/linq4js/tsconfig.json b/linq4js/tsconfig.json new file mode 100644 index 0000000000..f053fa2e23 --- /dev/null +++ b/linq4js/tsconfig.json @@ -0,0 +1,24 @@ +{ + "files": [ + "index.d.ts", + "linq4js-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "noImplicitAny": true, + "noImplicitReturns": true, + "noImplicitThis": true, + "strictNullChecks": true, + "target": "es6", + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "lib":[ + "es6" + ], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} \ No newline at end of file diff --git a/linq4js/tslint.json b/linq4js/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/linq4js/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/lodash/index.d.ts b/lodash/index.d.ts index 4671a672f3..da5710a7de 100644 --- a/lodash/index.d.ts +++ b/lodash/index.d.ts @@ -6707,7 +6707,7 @@ declare namespace _ { */ filter( collection: List|Dictionary, - predicate: string + predicate: string|RegExp ): T[]; /** @@ -6740,7 +6740,7 @@ declare namespace _ { * @see _.filter */ filter( - predicate: string + predicate: string|RegExp ): LoDashImplicitArrayWrapper; /** @@ -6761,7 +6761,7 @@ declare namespace _ { * @see _.filter */ filter( - predicate: string + predicate: string|RegExp ): LoDashImplicitArrayWrapper; /** @@ -6791,7 +6791,7 @@ declare namespace _ { * @see _.filter */ filter( - predicate: string + predicate: string|RegExp ): LoDashExplicitArrayWrapper; /** @@ -6812,7 +6812,7 @@ declare namespace _ { * @see _.filter */ filter( - predicate: string + predicate: string|RegExp ): LoDashExplicitArrayWrapper; /** @@ -10387,6 +10387,13 @@ declare namespace _ { * @param funcs Functions to invoke. * @return Returns the new function. */ + // 0-argument first function + flow(f1: () => R1, f2: (a: R1) => R2): () => R2; + flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): () => R3; + flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): () => R4; + flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): () => R5; + flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): () => R6; + flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): () => R7; // 1-argument first function flow(f1: (a1: A1) => R1, f2: (a: R1) => R2): (a1: A1) => R2; flow(f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (a1: A1) => R3; diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 8ccd742a0e..8accba65c0 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -3625,14 +3625,17 @@ namespace TestFilter { result = _.filter(array, listIterator); result = _.filter(array, ''); + result = _.filter(array, /./); result = _.filter(array, {a: 42}); result = _.filter(list, listIterator); result = _.filter(list, ''); + result = _.filter(list, /./); result = _.filter(list, {a: 42}); result = _.filter(dictionary, dictionaryIterator); result = _.filter(dictionary, ''); + result = _.filter(dictionary, /./); result = _.filter(dictionary, {a: 42}); } @@ -3647,14 +3650,17 @@ namespace TestFilter { result = _(array).filter(listIterator); result = _(array).filter(''); + result = _(array).filter(/./); result = _(array).filter({a: 42}); result = _(list).filter(listIterator); result = _(list).filter(''); + result = _(list).filter(/./); result = _(list).filter({a: 42}); result = _(dictionary).filter(dictionaryIterator); result = _(dictionary).filter(''); + result = _(dictionary).filter(/./); result = _(dictionary).filter({a: 42}); } @@ -3669,14 +3675,17 @@ namespace TestFilter { result = _(array).chain().filter(listIterator); result = _(array).chain().filter(''); + result = _(array).chain().filter(/./); result = _(array).chain().filter({a: 42}); result = _(list).chain().filter(listIterator); result = _(list).chain().filter(''); + result = _(list).chain().filter(/./); result = _(list).chain().filter({a: 42}); result = _(dictionary).chain().filter(dictionaryIterator); result = _(dictionary).chain().filter(''); + result = _(dictionary).chain().filter(/./); result = _(dictionary).chain().filter({a: 42}); } } diff --git a/lodash/v3/lodash-tests.ts b/lodash/v3/lodash-tests.ts index 8793d38779..023e5df57e 100644 --- a/lodash/v3/lodash-tests.ts +++ b/lodash/v3/lodash-tests.ts @@ -80,7 +80,7 @@ var keys: IKey[] = [ class Dog { constructor(public name: string) { } - public bark() { + bark() { console.log('Woof, woof!'); } } @@ -4064,21 +4064,15 @@ namespace TestFind { result = _(dictionary).find<{a: number}, TResult>({a: 42}); } -result = _.findWhere([1, 2, 3, 4], function (num) { - return num % 2 == 0; -}); +result = _.findWhere([1, 2, 3, 4], num => num % 2 == 0); result = _.findWhere(foodsCombined, { 'type': 'vegetable' }); result = _.findWhere(foodsCombined, 'organic'); -result = _.findLast([1, 2, 3, 4], function (num) { - return num % 2 == 0; -}); +result = _.findLast([1, 2, 3, 4], num => num % 2 == 0); result = _.findLast(foodsCombined, { 'type': 'vegetable' }); result = _.findLast(foodsCombined, 'organic'); -result = _([1, 2, 3, 4]).findLast(function (num) { - return num % 2 == 0; -}); +result = _([1, 2, 3, 4]).findLast(num => num % 2 == 0); result = _(foodsCombined).findLast({ 'type': 'vegetable' }); result = _(foodsCombined).findLast('organic'); @@ -4850,56 +4844,44 @@ interface ABC { c: number; } -result = _.reduce([1, 2, 3], function (sum: number, num: number) { - return sum + num; -}); -result = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function (r: ABC, num: number, key: string) { +result = _.reduce([1, 2, 3], (sum: number, num: number) => sum + num); +result = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, (r: ABC, num: number, key: string) => { r[key] = num * 3; return r; }, {}); -result = _.foldl([1, 2, 3], function (sum: number, num: number) { - return sum + num; -}); -result = _.foldl({ 'a': 1, 'b': 2, 'c': 3 }, function (r: ABC, num: number, key: string) { +result = _.foldl([1, 2, 3], (sum: number, num: number) => sum + num); +result = _.foldl({ 'a': 1, 'b': 2, 'c': 3 }, (r: ABC, num: number, key: string) => { r[key] = num * 3; return r; }, {}); -result = _.inject([1, 2, 3], function (sum: number, num: number) { - return sum + num; -}); -result = _.inject({ 'a': 1, 'b': 2, 'c': 3 }, function (r: ABC, num: number, key: string) { +result = _.inject([1, 2, 3], (sum: number, num: number) => sum + num); +result = _.inject({ 'a': 1, 'b': 2, 'c': 3 }, (r: ABC, num: number, key: string) => { r[key] = num * 3; return r; }, {}); -result = _([1, 2, 3]).reduce(function (sum: number, num: number) { - return sum + num; -}); -result = _({ 'a': 1, 'b': 2, 'c': 3 }).reduce(function (r: ABC, num: number, key: string) { +result = _([1, 2, 3]).reduce((sum: number, num: number) => sum + num); +result = _({ 'a': 1, 'b': 2, 'c': 3 }).reduce((r: ABC, num: number, key: string) => { r[key] = num * 3; return r; }, {}); -result = _([1, 2, 3]).foldl(function (sum: number, num: number) { - return sum + num; -}); -result = _({ 'a': 1, 'b': 2, 'c': 3 }).foldl(function (r: ABC, num: number, key: string) { +result = _([1, 2, 3]).foldl((sum: number, num: number) => sum + num); +result = _({ 'a': 1, 'b': 2, 'c': 3 }).foldl((r: ABC, num: number, key: string) => { r[key] = num * 3; return r; }, {}); -result = _([1, 2, 3]).inject(function (sum: number, num: number) { - return sum + num; -}); -result = _({ 'a': 1, 'b': 2, 'c': 3 }).inject(function (r: ABC, num: number, key: string) { +result = _([1, 2, 3]).inject((sum: number, num: number) => sum + num); +result = _({ 'a': 1, 'b': 2, 'c': 3 }).inject((r: ABC, num: number, key: string) => { r[key] = num * 3; return r; }, {}); -result = _.reduceRight([[0, 1], [2, 3], [4, 5]], function (a: number[], b: number[]) { return a.concat(b); }, []); -result = _.foldr([[0, 1], [2, 3], [4, 5]], function (a: number[], b: number[]) { return a.concat(b); }, []); +result = _.reduceRight([[0, 1], [2, 3], [4, 5]], (a: number[], b: number[]) => a.concat(b), []); +result = _.foldr([[0, 1], [2, 3], [4, 5]], (a: number[], b: number[]) => a.concat(b), []); // _.reject namespace TestReject { @@ -5455,9 +5437,9 @@ namespace TestSortBy { } } -result = _.sortByAll(stoogesAges, function(stooge) { return Math.sin(stooge.age); }, function(stooge) { return stooge.name.slice(1); }); +result = _.sortByAll(stoogesAges, (stooge) => Math.sin(stooge.age), (stooge) => stooge.name.slice(1)); result = _.sortByAll(stoogesAges, ['name', 'age']); -result = _.sortByAll(stoogesAges, 'name', function(stooge) { return Math.sin(stooge.age); }); +result = _.sortByAll(stoogesAges, 'name', (stooge) => Math.sin(stooge.age)); result = _(foodsOrganic).sortByAll('organic', (food) => food.name, { organic: true }).value(); @@ -6317,7 +6299,7 @@ namespace TestOnce { } } -var greetPartial = function (greeting: string, name: string) { return greeting + ' ' + name; }; +var greetPartial = (greeting: string, name: string) => greeting + ' ' + name; var hi = _.partial(greetPartial, 'hi'); hi('moe'); @@ -10384,7 +10366,7 @@ namespace TestNoConflict { // _.noop namespace TestNoop { { - let result: void; + let result: void; // tslint:disable-line:void-return result = _.noop(); result = _.noop(1); diff --git a/loopback/index.d.ts b/loopback/index.d.ts index ccfc270e10..2d4af5caa9 100644 --- a/loopback/index.d.ts +++ b/loopback/index.d.ts @@ -245,7 +245,7 @@ declare namespace l { * @header app.middleware(name, handler */ - middleware(name: string, paths?: any[]|string|RegExp, handler?: () => void): any; + middleware(name: string, paths?: any[]|string|RegExp, handler?: core.Handler): any; } // interface CookieOptions extends core.CookieOptions { } @@ -1067,7 +1067,7 @@ declare namespace l { * @class PersistedModel */ - class PersistedModel { + class PersistedModel extends Model { /** * Apply an update list @@ -1270,7 +1270,7 @@ declare namespace l { * @param {Array} model First model instance that matches the filter or null if none found */ - static findOne(filter?: {fields: string|any|any[]; include: string|any|any[]; order: string; skip: number; where: any; }, callback?: (err: Error, model: any[]) => void): void; + static findOne(filter?: {fields?: string|any|any[]; include?: string|any|any[]; order?: string; skip?: number; where?: any; }, callback?: (err: Error, model: any) => void): void; /** * Finds one record matching the optional filter object. If not found, creates @@ -1741,7 +1741,7 @@ declare namespace l { created: Date; /** Extends the `Model.settings` object. */ - settings: { http: { path: string }; acls: ACL, accessTokenIdLength: number}; + settings: { http: { path: string }; acls: ACL[], accessTokenIdLength: number}; /** * Create a cryptographically random access token id @@ -1838,7 +1838,7 @@ declare namespace l { principalId: string; /** settings Extends the `Model.settings` object. */ - settings: { http: { path: string }; acls: ACL, defaultPermission: 'DENY'}; + settings: { http: { path: string }; acls: ACL[], defaultPermission: 'DENY'}; /** * Check if the request has the permission to access. @@ -2125,7 +2125,7 @@ declare namespace l { * settings.ignoreErrors By default, when changes are rectified, an error will throw an exception. * However, if this setting is true, then errors will not throw exceptions. */ - settings: { http: { path: string }; acls: ACL; hashAlgorithm: string; ignoreErrors: boolean; }; + settings: { http: { path: string }; acls: ACL[]; hashAlgorithm: string; ignoreErrors: boolean; }; /** * Are both changes deletes? @@ -2800,7 +2800,7 @@ declare namespace l { */ settings: { http: { path: string }; - acls: ACL; + acls: ACL[]; emailVerificationRequired: boolean; ttl: number; maxTTL: number; diff --git a/ltx/ltx-tests.ts b/ltx/ltx-tests.ts index a207efb4b7..9e924cbe60 100644 --- a/ltx/ltx-tests.ts +++ b/ltx/ltx-tests.ts @@ -2,13 +2,13 @@ import * as ltx from './index'; ltx.parse(''); -let p = new ltx.Parser(); +const p = new ltx.Parser(); p.on('tree', (ignored: any) => {}); p.on('error', (ignored: any) => {}); -let el = new ltx.Element('root').c('children'); +const el = new ltx.Element('root').c('children'); el.c('child', {age: 5}).t('Hello').up() .c('child', {age: 7}).t('Hello').up() .c('child', {age: 99}).t('Hello').up(); diff --git a/magicsuggest/magicsuggest-tests.ts b/magicsuggest/magicsuggest-tests.ts index 46cb799d25..96a513a7b9 100644 --- a/magicsuggest/magicsuggest-tests.ts +++ b/magicsuggest/magicsuggest-tests.ts @@ -1,5 +1,3 @@ -/// - function basicTest() { $('#magicSuggest').magicSuggest(); } diff --git a/mailcheck/mailcheck-tests.ts b/mailcheck/mailcheck-tests.ts index 07fc473893..971ecf8218 100644 --- a/mailcheck/mailcheck-tests.ts +++ b/mailcheck/mailcheck-tests.ts @@ -1,5 +1,3 @@ -/// - import MC = require('mailcheck'); var domains = ['gmail.com', 'aol.com']; diff --git a/maker.js/index.d.ts b/maker.js/index.d.ts index ad06d7eb91..ff6a7bd69e 100644 --- a/maker.js/index.d.ts +++ b/maker.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Maker.js 0.9.31 +// Type definitions for Maker.js 0.9.33 // Project: https://github.com/Microsoft/maker.js // Definitions by: Dan Marshall // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -66,6 +66,17 @@ declare namespace MakerJs { * @returns String of the flattened array. */ function createRouteKey(route: string[]): string; + /** + * Travel along a route inside of a model to extract a specific node in its tree. + * + * @param modelContext Model to travel within. + * @param routeKeyOrRoute String of a flattened route, or a string array of route segments. + * @returns Model or Path object within the modelContext tree. + */ + function travel(modelContext: IModel, routeKeyOrRoute: string | string[]): { + path: IPath | IModel; + offset: IPoint; + }; /** * Clone an object. * @@ -139,6 +150,15 @@ declare namespace MakerJs { */ high: IPoint; } + /** + * A measurement of extents, with a center point. + */ + interface IMeasureWithCenter extends IMeasure { + /** + * The center point of the rectangle containing the item being measured. + */ + center: IPoint; + } /** * A map of measurements. */ @@ -926,7 +946,7 @@ declare namespace MakerJs.path { * * @param pathToMove The path to move. * @param origin The new origin for the path. - * @returns The original path (for chaining). + * @returns The original path (for cascading). */ function move(pathToMove: IPath, origin: IPoint): IPath; /** @@ -935,7 +955,7 @@ declare namespace MakerJs.path { * @param pathToMove The path to move. * @param delta The x & y adjustments as a point object. * @param subtract Optional boolean to subtract instead of add. - * @returns The original path (for chaining). + * @returns The original path (for cascading). */ function moveRelative(pathToMove: IPath, delta: IPoint, subtract?: boolean): IPath; /** @@ -952,7 +972,7 @@ declare namespace MakerJs.path { * @param pathToRotate The path to rotate. * @param angleInDegrees The amount of rotation, in degrees. * @param rotationOrigin The center point of rotation. - * @returns The original path (for chaining). + * @returns The original path (for cascading). */ function rotate(pathToRotate: IPath, angleInDegrees: number, rotationOrigin?: IPoint): IPath; /** @@ -960,7 +980,7 @@ declare namespace MakerJs.path { * * @param pathToScale The path to scale. * @param scaleValue The amount of scaling. - * @returns The original path (for chaining). + * @returns The original path (for cascading). */ function scale(pathToScale: IPath, scaleValue: number): IPath; /** @@ -1215,11 +1235,11 @@ declare namespace MakerJs.model { */ function mirror(modelToMirror: IModel, mirrorX: boolean, mirrorY: boolean): IModel; /** - * Move a model to an absolute point. Note that this is also accomplished by directly setting the origin property. This function exists for chaining. + * Move a model to an absolute point. Note that this is also accomplished by directly setting the origin property. This function exists for cascading. * * @param modelToMove The model to move. * @param origin The new position of the model. - * @returns The original model (for chaining). + * @returns The original model (for cascading). */ function move(modelToMove: IModel, origin: IPoint): IModel; /** @@ -1227,7 +1247,7 @@ declare namespace MakerJs.model { * * @param modelToMove The model to move. * @param delta The x & y adjustments as a point object. - * @returns The original model (for chaining). + * @returns The original model (for cascading). */ function moveRelative(modelToMove: IModel, delta: IPoint): IModel; /** @@ -1235,7 +1255,7 @@ declare namespace MakerJs.model { * * @param modelToPrefix The model to prefix. * @param prefix The prefix to prepend on paths ids. - * @returns The original model (for chaining). + * @returns The original model (for cascading). */ function prefixPathIds(modelToPrefix: IModel, prefix: string): IModel; /** @@ -1244,7 +1264,7 @@ declare namespace MakerJs.model { * @param modelToRotate The model to rotate. * @param angleInDegrees The amount of rotation, in degrees. * @param rotationOrigin The center point of rotation. - * @returns The original model (for chaining). + * @returns The original model (for cascading). */ function rotate(modelToRotate: IModel, angleInDegrees: number, rotationOrigin?: IPoint): IModel; /** @@ -1253,7 +1273,7 @@ declare namespace MakerJs.model { * @param modelToScale The model to scale. * @param scaleValue The amount of scaling. * @param scaleOrigin Optional boolean to scale the origin point. Typically false for the root model. - * @returns The original model (for chaining). + * @returns The original model (for cascading). */ function scale(modelToScale: IModel, scaleValue: number, scaleOrigin?: boolean): IModel; /** @@ -1261,7 +1281,7 @@ declare namespace MakerJs.model { * * @param modeltoConvert The model to convert. * @param destUnitType The unit system. - * @returns The scaled model (for chaining). + * @returns The scaled model (for cascading). */ function convertUnits(modeltoConvert: IModel, destUnitType: string): IModel; /** @@ -1373,7 +1393,7 @@ declare namespace MakerJs.model { * * @param modelContext The originated model to search for similar paths. * @param options Optional options object. - * @returns The simplified model (for chaining). + * @returns The simplified model (for cascading). */ function simplify(modelToSimplify: IModel, options?: ISimplifyOptions): IModel; } @@ -1478,7 +1498,7 @@ declare namespace MakerJs.measure { * @param baseMeasure The measurement to increase. * @param addMeasure The additional measurement. * @param addOffset Optional offset point of the additional measurement. - * @returns The increased original measurement (for chaining). + * @returns The increased original measurement (for cascading). */ function increase(baseMeasure: IMeasure, addMeasure: IMeasure): IMeasure; /** @@ -1583,7 +1603,7 @@ declare namespace MakerJs.measure { * @param atlas Optional atlas to save measurements. * @returns object with low and high points. */ - function modelExtents(modelToMeasure: IModel, atlas?: measure.Atlas): IMeasure; + function modelExtents(modelToMeasure: IModel, atlas?: measure.Atlas): IMeasureWithCenter; /** * A list of maps of measurements. * @@ -1612,6 +1632,22 @@ declare namespace MakerJs.measure { constructor(modelContext: IModel); measureModels(): void; } + /** + * A hexagon which surrounds a model. + */ + interface IBoundingHex extends IModel { + /** + * Radius of the hexagon, which is also the length of a side. + */ + radius: number; + } + /** + * Measures the minimum bounding hexagon surrounding a model. The hexagon is oriented such that the right and left sides are vertical, and the top and bottom are pointed. + * + * @param modelToMeasure The model to measure. + * @returns IBoundingHex object which is a hexagon model, with an additional radius property. + */ + function boundingHexagon(modelToMeasure: IModel): IBoundingHex; } declare namespace MakerJs.exporter { /** @@ -1787,6 +1823,29 @@ declare namespace MakerJs.model { function findChains(modelContext: IModel, callback: IChainCallback, options?: IFindChainsOptions): void; } declare namespace MakerJs.chain { + /** + * Shift the links of an endless chain. + * + * @param chainContext Chain to cycle through. Must be endless. + * @param amount Optional number of links to shift. May be negative to cycle backwards. + * @returns The chainContext for cascading. + */ + function cycle(chainContext: IChain, amount?: number): IChain; + /** + * Reverse the links of a chain. + * + * @param chainContext Chain to reverse. + * @returns The chainContext for cascading. + */ + function reverse(chainContext: IChain): IChain; + /** + * Set the beginning of an endless chain to a known routeKey of a path. + * + * @param chainContext Chain to cycle through. Must be endless. + * @param routeKey RouteKey of the desired path to start the chain with. + * @returns The chainContext for cascading. + */ + function startAt(chainContext: IChain, routeKey: string): IChain; /** * Get points along a chain of paths. * @@ -1825,7 +1884,7 @@ declare namespace MakerJs.model { * * @param modelContext The model to search for dead ends. * @param options Optional options object. - * @returns The input model (for chaining). + * @returns The input model (for cascading). */ function removeDeadEnds(modelContext: IModel, pointMatchingDistance?: any, keep?: IWalkPathBooleanCallback): IModel; } @@ -2123,6 +2182,18 @@ declare namespace MakerJs.models { * @param numericList String containing a list of numbers which can be delimited by spaces, commas, or anything non-numeric (Note: [exponential notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) is allowed). */ constructor(numericList: string); + /** + * Create a model by connecting points designated in a string. The model will be 'closed' - i.e. the last point will connect to the first point. + * + * Example: + * ``` + * var c = new makerjs.models.ConnectTheDots(false, '-10 0 10 0 0 20'); // 3 coordinates to form a polyline + * ``` + * + * @param isClosed Flag to specify if last point should connect to the first point. + * @param numericList String containing a list of numbers which can be delimited by spaces, commas, or anything non-numeric (Note: [exponential notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) is allowed). + */ + constructor(isClosed: boolean, numericList: string); /** * Create a model by connecting points designated in a numeric array. The model will be 'closed' - i.e. the last point will connect to the first point. * @@ -2134,6 +2205,18 @@ declare namespace MakerJs.models { * @param coords Array of coordinates. */ constructor(coords: number[]); + /** + * Create a model by connecting points designated in a numeric array. The model will be 'closed' - i.e. the last point will connect to the first point. + * + * Example: + * ``` + * var c = new makerjs.models.ConnectTheDots(false, [-10, 0, 10, 0, 0, 20]); // 3 coordinates to form a polyline + * ``` + * + * @param isClosed Flag to specify if last point should connect to the first point. + * @param coords Array of coordinates. + */ + constructor(isClosed: boolean, coords: number[]); /** * Create a model by connecting points designated in an array of points. The model may be closed, or left open. * diff --git a/maker.js/maker.js-tests.ts b/maker.js/maker.js-tests.ts index 4c7dbc25f0..f5f9d9db16 100644 --- a/maker.js/maker.js-tests.ts +++ b/maker.js/maker.js-tests.ts @@ -51,6 +51,7 @@ function test() { makerjs.isPoint([]); makerjs.pathType.Circle; makerjs.round(44.44444, .01); + makerjs.travel(model, ''); makerjs.unitType.Millimeter; new makerjs.Collector(); } @@ -105,6 +106,7 @@ function test() { } function testMeasure() { + makerjs.measure.boundingHexagon(model).radius; makerjs.measure.increase(mp, mm); makerjs.measure.isPointEqual(p1, p2); makerjs.measure.isPathEqual(paths.line, paths.circle, 4); @@ -123,6 +125,7 @@ function test() { makerjs.measure.pointDistance([0,0], [9,9]); new makerjs.measure.Atlas(model); mm.low[0]; + mm.center; mp.high[1]; var s = makerjs.measure.lineSlope(paths.line); makerjs.measure.isPointOnSlope([], s); @@ -172,6 +175,10 @@ function test() { new makerjs.models.BoltCircle(7, 7, 7, 7), new makerjs.models.BoltRectangle(2, 2, 2), new makerjs.models.ConnectTheDots(true, [ [0,0], [1,1] ]), + new makerjs.models.ConnectTheDots([0, 0, 1, 1]), + new makerjs.models.ConnectTheDots(true, [0, 0, 1, 1]), + new makerjs.models.ConnectTheDots(true, '0, 0, 1, 1'), + new makerjs.models.ConnectTheDots('0, 0, 1, 1'), new makerjs.models.Dogbone(1,1,1), new makerjs.models.Dome(5, 7), new makerjs.models.Ellipse(2,2), @@ -255,7 +262,10 @@ function test() { } function testChain() { + makerjs.chain.cycle(chain, 7); makerjs.chain.fillet(chain, 1); + makerjs.chain.reverse(chain); + makerjs.chain.startAt(chain, ''); makerjs.chain.toKeyPoints(chain); makerjs.chain.toPoints(chain, 1); } diff --git a/mapbox-gl/index.d.ts b/mapbox-gl/index.d.ts index 2e75704dde..64e8b8e573 100644 --- a/mapbox-gl/index.d.ts +++ b/mapbox-gl/index.d.ts @@ -978,7 +978,7 @@ declare namespace mapboxgl { "circle-translate-anchor"?: "map" | "viewport"; "circle-pitch-scale"?: "map" | "viewport"; "circle-stroke-width"?: number | StyleFunction; - "circle-stoke-color"?: string | StyleFunction; + "circle-stroke-color"?: string | StyleFunction; "circle-stroke-opactiy"?: number | StyleFunction; } } diff --git a/markitup/markitup-tests.ts b/markitup/markitup-tests.ts index f8b12d3c00..b8a7675529 100644 --- a/markitup/markitup-tests.ts +++ b/markitup/markitup-tests.ts @@ -1,6 +1,3 @@ -/// - - // https://github.com/markitup/1.x/blob/master/markitup/sets/default/set.js var mySettings = { onShiftEnter: { diff --git a/maskedinput/maskedinput-tests.ts b/maskedinput/maskedinput-tests.ts index 6d620ce1b9..99c1ecb8bb 100644 --- a/maskedinput/maskedinput-tests.ts +++ b/maskedinput/maskedinput-tests.ts @@ -1,10 +1,3 @@ -// Type definitions for Masked Input plugin for jQuery -// Project: http://digitalbush.com/projects/masked-input-plugin -// Definitions by: Lokesh Peta -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - $("#test").mask("9:000"); $("#test").mask("9:000", { numeric: true }); diff --git a/massive/index.d.ts b/massive/index.d.ts new file mode 100755 index 0000000000..53e857e689 --- /dev/null +++ b/massive/index.d.ts @@ -0,0 +1,106 @@ +// Type definitions for massive-js 2.2 +// Project: https://github.com/robconery/massive-js +// Definitions by: Pascal Birchler +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace massive { + interface ConnectionOptions { + connectionString?: string; + db?: string; + } + + interface Doc { + findDoc(context: any, callback: ResultCallback): void; + searchDoc(options: { + keys: string[]; + term: string; + }, callback: ResultCallback): void; + saveDoc(context: string, callback: ResultCallback): void; + destroy(context: any, callback: ResultCallback): void; + } + + interface QueryFile { + schema: string; + name: string; + db: Massive; + delimitedName: string; + delimitedSchema: string; + fullname: string; + delimitedFullName: string; + sql: string; + filePath: string; + } + + interface QueryFunction { + find: (params: any|any[], callback: ResultCallback) => void; + } + + interface QueryArguments { + sql: string; + options: any; + params: any; + next: ResultCallback; + } +} + +export interface Massive { + custom: any; + comment: Table; + friendship: Table; + participation: Table; + person: Table; + practice: Table; + practicesession: Table; + sport: Table; + testdata: (callback: ResultCallback) => void; + team: Table; + teammember: Table; + teamsport: Table; + scriptsDir: string; + connectionString: string; + query: () => void; + stream: () => void; + executeSqlFile: (args: any, next: ResultCallback) => void; + end: () => void; + tables: Array; + views: any[]; + queryFiles: massive.QueryFile[]; + schemas: any[]; + functions: any[]; + allowedSchemas: string; + blacklist: string; + exceptions: string; + excludeFunctions: boolean; + functionBlacklist: string; +} + +export type ResultCallback = (err: Error, res: any) => void; +export type ConnectCallback = (err: Error, db: Massive) => void; + +export interface QueryOptions { + limit?: number; + order?: string; + offset?: number; + columns?: string[]; +} + +export interface Table { + count(context: any, callback: ResultCallback): void; + find(context: any, callback: ResultCallback): void; + find(context: any, options: QueryOptions, callback: ResultCallback): void; + findOne(context: any, callback: ResultCallback): void; + findOne(context: any, options: QueryOptions, callback: ResultCallback): void; + insert(context: any, callback: ResultCallback): void; + save(context: any, callback: ResultCallback): void; + update(context: any, callback: ResultCallback): void; + update(context: any, data: any, callback: ResultCallback): void; + destroy(context: any, callback: ResultCallback): void; +} + +export function connectSync(options: massive.ConnectionOptions): Massive; + +export function connect(options: massive.ConnectionOptions, callback: ConnectCallback): void; + +export function run(context: string, filter: number|number[], callback: ResultCallback): void; + +export function saveDoc(name: string, data: any, callback: ResultCallback): void; diff --git a/massive/massive-tests.ts b/massive/massive-tests.ts new file mode 100644 index 0000000000..2978440f4a --- /dev/null +++ b/massive/massive-tests.ts @@ -0,0 +1,5 @@ +import * as Massive from 'massive'; + +Massive.connect({connectionString: 'foo'}, (err: Error, db: Massive.Massive) => {}); + +Massive.run('foo', 123, (err: Error, db: Massive.Massive) => {}); \ No newline at end of file diff --git a/massive/tsconfig.json b/massive/tsconfig.json new file mode 100755 index 0000000000..7c91e19b44 --- /dev/null +++ b/massive/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es5" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "massive-tests.ts" + ] +} \ No newline at end of file diff --git a/massive/tslint.json b/massive/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/massive/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/material-ui/index.d.ts b/material-ui/index.d.ts index c399116482..05512e2e9d 100644 --- a/material-ui/index.d.ts +++ b/material-ui/index.d.ts @@ -174,6 +174,7 @@ declare namespace __MaterialUI { height?: number; minWidth?: number; iconButtonSize?: number; + textTransform?: string; }; card?: { titleColor?: string; @@ -533,7 +534,7 @@ declare namespace __MaterialUI { type cornersAndCenter = 'bottom-center' | 'bottom-left' | 'bottom-right' | 'top-center' | 'top-left' | 'top-right'; } - interface AutoCompleteProps { + interface AutoCompleteProps extends TextFieldProps { anchorOrigin?: propTypes.origin; animated?: boolean; animation?: React.ComponentClass; @@ -688,6 +689,7 @@ declare namespace __MaterialUI { onMouseUp?: React.MouseEventHandler<{}>; onTouchEnd?: React.TouchEventHandler<{}>; onTouchStart?: React.TouchEventHandler<{}>; + overlayStyle?: React.CSSProperties; primary?: boolean; rippleStyle?: React.CSSProperties; secondary?: boolean; @@ -723,6 +725,7 @@ declare namespace __MaterialUI { className?: string; disableTouchRipple?: boolean; disabled?: boolean; + hoveredStyle?: React.CSSProperties; iconClassName?: string; iconStyle?: React.CSSProperties; onBlur?: React.FocusEventHandler<{}>; @@ -945,7 +948,7 @@ declare namespace __MaterialUI { ref?: string; text: string; } - interface DialogProps extends React.DOMAttributes<{}>, React.Props { + export interface DialogProps extends React.DOMAttributes<{}>, React.Props { actions?: Array>; /** @deprecated use a custom `actions` property instead */ actionFocus?: string; @@ -1331,6 +1334,9 @@ declare namespace __MaterialUI { className?: string; maxHeight?: number; menuStyle?: any; + listStyle?: React.CSSProperties; + menuItemStyle?: React.CSSProperties; + selectedMenuItemStyle?: React.CSSProperties; openImmediately?: boolean; } export class SelectField extends React.Component { @@ -1761,6 +1767,7 @@ declare namespace __MaterialUI { errorText?: React.ReactNode; floatingLabelFixed?: boolean; floatingLabelFocusStyle?: React.CSSProperties; + floatingLabelShrinkStyle?: React.CSSProperties; floatingLabelStyle?: React.CSSProperties; floatingLabelText?: React.ReactNode; fullWidth?: boolean; @@ -1772,9 +1779,10 @@ declare namespace __MaterialUI { name?: string; onBlur?: React.FocusEventHandler<{}>; onChange?: (e: React.FormEvent<{}>, newValue: string) => void; - onEnterKeyDown?: React.KeyboardEventHandler<{}>; onFocus?: React.FocusEventHandler<{}>; onKeyDown?: React.KeyboardEventHandler<{}>; + onKeyUp?: React.KeyboardEventHandler<{}>; + onKeyPress?: React.KeyboardEventHandler<{}>; rows?: number, rowsMax?: number, style?: React.CSSProperties; @@ -1785,6 +1793,7 @@ declare namespace __MaterialUI { underlineShow?: boolean; underlineStyle?: React.CSSProperties; value?: string | number; + autoFocus?: boolean; } export class TextField extends React.Component { blur(): void; diff --git a/material-ui/material-ui-tests.tsx b/material-ui/material-ui-tests.tsx index f2acb7922f..0ea5a72352 100644 --- a/material-ui/material-ui-tests.tsx +++ b/material-ui/material-ui-tests.tsx @@ -1,8 +1,3 @@ -/// -/// -/// -/// - import * as React from 'react'; import {Component, PropTypes} from 'react'; import * as ReactDOM from 'react-dom'; @@ -285,6 +280,9 @@ const lightBaseTheme = { desktopSubheaderHeight: 48, desktopToolbarHeight: 56, }, + button: { + textTransform: "lowercase" + }, fontFamily: 'Roboto, sans-serif', palette: { primary1Color: cyan500, diff --git a/mcustomscrollbar/mcustomscrollbar-tests.ts b/mcustomscrollbar/mcustomscrollbar-tests.ts index aecb236286..f00cd5a491 100644 --- a/mcustomscrollbar/mcustomscrollbar-tests.ts +++ b/mcustomscrollbar/mcustomscrollbar-tests.ts @@ -1,6 +1,3 @@ -/// - - class SimpleTest { element: JQuery; diff --git a/md5/md5-tests.ts b/md5/md5-tests.ts index 427a93486a..924c9b8d91 100644 --- a/md5/md5-tests.ts +++ b/md5/md5-tests.ts @@ -1,5 +1,3 @@ -/// - import fs = require("fs"); import md5 = require("md5"); /** @@ -7,7 +5,7 @@ import md5 = require("md5"); * md5(message) * message -- String or Buffer * returns String - * + * * Usage **************************************************** * var md5 = require('md5'); * @@ -15,10 +13,10 @@ import md5 = require("md5"); **************************************************** * This will print the following * 78e731027d8fd50ed642340b7c9a63b3 - * + * * It supports buffers, too - **************************************************** - * var fs = require('fs'); * + **************************************************** + * var fs = require('fs'); * * var md5 = require('md5'); * * * * fs.readFile('example.txt', function(err, buf) { * diff --git a/memcached/index.d.ts b/memcached/index.d.ts new file mode 100644 index 0000000000..23d892309b --- /dev/null +++ b/memcached/index.d.ts @@ -0,0 +1,322 @@ +// Type definitions for memcached 2.2 +// Project: https://github.com/3rd-Eden/memcached +// Definitions by: KentarouTakeda +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +import events = require("events"); +export = Memcached; + +declare class Memcached extends events.EventEmitter { + + static config: Memcached.options; + + /** + * Connect to a single server. + * @param location Server location e.g. "127.0.0.1:11211" + * @param options options + */ + constructor(location: string, options?: Memcached.options); + + /** + * Connect to a cluster of Memcached servers. + * @param location Server locations e.g. ["127.0.0.1:11211","127.0.0.1:11212"] + * @param options options + */ + constructor(location: string[], options?: Memcached.options); + + /** + * Connect to servers with weight. + * @param location Server locations e.g. {"127.0.0.1:11211": 1,"127.0.0.1:11212": 2} + * @param options options + */ + constructor(location: {[server: string]: number}, options ?: Memcached.options); + + /** + * Touches the given key. + * @param key The key + * @param lifetime After how long should the key expire measured in seconds + * @param cb + */ + touch(key: string, lifetime: number, cb: (this: Memcached.CommandData, err: any) => void): void; + + /** + * Get the value for the given key. + * @param key The key + * @param cb + */ + get(key: string, cb: (this: Memcached.CommandData, err: any, data: any) => void): void; + + /** + * Get the value and the CAS id. + * @param key The key + * @param cb + */ + gets(key: string, cb: (this: Memcached.CommandData, err: any, data: {[key: string]: any, cas: string}) => void): void; + + /** + * Retrieves a bunch of values from multiple keys. + * @param keys all the keys that needs to be fetched + * @param cb + */ + getMulti(keys: string[], cb: (this: undefined, err: any, data: {[key: string]: any}) => void): void; + + /** + * Stores a new value in Memcached. + * + * @param key The key + * @param value Either a buffer, JSON, number or string that you want to store. + * @param lifetime + * @param cb + */ + set(key: string, value: any, lifetime: number, cb: (this: Memcached.CommandData, err: any, result: boolean) => void): void; + + /** + * Replaces the value in memcached. + * @param key The key + * @param value Either a buffer, JSON, number or string that you want to store. + * @param lifetime + * @param cb + */ + replace(key: string, value: any, lifetime: number, cb: (this: Memcached.CommandData, err: any, result: boolean) => void): void; + + /** + * Add the value, only if it's not in memcached already. + * @param key The key + * @param value Either a buffer, JSON, number or string that you want to store. + * @param lifetime + * @param cb + */ + add(key: string, value: any, lifetime: number, cb: (this: Memcached.CommandData, err: any, result: boolean) => void): void; + + /** + * Add the value, only if it matches the given CAS value. + * @param key The key + * @param value Either a buffer, JSON, number or string that you want to store. + * @param cas + * @param lifetime + * @param cb + */ + cas(key: string, value: any, cas: string, lifetime: number, cb: (this: Memcached.CommandData, err: any, result: boolean) => void): void; + + /** + * Add the given value string to the value of an existing item. + * @param key The key + * @param value Either a buffer, JSON, number or string that you want to store. + * @param cb + */ + append(key: string, value: any, cb: (this: Memcached.CommandData, err: any, result: boolean) => void): void; + + /** + * Add the given value string to the value of an existing item. + * @param key The key + * @param value Either a buffer, JSON, number or string that you want to store. + * @param cb + */ + prepend(key: string, value: any, cb: (this: Memcached.CommandData, err: any, result: boolean) => void): void; + + /** + * Increment a given key. + * @param key The key + * @param amount The increment + * @param cb + */ + incr(key: string, amount: number, cb: (this: Memcached.CommandData, err: any, result: boolean|number) => void): void; + + /** + * Decrement a given key. + * @param key The key + * @param amount The decrement + * @param cb + */ + decr(key: string, amount: number, cb: (this: Memcached.CommandData, err: any, result: boolean|number) => void): void; + + /** + * Remove the key from memcached. + * @param key The key + * @param cb + */ + del(key: string, cb: (this: Memcached.CommandData, err: any, result: boolean) => void): void; + + /** + * Retrieves the version number of your server. + * @param cb + */ + version(cb: (err: any, version: Memcached.VersionData[]) => void): void; + + /** + * Retrieves your stats settings. + * @param cb + */ + settings(cb: (err: any, settings: Memcached.StatusData[]) => void): void; + + /** + * Retrieves stats from your memcached server. + * @param cb + */ + stats(cb: (err: any, stats: Memcached.StatusData[]) => void): void; + + /** + * Retrieves stats slabs information. + * @param cb + */ + slabs(cb: (err: any, stats: Memcached.StatusData[]) => void): void; + + /** + * Retrieves stats items information. + * @param cb + */ + items(cb: (err: any, stats: Memcached.StatusData[]) => void): void; + + /** + * Inspect cache, see examples for a detailed explanation. + * @param server + * @param slabid + * @param number + * @param cb + */ + cachedump(server: string, slabid: number, number: number, cb: (err: any, cachedump: Memcached.CacheDumpData|Memcached.CacheDumpData[]) => void): void; + + /** + * Flushes the memcached server. + * @param cb + */ + flush(cb: (this: undefined, err: any, results: boolean[]) => void): void; + + /** + * a issue occurred on one a server, we are going to attempt a retry next. + */ + on(event: "issue", cb: (err: Memcached.IssueData) => void): this; + + /** + * a server has been marked as failure or dead. + */ + on(event: "failure", cb: (err: Memcached.IssueData) => void): this; + + /** + * we are going to attempt to reconnect the to the failed server. + */ + on(event: "reconnecting", cb: (err: Memcached.IssueData) => void): this; + + /** + * successfully reconnected to the memcached server. + */ + on(event: "reconnect", cb: (err: Memcached.IssueData) => void): this; + + /** + * removing the server from our consistent hashing. + */ + on( event: "remove", cb: (err: Memcached.IssueData) => void): this; + + /** + * Closes all active memcached connections. + */ + end(): void; +} + +declare namespace Memcached { + export interface IssueData { + server: string; + tokens: [string, string]; + messages: string[]; + failures ?: number; + totalFailures ?: number; + totalReconnectsAttempted ?: number; + totalReconnectsSuccess ?: number; + totalReconnectsFailed ?: number; + totalDownTime ?: number; + } + + export interface CommandData { + start: number; + execution: number; + callback: (...args : any[]) => any; + type: string; + command: string; + validate: Array<[string, (...args : any[]) => any]>; + cas ?: string; + redundancyEnabled ?: boolean; + key ?: string; + value ?: any; + lifetime ?: number; + } + + export interface StatusData { + server ?: string; + [key: string]: string|boolean|number|undefined; + } + + export interface VersionData extends StatusData { + version: string; + major: string; + minor: string; + bugfix: string; + } + + export interface CacheDumpData { + key: string; + b: number; + s: number; + } + + export interface options { + /** + * 250, the maximum key size allowed. + */ + maxKeySize ?: number; + /** + * 2592000, the maximum expiration time of keys (in seconds). + */ + maxExpiration ?: number; + /** + * 1048576, the maximum size of a value. + */ + maxValue ?: number; + /** + * 10, the maximum size of the connection pool. + */ + poolSize ?: number; + /** + * md5, the hashing algorithm used to generate the hashRing values. + */ + algorithm ?: string; + /** + * 18000000, the time between reconnection attempts (in milliseconds). + */ + reconnect ?: number; + /** + * 5000, the time after which Memcached sends a connection timeout (in milliseconds). + */ + timeout ?: number; + /** + * 5, the number of socket allocation retries per request. + */ + retries ?: number; + /** + * 5, the number of failed-attempts to a server before it is regarded as 'dead'. + */ + failures ?: number; + /** + * 30000, the time between a server failure and an attempt to set it up back in service. + */ + retry ?: number; + /** + * false, if true, authorizes the automatic removal of dead servers from the pool. + */ + remove ?: boolean; + /** + * undefined, an array of server_locations to replace servers that fail and that are removed from the consistent hashing scheme. + */ + failOverServers ?: string|string[]; + /** + * true, whether to use md5 as hashing scheme when keys exceed maxKeySize. + */ + keyCompression ?: boolean; + /** + * 5000, the idle timeout for the connections. + */ + idle ?: number; + } +} diff --git a/memcached/memcached-tests.ts b/memcached/memcached-tests.ts new file mode 100644 index 0000000000..7671bebcb6 --- /dev/null +++ b/memcached/memcached-tests.ts @@ -0,0 +1,429 @@ +import Memcached = require('memcached'); +import assert = require('assert'); + +namespace main { + function isString(expected?: string): void { + if (expected !== undefined && typeof expected !== 'string') { + throw new Error(); + } + }; + function isArray(expected?: any[]): void { + if (expected !== undefined && !Array.isArray(expected)) { + throw new Error(); + } + }; + function isNumber(expected?: number): void { + if (expected !== undefined && typeof expected !== 'number') { + throw new Error(); + } + }; + function isBoolean(expected?: boolean): void { + if (expected !== undefined && typeof expected !== 'boolean') { + throw new Error(); + } + }; + function isFunction(expected?: (...args : any[]) => void): void { + if (expected !== undefined && typeof expected !== 'function') { + throw new Error(); + } + }; + function isVoid(expected?: undefined): void { + if (expected !== undefined) { + throw new Error(); + } + }; + + namespace test_global_options { + Memcached.config.maxKeySize = 250; + Memcached.config.maxExpiration = 2592000; + Memcached.config.maxValue = 1048576; + Memcached.config.poolSize = 10; + Memcached.config.algorithm = 'md5'; + Memcached.config.reconnect = 1000; + Memcached.config.timeout = 100; + Memcached.config.retries = 1; + Memcached.config.failures = 5; + Memcached.config.retry = 100; + Memcached.config.remove = false; + Memcached.config.failOverServers = undefined; + Memcached.config.keyCompression = true; + Memcached.config.idle = 5000; + } + + namespace test_constructor_with_string { + const location = '127.0.0.1:11211'; + + const memcached = new Memcached(location); + memcached.end(); + } + + namespace test_constructor_with_array { + const location = [ + '127.0.0.1:11211', + '127.0.0.1:11212', + '127.0.0.1:11213' + ]; + + const memcached = new Memcached(location); + memcached.end(); + } + + namespace test_constructor_with_object { + const location = { + '127.0.0.1:11211': 1, + '127.0.0.1:11212': 2, + '127.0.0.1:11213': 3 + }; + + const memcached = new Memcached(location); + memcached.end(); + } + + namespace test_constructor_with_options { + const location = '127.0.0.1:11211'; + const options: Memcached.options = { + maxKeySize: 250, + maxExpiration: 2592000, + maxValue: 1048576, + poolSize: 10, + algorithm: 'md5', + reconnect: 18000000, + timeout: 5000, + retries: 5, + failures: 5, + retry: 30000, + remove: false, + failOverServers: undefined, + keyCompression: true, + idle: 5000, + }; + + const memcached = new Memcached(location, options); + memcached.end(); + } + + const memcached = new Memcached('127.0.0.1:11211'); + + namespace test_events { + function isIssue(expected: Memcached.IssueData) { + isString(expected.server); + isArray(expected.tokens); + isArray(expected.messages); + isNumber(expected.failures); + isNumber(expected.totalFailures); + isNumber(expected.totalReconnectsAttempted); + isNumber(expected.totalReconnectsSuccess); + isNumber(expected.totalReconnectsFailed); + isNumber(expected.totalDownTime); + } + memcached.on('issue', err => isIssue(err)); + memcached.on('failure', err => isIssue(err)); + memcached.on('reconnecting', err => isIssue(err)); + memcached.on('reconnect', err => isIssue(err)); + memcached.on('remove', err => isIssue(err)); + } + + function isCommandData(expected: Memcached.CommandData) { + isNumber(expected.start); + isNumber(expected.execution); + isFunction(expected.callback); + isString(expected.type); + isString(expected.command); + isArray(expected.validate); + isBoolean(expected.redundancyEnabled); + isString(expected.key); + isNumber(expected.lifetime); + isString(expected.cas); + } + namespace test_set { + memcached.set('key', 'value', 3600, function(err) { + isCommandData(this); + }); + } + namespace test_touch { + memcached.touch('key', 3600, function(err) { + isCommandData(this); + }); + } + namespace test_get { + memcached.get('key', function(err, data) { + isCommandData(this); + }); + } + namespace test_getMulti { + memcached.getMulti(['foo', 'bar'], function(err, data) { + isVoid(this); + assert(typeof data, 'object'); + }); + } + namespace test_cas { + const promises = []; + const key = 'caskey'; + const value = 'casvalue'; + + Promise.resolve() + .then(() => new Promise(resolve => { + memcached.set(key, value, 0, function() { + isCommandData(this); + resolve(); + }); + })) + .then(() => new Promise(resolve => { + memcached.gets(key, function(err, data) { + isCommandData(this); + memcached.cas(key, value, data.cas, 0, function(err, result) { + isCommandData(this); + assert(result); + resolve(); + }); + }); + })) + .then(() => new Promise(resolve => { + memcached.cas(key, value, '99', 0, function(err, result) { + isCommandData(this); + assert(!result); + resolve(); + }); + })) + ; + + } + namespace test_replace { + const promises = []; + const key = 'replacekey'; + const value = 'replacevalue'; + + Promise.resolve() + .then(() => new Promise(resolve => { + memcached.set(key, value, 0, () => { + resolve(); + }); + })) + .then(() => new Promise(resolve => { + memcached.replace(key, value, 0, function(err, result) { + assert(result); + isCommandData(this); + resolve(); + }); + })) + .then(() => new Promise(resolve => { + memcached.replace('noexistss', value, 0, function(err, result) { + assert(!result); + isCommandData(this); + resolve(); + }); + })) + ; + } + namespace test_add { + const promises = []; + const key = 'addkey'; + const value = 'addvalue'; + + Promise.resolve() + .then(() => new Promise(resolve => { + memcached.add(key, value, 0, function(err, result) { + assert(result); + isCommandData(this); + resolve(); + }); + })) + .then(() => new Promise(resolve => { + memcached.add(key, value, 0, function(err, result) { + assert(!result); + isCommandData(this); + resolve(); + }); + })) + ; + } + namespace test_append { + const promises = []; + const key = 'appendkey'; + const value = 'appendvalue'; + + Promise.resolve() + .then(() => new Promise(resolve => { + memcached.set(key, value, 0, (err, result) => { + isBoolean(result); + resolve(); + }); + })) + .then(() => new Promise(resolve => { + memcached.append(key, value, (err, result) => { + isBoolean(result); + resolve(); + }); + })) + ; + } + namespace test_prepend { + const promises = []; + const key = 'prependkey'; + const value = 'prependvalue'; + Promise.resolve() + .then(() => new Promise(resolve => { + memcached.set(key, value, 0, (err, result) => { + isBoolean(result); + resolve(); + }); + })) + .then(() => new Promise(resolve => { + memcached.prepend(key, value, function(err, result) { + isBoolean(result); + isCommandData(this); + resolve(); + }); + })) + ; + } + namespace test_incr { + const promises = []; + const key = 'incrkey'; + const value = 2; + + Promise.resolve() + .then(() => new Promise(resolve => { + memcached.set(key, value, 0, (err, result) => { + isBoolean(result); + resolve(); + }); + })) + .then(() => new Promise(resolve => { + memcached.incr(key, value, function(err, result) { + assert.deepStrictEqual(result, 4); + isCommandData(this); + resolve(); + }); + })) + .then(() => new Promise(resolve => { + memcached.incr('noexists', value, function(err, result) { + assert.deepStrictEqual(result, false); + isCommandData(this); + resolve(); + }); + })) + ; + } + namespace test_decr { + const promises = []; + const key = 'decrkey'; + const value = 2; + Promise.resolve() + .then(() => new Promise(resolve => { + memcached.set(key, value, 0, function(err, result) { + isCommandData(this); + isBoolean(result); + resolve(); + }); + })) + .then(() => new Promise(resolve => { + memcached.decr(key, value, function(err, result) { + assert.deepStrictEqual(result, 0); + isCommandData(this); + resolve(); + }); + })) + .then(() => new Promise(resolve => { + memcached.decr('noexists', value, function(err, result) { + assert.deepStrictEqual(result, false); + isCommandData(this); + resolve(); + }); + })) + ; + } + namespace test_decr { + const promises = []; + const key = 'delkey'; + const value = 'delvalue'; + Promise.resolve() + .then(() => new Promise(resolve => { + memcached.set(key, value, 0, (err, result) => { + isBoolean(result); + resolve(); + }); + })) + .then(() => new Promise(resolve => { + memcached.del(key, function(err, result) { + isBoolean(result); + isCommandData(this); + resolve(); + }); + })) + ; + } + + namespace test_version { + memcached.version((err, data) => { + for (const version of data) { + isString(version.server); + isString(version.version); + isString(version.major); + isString(version.minor); + isString(version.bugfix); + } + }); + } + namespace test_stats { + memcached.stats((err : any, data: Memcached.StatusData[]) => { + isArray(data); + for (const stat of data) { + isString(stat.server); + } + }); + }; + namespace test_settings { + memcached.settings((err : any, data: Memcached.StatusData[]) => { + isArray(data); + for (const setting of data) { + isString(setting.server); + } + }); + }; + namespace test_slabs { + memcached.slabs((err : any, data: Memcached.StatusData[]) => { + isArray(data); + for (const setting of data) { + isString(setting.server); + } + }); + }; + let promise: Promise; + namespace test_items { + promise = new Promise(resolve => { + memcached.items((err, data) => { + isArray(data); + for (const setting of data) { + isString(setting.server); + } + resolve(data); + }); + }); + }; + namespace test_cachedump { + promise.then(data => { + for (const node of data) { + const server = node.server; + delete node.server; + Object.keys(node).forEach(slabid => { + memcached.cachedump(server, Number(slabid), node[slabid].number, (err, data) => { + if (!Array.isArray(data)) data = [data]; + data.forEach(cache => { + isNumber(cache.b); + isNumber(cache.s); + isString(cache.key); + }); + }); + }); + } + }); + }; + + namespace test_flush { + memcached.flush(function(err, results) { + isVoid(this); + isArray(results); + }); + }; +} diff --git a/memcached/tsconfig.json b/memcached/tsconfig.json new file mode 100644 index 0000000000..263ad39c54 --- /dev/null +++ b/memcached/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "strictNullChecks": true, + "noImplicitReturns": true, + "noImplicitAny": true, + "noImplicitThis": true, + "lib": ["es6"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "module": "commonjs", + "target": "es5", + "sourceMap": false, + "baseUrl": "../", + "typeRoots": ["../"] + }, + "files": [ + "index.d.ts", + "memcached-tests.ts" + ] +} diff --git a/pixi.js/v3/tslint.json b/memcached/tslint.json similarity index 56% rename from pixi.js/v3/tslint.json rename to memcached/tslint.json index dca585dadc..68d10d72a6 100644 --- a/pixi.js/v3/tslint.json +++ b/memcached/tslint.json @@ -1,8 +1,6 @@ { "extends": "../tslint.json", "rules": { - "forbidden-types": false, - "no-empty-interface": false, "unified-signatures": false } } diff --git a/mendixmodelsdk/index.d.ts b/mendixmodelsdk/index.d.ts index 29192f4bc4..d75cdb97aa 100644 --- a/mendixmodelsdk/index.d.ts +++ b/mendixmodelsdk/index.d.ts @@ -207,8 +207,188 @@ limitations under the License. */ +// Outdated mobservable typings. +// TODO: Use the types bundled with mobservable. Or use mobx. + +interface _IMobservableStatic { + /** + * Turns an object, array or function into a reactive structure. + * @param value the value which should become observable. + */ + makeReactive: IMakeReactive; + + /** + * Extends an object with reactive capabilities. + * @param target the object to which reactive properties should be added + * @param properties the properties that should be added and made reactive + * @returns targer + */ + extendReactive(target: Object, properties: Object):Object; + + /** + * Returns true if the provided value is reactive. + * @param value object, function or array + * @param propertyName if propertyName is specified, checkes whether value.propertyName is reactive. + */ + isReactive(value: any, propertyName?:string): boolean; + + /** + * Can be used in combination with makeReactive / extendReactive. + * Enforces that a reference to 'value' is stored as property, + * but that 'value' itself is not turned into something reactive. + * Future assignments to the same property will inherit this behavior. + * @param value initial value of the reactive property that is being defined. + */ + asReference(value: any):{value:T}; + + /** + * ES6 / Typescript decorator which can to make class properties and getter functions reactive. + */ + observable(target: Object, key: string):any; // decorator / annotation + + /** + * Creates a reactive view and keeps it alive, so that the view is always + * updated if one of the dependencies changes, even when the view is not further used by something else. + * @param func The reactive view + * @param scope (optional) + * @returns disposer function, which can be used to stop the view from being updated in the future. + */ + observe(func: Mobservable.Lambda, scope?: any): Mobservable.Lambda; + + /** + * Deprecated, use mobservable.observe instead. + */ + sideEffect(func: Mobservable.Lambda, scope?: any): Mobservable.Lambda; + + /** + * Similar to 'observer', observes the given predicate until it returns true. + * Once it returns true, the 'effect' function is invoked an the observation is cancelled. + * @param predicate + * @param effect + * @param scope (optional) + * @returns disposer function to prematurely end the observer. + */ + observeUntil(predicate: ()=>boolean, effect: Mobservable.Lambda, scope?: any): Mobservable.Lambda; + + /** + * During a transaction no views are updated until the end of the transaction. + * The transaction will be run synchronously nonetheless. + * @param action a function that updates some reactive state + * @returns any value that was returned by the 'action' parameter. + */ + transaction(action: ()=>T): T; + + /** + * Converts a reactive structure into a non-reactive structure. + * Basically a deep-clone. + */ + toJSON(value: T): T; + + /** + * Sets the reporting level Defaults to 1. Use 0 for production or 2 for increased verbosity. + */ + logLevel: number; // 0 = production, 1 = development, 2 = debugging + + extras: { + getDependencyTree(thing:any, property?:string): Mobservable.IDependencyTree; + + getObserverTree(thing:any, property?:string): Mobservable.IObserverTree; + + trackTransitions(extensive?:boolean, onReport?:(lines:Mobservable.ITransitionEvent) => void) : Mobservable.Lambda; + } +} + +interface IMakeReactive { + (value: T[], opts?: Mobservable.IMakeReactiveOptions): Mobservable.IObservableArray; + (value: ()=>T, opts?: Mobservable.IMakeReactiveOptions): Mobservable.IObservableValue; + (value: T, opts?: Mobservable.IMakeReactiveOptions): Mobservable.IObservableValue; + (value: Object, opts?: Mobservable.IMakeReactiveOptions): T; +} + +interface IMobservableStatic extends _IMobservableStatic, IMakeReactive { +} + +declare namespace Mobservable { + interface IMakeReactiveOptions { + as?: string /* "auto" | "reference" | TODO: see #8 "structure" */ + scope?: Object, + context?: Object, + recurse?: boolean; + name?: string; + // protected: boolean TODO: see #9 + } + + export interface IContextInfoStruct { + object: Object; + name: string; + } + + export type IContextInfo = IContextInfoStruct | string; + + interface Lambda { + (): void; + name?: string; + } + + interface IObservable { + observe(callback: (...args: any[])=>void, fireImmediately?: boolean): Lambda; + } + + interface IObservableValue extends IObservable { + (): T; + (value: T):void; + observe(callback: (newValue: T, oldValue: T)=>void, fireImmediately?: boolean): Lambda; + } + + interface IObservableArray extends IObservable, Array { + spliceWithArray(index: number, deleteCount?: number, newItems?: T[]): T[]; + observe(listener: (changeData: IArrayChange|IArraySplice)=>void, fireImmediately?: boolean): Lambda; + clear(): T[]; + replace(newItems: T[]): T[]; + find(predicate: (item: T,index: number,array: IObservableArray)=>boolean,thisArg?: any,fromIndex?: number): T; + remove(value: T): boolean; + } + + interface IArrayChange { + type: string; // Always: 'update' + object: IObservableArray; + index: number; + oldValue: T; + } + + interface IArraySplice { + type: string; // Always: 'splice' + object: IObservableArray; + index: number; + removed: T[]; + addedCount: number; + } + + interface IDependencyTree { + id: number; + name: string; + context: any; + dependencies?: IDependencyTree[]; + } + + interface IObserverTree { + id: number; + name: string; + context: any; + observers?: IObserverTree[]; + listeners?: number; // amount of functions manually attached using an .observe method + } + + interface ITransitionEvent { + id: number; + name: string; + context: Object; + state: string; + changed: boolean; + newValue: string; + } +} -/// declare module "mendixmodelsdk" { namespace sdk { namespace internal { diff --git a/meteor-roles/meteor-roles-tests.ts b/meteor-roles/meteor-roles-tests.ts index 8f73f13208..50552c82ff 100644 --- a/meteor-roles/meteor-roles-tests.ts +++ b/meteor-roles/meteor-roles-tests.ts @@ -1,6 +1,3 @@ -/// - - import * as _ from 'underscore'; /** diff --git a/meteor/README.md b/meteor/README.md index 7c8aa5cb1d..f560dd005e 100644 --- a/meteor/README.md +++ b/meteor/README.md @@ -1,15 +1,8 @@ -# Meteor Type Definitions [DEPRECATED] - -## Deprecated - -These definitions for Meteor are now deprecated. They should still work for versions of Meteor up to 1.2.1. - -The canonical TypeScript definitions for Meteor can now be found using the NPM [Typings definition manager](https://www.npmjs.com/package/typings). If you prefer to view the definitions directly, or contribute to them, they can be found here: . - +# Meteor Type Definitions ## Description -These are the definitions for version 1.3 of Meteor. These definitions were generated from the from the same [Meteor data.js file] (https://github.com/meteor/meteor/blob/devel/docs/client/data.js) that is used to generate the official [Meteor docs] (http://docs.meteor.com/). The code that generates these definitions can be found [here](https://github.com/meteor-typescript/meteor-typescript-libs/). +These are the definitions for version 1.4 of Meteor. These definitions were generated from the from the same [Meteor data.js file] (https://github.com/meteor/meteor/blob/devel/docs/client/data.js) that is used to generate the official [Meteor docs] (http://docs.meteor.com/). The code that generates these definitions can be found [here](https://github.com/meteor-typescript/meteor-typescript-libs/). ## Upcoming Meteor `typescript` package diff --git a/meteor/index.d.ts b/meteor/index.d.ts index 0eb949e57b..b33973f943 100644 --- a/meteor/index.d.ts +++ b/meteor/index.d.ts @@ -1,915 +1,2143 @@ -// Type definitions for Meteor 1.3 +// Type definitions for Meteor 1.4 // Project: http://www.meteor.com/ -// Definitions by: Dave Allen +// Definitions by: Alex Borodach , Dave Allen , Olivier Refalo , Daniel Neveux , Birk Skyum // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/** - * These are the common (for client and server) modules and interfaces that can't be automatically generated from the Meteor data.js file - */ +interface URLS { + resetPassword: (token: string) => string; + verifyEmail: (token: string) => string; + enrollAccount: (token: string) => string; +} +declare module Accounts { + var urls: URLS; + + function user(): Meteor.User; + + function userId(): string; + + function createUser(options: { + username?: string; + email?: string; + password?: string; + profile?: Object; + }, callback?: Function): string; + + function config(options: { + sendVerificationEmail?: boolean; + forbidClientAccountCreation?: boolean; + restrictCreationByEmailDomain?: string | Function; + loginExpirationInDays?: number; + oauthSecretKey?: string; + }): void; + + function onLogin(func: Function): { + stop: () => void + }; + + function onLoginFailure(func: Function): { + stop: () => void + }; + + function loginServicesConfigured(): boolean; + + function onPageLoadLogin(func: Function): void; +} + +declare module "meteor/accounts-base" { + interface URLS { + resetPassword: (token: string) => string; + verifyEmail: (token: string) => string; + enrollAccount: (token: string) => string; + } + + module Accounts { + var urls: URLS; + + function user(): Meteor.User; + + function userId(): string; + + function createUser(options: { + username?: string; + email?: string; + password?: string; + profile?: Object; + }, callback?: Function): string; + + function config(options: { + sendVerificationEmail?: boolean; + forbidClientAccountCreation?: boolean; + restrictCreationByEmailDomain?: string | Function; + loginExpirationInDays?: number; + oauthSecretKey?: string; + }): void; + + function onLogin(func: Function): { + stop: () => void + }; + + function onLoginFailure(func: Function): { + stop: () => void + }; + + function loginServicesConfigured(): boolean; + + function onPageLoadLogin(func: Function): void; + } +} + +declare module Accounts { + function changePassword(oldPassword: string, newPassword: string, callback?: Function): void; + + function forgotPassword(options: { + email?: string; + }, callback?: Function): void; + + function resetPassword(token: string, newPassword: string, callback?: Function): void; + + function verifyEmail(token: string, callback?: Function): void; + + function onEmailVerificationLink(callback: Function): void; + + function onEnrollmentLink(callback: Function): void; + + function onResetPasswordLink(callback: Function): void; + + function loggingIn(): boolean; + + function logout(callback?: Function): void; + + function logoutOtherClients(callback?: Function): void; + + var ui: { + config(options: { + requestPermissions?: Object; + requestOfflineToken?: Object; + forceApprovalPrompt?: Object; + passwordSignupFields?: string; + }): void; + }; +} + +declare module "meteor/accounts-base" { + module Accounts { + function changePassword(oldPassword: string, newPassword: string, callback?: Function): void; + + function forgotPassword(options: { + email?: string; + }, callback?: Function): void; + + function resetPassword(token: string, newPassword: string, callback?: Function): void; + + function verifyEmail(token: string, callback?: Function): void; + + function onEmailVerificationLink(callback: Function): void; + + function onEnrollmentLink(callback: Function): void; + + function onResetPasswordLink(callback: Function): void; + + function loggingIn(): boolean; + + function logout(callback?: Function): void; + + function logoutOtherClients(callback?: Function): void; + + var ui: { + config(options: { + requestPermissions?: Object; + requestOfflineToken?: Object; + forceApprovalPrompt?: Object; + passwordSignupFields?: string; + }): void; + }; + } +} + +interface EmailFields { + from?: () => string; + subject?: (user: Meteor.User) => string; + text?: (user: Meteor.User, url: string) => string; + html?: (user: Meteor.User, url: string) => string; +} + +interface Header { + [id: string]: string; +} + +interface EmailTemplates { + from: string; + siteName: string; + headers?: Header; + resetPassword: EmailFields; + enrollAccount: EmailFields; + verifyEmail: EmailFields; +} + +declare module Accounts { + var emailTemplates: EmailTemplates; + + function addEmail(userId: string, newEmail: string, verified?: boolean): void; + + function removeEmail(userId: string, email: string): void; + + function onCreateUser(func: Function): void; + + function findUserByEmail(email: string): Object; + + function findUserByUsername(username: string): Object; + + function sendEnrollmentEmail(userId: string, email?: string): void; + + function sendResetPasswordEmail(userId: string, email?: string): void; + + function sendVerificationEmail(userId: string, email?: string): void; + + function setUsername(userId: string, newUsername: string): void; + + function setPassword(userId: string, newPassword: string, options?: { + logout?: Object; + }): void; + + function validateNewUser(func: Function): boolean; + + function validateLoginAttempt(func: Function): { + stop: () => void + }; + + function _hashPassword(password: string): { digest: string; algorithm: string; }; + + interface IValidateLoginAttemptCbOpts { + type: string; + allowed: boolean; + error: Meteor.Error; + user: Meteor.User; + connection: Meteor.Connection; + methodName: string; + methodArguments: any[]; + } +} + +declare module "meteor/accounts-base" { + interface EmailFields { + from?: () => string; + subject?: (user: Meteor.User) => string; + text?: (user: Meteor.User, url: string) => string; + html?: (user: Meteor.User, url: string) => string; + } + + interface Header { + [id: string]: string; + } + + interface EmailTemplates { + from: string; + siteName: string; + headers?: Header; + resetPassword: EmailFields; + enrollAccount: EmailFields; + verifyEmail: EmailFields; + } + + module Accounts { + var emailTemplates: EmailTemplates; + + function addEmail(userId: string, newEmail: string, verified?: boolean): void; + + function removeEmail(userId: string, email: string): void; + + function onCreateUser(func: Function): void; + + function findUserByEmail(email: string): Object; + + function findUserByUsername(username: string): Object; + + function sendEnrollmentEmail(userId: string, email?: string): void; + + function sendResetPasswordEmail(userId: string, email?: string): void; + + function sendVerificationEmail(userId: string, email?: string): void; + + function setUsername(userId: string, newUsername: string): void; + + function setPassword(userId: string, newPassword: string, options?: { + logout?: Object; + }): void; + + function validateNewUser(func: Function): boolean; + + function validateLoginAttempt(func: Function): { + stop: () => void + }; + + function _hashPassword(password: string): { digest: string; algorithm: string; }; + + interface IValidateLoginAttemptCbOpts { + type: string; + allowed: boolean; + error: Meteor.Error; + user: Meteor.User; + connection: Meteor.Connection; + methodName: string; + methodArguments: any[]; + } + } +} + +declare module Blaze { + var View: ViewStatic; + + interface ViewStatic { + new (name?: string, renderFunction?: Function): View; + } + + interface View { + name: string; + parentView: View; + isCreated: boolean; + isRendered: boolean; + isDestroyed: boolean; + renderCount: number; + autorun(runFunc: (computation: Tracker.Computation) => void): Tracker.Computation; + onViewCreated(func: Function): void; + onViewReady(func: Function): void; + onViewDestroyed(func: Function): void; + firstNode(): Node; + lastNode(): Node; + template: Template; + templateInstance(): TemplateInstance; + } + var currentView: View; + + function isTemplate(value: any): boolean; + + interface HelpersMap { + [key: string]: Function; + } + + interface EventsMap { + [key: string]: Function; + } + + var Template: TemplateStatic; + + interface TemplateStatic { + new (viewName?: string, renderFunction?: Function): Template; + + registerHelper(name: string, func: Function): void; + instance(): TemplateInstance; + currentData(): any; + parentData(numLevels: number): any; + } + + interface Template { + viewName: string; + renderFunction: Function; + constructView(): View; + head: Template; + find(selector: string): HTMLElement; + findAll(selector: string): HTMLElement[]; + $: any; + onCreated(cb: Function): void; + onRendered(cb: Function): void; + onDestroyed(cb: Function): void; + created: Function; + rendered: Function; + destroyed: Function; + helpers(helpersMap: HelpersMap): void; + events(eventsMap: EventsMap): void; + } + + var TemplateInstance: TemplateInstanceStatic; + + interface TemplateInstanceStatic { + new (view: View): TemplateInstance; + } + + interface TemplateInstance { + $(selector: string): any; + autorun(runFunc: (computation: Tracker.Computation) => void): Tracker.Computation; + data: Object; + find(selector: string): HTMLElement; + findAll(selector: string): HTMLElement[]; + firstNode: Object; + lastNode: Object; + subscribe(name: string, ...args: any[]): Meteor.SubscriptionHandle; + subscriptionsReady(): boolean; + view: Object; + } + + function Each(argFunc: Function, contentFunc: Function, elseFunc?: Function): View; + + function Unless(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): View; + + function If(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): View; + + function Let(bindings: Function, contentFunc: Function): View; + + function With(data: Object | Function, contentFunc: Function): View; + + function getData(elementOrView?: HTMLElement | View): Object; + + function getView(element?: HTMLElement): View; + + function remove(renderedView: View): void; + + function render(templateOrView: Template | View, parentNode: Node, nextNode?: Node, parentView?: View): View; + + function renderWithData(templateOrView: Template | View, data: Object | Function, parentNode: Node, nextNode?: Node, parentView?: View): View; + + function toHTML(templateOrView: Template | View): string; + + function toHTMLWithData(templateOrView: Template | View, data: Object | Function): string; +} + +declare module "meteor/blaze" { + module Blaze { + var View: ViewStatic; + + interface ViewStatic { + new (name?: string, renderFunction?: Function): View; + } + + interface View { + name: string; + parentView: View; + isCreated: boolean; + isRendered: boolean; + isDestroyed: boolean; + renderCount: number; + autorun(runFunc: (computation: Tracker.Computation) => void): Tracker.Computation; + onViewCreated(func: Function): void; + onViewReady(func: Function): void; + onViewDestroyed(func: Function): void; + firstNode(): Node; + lastNode(): Node; + template: Template; + templateInstance(): TemplateInstance; + } + var currentView: View; + + function isTemplate(value: any): boolean; + + interface HelpersMap { + [key: string]: Function; + } + + interface EventsMap { + [key: string]: Function; + } + + var Template: TemplateStatic; + + interface TemplateStatic { + new (viewName?: string, renderFunction?: Function): Template; + + registerHelper(name: string, func: Function): void; + instance(): TemplateInstance; + currentData(): any; + parentData(numLevels: number): any; + } + + interface Template { + viewName: string; + renderFunction: Function; + constructView(): View; + head: Template; + find(selector: string): HTMLElement; + findAll(selector: string): HTMLElement[]; + $: any; + onCreated(cb: Function): void; + onRendered(cb: Function): void; + onDestroyed(cb: Function): void; + created: Function; + rendered: Function; + destroyed: Function; + helpers(helpersMap: HelpersMap): void; + events(eventsMap: EventsMap): void; + } + + var TemplateInstance: TemplateInstanceStatic; + + interface TemplateInstanceStatic { + new (view: View): TemplateInstance; + } + + interface TemplateInstance { + $(selector: string): any; + autorun(runFunc: (computation: Tracker.Computation) => void): Tracker.Computation; + data: Object; + find(selector: string): HTMLElement; + findAll(selector: string): HTMLElement[]; + firstNode: Object; + lastNode: Object; + subscribe(name: string, ...args: any[]): Meteor.SubscriptionHandle; + subscriptionsReady(): boolean; + view: Object; + } + + function Each(argFunc: Function, contentFunc: Function, elseFunc?: Function): View; + + function Unless(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): View; + + function If(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): View; + + function Let(bindings: Function, contentFunc: Function): View; + + function With(data: Object | Function, contentFunc: Function): View; + + function getData(elementOrView?: HTMLElement | View): Object; + + function getView(element?: HTMLElement): View; + + function remove(renderedView: View): void; + + function render(templateOrView: Template | View, parentNode: Node, nextNode?: Node, parentView?: View): View; + + function renderWithData(templateOrView: Template | View, data: Object | Function, parentNode: Node, nextNode?: Node, parentView?: View): View; + + function toHTML(templateOrView: Template | View): string; + + function toHTMLWithData(templateOrView: Template | View, data: Object | Function): string; + } +} + +declare module BrowserPolicy { + var framing: { + disallow(): void; + restrictToOrigin(origin: string): void; + allowAll(): void; + }; + + var content: { + allowEval(): void; + allowInlineStyles(): void; + allowInlineScripts(): void; + allowSameOriginForAll(): void; + allowDataUrlForAll(): void; + allowOriginForAll(origin: string): void; + allowImageOrigin(origin: string): void; + allowMediaOrigin(origin: string): void; + allowFontOrigin(origin: string): void; + allowStyleOrigin(origin: string): void; + allowScriptOrigin(origin: string): void; + allowFrameOrigin(origin: string): void; + allowContentTypeSniffing(): void; + allowAllContentOrigin(): void; + allowAllContentDataUrl(): void; + allowAllContentSameOrigin(): void; + + disallowAll(): void; + disallowInlineStyles(): void; + disallowEval(): void; + disallowInlineScripts(): void; + disallowFont(): void; + disallowObject(): void; + disallowAllContent(): void; + }; +} + +declare module "meteor/browser-policy-common" { + module BrowserPolicy { + var framing: { + disallow(): void; + restrictToOrigin(origin: string): void; + allowAll(): void; + }; + + var content: { + allowEval(): void; + allowInlineStyles(): void; + allowInlineScripts(): void; + allowSameOriginForAll(): void; + allowDataUrlForAll(): void; + allowOriginForAll(origin: string): void; + allowImageOrigin(origin: string): void; + allowMediaOrigin(origin: string): void; + allowFontOrigin(origin: string): void; + allowStyleOrigin(origin: string): void; + allowScriptOrigin(origin: string): void; + allowFrameOrigin(origin: string): void; + allowContentTypeSniffing(): void; + allowAllContentOrigin(): void; + allowAllContentDataUrl(): void; + allowAllContentSameOrigin(): void; + + disallowAll(): void; + disallowInlineStyles(): void; + disallowEval(): void; + disallowInlineScripts(): void; + disallowFont(): void; + disallowObject(): void; + disallowAllContent(): void; + }; + } +} + +declare module Match { + var Any: any; + var String: any; + var Integer: any; + var Boolean: any; + var undefined: any; + var Object: any; + + function Optional(pattern: any): boolean; + + function ObjectIncluding(dico: any): boolean; + + function OneOf(...patterns: any[]): any; + + function Where(condition: any): any; + + function test(value: any, pattern: any): boolean; +} + +declare function check(value: any, pattern: any): void; + +declare module "meteor/check" { + module Match { + var Any: any; + var String: any; + var Integer: any; + var Boolean: any; + var undefined: any; + var Object: any; + + function Optional(pattern: any): boolean; + + function ObjectIncluding(dico: any): boolean; + + function OneOf(...patterns: any[]): any; + + function Where(condition: any): any; + + function test(value: any, pattern: any): boolean; + } + + function check(value: any, pattern: any): void; +} + +declare module DDPRateLimiter { + interface Matcher { + type?: string | ((type: string) => boolean); + name?: string | ((name: string) => boolean); + userId?: string | ((userId: string) => boolean); + connectionId?: string | ((connectionId: string) => boolean); + clientAddress?: string | ((clientAddress: string) => boolean); + } + + function addRule(matcher: Matcher, numRequests: number, timeInterval: number): string; + + function removeRule(ruleId: string): boolean; +} + +declare module "meteor/ddp-rate-limiter" { + module DDPRateLimiter { + interface Matcher { + type?: string | ((type: string) => boolean); + name?: string | ((name: string) => boolean); + userId?: string | ((userId: string) => boolean); + connectionId?: string | ((connectionId: string) => boolean); + clientAddress?: string | ((clientAddress: string) => boolean); + } + + function addRule(matcher: Matcher, numRequests: number, timeInterval: number): string; + + function removeRule(ruleId: string): boolean; + } +} + +declare module DDP { + interface DDPStatic { + subscribe(name: string, ...rest: any[]): Meteor.SubscriptionHandle; + call(method: string, ...parameters: any[]): void; + apply(method: string, ...parameters: any[]): void; + methods(IMeteorMethodsDictionary: any): any; + status(): DDPStatus; + reconnect(): void; + disconnect(): void; + onReconnect(): void; + } + + function _allSubscriptionsReady(): boolean; + + type Status = 'connected' | 'connecting' | 'failed' | 'waiting' | 'offline'; + + interface DDPStatus { + connected: boolean; + status: Status; + retryCount: number; + retryTime?: number; + reason?: string; + } + + function connect(url: string): DDPStatic; +} + +declare module DDPCommon { + interface MethodInvocation { + new (options: {}): MethodInvocation; + + unblock(): void; + + setUserId(userId: number): void; + } +} + +declare module "meteor/ddp" { + module DDP { + interface DDPStatic { + subscribe(name: string, ...rest: any[]): Meteor.SubscriptionHandle; + call(method: string, ...parameters: any[]): void; + apply(method: string, ...parameters: any[]): void; + methods(IMeteorMethodsDictionary: any): any; + status(): DDPStatus; + reconnect(): void; + disconnect(): void; + onReconnect(): void; + } + + function _allSubscriptionsReady(): boolean; + + type Status = 'connected' | 'connecting' | 'failed' | 'waiting' | 'offline'; + + interface DDPStatus { + connected: boolean; + status: Status; + retryCount: number; + retryTime?: number; + reason?: string; + } + + function connect(url: string): DDPStatic; + } + + module DDPCommon { + interface MethodInvocation { + new (options: {}): MethodInvocation; + + unblock(): void; + + setUserId(userId: number): void; + } + } +} + +interface EJSONableCustomType { + clone(): EJSONableCustomType; + equals(other: Object): boolean; + toJSONValue(): JSONable; + typeName(): string; +} interface EJSONable { - [key: string]: number | string | boolean | Object | number[] | string[] | Object[] | Date | Uint8Array | EJSON.CustomType; + [key: string]: number | string | boolean | Object | number[] | string[] | Object[] | Date | Uint8Array | EJSONableCustomType; } interface JSONable { - [key: string]: number | string | boolean | Object | number[] | string[] | Object[]; + [key: string]: number | string | boolean | Object | number[] | string[] | Object[]; } -interface EJSON extends EJSONable {} +interface EJSON extends EJSONable { } -declare namespace Match { - var Any: any; - var String: any; - var Integer: any; - var Boolean: any; - var undefined: any; - //function null(); // not allowed in TypeScript - var Object: any; - function Optional(pattern: any):boolean; - function ObjectIncluding(dico: any):boolean; - function OneOf(...patterns: any[]): any; - function Where(condition: any): any; +declare module EJSON { + function addType(name: string, factory: (val: JSONable) => EJSONableCustomType): void; + + function clone(val: T): T; + + function equals(a: EJSON, b: EJSON, options?: { + keyOrderSensitive?: boolean; + }): boolean; + + function fromJSONValue(val: JSONable): any; + + function isBinary(x: Object): boolean; + var newBinary: any; + + function parse(str: string): EJSON; + + function stringify(val: EJSON, options?: { + indent?: boolean | number | string; + canonical?: boolean; + }): string; + + function toJSONValue(val: EJSON): JSONable; } -declare namespace Meteor { - interface UserEmail { - address:string; - verified:boolean; - } +declare module "meteor/ejson" { + interface EJSONableCustomType { + clone(): EJSONableCustomType; + equals(other: Object): boolean; + toJSONValue(): JSONable; + typeName(): string; + } + interface EJSONable { + [key: string]: number | string | boolean | Object | number[] | string[] | Object[] | Date | Uint8Array | EJSONableCustomType; + } + interface JSONable { + [key: string]: number | string | boolean | Object | number[] | string[] | Object[]; + } + interface EJSON extends EJSONable { } - interface User { - _id?:string; - username?:string; - emails?:Meteor.UserEmail[]; - createdAt?: number; - profile?: any; - services?: any; - } + module EJSON { + function addType(name: string, factory: (val: JSONable) => EJSONableCustomType): void; - enum StatusEnum { - connected, - connecting, - failed, - waiting, - offline - } + function clone(val: T): T; - interface LiveQueryHandle { - stop(): void; - } + function equals(a: EJSON, b: EJSON, options?: { + keyOrderSensitive?: boolean; + }): boolean; + + function fromJSONValue(val: JSONable): any; + + function isBinary(x: Object): boolean; + var newBinary: any; + + function parse(str: string): EJSON; + + function stringify(val: EJSON, options?: { + indent?: boolean | number | string; + canonical?: boolean; + }): string; + + function toJSONValue(val: EJSON): JSONable; + } } -declare namespace DDP { - interface DDPStatic { - subscribe(name: string, ...rest: any[]): Meteor.SubscriptionHandle; - call(method: string, ...parameters: any[]):void; - apply(method: string, ...parameters: any[]):void; - methods(IMeteorMethodsDictionary: any): any; - status():DDPStatus; - reconnect(): void; - disconnect(): void; - onReconnect(): void; - } - - interface DDPStatus { - connected: boolean; - status: Meteor.StatusEnum; - retryCount: number; - //To turn this into an interval until the next reconnection, use retryTime - (new Date()).getTime() - retryTime?: number; - reason?: string; - } -} - -declare namespace Mongo { - interface Selector { - [key: string]:any; - } - interface Selector extends Object {} - interface Modifier {} - interface SortSpecifier {} - interface FieldSpecifier { - [id: string]: Number; - } -} - -declare namespace HTTP { - - interface HTTPRequest { - content?:string; - data?:any; - query?:string; - params?:{[id:string]:string}; - auth?:string; - headers?:{[id:string]:string}; - timeout?:number; - followRedirects?:boolean; - } - - interface HTTPResponse { - statusCode?:number; - headers?:{[id:string]: string}; - content?:string; - data?:any; - } - - function call(method: string, url: string, options?: HTTP.HTTPRequest, asyncCallback?:Function):HTTP.HTTPResponse; - function del(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; - function get(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; - function post(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; - function put(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; -} - -declare namespace Random { - function id(numberOfChars?: number): string; - function secret(numberOfChars?: number): string; - function fraction():number; - function hexString(numberOfDigits:number):string; // @param numberOfDigits, @returns a random hex string of the given length - function choice(array:any[]):string; // @param array, @return a random element in array - function choice(str:string):string; // @param str, @return a random char in str -} - -declare namespace Accounts { - function loginServicesConfigured(): boolean; - - function onPageLoadLogin(func: Function): void; -} -/** - * These are the client modules and interfaces that can't be automatically generated from the Meteor data.js file - */ - -declare namespace Meteor { - /** Start definitions for Template **/ - export interface Event { - type:string; - target:HTMLElement; - currentTarget:HTMLElement; - which: number; - stopPropagation():void; - stopImmediatePropagation():void; - preventDefault():void; - isPropagationStopped():boolean; - isImmediatePropagationStopped():boolean; - isDefaultPrevented():boolean; - } - - interface EventHandlerFunction extends Function { - (event?:Meteor.Event, templateInstance?: Blaze.TemplateInstance):void; - } - - interface EventMap { - [id:string]:Meteor.EventHandlerFunction; - } - /** End definitions for Template **/ - - interface LoginWithExternalServiceOptions { - requestPermissions?: string[]; - requestOfflineToken?: boolean; - loginUrlParameters?: {[param: string]: any} - loginHint?: string; - loginStyle?: string; - redirectUrl?: "popup" | "redirect"; - profile?: any; - email?: string; - } - - function loginWithMeteorDeveloperAccount(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithFacebook(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithGithub(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithGoogle(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithMeetup(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithTwitter(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithWeibo(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function _sleepForMs(milliseconds: number): void; - - interface SubscriptionHandle { - stop(): void; - ready(): boolean; - } -} - -declare namespace Blaze { - interface View { - name: string; - parentView: Blaze.View; - isCreated: boolean; - isRendered: boolean; - isDestroyed: boolean; - renderCount: number; - autorun(runFunc: Function): void; - onViewCreated(func: Function): void; - onViewReady(func: Function): void; - onViewDestroyed(func: Function): void; - firstNode(): Node; - lastNode(): Node; - template: Blaze.Template; - templateInstance(): any; - } - interface Template { - viewName: string; - renderFunction: Function; - constructView(): Blaze.View; - } -} - -declare namespace BrowserPolicy { - - interface framing { - disallow():void; - restrictToOrigin(origin:string):void; - allowAll():void; - } - interface content { - allowEval():void; - allowInlineStyles():void; - allowInlineScripts():void; - allowSameOriginForAll():void; - allowDataUrlForAll():void; - allowOriginForAll(origin:string):void; - allowImageOrigin(origin:string):void; - allowFrameOrigin(origin:string):void; - allowContentTypeSniffing():void; - allowAllContentOrigin():void; - allowAllContentDataUrl():void; - allowAllContentSameOrigin():void; - - disallowAll():void; - disallowInlineStyles():void; - disallowEval():void; - disallowInlineScripts():void; - disallowFont():void; - disallowObject():void; - disallowAllContent():void; - //TODO: add the basic content types - // allowOrigin(origin) - // allowDataUrl() - // allowSameOrigin() - // disallow() - } -} - - -/** - * These are the server modules and interfaces that can't be automatically generated from the Meteor data.js file - */ - -declare namespace Meteor { - interface EmailFields { - from?: () => string; - subject?: (user: Meteor.User) => string; - text?: (user: Meteor.User, url: string) => string; - html?: (user: Meteor.User, url: string) => string; - } - - interface EmailTemplates { - from?: string; - siteName?: string; - headers?: { [id: string]: string }; // TODO: should define IHeaders interface - resetPassword?: Meteor.EmailFields; - enrollAccount?: Meteor.EmailFields; - verifyEmail?: Meteor.EmailFields; - } - - interface Connection { - id: string; - close: Function; - onClose: Function; - clientAddress: string; - httpHeaders: Object; - } - - interface IValidateLoginAttemptCbOpts { - type: string; - allowed: boolean; - error: Error; - user: Meteor.User; - connection: Meteor.Connection; - methodName: string; - methodArguments: any[]; - } -} - -declare namespace Mongo { - interface AllowDenyOptions { - insert?: (userId: string, doc: any) => boolean; - update?: (userId: string, doc: any, fieldNames: string[], modifier: any) => boolean; - remove?: (userId: string, doc: any) => boolean; - fetch?: string[]; - transform?: Function; - } -} - -declare namespace Accounts { - interface IValidateLoginAttemptCbOpts { - type?: string; - allowed?: boolean; - error?: Meteor.Error; - user?: Meteor.User; - connection?: Meteor.Connection; - methodName?: string; - methodArguments?: any[]; - } +declare module Email { + function send(options: { + from?: string; + to?: string | string[]; + cc?: string | string[]; + bcc?: string | string[]; + replyTo?: string | string[]; + subject?: string; + text?: string; + html?: string; + headers?: Object; + attachments?: Object[]; + mailComposer?: MailComposer; + }): void; } interface MailComposerOptions { - escapeSMTP: boolean; - encoding: string; - charset: string; - keepBcc: boolean; - forceEmbeddedImages: boolean; + escapeSMTP: boolean; + encoding: string; + charset: string; + keepBcc: boolean; + forceEmbeddedImages: boolean; } declare var MailComposer: MailComposerStatic; interface MailComposerStatic { - new(options: MailComposerOptions): MailComposer; + new (options: MailComposerOptions): MailComposer; } interface MailComposer { - addHeader(name: string, value: string): void; - setMessageOption(from: string, to: string, body: string, html: string): void; - streamMessage(): void; - pipe(stream: any /** fs.WriteStream **/): void; -} -/** - * These are the modules and interfaces for packages that can't be automatically generated from the Meteor data.js file - */ - -interface ILengthAble { - length: number; + addHeader(name: string, value: string): void; + setMessageOption(from: string, to: string, body: string, html: string): void; + streamMessage(): void; + pipe(stream: any /** fs.WriteStream **/): void; } -interface ITinytestAssertions { - ok(doc: Object): void; - expect_fail(): void; - fail(doc: Object): void; - runId(): string; - equal(actual: T, expected: T, message?: string, not?: boolean): void; - notEqual(actual: T, expected: T, message?: string): void; - instanceOf(obj : Object, klass: Function, message?: string): void; - notInstanceOf(obj : Object, klass: Function, message?: string): void; - matches(actual : any, regexp: RegExp, message?: string): void; - notMatches(actual : any, regexp: RegExp, message?: string): void; - throws(f: Function, expected?: string|RegExp): void; - isTrue(v: boolean, msg?: string): void; - isFalse(v: boolean, msg?: string): void; - isNull(v: any, msg?: string): void; - isNotNull(v: any, msg?: string): void; - isUndefined(v: any, msg?: string): void; - isNotUndefined(v: any, msg?: string): void; - isNan(v: any, msg?: string): void; - isNotNan(v: any, msg?: string): void; - include(s: Array|Object|string, value: any, msg?: string, not?: boolean): void; +declare module "meteor/email" { + module Email { + function send(options: { + from?: string; + to?: string | string[]; + cc?: string | string[]; + bcc?: string | string[]; + replyTo?: string | string[]; + subject?: string; + text?: string; + html?: string; + headers?: Object; + attachments?: Object[]; + mailComposer?: MailComposer; + }): void; + } - notInclude(s: Array|Object|string, value: any, msg?: string, not?: boolean): void; - length(obj: ILengthAble, expected_length: number, msg?: string): void; - _stringEqual(actual: string, expected: string, msg?: string): void; + interface MailComposerOptions { + escapeSMTP: boolean; + encoding: string; + charset: string; + keepBcc: boolean; + forceEmbeddedImages: boolean; + } + + var MailComposer: MailComposerStatic; + interface MailComposerStatic { + new (options: MailComposerOptions): MailComposer; + } + interface MailComposer { + addHeader(name: string, value: string): void; + setMessageOption(from: string, to: string, body: string, html: string): void; + streamMessage(): void; + pipe(stream: any /** fs.WriteStream **/): void; + } } -declare namespace Tinytest { - function add(description : string , func : (test : ITinytestAssertions) => void) : void; - function addAsync(description : string , func : (test : ITinytestAssertions) => void) : void; +declare module HTTP { + interface HTTPRequest { + content?: string; + data?: any; + query?: string; + params?: { + [id: string]: string + }; + auth?: string; + headers?: { + [id: string]: string + }; + timeout?: number; + followRedirects?: boolean; + } + + interface HTTPResponse { + statusCode?: number; + headers?: { + [id: string]: string + }; + content?: string; + data?: any; + } + + function call(method: string, url: string, options?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function del(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function get(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function post(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function put(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function call(method: string, url: string, options?: { + content?: string; + data?: Object; + query?: string; + params?: Object; + auth?: string; + headers?: Object; + timeout?: number; + followRedirects?: boolean; + npmRequestOptions?: Object; + beforeSend?: Function; + }, asyncCallback?: Function): HTTP.HTTPResponse; } -// Kept in for backwards compatibility -declare namespace Meteor { - interface Tinytest { - add(description : string , func : (test : ITinytestAssertions) => void) : void; - addAsync(description : string , func : (test : ITinytestAssertions) => void) : void; - } +declare module "meteor/http" { + module HTTP { + interface HTTPRequest { + content?: string; + data?: any; + query?: string; + params?: { + [id: string]: string + }; + auth?: string; + headers?: { + [id: string]: string + }; + timeout?: number; + followRedirects?: boolean; + } + + interface HTTPResponse { + statusCode?: number; + headers?: { + [id: string]: string + }; + content?: string; + data?: any; + } + + function call(method: string, url: string, options?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function del(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function get(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function post(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function put(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function call(method: string, url: string, options?: { + content?: string; + data?: Object; + query?: string; + params?: Object; + auth?: string; + headers?: Object; + timeout?: number; + followRedirects?: boolean; + npmRequestOptions?: Object; + beforeSend?: Function; + }, asyncCallback?: Function): HTTP.HTTPResponse; + } } -declare namespace Accounts { - function addEmail(userId: string, newEmail: string, verified?: boolean): void; - function changePassword(oldPassword: string, newPassword: string, callback?: Function): void; - function createUser(options: { - username?: string; - email?: string; - password?: string; - profile?: Object; - }, callback?: Function): string; - var emailTemplates: Meteor.EmailTemplates; - function findUserByEmail(email: string): Object; - function findUserByUsername(username: string): Object; - function forgotPassword(options: { - email?: string; - }, callback?: Function): void; - function onEmailVerificationLink(callback: Function): void; - function onEnrollmentLink(callback: Function): void; - function onResetPasswordLink(callback: Function): void; - function removeEmail(userId: string, email: string): void; - function resetPassword(token: string, newPassword: string, callback?: Function): void; - function sendEnrollmentEmail(userId: string, email?: string): void; - function sendResetPasswordEmail(userId: string, email?: string): void; - function sendVerificationEmail(userId: string, email?: string): void; - function setPassword(userId: string, newPassword: string, options?: { - logout?: Object; - }): void; - function setUsername(userId: string, newUsername: string): void; - var ui: { - config(options: { - requestPermissions?: Object; - requestOfflineToken?: Object; - forceApprovalPrompt?: Object; - passwordSignupFields?: string; - }): void; - }; - function verifyEmail(token: string, callback?: Function): void; - function config(options: { - sendVerificationEmail?: boolean; - forbidClientAccountCreation?: boolean; - restrictCreationByEmailDomain?: string | Function; - loginExpirationInDays?: number; - oauthSecretKey?: string; - }): void; - function onLogin(func: Function): { stop: () => void }; - function onLoginFailure(func: Function): { stop: () => void }; - function user(): Meteor.User; - function userId(): string; - function loggingIn(): boolean; - function logout(callback?: Function): void; - function logoutOtherClients(callback?: Function): void; - function onCreateUser(func: Function): void; - function validateLoginAttempt(cb: (params: Accounts.IValidateLoginAttemptCbOpts) => boolean): { stop: () => void }; - function validateNewUser(func: Function): boolean; - function _hashPassword(password: string): { digest: string; algorithm: string; }; +declare module Meteor { + /** Global props **/ + var isClient: boolean; + var isCordova: boolean; + var isServer: boolean; + var isProduction: boolean; + var release: string; + /** Global props **/ + + /** Settings **/ + interface Settings { + public: { + [id: string]: any + }, [id: string]: any + } + var settings: Settings; + /** Settings **/ + + /** User **/ + interface UserEmail { + address: string; + verified: boolean; + } + interface User { + _id?: string; + username?: string; + emails?: UserEmail[]; + createdAt?: number; + profile?: any; + services?: any; + } + + function user(): User; + + function userId(): string; + var users: Mongo.Collection; + /** User **/ + + /** Error **/ + var Error: ErrorStatic; + interface ErrorStatic { + new (error: string | number, reason?: string, details?: string): Error; + } + interface Error { + error: string | number; + reason?: string; + details?: string; + } + /** Error **/ + + /** Method **/ + function methods(methods: Object): void; + + function call(name: string, ...args: any[]): any; + + function apply(name: string, args: EJSONable[], options?: { + wait?: boolean; + onResultReceived?: Function; + }, asyncCallback?: Function): any; + /** Method **/ + + /** Url **/ + function absoluteUrl(path?: string, options?: { + secure?: boolean; + replaceLocalhost?: boolean; + rootUrl?: string; + }): string; + /** Url **/ + + /** Timeout **/ + function setInterval(func: Function, delay: number): number; + + function setTimeout(func: Function, delay: number): number; + + function clearInterval(id: number): void; + + function clearTimeout(id: number): void; + + function defer(func: Function): void; + /** Timeout **/ + + /** utils **/ + function startup(func: Function): void; + + function wrapAsync(func: Function, context?: Object): any; + + function bindEnvironment(func: Function): any; + /** utils **/ + + /** Pub/Sub **/ + interface SubscriptionHandle { + stop(): void; + ready(): boolean; + } + interface LiveQueryHandle { + stop(): void; + } + /** Pub/Sub **/ } -declare namespace App { - function accessRule(pattern: string, options?: { - type?: string; - launchExternal?: boolean; - }): void; - function configurePlugin(id: string, config: Object): void; - function icons(icons: Object): void; - function info(options: { - id?: string; - version?: string; - name?: string; - description?: string; - author?: string; - email?: string; - website?: string; - }): void; - function launchScreens(launchScreens: Object): void; - function setPreference(name: string, value: string, platform?: string): void; +declare module "meteor/meteor" { + module Meteor { + /** Global props **/ + var isClient: boolean; + var isCordova: boolean; + var isServer: boolean; + var isProduction: boolean; + var release: string; + /** Global props **/ + + /** Settings **/ + interface Settings { + public: { + [id: string]: any + }, [id: string]: any + } + var settings: Settings; + /** Settings **/ + + /** User **/ + interface UserEmail { + address: string; + verified: boolean; + } + interface User { + _id?: string; + username?: string; + emails?: UserEmail[]; + createdAt?: number; + profile?: any; + services?: any; + } + + function user(): User; + + function userId(): string; + var users: Mongo.Collection; + /** User **/ + + /** Error **/ + var Error: ErrorStatic; + interface ErrorStatic { + new (error: string | number, reason?: string, details?: string): Error; + } + interface Error { + error: string | number; + reason?: string; + details?: string; + } + /** Error **/ + + /** Method **/ + function methods(methods: Object): void; + + function call(name: string, ...args: any[]): any; + + function apply(name: string, args: EJSONable[], options?: { + wait?: boolean; + onResultReceived?: Function; + }, asyncCallback?: Function): any; + /** Method **/ + + /** Url **/ + function absoluteUrl(path?: string, options?: { + secure?: boolean; + replaceLocalhost?: boolean; + rootUrl?: string; + }): string; + /** Url **/ + + /** Timeout **/ + function setInterval(func: Function, delay: number): number; + + function setTimeout(func: Function, delay: number): number; + + function clearInterval(id: number): void; + + function clearTimeout(id: number): void; + + function defer(func: Function): void; + /** Timeout **/ + + /** utils **/ + function startup(func: Function): void; + + function wrapAsync(func: Function, context?: Object): any; + + function bindEnvironment(func: Function): any; + /** utils **/ + + /** Pub/Sub **/ + interface SubscriptionHandle { + stop(): void; + ready(): boolean; + } + interface LiveQueryHandle { + stop(): void; + } + /** Pub/Sub **/ + } } -declare namespace Assets { - function getBinary(assetPath: string, asyncCallback?: Function): EJSON; - function getText(assetPath: string, asyncCallback?: Function): string; +declare module Meteor { + /** Login **/ + interface LoginWithExternalServiceOptions { + requestPermissions?: string[]; + requestOfflineToken?: Boolean; + forceApprovalPrompt?: Boolean; + loginUrlParameters?: Object; + redirectUrl?: string; + loginHint?: string; + loginStyle?: string; + } + + function loginWithMeteorDeveloperAccount(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithFacebook(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithGithub(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithGoogle(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithMeetup(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithTwitter(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithWeibo(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loggingIn(): boolean; + + function loginWith(options?: { + requestPermissions?: string[]; + requestOfflineToken?: boolean; + loginUrlParameters?: Object; + userEmail?: string; + loginStyle?: string; + redirectUrl?: string; + }, callback?: Function): void; + + function loginWithPassword(user: Object | string, password: string, callback?: Function): void; + + function loginWithToken(token: string, callback?: Function): void; + + function logout(callback?: Function): void; + + function logoutOtherClients(callback?: Function): void; + /** Login **/ + + /** Event **/ + interface Event { + type: string; + target: HTMLElement; + currentTarget: HTMLElement; + which: number; + stopPropagation(): void; + stopImmediatePropagation(): void; + preventDefault(): void; + isPropagationStopped(): boolean; + isImmediatePropagationStopped(): boolean; + isDefaultPrevented(): boolean; + } + interface EventHandlerFunction extends Function { + (event?: Meteor.Event, templateInstance?: Blaze.TemplateInstance): void; + } + interface EventMap { + [id: string]: Meteor.EventHandlerFunction; + } + /** Event **/ + + /** Connection **/ + function reconnect(): void; + + function disconnect(): void; + /** Connection **/ + + /** Status **/ + function status(): DDP.DDPStatus; + /** Status **/ + + /** Pub/Sub **/ + function subscribe(name: string, ...args: any[]): Meteor.SubscriptionHandle; + /** Pub/Sub **/ } -declare namespace Blaze { - function Each(argFunc: Function, contentFunc: Function, elseFunc?: Function): Blaze.View; - function If(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): Blaze.View; - function Let(bindings: Function, contentFunc: Function): Blaze.View; - var Template: TemplateStatic; - interface TemplateStatic { - new(viewName?: string, renderFunction?: Function): Template; - // It should be [templateName: string]: TemplateInstance but this is not possible -- user will need to cast to TemplateInstance - [templateName: string]: any | Template; // added "any" to make it work - head: Template; - find(selector:string):Blaze.Template; - findAll(selector:string):Blaze.Template[]; - $:any; - } - interface Template { - } +declare module "meteor/meteor" { + module Meteor { + /** Login **/ + interface LoginWithExternalServiceOptions { + requestPermissions?: string[]; + requestOfflineToken?: Boolean; + forceApprovalPrompt?: Boolean; + loginUrlParameters?: Object; + redirectUrl?: string; + loginHint?: string; + loginStyle?: string; + } - var TemplateInstance: TemplateInstanceStatic; - interface TemplateInstanceStatic { - new(view: Blaze.View): TemplateInstance; - } - interface TemplateInstance { - $(selector: string): any; - autorun(runFunc: Function): Object; - data: Object; - find(selector?: string): Blaze.TemplateInstance; - findAll(selector: string): Blaze.TemplateInstance[]; - firstNode: Object; - lastNode: Object; - subscribe(name: string, ...args: any[]): Meteor.SubscriptionHandle; - subscriptionsReady(): boolean; - view: Object; - } + function loginWithMeteorDeveloperAccount(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function Unless(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): Blaze.View; - var View: ViewStatic; - interface ViewStatic { - new(name?: string, renderFunction?: Function): View; - } - interface View { - } + function loginWithFacebook(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function With(data: Object | Function, contentFunc: Function): Blaze.View; - var currentView: Blaze.View; - function getData(elementOrView?: HTMLElement | Blaze.View): Object; - function getView(element?: HTMLElement): Blaze.View; - function isTemplate(value: any): boolean; - function remove(renderedView: Blaze.View): void; - function render(templateOrView: Template | Blaze.View, parentNode: Node, nextNode?: Node, parentView?: Blaze.View): Blaze.View; - function renderWithData(templateOrView: Template | Blaze.View, data: Object | Function, parentNode: Node, nextNode?: Node, parentView?: Blaze.View): Blaze.View; - function toHTML(templateOrView: Template | Blaze.View): string; - function toHTMLWithData(templateOrView: Template | Blaze.View, data: Object | Function): string; + function loginWithGithub(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithGoogle(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithMeetup(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithTwitter(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithWeibo(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loggingIn(): boolean; + + function loginWith(options?: { + requestPermissions?: string[]; + requestOfflineToken?: boolean; + loginUrlParameters?: Object; + userEmail?: string; + loginStyle?: string; + redirectUrl?: string; + }, callback?: Function): void; + + function loginWithPassword(user: Object | string, password: string, callback?: Function): void; + + function loginWithToken(token: string, callback?: Function): void; + + function logout(callback?: Function): void; + + function logoutOtherClients(callback?: Function): void; + /** Login **/ + + /** Event **/ + interface Event { + type: string; + target: HTMLElement; + currentTarget: HTMLElement; + which: number; + stopPropagation(): void; + stopImmediatePropagation(): void; + preventDefault(): void; + isPropagationStopped(): boolean; + isImmediatePropagationStopped(): boolean; + isDefaultPrevented(): boolean; + } + interface EventHandlerFunction extends Function { + (event?: Meteor.Event, templateInstance?: Blaze.TemplateInstance): void; + } + interface EventMap { + [id: string]: Meteor.EventHandlerFunction; + } + /** Event **/ + + /** Connection **/ + function reconnect(): void; + + function disconnect(): void; + /** Connection **/ + + /** Status **/ + function status(): DDP.DDPStatus; + /** Status **/ + + /** Pub/Sub **/ + function subscribe(name: string, ...args: any[]): Meteor.SubscriptionHandle; + /** Pub/Sub **/ + } } -declare namespace Cordova { - function depends(dependencies:{[id:string]:string}): void; +declare module Meteor { + /** Connection **/ + interface Connection { + id: string; + close: Function; + onClose: Function; + clientAddress: string; + httpHeaders: Object; + } + + function onConnection(callback: Function): void; + /** Connection **/ + + function publish(name: string, func: Function): void; + + function _debug(...args: any[]): void; } -declare namespace DDP { - function connect(url: string): DDP.DDPStatic; +interface Subscription { + added(collection: string, id: string, fields: Object): void; + changed(collection: string, id: string, fields: Object): void; + connection: Meteor.Connection; + error(error: Error): void; + onStop(func: Function): void; + ready(): void; + removed(collection: string, id: string): void; + stop(): void; + userId: string; } -declare namespace DDPCommon { - function MethodInvocation(options: { - }): any; +declare module "meteor/meteor" { + module Meteor { + /** Connection **/ + interface Connection { + id: string; + close: Function; + onClose: Function; + clientAddress: string; + httpHeaders: Object; + } + + function onConnection(callback: Function): void; + /** Connection **/ + + function publish(name: string, func: Function): void; + + function _debug(...args: any[]): void; + } + + interface Subscription { + added(collection: string, id: string, fields: Object): void; + changed(collection: string, id: string, fields: Object): void; + connection: Meteor.Connection; + error(error: Error): void; + onStop(func: Function): void; + ready(): void; + removed(collection: string, id: string): void; + stop(): void; + userId: string; + } } -declare namespace EJSON { - var CustomType: CustomTypeStatic; - interface CustomTypeStatic { - new(): CustomType; - } - interface CustomType { - clone(): EJSON.CustomType; - equals(other: Object): boolean; - toJSONValue(): JSONable; - typeName(): string; - } +declare module Mongo { + interface Selector { + [key: string]: any; + } + interface Selector extends Object { } + interface Modifier { } + interface SortSpecifier { } + interface FieldSpecifier { + [id: string]: Number; + } - function addType(name: string, factory: (val: JSONable) => EJSON.CustomType): void; - function clone(val:T): T; - function equals(a: EJSON, b: EJSON, options?: { - keyOrderSensitive?: boolean; - }): boolean; - function fromJSONValue(val: JSONable): any; - function isBinary(x: Object): boolean; - var newBinary: any; - function parse(str: string): EJSON; - function stringify(val: EJSON, options?: { - indent?: boolean | number | string; - canonical?: boolean; - }): string; - function toJSONValue(val: EJSON): JSONable; + var Collection: CollectionStatic; + interface CollectionStatic { + new (name: string, options?: { + connection?: Object; + idGeneration?: string; + transform?: Function; + }): Collection; + } + interface Collection { + allow(options: { + insert?: (userId: string, doc: T) => boolean; + update?: (userId: string, doc: T, fieldNames: string[], modifier: any) => boolean; + remove?: (userId: string, doc: T) => boolean; + fetch?: string[]; + transform?: Function; + }): boolean; + deny(options: { + insert?: (userId: string, doc: T) => boolean; + update?: (userId: string, doc: T, fieldNames: string[], modifier: any) => boolean; + remove?: (userId: string, doc: T) => boolean; + fetch?: string[]; + transform?: Function; + }): boolean; + find(selector?: Selector | ObjectID | string, options?: { + sort?: SortSpecifier; + skip?: number; + limit?: number; + fields?: FieldSpecifier; + reactive?: boolean; + transform?: Function; + }): Cursor; + findOne(selector?: Selector | ObjectID | string, options?: { + sort?: SortSpecifier; + skip?: number; + fields?: FieldSpecifier; + reactive?: boolean; + transform?: Function; + }): T; + insert(doc: T, callback?: Function): string; + rawCollection(): any; + rawDatabase(): any; + remove(selector: Selector | ObjectID | string, callback?: Function): number; + update(selector: Selector | ObjectID | string, modifier: Modifier, options?: { + multi?: boolean; + upsert?: boolean; + }, callback?: Function): number; + upsert(selector: Selector | ObjectID | string, modifier: Modifier, options?: { + multi?: boolean; + }, callback?: Function): { + numberAffected?: number; insertedId?: string; + }; + _ensureIndex(keys: { + [key: string]: number | string + } | string, options?: { + [key: string]: any + }): void; + _dropIndex(keys: { + [key: string]: number | string + } | string): void; + } + + var Cursor: CursorStatic; + interface CursorStatic { + new (): Cursor; + } + interface ObserveCallbacks { + added?(document: Object): void; + addedAt?(document: Object, atIndex: number, before: Object): void; + changed?(newDocument: Object, oldDocument: Object): void; + changedAt?(newDocument: Object, oldDocument: Object, indexAt: number): void; + removed?(oldDocument: Object): void; + removedAt?(oldDocument: Object, atIndex: number): void; + movedTo?(document: Object, fromIndex: number, toIndex: number, before: Object): void; + } + interface ObserveChangesCallbacks { + added?(id: string, fields: Object): void; + addedBefore?(id: string, fields: Object, before: Object): void; + changed?(id: string, fields: Object): void; + movedBefore?(id: string, before: Object): void; + removed?(id: string): void; + } + interface Cursor { + count(applySkipLimit?: boolean): number; + fetch(): Array; + forEach(callback: < T > (doc: T, index: number, cursor: Cursor) => void, thisArg?: any): void; + map(callback: (doc: T, index: number, cursor: Cursor) => U, thisArg?: any): Array; + observe(callbacks: ObserveCallbacks): Meteor.LiveQueryHandle; + observeChanges(callbacks: ObserveChangesCallbacks): Meteor.LiveQueryHandle; + } + + var ObjectID: ObjectIDStatic; + interface ObjectIDStatic { + new (hexString?: string): ObjectID; + } + interface ObjectID { } } -declare namespace Match { - function test(value: any, pattern: any): boolean; +declare module "meteor/mongo" { + module Mongo { + interface Selector { + [key: string]: any; + } + interface Selector extends Object { } + interface Modifier { } + interface SortSpecifier { } + interface FieldSpecifier { + [id: string]: Number; + } + + var Collection: CollectionStatic; + interface CollectionStatic { + new (name: string, options?: { + connection?: Object; + idGeneration?: string; + transform?: Function; + }): Collection; + } + interface Collection { + allow(options: { + insert?: (userId: string, doc: T) => boolean; + update?: (userId: string, doc: T, fieldNames: string[], modifier: any) => boolean; + remove?: (userId: string, doc: T) => boolean; + fetch?: string[]; + transform?: Function; + }): boolean; + deny(options: { + insert?: (userId: string, doc: T) => boolean; + update?: (userId: string, doc: T, fieldNames: string[], modifier: any) => boolean; + remove?: (userId: string, doc: T) => boolean; + fetch?: string[]; + transform?: Function; + }): boolean; + find(selector?: Selector | ObjectID | string, options?: { + sort?: SortSpecifier; + skip?: number; + limit?: number; + fields?: FieldSpecifier; + reactive?: boolean; + transform?: Function; + }): Cursor; + findOne(selector?: Selector | ObjectID | string, options?: { + sort?: SortSpecifier; + skip?: number; + fields?: FieldSpecifier; + reactive?: boolean; + transform?: Function; + }): T; + insert(doc: T, callback?: Function): string; + rawCollection(): any; + rawDatabase(): any; + remove(selector: Selector | ObjectID | string, callback?: Function): number; + update(selector: Selector | ObjectID | string, modifier: Modifier, options?: { + multi?: boolean; + upsert?: boolean; + }, callback?: Function): number; + upsert(selector: Selector | ObjectID | string, modifier: Modifier, options?: { + multi?: boolean; + }, callback?: Function): { + numberAffected?: number; insertedId?: string; + }; + _ensureIndex(keys: { + [key: string]: number | string + } | string, options?: { + [key: string]: any + }): void; + _dropIndex(keys: { + [key: string]: number | string + } | string): void; + } + + var Cursor: CursorStatic; + interface CursorStatic { + new (): Cursor; + } + interface ObserveCallbacks { + added?(document: Object): void; + addedAt?(document: Object, atIndex: number, before: Object): void; + changed?(newDocument: Object, oldDocument: Object): void; + changedAt?(newDocument: Object, oldDocument: Object, indexAt: number): void; + removed?(oldDocument: Object): void; + removedAt?(oldDocument: Object, atIndex: number): void; + movedTo?(document: Object, fromIndex: number, toIndex: number, before: Object): void; + } + interface ObserveChangesCallbacks { + added?(id: string, fields: Object): void; + addedBefore?(id: string, fields: Object, before: Object): void; + changed?(id: string, fields: Object): void; + movedBefore?(id: string, before: Object): void; + removed?(id: string): void; + } + interface Cursor { + count(applySkipLimit?: boolean): number; + fetch(): Array; + forEach(callback: < T > (doc: T, index: number, cursor: Cursor) => void, thisArg?: any): void; + map(callback: (doc: T, index: number, cursor: Cursor) => U, thisArg?: any): Array; + observe(callbacks: ObserveCallbacks): Meteor.LiveQueryHandle; + observeChanges(callbacks: ObserveChangesCallbacks): Meteor.LiveQueryHandle; + } + + var ObjectID: ObjectIDStatic; + interface ObjectIDStatic { + new (hexString?: string): ObjectID; + } + interface ObjectID { } + } } -declare namespace Meteor { - var Error: ErrorStatic; - interface ErrorStatic { - new(error: string | number, reason?: string, details?: string): Error; - } - interface Error { - error: string | number; - reason?: string; - details?: string; - } - function absoluteUrl(path?: string, options?: { - secure?: boolean; - replaceLocalhost?: boolean; - rootUrl?: string; - }): string; - function apply(name: string, args: EJSONable[], options?: { - wait?: boolean; - onResultReceived?: Function; - }, asyncCallback?: Function): any; - function call(name: string, ...args: any[]): any; - function clearInterval(id: number): void; - function clearTimeout(id: number): void; - function disconnect(): void; - var isClient: boolean; - var isCordova: boolean; - var isDevelopment: boolean; - var isProduction: boolean; - var isServer: boolean; - var isTest: boolean; - function loggingIn(): boolean; - function loginWith(options?: { - requestPermissions?: string[]; - requestOfflineToken?: boolean; - loginUrlParameters?: Object; - loginHint?: string; - loginStyle?: string; - redirectUrl?: string; - }, callback?: Function): void; - function loginWithPassword(user: Object | string, password: string, callback?: Function): void; - function logout(callback?: Function): void; - function logoutOtherClients(callback?: Function): void; - function methods(methods: Object): void; - function onConnection(callback: Function): void; - function publish(name: string, func: Function): void; - function reconnect(): void; - var release: string; - function setInterval(func: Function, delay: number): number; - function setTimeout(func: Function, delay: number): number; - var settings: { public: {[id:string]: any}, private: {[id:string]: any}, [id:string]: any}; - function startup(func: Function): void; - function status(): Meteor.StatusEnum; - function subscribe(name: string, ...args: any[]): Meteor.SubscriptionHandle; - function user(): Meteor.User; - function userId(): string; - var users: Mongo.Collection; - function wrapAsync(func: Function, context?: Object): any; +declare module Mongo { + interface AllowDenyOptions { + insert?: (userId: string, doc: any) => boolean; + update?: (userId: string, doc: any, fieldNames: string[], modifier: any) => boolean; + remove?: (userId: string, doc: any) => boolean; + fetch?: string[]; + transform?: Function; + } } -declare namespace Mongo { - var Collection: CollectionStatic; - interface CollectionStatic { - new(name: string, options?: { - connection?: Object; - idGeneration?: string; - transform?: Function; - }): Collection; - } - interface Collection { - allow(options: { - insert?: (userId: string, doc: T) => boolean; - update?: (userId: string, doc: T, fieldNames: string[], modifier: any) => boolean; - remove?: (userId: string, doc: T) => boolean; - fetch?: string[]; - transform?: Function; - }): boolean; - deny(options: { - insert?: (userId: string, doc: T) => boolean; - update?: (userId: string, doc: T, fieldNames: string[], modifier: any) => boolean; - remove?: (userId: string, doc: T) => boolean; - fetch?: string[]; - transform?: Function; - }): boolean; - find(selector?: Mongo.Selector | Mongo.ObjectID | string, options?: { - sort?: Mongo.SortSpecifier; - skip?: number; - limit?: number; - fields?: Mongo.FieldSpecifier; - reactive?: boolean; - transform?: Function; - disableOplog?: boolean; - pollingIntervalMs?: number; - pollingThrottleMs?: number; - }): Mongo.Cursor; - findOne(selector?: Mongo.Selector | Mongo.ObjectID | string, options?: { - sort?: Mongo.SortSpecifier; - skip?: number; - fields?: Mongo.FieldSpecifier; - reactive?: boolean; - transform?: Function; - }): T; - insert(doc: T, callback?: Function): string; - rawCollection(): any; - rawDatabase(): any; - remove(selector: Mongo.Selector | Mongo.ObjectID | string, callback?: Function): number; - update(selector: Mongo.Selector | Mongo.ObjectID | string, modifier: Mongo.Modifier, options?: { - multi?: boolean; - upsert?: boolean; - }, callback?: Function): number; - upsert(selector: Mongo.Selector | Mongo.ObjectID | string, modifier: Mongo.Modifier, options?: { - multi?: boolean; - }, callback?: Function): {numberAffected?: number; insertedId?: string;}; - _ensureIndex(indexName: string, options?: {[key: string]: any}): void; - } - - var Cursor: CursorStatic; - interface CursorStatic { - new(): Cursor; - } - interface Cursor { - count(): number; - fetch(): Array; - forEach(callback: (doc: T, index: number, cursor: Mongo.Cursor) => void, thisArg?: any): void; - map(callback: (doc: T, index: number, cursor: Mongo.Cursor) => U, thisArg?: any): Array; - observe(callbacks: Object): Meteor.LiveQueryHandle; - observeChanges(callbacks: Object): Meteor.LiveQueryHandle; - } - - var ObjectID: ObjectIDStatic; - interface ObjectIDStatic { - new(hexString?: string): ObjectID; - } - interface ObjectID { - valueOf(): string; - getTimestamp(): Date; - } - +declare module "meteor/mongo" { + module Mongo { + interface AllowDenyOptions { + insert?: (userId: string, doc: any) => boolean; + update?: (userId: string, doc: any, fieldNames: string[], modifier: any) => boolean; + remove?: (userId: string, doc: any) => boolean; + fetch?: string[]; + transform?: Function; + } + } } -declare namespace Npm { - function depends(dependencies:{[id:string]:string}): void; - function require(name: string): any; +declare module Random { + function id(numberOfChars?: number): string; + + function secret(numberOfChars?: number): string; + + function fraction(): number; + // @param numberOfDigits, @returns a random hex string of the given length + function hexString(numberOfDigits: number): string; + // @param array, @return a random element in array + function choice(array: any[]): string; + // @param str, @return a random char in str + function choice(str: string): string; } -declare namespace Package { - function describe(options: { - summary?: string; - version?: string; - name?: string; - git?: string; - documentation?: string; - debugOnly?: boolean; - prodOnly?: boolean; - testOnly?: boolean; - }): void; - function onTest(func: Function): void; - function onUse(func: Function): void; - function registerBuildPlugin(options?: { - name?: string; - use?: string | string[]; - sources?: string[]; - npmDependencies?: Object; - }): void; -} +declare module "meteor/random" { + module Random { + function id(numberOfChars?: number): string; -declare namespace Tracker { - function Computation(): void; - interface Computation { - firstRun: boolean; - invalidate(): void; - invalidated: boolean; - onInvalidate(callback: Function): void; - onStop(callback: Function): void; - stop(): void; - stopped: boolean; - } + function secret(numberOfChars?: number): string; - var Dependency: DependencyStatic; - interface DependencyStatic { - new(): Dependency; - } - interface Dependency { - changed(): void; - depend(fromComputation?: Tracker.Computation): boolean; - hasDependents(): boolean; - } - - var active: boolean; - function afterFlush(callback: Function): void; - function autorun(runFunc: (computation: Tracker.Computation) => void, options?: { - onError?: Function; - }): Tracker.Computation; - var currentComputation: Tracker.Computation; - function flush(): void; - function nonreactive(func: Function): void; - function onInvalidate(callback: Function): void; -} - -declare namespace Session { - function equals(key: string, value: string | number | boolean | any /** Null **/ | any /** Undefined **/): boolean; - function get(key: string): any; - function set(key: string, value: EJSONable | any /** Undefined **/): void; - function setDefault(key: string, value: EJSONable | any /** Undefined **/): void; -} - -declare namespace HTTP { - function call(method: string, url: string, options?: { - content?: string; - data?: Object; - query?: string; - params?: Object; - auth?: string; - headers?: Object; - timeout?: number; - followRedirects?: boolean; - npmRequestOptions?: Object; - beforeSend?: Function; - }, asyncCallback?: Function): HTTP.HTTPResponse; - function del(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse; - function get(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse; - function patch(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse; - function post(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse; - function put(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse; -} - -declare namespace Email { - function send(options: { - from?: string; - to?: string | string[]; - cc?: string | string[]; - bcc?: string | string[]; - replyTo?: string | string[]; - subject?: string; - text?: string; - html?: string; - headers?: Object; - attachments?: Object[]; - mailComposer?: MailComposer; - }): void; -} - -declare var CompileStep: CompileStepStatic; -interface CompileStepStatic { - new(): CompileStep; -} -interface CompileStep { - addAsset(options: { - }, path: string, data: any /** Buffer **/ | string): any; - addHtml(options: { - section?: string; - data?: string; - }): any; - addJavaScript(options: { - path?: string; - data?: string; - sourcePath?: string; - }): any; - addStylesheet(options: { - }, path: string, data: string, sourceMap: string): any; - arch: any; - declaredExports: any; - error(options: { - }, message: string, sourcePath?: string, line?: number, func?: string): any; - fileOptions: any; - fullInputPath: any; - inputPath: any; - inputSize: any; - packageName: any; - pathForSourceMap: any; - read(n?: number): any; - rootOutputPath: any; -} - -declare var PackageAPI: PackageAPIStatic; -interface PackageAPIStatic { - new(): PackageAPI; -} -interface PackageAPI { - addAssets(filenames: string | string[], architecture: string | string[]): void; - addFiles(filenames: string | string[], architecture?: string | string[], options?: { - bare?: boolean; - }): void; - export(exportedObjects: string | string[], architecture?: string | string[], exportOptions?: Object, testOnly?: boolean): void; - imply(packageNames: string | string[], architecture?: string | string[]): void; - use(packageNames: string | string[], architecture?: string | string[], options?: { - weak?: boolean; - unordered?: boolean; - }): void; - versionsFrom(meteorRelease: string | string[]): void; + function fraction(): number; + // @param numberOfDigits, @returns a random hex string of the given length + function hexString(numberOfDigits: number): string; + // @param array, @return a random element in array + function choice(array: any[]): string; + // @param str, @return a random char in str + function choice(str: string): string; + } } declare var ReactiveVar: ReactiveVarStatic; interface ReactiveVarStatic { - new(initialValue: T, equalsFunc?: Function): ReactiveVar; + new (initialValue: T, equalsFunc?: Function): ReactiveVar; } interface ReactiveVar { - get(): T; - set(newValue: T): void; + get(): T; + set(newValue: T): void; } -declare var Subscription: SubscriptionStatic; -interface SubscriptionStatic { - new(): Subscription; +declare module "meteor/reactive-var" { + var ReactiveVar: ReactiveVarStatic; + interface ReactiveVarStatic { + new (initialValue: T, equalsFunc?: Function): ReactiveVar; + } + interface ReactiveVar { + get(): T; + set(newValue: T): void; + } } -interface Subscription { - added(collection: string, id: string, fields: Object): void; - changed(collection: string, id: string, fields: Object): void; - connection: Meteor.Connection; - error(error: Error): void; - onStop(func: Function): void; - ready(): void; - removed(collection: string, id: string): void; - stop(): void; - userId: string; + +declare module Session { + function equals(key: string, value: string | number | boolean | any): boolean; + + function get(key: string): any; + + function set(key: string, value: EJSONable | any): void; + + function setDefault(key: string, value: EJSONable | any): void; +} + +declare module "meteor/session" { + module Session { + function equals(key: string, value: string | number | boolean | any): boolean; + + function get(key: string): any; + + function set(key: string, value: EJSONable | any): void; + + function setDefault(key: string, value: EJSONable | any): void; + } } declare var Template: TemplateStatic; -interface TemplateStatic { - new(): Template; - // It should be [templateName: string]: TemplateInstance but this is not possible -- user will need to cast to TemplateInstance - [templateName: string]: any | Template; // added "any" to make it work - head: Template; - find(selector:string):Blaze.Template; - findAll(selector:string):Blaze.Template[]; - $:any; - body: Template; - currentData(): {}; - deregisterHelper(name: string): void; - instance(): Blaze.TemplateInstance; - parentData(numLevels?: number): {}; - registerHelper(name: string, helperFunction: Function): void; +interface TemplateStatic extends Blaze.TemplateStatic { + new (viewName?: string, renderFunction?: Function): Blaze.Template; + body: Blaze.Template; + [index: string]: any | Blaze.Template; } -interface Template { - created: Function; - destroyed: Function; - events(eventMap: Meteor.EventMap): void; - helpers(helpers:{[id:string]: any}): void; - onCreated: Function; - onDestroyed: Function; - onRendered: Function; - rendered: Function; + +declare module "meteor/templating" { + var Template: TemplateStatic; + interface TemplateStatic extends Blaze.TemplateStatic { + new (viewName?: string, renderFunction?: Function): Blaze.Template; + body: Blaze.Template; + [index: string]: any | Blaze.Template; + } +} + +interface ILengthAble { + length: number; +} + +interface ITinytestAssertions { + ok(doc: Object): void; + expect_fail(): void; + fail(doc: Object): void; + runId(): string; + equal(actual: T, expected: T, message?: string, not?: boolean): void; + notEqual(actual: T, expected: T, message?: string): void; + instanceOf(obj: Object, klass: Function, message?: string): void; + notInstanceOf(obj: Object, klass: Function, message?: string): void; + matches(actual: any, regexp: RegExp, message?: string): void; + notMatches(actual: any, regexp: RegExp, message?: string): void; + throws(f: Function, expected?: string | RegExp): void; + isTrue(v: boolean, msg?: string): void; + isFalse(v: boolean, msg?: string): void; + isNull(v: any, msg?: string): void; + isNotNull(v: any, msg?: string): void; + isUndefined(v: any, msg?: string): void; + isNotUndefined(v: any, msg?: string): void; + isNan(v: any, msg?: string): void; + isNotNan(v: any, msg?: string): void; + include(s: Array | Object | string, value: any, msg?: string, not?: boolean): void; + + notInclude(s: Array | Object | string, value: any, msg?: string, not?: boolean): void; + length(obj: ILengthAble, expected_length: number, msg?: string): void; + _stringEqual(actual: string, expected: string, msg?: string): void; +} + +declare module Tinytest { + function add(description: string, func: (test: ITinytestAssertions) => void): void; + + function addAsync(description: string, func: (test: ITinytestAssertions) => void): void; +} + +declare module "meteor/tiny-test" { + interface ILengthAble { + length: number; + } + + interface ITinytestAssertions { + ok(doc: Object): void; + expect_fail(): void; + fail(doc: Object): void; + runId(): string; + equal(actual: T, expected: T, message?: string, not?: boolean): void; + notEqual(actual: T, expected: T, message?: string): void; + instanceOf(obj: Object, klass: Function, message?: string): void; + notInstanceOf(obj: Object, klass: Function, message?: string): void; + matches(actual: any, regexp: RegExp, message?: string): void; + notMatches(actual: any, regexp: RegExp, message?: string): void; + throws(f: Function, expected?: string | RegExp): void; + isTrue(v: boolean, msg?: string): void; + isFalse(v: boolean, msg?: string): void; + isNull(v: any, msg?: string): void; + isNotNull(v: any, msg?: string): void; + isUndefined(v: any, msg?: string): void; + isNotUndefined(v: any, msg?: string): void; + isNan(v: any, msg?: string): void; + isNotNan(v: any, msg?: string): void; + include(s: Array | Object | string, value: any, msg?: string, not?: boolean): void; + + notInclude(s: Array | Object | string, value: any, msg?: string, not?: boolean): void; + length(obj: ILengthAble, expected_length: number, msg?: string): void; + _stringEqual(actual: string, expected: string, msg?: string): void; + } + + module Tinytest { + function add(description: string, func: (test: ITinytestAssertions) => void): void; + + function addAsync(description: string, func: (test: ITinytestAssertions) => void): void; + } +} + +declare module App { + function accessRule(pattern: string, options?: { + type?: string; + launchExternal?: boolean; + }): void; + + function configurePlugin(id: string, config: Object): void; + + function icons(icons: Object): void; + + function info(options: { + id?: string; + version?: string; + name?: string; + description?: string; + author?: string; + email?: string; + website?: string; + }): void; + + function launchScreens(launchScreens: Object): void; + + function setPreference(name: string, value: string, platform?: string): void; } -declare function check(value: any, pattern: any): void; declare function execFileAsync(command: string, args?: any[], options?: { - cwd?: Object; - env?: Object; - stdio?: any[] | string; - destination?: any; - waitForClose?: string; + cwd?: Object; + env?: Object; + stdio?: any[] | string; + destination?: any; + waitForClose?: string; }): any; declare function execFileSync(command: string, args?: any[], options?: { - cwd?: Object; - env?: Object; - stdio?: any[] | string; - destination?: any; - waitForClose?: string; + cwd?: Object; + env?: Object; + stdio?: any[] | string; + destination?: any; + waitForClose?: string; }): String; -declare function getExtension(): String; + +declare module Assets { + function getBinary(assetPath: string, asyncCallback?: Function): EJSON; + + function getText(assetPath: string, asyncCallback?: Function): string; + + function absoluteFilePath(assetPath: string): string; +} + +declare module Cordova { + function depends(dependencies: { + [id: string]: string + }): void; +} + +declare module Npm { + function depends(dependencies: { + [id: string]: string + }): void; + + function require(name: string): any; +} + +declare namespace Package { + function describe(options: { + summary?: string; + version?: string; + name?: string; + git?: string; + documentation?: string; + debugOnly?: boolean; + prodOnly?: boolean; + testOnly?: boolean; + }): void; + + function onTest(func: (api: PackageAPI) => void): void; + + function onUse(func: (api: PackageAPI) => void): void; + + function registerBuildPlugin(options?: { + name?: string; + use?: string | string[]; + sources?: string[]; + npmDependencies?: Object; + }): void; +} + +interface PackageAPI { + new (): PackageAPI; + addAssets(filenames: string | string[], architecture: string | string[]): void; + addFiles(filenames: string | string[], architecture?: string | string[], options?: { + bare?: boolean; + }): void; + export(exportedObjects: string | string[], architecture?: string | string[], exportOptions?: Object, testOnly?: boolean): void; + imply(packageNames: string | string[], architecture?: string | string[]): void; + use(packageNames: string | string[], architecture?: string | string[], options?: { + weak?: boolean; + unordered?: boolean; + }): void; + versionsFrom(meteorRelease: string | string[]): void; +} + +declare var console: Console; + +declare module "meteor/tools" { + module App { + function accessRule(pattern: string, options?: { + type?: string; + launchExternal?: boolean; + }): void; + + function configurePlugin(id: string, config: Object): void; + + function icons(icons: Object): void; + + function info(options: { + id?: string; + version?: string; + name?: string; + description?: string; + author?: string; + email?: string; + website?: string; + }): void; + + function launchScreens(launchScreens: Object): void; + + function setPreference(name: string, value: string, platform?: string): void; + } + + function execFileAsync(command: string, args?: any[], options?: { + cwd?: Object; + env?: Object; + stdio?: any[] | string; + destination?: any; + waitForClose?: string; + }): any; + + function execFileSync(command: string, args?: any[], options?: { + cwd?: Object; + env?: Object; + stdio?: any[] | string; + destination?: any; + waitForClose?: string; + }): String; + + module Assets { + function getBinary(assetPath: string, asyncCallback?: Function): EJSON; + + function getText(assetPath: string, asyncCallback?: Function): string; + + function absoluteFilePath(assetPath: string): string; + } + + module Cordova { + function depends(dependencies: { + [id: string]: string + }): void; + } + + module Npm { + function depends(dependencies: { + [id: string]: string + }): void; + + function require(name: string): any; + } + + namespace Package { + function describe(options: { + summary?: string; + version?: string; + name?: string; + git?: string; + documentation?: string; + debugOnly?: boolean; + prodOnly?: boolean; + testOnly?: boolean; + }): void; + + function onTest(func: (api: PackageAPI) => void): void; + + function onUse(func: (api: PackageAPI) => void): void; + + function registerBuildPlugin(options?: { + name?: string; + use?: string | string[]; + sources?: string[]; + npmDependencies?: Object; + }): void; + } + + interface PackageAPI { + new (): PackageAPI; + addAssets(filenames: string | string[], architecture: string | string[]): void; + addFiles(filenames: string | string[], architecture?: string | string[], options?: { + bare?: boolean; + }): void; + export(exportedObjects: string | string[], architecture?: string | string[], exportOptions?: Object, testOnly?: boolean): void; + imply(packageNames: string | string[], architecture?: string | string[]): void; + use(packageNames: string | string[], architecture?: string | string[], options?: { + weak?: boolean; + unordered?: boolean; + }): void; + versionsFrom(meteorRelease: string | string[]): void; + } + + var console: Console; +} + +declare module Tracker { + function Computation(): void; + interface Computation { + firstRun: boolean; + invalidate(): void; + invalidated: boolean; + onInvalidate(callback: Function): void; + onStop(callback: Function): void; + stop(): void; + stopped: boolean; + } + var currentComputation: Computation; + + var Dependency: DependencyStatic; + interface DependencyStatic { + new (): Dependency; + } + interface Dependency { + changed(): void; + depend(fromComputation?: Computation): boolean; + hasDependents(): boolean; + } + + var active: boolean; + + function afterFlush(callback: Function): void; + + function autorun(runFunc: (computation: Computation) => void, options?: { + onError?: Function; + }): Computation; + + function flush(): void; + + function nonreactive(func: Function): void; + + function onInvalidate(callback: Function): void; +} + +declare module "meteor/tracker" { + module Tracker { + function Computation(): void; + interface Computation { + firstRun: boolean; + invalidate(): void; + invalidated: boolean; + onInvalidate(callback: Function): void; + onStop(callback: Function): void; + stop(): void; + stopped: boolean; + } + var currentComputation: Computation; + + var Dependency: DependencyStatic; + interface DependencyStatic { + new (): Dependency; + } + interface Dependency { + changed(): void; + depend(fromComputation?: Computation): boolean; + hasDependents(): boolean; + } + + var active: boolean; + + function afterFlush(callback: Function): void; + + function autorun(runFunc: (computation: Computation) => void, options?: { + onError?: Function; + }): Computation; + + function flush(): void; + + function nonreactive(func: Function): void; + + function onInvalidate(callback: Function): void; + } +} + +declare module Match { + function Maybe(pattern: any): boolean; +} + +declare module "meteor/check" { + module Match { + function Maybe(pattern: any): boolean; + } +} + +declare module Meteor { + /** Global props **/ + var isDevelopment: boolean; + var isTest: boolean; + /** Global props **/ +} + +declare module "meteor/meteor" { + module Meteor { + /** Global props **/ + var isDevelopment: boolean; + var isTest: boolean; + /** Global props **/ + } +} + +declare module Accounts { + function onLogout(func: Function): void; +} + +declare module "meteor/accounts-base" { + module Accounts { + function onLogout(func: Function): void; + } +} + +declare module Accounts { + function onLogout(func: (user: Meteor.User, connection: Meteor.Connection) => void): void; +} + +declare module "meteor/accounts-base" { + module Accounts { + function onLogout(func: (user: Meteor.User, connection: Meteor.Connection) => void): void; + } +} diff --git a/meteor/meteor-tests.ts b/meteor/meteor-tests.ts index b700e4d616..c269105eb3 100644 --- a/meteor/meteor-tests.ts +++ b/meteor/meteor-tests.ts @@ -6,11 +6,24 @@ /*********************************** Begin setup for tests ******************************/ +import { Mongo } from "meteor/mongo"; +import { Meteor } from "meteor/meteor"; +import { check, Match } from "meteor/check"; +import { Tracker } from "meteor/tracker"; +import { Template } from "meteor/templating"; +import { Blaze } from "meteor/blaze"; +import { Session } from "meteor/session"; +import { HTTP } from "meteor/http"; +import { ReactiveVar } from "meteor/reactive-var"; +import { Accounts } from "meteor/accounts-base"; +import { BrowserPolicy } from "meteor/browser-policy-common"; +import { DDPRateLimiter } from "meteor/ddp-rate-limiter"; + var Rooms = new Mongo.Collection('rooms'); var Messages = new Mongo.Collection('messages'); interface MonkeyDAO { - _id: string; - name: string; + _id: string; + name: string; } var Monkeys = new Mongo.Collection('monkeys'); //var x = new Mongo.Collection('x'); @@ -23,72 +36,73 @@ var Monkeys = new Mongo.Collection('monkeys'); * Tests Meteor.isServer, Meteor.startup, Collection.insert(), Collection.find() */ if (Meteor.isServer) { - Meteor.startup(function () { - if (Rooms.find().count() === 0) { - Rooms.insert({name: "Initial room"}); - } - }); + Meteor.startup(function () { + if (Rooms.find().count() === 0) { + Rooms.insert({ name: "Initial room" }); + } + }); } /** * From Publish and Subscribe, Meteor.publish section **/ Meteor.publish("rooms", function () { - return Rooms.find({}, {fields: {secretInfo: 0}}); + return Rooms.find({}, { fields: { secretInfo: 0 } }); }); Meteor.publish("adminSecretInfo", function () { - return Rooms.find({admin: this.userId}, {fields: {secretInfo: 1}}); + return Rooms.find({ admin: this.userId }, { fields: { secretInfo: 1 } }); }); Meteor.publish("roomAndMessages", function (roomId: string) { - check(roomId, String); - return [ - Rooms.find({_id: roomId}, {fields: {secretInfo: 0}}), - Messages.find({roomId: roomId}) - ]; + check(roomId, String); + return [ + Rooms.find({ _id: roomId }, { fields: { secretInfo: 0 } }), + Messages.find({ roomId: roomId }) + ]; }); /** * Also from Publish and Subscribe, Meteor.publish section */ Meteor.publish("counts-by-room", function (roomId: string) { - var self = this; - check(roomId, String); - var count = 0; - var initializing = true; - var handle = Messages.find({roomId: roomId}).observeChanges({ - added: function (id: any) { - count++; -// if (!initializing) + var self = this; + check(roomId, String); + var count = 0; + var initializing = true; + var handle = Messages.find({ roomId: roomId }).observeChanges({ + added: function (id: any) { + count++; + // if (!initializing) + // this.changed("counts", roomId, {count: count}); + }, + removed: function (id: any) { + count--; + // Todo: Not sure how to define in typescript + // self.changed("counts", roomId, {count: count}); + } + }); -// Todo: Not sure how to define in typescript -// self.changed("counts", roomId, {count: count}); - }, - removed: function (id: any) { - count--; -// Todo: Not sure how to define in typescript -// self.changed("counts", roomId, {count: count}); - } - }); + initializing = false; - initializing = false; + // Todo: Not sure how to define in typescript + // self.added("counts", roomId, {count: count}); + self.ready(); -// Todo: Not sure how to define in typescript -// self.added("counts", roomId, {count: count}); - self.ready(); - - self.onStop(function () { - handle.stop(); - }); + self.onStop(function () { + handle.stop(); + }); }); var Counts = new Mongo.Collection("counts"); Tracker.autorun(function () { - Meteor.subscribe("counts-by-room", Session.get("roomId")); + Meteor.subscribe("counts-by-room", Session.get("roomId")); }); +// Checking status +let status: DDP.Status = 'connected'; + console.log("Current room has " + Counts.find(Session.get("roomId")).count + " messages."); @@ -102,47 +116,47 @@ Meteor.subscribe("allplayers"); * Also from Meteor.subscribe section */ Tracker.autorun(function () { - Meteor.subscribe("chat", {room: Session.get("current-room")}); - Meteor.subscribe("privateMessages"); + Meteor.subscribe("chat", { room: Session.get("current-room") }); + Meteor.subscribe("privateMessages"); }); /** * From Methods, Meteor.methods section */ Meteor.methods({ - foo: function (arg1: string, arg2: number[]) { - check(arg1, String); - check(arg2, [Number]); + foo: function (arg1: string, arg2: number[]) { + check(arg1, String); + check(arg2, [Number]); - var you_want_to_throw_an_error = true; - if (you_want_to_throw_an_error) - throw new Meteor.Error("404", "Can't find my pants"); - return "some return value"; - }, + var you_want_to_throw_an_error = true; + if (you_want_to_throw_an_error) + throw new Meteor.Error("404", "Can't find my pants"); + return "some return value"; + }, - bar: function () { - // .. do other stuff .. - return "baz"; - } + bar: function () { + // .. do other stuff .. + return "baz"; + } }); /** * From Methods, Meteor.Error section */ function meteorErrorTestFunction1() { - throw new Meteor.Error("logged-out", - "The user must be logged in to post a comment."); + throw new Meteor.Error("logged-out", + "The user must be logged in to post a comment."); } function meteorErrorTestFunction2() { - throw new Meteor.Error(403, - "The user must be logged in to post a comment."); + throw new Meteor.Error(403, + "The user must be logged in to post a comment."); } Meteor.call("methodName", function (error: Meteor.Error) { - if (error.error === "logged-out") { - Session.set("errorMessage", "Please log in to post a comment."); - } + if (error.error === "logged-out") { + Session.set("errorMessage", "Please log in to post a comment."); + } }); var error = new Meteor.Error("logged-out", "The user must be logged in to post a comment."); console.log(error.error === "logged-out"); @@ -152,7 +166,7 @@ console.log(error.details !== ""); /** * From Methods, Meteor.call section */ -Meteor.call('foo', 1, 2, function (error:any, result:any) {} ); +Meteor.call('foo', 1, 2, function (error: any, result: any) { }); var result = Meteor.call('foo', 1, 2); /** @@ -161,22 +175,22 @@ var result = Meteor.call('foo', 1, 2); // DA: I added the "var" keyword in there interface ChatroomsDAO { - _id?: string; + _id?: string; } interface MessagesDAO { - _id?: string; + _id?: string; } var Chatrooms = new Mongo.Collection("chatrooms"); Messages = new Mongo.Collection("messages"); -var myMessages:any[] = Messages.find({userId: Session.get('myUserId')}).fetch(); +var myMessages: any[] = Messages.find({ userId: Session.get('myUserId') }).fetch(); -Messages.insert({text: "Hello, world!"}); +Messages.insert({ text: "Hello, world!" }); -Messages.update(myMessages[0]._id, {$set: {important: true}}); +Messages.update(myMessages[0]._id, { $set: { important: true } }); var Posts = new Mongo.Collection("posts"); -Posts.insert({title: "Hello world", body: "First post"}); +Posts.insert({ title: "Hello world", body: "First post" }); // Couldn't find assert() in the meteor docs //assert(Posts.find().count() === 1); @@ -192,30 +206,30 @@ Posts.insert({title: "Hello world", body: "First post"}); **/ class Animal { - private sound:string; - constructor(doc:any) { + private sound: string; + constructor(doc: any) { } makeNoise() { - console.log(this.sound) + console.log(this.sound) } } interface AnimalDAO { - _id?: string; - name: string; - sound: string; - makeNoise?: () => void; + _id?: string; + name: string; + sound: string; + makeNoise?: () => void; } // Define a Collection that uses Animal as its document var Animals = new Mongo.Collection("Animals", { - transform: function (doc:any): Animal { return new Animal(doc); } + transform: function (doc: any): Animal { return new Animal(doc); } }); // Create an Animal and call its makeNoise method -Animals.insert({name: "raptor", sound: "roar"}); -Animals.findOne({name: "raptor"}).makeNoise(); // prints "roar" +Animals.insert({ name: "raptor", sound: "roar" }); +Animals.findOne({ name: "raptor" }).makeNoise(); // prints "roar" /** * From Collections, Collection.insert section @@ -224,9 +238,9 @@ Animals.findOne({name: "raptor"}).makeNoise(); // prints "roar" var Lists = new Mongo.Collection('Lists'); var Items = new Mongo.Collection('Lists'); -var groceriesId = Lists.insert({name: "Groceries"}); -Items.insert({list: groceriesId, name: "Watercress"}); -Items.insert({list: groceriesId, name: "Persimmons"}); +var groceriesId = Lists.insert({ name: "Groceries" }); +Items.insert({ list: groceriesId, name: "Watercress" }); +Items.insert({ list: groceriesId, name: "Persimmons" }); /** * From Collections, collection.update section @@ -234,39 +248,39 @@ Items.insert({list: groceriesId, name: "Persimmons"}); var Players = new Mongo.Collection('Players'); Template['adminDashboard'].events({ - 'click .givePoints': function () { - Players.update(Session.get("currentPlayer"), {$inc: {score: 5}}); - } + 'click .givePoints': function () { + Players.update(Session.get("currentPlayer"), { $inc: { score: 5 } }); + } }); /** * Also from Collections, collection.update section */ Meteor.methods({ - declareWinners: function () { - Players.update({score: {$gt: 10}}, - {$addToSet: {badges: "Winner"}}, - {multi: true}); - } + declareWinners: function () { + Players.update({ score: { $gt: 10 } }, + { $addToSet: { badges: "Winner" } }, + { multi: true }); + } }); /** * From Collections, collection.remove section */ Template['chat'].events({ - 'click .remove': function () { - Messages.remove(this._id); - } + 'click .remove': function () { + Messages.remove(this._id); + } }); // DA: I added this next line var Logs = new Mongo.Collection('logs'); Meteor.startup(function () { - if (Meteor.isServer) { - Logs.remove({}); - Players.remove({karma: {$lt: -2}}); - } + if (Meteor.isServer) { + Logs.remove({}); + Players.remove({ karma: { $lt: -2 } }); + } }); /*** @@ -274,50 +288,50 @@ Meteor.startup(function () { */ interface iPost { - _id: string; - owner: string; - userId: string; - locked: boolean; + _id: string; + owner: string; + userId: string; + locked: boolean; } Posts = new Mongo.Collection("posts"); Posts.allow({ - insert: function (userId:string, doc: iPost) { - // the user must be logged in, and the document must be owned by the user - return (userId && doc.owner === userId); - }, - update: function (userId:string, doc: iPost, fields:string[], modifier:any) { - // can only change your own documents - return doc.owner === userId; - }, - remove: function (userId:string, doc: iPost) { - // can only remove your own documents - return doc.owner === userId; - }, - fetch: ['owner'] + insert: function (userId: string, doc: iPost) { + // the user must be logged in, and the document must be owned by the user + return (userId && doc.owner === userId); + }, + update: function (userId: string, doc: iPost, fields: string[], modifier: any) { + // can only change your own documents + return doc.owner === userId; + }, + remove: function (userId: string, doc: iPost) { + // can only remove your own documents + return doc.owner === userId; + }, + fetch: ['owner'] }); Posts.deny({ - update: function (userId:string, doc: iPost, fields:string[], modifier:any) { - // can't change owners - return doc.userId !== userId; - }, - remove: function (userId:string, doc: iPost) { - // can't remove locked documents - return doc.locked; - }, - fetch: ['locked'] // no need to fetch 'owner' + update: function (userId: string, doc: iPost, fields: string[], modifier: any) { + // can't change owners + return doc.userId !== userId; + }, + remove: function (userId: string, doc: iPost) { + // can't remove locked documents + return doc.locked; + }, + fetch: ['locked'] // no need to fetch 'owner' }); /** * From Collections, cursor.forEach section */ -var topPosts = Posts.find({}, {sort: {score: -1}, limit: 5}); +var topPosts = Posts.find({}, { sort: { score: -1 }, limit: 5 }); var count = 0; -topPosts.forEach(function (post:{title:string}) { - console.log("Title of post " + count + ": " + post.title); - count += 1; +topPosts.forEach(function (post: { title: string }) { + console.log("Title of post " + count + ": " + post.title); + count += 1; }); /** @@ -327,26 +341,28 @@ topPosts.forEach(function (post:{title:string}) { var Users = new Mongo.Collection('users'); var count1 = 0; -var query = Users.find({admin: true, onlineNow: true}); +var query = Users.find({ admin: true, onlineNow: true }); var handle = query.observeChanges({ - added: function (id:string, user:{name:string}) { - count1++; - console.log(user.name + " brings the total to " + count1 + " admins."); - }, - removed: function () { - count1--; - console.log("Lost one. We're now down to " + count1 + " admins."); - } + added: function (id: string, user: { name: string }) { + count1++; + console.log(user.name + " brings the total to " + count1 + " admins."); + }, + removed: function () { + count1--; + console.log("Lost one. We're now down to " + count1 + " admins."); + } }); +let cursor: Mongo.Cursor; + // After five seconds, stop keeping the count. -setTimeout(function () {handle.stop();}, 5000); +setTimeout(function () { handle.stop(); }, 5000); /** * From Sessions, Session.set section */ Tracker.autorun(function () { - Meteor.subscribe("chat-history", {room: Session.get("currentRoomId")}); + Meteor.subscribe("chat-history", { room: Session.get("currentRoomId") }); }); // Causes the function passed to Tracker.autorun to be re-run, so @@ -375,59 +391,59 @@ Session.equals("key", value); * From Accounts, Meteor.users section */ Meteor.publish("userData", function () { - return Meteor.users.find({_id: this.userId}, - {fields: {'other': 1, 'things': 1}}); + return Meteor.users.find({ _id: this.userId }, + { fields: { 'other': 1, 'things': 1 } }); }); -Meteor.users.deny({update: function () { return true; }}); +Meteor.users.deny({ update: function () { return true; } }); /** * From Accounts, Meteor.loginWithExternalService section */ Meteor.loginWithGithub({ - requestPermissions: ['user', 'public_repo'] + requestPermissions: ['user', 'public_repo'] }, function (err: Meteor.Error) { - if (err) - Session.set('errorMessage', err.reason || 'Unknown error'); + if (err) + Session.set('errorMessage', err.reason || 'Unknown error'); }); /** * From Accounts, Accounts.ui.config section */ Accounts.ui.config({ - requestPermissions: { - facebook: ['user_likes'], - github: ['user', 'repo'] - }, - requestOfflineToken: { - google: true - }, - passwordSignupFields: 'USERNAME_AND_OPTIONAL_EMAIL' + requestPermissions: { + facebook: ['user_likes'], + github: ['user', 'repo'] + }, + requestOfflineToken: { + google: true + }, + passwordSignupFields: 'USERNAME_AND_OPTIONAL_EMAIL' }); /** * From Accounts, Accounts.validateNewUser section */ -Accounts.validateNewUser(function (user:{username:string}) { - if (user.username && user.username.length >= 3) - return true; - throw new Meteor.Error("403", "Username must have at least 3 characters"); +Accounts.validateNewUser(function (user: { username: string }) { + if (user.username && user.username.length >= 3) + return true; + throw new Meteor.Error("403", "Username must have at least 3 characters"); }); // Validate username, without a specific error message. -Accounts.validateNewUser(function (user:{username:string}) { - return user.username !== "root"; +Accounts.validateNewUser(function (user: { username: string }) { + return user.username !== "root"; }); /** * From Accounts, Accounts.onCreateUser section */ -Accounts.onCreateUser(function(options:{profile:any}, user:{profile:any, dexterity:number}) { - var d6 = function () { return Math.floor(Math.random() * 6) + 1; }; - user.dexterity = d6() + d6() + d6(); - // We still want the default hook's 'profile' behavior. - if (options.profile) - user.profile = options.profile; - return user; +Accounts.onCreateUser(function (options: { profile: any }, user: { profile: any, dexterity: number }) { + var d6 = function () { return Math.floor(Math.random() * 6) + 1; }; + user.dexterity = d6() + d6() + d6(); + // We still want the default hook's 'profile' behavior. + if (options.profile) + user.profile = options.profile; + return user; }); /** @@ -435,26 +451,27 @@ Accounts.onCreateUser(function(options:{profile:any}, user:{profile:any, dexteri */ Accounts.emailTemplates.siteName = "AwesomeSite"; Accounts.emailTemplates.from = "AwesomeSite Admin "; -Accounts.emailTemplates.enrollAccount.subject = function (user:{ profile:{name: string} }) { - return "Welcome to Awesome Town, " + user.profile.name; +Accounts.emailTemplates.enrollAccount.subject = function (user: { profile: { name: string } }) { + return "Welcome to Awesome Town, " + user.profile.name; }; -Accounts.emailTemplates.enrollAccount.text = function (user:any, url:string) { - return "You have been selected to participate in building a better future!" - + " To activate your account, simply click the link below:\n\n" - + url; +Accounts.emailTemplates.enrollAccount.text = function (user: any, url: string) { + return "You have been selected to participate in building a better future!" + + " To activate your account, simply click the link below:\n\n" + + url; }; /** * From Templates, Template.myTemplate.helpers section */ Template['adminDashboard'].helpers({ - foo: function () { - return Session.get("foo"); - } + foo: function () { + return Session.get("foo"); + } }); + Template['newTemplate'].helpers({ - helperName: function () { - } + helperName: function () { + } }); Template['newTemplate'].created = function () { @@ -470,12 +487,12 @@ Template['newTemplate'].destroyed = function () { }; Template['newTemplate'].events({ - 'click .something': function (event: Meteor.Event, template: Blaze.TemplateInstance) { - } + 'click .something': function (event: Meteor.Event, template: Blaze.TemplateInstance) { + } }); -Template.registerHelper('testHelper', function() { - return 'tester'; +Template.registerHelper('testHelper', function () { + return 'tester'; }); var instance = Template.instance(); @@ -488,23 +505,25 @@ var body = Template.body; */ var Chats = new Mongo.Collection('chats'); -Meteor.publish("chats-in-room", function (roomId:string) { - // Make sure roomId is a string, not an arbitrary mongo selector object. - check(roomId, String); - return Chats.find({room: roomId}); +Meteor.publish("chats-in-room", function (roomId: string) { + // Make sure roomId is a string, not an arbitrary mongo selector object. + check(roomId, String); + return Chats.find({ room: roomId }); }); -Meteor.methods({addChat: function (roomId:string, message:{text:string, timestamp:Date, tags:string}) { - check(roomId, String); - check(message, { - text: String, - timestamp: Date, - // Optional, but if present must be an array of strings. - tags: Match.Optional('Test String') - }); +Meteor.methods({ + addChat: function (roomId: string, message: { text: string, timestamp: Date, tags: string }) { + check(roomId, String); + check(message, { + text: String, + timestamp: Date, + // Optional, but if present must be an array of strings. + tags: Match.Optional('Test String') + }); - // ... do something with the message ... -}}); + // ... do something with the message ... + } +}); /** * From Match patterns section @@ -521,27 +540,27 @@ check(undefined, Match.Optional('test')); // OK * From Deps, Tracker.autorun section */ Tracker.autorun(function () { - var oldest = Monkeys.findOne('age = 20'); + var oldest = Monkeys.findOne('age = 20'); - if (oldest) - Session.set("oldest", oldest.name); + if (oldest) + Session.set("oldest", oldest.name); }); Tracker.autorun(function (c) { - if (! Session.equals("shouldAlert", true)) - return; + if (!Session.equals("shouldAlert", true)) + return; - c.stop(); - alert("Oh no!"); + c.stop(); + alert("Oh no!"); }); /** * From Deps, Deps.Computation */ if (Tracker.active) { - Tracker.onInvalidate(function () { - console.log('invalidated'); - }); + Tracker.onInvalidate(function () { + console.log('invalidated'); + }); } /** @@ -551,50 +570,52 @@ var weather = "sunny"; var weatherDep = new Tracker.Dependency; var getWeather = function () { - weatherDep.depend(); - return weather; + weatherDep.depend(); + return weather; }; -var setWeather = function (w:string) { - weather = w; - // (could add logic here to only call changed() - // if the new value is different from the old) - weatherDep.changed(); +var setWeather = function (w: string) { + weather = w; + // (could add logic here to only call changed() + // if the new value is different from the old) + weatherDep.changed(); }; /** * From HTTP, HTTP.call section */ -Meteor.methods({checkTwitter: function (userId:string) { - check(userId, String); - this.unblock(); - var result = HTTP.call("GET", "http://api.twitter.com/xyz", - {params: {user: userId}}); - if (result.statusCode === 200) - return true - return false; -}}); +Meteor.methods({ + checkTwitter: function (userId: string) { + check(userId, String); + this.unblock(); + var result = HTTP.call("GET", "http://api.twitter.com/xyz", + { params: { user: userId } }); + if (result.statusCode === 200) + return true + return false; + } +}); HTTP.call("POST", "http://api.twitter.com/xyz", - {data: {some: "json", stuff: 1}}, - function (error: Meteor.Error, result:any) { - if (result.statusCode === 200) { - Session.set("twizzled", true); - } + { data: { some: "json", stuff: 1 } }, + function (error: Meteor.Error, result: any) { + if (result.statusCode === 200) { + Session.set("twizzled", true); + } }); /** * From Email, Email.send section */ Meteor.methods({ - sendEmail: function (to:string, from:string, subject:string, text:string) { - check([to, from, subject, text], [String]); + sendEmail: function (to: string, from: string, subject: string, text: string) { + check([to, from, subject, text], [String]); - // Let other method calls from the same client start running, - // without waiting for the email sending to complete. - this.unblock(); - } + // Let other method calls from the same client start running, + // without waiting for the email sending to complete. + this.unblock(); + } }); // In your client code: asynchronously send an email @@ -603,74 +624,112 @@ Meteor.call('sendEmail', 'Hello from Meteor!', 'This is a test of Email.send.'); -var testTemplate = new Blaze.Template(); -var testView = new Blaze.View(); +var testTemplate = new Blaze.Template('foo'); +var testView = new Blaze.View('foo'); +Blaze.Template.instance(); declare var el: HTMLElement; Blaze.render(testTemplate, el); -Blaze.renderWithData(testTemplate, {testData: 123}, el); +Blaze.renderWithData(testTemplate, { testData: 123 }, el); Blaze.remove(testView); Blaze.getData(el); Blaze.getData(testView); Blaze.toHTML(testTemplate); Blaze.toHTML(testView); -Blaze.toHTMLWithData(testTemplate, {test: 1}); -Blaze.toHTMLWithData(testTemplate, function() {}); -Blaze.toHTMLWithData(testView, {test: 1}); -Blaze.toHTMLWithData(testView, function() {}); +Blaze.toHTMLWithData(testTemplate, { test: 1 }); +Blaze.toHTMLWithData(testTemplate, function () { }); +Blaze.toHTMLWithData(testView, { test: 1 }); +Blaze.toHTMLWithData(testView, function () { }); var reactiveVar1 = new ReactiveVar('test value'); -var reactiveVar2 = new ReactiveVar('test value', function(oldVal:any) { return true; }); +var reactiveVar2 = new ReactiveVar('test value', function (oldVal: any) { return true; }); var varValue: string = reactiveVar1.get(); reactiveVar1.set('new value'); // Covers this PR: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/8233 var isConfigured: boolean = Accounts.loginServicesConfigured(); -Accounts.onPageLoadLogin(function() { - // do something +Accounts.onPageLoadLogin(function () { + // do something }); // Covers this PR: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/8065 -var loginOpts: Meteor.LoginWithExternalServiceOptions = { - requestPermissions: ["a", "b"], - requestOfflineToken: true, - loginUrlParameters: {asdf: 1, qwer: "1234"}, - loginHint: "Help me", - loginStyle: "Bold and powerful", - redirectUrl: "popup", - profile: "asdfasdf", - email: "asdf@ASDf.com" +var loginOpts = { + requestPermissions: ["a", "b"], + requestOfflineToken: true, + loginUrlParameters: { asdf: 1, qwer: "1234" }, + loginHint: "Help me", + loginStyle: "Bold and powerful", + redirectUrl: "popup", + profile: "asdfasdf" }; -Meteor.loginWithMeteorDeveloperAccount(loginOpts, function(error: Meteor.Error) {}); +Meteor.loginWithMeteorDeveloperAccount(loginOpts, function (error: Meteor.Error) { }); Accounts.emailTemplates.siteName = "AwesomeSite"; Accounts.emailTemplates.from = "AwesomeSite Admin "; Accounts.emailTemplates.headers = { asdf: 'asdf', qwer: 'qwer' }; Accounts.emailTemplates.enrollAccount.subject = function (user: Meteor.User) { - return "Welcome to Awesome Town, " + user.profile.name; + return "Welcome to Awesome Town, " + user.profile.name; }; Accounts.emailTemplates.enrollAccount.html = function (user: Meteor.User, url: string) { - return "

              Some html here

              "; + return "

              Some html here

              "; }; -Accounts.emailTemplates.enrollAccount.from = function() { - return "asdf@asdf.com"; +Accounts.emailTemplates.enrollAccount.from = function () { + return "asdf@asdf.com"; }; Accounts.emailTemplates.enrollAccount.text = function (user: Meteor.User, url: string) { - return "You have been selected to participate in building a better future!" + return "You have been selected to participate in building a better future!" + " To activate your account, simply click the link below:\n\n" + url; }; -var handle = Accounts.validateLoginAttempt(function(attemptInfoObject: Accounts.IValidateLoginAttemptCbOpts) { - var type: string = attemptInfoObject.type; - var allowed: boolean = attemptInfoObject.allowed; - var error: Meteor.Error = attemptInfoObject.error; - var user: Meteor.User = attemptInfoObject.user; - var connection: Meteor.Connection = attemptInfoObject.connection; - var methodName: string = attemptInfoObject.methodName; - var methodArguments: any[] = attemptInfoObject.methodArguments; - return true; +var handle = Accounts.validateLoginAttempt(function (attemptInfoObject: Accounts.IValidateLoginAttemptCbOpts) { + var type: string = attemptInfoObject.type; + var allowed: boolean = attemptInfoObject.allowed; + var error: Meteor.Error = attemptInfoObject.error; + var user: Meteor.User = attemptInfoObject.user; + var connection: Meteor.Connection = attemptInfoObject.connection; + var methodName: string = attemptInfoObject.methodName; + var methodArguments: any[] = attemptInfoObject.methodArguments; + return true; }); handle.stop(); + + +// Covers https://github.com/meteor-typings/meteor/issues/8 +const publicSetting = Meteor.settings.public['somePublicSetting']; +const deeperPublicSetting = Meteor.settings.public['somePublicSetting']['deeperSetting']; +const privateSetting = Meteor.settings['somePrivateSetting']; +const deeperPrivateSetting = Meteor.settings['somePrivateSettings']['deeperSetting']; + + +// Covers https://github.com/meteor-typings/meteor/issues/9 +const username = (Template.instance().find('#username')).value; + + +// Covers https://github.com/meteor-typings/meteor/issues/3 +BrowserPolicy.framing.disallow(); +BrowserPolicy.content.allowEval(); + + +// Covers https://github.com/meteor-typings/meteor/issues/18 +if (Meteor.isDevelopment) { + Rooms._dropIndex({ field: 1 }); +} + + +// Covers https://github.com/meteor-typings/meteor/issues/20 +Rooms.find().count(true); + + +// Covers https://github.com/meteor-typings/meteor/issues/21 +if (Meteor.isTest) { + // do something +} + +DDPRateLimiter.addRule({ userId: 'foo' }, 5, 1000); + +DDPRateLimiter.addRule((userId: string) => userId == 'foo', 5, 1000); + +Template.instance().autorun(() => { }).stop(); diff --git a/metismenu/metismenu-tests.ts b/metismenu/metismenu-tests.ts index eb17270021..64aa809cf7 100644 --- a/metismenu/metismenu-tests.ts +++ b/metismenu/metismenu-tests.ts @@ -1,5 +1,3 @@ -/// - $('#menu').metisMenu(); $('.metismenu').metisMenu({toggle: false}); diff --git a/mobservable/index.d.ts b/mobservable/index.d.ts deleted file mode 100644 index 719eddaf31..0000000000 --- a/mobservable/index.d.ts +++ /dev/null @@ -1,178 +0,0 @@ -// Type definitions for mobservable 0.6 -// Project: https://mweststrate.github.io/mobservable -// Definitions by: Michel Weststrate -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace Mobservable { - interface Static extends MakeReactive { - /** - * Turns an object, array or function into a reactive structure. - * @param value the value which should become observable. - */ - makeReactive: MakeReactive; - - /** - * Extends an object with reactive capabilities. - * @param target the object to which reactive properties should be added - * @param properties the properties that should be added and made reactive - * @returns targer - */ - extendReactive(target: Object, properties: Object): Object; - - /** - * Returns true if the provided value is reactive. - * @param value object, function or array - * @param propertyName if propertyName is specified, checkes whether value.propertyName is reactive. - */ - isReactive(value: any, propertyName?: string): boolean; - - /** - * Can be used in combination with makeReactive / extendReactive. - * Enforces that a reference to 'value' is stored as property, - * but that 'value' itself is not turned into something reactive. - * Future assignments to the same property will inherit this behavior. - * @param value initial value of the reactive property that is being defined. - */ - asReference(value: any): {value: T}; - - /** - * ES6 / Typescript decorator which can to make class properties and getter functions reactive. - */ - observable(target: Object, key: string): any; // decorator / annotation - - /** - * Creates a reactive view and keeps it alive, so that the view is always - * updated if one of the dependencies changes, even when the view is not further used by something else. - * @param func The reactive view - * @param scope (optional) - * @returns disposer function, which can be used to stop the view from being updated in the future. - */ - observe(func: Mobservable.Lambda, scope?: any): Mobservable.Lambda; - - /** - * Deprecated, use mobservable.observe instead. - */ - sideEffect(func: Mobservable.Lambda, scope?: any): Mobservable.Lambda; - - /** - * Similar to 'observer', observes the given predicate until it returns true. - * Once it returns true, the 'effect' function is invoked an the observation is cancelled. - * @param predicate - * @param effect - * @param scope (optional) - * @returns disposer function to prematurely end the observer. - */ - observeUntil(predicate: () => boolean, effect: Mobservable.Lambda, scope?: any): Mobservable.Lambda; - - /** - * During a transaction no views are updated until the end of the transaction. - * The transaction will be run synchronously nonetheless. - * @param action a function that updates some reactive state - * @returns any value that was returned by the 'action' parameter. - */ - transaction(action: () => T): T; - - /** - * Converts a reactive structure into a non-reactive structure. - * Basically a deep-clone. - */ - toJSON(value: T): T; - - /** - * Sets the reporting level Defaults to 1. Use 0 for production or 2 for increased verbosity. - */ - logLevel: number; // 0 = production, 1 = development, 2 = debugging - - extras: { - getDependencyTree(thing: any, property?: string): Mobservable.DependencyTree; - - getObserverTree(thing: any, property?: string): Mobservable.ObserverTree; - - trackTransitions(extensive?: boolean, onReport?: (lines: Mobservable.TransitionEvent) => void): Mobservable.Lambda; - }; - } - - interface MakeReactive { - (value: T[], opts?: Mobservable.MakeReactiveOptions): Mobservable.ObservableArray; - (value: () => T, opts?: Mobservable.MakeReactiveOptions): Mobservable.ObservableValue; - (value: T, opts?: Mobservable.MakeReactiveOptions): Mobservable.ObservableValue; - (value: Object, opts?: Mobservable.MakeReactiveOptions): T; - } - - interface MakeReactiveOptions { - as?: string; /* "auto" | "reference" | TODO: see #8 "structure" */ - scope?: Object; - context?: Object; - recurse?: boolean; - name?: string; - // protected: boolean TODO: see #9 - } - - type ContextInfo = { object: Object; name: string } | string; - - interface Lambda { - (): void; - name?: string; - } - - interface Observable { - observe(callback: (...args: any[]) => void, fireImmediately?: boolean): Lambda; - } - - interface ObservableValue extends Observable { - (): T; - (value: T): void; - observe(callback: (newValue: T, oldValue: T) => void, fireImmediately?: boolean): Lambda; - } - - interface ObservableArray extends Observable, Array { - spliceWithArray(index: number, deleteCount?: number, newItems?: T[]): T[]; - observe(listener: (changeData: ArrayChange|ArraySplice) => void, fireImmediately?: boolean): Lambda; - clear(): T[]; - replace(newItems: T[]): T[]; - find(predicate: (item: T, index: number, array: ObservableArray) => boolean, thisArg?: any, fromIndex?: number): T; - remove(value: T): boolean; - } - - interface ArrayChange { - type: string; // Always: 'update' - object: ObservableArray; - index: number; - oldValue: T; - } - - interface ArraySplice { - type: string; // Always: 'splice' - object: ObservableArray; - index: number; - removed: T[]; - addedCount: number; - } - - interface DependencyTree { - id: number; - name: string; - context: any; - dependencies?: DependencyTree[]; - } - - interface ObserverTree { - id: number; - name: string; - context: any; - observers?: ObserverTree[]; - listeners?: number; // amount of functions manually attached using an .observe method - } - - interface TransitionEvent { - id: number; - name: string; - context: Object; - state: string; - changed: boolean; - newValue: string; - } -} - -declare const Mobservable: Mobservable.Static; -export = Mobservable; diff --git a/mobservable/mobservable-tests.ts b/mobservable/mobservable-tests.ts deleted file mode 100644 index 060f0d14b3..0000000000 --- a/mobservable/mobservable-tests.ts +++ /dev/null @@ -1,56 +0,0 @@ -import mobservable = require('mobservable'); -import {observable} from "mobservable"; - -var v = mobservable(3); -v.observe(() => {}); - -var a = mobservable([1, 2, 3]); - -class Order { - @observable price: number = 3; - @observable amount: number = 2; - @observable orders: string[] = []; - - @observable get total() { - return this.amount * this.price * (1 + this.orders.length); - } -} - -export function testObservable() { - var a = mobservable(3); - var b = mobservable(() => a() * 2); -} - -export function testAnnotations() { - var order1totals: number[] = []; - var order1 = new Order(); - var order2 = new Order(); - - var disposer = mobservable.observe(() => { - order1totals.push(order1.total); - }); - - order2.price = 4; - order1.amount = 1; - - order2.orders.push('bla'); - - order1.orders.splice(0, 0, 'boe', 'hoi'); - - disposer(); - order1.orders.pop(); -}; - -export function testTyping() { - var ar: mobservable.ObservableArray = mobservable.makeReactive([1, 2]); - ar.observe((d: mobservable.ArrayChange | mobservable.ArraySplice) => { - console.log(d.type); - }); - - var ar2: mobservable.ObservableArray = mobservable([1, 2]); - ar2.observe((d: mobservable.ArrayChange | mobservable.ArraySplice) => { - console.log(d.type); - }); - - var x: mobservable.ObservableValue = mobservable(3); -} \ No newline at end of file diff --git a/mobservable/tsconfig.json b/mobservable/tsconfig.json deleted file mode 100644 index cee6db4b01..0000000000 --- a/mobservable/tsconfig.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "baseUrl": "../", - "experimentalDecorators": true, - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "mobservable-tests.ts" - ] -} \ No newline at end of file diff --git a/mocha/index.d.ts b/mocha/index.d.ts index 40210dc69d..b87a6e7d9b 100644 --- a/mocha/index.d.ts +++ b/mocha/index.d.ts @@ -112,23 +112,23 @@ declare class Mocha { // merge the Mocha class declaration with a module declare namespace Mocha { interface ISuiteCallbackContext { - timeout(ms: number): void; - retries(n: number): void; - slow(ms: number): void; + timeout(ms: number): this; + retries(n: number): this; + slow(ms: number): this; } interface IHookCallbackContext { - skip(): void; - timeout(ms: number): void; + skip(): this; + timeout(ms: number): this; [index: string]: any; } interface ITestCallbackContext { - skip(): void; - timeout(ms: number): void; - retries(n: number): void; - slow(ms: number): void; + skip(): this; + timeout(ms: number): this; + retries(n: number): this; + slow(ms: number): this; [index: string]: any; } diff --git a/mocha/mocha-tests.ts b/mocha/mocha-tests.ts index 8e8dc0d938..7271ebbd0c 100644 --- a/mocha/mocha-tests.ts +++ b/mocha/mocha-tests.ts @@ -9,9 +9,7 @@ function test_describe() { describe.skip('something', () => { }); describe('something', function () { - this.retries(3); - this.slow(1000); - this.timeout(2000); + this.retries(3).slow(1000).timeout(2000).retries(3); }); } @@ -23,9 +21,7 @@ function test_context() { context.skip('some context', () => { }); context('some context', function () { - this.retries(3); - this.slow(1000); - this.timeout(2000); + this.retries(3).slow(1000).timeout(2000).retries(3); }); } @@ -37,9 +33,7 @@ function test_suite() { suite.skip('some context', () => { }); suite('some context', function () { - this.retries(3); - this.slow(1000); - this.timeout(2000); + this.retries(3).slow(1000).timeout(2000).retries(3); }); } @@ -56,9 +50,7 @@ function test_it() { it.skip('does something', () => { }); it('does something', function () { - this.skip(); - this.retries(3); - this.timeout(2000); + this.skip().retries(3).slow(1000).timeout(2000).skip(); }); } @@ -75,9 +67,7 @@ function test_test() { test.skip('does something', () => { }); test('does something', function () { - this.skip(); - this.retries(3); - this.timeout(2000); + this.skip().retries(3).slow(1000).timeout(2000).skip(); }); } @@ -94,9 +84,7 @@ function test_specify() { specify.skip('does something', () => { }); specify('does something', function () { - this.skip(); - this.retries(3); - this.timeout(2000); + this.skip().retries(3).slow(1000).timeout(2000).skip(); }); } @@ -112,8 +100,7 @@ function test_before() { before("my description", done => { }); before("my description", function () { - this.skip(); - this.timeout(2000); + this.skip().timeout(2000).skip(); }); } diff --git a/mongoose/index.d.ts b/mongoose/index.d.ts index 7ef5615436..25b0e177ea 100644 --- a/mongoose/index.d.ts +++ b/mongoose/index.d.ts @@ -385,6 +385,9 @@ declare module "mongoose" { * If connecting to multiple mongos servers, set the mongos option to true. */ mongos?: boolean; + + /** sets the underlying driver's promise library (see http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html) */ + promiseLibrary?: any; } interface ConnectionOptions extends @@ -720,6 +723,8 @@ declare module "mongoose" { validateBeforeSave?: boolean; /** defaults to "__v" */ versionKey?: string|boolean; + /** defaults to false */ + retainKeyOrder?: boolean; /** * skipVersioning allows excluding paths from * versioning (the internal revision will not be diff --git a/mssql/index.d.ts b/mssql/index.d.ts index 8aaca045e2..5f013e33a1 100644 --- a/mssql/index.d.ts +++ b/mssql/index.d.ts @@ -1,91 +1,96 @@ // Type definitions for mssql 3.3 // Project: https://www.npmjs.com/package/mssql -// Definitions by: COLSA Corporation , Ben Farr , Vitor Buzinaro , Matt Richardson +// Definitions by: COLSA Corporation , Ben Farr , Vitor Buzinaro , Matt Richardson , Jørgen Elgaard Larsen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// import events = require('events'); +export interface ISqlType { + type: ISqlTypeFactory; +} +export interface ISqlTypeWithNoParams extends ISqlType { type: ISqlTypeFactoryWithNoParams } +export interface ISqlTypeWithLength extends ISqlType { type: ISqlTypeFactoryWithLength; length: number } +export interface ISqlTypeWithScale extends ISqlType { type: ISqlTypeFactoryWithScale; scale: number } +export interface ISqlTypeWithPrecisionScale extends ISqlType { type: ISqlTypeFactoryWithPrecisionScale; precision: number, scale: number } +export interface ISqlTypeWithTvpType extends ISqlType { type: ISqlTypeFactoryWithTvpType; tvpType: any } -type sqlTypeWithNoParams = { type: sqlTypeFactoryWithNoParams } -type sqlTypeWithLength = { type: sqlTypeFactoryWithLength, length: number } -type sqlTypeWithScale = { type: sqlTypeFactoryWithScale, scale: number } -type sqlTypeWithPrecisionScale = { type: sqlTypeFactoryWithPrecisionScale, precision: number, scale: number } -type sqlTypeWithTvpType = { type: sqlTypeFactoryWithTvpType, tvpType: any } +export interface ISqlTypeFactory { +} +export interface ISqlTypeFactoryWithNoParams extends ISqlTypeFactory { (): ISqlTypeWithNoParams; } +export interface ISqlTypeFactoryWithLength extends ISqlTypeFactory { (length?: number): ISqlTypeWithLength } +export interface ISqlTypeFactoryWithScale extends ISqlTypeFactory { (scale?: number): ISqlTypeWithScale } +export interface ISqlTypeFactoryWithPrecisionScale extends ISqlTypeFactory { (precision?: number, scale?: number): ISqlTypeWithPrecisionScale; } +export interface ISqlTypeFactoryWithTvpType extends ISqlTypeFactory { (tvpType: any): ISqlTypeWithTvpType } -type sqlTypeFactoryWithNoParams = () => sqlTypeWithNoParams; -type sqlTypeFactoryWithLength = (length?: number) => sqlTypeWithLength; -type sqlTypeFactoryWithScale = (scale?: number) => sqlTypeWithScale; -type sqlTypeFactoryWithPrecisionScale = (precision?: number, scale?: number) => sqlTypeWithPrecisionScale; -type sqlTypeFactoryWithTvpType = (tvpType: any) => sqlTypeWithTvpType; -export declare var VarChar: sqlTypeFactoryWithLength; -export declare var NVarChar: sqlTypeFactoryWithLength; -export declare var Text: sqlTypeFactoryWithNoParams; -export declare var Int: sqlTypeFactoryWithNoParams; -export declare var BigInt: sqlTypeFactoryWithNoParams; -export declare var TinyInt: sqlTypeFactoryWithNoParams; -export declare var SmallInt: sqlTypeFactoryWithNoParams; -export declare var Bit: sqlTypeFactoryWithNoParams; -export declare var Float: sqlTypeFactoryWithNoParams; -export declare var Numeric: sqlTypeFactoryWithPrecisionScale; -export declare var Decimal: sqlTypeFactoryWithPrecisionScale; -export declare var Real: sqlTypeFactoryWithNoParams; -export declare var Date: sqlTypeFactoryWithNoParams; -export declare var DateTime: sqlTypeFactoryWithNoParams; -export declare var DateTime2: sqlTypeFactoryWithScale; -export declare var DateTimeOffset: sqlTypeFactoryWithScale; -export declare var SmallDateTime: sqlTypeFactoryWithNoParams; -export declare var Time: sqlTypeFactoryWithScale; -export declare var UniqueIdentifier: sqlTypeFactoryWithNoParams; -export declare var SmallMoney: sqlTypeFactoryWithNoParams; -export declare var Money: sqlTypeFactoryWithNoParams; -export declare var Binary: sqlTypeFactoryWithNoParams; -export declare var VarBinary: sqlTypeFactoryWithLength; -export declare var Image: sqlTypeFactoryWithNoParams; -export declare var Xml: sqlTypeFactoryWithNoParams; -export declare var Char: sqlTypeFactoryWithLength; -export declare var NChar: sqlTypeFactoryWithLength; -export declare var NText: sqlTypeFactoryWithNoParams; -export declare var TVP: sqlTypeFactoryWithTvpType; -export declare var UDT: sqlTypeFactoryWithNoParams; -export declare var Geography: sqlTypeFactoryWithNoParams; -export declare var Geometry: sqlTypeFactoryWithNoParams; +export declare var VarChar: ISqlTypeFactoryWithLength; +export declare var NVarChar: ISqlTypeFactoryWithLength; +export declare var Text: ISqlTypeFactoryWithNoParams; +export declare var Int: ISqlTypeFactoryWithNoParams; +export declare var BigInt: ISqlTypeFactoryWithNoParams; +export declare var TinyInt: ISqlTypeFactoryWithNoParams; +export declare var SmallInt: ISqlTypeFactoryWithNoParams; +export declare var Bit: ISqlTypeFactoryWithNoParams; +export declare var Float: ISqlTypeFactoryWithNoParams; +export declare var Numeric: ISqlTypeFactoryWithPrecisionScale; +export declare var Decimal: ISqlTypeFactoryWithPrecisionScale; +export declare var Real: ISqlTypeFactoryWithNoParams; +export declare var Date: ISqlTypeFactoryWithNoParams; +export declare var DateTime: ISqlTypeFactoryWithNoParams; +export declare var DateTime2: ISqlTypeFactoryWithScale; +export declare var DateTimeOffset: ISqlTypeFactoryWithScale; +export declare var SmallDateTime: ISqlTypeFactoryWithNoParams; +export declare var Time: ISqlTypeFactoryWithScale; +export declare var UniqueIdentifier: ISqlTypeFactoryWithNoParams; +export declare var SmallMoney: ISqlTypeFactoryWithNoParams; +export declare var Money: ISqlTypeFactoryWithNoParams; +export declare var Binary: ISqlTypeFactoryWithNoParams; +export declare var VarBinary: ISqlTypeFactoryWithLength; +export declare var Image: ISqlTypeFactoryWithNoParams; +export declare var Xml: ISqlTypeFactoryWithNoParams; +export declare var Char: ISqlTypeFactoryWithLength; +export declare var NChar: ISqlTypeFactoryWithLength; +export declare var NText: ISqlTypeFactoryWithNoParams; +export declare var TVP: ISqlTypeFactoryWithTvpType; +export declare var UDT: ISqlTypeFactoryWithNoParams; +export declare var Geography: ISqlTypeFactoryWithNoParams; +export declare var Geometry: ISqlTypeFactoryWithNoParams; export declare var TYPES: { - VarChar: sqlTypeFactoryWithLength; - NVarChar: sqlTypeFactoryWithLength; - Text: sqlTypeFactoryWithNoParams; - Int: sqlTypeFactoryWithNoParams; - BigInt: sqlTypeFactoryWithNoParams; - TinyInt: sqlTypeFactoryWithNoParams; - SmallInt: sqlTypeFactoryWithNoParams; - Bit: sqlTypeFactoryWithNoParams; - Float: sqlTypeFactoryWithNoParams; - Numeric: sqlTypeFactoryWithPrecisionScale; - Decimal: sqlTypeFactoryWithPrecisionScale; - Real: sqlTypeFactoryWithNoParams; - Date: sqlTypeFactoryWithNoParams; - DateTime: sqlTypeFactoryWithNoParams; - DateTime2: sqlTypeFactoryWithScale; - DateTimeOffset: sqlTypeFactoryWithScale; - SmallDateTime: sqlTypeFactoryWithNoParams; - Time: sqlTypeFactoryWithScale; - UniqueIdentifier: sqlTypeFactoryWithNoParams; - SmallMoney: sqlTypeFactoryWithNoParams; - Money: sqlTypeFactoryWithNoParams; - Binary: sqlTypeFactoryWithNoParams; - VarBinary: sqlTypeFactoryWithLength; - Image: sqlTypeFactoryWithNoParams; - Xml: sqlTypeFactoryWithNoParams; - Char: sqlTypeFactoryWithLength; - NChar: sqlTypeFactoryWithLength; - NText: sqlTypeFactoryWithNoParams; - TVP: sqlTypeFactoryWithTvpType; - UDT: sqlTypeFactoryWithNoParams; - Geography: sqlTypeFactoryWithNoParams; - Geometry: sqlTypeFactoryWithNoParams; + VarChar: ISqlTypeFactoryWithLength; + NVarChar: ISqlTypeFactoryWithLength; + Text: ISqlTypeFactoryWithNoParams; + Int: ISqlTypeFactoryWithNoParams; + BigInt: ISqlTypeFactoryWithNoParams; + TinyInt: ISqlTypeFactoryWithNoParams; + SmallInt: ISqlTypeFactoryWithNoParams; + Bit: ISqlTypeFactoryWithNoParams; + Float: ISqlTypeFactoryWithNoParams; + Numeric: ISqlTypeFactoryWithPrecisionScale; + Decimal: ISqlTypeFactoryWithPrecisionScale; + Real: ISqlTypeFactoryWithNoParams; + Date: ISqlTypeFactoryWithNoParams; + DateTime: ISqlTypeFactoryWithNoParams; + DateTime2: ISqlTypeFactoryWithScale; + DateTimeOffset: ISqlTypeFactoryWithScale; + SmallDateTime: ISqlTypeFactoryWithNoParams; + Time: ISqlTypeFactoryWithScale; + UniqueIdentifier: ISqlTypeFactoryWithNoParams; + SmallMoney: ISqlTypeFactoryWithNoParams; + Money: ISqlTypeFactoryWithNoParams; + Binary: ISqlTypeFactoryWithNoParams; + VarBinary: ISqlTypeFactoryWithLength; + Image: ISqlTypeFactoryWithNoParams; + Xml: ISqlTypeFactoryWithNoParams; + Char: ISqlTypeFactoryWithLength; + NChar: ISqlTypeFactoryWithLength; + NText: ISqlTypeFactoryWithNoParams; + TVP: ISqlTypeFactoryWithTvpType; + UDT: ISqlTypeFactoryWithNoParams; + Geography: ISqlTypeFactoryWithNoParams; + Geometry: ISqlTypeFactoryWithNoParams; }; export declare var MAX: number; @@ -100,8 +105,19 @@ interface IMap extends Array<{ js: any, sql: any }> { export declare var map: IMap; export declare var DRIVERS: string[]; +export interface IColumnMetadata { + [name: string]: { + index: number; + name: string; + length: number; + type: ISqlType; + udt?: any; + } +} +export interface IRecordSet extends Array { + columns: IColumnMetadata; +} -type recordSet = any; type IIsolationLevel = number; export declare var ISOLATION_LEVEL: { @@ -204,22 +220,23 @@ export declare class Request extends events.EventEmitter { public constructor(connection?: Connection); public constructor(transaction: Transaction); public constructor(preparedStatement: PreparedStatement); - public execute(procedure: string): Promise; - public execute(procedure: string, callback: (err?: any, recordsets?: Entity[], returnValue?: any, rowsAffected?: number) => void): void; - public input(name: string, value: any): void; - public input(name: string, type: any, value: any): void; - public output(name: string, type: any, value?: any): void; - public pipe(stream: NodeJS.WritableStream): void; - public query(command: string): Promise; - public query(command: string): Promise; - public query(command: string, callback: (err?: any, recordset?: any, rowsAffected?: number) => void): void; - public query(command: string, callback: (err?: any, recordset?: Entity[]) => void): void; - public batch(batch: string): Promise; - public batch(batch: string): Promise; - public batch(batch: string, callback: (err?: any, recordset?: any) => void): void; - public batch(batch: string, callback: (err?: any, recordset?: Entity[]) => void): void; - public bulk(table: Table): Promise; - public bulk(table: Table, callback: (err: any, rowCount: any) => void): void; + public execute(procedure: string): Promise>; + public execute(procedure: string): Promise>; + public execute(procedure: string, callback: (err?: any, recordsets?: IRecordSet, returnValue?: any, rowsAffected?: number) => void): void; + public input(name: string, value: any): Request; + public input(name: string, type: any, value: any): Request; + public output(name: string, type: any, value?: any): Request; + public pipe(stream: NodeJS.WritableStream): NodeJS.WritableStream; + public query(command: string): Promise>; + public query(command: string): Promise>; + public query(command: string, callback: (err?: Error, recordset?: IRecordSet, rowsAffected?: number) => void): void; + public query(command: string, callback: (err?: Error, recordset?: IRecordSet) => void): void; + public batch(batch: string): Promise>; + public batch(batch: string): Promise>; + public batch(batch: string, callback: (err?: Error, recordset?: IRecordSet) => void): void; + public batch(batch: string, callback: (err?: any, recordset?: IRecordSet) => void): void; + public bulk(table: Table): Promise; + public bulk(table: Table, callback: (err: Error, rowCount: any) => void): void; public cancel(): void; } @@ -258,16 +275,14 @@ export declare class PreparedStatement extends events.EventEmitter { public multiple: boolean; public stream: any; public constructor(connection?: Connection); - public input(name: string, type: any): void; - public output(name: string, type: any): void; + public input(name: string, type: ISqlType): PreparedStatement; + public output(name: string, type: ISqlType): PreparedStatement; public prepare(statement?: string): Promise; - public prepare(statement?: string, callback?: (err?: any) => void): void; - public execute(values: Object): Promise; - public execute(values: Object): Promise; - public execute(values: Object, callback: (err: any, recordSet: recordSet, rowsAffected: number) => void): void; - public execute(values: Object, callback: (err: any, recordSet: Entity[]) => void): void; + public prepare(statement?: string, callback?: (err?: Error) => void): PreparedStatement; + public execute(values: Object): Promise; + public execute(values: Object, callback: (err?: Error) => void): Request; public unprepare(): Promise; - public unprepare(callback: (err?: any) => void): void; + public unprepare(callback: (err?: Error) => void): PreparedStatement; } export declare class PreparedStatementError implements Error { diff --git a/mssql/mssql-tests.ts b/mssql/mssql-tests.ts index 52ae6f953c..764f6da8e1 100644 --- a/mssql/mssql-tests.ts +++ b/mssql/mssql-tests.ts @@ -1,5 +1,3 @@ -/// - import sql = require('mssql'); interface Entity{ diff --git a/mu2/mu2-tests.ts b/mu2/mu2-tests.ts index dc960f20d7..d85e1463b9 100644 --- a/mu2/mu2-tests.ts +++ b/mu2/mu2-tests.ts @@ -1,6 +1,3 @@ - -/// - import mu2 = require('mu2'); import stream = require('stream'); diff --git a/multiparty/multiparty-tests.ts b/multiparty/multiparty-tests.ts index be49092189..839ca92882 100644 --- a/multiparty/multiparty-tests.ts +++ b/multiparty/multiparty-tests.ts @@ -1,5 +1,3 @@ - -/// import multiparty = require('multiparty'); import http = require('http'); import util = require('util'); diff --git a/mz/mz-tests.ts b/mz/mz-tests.ts index 8246eecbab..7eda9f28bf 100644 --- a/mz/mz-tests.ts +++ b/mz/mz-tests.ts @@ -1,7 +1,4 @@ /// -/// - - import assert = require('assert') import fs = require('mz/fs') diff --git a/n3/n3-tests.ts b/n3/n3-tests.ts index a7e529bc7d..13247dfdb2 100644 --- a/n3/n3-tests.ts +++ b/n3/n3-tests.ts @@ -1,5 +1,3 @@ -/// - import * as N3 from "n3"; import * as fs from "fs"; import * as stream from "stream"; @@ -26,7 +24,7 @@ function test_serialize() { }); } -/** +/** The following tests are taken from ... https://github.com/RubenVerborgh/N3.js/blob/master/README.md */ diff --git a/nanoscroller/index.d.ts b/nanoscroller/index.d.ts new file mode 100644 index 0000000000..ede65fc283 --- /dev/null +++ b/nanoscroller/index.d.ts @@ -0,0 +1,126 @@ +// Type definitions for nanoScroller 0.8 +// Project: http://jamesflorentino.github.io/nanoScrollerJS/ +// Definitions by: Yannick Beauchamp-Hurtubise +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace JQueryNanoScroller { + interface NanoScrollerOptions { + /** + * To scroll at the top or bottom. + */ + scroll?: 'top' | 'bottom'; + /** + * To scroll at the top with an offset value. + */ + scrollTop?: number; + /** + * To scroll at the bottom with an offset value. + */ + scrollBottom?: number; + /** + * To scroll to an element. + */ + scrollTo?: JQuery; + /** + * To stop the operation. + * This option will tell the plugin to disable all event bindings and hide the gadget scrollbar from the UI. + */ + stop?: boolean; + /** + * Destroys nanoScroller and restores browser's native scrollbar. + */ + destroy?: boolean; + /** + * To flash the scrollbar gadget for an amount of time defined in plugin settings (defaults to 1,5s). + * Useful if you want to show the user that there is more content waiting for him. + */ + flash?: boolean; + /** + * Set to true if you want to use native scrolling in iOS 5+. + * This will disable your custom nanoScroller scrollbar in iOS 5+ and use the native one instead. + * While the native iOS scrollbar usually works much better, there could possibly be bugs in certain situations. + * @default false + */ + iOSNativeScrolling?: boolean; + /** + * Sets the minimum height of the slider element. + * @default 20 + */ + sliderMinHeight?: number; + /** + * Sets the maximum height of the slider element. + * @default null + */ + sliderMaxHeight?: number | null; + /** + * Set to true to prevent page scrolling when top or bottom inside the content div is reached. + * @default false + */ + preventPageScrolling?: boolean; + /** + * Set to true to disable the resize from nanoscroller. + * Useful if you want total control of the resize event. + * If you set this option to true remember to call the reset method so that the scroll don't have strange behavior. + * @default false + */ + disableResize?: boolean; + /** + * Set to true to stop the scrollbar from auto-hiding itself. + * @default false + */ + alwaysVisible?: boolean; + /** + * Use this setting to specify the scrollbar hide delay in milliseconds if you have enabled the flash option. + * @default 1500 + */ + flashDelay?: number; + /** + * A classname for scrollbar track element. + * If you change this setting, you also have to change it in the plugin's CSS file. + * @default 'nano-pane' + */ + paneClass?: string; + /** + * A classname for scrollbar thumb element. + * If you change this setting, you also have to change it in the plugin's CSS file. + * @default 'nano-slider' + */ + sliderClass?: string; + /** + * A classname for your content div. + * If you change this setting, you also have to change it in the plugin's CSS file. + * @default 'nano-content' + */ + contentClass?: string; + /** + * A classname for scrollbar enabled mode. + * If you change this setting, you also have to change it in the plugin's CSS file. + * @default 'has-scrollbar' + */ + enabledClass?: string; + /** + * A classname for scrollbar flashed mode. + * If you change this setting, you also have to change it in the plugin's CSS file. + * @default 'flashed' + */ + flashedClass?: string; + /** + * + * If you change this setting, you also have to change it in the plugin's CSS file. + * @default 'active' + */ + activeClass?: string; + /** + * Set the tab order of the scrollable content. + * Set to -1 to skip over the scrollable content when tabbing. + * @default 0 + */ + tabIndex?: number; + } +} + +interface JQuery { + nanoScroller(options?: JQueryNanoScroller.NanoScrollerOptions): JQuery; +} diff --git a/nanoscroller/nanoscroller-tests.ts b/nanoscroller/nanoscroller-tests.ts new file mode 100644 index 0000000000..3b9eeea820 --- /dev/null +++ b/nanoscroller/nanoscroller-tests.ts @@ -0,0 +1,8 @@ +/// + +$('.nano').nanoScroller(); + +$('.nano').nanoScroller({ + scroll: 'bottom', + flash: true +}); diff --git a/whatwg-fetch/tsconfig.json b/nanoscroller/tsconfig.json similarity index 93% rename from whatwg-fetch/tsconfig.json rename to nanoscroller/tsconfig.json index 1855761487..9727a9e274 100644 --- a/whatwg-fetch/tsconfig.json +++ b/nanoscroller/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "whatwg-fetch-tests.ts" + "nanoscroller-tests.ts" ] } \ No newline at end of file diff --git a/nanoscroller/tslint.json b/nanoscroller/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/nanoscroller/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/navigation/index.d.ts b/navigation/index.d.ts index 953255f8eb..eb045d8bfe 100644 --- a/navigation/index.d.ts +++ b/navigation/index.d.ts @@ -1,603 +1,553 @@ -// Type definitions for Navigation 2.0.0 +// Type definitions for Navigation 4.0 // Project: http://grahammendick.github.io/navigation/ // Definitions by: Graham Mendick // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export = Navigation; -declare namespace Navigation { +/** + * Defines a contract a class must implement in order to configure a State + */ +interface StateInfo { /** - * Defines a contract a class must implement in order to configure a State + * Gets the unique key */ - interface StateInfo { - /** - * Gets the unique key - */ - key: string; - /** - * Gets the default NavigationData for this State - */ - defaults?: any; - /** - * Gets the default NavigationData Types for this State - */ - defaultTypes?: any; - /** - * Gets the textual description of the state - */ - title?: string; - /** - * Gets the route Url patterns - */ - route?: string | string[]; - /** - * Gets a value that indicates whether to maintain the crumb trail - */ - trackCrumbTrail?: boolean | string; - /** - * Gets a value that indicates whether NavigationData Types are - * preserved when navigating - */ - trackTypes?: boolean; - /** - * Gets the additional state attributes - */ - [extras: string]: any; - } - + key: string; /** - * Represents a view and is the destination of a navigation + * Gets the default NavigationData for this State */ - class State implements StateInfo { - /** - * Gets the unique key - */ - key: string; - /** - * Gets the default NavigationData for this State - */ - defaults: any; - /** - * Gets the default NavigationData Types for this State - */ - defaultTypes: any; - /** - * Gets the formatted default NavigationData for this State - */ - formattedDefaults: any; - /** - * Gets the formatted default array NavigationData for this State - */ - formattedArrayDefaults: { [index: string]: string[]; }; - /** - * Gets the textual description of the state - */ - title: string; - /** - * Gets the route Url patterns - */ - route: string | string[]; - /** - * Gets a value that indicates whether to maintain the crumb trail - */ - trackCrumbTrail: boolean; - /** - * Gets the crumb trail key - */ - crumbTrailKey: string; - /** - * Gets a value that indicates whether NavigationData Types are - * preserved when navigating - */ - trackTypes: boolean; - /** - * Gets the additional state attributes - */ - [extras: string]: any; - /** - * Called on the old State before navigating to a different State - * @param state The new State - * @param data The new NavigationData - * @param url The new target location - * @param unload The function to call to continue to navigate - * @param history A value indicating whether browser history was used - */ - unloading: (state: State, data: any, url: string, unload: () => void, history?: boolean) => void; - /** - * Called on the old State after navigating to a different State - */ - dispose: () => void; - /** - * Called on the current State after navigating to it - * @param data The current NavigationData - * @param asyncData The data passed asynchronously while navigating - */ - navigated: (data: any, asyncData: any) => void; - /** - * Called on the new State before navigating to it - * @param data The new NavigationData - * @param url The new target location - * @param navigate The function to call to continue to navigate - * @param history A value indicating whether browser history was used - */ - navigating: (data: any, url: string, navigate: (asyncData?: any) => void, history: boolean) => void; - /** - * Encodes the Url value - * @param state The State navigated to - * @param key The key of the navigation data item - * @param val The Url value of the navigation data item - * @param queryString A value indicating the Url value's location - */ - urlEncode(state: State, key: string, val: string, queryString: boolean): string; - /** - * Decodes the Url value - * @param state The State navigated to - * @param key The key of the navigation data item - * @param val The Url value of the navigation data item - * @param queryString A value indicating the Url value's location - */ - urlDecode(state: State, key: string, val: string, queryString: boolean): string; - /** - * Validates the NavigationData before navigating to the new State - * @param data The new NavigationData - * @returns Validation success indicator - */ - validate(data: any): boolean; - /** - * Truncates the crumb trail whenever a repeated or initial State is - * encountered - * @param The State navigated to - * @param The Crumb collection representing the crumb trail - * @returns Truncated crumb trail - */ - truncateCrumbTrail(state: State, crumbs: Crumb[]): Crumb[]; - } - + defaults?: any; /** - * Defines a contract a class must implement in order to manage the browser - * Url + * Gets the default NavigationData Types for this State */ - interface HistoryManager { - /** - * Gets or sets a value indicating whether to disable browser history - */ - disabled: boolean; - /** - * Registers browser history event listeners - * @param navigateHistory The history navigation event handler - */ - init(navigateHistory: () => void): void; - /** - * Adds browser history - * @param url The current url - * @param replace A value indicating whether to replace the current - * browser history entry - */ - addHistory(url: string, replace: boolean): void; - /** - * Gets the current location - */ - getCurrentUrl(): string; - /** - * Gets an Href from the url - */ - getHref(url: string): string; - /** - * Gets a Url from the anchor or location - */ - getUrl(hrefElement: HTMLAnchorElement | Location): string; - /** - * Removes browser history event listeners - */ - stop(): void; - } - + defaultTypes?: any; /** - * Manages history using the browser Url's hash. If used in a browser - * without the hashchange event or outside of a browser environment, then - * history is disabled + * Gets the textual description of the state */ - class HashHistoryManager implements HistoryManager { - /** - * Gets or sets a value indicating whether to disable browser history. - * Set to true if used in a browser without the hashchange event or - * outside of a browser environment - */ - disabled: boolean; - /** - * Initializes a new instance of the HashHistoryManager class - */ - constructor(); - /** - * Initializes a new instance of the HashHistoryManager class - * @param replaceQueryIdentifier a value indicating whether to use '#' - * in place of '?'. Set to true for Internet explorer 6 and 7 support - */ - constructor(replaceQueryIdentifier: boolean); - /** - * Registers a listener for the hashchange event - * @param navigateHistory The history navigation event handler - */ - init(navigateHistory: any): void; - /** - * Sets the browser Url's hash to the url - * @param url The current url - * @param replace A value indicating whether to replace the current - * browser history entry - */ - addHistory(url: string, replace: boolean): void; - /** - * Gets the current location - */ - getCurrentUrl(): string; - /** - * Gets an Href from the url - */ - getHref(url: string): string; - /** - * Gets a Url from the anchor or location - */ - getUrl(hrefElement: HTMLAnchorElement | Location): string; - /** - * Removes a listener for the hashchange event - */ - stop(): void; - } - + title?: string; /** - * Manages history using the HTML5 history api. If used in a browser - * without the HTML5 history api or outside of a browser environment, then - * history is disabled + * Gets the route Url patterns */ - class HTML5HistoryManager implements HistoryManager { - /** - * Gets or sets a value indicating whether to disable browser history. - * Set to true if used in a browser without the HTML5 history api or - * outside of a browser environment - */ - disabled: boolean; - /** - * Initializes a new instance of the HTML5HistoryManager class - */ - constructor(); - /** - * Initializes a new instance of the HTML5HistoryManager class - * @param applicationPath The application path - */ - constructor(applicationPath: string); - /** - * Registers a listener for the popstate event - * @param navigateHistory The history navigation event handler - */ - init(navigateHistory: () => void): void; - /** - * Sets the browser Url to the url using pushState - * @param url The current url - * @param replace A value indicating whether to replace the current - * browser history entry - */ - addHistory(url: string, replace: boolean): void; - /** - * Gets the current location - */ - getCurrentUrl(): string; - /** - * Gets an Href from the url - */ - getHref(url: string): string; - /** - * Gets a Url from the anchor or location - */ - getUrl(hrefElement: HTMLAnchorElement | Location): string; - /** - * Removes a listener for the popstate event - */ - stop(): void; - } - + route?: string | string[]; /** - * Represents one piece of the crumb trail and holds the information need - * to return to and recreate the State as previously visited + * Gets a value that indicates whether to maintain the crumb trail */ - class Crumb { - /** - * Gets the Context Data held at the time of navigating away from this - * State - */ - data: any; - /** - * Gets the configuration information associated with this navigation - */ - state: State; - /** - * Gets a value indicating whether the Crumb is the last in the crumb - * trail - */ - last: boolean; - /** - * Gets the State Title - */ - title: string; - /** - * Gets the link navigation to return to the State and pass the - * associated Data - */ - url: string; - /** - * Gets the link navigation without crumb trail to return to the State - * and pass the associated Data - */ - crumblessUrl: string; - /** - * Initializes a new instance of the Crumb class - * @param data The Context Data held at the time of navigating away - * from this State - * @param state The configuration information associated with this - * navigation - * @param link The link navigation to return to the State and pass the - * associated Data - * @param crumblessLink The link navigation without crumb trail to - * return to the State and pass the associated Data - * @param last A value indicating whether the Crumb is the last in the - * crumb trail - */ - constructor(data: any, state: State, link: string, crumblessLink: string, last: boolean); - } - + trackCrumbTrail?: boolean | string; /** - * Provides properties for accessing context sensitive navigation - * information. Holds the current State and NavigationData + * Gets a value that indicates whether NavigationData Types are + * preserved when navigating */ - class StateContext { - /** - * Gets the last State displayed before the current State - */ - oldState: State; - /** - * Gets the NavigationData for the last displayed State - */ - oldData: any; - /** - * Gets the State of the last Crumb in the crumb trail - */ - previousState: State; - /** - * Gets the NavigationData of the last Crumb in the crumb trail - */ - previousData: any; - /** - * Gets the current State - */ - state: State; - /** - * Gets the NavigationData for the current State - */ - data: any; - /** - * Gets the current Url - */ - url: string; - /** - * Gets or sets the current title - */ - title: string; - /** - * Gets a Crumb collection representing the crumb trail, ordered oldest - * Crumb first - */ - crumbs: Crumb[]; - /** - * Gets the next crumb - */ - nextCrumb: Crumb; - /** - * Clears the Context Data - */ - clear(): void; - /** - * Combines the data with all the current NavigationData - * @param The data to add to the current NavigationData - * @returns The combined data - */ - includeCurrentData(data: any): any; - /** - * Combines the data with a subset of the current NavigationData - * @param The data to add to the current NavigationData - * @returns The combined data - */ - includeCurrentData(data: any, keys: string[]): any; - } - + trackTypes?: boolean; /** - * Manages all navigation. These can be forward, backward or refreshing the - * current State + * Gets the additional state attributes */ - class StateNavigator { - /** - * Provides access to context sensitive navigation information - */ - stateContext: StateContext; - /** - * Gets the browser Url manager - */ - historyManager: HistoryManager; - /** - * Gets a list of States - */ - states: { [index: string]: State; }; - /** - * Initializes a new instance of the StateNavigator class - */ - constructor(); - /** - * Initializes a new instance of the StateNavigator class - * @param states A collection of States - */ - constructor(states: StateInfo[]); - /** - * Initializes a new instance of the StateNavigator class - * @param states A collection of States - * @param historyManager The manager of the browser Url - */ - constructor(states: StateInfo[], historyManager: HistoryManager); - /** - * Configures the StateNavigator - * @param stateInfos A collection of State Infos - */ - configure(stateInfos: StateInfo[]): void; - /** - * Configures the StateNavigator - * @param stateInfos A collection of State Infos - * @param historyManager The manager of the browser Url - */ - configure(stateInfos: StateInfo[], historyManager: HistoryManager): void; - /** - * Registers a navigate event listener - * @param handler The navigate event listener - */ - onNavigate(handler: (oldState: State, state: State, data: any, asyncData: any) => void): void; - /** - * Unregisters a navigate event listener - * @param handler The navigate event listener - */ - offNavigate(handler: (oldState: State, state: State, data: any, asyncData: any) => void): void; - /** - * Navigates to a State - * @param stateKey The key of a State - * @throws state does not match the key of a State or there is - * NavigationData that cannot be converted to a String - * @throws A mandatory route parameter has not been supplied a value - */ - navigate(stateKey: string): void; - /** - * Navigates to a State - * @param stateKey The key of a State - * @param navigationData The NavigationData to be passed to the next - * State and stored in the StateContext - * @throws state does not match the key of a State or there is - * NavigationData that cannot be converted to a String - * @throws A mandatory route parameter has not been supplied a value - */ - navigate(stateKey: string, navigationData: any): void; - /** - * Navigates to a State - * @param stateKey The key of a State - * @param navigationData The NavigationData to be passed to the next - * State and stored in the StateContext - * @param A value determining the effect on browser history - * @throws state does not match the key of a State or there is - * NavigationData that cannot be converted to a String - * @throws A mandatory route parameter has not been supplied a value - */ - navigate(stateKey: string, navigationData: any, historyAction: 'add' | 'replace' | 'none'): void; - /** - * Gets a Url to navigate to a State - * @param stateKey The key of a State - * @returns Url that will navigate to State specified in the action - * @throws state does not match the key of a State or there is - * NavigationData that cannot be converted to a String - */ - getNavigationLink(stateKey: string): string; - /** - * Gets a Url to navigate to a State - * @param stateKey The key of a State - * @param navigationData The NavigationData to be passed to the next - * State and stored in the StateContext - * @returns Url that will navigate to State specified in the action - * @throws state does not match the key of a State or there is - * NavigationData that cannot be converted to a String - */ - getNavigationLink(stateKey: string, navigationData: any): string; - /** - * Determines if the distance specified is within the bounds of the - * crumb trail represented by the Crumbs collection - */ - canNavigateBack(distance: number): boolean; - /** - * Navigates back along the crumb trail - * @param distance Starting at 1, the number of Crumb steps to go back - * @throws canNavigateBack returns false for this distance - * @throws A mandatory route parameter has not been supplied a value - */ - navigateBack(distance: number): void; - /** - * Navigates back along the crumb trail - * @param distance Starting at 1, the number of Crumb steps to go back - * @param A value determining the effect on browser history - * @throws canNavigateBack returns false for this distance - * @throws A mandatory route parameter has not been supplied a value - */ - navigateBack(distance: number, historyAction: 'add' | 'replace' | 'none'): void; - /** - * Gets a Url to navigate back along the crumb trail - * @param distance Starting at 1, the number of Crumb steps to go back - * @throws canNavigateBack returns false for this distance - */ - getNavigationBackLink(distance: number): string; - /** - * Navigates to the current State passing no NavigationData - * @throws A mandatory route parameter has not been supplied a value - */ - refresh(): void; - /** - * Navigates to the current State - * @param navigationData The NavigationData to be passed to the current - * State and stored in the StateContext - * @throws There is NavigationData that cannot be converted to a String - * @throws A mandatory route parameter has not been supplied a value - */ - refresh(navigationData: any): void; - /** - * Navigates to the current State - * @param navigationData The NavigationData to be passed to the current - * State and stored in the StateContext - * @param A value determining the effect on browser history - * @throws There is NavigationData that cannot be converted to a String - * @throws A mandatory route parameter has not been supplied a value - */ - refresh(navigationData: any, historyAction: 'add' | 'replace' | 'none'): void; - /** - * Gets a Url to navigate to the current State - */ - getRefreshLink(): string; - /** - * Gets a Url to navigate to the current State - * @param navigationData The NavigationData to be passed to the current - * State and stored in the StateContext - * @returns Url that will navigate to the current State - * @throws There is NavigationData that cannot be converted to a String - */ - getRefreshLink(navigationData: any): string; - /** - * Navigates to the url - * @param url The target location - */ - navigateLink(url: string): void; - /** - * Navigates to the url - * @param url The target location - * @param A value determining the effect on browser history - */ - navigateLink(url: string, historyAction: 'add' | 'replace' | 'none'): void; - /** - * Navigates to the url - * @param url The target location - * @param A value determining the effect on browser history - * @param history A value indicating whether browser history was used - */ - navigateLink(url: string, historyAction: 'add' | 'replace' | 'none', history: boolean): void; - /** - * Parses the url out into State and Navigation Data - * @param url The url to parse - */ - parseLink(url: string): { state: State; data: any; }; - /** - * Navigates to the current location - */ - start(): void; - /** - * Navigates to the passed in url - * @param url The url to navigate to - */ - start(url: string): void; - } + [extras: string]: any; } + +/** + * Represents a view and is the destination of a navigation + */ +export class State implements StateInfo { + /** + * Gets the unique key + */ + key: string; + /** + * Gets the default NavigationData for this State + */ + defaults: any; + /** + * Gets the default NavigationData Types for this State + */ + defaultTypes: any; + /** + * Gets the formatted default NavigationData for this State + */ + formattedDefaults: any; + /** + * Gets the formatted default array NavigationData for this State + */ + formattedArrayDefaults: { [index: string]: string[]; }; + /** + * Gets the textual description of the state + */ + title: string; + /** + * Gets the route Url patterns + */ + route: string | string[]; + /** + * Gets a value that indicates whether to maintain the crumb trail + */ + trackCrumbTrail: boolean; + /** + * Gets the crumb trail key + */ + crumbTrailKey: string; + /** + * Gets a value that indicates whether NavigationData Types are + * preserved when navigating + */ + trackTypes: boolean; + /** + * Gets the additional state attributes + */ + [extras: string]: any; + /** + * Called on the old State before navigating to a different State + * @param state The new State + * @param data The new NavigationData + * @param url The new target location + * @param unload The function to call to continue to navigate + * @param history A value indicating whether browser history was used + */ + unloading: (state: State, data: any, url: string, unload: () => void, history?: boolean) => void; + /** + * Called on the old State after navigating to a different State + */ + dispose: () => void; + /** + * Called on the current State after navigating to it + * @param data The current NavigationData + * @param asyncData The data passed asynchronously while navigating + */ + navigated: (data: any, asyncData: any) => void; + /** + * Called on the new State before navigating to it + * @param data The new NavigationData + * @param url The new target location + * @param navigate The function to call to continue to navigate + * @param history A value indicating whether browser history was used + */ + navigating: (data: any, url: string, navigate: (asyncData?: any) => void, history: boolean) => void; + /** + * Encodes the Url value + * @param state The State navigated to + * @param key The key of the navigation data item + * @param val The Url value of the navigation data item + * @param queryString A value indicating the Url value's location + */ + urlEncode(state: State, key: string, val: string, queryString: boolean): string; + /** + * Decodes the Url value + * @param state The State navigated to + * @param key The key of the navigation data item + * @param val The Url value of the navigation data item + * @param queryString A value indicating the Url value's location + */ + urlDecode(state: State, key: string, val: string, queryString: boolean): string; + /** + * Validates the NavigationData before navigating to the new State + * @param data The new NavigationData + * @returns Validation success indicator + */ + validate(data: any): boolean; + /** + * Truncates the crumb trail whenever a repeated or initial State is + * encountered + * @param The State navigated to + * @param The new NavigationData + * @param The Crumb collection representing the crumb trail + * @returns Truncated crumb trail + */ + truncateCrumbTrail(state: State, data: any, crumbs: Crumb[]): Crumb[]; +} + +/** + * Defines a contract a class must implement in order to manage the browser + * Url + */ +interface HistoryManager { + /** + * Gets or sets a value indicating whether to disable browser history + */ + disabled: boolean; + /** + * Registers browser history event listeners + * @param navigateHistory The history navigation event handler + */ + init(navigateHistory: () => void): void; + /** + * Adds browser history + * @param url The current url + * @param replace A value indicating whether to replace the current + * browser history entry + */ + addHistory(url: string, replace: boolean): void; + /** + * Gets the current location + */ + getCurrentUrl(): string; + /** + * Gets an Href from the url + */ + getHref(url: string): string; + /** + * Gets a Url from the anchor or location + */ + getUrl(hrefElement: HTMLAnchorElement | Location): string; + /** + * Removes browser history event listeners + */ + stop(): void; +} + +/** + * Manages history using the browser Url's hash. If used in a browser + * without the hashchange event or outside of a browser environment, then + * history is disabled + */ +export class HashHistoryManager implements HistoryManager { + /** + * Gets or sets a value indicating whether to disable browser history. + * Set to true if used in a browser without the hashchange event or + * outside of a browser environment + */ + disabled: boolean; + /** + * Initializes a new instance of the HashHistoryManager class + * @param replaceQueryIdentifier a value indicating whether to use '#' + * in place of '?'. Set to true for Internet explorer 6 and 7 support + */ + constructor(replaceQueryIdentifier?: boolean); + /** + * Registers a listener for the hashchange event + * @param navigateHistory The history navigation event handler + */ + init(navigateHistory: any): void; + /** + * Sets the browser Url's hash to the url + * @param url The current url + * @param replace A value indicating whether to replace the current + * browser history entry + */ + addHistory(url: string, replace: boolean): void; + /** + * Gets the current location + */ + getCurrentUrl(): string; + /** + * Gets an Href from the url + */ + getHref(url: string): string; + /** + * Gets a Url from the anchor or location + */ + getUrl(hrefElement: HTMLAnchorElement | Location): string; + /** + * Removes a listener for the hashchange event + */ + stop(): void; +} + +/** + * Manages history using the HTML5 history api. If used in a browser + * without the HTML5 history api or outside of a browser environment, then + * history is disabled + */ +export class HTML5HistoryManager implements HistoryManager { + /** + * Gets or sets a value indicating whether to disable browser history. + * Set to true if used in a browser without the HTML5 history api or + * outside of a browser environment + */ + disabled: boolean; + /** + * Initializes a new instance of the HTML5HistoryManager class + * @param applicationPath The application path + */ + constructor(applicationPath?: string); + /** + * Registers a listener for the popstate event + * @param navigateHistory The history navigation event handler + */ + init(navigateHistory: () => void): void; + /** + * Sets the browser Url to the url using pushState + * @param url The current url + * @param replace A value indicating whether to replace the current + * browser history entry + */ + addHistory(url: string, replace: boolean): void; + /** + * Gets the current location + */ + getCurrentUrl(): string; + /** + * Gets an Href from the url + */ + getHref(url: string): string; + /** + * Gets a Url from the anchor or location + */ + getUrl(hrefElement: HTMLAnchorElement | Location): string; + /** + * Removes a listener for the popstate event + */ + stop(): void; +} + +/** + * Represents one piece of the crumb trail and holds the information need + * to return to and recreate the State as previously visited + */ +export class Crumb { + /** + * Gets the Context Data held at the time of navigating away from this + * State + */ + data: any; + /** + * Gets the configuration information associated with this navigation + */ + state: State; + /** + * Gets a value indicating whether the Crumb is the last in the crumb + * trail + */ + last: boolean; + /** + * Gets the State Title + */ + title: string; + /** + * Gets the link navigation to return to the State and pass the + * associated Data + */ + url: string; + /** + * Gets the link navigation without crumb trail to return to the State + * and pass the associated Data + */ + crumblessUrl: string; + /** + * Initializes a new instance of the Crumb class + * @param data The Context Data held at the time of navigating away + * from this State + * @param state The configuration information associated with this + * navigation + * @param link The link navigation to return to the State and pass the + * associated Data + * @param crumblessLink The link navigation without crumb trail to + * return to the State and pass the associated Data + * @param last A value indicating whether the Crumb is the last in the + * crumb trail + */ + constructor(data: any, state: State, link: string, crumblessLink: string, last: boolean); +} + +/** + * Provides properties for accessing context sensitive navigation + * information. Holds the current State and NavigationData + */ +export class StateContext { + /** + * Gets the last State displayed before the current State + */ + oldState: State; + /** + * Gets the NavigationData for the last displayed State + */ + oldData: any; + /** + * Gets the State of the last Crumb in the crumb trail + */ + previousState: State; + /** + * Gets the NavigationData of the last Crumb in the crumb trail + */ + previousData: any; + /** + * Gets the current State + */ + state: State; + /** + * Gets the NavigationData for the current State + */ + data: any; + /** + * Gets the current Url + */ + url: string; + /** + * Gets or sets the current title + */ + title: string; + /** + * Gets a Crumb collection representing the crumb trail, ordered oldest + * Crumb first + */ + crumbs: Crumb[]; + /** + * Gets the next crumb + */ + nextCrumb: Crumb; + /** + * Clears the Context Data + */ + clear(): void; + /** + * Combines the data with a subset of the current NavigationData + * @param The data to add to the current NavigationData + * @returns The combined data + */ + includeCurrentData(data: any, keys?: string[]): any; +} + +/** + * Fluently manages all navigation. These can be forward, backward or + * refreshing the current State + */ +interface FluentNavigator { + /** + * Gets the current Url + */ + url: string; + /** + * Navigates to a State + * @param stateKey The key of a State + * @param navigationData The NavigationData to be passed to the next + * State and stored in the StateContext + * @throws state does not match the key of a State or there is + * NavigationData that cannot be converted to a String + * @throws A mandatory route parameter has not been supplied a value + */ + navigate(stateKey: string, navigationData?: any): FluentNavigator; + /** + * Navigates back along the crumb trail + * @param distance Starting at 1, the number of Crumb steps to go back + * @throws canNavigateBack returns false for this distance + * @throws A mandatory route parameter has not been supplied a value + */ + navigateBack(distance: number): FluentNavigator; + /** + * Navigates to the current State + * @param navigationData The NavigationData to be passed to the current + * State and stored in the StateContext + * @param A value determining the effect on browser history + * @throws There is NavigationData that cannot be converted to a String + * @throws A mandatory route parameter has not been supplied a value + */ + refresh(navigationData?: any): FluentNavigator; +} + +/** + * Manages all navigation. These can be forward, backward or refreshing the + * current State + */ +export class StateNavigator { + /** + * Provides access to context sensitive navigation information + */ + stateContext: StateContext; + /** + * Gets the browser Url manager + */ + historyManager: HistoryManager; + /** + * Gets a list of States + */ + states: { [index: string]: State; }; + /** + * Initializes a new instance of the StateNavigator class + * @param states A collection of States + * @param historyManager The manager of the browser Url + */ + constructor(states?: StateInfo[], historyManager?: HistoryManager); + /** + * Configures the StateNavigator + * @param stateInfos A collection of State Infos + * @param historyManager The manager of the browser Url + */ + configure(stateInfos: StateInfo[], historyManager?: HistoryManager): void; + /** + * Registers a navigate event listener + * @param handler The navigate event listener + */ + onNavigate(handler: (oldState: State, state: State, data: any, asyncData: any) => void): void; + /** + * Unregisters a navigate event listener + * @param handler The navigate event listener + */ + offNavigate(handler: (oldState: State, state: State, data: any, asyncData: any) => void): void; + /** + * Navigates to a State + * @param stateKey The key of a State + * @param navigationData The NavigationData to be passed to the next + * State and stored in the StateContext + * @param A value determining the effect on browser history + * @throws state does not match the key of a State or there is + * NavigationData that cannot be converted to a String + * @throws A mandatory route parameter has not been supplied a value + */ + navigate(stateKey: string, navigationData?: any, historyAction?: 'add' | 'replace' | 'none'): void; + /** + * Gets a Url to navigate to a State + * @param stateKey The key of a State + * @param navigationData The NavigationData to be passed to the next + * State and stored in the StateContext + * @returns Url that will navigate to State specified in the action + * @throws state does not match the key of a State or there is + * NavigationData that cannot be converted to a String + */ + getNavigationLink(stateKey: string, navigationData?: any): string; + /** + * Determines if the distance specified is within the bounds of the + * crumb trail represented by the Crumbs collection + */ + canNavigateBack(distance: number): boolean; + /** + * Navigates back along the crumb trail + * @param distance Starting at 1, the number of Crumb steps to go back + * @param A value determining the effect on browser history + * @throws canNavigateBack returns false for this distance + * @throws A mandatory route parameter has not been supplied a value + */ + navigateBack(distance: number, historyAction?: 'add' | 'replace' | 'none'): void; + /** + * Gets a Url to navigate back along the crumb trail + * @param distance Starting at 1, the number of Crumb steps to go back + * @throws canNavigateBack returns false for this distance + */ + getNavigationBackLink(distance: number): string; + /** + * Navigates to the current State + * @param navigationData The NavigationData to be passed to the current + * State and stored in the StateContext + * @param A value determining the effect on browser history + * @throws There is NavigationData that cannot be converted to a String + * @throws A mandatory route parameter has not been supplied a value + */ + refresh(navigationData?: any, historyAction?: 'add' | 'replace' | 'none'): void; + /** + * Gets a Url to navigate to the current State + * @param navigationData The NavigationData to be passed to the current + * State and stored in the StateContext + * @returns Url that will navigate to the current State + * @throws There is NavigationData that cannot be converted to a String + */ + getRefreshLink(navigationData?: any): string; + /** + * Navigates to the url + * @param url The target location + * @param A value determining the effect on browser history + * @param history A value indicating whether browser history was used + */ + navigateLink(url: string, historyAction?: 'add' | 'replace' | 'none', history?: boolean): void; + /** + * Parses the url out into State and Navigation Data + * @param url The url to parse + */ + parseLink(url: string): { state: State; data: any; }; + /** + * Creates a FluentNavigator + * @param withContext a value indicating whether to inherit the current + * context + * @returns A FluentNavigator + */ + fluent(withContext?: boolean): FluentNavigator; + /** + * Navigates to the passed in url + * @param url The url to navigate to + */ + start(url?: string): void; +} + diff --git a/navigation/navigation-tests.ts b/navigation/navigation-tests.ts index bec19b7f62..7d1ea6bff8 100644 --- a/navigation/navigation-tests.ts +++ b/navigation/navigation-tests.ts @@ -1,91 +1,98 @@ -import Navigation = require("navigation"); +import { Crumb, HashHistoryManager, StateNavigator, State } from 'navigation'; - -namespace NavigationTests { - // History Manager - class LogHistoryManager extends Navigation.HashHistoryManager { - addHistory(url: string) { - console.log('add history'); - super.addHistory(url, false); - } - } - - // Configuration - var config = [ - { key: 'people', route: ['people/{page}', 'people/{page}/sort/{sort}'], defaults: { page: 1 }, help: 'people.htm' }, - { key: 'person', route: 'person/{id}', trackTypes: false, defaultTypes: { id: 'number' }, trackCrumbTrail: true } - ]; - var stateNavigator = new Navigation.StateNavigator(config); - stateNavigator.configure(config, new LogHistoryManager()); - - // States - var states = stateNavigator.states; - var people = states['people']; - var person = states['person']; - var help = people['help']; - var pageDefault = people.defaults.page; - var idDefaultType = person.defaultTypes.id; - - // State Controller - people.dispose = () => {}; - people.navigating = (data, url, navigate) => { - navigate([]); - }; - people.navigated = (data, asyncData) => {}; - person.navigating = (data, url, navigate) => { - navigate(); - }; - person.navigated = (data) => {}; - person.urlEncode = function urlEncode(state: Navigation.State, key: string, val: string, queryString: boolean): string { - return queryString ? val.replace(/\s/g, '+') : encodeURIComponent(val); - }; - person.urlDecode = function urlDecode(state: Navigation.State, key: string, val: string, queryString: boolean): string { - return queryString ? val.replace(/\+/g, ' ') : decodeURIComponent(val); - }; - person.validate = (data: any) => data.id > 0; - - // Navigation Event - var navigationListener = (oldState: Navigation.State, state: Navigation.State, data: any, asyncData: any) => { - stateNavigator.offNavigate(navigationListener); - }; - stateNavigator.onNavigate(navigationListener); - - // Navigation - stateNavigator.navigate('people'); - stateNavigator.navigate('people', null, 'add'); - stateNavigator.refresh(); - stateNavigator.refresh({ page: 3 }); - stateNavigator.refresh({ page: 2 }, 'replace'); - stateNavigator.navigate('person', { id: 10 }); - var canGoBack: boolean = stateNavigator.canNavigateBack(1); - stateNavigator.navigateBack(1); - stateNavigator.stateContext.clear(); - - // Navigation Link - var link = stateNavigator.getNavigationLink('people'); - link = stateNavigator.getRefreshLink(); - link = stateNavigator.getRefreshLink({ page: 2 }); - stateNavigator.navigateLink(link); - link = stateNavigator.getNavigationLink('person', { id: 10 }); - stateNavigator.navigateLink(link, 'replace'); - link = stateNavigator.getNavigationBackLink(1); - var crumb = stateNavigator.stateContext.crumbs[0]; - link = crumb.url; - stateNavigator.navigateLink(link, 'none', true); - - // State Context - var state: Navigation.State = stateNavigator.stateContext.state; - var url: string = stateNavigator.stateContext.url; - var title: string = stateNavigator.stateContext.title; - var page: number = stateNavigator.stateContext.data.page; - state = stateNavigator.stateContext.oldState; - page = stateNavigator.stateContext.oldData.page; - state = stateNavigator.stateContext.previousState; - page = stateNavigator.stateContext.previousData.page; - - // Navigation Data - var data = stateNavigator.stateContext.includeCurrentData({ sort: 'name' }, ['page']); - stateNavigator.refresh(data); - var data = stateNavigator.stateContext.includeCurrentData({ pageSize: 10 }); - stateNavigator.refresh(data); +// History Manager +class LogHistoryManager extends HashHistoryManager { + addHistory(url: string) { + console.log('add history'); + super.addHistory(url, false); + } } + +// Configuration +var config = [ + { key: 'people', route: ['people/{page}', 'people/{page}/sort/{sort}'], defaults: { page: 1 }, help: 'people.htm' }, + { key: 'person', route: 'person/{id}', trackTypes: false, defaultTypes: { id: 'number' }, trackCrumbTrail: true } +]; +var stateNavigator = new StateNavigator(config); +stateNavigator.configure(config, new LogHistoryManager()); + +// States +var states = stateNavigator.states; +var people = states['people']; +var person = states['person']; +var help = people['help']; +var pageDefault = people.defaults.page; +var idDefaultType = person.defaultTypes.id; + +// State Controller +people.dispose = () => {}; +people.navigating = (data, url, navigate) => { + navigate([]); +}; +people.navigated = (data, asyncData) => {}; +person.navigating = (data, url, navigate) => { + navigate(); +}; +person.navigated = (data) => {}; +person.urlEncode = function urlEncode(state: State, key: string, val: string, queryString: boolean): string { + return queryString ? val.replace(/\s/g, '+') : encodeURIComponent(val); +}; +person.urlDecode = function urlDecode(state: State, key: string, val: string, queryString: boolean): string { + return queryString ? val.replace(/\+/g, ' ') : decodeURIComponent(val); +}; +person.validate = (data: any) => data.id > 0; +person.truncateCrumbTrail = (state: State, data: any, crumbs: Crumb[]) => crumbs; + +// Navigation Event +var navigationListener = (oldState: State, state: State, data: any, asyncData: any) => { + stateNavigator.offNavigate(navigationListener); +}; +stateNavigator.onNavigate(navigationListener); + +// Navigation +stateNavigator.navigate('people'); +stateNavigator.navigate('people', null, 'add'); +stateNavigator.refresh(); +stateNavigator.refresh({ page: 3 }); +stateNavigator.refresh({ page: 2 }, 'replace'); +stateNavigator.navigate('person', { id: 10 }); +var canGoBack: boolean = stateNavigator.canNavigateBack(1); +stateNavigator.navigateBack(1); +stateNavigator.stateContext.clear(); + +// Navigation Link +var link = stateNavigator.getNavigationLink('people'); +link = stateNavigator.getRefreshLink(); +link = stateNavigator.getRefreshLink({ page: 2 }); +stateNavigator.navigateLink(link); +link = stateNavigator.getNavigationLink('person', { id: 10 }); +stateNavigator.navigateLink(link, 'replace'); +link = stateNavigator.getNavigationBackLink(1); +var crumb = stateNavigator.stateContext.crumbs[0]; +link = crumb.url; +stateNavigator.navigateLink(link, 'none', true); + +// Fluent Navigation +var link = stateNavigator.fluent() + .navigate('people') + .refresh() + .refresh({ page: 3 }) + .navigate('person', { id: 10 }) + .navigateBack(1) + .url; + +// State Context +var state: State = stateNavigator.stateContext.state; +var url: string = stateNavigator.stateContext.url; +var title: string = stateNavigator.stateContext.title; +var page: number = stateNavigator.stateContext.data.page; +state = stateNavigator.stateContext.oldState; +page = stateNavigator.stateContext.oldData.page; +state = stateNavigator.stateContext.previousState; +page = stateNavigator.stateContext.previousData.page; + +// Navigation Data +var data = stateNavigator.stateContext.includeCurrentData({ sort: 'name' }, ['page']); +stateNavigator.refresh(data); +var data = stateNavigator.stateContext.includeCurrentData({ pageSize: 10 }); +stateNavigator.refresh(data); diff --git a/navigation/tslint.json b/navigation/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/navigation/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/navigo/index.d.ts b/navigo/index.d.ts new file mode 100644 index 0000000000..35c9f009f6 --- /dev/null +++ b/navigo/index.d.ts @@ -0,0 +1,49 @@ +// Type definitions for navigo 4.0 +// Project: https://github.com/krasimir/navigo +// Definitions by: Adrian Ehrsam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface NavigoHooks { + before?: ((done: (suppress?: boolean) => void) => void); + after?: () => void; +} +type RouteHandler = ((parametersObj: any, query: string) => void) | { as: string; uses: (parametersObj: any) => void }; + +declare class Navigo { + + /** + * Constructs the router + * @param root The main URL of your application. + * @param useHash If useHash set to true then the router uses an old routing approach with hash in the URL. Navigo anyways falls back to this mode if there is no History API supported. + */ + constructor(root?: string | null, useHash?: boolean); + + + on(location: string, handler: RouteHandler, hooks?: NavigoHooks): Navigo; + on(location: RegExp, handler: (...parameters: string[]) => void, hooks?: NavigoHooks): Navigo; + on(routes: { [key: string]: RouteHandler }): Navigo; + + on(rootHandler: RouteHandler, hooks?: NavigoHooks): Navigo; + + notFound(handler: ((query: string) => void), hooks?: NavigoHooks): void; + + navigate(path: string, absolute?: boolean): void; + + updatePageLinks(): void; + + generate(path: string, params?: any): string; + + resolve(currentURL?: string): boolean; + + link(path: string): string; + + disableIfAPINotAvailable(): void; + + pause(): void; + + resume(): void; + + destroy(): void; +} +export = Navigo; +export as namespace Navigo; \ No newline at end of file diff --git a/navigo/navigo-tests.ts b/navigo/navigo-tests.ts new file mode 100644 index 0000000000..73ea91f416 --- /dev/null +++ b/navigo/navigo-tests.ts @@ -0,0 +1,123 @@ +import Navigo = require("navigo"); + +var root = null; +var useHash = false; + +var router = new Navigo(root, useHash); + +router + .on('/products/list', () => { + // display all the products + }) + .resolve(); + +router + .on(() => { + // show home page here + }) + .resolve(); + +router + .on({ + '/products/list': () => { + // do something + }, + '/products': () => { + // do something + } + }) + .resolve(); + +router + .on({ + 'products/:id': () => { + // do something + }, + 'products': () => { + // do something + }, + '*': () => { + // do something + } + }) + .resolve(); + + +router + .on('/user/:id/:action', (params: { id: string; action: string }) => { + // If we have http://site.com/user/42/save as a url then + // params.id = 42 + // params.action = save + }) + .resolve(); + +router + .on('/user/:id/:action', (params: { id: string; action: string }, query: string) => { + // If we have http://site.com/user/42/save?answer=42 as a url then + // params.id = 42 + // params.action = save + // query = answer=42 + }) + .resolve(); + +router.notFound((query: string) => { + // ... +}); + +router + .on(/users\/(\d+)\/(\w+)\/?/, (id: string, action: string) => { + // If we have http://site.com/user/42/save as a url then + // id = 42 + // action = save + }) + .resolve(); + +router + .on('/user/*', () => { + // This function will be called on every + // URL that starts with /user + }) + .resolve(); + +router.notFound(() => { + // called when there is path specified but + // there is no route matching +}); + +router.navigate('/products/list'); + +router.navigate('http://site.com/products/list', true); + +router = new Navigo('http://site.com/', true); +var handler = () => { + // do something +}; +router.on({ + '/trip/:tripId/edit': { as: 'trip.edit', uses: handler }, + '/trip/save': { as: 'trip.save', uses: handler }, + '/trip/:action/:tripId': { as: 'trip.action', uses: handler } +}); +var a: string = (router.generate('trip.edit', { tripId: 42 })); // --> /trip/42/edit +a = (router.generate('trip.action', { tripId: 42, action: 'save' })); // --> /trip/save/42 +a = (router.generate('trip.save')); // --> /trip/save + +router.pause(); +router.navigate('/en/products'); +router.resume(); // or .pause(false) + +router.on( + '/user/edit', + () => { + // show user edit page + }, + { + before: (done) => { + // doing some async operation + done(false); + done(); + }, + after: () => { + // do something + } + } +); diff --git a/navigo/tsconfig.json b/navigo/tsconfig.json new file mode 100644 index 0000000000..18a90350c6 --- /dev/null +++ b/navigo/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es5" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "navigo-tests.ts" + ] +} \ No newline at end of file diff --git a/navigo/tslint.json b/navigo/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/navigo/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/nconf/index.d.ts b/nconf/index.d.ts index 3a9a06edb4..ff72f3e568 100644 --- a/nconf/index.d.ts +++ b/nconf/index.d.ts @@ -40,10 +40,11 @@ export declare function path(key: any): any[]; export declare function loadFiles(files: any, callback?: ICallbackFunction): void; export declare function loadFilesSync(files: any, callback?: ICallbackFunction): void; -export declare var formats: { +export interface IFormats { json: IFormat; ini: IFormat; -}; +} +export declare var formats: IFormats; export interface IFormat { stringify: (obj: any, replacer: any, spacing?: any) => string; diff --git a/nedb-logger/index.d.ts b/nedb-logger/index.d.ts new file mode 100644 index 0000000000..4c47ee0dad --- /dev/null +++ b/nedb-logger/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for NeDB Logger 1.8 +// Project: https://github.com/louischatriot/nedb-logger +// Definitions by: Joe vanderstelt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = NeDBLoggerDataStore; +export as namespace NedbLogger; + +declare namespace NeDBLoggerDataStore { } +declare class NeDBLoggerDataStore { + + constructor(path?: string | {filename: string}); + + /** + * Insert a new document + * @param {Function} cb Optional callback, signature: err, insertedDoc + */ + insert(newDoc: T, cb?: (err: Error, document: T) => void): void; + +} diff --git a/nedb-logger/nedb-logger-tests.ts b/nedb-logger/nedb-logger-tests.ts new file mode 100644 index 0000000000..b6665ad44d --- /dev/null +++ b/nedb-logger/nedb-logger-tests.ts @@ -0,0 +1,64 @@ +/** + * Created by Joe Vanderstelt 2017-02-22. + */ + +/// + + +import * as es6styleimport from 'nedb-logger'; + +import Q = require('q'); +import nedblogger = require('nedb-logger'); + +class BaseCollection { + + private dataStore: nedblogger; + + constructor(dataStore: nedblogger) { + + this.dataStore = dataStore; + } + + insert(document: T): Q.Promise { + + var deferred = Q.defer(); + + this.dataStore.insert(document, function(err: Error, newDoc: T) { // Callback is optional + // newDoc is the newly inserted document, including its _id + if (err) { + deferred.reject(err); + } else { + deferred.resolve(newDoc); + } + }); + + return deferred.promise; + } + +} + +// Type 1: Persistent datastore with manual loading + +import Datastore = require('nedb-logger'); +var db = new Datastore({filename: 'path/to/datafile'}); + +var doc: any = { + hello: 'world' + , n: 5 + , today: new Date() + , nedbIsAwesome: true + , notthere: null + , notToBeSaved: undefined // Will not be saved + , fruits: ['apple', 'orange', 'pear'] + , infos: {name: 'nedb'} +}; + +db.insert(doc, function(err: Error, newDoc: any) { // Callback is optional + // newDoc is the newly inserted document, including its _id + // newDoc has no key called notToBeSaved since its value was undefined +}); + +db.insert([{a: 5}, {a: 42}], function(err: Error, newdocs: any[]) { + // Two documents were inserted in the database + // newDocs is an array with these documents, augmented with their _id +}); diff --git a/nedb-logger/tsconfig.json b/nedb-logger/tsconfig.json new file mode 100644 index 0000000000..917e72a038 --- /dev/null +++ b/nedb-logger/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "nedb-logger-tests.ts" + ] +} \ No newline at end of file diff --git a/nedb-logger/tslint.json b/nedb-logger/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/nedb-logger/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/ng-command/ng-command-tests.ts b/ng-command/ng-command-tests.ts index c6eb344ed7..32f9bef158 100644 --- a/ng-command/ng-command-tests.ts +++ b/ng-command/ng-command-tests.ts @@ -1,5 +1,3 @@ -/// - var app = angular.module('testModule', ['ng-command']); class CommandTestController { diff --git a/ng-dialog/ng-dialog-tests.ts b/ng-dialog/ng-dialog-tests.ts index 6c867f422d..b66ed173b7 100644 --- a/ng-dialog/ng-dialog-tests.ts +++ b/ng-dialog/ng-dialog-tests.ts @@ -1,4 +1,3 @@ -/// import * as angular from 'angular'; var app = angular.module('testModule', ['ngDialog']); diff --git a/ng-grid/ng-grid-tests.ts b/ng-grid/ng-grid-tests.ts index f14e9cb540..c6331fdc15 100644 --- a/ng-grid/ng-grid-tests.ts +++ b/ng-grid/ng-grid-tests.ts @@ -1,5 +1,3 @@ -/// - var options1: ngGrid.IGridOptions = { data: [{ 'Name': 'Bob' }, { 'Name': 'Jane' }] }; diff --git a/ng-notify/ng-notify-tests.ts b/ng-notify/ng-notify-tests.ts index e140cb6130..9f81d25e87 100644 --- a/ng-notify/ng-notify-tests.ts +++ b/ng-notify/ng-notify-tests.ts @@ -1,5 +1,3 @@ -/// - class NgNotifyTestController { static $inject = ['$scope', 'ngNotify']; diff --git a/ng-stomp/index.d.ts b/ng-stomp/index.d.ts index d686031bbf..3a91a64844 100644 --- a/ng-stomp/index.d.ts +++ b/ng-stomp/index.d.ts @@ -1,36 +1,31 @@ -// Type definitions for ngStomp +// Type definitions for ngStomp 0.2 // Project: https://github.com/beevelop/ng-stomp // Definitions by: Lukasz Potapczuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + /// - interface ngStomp { - sock:any; - stomp:any; - debug:any; - off: any; + sock: any; + stomp: any; + debug: any; + off: any; - setDebug:(callback:Function)=> void; - - connect: (endpoint:string, headers?:Headers)=> angular.IHttpPromise; - - disconnect: (callback:()=>void) => angular.IHttpPromise; - - subscribe: (destination:string, callback:(payload:string, headers:Headers, res:Function)=>void, headers?:Headers, scope?:any) => any; - - unsubscribe: () => any; - - send: (destination:string, body:any, headers:Headers)=> any; - - } - - interface Headers { - [key: string]: any; - } + setDebug(callback: Function): void; + connect(endpoint: string, headers?: ngStomp.Headers): angular.IHttpPromise; + disconnect(callback: () => void): angular.IHttpPromise; + subscribe(destination: string, callback: (payload: string, headers: ngStomp.Headers, res: Function) => void, headers?: ngStomp.Headers, scope?: any): any; + unsubscribe(): any; + send(destination: string, body: any, headers: ngStomp.Headers): any; +} +declare namespace ngStomp { + interface Headers { + [key: string]: any; + } +} diff --git a/ng-stomp/ng-stomp-tests.ts b/ng-stomp/ng-stomp-tests.ts index b579a3aa06..c1b662d1a5 100644 --- a/ng-stomp/ng-stomp-tests.ts +++ b/ng-stomp/ng-stomp-tests.ts @@ -1,48 +1,34 @@ -/// +class test { + constructor(private ngstomp: ngStomp) { + const connectHeaders = { + Auth: "user", + Accept: "lol" + }; -namespace ngStompTesting { + ngstomp.connect('/endpoint', connectHeaders) + // frame = CONNECTED headers + .then(function (frame) { + this.subscription = ngstomp.subscribe('/dest', function (payload, headers, res) { + this.payload = payload; + }, { + headers: "are awesome" + }); - "use strict"; - var ngStompTest = "ngStompTest"; + // Unsubscribe + this.subscription.unsubscribe(); - class test { - constructor(private ngstomp:ngStomp) { - var connectHeaders ={ - "Auth": "user", - "Accept": "lol" - }; + // Send message + ngstomp.send('/dest', { + message: 'body' + }, { + priority: 9, + custom: 42 //Custom Headers + }); - ngstomp.connect('/endpoint', connectHeaders) - - - // frame = CONNECTED headers - .then(function (frame) { - - this.subscription = ngstomp.subscribe('/dest', function (payload, headers, res) { - this.payload = payload; - }, { - "headers": "are awesome" - }); - - // Unsubscribe - this.subscription.unsubscribe(); - - // Send message - ngstomp.send('/dest', { - message: 'body' - }, { - priority: 9, - custom: 42 //Custom Headers - }); - - // Disconnect - ngstomp.disconnect(function () { - - }); - }); - } - - } - - angular.module("app").controller(ngStompTest, test); + // Disconnect + ngstomp.disconnect(() => {}); + }); + } } + +angular.module("app").controller("ngStompTest", test); diff --git a/ng-stomp/tslint.json b/ng-stomp/tslint.json new file mode 100644 index 0000000000..2ab0c36fa8 --- /dev/null +++ b/ng-stomp/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} \ No newline at end of file diff --git a/ngprogress-lite/ngprogress-lite-tests.ts b/ngprogress-lite/ngprogress-lite-tests.ts index c7df7f9b6b..c4b903d78b 100644 --- a/ngprogress-lite/ngprogress-lite-tests.ts +++ b/ngprogress-lite/ngprogress-lite-tests.ts @@ -1,6 +1,3 @@ -/// - - var app = angular.module('testApp', ['ngProgressLite']); app.config( diff --git a/node-forge/index.d.ts b/node-forge/index.d.ts index 8640f699d4..586827253a 100644 --- a/node-forge/index.d.ts +++ b/node-forge/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for node-forge 0.6.42 // Project: https://github.com/digitalbazaar/forge // Definitions by: Seth Westphal +// Kay Schecker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "node-forge" { @@ -23,6 +24,7 @@ declare module "node-forge" { function privateKeyToPem(key: Key, maxline?: number): PEM; function publicKeyToPem(key: Key, maxline?: number): PEM; + function certificateToPem(cert: Certificate, maxline?: number): PEM; interface oids { [key: string]: string; @@ -234,4 +236,40 @@ declare module "node-forge" { } } } + + namespace pkcs12 { + + interface BagsFilter { + localKeyId?: string; + localKeyIdHex?: string; + friendlyName?: string; + bagType?: string; + } + + interface Bag { + type: string; + attributes: any; + key?: pki.Key; + cert?: pki.Certificate; + asn1: asn1.Asn1 + } + + interface Pkcs12Pfx { + version: string; + safeContents: [{ + encrypted: boolean; + safeBags: Bag[]; + }]; + getBags: (filter: BagsFilter) => { + [key: string]: Bag[]|undefined; + localKeyId?: Bag[]; + friendlyName?: Bag[]; + }; + getBagsByFriendlyName: (fiendlyName: string, bagType: string) => Bag[] + getBagsByLocalKeyId: (localKeyId: string, bagType: string) => Bag[] + } + + function pkcs12FromAsn1(obj:any, strict?: boolean, password?: string) : Pkcs12Pfx; + function pkcs12FromAsn1(obj:any, password?: string) : Pkcs12Pfx; + } } diff --git a/node-hue-api/node-hue-api-tests.ts b/node-hue-api/node-hue-api-tests.ts index 44903fa4da..44e24da9b1 100644 --- a/node-hue-api/node-hue-api-tests.ts +++ b/node-hue-api/node-hue-api-tests.ts @@ -1,5 +1,3 @@ -/// - import hue = require('node-hue-api'); hue.nupnpSearch().then(function (bridges) { diff --git a/node-int64/node-int64-tests.ts b/node-int64/node-int64-tests.ts index 16df3a00ca..3235efa3d8 100644 --- a/node-int64/node-int64-tests.ts +++ b/node-int64/node-int64-tests.ts @@ -1,9 +1,5 @@ -/// - // Play example copy - - // First, let's illustrate the problem ... (0x123456789).toString(16); //!! '123456789' // <- what we expect. diff --git a/node-mysql-wrapper/node-mysql-wrapper-tests.ts b/node-mysql-wrapper/node-mysql-wrapper-tests.ts index 5b67969ffe..2811292fe6 100644 --- a/node-mysql-wrapper/node-mysql-wrapper-tests.ts +++ b/node-mysql-wrapper/node-mysql-wrapper-tests.ts @@ -1,7 +1,3 @@ - -/// -/// - var express = require('express'); var app = express(); var server = require('http').createServer(app); diff --git a/node-powershell/index.d.ts b/node-powershell/index.d.ts new file mode 100644 index 0000000000..978d7e7c29 --- /dev/null +++ b/node-powershell/index.d.ts @@ -0,0 +1,92 @@ +// Type definitions for node-powershell v3.1.1 +// Project: https://github.com/rannn505/node-powershell +// Definitions by: Rodrigo F. Fernandes +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'node-powershell' { + module NodePowershell { + export interface ShellOptions { + /** + * Determines whether to log verbose to the console. + */ + debugMsg?: boolean; + + /** + * Sets the input encoding for the current shell. + */ + inputEncoding?: string; + + /** + * Sets the output encoding for the current shell. + */ + outputEncoding?: string; + + /** + * Sets the default execution policy for the current shell session + */ + executionPolicy?: string; + + /** + * Determines whether to load the Windows PS profile + */ + noProfile?: boolean; + } + + export interface ShellStream { + stdin: NodeJS.WritableStream; + stdout: NodeJS.ReadableStream; + err: NodeJS.ReadableStream; + } + } + + class NodePowershell { + /** + * An array containing the command history ever added to the shell instance. + */ + history: string[]; + + /** + * An object containing the sdtio (in,out,err) [stream.Readable] of the PowerShell Instance. + */ + streams: NodePowershell.ShellStream; + + /** + * Creates a new Shell instance. + */ + constructor(options: NodePowershell.ShellOptions); + + /** + * Adds a command to the end of the pipeline of the shell object. + * @param {string} required - PowerShell command - PowerShell script + * @param {array} optional - {name: ‘’, value: ‘’} - {name: value} - ‘switch’ + * @returns Every command currently in the pipeline. + */ + addCommand(command: string, params?: string[] | { [key: string]: string }[]): Promise; + + /** + * Runs the commands of the shell object pipeline. + * @returns Promise with the command output. + */ + invoke(): Promise; + + /** + * Releases all resources used by the shell object and closes the PowerShell child_process. + * @returns Promise with the error message. + */ + dispose(): Promise; + + /** + * Listens to events emitted from the shell. + * @param eventName required - Possible events: + * 'output' - Emits when shell has an output. + * 'err' - Emits when shell has an error. + * 'end' - Emits when shell ends. + * @param callback required - Callback function to be called when the event emits. + */ + on(eventName: string, callback: (output: string) => void): void; + } + + export = NodePowershell; +} diff --git a/node-powershell/node-powershell-tests.ts b/node-powershell/node-powershell-tests.ts new file mode 100644 index 0000000000..a60f9db331 --- /dev/null +++ b/node-powershell/node-powershell-tests.ts @@ -0,0 +1,33 @@ +import * as nodePowershell from 'node-powershell'; + +var options: nodePowershell.ShellOptions = { + debugMsg: true +}; + +// Initialization +var ps = new nodePowershell(options); + +// Methods +ps.addCommand('Write-Host node-powershell', [ + { name: 'foregroundcolor', value: 'red' }, + { name: 'nonewline' } //switch +]).then((cmdsArr: string[]) => { }).catch((err: any) => { }); + +ps.addCommand('Write-Host node-powershell', [ + { foregroundcolor: 'red' } +]); + +ps.invoke().then((output: string) => { }).catch((err: any) => { }); + +ps.dispose().then((code: string) => { }).catch((err: any) => { }); + +// Properties +console.log(ps.history); + +ps.streams.stdin.write('data'); +ps.streams.stdout.on('data', (data: any) => { }); + +// Events +ps.on('output', (data: string) => { }); +ps.on('err', (err: string) => { }); +ps.on('end', (code: string) => { }); diff --git a/node-powershell/tsconfig.json b/node-powershell/tsconfig.json new file mode 100644 index 0000000000..6cd3607f4f --- /dev/null +++ b/node-powershell/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "node-powershell-tests.ts" + ] +} diff --git a/node-xmpp-client/node-xmpp-client-tests.ts b/node-xmpp-client/node-xmpp-client-tests.ts index 734067738e..0f7a4205ac 100644 --- a/node-xmpp-client/node-xmpp-client-tests.ts +++ b/node-xmpp-client/node-xmpp-client-tests.ts @@ -1,6 +1,6 @@ import {Client} from './index'; -let client = new Client({ +const client = new Client({ jid: 'user@example.com', password: 'password' }); @@ -10,10 +10,10 @@ client.connect(); client.on('online', () => {}); client.on('stanza', stanza => { - let _ = stanza; + const _ = stanza; }); -let stanza = new Client.Stanza('chat', {}) +const stanza = new Client.Stanza('chat', {}) .c('show').t('chat').up() .c('status').t('message'); client.send(stanza); diff --git a/node-xmpp-core/index.d.ts b/node-xmpp-core/index.d.ts new file mode 100644 index 0000000000..dd2b89ca22 --- /dev/null +++ b/node-xmpp-core/index.d.ts @@ -0,0 +1,97 @@ +// Type definitions for node-xmpp-core 5.0 +// Project: github.com/node-xmpp/node-xmpp/ +// Definitions by: PJakcson +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 +/// +import {Element} from 'ltx'; +import {EventEmitter} from 'events'; + +// fixme: not ideal +export {createElement, Element, escapeXML, escapeXMLText} from 'ltx'; + +export declare class Connection extends EventEmitter { + constructor(opts?: any); +} + +export declare namespace SRV { + /** + * returns a lazy iterator which can be restarted via connection.connect() + */ + function connect(opts?: any): any; +} + +export declare class Stanza extends Element { + from: string; + to: string; + id: string; + type: string; + + constructor(name: string, attrs?: any); +} + +/** + * JSX compatible API, use this function as pragma + * https://facebook.github.io/jsx/ + * Returns a Stanza if name is presence, message or iq an ltx Element otherwise. + * + * @param {string} name name of the element + * @param {any} attrs attribute key/value pairs + * @return {Element} Stanza or Element + */ +export declare function createStanza(name: string, attrs?: any): Element; + +export declare class IQ extends Stanza { + constructor(attrs?: any); +} + +export declare class Message extends Stanza { + constructor(attrs?: any); +} + +export declare class Presence extends Stanza { + constructor(attrs?: any); +} + +export declare class JID { + local: string; + domain: string; + resource: string; + + constructor(local: string, domain?: string, resource?: string); + + parseJID(jid: string): void; + + toString(unescape?: any): string; + + /** + * Convenience method to distinguish users + **/ + bare(): JID; + + /** + * Comparison function + **/ + equals(other: JID): boolean; + + /** + * http://xmpp.org/rfcs/rfc6122.html#addressing-localpart + **/ + setLocal(local: string, escape?: any): void; + + getLocal(unescape?: any): string; + + /** + * http://xmpp.org/rfcs/rfc6122.html#addressing-domain + */ + setDomain(value: string): void; + + getDomain(): string; + + /** + * http://xmpp.org/rfcs/rfc6122.html#addressing-resourcepart + */ + setResource(value: string): void; + + getResource(): string; +} diff --git a/node-xmpp-core/node-xmpp-core-tests.ts b/node-xmpp-core/node-xmpp-core-tests.ts new file mode 100644 index 0000000000..ebb27f3b17 --- /dev/null +++ b/node-xmpp-core/node-xmpp-core-tests.ts @@ -0,0 +1,6 @@ +import {Connection} from './index'; + +const con = new Connection(); +con.on('online', () => { + con.eventNames(); +}); diff --git a/node-xmpp-core/tsconfig.json b/node-xmpp-core/tsconfig.json new file mode 100644 index 0000000000..61048d84cb --- /dev/null +++ b/node-xmpp-core/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "node-xmpp-core-tests.ts" + ] +} diff --git a/node-xmpp-core/tslint.json b/node-xmpp-core/tslint.json new file mode 100644 index 0000000000..ec365f164b --- /dev/null +++ b/node-xmpp-core/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} diff --git a/node-zookeeper-client/tsconfig.json b/node-zookeeper-client/tsconfig.json index 1f5ffdedf8..7b493509d7 100644 --- a/node-zookeeper-client/tsconfig.json +++ b/node-zookeeper-client/tsconfig.json @@ -2,7 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es5" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/node/index.d.ts b/node/index.d.ts index d23cc981e4..ca6e83a267 100644 --- a/node/index.d.ts +++ b/node/index.d.ts @@ -40,6 +40,17 @@ interface WeakMapConstructor { } interface SetConstructor { } interface WeakSetConstructor { } +// Forward-declare needed types from lib.es2015.d.ts (in case users are using `--lib es5`) +interface Iterable {} +interface Iterator { + next(value?: any): IteratorResult; +} +interface IteratorResult {} +interface SymbolConstructor { + readonly iterator: symbol; +} +declare var Symbol: SymbolConstructor; + /************************************************ * * * GLOBAL * @@ -1837,6 +1848,41 @@ declare module "url" { export function parse(urlStr: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url; export function format(url: Url): string; export function resolve(from: string, to: string): string; + + export class URLSearchParams implements Iterable { + constructor(init?: URLSearchParams | string); + append(name: string, value: string): void; + delete(name: string): void; + entries(): Iterator; + forEach(callback: (value: string, name: string) => void): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + keys(): Iterator; + set(name: string, value: string): void; + sort(): void; + toString(): string; + values(): Iterator; + [Symbol.iterator](): Iterator; + } + + export class URL { + constructor(input: string, base?: string | URL); + hash: string; + host: string; + hostname: string; + href: string; + readonly origin: string; + password: string; + pathname: string; + port: string; + protocol: string; + search: string; + readonly searchParams: URLSearchParams; + username: string; + toString(): string; + toJSON(): string; + } } declare module "dns" { @@ -1852,7 +1898,7 @@ declare module "dns" { export function resolve4(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolve6(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolveMx(domain: string, callback: (err: Error, addresses: MxRecord[]) => void): string[]; - export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveTxt(domain: string, callback: (err: Error, addresses: string[][]) => void): string[][]; export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; @@ -1903,7 +1949,7 @@ declare module "net" { bufferSize: number; setEncoding(encoding?: string): this; write(data: any, encoding?: string, callback?: Function): void; - destroy(): void; + destroy(err?: any): void; pause(): this; resume(): this; setTimeout(timeout: number, callback?: Function): void; @@ -2030,6 +2076,7 @@ declare module "net" { unref(): Server; maxConnections: number; connections: number; + listening: boolean; /** * events.EventEmitter @@ -2873,7 +2920,7 @@ declare module "tls" { version: string; } - export class TLSSocket extends stream.Duplex { + export class TLSSocket extends net.Socket { /** * Construct a new tls.TLSSocket object from an existing TCP socket. */ @@ -3000,7 +3047,7 @@ declare module "tls" { /** * The numeric representation of the local port. */ - localPort: string; + localPort: number; /** * The string representation of the remote IP address. * For example, '74.125.127.100' or '2001:4860:a005::68'. @@ -3212,10 +3259,10 @@ declare module "tls" { context: any; } - export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) => void): Server; - export function connect(options: ConnectionOptions, secureConnectionListener?: () => void): ClearTextStream; - export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; - export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; + export function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + export function connect(options: ConnectionOptions, secureConnectionListener?: () => void): TLSSocket; + export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; export function createSecureContext(details: SecureContextOptions): SecureContext; } diff --git a/node/node-tests.ts b/node/node-tests.ts index 9585b3893a..04166bc006 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -420,6 +420,79 @@ namespace url_tests { var helloUrl = url.parse('http://example.com/?hello=world', true) assert.equal(helloUrl.query.hello, 'world'); } + + { + let myURL = new url.URL('https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); + assert.equal(myURL.hash, '#bar'); + assert.equal(myURL.host, 'example.org:81'); + assert.equal(myURL.hostname, 'example.org'); + assert.equal(myURL.href, 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); + assert.equal(myURL.origin, 'https://example.org:81'); + assert.equal(myURL.password, 'thepwd'); + assert.equal(myURL.username, 'theuser'); + assert.equal(myURL.pathname, '/foo/path'); + assert.equal(myURL.port, "81"); + assert.equal(myURL.protocol, "https:"); + assert.equal(myURL.search, "?query=string"); + assert.equal(myURL.toString(), 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); + assert(myURL.searchParams instanceof url.URLSearchParams); + + myURL.host = 'example.org:82'; + myURL.hostname = 'example.com'; + myURL.href = 'http://other.com'; + myURL.hash = 'baz'; + myURL.password = "otherpwd"; + myURL.username = "otheruser"; + myURL.pathname = "/otherPath"; + myURL.port = "82"; + myURL.protocol = "http"; + myURL.search = "a=b"; + assert.equal(myURL.href, 'http://otheruser:otherpwd@other.com:82/otherPath?a=b#baz'); + + myURL = new url.URL('/foo', 'https://example.org/'); + assert.equal(myURL.href, 'https://example.org/foo'); + assert.equal(myURL.toJSON(), myURL.href); + } + + { + const searchParams = new url.URLSearchParams('abc=123'); + + assert.equal(searchParams.toString(), 'abc=123'); + searchParams.forEach((value: string, name: string): void => { + assert.equal(name, 'abc'); + assert.equal(value, '123'); + }); + + assert.equal(searchParams.get('abc'), '123'); + + searchParams.append('abc', 'xyz'); + + assert.deepEqual(searchParams.getAll('abc'), ['123', 'xyz']); + + const entries = searchParams.entries(); + assert.deepEqual(entries.next(), { value: ["abc", "123"], done: false}); + assert.deepEqual(entries.next(), { value: ["abc", "xyz"], done: false}); + assert.deepEqual(entries.next(), { value: undefined, done: true}); + + const keys = searchParams.keys(); + assert.deepEqual(keys.next(), { value: "abc", done: false}); + assert.deepEqual(keys.next(), { value: "abc", done: false}); + assert.deepEqual(keys.next(), { value: undefined, done: true}); + + const values = searchParams.values(); + assert.deepEqual(values.next(), { value: "123", done: false}); + assert.deepEqual(values.next(), { value: "xyz", done: false}); + assert.deepEqual(values.next(), { value: undefined, done: true}); + + searchParams.set('abc', 'b'); + assert.deepEqual(searchParams.getAll('abc'), ['b']); + + searchParams.delete('a'); + assert(!searchParams.has('a')); + assert.equal(searchParams.get('a'), null); + + searchParams.sort(); + } } ///////////////////////////////////////////////////// @@ -447,7 +520,7 @@ function stream_readable_pipe_test() { assert(typeof r.bytesRead === 'number'); assert(typeof r.path === 'string'); - assert(typeof rs.path === 'Buffer'); + assert(rs.path instanceof Buffer); r.pipe(z).pipe(w); @@ -2086,7 +2159,7 @@ namespace v8_tests { const heapStats = v8.getHeapStatistics(); const heapSpaceStats = v8.getHeapSpaceStatistics(); - + const zapsGarbage: number = heapStats.does_zap_garbage; v8.setFlagsFromString('--collect_maps'); diff --git a/node/tsconfig.json b/node/tsconfig.json index 640b4f775e..5914d22a4c 100644 --- a/node/tsconfig.json +++ b/node/tsconfig.json @@ -6,7 +6,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es5" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/node/v6/index.d.ts b/node/v6/index.d.ts index 826bd1108b..c523026875 100644 --- a/node/v6/index.d.ts +++ b/node/v6/index.d.ts @@ -2829,7 +2829,7 @@ declare module "tls" { version: string; } - export class TLSSocket extends stream.Duplex { + export class TLSSocket extends net.Socket { /** * Construct a new tls.TLSSocket object from an existing TCP socket. */ @@ -2956,7 +2956,7 @@ declare module "tls" { /** * The numeric representation of the local port. */ - localPort: string; + localPort: number; /** * The string representation of the remote IP address. * For example, '74.125.127.100' or '2001:4860:a005::68'. @@ -3168,10 +3168,10 @@ declare module "tls" { context: any; } - export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) => void): Server; - export function connect(options: ConnectionOptions, secureConnectionListener?: () => void): ClearTextStream; - export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; - export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; + export function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + export function connect(options: ConnectionOptions, secureConnectionListener?: () => void): TLSSocket; + export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; export function createSecureContext(details: SecureContextOptions): SecureContext; } diff --git a/notNeededPackages.json b/notNeededPackages.json index 0cd56b96d1..049791856c 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -305,6 +305,42 @@ "typingsPackageName": "gaea-model", "sourceRepoURL": "https://github.com/ascoders/gaea-model", "asOfVersion": "0.0.0" + }, + { + "libraryName": "pixi-spine", + "typingsPackageName": "pixi-spine", + "sourceRepoURL": "https://github.com/pixijs/pixi-spine", + "asOfVersion": "1.4.2" + }, + { + "libraryName": "jsonschema", + "typingsPackageName": "jsonschema", + "sourceRepoURL": "https://github.com/tdegrunt/jsonschema", + "asOfVersion": "1.1.1" + }, + { + "libraryName": "Raven JS", + "typingsPackageName": "raven-js", + "sourceRepoURL": "https://github.com/getsentry/raven-js", + "asOfVersion": "3.10.0" + }, + { + "libraryName": "antd", + "typingsPackageName": "antd", + "sourceRepoURL": "https://github.com/ant-design/ant-design", + "asOfVersion": "1.0.0" + }, + { + "libraryName": "FineUploader", + "typingsPackageName": "fine-uploader", + "sourceRepoURL": "http://fineuploader.com/", + "asOfVersion": "5.14.0" + }, + { + "libraryName": "mobservable", + "typingsPackageName": "mobservable", + "sourceRepoURL": "github.com/mweststrate/mobservable", + "asOfVersion": "1.2.5" } ] -} +} \ No newline at end of file diff --git a/nouislider/v7/nouislider-tests.ts b/nouislider/v7/nouislider-tests.ts index 0bb6023774..08f9ebd74d 100644 --- a/nouislider/v7/nouislider-tests.ts +++ b/nouislider/v7/nouislider-tests.ts @@ -1,6 +1,3 @@ - -/// - //basic var basicSlider = $("
              ").noUiSlider({ start: 80, diff --git a/npm/npm-tests.ts b/npm/npm-tests.ts index ccebbdb35a..8ca5f01887 100644 --- a/npm/npm-tests.ts +++ b/npm/npm-tests.ts @@ -4,9 +4,6 @@ * Created by using code samples from https://github.com/npm/npm#using-npm-programmatically. */ -/// - - import npm = require("npm"); npm.load({}, function (er) { diff --git a/office-js/index.d.ts b/office-js/index.d.ts index dd18c22914..8dc027f765 100644 --- a/office-js/index.d.ts +++ b/office-js/index.d.ts @@ -52,6 +52,7 @@ declare namespace Office { contentLanguage: string; displayLanguage: string; license: string; + officeTheme: OfficeTheme; touchEnabled: boolean; ui: UI; requirements: { @@ -111,7 +112,12 @@ declare namespace Office { */ xFrameDenySafe?: boolean, } - + export interface OfficeTheme { + bodyBackgroundColor: string; + bodyForegroundColor: string; + controlBackgroundColor: string; + controlForgroundColor: string; + } /** * Dialog object returned as part of the displayDialogAsync callback. The object exposes methods for registering event handlers and closing the dialog */ @@ -1419,334 +1425,174 @@ declare namespace Office { ////////////////////// Begin Exchange APIs ///////////////////// //////////////////////////////////////////////////////////////// - -declare namespace Office.MailboxEnums { - export enum BodyType { - /** - * The body is in HTML format - */ - Html, - /** - * The body is in text format - */ - text - } - export enum EntityType { - /** - * Specifies that the entity is a meeting suggestion - */ - MeetingSuggestion, - /** - * Specifies that the entity is a task suggestion - */ - TaskSuggestion, - /** - * Specifies that the entity is a postal address - */ - Address, - /** - * Specifies that the entity is SMTP email address - */ - EmailAddress, - /** - * Specifies that the entity is an Internet URL - */ - Url, - /** - * Specifies that the entity is US phone number - */ - PhoneNumber, - /** - * Specifies that the entity is a contact - */ - Contact - } - export enum ItemType { - /** - * A meeting request, response, or cancellation - */ - Message, - /** - * Specifies an appointment item - */ - Appointment - } - export enum ResponseType { - /** - * There has been no response from the attendee - */ - None, - /** - * The attendee is the meeting organizer - */ - Organizer, - /** - * The meeting request was tentatively accepted by the attendee - */ - Tentative, - /** - * The meeting request was accepted by the attendee - */ - Accepted, - /** - * The meeting request was declined by the attendee - */ - Declined - } - export enum RecipientType { - /** - * Specifies that the recipient is not one of the other recipient types - */ - Other, - /** - * Specifies that the recipient is a distribution list containing a list of email addresses - */ - DistributionList, - /** - * Specifies that the recipient is an SMTP email address that is on the Exchange server - */ - User, - /** - * Specifies that the recipient is an SMTP email address that is not on the Exchange server - */ - ExternalUser - } - export enum AttachmentType { - /** - * The attachment is a file - */ - File, - /** - * The attachment is an Exchange item - */ - Item - } -} declare namespace Office { - export module Types { - export interface ItemRead extends Office.Item { - subject: any; + export module MailboxEnums { + export enum AttachmentType { /** - * Displays a reply form that includes the sender and all the recipients of the selected message - * @param htmlBody A string that contains text and HTML and that represents the body of the reply form. The string is limited to 32 KB + * The attachment is a file */ - displayReplyAllForm(htmlBody: string): void; + File, /** - * Displays a reply form that includes only the sender of the selected message - * @param htmlBody A string that contains text and HTML and that represents the body of the reply form. The string is limited to 32 KB + * The attachment is an Exchange item */ - displayReplyForm(htmlBody: string): void; - /** - * Gets an array of entities found in an message - */ - getEntities(): Office.Entities; - /** - * Gets an array of entities of the specified entity type found in an message - * @param entityType One of the EntityType enumeration values - */ - getEntitiesByType(entityType: Office.MailboxEnums.EntityType): Office.Entities; - /** - * Returns well-known entities that pass the named filter defined in the manifest XML file - * @param name A TableData object with the headers and rows - */ - getFilteredEntitiesByName(name: string): Office.Entities; - /** - * Returns string values in the currently selected message object that match the regular expressions defined in the manifest XML file - */ - getRegExMatches(): string[]; - /** - * Returns string values that match the named regular expression defined in the manifest XML file - */ - getRegExMatchesByName(name: string): string[]; + Item } - export interface ItemCompose extends Office.Item { - body: Office.Body; - subject: any; + export enum EntityType { /** - * Adds a file to a message as an attachment - * @param uri The URI that provides the location of the file to attach to the message. The maximum length is 2048 characters - * @param attachmentName The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional callback method + * Specifies that the entity is a meeting suggestion */ - addFileAttachmentAsync(uri: string, attachmentName: string, options?: any, callback?: (result: AsyncResult) => void): void; + MeetingSuggestion, /** - * Adds an Exchange item, such as a message, as an attachment to the message - * @param itemId The Exchange identifier of the item to attach. The maximum length is 100 characters - * @param attachmentName The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional callback method + * Specifies that the entity is a task suggestion */ - addItemAttachmentAsync(itemId: any, attachmentName: string, options?: any, callback?: (result: AsyncResult) => void): void; + TaskSuggestion, /** - * Removes an attachment from a message - * @param attachmentIndex The index of the attachment to remove. The maximum length of the string is 100 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional callback method + * Specifies that the entity is a postal address */ - removeAttachmentAsync(attachmentIndex: string, option?: any, callback?: (result: AsyncResult) => void): void; + Address, + /** + * Specifies that the entity is SMTP email address + */ + EmailAddress, + /** + * Specifies that the entity is an Internet URL + */ + Url, + /** + * Specifies that the entity is US phone number + */ + PhoneNumber, + /** + * Specifies that the entity is a contact + */ + Contact } - export interface MessageCompose extends Office.Message { - attachments: Office.AttachmentDetails[]; - body: Office.Body; - bcc: Office.Recipients; - cc: Office.Recipients; - subject: Office.Subject; - to: Office.Recipients; + export enum ItemNotificationMessageType { /** - * Adds a file to a message as an attachment - * @param uri The URI that provides the location of the file to attach to the message. The maximum length is 2048 characters - * @param attachmentName The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional callback method + * The notificationMessage is a progress indicator. */ - addFileAttachmentAsync(uri: string, attachmentName: string, options?: any, callback?: (result: AsyncResult) => void): void; + ProgressIndicator, /** - * Adds an Exchange item, such as a message, as an attachment to the message - * @param itemId The Exchange identifier of the item to attach. The maximum length is 100 characters - * @param attachmentName The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional callback method + * The notificationMessage is an informational message. */ - addItemAttachmentAsync(itemId: any, attachmentName: string, options?: any, callback?: (result: AsyncResult) => void): void; + InformationalMessage, /** - * Removes an attachment from a message - * @param attachmentIndex The index of the attachment to remove. The maximum length of the string is 100 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional callback method + * The notificationMessage is an error message. */ - removeAttachmentAsync(attachmentIndex: string, option?: any, callback?: (result: AsyncResult) => void): void; + ErrorMessage } - export interface MessageRead extends Office.Message { - cc: Office.EmailAddressDetails[]; - from: Office.EmailAddressDetails; - internetMessageId: string; - normalizedSubject: string; - sender: Office.EmailAddressDetails; - subject: string; - to: Office.EmailAddressDetails; + export enum ItemType { /** - * Displays a reply form that includes the sender and all the recipients of the selected message - * @param htmlBody A string that contains text and HTML and that represents the body of the reply form. The string is limited to 32 KB + * An email, meeting request, meeting response, or meeting cancellation */ - displayReplyAllForm(htmlBody: string): void; + Message, /** - * Displays a reply form that includes only the sender of the selected message - * @param htmlBody A string that contains text and HTML and that represents the body of the reply form. The string is limited to 32 KB + * An appointment item */ - displayReplyForm(htmlBody: string): void; - /** - * Gets an array of entities found in an message - */ - getEntities(): Office.Entities; - /** - * Gets an array of entities of the specified entity type found in an message - * @param entityType One of the EntityType enumeration values - */ - getEntitiesByType(entityType: Office.MailboxEnums.EntityType): Office.Entities; - /** - * Returns well-known entities that pass the named filter defined in the manifest XML file - * @param name A TableData object with the headers and rows - */ - getFilteredEntitiesByName(name: string): Office.Entities; - /** - * Returns string values in the currently selected message object that match the regular expressions defined in the manifest XML file - */ - getRegExMatches(): string[]; - /** - * Returns string values that match the named regular expression defined in the manifest XML file - */ - getRegExMatchesByName(name: string): string[]; + Appointment } - export interface AppointmentCompose extends Office.Appointment { - body: Office.Body; - end: Office.Time; - location: Office.Location; - optionalAttendees: Office.Recipients; - requiredAttendees: Office.Recipients; - start: Office.Time; - subject: Office.Subject; + export enum ResponseType { /** - * Adds a file to an appointment as an attachment - * @param uri The URI that provides the location of the file to attach to the appointment. The maximum length is 2048 characters - * @param attachmentName The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional callback method + * There has been no response from the attendee */ - addFileAttachmentAsync(uri: string, attachmentName: string, options?: any, callback?: (result: AsyncResult) => void): void; + None, /** - * Adds an Exchange item, such as a message, as an attachment to the appointment - * @param itemId The Exchange identifier of the item to attach. The maximum length is 100 characters - * @param attachmentName The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional callback method + * The attendee is the meeting organizer */ - addItemAttachmentAsync(itemId: any, attachmentName: string, options?: any, callback?: (result: AsyncResult) => void): void; + Organizer, /** - * Removes an attachment from a appointment - * @param attachmentIndex The index of the attachment to remove. The maximum length of the string is 100 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional callback method + * The meeting request was tentatively accepted by the attendee */ - removeAttachmentAsync(attachmentIndex: string, option?: any, callback?: (result: AsyncResult) => void): void; + Tentative, + /** + * The meeting request was accepted by the attendee + */ + Accepted, + /** + * The meeting request was declined by the attendee + */ + Declined } - export interface AppointmentRead extends Office.Appointment { - attachments: Office.AttachmentDetails[]; - end: Date; - location: string; - normalizedSubject: string; - optionalAttendees: Office.EmailAddressDetails; - organizer: Office.EmailAddressDetails; - requiredAttendees: Office.EmailAddressDetails; - resources: string[]; - start: Date; - subject: string; + export enum RecipientType { /** - * Displays a reply form that includes the organizer and all the attendees of the selected appointment item - * @param htmlBody A string that contains text and HTML and that represents the body of the reply form. The string is limited to 32 KB + * Specifies that the recipient is a distribution list containing a list of email addresses */ - displayReplyAllForm(htmlBody: string): void; + DistributionList, /** - * Displays a reply form that includes only the organizer of the selected appointment item - * @param htmlBody A string that contains text and HTML and that represents the body of the reply form. The string is limited to 32 KB + * Specifies that the recipient is an SMTP email address that is on the Exchange server */ - displayReplyForm(htmlBody: string): void; + User, /** - * Gets an array of entities found in an appointment + * Specifies that the recipient is an SMTP email address that is not on the Exchange server */ - getEntities(): Office.Entities; + ExternalUser, /** - * Gets an array of entities of the specified entity type found in an appointment - * @param entityType One of the EntityType enumeration values + * Specifies that the recipient is not one of the other recipient types */ - getEntitiesByType(entityType: Office.MailboxEnums.EntityType): Office.Entities; - /** - * Returns well-known entities that pass the named filter defined in the manifest XML file - * @param name A TableData object with the headers and rows - */ - getFilteredEntitiesByName(name: string): Office.Entities; - /** - * Returns string values in the currently selected appointment object that match the regular expressions defined in the manifest XML file - */ - getRegExMatches(): string[]; - /** - * Returns string values that match the named regular expression defined in the manifest XML file - */ - getRegExMatchesByName(name: string): string[]; + Other + } + export enum RestVersion { + v1_0, + v2_0, + Beta } } export module cast { export module item { - function toAppointmentCompose(item: Office.Item): Office.Types.AppointmentCompose; - function toAppointmentRead(item: Office.Item): Office.Types.AppointmentRead; + function toAppointmentCompose(item: Office.Item): Office.AppointmentCompose; + function toAppointmentRead(item: Office.Item): Office.AppointmentRead; function toAppointment(item: Office.Item): Office.Appointment; - function toMessageCompose(item: Office.Item): Office.Types.MessageCompose; - function toMessageRead(item: Office.Item): Office.Types.MessageRead; + function toMessageCompose(item: Office.Item): Office.MessageCompose; + function toMessageRead(item: Office.Item): Office.MessageRead; function toMessage(item: Office.Item): Office.Message; - function toItemCompose(item: Office.Item): Office.Types.ItemCompose; - function toItemRead(item: Office.Item): Office.Types.ItemRead; + function toItemCompose(item: Office.Item): Office.ItemCompose; + function toItemRead(item: Office.Item): Office.ItemRead; } } + export interface AsyncContextOptions { + asyncContext?: any; + } + export interface CoercionTypeOptions { + coercionType?: CoercionType; + } + export enum SourceProperty { + /** + * The source of the data is from the body of the message. + */ + Body, + /** + * The source of the data is from the subject of the message. + */ + Subject + } + export interface Appointment extends Item { + } + export interface AppointmentCompose extends Appointment, ItemCompose { + end: Time; + location: Location; + optionalAttendees: Recipients; + requiredAttendees: Recipients; + start: Time; + } + export interface AppointmentRead extends Appointment, ItemRead { + end: Date; + location: string; + optionalAttendees: Array; + organizer: EmailAddressDetails; + requiredAttendees: Array; + resources: EmailAddressDetails; + start: Date; + } + export interface AppointmentForm { + requiredAttendees: Array | Array; + optionalAttendees: Array | Array; + start: Date; + end: Date; + location: string; + resources: Array; + subject: string; + body: string; + } export interface AttachmentDetails { attachmentType: Office.MailboxEnums.AttachmentType; contentType: string; @@ -1755,16 +1601,51 @@ declare namespace Office { name: string; size: number; } + export interface Body { + /** + * Returns the current body in a specified format + * @param coercionType The format of the returned body + * @param options Any optional parameters or state data passed to the method + * @param The optional method to call when the getAsync method returns + */ + getAsync(coercionType: CoercionType, options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /* + * Gets a value that indicates whether the content is in HTML or text format + * @param tableData A TableData object with the headers and rows + * @param options Any optional parameters or state data passed to the method + * @param callback The optional method to call when the getTypeAsync method returns + */ + getTypeAsync(options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Adds the specified content to the beginning of the item body + * @param data The string to be inserted at the beginning of the body. The string is limited to 1,000,000 characters + * @param options Any optional parameters or state data passed to the method + * @param callback The optional method to call when the string is inserted + */ + prependAsync(data: string, options?: AsyncContextOptions & CoercionTypeOptions, callback?: (result: AsyncResult) => void): void; + /** + * Replaces the entire body with the specified text. + * @param data The string that will replace the existing body. The string is limited to 1,000,000 characters + * @param options Any optional parameters or state data passed to the method + * @param callback the optional method to call when the body is replaced + */ + setAsync(data: string, options?: AsyncContextOptions & CoercionTypeOptions, callback?: (result: AsyncResult) => void): void; + /** + * Replaces the selection in the body with the specified text + * @param data The string to be inserted at the beginning of the body. The string is limited to 1,000,000 characters + * @param options Any optional parameters or state data passed to the method + * @param callback The optional method to call when the string is inserted + */ + setSelectedDataAsync(data: string, options?: AsyncContextOptions & CoercionTypeOptions, callback?: (result: AsyncResult) => void): void; + } export interface Contact { + addresses: Array; + businessName: string; + emailAddresses: Array; personName: string; - businessName: string; - phoneNumbers: PhoneNumber[]; - emailAddresses: string[]; - urls: string[]; - addresses: string[]; - contactString: string; + phoneNumbers: Array; + urls: Array; } - export interface Context { mailbox: Mailbox; roamingSettings: RoamingSettings; @@ -1793,6 +1674,11 @@ declare namespace Office { */ saveAsync(callback?: (result: AsyncResult) => void, userContext?: any): void; } + export interface Diagnostics { + hostName: string; + hostVersion: string; + OWAView: string; + } export interface EmailAddressDetails { emailAddress: string; displayName: string; @@ -1800,24 +1686,22 @@ declare namespace Office { recipientType: Office.MailboxEnums.RecipientType; } export interface EmailUser { - name: string; - userId: string; + displayName: string; + emailAddress: string; } export interface Entities { - addresses: string[]; - taskSuggestions: string[]; - meetingSuggestions: MeetingSuggestion[]; - emailAddresses: string[]; - urls: string[]; - phoneNumbers: PhoneNumber[]; - contacts: Contact[]; + addresses: Array; + contacts: Array; + emailAddresses: Array; + meetingSuggestions: Array; + phoneNumbers: Array; + taskSuggestions: Array; + urls: Array; } export interface Item { - dateTimeCreated: Date; - dateTimeModified: Date; - itemClass: string; - itemId: string; + body: Body; itemType: Office.MailboxEnums.ItemType; + notificationMessages: NotificationMessages; /** * Asynchronously loads custom properties that are specific to the item and a app for Office * @param callback The optional callback method @@ -1825,30 +1709,110 @@ declare namespace Office { */ loadCustomPropertiesAsync(callback?: (result: AsyncResult) => void, userContext?: any): void; } - export interface Appointment extends Item { + export interface ItemCompose extends Item { + subject: Subject; + /** + * Adds a file to a message as an attachment + * @param uri The URI that provides the location of the file to attach to the message. The maximum length is 2048 characters + * @param attachmentName The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters + * @param options Any optional parameters or state data passed to the method + * @param callback The optional callback method + */ + addFileAttachmentAsync(uri: string, attachmentName: string, options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Adds an Exchange item, such as a message, as an attachment to the message + * @param itemId The Exchange identifier of the item to attach. The maximum length is 100 characters + * @param attachmentName The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters + * @param options Any optional parameters or state data passed to the method + * @param callback The optional callback method + */ + addItemAttachmentAsync(itemId: any, attachmentName: string, options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Closes the current item that is being composed + * + * The behaviors of the close method depends on the current state of the item being composed. If the item has unsaved changes, the client + * prompts the user to save, discard, or close the action. + * + * In the Outlook desktop client, if the message is an inline reply, the close method has no effect. + */ + close(): void; + /** + * Asynchronously returns selected data from the subject or body of a message. + * + * If there is no selection but the cursor is in the body or the subject, the method returns null for the selected data. If a field other + * than the body or subject is selected, the method returns the InvalidSelection error + */ + getSelectedDataAsync(coercionType: CoercionType, options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Removes an attachment from a message + * @param attachmentIndex The index of the attachment to remove. The maximum length of the string is 100 characters + * @param options Any optional parameters or state data passed to the method + * @param callback The optional callback method + */ + removeAttachmentAsync(attachmentIndex: string, options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Asynchronously saves an item. + * + * When invoked, this method saves the current message as a draft and returns the item id via the callback method. In Outlook Web App or + * Outlook in online mode, the item is saved to the server. In Outlook in cached mode, the item is saved to the local cache. + */ + saveAsync(options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Asynchronously inserts data into the body or subject of a message. + */ + setSelectedDataAsync(data: string, options?: AsyncContextOptions & CoercionTypeOptions, callback?: (result: AsyncResult) => void): void; } - export interface Body { + export interface ItemRead extends Item { + itemClass: string; + itemId: string; + normalizedSubject: string; + subject: string; /** - * Gets a value that indicates whether the content is in HTML or text format - * @param tableData A TableData object with the headers and rows - * @param options Any optional parameters or state data passed to the method - * @param callback The optional method to call when the getTypeAsync method returns + * Displays a reply form that includes the sender and all the recipients of the selected message + * @param formData A string that contains text and HTML and that represents the body of the reply form. The string is limited to 32 KB + * OR + * An object that contains body or attachment data and a callback function */ - getTypeAsync(options?: any, callback?: (result: AsyncResult) => void): void; + displayReplyAllForm(formData: string | ReplyFormData): void; /** - * Adds the specified content to the beginning of the item body - * @param data The string to be inserted at the beginning of the body. The string is limited to 1,000,000 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional method to call when the string is inserted + * Displays a reply form that includes only the sender of the selected message + * @param formData A string that contains text and HTML and that represents the body of the reply form. The string is limited to 32 KB + * OR + * An object that contains body or attachment data and a callback function */ - prependAsync(data: string, options?: any, callback?: (result: AsyncResult) => void): void; + displayReplyForm(formData: string | ReplyFormData): void; /** - * Replaces the selection in the body with the specified text - * @param data The string to be inserted at the beginning of the body. The string is limited to 1,000,000 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional method to call when the string is inserted + * Gets the entities found in the selected item */ - setSelectedDataAsync(data: string, options?: any, callback?: (result: AsyncResult) => void): void; + getEntities(): Entities; + /** + * Gets an array of entities of the specified entity type found in an message + * @param entityType One of the EntityType enumeration values + */ + getEntitiesByType(entityType: Office.MailboxEnums.EntityType): Array<(string | Contact | MeetingSuggestion | PhoneNumber | TaskSuggestion)>; + /** + * Returns well-known entities that pass the named filter defined in the manifest XML file + * @param name The name of the ItemHasKnownEntity rule element that defines the filter to match + */ + getFilteredEntitiesByName(name: string): Array<(string | Contact | MeetingSuggestion | PhoneNumber | TaskSuggestion)>; + /** + * Returns string values in the currently selected message object that match the regular expressions defined in the manifest XML file + */ + getRegExMatches(): any; + /** + * Returns string values that match the named regular expression defined in the manifest XML file + */ + getRegExMatchesByName(name: string): Array; + } + export interface LocalClientTime { + month: number; + date: number; + year: number; + hours: number; + minutes: number; + seconds: number; + milliseconds: number; + timezoneOffset: number; } export interface Location { /** @@ -1856,50 +1820,63 @@ declare namespace Office { * @param options Any optional parameters or state data passed to the method * @param callback The optional method to call when the string is inserted */ - getAsync(options?: any, callback?: (result: AsyncResult) => void): void; + getAsync(options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Begins an asynchronous request to set the location of an appointment * @param data The location of the appointment. The string is limited to 255 characters * @param options Any optional parameters or state data passed to the method * @param callback The optional method to call when the location is set */ - setAsync(location: string, options?: any, callback?: (result: AsyncResult) => void): void; + setAsync(location: string, options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; } export interface Mailbox { + diagnostics: Diagnostics; + ewsUrl: string; item: Item; userProfile: UserProfile; + /** + * Converts an item ID formatted for REST into EWS format. + * @param itemId An item ID formatted for the Outlook REST APIs + * @param restVersion A value indicating the version of the Outlook REST API used to retrieve the item ID + */ + convertToEwsId(itemId: string, restVersion: Office.MailboxEnums.RestVersion): string; /** * Gets a Date object from a dictionary containing time information * @param timeValue A Date object */ - convertToLocalClientTime(timeValue: Date): any; + convertToLocalClientTime(timeValue: Date): LocalClientTime; + /** + * Converts an item ID formatted for EWS into REST format. + * @param itemId An item ID formatted for the Outlook EWS APIs + * @param restVersion A value indicating the version of the Outlook REST API that the converted ID will be used with + */ + convertToRestId(itemId: string, restVersion: Office.MailboxEnums.RestVersion): string; /** * Gets a dictionary containing time information in local client time * @param input A dictionary containing a date. The dictionary should contain the following fields: year, month, date, hours, minutes, seconds, time zone, time zone offset */ - convertToUtcClientTime(input: any): Date; + convertToUtcClientTime(input: LocalClientTime): Date; /** * Displays an existing calendar appointment * @param itemId The Exchange Web Services (EWS) identifier for an existing calendar appointment */ - displayAppointmentForm(itemId: any): void; + displayAppointmentForm(itemId: string): void; /** * Displays an existing message * @param itemId The Exchange Web Services (EWS) identifier for an existing message */ - displayMessageForm(itemId: any): void; + displayMessageForm(itemId: string): void; /** * Displays a form for creating a new calendar appointment - * @param requiredAttendees An array of strings containing the email addresses or an array containing an EmailAddressDetails object for each of the required attendees for the appointment. The array is limited to a maximum of 100 entries - * @param optionalAttendees An array of strings containing the email addresses or an array containing an EmailAddressDetails object for each of the optional attendees for the appointment. The array is limited to a maximum of 100 entries - * @param start A Date object specifying the start date and time of the appointment - * @param end A Date object specifying the end date and time of the appointment - * @param location A string containing the location of the appointment. The string is limited to a maximum of 255 characters - * @param resources An array of strings containing the resources required for the appointment. The array is limited to a maximum of 100 entries - * @param subject A string containing the subject of the appointment. The string is limited to a maximum of 255 characters - * @param body The body of the appointment message. The body content is limited to a maximum size of 32 KB + * @param parameters A dictionary of parameters describing the new appointment. */ - displayNewAppointmentForm(requiredAttendees: any, optionalAttendees: any, start: Date, end: Date, location: string, resources: string[], subject: string, body: string): void; + displayNewAppointmentForm(parameters?: AppointmentForm): void; + /** + * Displays a new message form + * WARNING: This api is not officially released, and may not work on all platforms + * @param options A dictionary containing all values to be filled in for the user in the new form + */ + displayNewMessageForm(options?: any): void; /** * Gets a string that contains a token used to get an attachment or item from an Exchange Server * @param callback The optional method to call when the string is inserted @@ -1923,20 +1900,63 @@ declare namespace Office { export interface Message extends Item { conversationId: string; } - export interface MeetingRequest extends Message { - start: Date; - end: Date; - location: string; - optionalAttendees: EmailAddressDetails[]; - requiredAttendees: EmailAddressDetails[]; + export interface MessageCompose extends Message, ItemCompose { + bcc: Recipients; + cc: Recipients; + to: Recipients; + } + export interface MessageRead extends Message, ItemRead { + cc: Array; + from: EmailAddressDetails; + internetMessageId: string; + sender: EmailAddressDetails; + to: Array; } export interface MeetingSuggestion { - meetingString: string; - attendees: EmailAddressDetails[]; + attendees: Array; + end: string; location: string; + meetingstring: string; + start: string; subject: string; - start: Date; - end: Date; + } + export interface NotificationMessageDetails { + key?: string; + type: Office.MailboxEnums.ItemNotificationMessageType; + icon?: string; + message: string; + persistent?: Boolean; + } + export interface NotificationMessages { + /** + * Adds a notification to an item + * @param key A developer-specified key used to refrence this notification message. Developers can use it to modify this message later. + * @param JSONmessage A JSON object that contains the notification message to be added to this item + * @param options Any optional parameters or state data passed to the method + * @param callback The optional callback method + */ + addAsync(key: string, JSONmessage: NotificationMessageDetails, options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Returns all keys and messages for an item. + * @param options Any optional parameters or state data passed to the method + * @param callback The optional callback method + */ + getAllAsync(options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Removes a notification message for an item. + * @param key The key for the notification message to remove + * @param options Any optional parameters or state data passed to the method + * @param callback The optional callback method + */ + removeAsync(key: string, options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Replaces a notification message that has a given key with another message + * @param key The key for the notification message to replace. + * @param JSONmessage A JSON object that contains the new notification message to replace the existing message + * @param options Any optional parameters or state data passed to the method + * @param callback The optional callback method + */ + replaceAsync(key: string, JSONmessage: NotificationMessageDetails, options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; } export interface PhoneNumber { phoneString: string; @@ -1950,20 +1970,31 @@ declare namespace Office { * @param options Any optional parameters or state data passed to the method * @param callback The optional method to call when the string is inserted */ - addAsync(recipients: any, options?: any, callback?: (result: AsyncResult) => void): void; + addAsync(recipients: Array, options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Begins an asynchronous request to get the recipient list for an appointment or message * @param options Any optional parameters or state data passed to the method * @param callback The optional method to call when the string is inserted */ - getAsync(options?: any, callback?: (result: AsyncResult) => void): void; + getAsync(options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Begins an asynchronous request to set the recipient list for an appointment or message * @param recipients The recipients to add to the recipients list * @param options Any optional parameters or state data passed to the method * @param callback The optional method to call when the string is inserted */ - setAsync(recipients: any, options?: any, callback?: (result: AsyncResult) => void): void; + setAsync(recipients: Array, options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + } + export interface ReplyFormAttachment { + type: string; + name: string; + url?: string; + itemId?: string; + } + export interface ReplyFormData { + htmlBody?: string; + attachments?: Array; + callback?: (result: AsyncResult) => void; } export interface RoamingSettings { /** @@ -1994,17 +2025,17 @@ declare namespace Office { * @param options Any optional parameters or state data passed to the method * @param callback The optional method to call when the string is inserted */ - getAsync(options?: any, callback?: (result: AsyncResult) => void): void; + getAsync(options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Begins an asynchronous call to set the subject of an appointment or message * @param data The subject of the appointment. The string is limited to 255 characters * @param options Any optional parameters or state data passed to the method * @param callback The optional method to call when the string is inserted */ - setAsync(data: string, options?: any, callback?: (result: AsyncResult) => void): void; + setAsync(data: string, options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; } export interface TaskSuggestion { - assignees: EmailUser[]; + assignees: Array; taskString: string; } export interface Time { @@ -2013,14 +2044,14 @@ declare namespace Office { * @param options Any optional parameters or state data passed to the method * @param callback The optional method to call when the string is inserted */ - getAsync(options?: any, callback?: (result: AsyncResult) => void): void; + getAsync(options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Begins an asynchronous request to set the start or end time * @param dateTime A date-time object in Coordinated Universal Time (UTC) * @param options Any optional parameters or state data passed to the method * @param callback The optional method to call when the string is inserted */ - setAsync(dateTime: Date, options?: any, callback?: (result: AsyncResult) => void): void; + setAsync(dateTime: Date, options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; } export interface UserProfile { displayName: string; @@ -2072,7 +2103,7 @@ declare module OfficeExtension { requestHeaders: { [name: string]: string }; /** Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ - load(object: ClientObject, option?: string | string[]| LoadOption): void; + load(object: ClientObject, option?: string | string[] | LoadOption): void; /** * Queues up a command to recursively load the specified properties of the object and its navigation properties. @@ -10328,29 +10359,7 @@ declare module Excel { //////////////////////////////////////////////////////////////// -declare module Word { - /** - * - * The Application object. - * - * [Api set: WordApi 1.3] - */ - class Application extends OfficeExtension.ClientObject { - /** - * - * Creates a new document by using a base64 encoded .docx file. - * - * @param base64File Optional. The base64 encoded .docx file. The default value is null. - * - * [Api set: WordApi 1.3] - */ - createDocument(base64File?: string): Word.Document; - /** - * Create a new instance of Word.Application object - */ - static newObject(context: OfficeExtension.ClientRequestContext): Word.Application; - toJSON(): {}; - } +declare namespace Word { /** * * Represents the body of a document or a section. @@ -10395,25 +10404,46 @@ declare module Word { paragraphs: Word.ParagraphCollection; /** * - * Gets the parent body of the body. For example, a table cell body's parent body could be a header. Read-only. + * Gets the parent body of the body. For example, a table cell body's parent body could be a header. Throws if there isn't a parent body. Read-only. * * [Api set: WordApi 1.3] */ parentBody: Word.Body; /** * - * Gets the content control that contains the body. Returns a null object if there isn't a parent content control. Read-only. + * Gets the parent body of the body. For example, a table cell body's parent body could be a header. Returns a null object if there isn't a parent body. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentBodyOrNullObject: Word.Body; + /** + * + * Gets the content control that contains the body. Throws if there isn't a parent content control. Read-only. * * [Api set: WordApi 1.1] */ parentContentControl: Word.ContentControl; /** * - * Gets the parent section of the body. Read-only. + * Gets the content control that contains the body. Returns a null object if there isn't a parent content control. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentContentControlOrNullObject: Word.ContentControl; + /** + * + * Gets the parent section of the body. Throws if there isn't a parent section. Read-only. * * [Api set: WordApi 1.3] */ parentSection: Word.Section; + /** + * + * Gets the parent section of the body. Returns a null object if there isn't a parent section. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentSectionOrNullObject: Word.Section; /** * * Gets the collection of table objects in the body. Read-only. @@ -10449,6 +10479,15 @@ declare module Word { * [Api set: WordApi 1.3] */ type: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.BodyUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Body): void; /** * * Clears the contents of the body object. The user can perform the undo operation on the cleared content. @@ -10474,19 +10513,19 @@ declare module Word { * * Gets the whole body, or the starting or ending point of the body, as a range. * - * @param rangeLocation Optional. The range location can be 'Whole', 'Start', 'End', 'After' or 'Content'. - * * [Api set: WordApi 1.3] + * + * @param rangeLocation Optional. The range location can be 'Whole', 'Start', 'End', 'After' or 'Content'. */ getRange(rangeLocation?: string): Word.Range; /** * * Inserts a break at the specified location in the main document. The insertLocation value can be 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param breakType Required. The break type to add to the body. * @param insertLocation Required. The value can be 'Start' or 'End'. - * - * [Api set: WordApi 1.1] */ insertBreak(breakType: string, insertLocation: string): void; /** @@ -10500,82 +10539,82 @@ declare module Word { * * Inserts a document into the body at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param base64File Required. The base64 encoded content of a .docx file. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. - * - * [Api set: WordApi 1.1] */ insertFileFromBase64(base64File: string, insertLocation: string): Word.Range; /** * * Inserts HTML at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param html Required. The HTML to be inserted in the document. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. - * - * [Api set: WordApi 1.1] */ insertHtml(html: string, insertLocation: string): Word.Range; /** * * Inserts a picture into the body at the specified location. The insertLocation value can be 'Start' or 'End'. * + * [Api set: WordApi 1.2] + * * @param base64EncodedImage Required. The base64 encoded image to be inserted in the body. * @param insertLocation Required. The value can be 'Start' or 'End'. - * - * [Api set: WordApi 1.2] */ insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: string): Word.InlinePicture; /** * * Inserts OOXML at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param ooxml Required. The OOXML to be inserted. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. - * - * [Api set: WordApi 1.1] */ insertOoxml(ooxml: string, insertLocation: string): Word.Range; /** * * Inserts a paragraph at the specified location. The insertLocation value can be 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param paragraphText Required. The paragraph text to be inserted. * @param insertLocation Required. The value can be 'Start' or 'End'. - * - * [Api set: WordApi 1.1] */ insertParagraph(paragraphText: string, insertLocation: string): Word.Paragraph; /** * * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Start' or 'End'. * + * [Api set: WordApi 1.3] + * * @param rowCount Required. The number of rows in the table. * @param columnCount Required. The number of columns in the table. * @param insertLocation Required. The value can be 'Start' or 'End'. * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. - * - * [Api set: WordApi 1.3] */ insertTable(rowCount: number, columnCount: number, insertLocation: string, values?: Array>): Word.Table; /** * * Inserts text into the body at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param text Required. Text to be inserted. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. - * - * [Api set: WordApi 1.1] */ insertText(text: string, insertLocation: string): Word.Range; /** * * Performs a search with the specified searchOptions on the scope of the body object. The search results are a collection of range objects. * + * [Api set: WordApi 1.1] + * * @param searchText Required. The search text. * @param searchOptions Optional. Options for the search. - * - * [Api set: WordApi 1.1] */ search(searchText: string, searchOptions?: Word.SearchOptions | { ignorePunct?: boolean; @@ -10590,9 +10629,9 @@ declare module Word { * * Selects the body and navigates the Word UI to it. * - * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. - * * [Api set: WordApi 1.1] + * + * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. */ select(selectionMode?: string): void; /** @@ -10604,7 +10643,7 @@ declare module Word { */ track(): Word.Body; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.Body; toJSON(): { @@ -10666,25 +10705,46 @@ declare module Word { parentBody: Word.Body; /** * - * Gets the content control that contains the content control. Returns a null object if there isn't a parent content control. Read-only. + * Gets the content control that contains the content control. Throws if there isn't a parent content control. Read-only. * * [Api set: WordApi 1.1] */ parentContentControl: Word.ContentControl; /** * - * Gets the table that contains the content control. Returns a null object if it is not contained in a table. Read-only. + * Gets the content control that contains the content control. Returns a null object if there isn't a parent content control. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentContentControlOrNullObject: Word.ContentControl; + /** + * + * Gets the table that contains the content control. Throws if it is not contained in a table. Read-only. * * [Api set: WordApi 1.3] */ parentTable: Word.Table; /** * - * Gets the table cell that contains the content control. Returns a null object if it is not contained in a table cell. Read-only. + * Gets the table cell that contains the content control. Throws if it is not contained in a table cell. Read-only. * * [Api set: WordApi 1.3] */ parentTableCell: Word.TableCell; + /** + * + * Gets the table cell that contains the content control. Returns a null object if it is not contained in a table cell. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentTableCellOrNullObject: Word.TableCell; + /** + * + * Gets the table that contains the content control. Returns a null object if it is not contained in a table. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentTableOrNullObject: Word.Table; /** * * Gets the collection of table objects in the content control. Read-only. @@ -10790,6 +10850,15 @@ declare module Word { * [Api set: WordApi 1.1] */ type: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ContentControlUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ContentControl): void; /** * * Clears the contents of the content control. The user can perform the undo operation on the cleared content. @@ -10801,9 +10870,9 @@ declare module Word { * * Deletes the content control and its content. If keepContent is set to true, the content is not deleted. * - * @param keepContent Required. Indicates whether the content should be deleted with the content control. If keepContent is set to true, the content is not deleted. - * * [Api set: WordApi 1.1] + * + * @param keepContent Required. Indicates whether the content should be deleted with the content control. If keepContent is set to true, the content is not deleted. */ delete(keepContent: boolean): void; /** @@ -10824,111 +10893,111 @@ declare module Word { * * Gets the whole content control, or the starting or ending point of the content control, as a range. * - * @param rangeLocation Optional. The range location can be 'Whole', 'Before', 'Start', 'End', 'After' or 'Content'. - * * [Api set: WordApi 1.3] + * + * @param rangeLocation Optional. The range location can be 'Whole', 'Before', 'Start', 'End', 'After' or 'Content'. */ getRange(rangeLocation?: string): Word.Range; /** * * Gets the text ranges in the content control by using punctuation marks and/or other ending marks. * + * [Api set: WordApi 1.3] + * * @param endingMarks Required. The punctuation marks and/or other ending marks as an array of strings. * @param trimSpacing Optional. Indicates whether to trim spacing characters (spaces, tabs, column breaks and paragraph end marks) from the start and end of the ranges returned in the range collection. Default is false which indicates that spacing characters at the start and end of the ranges are included in the range collection. - * - * [Api set: WordApi 1.3] */ getTextRanges(endingMarks: Array, trimSpacing?: boolean): Word.RangeCollection; /** * * Inserts a break at the specified location in the main document. The insertLocation value can be 'Start', 'End', 'Before' or 'After'. This method cannot be used with 'RichTextTable', 'RichTextTableRow' and 'RichTextTableCell' content controls. * + * [Api set: WordApi 1.1] + * * @param breakType Required. Type of break. * @param insertLocation Required. The value can be 'Start', 'End', 'Before' or 'After'. - * - * [Api set: WordApi 1.1] */ insertBreak(breakType: string, insertLocation: string): void; /** * * Inserts a document into the content control at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param base64File Required. The base64 encoded content of a .docx file. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls. - * - * [Api set: WordApi 1.1] */ insertFileFromBase64(base64File: string, insertLocation: string): Word.Range; /** * * Inserts HTML into the content control at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param html Required. The HTML to be inserted in to the content control. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls. - * - * [Api set: WordApi 1.1] */ insertHtml(html: string, insertLocation: string): Word.Range; /** * * Inserts an inline picture into the content control at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.2] + * * @param base64EncodedImage Required. The base64 encoded image to be inserted in the content control. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls. - * - * [Api set: WordApi 1.2] */ insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: string): Word.InlinePicture; /** * * Inserts OOXML into the content control at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param ooxml Required. The OOXML to be inserted in to the content control. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls. - * - * [Api set: WordApi 1.1] */ insertOoxml(ooxml: string, insertLocation: string): Word.Range; /** * * Inserts a paragraph at the specified location. The insertLocation value can be 'Start', 'End', 'Before' or 'After'. * + * [Api set: WordApi 1.1] + * * @param paragraphText Required. The paragrph text to be inserted. * @param insertLocation Required. The value can be 'Start', 'End', 'Before' or 'After'. 'Before' and 'After' cannot be used with 'RichTextTable', 'RichTextTableRow' and 'RichTextTableCell' content controls. - * - * [Api set: WordApi 1.1] */ insertParagraph(paragraphText: string, insertLocation: string): Word.Paragraph; /** * * Inserts a table with the specified number of rows and columns into, or next to, a content control. The insertLocation value can be 'Start', 'End', 'Before' or 'After'. * + * [Api set: WordApi 1.3] + * * @param rowCount Required. The number of rows in the table. * @param columnCount Required. The number of columns in the table. * @param insertLocation Required. The value can be 'Start', 'End', 'Before' or 'After'. 'Before' and 'After' cannot be used with 'RichTextTable', 'RichTextTableRow' and 'RichTextTableCell' content controls. * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. - * - * [Api set: WordApi 1.3] */ insertTable(rowCount: number, columnCount: number, insertLocation: string, values?: Array>): Word.Table; /** * * Inserts text into the content control at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param text Required. The text to be inserted in to the content control. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls. - * - * [Api set: WordApi 1.1] */ insertText(text: string, insertLocation: string): Word.Range; /** * * Performs a search with the specified searchOptions on the scope of the content control object. The search results are a collection of range objects. * + * [Api set: WordApi 1.1] + * * @param searchText Required. The search text. * @param searchOptions Optional. Options for the search. - * - * [Api set: WordApi 1.1] */ search(searchText: string, searchOptions?: Word.SearchOptions | { ignorePunct?: boolean; @@ -10943,21 +11012,21 @@ declare module Word { * * Selects the content control. This causes Word to scroll to the selection. * - * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. - * * [Api set: WordApi 1.1] + * + * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. */ select(selectionMode?: string): void; /** * * Splits the content control into child ranges by using delimiters. * + * [Api set: WordApi 1.3] + * * @param delimiters Required. The delimiters as an array of strings. * @param multiParagraphs Optional. Indicates whether a returned child range can cover multiple paragraphs. Default is false which indicates that the paragraph boundaries are also used as delimiters. * @param trimDelimiters Optional. Indicates whether to trim delimiters from the ranges in the range collection. Default is false which indicates that the delimiters are included in the ranges returned in the range collection. * @param trimSpacing Optional. Indicates whether to trim spacing characters (spaces, tabs, column breaks and paragraph end marks) from the start and end of the ranges returned in the range collection. Default is false which indicates that spacing characters at the start and end of the ranges are included in the range collection. - * - * [Api set: WordApi 1.3] */ split(delimiters: Array, multiParagraphs?: boolean, trimDelimiters?: boolean, trimSpacing?: boolean): Word.RangeCollection; /** @@ -10969,7 +11038,7 @@ declare module Word { */ track(): Word.ContentControl; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.ContentControl; toJSON(): { @@ -11001,54 +11070,70 @@ declare module Word { items: Array; /** * - * Gets a content control by its identifier. - * - * @param id Required. A content control identifier. + * Gets a content control by its identifier. Throws if there isn't a content control with the identifier in this collection. * * [Api set: WordApi 1.1] + * + * @param id Required. A content control identifier. */ getById(id: number): Word.ContentControl; + /** + * + * Gets a content control by its identifier. Returns a null object if there isn't a content control with the identifier in this collection. + * + * [Api set: WordApi 1.3] + * + * @param id Required. A content control identifier. + */ + getByIdOrNullObject(id: number): Word.ContentControl; /** * * Gets the content controls that have the specified tag. * - * @param tag Required. A tag set on a content control. - * * [Api set: WordApi 1.1] + * + * @param tag Required. A tag set on a content control. */ getByTag(tag: string): Word.ContentControlCollection; /** * * Gets the content controls that have the specified title. * - * @param title Required. The title of a content control. - * * [Api set: WordApi 1.1] + * + * @param title Required. The title of a content control. */ getByTitle(title: string): Word.ContentControlCollection; /** * * Gets the content controls that have the specified types and/or subtypes. * - * @param types Required. An array of content control types and/or subtypes. - * * [Api set: WordApi 1.3] + * + * @param types Required. An array of content control types and/or subtypes. */ getByTypes(types: Array): Word.ContentControlCollection; /** * - * Gets the first content control in this collection. + * Gets the first content control in this collection. Throws if this collection is empty. * * [Api set: WordApi 1.3] */ getFirst(): Word.ContentControl; + /** + * + * Gets the first content control in this collection. Returns a null object if this collection is empty. + * + * [Api set: WordApi 1.3] + */ + getFirstOrNullObject(): Word.ContentControl; /** * * Gets a content control by its index in the collection. * - * @param index The index. - * * [Api set: WordApi 1.1] + * + * @param index The index. */ getItem(index: number): Word.ContentControl; /** @@ -11060,7 +11145,7 @@ declare module Word { */ track(): Word.ContentControlCollection; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.ContentControlCollection; toJSON(): {}; @@ -11093,6 +11178,15 @@ declare module Word { * [Api set: WordApi 1.3] */ value: any; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.CustomPropertyUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: CustomProperty): void; /** * * Deletes the custom property. @@ -11109,7 +11203,7 @@ declare module Word { */ track(): Word.CustomProperty; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.CustomProperty; toJSON(): { @@ -11127,6 +11221,16 @@ declare module Word { class CustomPropertyCollection extends OfficeExtension.ClientObject { /** Gets the loaded child items in this collection. */ items: Array; + /** + * + * Creates a new or sets an existing custom property. + * + * [Api set: WordApi 1.3] + * + * @param key Required. The custom property's key, which is case-insensitive. + * @param value Required. The custom property's value. + */ + add(key: string, value: any): Word.CustomProperty; /** * * Deletes all custom properties in this collection. @@ -11143,23 +11247,22 @@ declare module Word { getCount(): OfficeExtension.ClientResult; /** * - * Gets a custom property object by its key, which is case-insensitive. - * - * @param key The key that identifies the custom property object. + * Gets a custom property object by its key, which is case-insensitive. Throws if the custom property does not exist. * * [Api set: WordApi 1.3] + * + * @param key The key that identifies the custom property object. */ getItem(key: string): Word.CustomProperty; /** * - * Creates or sets a custom property. - * - * @param key Required. The custom property's key, which is case-insensitive. - * @param value Required. The custom property's value. + * Gets a custom property object by its key, which is case-insensitive. Returns a null object if the custom property does not exist. * * [Api set: WordApi 1.3] + * + * @param key Required. The key that identifies the custom property object. */ - set(key: string, value: any): Word.CustomProperty; + getItemOrNullObject(key: string): Word.CustomProperty; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -11169,7 +11272,7 @@ declare module Word { */ track(): Word.CustomPropertyCollection; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.CustomPropertyCollection; toJSON(): {}; @@ -11216,6 +11319,15 @@ declare module Word { * [Api set: WordApi 1.1] */ saved: boolean; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.DocumentUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Document): void; /** * * Gets the current selection of the document. Multiple selections are not supported. @@ -11223,13 +11335,6 @@ declare module Word { * [Api set: WordApi 1.1] */ getSelection(): Word.Range; - /** - * - * Open the document. - * - * [Api set: WordApi 1.3] - */ - open(): void; /** * * Saves the document. This will use the Word default file naming convention if the document has not been saved before. @@ -11246,7 +11351,7 @@ declare module Word { */ track(): Word.Document; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.Document; toJSON(): { @@ -11327,7 +11432,7 @@ declare module Word { keywords: string; /** * - * Gets or sets the last author of the document. + * Gets the last author of the document. Read only. * * [Api set: WordApi 1.3] */ @@ -11388,6 +11493,15 @@ declare module Word { * [Api set: WordApi 1.3] */ title: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.DocumentPropertiesUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: DocumentProperties): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -11397,7 +11511,7 @@ declare module Word { */ track(): Word.DocumentProperties; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.DocumentProperties; toJSON(): { @@ -11504,6 +11618,15 @@ declare module Word { * [Api set: WordApi 1.1] */ underline: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.FontUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Font): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -11513,7 +11636,7 @@ declare module Word { */ track(): Word.Font; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.Font; toJSON(): { @@ -11546,25 +11669,46 @@ declare module Word { paragraph: Word.Paragraph; /** * - * Gets the content control that contains the inline image. Returns a null object if there isn't a parent content control. Read-only. + * Gets the content control that contains the inline image. Throws if there isn't a parent content control. Read-only. * * [Api set: WordApi 1.1] */ parentContentControl: Word.ContentControl; /** * - * Gets the table that contains the inline image. Returns a null object if it is not contained in a table. Read-only. + * Gets the content control that contains the inline image. Returns a null object if there isn't a parent content control. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentContentControlOrNullObject: Word.ContentControl; + /** + * + * Gets the table that contains the inline image. Throws if it is not contained in a table. Read-only. * * [Api set: WordApi 1.3] */ parentTable: Word.Table; /** * - * Gets the table cell that contains the inline image. Returns a null object if it is not contained in a table cell. Read-only. + * Gets the table cell that contains the inline image. Throws if it is not contained in a table cell. Read-only. * * [Api set: WordApi 1.3] */ parentTableCell: Word.TableCell; + /** + * + * Gets the table cell that contains the inline image. Returns a null object if it is not contained in a table cell. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentTableCellOrNullObject: Word.TableCell; + /** + * + * Gets the table that contains the inline image. Returns a null object if it is not contained in a table. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentTableOrNullObject: Word.Table; /** * * Gets or sets a string that represents the alternative text associated with the inline image @@ -11588,7 +11732,7 @@ declare module Word { height: number; /** * - * Gets or sets a hyperlink on the image. Use a newline character ('\n') to separate the address part from the optional location part. + * Gets or sets a hyperlink on the image. Use a '#' to separate the address part from the optional location part. * * [Api set: WordApi 1.1] */ @@ -11607,6 +11751,15 @@ declare module Word { * [Api set: WordApi 1.1] */ width: number; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.InlinePictureUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: InlinePicture): void; /** * * Deletes the inline picture from the document. @@ -11623,28 +11776,35 @@ declare module Word { getBase64ImageSrc(): OfficeExtension.ClientResult; /** * - * Gets the next inline image. + * Gets the next inline image. Throws if this inline image is the last one. * * [Api set: WordApi 1.3] */ getNext(): Word.InlinePicture; /** * - * Gets the picture, or the starting or ending point of the picture, as a range. - * - * @param rangeLocation Optional. The range location can be 'Whole', 'Start' or 'End'. + * Gets the next inline image. Returns a null object if this inline image is the last one. * * [Api set: WordApi 1.3] */ + getNextOrNullObject(): Word.InlinePicture; + /** + * + * Gets the picture, or the starting or ending point of the picture, as a range. + * + * [Api set: WordApi 1.3] + * + * @param rangeLocation Optional. The range location can be 'Whole', 'Start' or 'End'. + */ getRange(rangeLocation?: string): Word.Range; /** * * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.2] + * * @param breakType Required. The break type to add. * @param insertLocation Required. The value can be 'Before' or 'After'. - * - * [Api set: WordApi 1.2] */ insertBreak(breakType: string, insertLocation: string): void; /** @@ -11658,69 +11818,69 @@ declare module Word { * * Inserts a document at the specified location. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.2] + * * @param base64File Required. The base64 encoded content of a .docx file. * @param insertLocation Required. The value can be 'Before' or 'After'. - * - * [Api set: WordApi 1.2] */ insertFileFromBase64(base64File: string, insertLocation: string): Word.Range; /** * * Inserts HTML at the specified location. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.2] + * * @param html Required. The HTML to be inserted. * @param insertLocation Required. The value can be 'Before' or 'After'. - * - * [Api set: WordApi 1.2] */ insertHtml(html: string, insertLocation: string): Word.Range; /** * * Inserts an inline picture at the specified location. The insertLocation value can be 'Replace', 'Before' or 'After'. * + * [Api set: WordApi 1.2] + * * @param base64EncodedImage Required. The base64 encoded image to be inserted. * @param insertLocation Required. The value can be 'Replace', 'Before' or 'After'. - * - * [Api set: WordApi 1.2] */ insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: string): Word.InlinePicture; /** * * Inserts OOXML at the specified location. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.2] + * * @param ooxml Required. The OOXML to be inserted. * @param insertLocation Required. The value can be 'Before' or 'After'. - * - * [Api set: WordApi 1.2] */ insertOoxml(ooxml: string, insertLocation: string): Word.Range; /** * * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.2] + * * @param paragraphText Required. The paragraph text to be inserted. * @param insertLocation Required. The value can be 'Before' or 'After'. - * - * [Api set: WordApi 1.2] */ insertParagraph(paragraphText: string, insertLocation: string): Word.Paragraph; /** * * Inserts text at the specified location. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.2] + * * @param text Required. Text to be inserted. * @param insertLocation Required. The value can be 'Before' or 'After'. - * - * [Api set: WordApi 1.2] */ insertText(text: string, insertLocation: string): Word.Range; /** * * Selects the inline picture. This causes Word to scroll to the selection. * - * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. - * * [Api set: WordApi 1.2] + * + * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. */ select(selectionMode?: string): void; /** @@ -11732,7 +11892,7 @@ declare module Word { */ track(): Word.InlinePicture; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.InlinePicture; toJSON(): { @@ -11755,11 +11915,18 @@ declare module Word { items: Array; /** * - * Gets the first inline image in this collection. + * Gets the first inline image in this collection. Throws if this collection is empty. * * [Api set: WordApi 1.3] */ getFirst(): Word.InlinePicture; + /** + * + * Gets the first inline image in this collection. Returns a null object if this collection is empty. + * + * [Api set: WordApi 1.3] + */ + getFirstOrNullObject(): Word.InlinePicture; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -11769,7 +11936,7 @@ declare module Word { */ track(): Word.InlinePictureCollection; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.InlinePictureCollection; toJSON(): {}; @@ -11813,82 +11980,82 @@ declare module Word { * * Gets the paragraphs that occur at the specified level in the list. * - * @param level Required. The level in the list. - * * [Api set: WordApi 1.3] + * + * @param level Required. The level in the list. */ getLevelParagraphs(level: number): Word.ParagraphCollection; /** * * Gets the bullet, number or picture at the specified level as a string. * - * @param level Required. The level in the list. - * * [Api set: WordApi 1.3] + * + * @param level Required. The level in the list. */ getLevelString(level: number): OfficeExtension.ClientResult; /** * * Inserts a paragraph at the specified location. The insertLocation value can be 'Start', 'End', 'Before' or 'After'. * + * [Api set: WordApi 1.3] + * * @param paragraphText Required. The paragraph text to be inserted. * @param insertLocation Required. The value can be 'Start', 'End', 'Before' or 'After'. - * - * [Api set: WordApi 1.3] */ insertParagraph(paragraphText: string, insertLocation: string): Word.Paragraph; /** * * Sets the alignment of the bullet, number or picture at the specified level in the list. * + * [Api set: WordApi 1.3] + * * @param level Required. The level in the list. * @param alignment Required. The level alignment that can be 'left', 'centered' or 'right'. - * - * [Api set: WordApi 1.3] */ setLevelAlignment(level: number, alignment: string): void; /** * * Sets the bullet format at the specified level in the list. If the bullet is 'Custom', the charCode is required. * + * [Api set: WordApi 1.3] + * * @param level Required. The level in the list. * @param listBullet Required. The bullet. * @param charCode Optional. The bullet character's code value. Used only if the bullet is 'Custom'. * @param fontName Optional. The bullet's font name. Used only if the bullet is 'Custom'. - * - * [Api set: WordApi 1.3] */ setLevelBullet(level: number, listBullet: string, charCode?: number, fontName?: string): void; /** * * Sets the two indents of the specified level in the list. * + * [Api set: WordApi 1.3] + * * @param level Required. The level in the list. * @param textIndent Required. The text indent in points. It is the same as paragraph left indent. * @param textIndent Required. The relative indent, in points, of the bullet, number or picture. It is the same as paragraph first line indent. - * - * [Api set: WordApi 1.3] */ setLevelIndents(level: number, textIndent: number, bulletNumberPictureIndent: number): void; /** * * Sets the numbering format at the specified level in the list. * + * [Api set: WordApi 1.3] + * * @param level Required. The level in the list. * @param listNumbering Required. The ordinal format. * @param formatString Optional. The numbering string format defined as an array of strings and/or integers. Each integer is a level of number type that is higher than or equal to this level. For example, an array of ["(", level - 1, ".", level, ")"] can define the format of "(2.c)", where 2 is the parent's item number and c is this level's item number. - * - * [Api set: WordApi 1.3] */ setLevelNumbering(level: number, listNumbering: string, formatString?: Array): void; /** * * Sets the starting number at the specified level in the list. Default value is 1. * + * [Api set: WordApi 1.3] + * * @param level Required. The level in the list. * @param startingNumber Required. The number to start with. - * - * [Api set: WordApi 1.3] */ setLevelStartingNumber(level: number, startingNumber: number): void; /** @@ -11900,7 +12067,7 @@ declare module Word { */ track(): Word.List; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.List; toJSON(): { @@ -11920,28 +12087,44 @@ declare module Word { items: Array; /** * - * Gets a list by its identifier. - * - * @param id Required. A list identifier. + * Gets a list by its identifier. Throws if there isn't a list with the identifier in this collection. * * [Api set: WordApi 1.3] + * + * @param id Required. A list identifier. */ getById(id: number): Word.List; /** * - * Gets the first list in this collection. + * Gets a list by its identifier. Returns a null object if there isn't a list with the identifier in this collection. + * + * [Api set: WordApi 1.3] + * + * @param id Required. A list identifier. + */ + getByIdOrNullObject(id: number): Word.List; + /** + * + * Gets the first list in this collection. Throws if this collection is empty. * * [Api set: WordApi 1.3] */ getFirst(): Word.List; /** * - * Gets a list object by its index in the collection. - * - * @param index A number that identifies the index location of a list object. + * Gets the first list in this collection. Returns a null object if this collection is empty. * * [Api set: WordApi 1.3] */ + getFirstOrNullObject(): Word.List; + /** + * + * Gets a list object by its index in the collection. + * + * [Api set: WordApi 1.3] + * + * @param index A number that identifies the index location of a list object. + */ getItem(index: number): Word.List; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. @@ -11952,7 +12135,7 @@ declare module Word { */ track(): Word.ListCollection; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.ListCollection; toJSON(): {}; @@ -11985,22 +12168,40 @@ declare module Word { * [Api set: WordApi 1.3] */ siblingIndex: number; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ListItemUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ListItem): void; /** * - * Gets the list item parent, or the closest ancestor if the parent does not exist. - * - * @param parentOnly Optional. Specified only the list item's parent will be returned. The default is false that specifies to get the lowest ancestor. + * Gets the list item parent, or the closest ancestor if the parent does not exist. Throws if the list item has no ancester. * * [Api set: WordApi 1.3] + * + * @param parentOnly Optional. Specified only the list item's parent will be returned. The default is false that specifies to get the lowest ancestor. */ getAncestor(parentOnly?: boolean): Word.Paragraph; /** * - * Gets all descendant list items of the list item. - * - * @param directChildrenOnly Optional. Specified only the list item's direct children will be returned. The default is false that indicates to get all descendant items. + * Gets the list item parent, or the closest ancestor if the parent does not exist. Returns a null object if the list item has no ancester. * * [Api set: WordApi 1.3] + * + * @param parentOnly Optional. Specified only the list item's parent will be returned. The default is false that specifies to get the lowest ancestor. + */ + getAncestorOrNullObject(parentOnly?: boolean): Word.Paragraph; + /** + * + * Gets all descendant list items of the list item. + * + * [Api set: WordApi 1.3] + * + * @param directChildrenOnly Optional. Specified only the list item's direct children will be returned. The default is false that indicates to get all descendant items. */ getDescendants(directChildrenOnly?: boolean): Word.ParagraphCollection; /** @@ -12012,7 +12213,7 @@ declare module Word { */ track(): Word.ListItem; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.ListItem; toJSON(): { @@ -12051,18 +12252,32 @@ declare module Word { inlinePictures: Word.InlinePictureCollection; /** * - * Gets the List to which this paragraph belongs. Returns a null object if the paragraph is not in a list. Read-only. + * Gets the List to which this paragraph belongs. Throws if the paragraph is not in a list. Read-only. * * [Api set: WordApi 1.3] */ list: Word.List; /** * - * Gets the ListItem for the paragraph. Returns a null object if the paragraph is not part of a list. Read-only. + * Gets the ListItem for the paragraph. Throws if the paragraph is not part of a list. Read-only. * * [Api set: WordApi 1.3] */ listItem: Word.ListItem; + /** + * + * Gets the ListItem for the paragraph. Returns a null object if the paragraph is not part of a list. Read-only. + * + * [Api set: WordApi 1.3] + */ + listItemOrNullObject: Word.ListItem; + /** + * + * Gets the List to which this paragraph belongs. Returns a null object if the paragraph is not in a list. Read-only. + * + * [Api set: WordApi 1.3] + */ + listOrNullObject: Word.List; /** * * Gets the parent body of the paragraph. Read-only. @@ -12072,25 +12287,46 @@ declare module Word { parentBody: Word.Body; /** * - * Gets the content control that contains the paragraph. Returns a null object if there isn't a parent content control. Read-only. + * Gets the content control that contains the paragraph. Throws if there isn't a parent content control. Read-only. * * [Api set: WordApi 1.1] */ parentContentControl: Word.ContentControl; /** * - * Gets the table that contains the paragraph. Returns a null object if it is not contained in a table. Read-only. + * Gets the content control that contains the paragraph. Returns a null object if there isn't a parent content control. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentContentControlOrNullObject: Word.ContentControl; + /** + * + * Gets the table that contains the paragraph. Throws if it is not contained in a table. Read-only. * * [Api set: WordApi 1.3] */ parentTable: Word.Table; /** * - * Gets the table cell that contains the paragraph. Returns a null object if it is not contained in a table cell. Read-only. + * Gets the table cell that contains the paragraph. Throws if it is not contained in a table cell. Read-only. * * [Api set: WordApi 1.3] */ parentTableCell: Word.TableCell; + /** + * + * Gets the table cell that contains the paragraph. Returns a null object if it is not contained in a table cell. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentTableCellOrNullObject: Word.TableCell; + /** + * + * Gets the table that contains the paragraph. Returns a null object if it is not contained in a table. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentTableOrNullObject: Word.Table; /** * * Gets or sets the alignment for a paragraph. The value can be 'left', 'centered', 'right', or 'justified'. @@ -12203,14 +12439,23 @@ declare module Word { * [Api set: WordApi 1.1] */ text: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ParagraphUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Paragraph): void; /** * * Lets the paragraph join an existing list at the specified level. Fails if the paragraph cannot join the list or if the paragraph is already a list item. * + * [Api set: WordApi 1.3] + * * @param listId Required. The ID of an existing list. * @param level Required. The level in the list. - * - * [Api set: WordApi 1.3] */ attachToList(listId: number, level: number): Word.List; /** @@ -12243,11 +12488,18 @@ declare module Word { getHtml(): OfficeExtension.ClientResult; /** * - * Gets the next paragraph. + * Gets the next paragraph. Throws if the paragraph is the last one. * * [Api set: WordApi 1.3] */ getNext(): Word.Paragraph; + /** + * + * Gets the next paragraph. Returns a null object if the paragraph is the last one. + * + * [Api set: WordApi 1.3] + */ + getNextOrNullObject(): Word.Paragraph; /** * * Gets the Office Open XML (OOXML) representation of the paragraph object. @@ -12257,38 +12509,45 @@ declare module Word { getOoxml(): OfficeExtension.ClientResult; /** * - * Gets the previous paragraph. + * Gets the previous paragraph. Throws if the paragraph is the first one. * * [Api set: WordApi 1.3] */ getPrevious(): Word.Paragraph; /** * - * Gets the whole paragraph, or the starting or ending point of the paragraph, as a range. - * - * @param rangeLocation Optional. The range location can be 'Whole', 'Start', 'End', 'After' or 'Content'. + * Gets the previous paragraph. Returns a null object if the paragraph is the first one. * * [Api set: WordApi 1.3] */ + getPreviousOrNullObject(): Word.Paragraph; + /** + * + * Gets the whole paragraph, or the starting or ending point of the paragraph, as a range. + * + * [Api set: WordApi 1.3] + * + * @param rangeLocation Optional. The range location can be 'Whole', 'Start', 'End', 'After' or 'Content'. + */ getRange(rangeLocation?: string): Word.Range; /** * * Gets the text ranges in the paragraph by using punctuation marks and/or other ending marks. * + * [Api set: WordApi 1.3] + * * @param endingMarks Required. The punctuation marks and/or other ending marks as an array of strings. * @param trimSpacing Optional. Indicates whether to trim spacing characters (spaces, tabs, column breaks and paragraph end marks) from the start and end of the ranges returned in the range collection. Default is false which indicates that spacing characters at the start and end of the ranges are included in the range collection. - * - * [Api set: WordApi 1.3] */ getTextRanges(endingMarks: Array, trimSpacing?: boolean): Word.RangeCollection; /** * * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.1] + * * @param breakType Required. The break type to add to the document. * @param insertLocation Required. The value can be 'Before' or 'After'. - * - * [Api set: WordApi 1.1] */ insertBreak(breakType: string, insertLocation: string): void; /** @@ -12302,82 +12561,82 @@ declare module Word { * * Inserts a document into the paragraph at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param base64File Required. The base64 encoded content of a .docx file. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. - * - * [Api set: WordApi 1.1] */ insertFileFromBase64(base64File: string, insertLocation: string): Word.Range; /** * * Inserts HTML into the paragraph at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param html Required. The HTML to be inserted in the paragraph. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. - * - * [Api set: WordApi 1.1] */ insertHtml(html: string, insertLocation: string): Word.Range; /** * * Inserts a picture into the paragraph at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param base64EncodedImage Required. The base64 encoded image to be inserted. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. - * - * [Api set: WordApi 1.1] */ insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: string): Word.InlinePicture; /** * * Inserts OOXML into the paragraph at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param ooxml Required. The OOXML to be inserted in the paragraph. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. - * - * [Api set: WordApi 1.1] */ insertOoxml(ooxml: string, insertLocation: string): Word.Range; /** * * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.1] + * * @param paragraphText Required. The paragraph text to be inserted. * @param insertLocation Required. The value can be 'Before' or 'After'. - * - * [Api set: WordApi 1.1] */ insertParagraph(paragraphText: string, insertLocation: string): Word.Paragraph; /** * * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.3] + * * @param rowCount Required. The number of rows in the table. * @param columnCount Required. The number of columns in the table. * @param insertLocation Required. The value can be 'Before' or 'After'. * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. - * - * [Api set: WordApi 1.3] */ insertTable(rowCount: number, columnCount: number, insertLocation: string, values?: Array>): Word.Table; /** * * Inserts text into the paragraph at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param text Required. Text to be inserted. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. - * - * [Api set: WordApi 1.1] */ insertText(text: string, insertLocation: string): Word.Range; /** * * Performs a search with the specified searchOptions on the scope of the paragraph object. The search results are a collection of range objects. * + * [Api set: WordApi 1.1] + * * @param searchText Required. The search text. * @param searchOptions Optional. Options for the search. - * - * [Api set: WordApi 1.1] */ search(searchText: string, searchOptions?: Word.SearchOptions | { ignorePunct?: boolean; @@ -12392,20 +12651,20 @@ declare module Word { * * Selects and navigates the Word UI to the paragraph. * - * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. - * * [Api set: WordApi 1.1] + * + * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. */ select(selectionMode?: string): void; /** * * Splits the paragraph into child ranges by using delimiters. * + * [Api set: WordApi 1.3] + * * @param delimiters Required. The delimiters as an array of strings. * @param trimDelimiters Optional. Indicates whether to trim delimiters from the ranges in the range collection. Default is false which indicates that the delimiters are included in the ranges returned in the range collection. * @param trimSpacing Optional. Indicates whether to trim spacing characters (spaces, tabs, column breaks and paragraph end marks) from the start and end of the ranges returned in the range collection. Default is false which indicates that spacing characters at the start and end of the ranges are included in the range collection. - * - * [Api set: WordApi 1.3] */ split(delimiters: Array, trimDelimiters?: boolean, trimSpacing?: boolean): Word.RangeCollection; /** @@ -12424,7 +12683,7 @@ declare module Word { */ track(): Word.Paragraph; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.Paragraph; toJSON(): { @@ -12438,6 +12697,7 @@ declare module Word { "lineUnitAfter": number; "lineUnitBefore": number; "listItem": ListItem; + "listItemOrNullObject": ListItem; "outlineLevel": number; "rightIndent": number; "spaceAfter": number; @@ -12459,18 +12719,32 @@ declare module Word { items: Array; /** * - * Gets the first paragraph in this collection. + * Gets the first paragraph in this collection. Throws if the collection is empty. * * [Api set: WordApi 1.3] */ getFirst(): Word.Paragraph; /** * - * Gets the last paragraph in this collection. + * Gets the first paragraph in this collection. Returns a null object if the collection is empty. + * + * [Api set: WordApi 1.3] + */ + getFirstOrNullObject(): Word.Paragraph; + /** + * + * Gets the last paragraph in this collection. Throws if the collection is empty. * * [Api set: WordApi 1.3] */ getLast(): Word.Paragraph; + /** + * + * Gets the last paragraph in this collection. Returns a null object if the collection is empty. + * + * [Api set: WordApi 1.3] + */ + getLastOrNullObject(): Word.Paragraph; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -12480,7 +12754,7 @@ declare module Word { */ track(): Word.ParagraphCollection; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.ParagraphCollection; toJSON(): {}; @@ -12536,25 +12810,46 @@ declare module Word { parentBody: Word.Body; /** * - * Gets the content control that contains the range. Returns a null object if there isn't a parent content control. Read-only. + * Gets the content control that contains the range. Throws if there isn't a parent content control. Read-only. * * [Api set: WordApi 1.1] */ parentContentControl: Word.ContentControl; /** * - * Gets the table that contains the range. Returns null if it is not contained in a table. Read-only. + * Gets the content control that contains the range. Returns a null object if there isn't a parent content control. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentContentControlOrNullObject: Word.ContentControl; + /** + * + * Gets the table that contains the range. Throws if it is not contained in a table. Read-only. * * [Api set: WordApi 1.3] */ parentTable: Word.Table; /** * - * Gets the table cell that contains the range. Returns a null object if it is not contained in a table cell. Read-only. + * Gets the table cell that contains the range. Throws if it is not contained in a table cell. Read-only. * * [Api set: WordApi 1.3] */ parentTableCell: Word.TableCell; + /** + * + * Gets the table cell that contains the range. Returns a null object if it is not contained in a table cell. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentTableCellOrNullObject: Word.TableCell; + /** + * + * Gets the table that contains the range. Returns a null object if it is not contained in a table. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentTableOrNullObject: Word.Table; /** * * Gets the collection of table objects in the range. Read-only. @@ -12564,7 +12859,7 @@ declare module Word { tables: Word.TableCollection; /** * - * Gets the first hyperlink in the range, or sets a hyperlink on the range. All hyperlinks in the range are deleted when you set a new hyperlink on the range. Use a newline character ('\n') to separate the address part from the optional location part. + * Gets the first hyperlink in the range, or sets a hyperlink on the range. All hyperlinks in the range are deleted when you set a new hyperlink on the range. Use a '#' to separate the address part from the optional location part. * * [Api set: WordApi 1.3] */ @@ -12597,6 +12892,15 @@ declare module Word { * [Api set: WordApi 1.1] */ text: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.RangeUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Range): void; /** * * Clears the contents of the range object. The user can perform the undo operation on the cleared content. @@ -12608,9 +12912,9 @@ declare module Word { * * Compares this range's location with another range's location. * - * @param range Required. The range to compare with this range. - * * [Api set: WordApi 1.3] + * + * @param range Required. The range to compare with this range. */ compareLocationWith(range: Word.Range): OfficeExtension.ClientResult; /** @@ -12622,13 +12926,22 @@ declare module Word { delete(): void; /** * - * Returns a new range that extends from this range in either direction to cover another range. This range is not changed. - * - * @param range Required. Another range. + * Returns a new range that extends from this range in either direction to cover another range. This range is not changed. Throws if the two ranges do not have a union. * * [Api set: WordApi 1.3] + * + * @param range Required. Another range. */ expandTo(range: Word.Range): Word.Range; + /** + * + * Returns a new range that extends from this range in either direction to cover another range. This range is not changed. Returns a null object if the two ranges do not have a union. + * + * [Api set: WordApi 1.3] + * + * @param range Required. Another range. + */ + expandToOrNullObject(range: Word.Range): Word.Range; /** * * Gets the HTML representation of the range object. @@ -12645,14 +12958,24 @@ declare module Word { getHyperlinkRanges(): Word.RangeCollection; /** * - * Gets the next text range by using punctuation marks and/or other ending marks. + * Gets the next text range by using punctuation marks and/or other ending marks. Throws if this text range is the last one. + * + * [Api set: WordApi 1.3] * * @param endingMarks Required. The punctuation marks and/or other ending marks as an array of strings. * @param trimSpacing Optional. Indicates whether to trim spacing characters (spaces, tabs, column breaks and paragraph end marks) from the start and end of the returned range. Default is false which indicates that spacing characters at the start and end of the range are included. - * - * [Api set: WordApi 1.3] */ getNextTextRange(endingMarks: Array, trimSpacing?: boolean): Word.Range; + /** + * + * Gets the next text range by using punctuation marks and/or other ending marks. Returns a null object if this text range is the last one. + * + * [Api set: WordApi 1.3] + * + * @param endingMarks Required. The punctuation marks and/or other ending marks as an array of strings. + * @param trimSpacing Optional. Indicates whether to trim spacing characters (spaces, tabs, column breaks and paragraph end marks) from the start and end of the returned range. Default is false which indicates that spacing characters at the start and end of the range are included. + */ + getNextTextRangeOrNullObject(endingMarks: Array, trimSpacing?: boolean): Word.Range; /** * * Gets the OOXML representation of the range object. @@ -12664,29 +12987,29 @@ declare module Word { * * Clones the range, or gets the starting or ending point of the range as a new range. * - * @param rangeLocation Optional. The range location can be 'Whole', 'Start', 'End', 'After' or 'Content'. - * * [Api set: WordApi 1.3] + * + * @param rangeLocation Optional. The range location can be 'Whole', 'Start', 'End', 'After' or 'Content'. */ getRange(rangeLocation?: string): Word.Range; /** * * Gets the text child ranges in the range by using punctuation marks and/or other ending marks. * + * [Api set: WordApi 1.3] + * * @param endingMarks Required. The punctuation marks and/or other ending marks as an array of strings. * @param trimSpacing Optional. Indicates whether to trim spacing characters (spaces, tabs, column breaks and paragraph end marks) from the start and end of the ranges returned in the range collection. Default is false which indicates that spacing characters at the start and end of the ranges are included in the range collection. - * - * [Api set: WordApi 1.3] */ getTextRanges(endingMarks: Array, trimSpacing?: boolean): Word.RangeCollection; /** * * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.1] + * * @param breakType Required. The break type to add. * @param insertLocation Required. The value can be 'Before' or 'After'. - * - * [Api set: WordApi 1.1] */ insertBreak(breakType: string, insertLocation: string): void; /** @@ -12700,91 +13023,100 @@ declare module Word { * * Inserts a document at the specified location. The insertLocation value can be 'Replace', 'Start', 'End', 'Before' or 'After'. * + * [Api set: WordApi 1.1] + * * @param base64File Required. The base64 encoded content of a .docx file. * @param insertLocation Required. The value can be 'Replace', 'Start', 'End', 'Before' or 'After'. - * - * [Api set: WordApi 1.1] */ insertFileFromBase64(base64File: string, insertLocation: string): Word.Range; /** * * Inserts HTML at the specified location. The insertLocation value can be 'Replace', 'Start', 'End', 'Before' or 'After'. * + * [Api set: WordApi 1.1] + * * @param html Required. The HTML to be inserted. * @param insertLocation Required. The value can be 'Replace', 'Start', 'End', 'Before' or 'After'. - * - * [Api set: WordApi 1.1] */ insertHtml(html: string, insertLocation: string): Word.Range; /** * * Inserts a picture at the specified location. The insertLocation value can be 'Replace', 'Start', 'End', 'Before' or 'After'. * + * [Api set: WordApi 1.2] + * * @param base64EncodedImage Required. The base64 encoded image to be inserted. * @param insertLocation Required. The value can be 'Replace', 'Start', 'End', 'Before' or 'After'. - * - * [Api set: WordApi 1.2] */ insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: string): Word.InlinePicture; /** * * Inserts OOXML at the specified location. The insertLocation value can be 'Replace', 'Start', 'End', 'Before' or 'After'. * + * [Api set: WordApi 1.1] + * * @param ooxml Required. The OOXML to be inserted. * @param insertLocation Required. The value can be 'Replace', 'Start', 'End', 'Before' or 'After'. - * - * [Api set: WordApi 1.1] */ insertOoxml(ooxml: string, insertLocation: string): Word.Range; /** * * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.1] + * * @param paragraphText Required. The paragraph text to be inserted. * @param insertLocation Required. The value can be 'Before' or 'After'. - * - * [Api set: WordApi 1.1] */ insertParagraph(paragraphText: string, insertLocation: string): Word.Paragraph; /** * * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.3] + * * @param rowCount Required. The number of rows in the table. * @param columnCount Required. The number of columns in the table. * @param insertLocation Required. The value can be 'Before' or 'After'. * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. - * - * [Api set: WordApi 1.3] */ insertTable(rowCount: number, columnCount: number, insertLocation: string, values?: Array>): Word.Table; /** * * Inserts text at the specified location. The insertLocation value can be 'Replace', 'Start', 'End', 'Before' or 'After'. * + * [Api set: WordApi 1.1] + * * @param text Required. Text to be inserted. * @param insertLocation Required. The value can be 'Replace', 'Start', 'End', 'Before' or 'After'. - * - * [Api set: WordApi 1.1] */ insertText(text: string, insertLocation: string): Word.Range; /** * - * Returns a new range as the intersection of this range with another range. This range is not changed. - * - * @param range Required. Another range. + * Returns a new range as the intersection of this range with another range. This range is not changed. Throws if the two ranges are not overlapped or adjacent. * * [Api set: WordApi 1.3] + * + * @param range Required. Another range. */ intersectWith(range: Word.Range): Word.Range; + /** + * + * Returns a new range as the intersection of this range with another range. This range is not changed. Returns a null object if the two ranges are not overlapped or adjacent. + * + * [Api set: WordApi 1.3] + * + * @param range Required. Another range. + */ + intersectWithOrNullObject(range: Word.Range): Word.Range; /** * * Performs a search with the specified searchOptions on the scope of the range object. The search results are a collection of range objects. * + * [Api set: WordApi 1.1] + * * @param searchText Required. The search text. * @param searchOptions Optional. Options for the search. - * - * [Api set: WordApi 1.1] */ search(searchText: string, searchOptions?: Word.SearchOptions | { ignorePunct?: boolean; @@ -12799,21 +13131,21 @@ declare module Word { * * Selects and navigates the Word UI to the range. * - * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. - * * [Api set: WordApi 1.1] + * + * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. */ select(selectionMode?: string): void; /** * * Splits the range into child ranges by using delimiters. * + * [Api set: WordApi 1.3] + * * @param delimiters Required. The delimiters as an array of strings. * @param multiParagraphs Optional. Indicates whether a returned child range can cover multiple paragraphs. Default is false which indicates that the paragraph boundaries are also used as delimiters. * @param trimDelimiters Optional. Indicates whether to trim delimiters from the ranges in the range collection. Default is false which indicates that the delimiters are included in the ranges returned in the range collection. * @param trimSpacing Optional. Indicates whether to trim spacing characters (spaces, tabs, column breaks and paragraph end marks) from the start and end of the ranges returned in the range collection. Default is false which indicates that spacing characters at the start and end of the ranges are included in the range collection. - * - * [Api set: WordApi 1.3] */ split(delimiters: Array, multiParagraphs?: boolean, trimDelimiters?: boolean, trimSpacing?: boolean): Word.RangeCollection; /** @@ -12825,7 +13157,7 @@ declare module Word { */ track(): Word.Range; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.Range; toJSON(): { @@ -12841,18 +13173,25 @@ declare module Word { * * Contains a collection of [range](range.md) objects. * - * [Api set: WordApi 1.3] + * [Api set: WordApi 1.1] */ class RangeCollection extends OfficeExtension.ClientObject { /** Gets the loaded child items in this collection. */ items: Array; /** * - * Gets the first range in this collection. + * Gets the first range in this collection. Throws if this collection is empty. * * [Api set: WordApi 1.3] */ getFirst(): Word.Range; + /** + * + * Gets the first range in this collection. Returns a null object if this collection is empty. + * + * [Api set: WordApi 1.3] + */ + getFirstOrNullObject(): Word.Range; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -12862,7 +13201,7 @@ declare module Word { */ track(): Word.RangeCollection; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.RangeCollection; toJSON(): {}; @@ -12924,6 +13263,15 @@ declare module Word { * [Api set: WordApi 1.1] */ matchWildcards: boolean; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.SearchOptionsUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: SearchOptions): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -12956,45 +13304,47 @@ declare module Word { * [Api set: WordApi 1.1] */ body: Word.Body; - /** - * - * Gets or sets a value that indicates whether even-numbered pages have a different header and footer from odd-numbered pages in the section. - * - * [Api set: WordApi 1.3] - */ - headerFooterEvenPageDifferent: boolean; - /** - * - * Gets or sets a value that indicates whether the first page has a different header and footer from the other pages in the section. - * - * [Api set: WordApi 1.3] - */ - headerFooterFirstPageDifferent: boolean; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.SectionUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Section): void; /** * * Gets one of the section's footers. * - * @param type Required. The type of footer to return. This value can be: 'primary', 'firstPage' or 'evenPages'. - * * [Api set: WordApi 1.1] + * + * @param type Required. The type of footer to return. This value can be: 'primary', 'firstPage' or 'evenPages'. */ getFooter(type: string): Word.Body; /** * * Gets one of the section's headers. * - * @param type Required. The type of header to return. This value can be: 'primary', 'firstPage' or 'evenPages'. - * * [Api set: WordApi 1.1] + * + * @param type Required. The type of header to return. This value can be: 'primary', 'firstPage' or 'evenPages'. */ getHeader(type: string): Word.Body; /** * - * Gets the next section. + * Gets the next section. Throws if this section is the last one. * * [Api set: WordApi 1.3] */ getNext(): Word.Section; + /** + * + * Gets the next section. Returns a null object if this section is the last one. + * + * [Api set: WordApi 1.3] + */ + getNextOrNullObject(): Word.Section; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -13004,13 +13354,11 @@ declare module Word { */ track(): Word.Section; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.Section; toJSON(): { "body": Body; - "headerFooterEvenPageDifferent": boolean; - "headerFooterFirstPageDifferent": boolean; }; } /** @@ -13024,11 +13372,18 @@ declare module Word { items: Array; /** * - * Gets the first section in this collection. + * Gets the first section in this collection. Throws if this collection is empty. * * [Api set: WordApi 1.3] */ getFirst(): Word.Section; + /** + * + * Gets the first section in this collection. Returns a null object if this collection is empty. + * + * [Api set: WordApi 1.3] + */ + getFirstOrNullObject(): Word.Section; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -13038,7 +13393,7 @@ declare module Word { */ track(): Word.SectionCollection; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.SectionCollection; toJSON(): {}; @@ -13057,20 +13412,6 @@ declare module Word { * [Api set: WordApi 1.3] */ font: Word.Font; - /** - * - * Gets the paragraph after the table. Read-only. - * - * [Api set: WordApi 1.3] - */ - paragraphAfter: Word.Paragraph; - /** - * - * Gets the paragraph before the table. Read-only. - * - * [Api set: WordApi 1.3] - */ - paragraphBefore: Word.Paragraph; /** * * Gets the parent body of the table. Read-only. @@ -13080,25 +13421,46 @@ declare module Word { parentBody: Word.Body; /** * - * Gets the content control that contains the table. Read-only. + * Gets the content control that contains the table. Throws if there isn't a parent content control. Read-only. * * [Api set: WordApi 1.3] */ parentContentControl: Word.ContentControl; /** * - * Gets the table that contains this table. Returns a null object if it is not contained in a table. Read-only. + * Gets the content control that contains the table. Returns a null object if there isn't a parent content control. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentContentControlOrNullObject: Word.ContentControl; + /** + * + * Gets the table that contains this table. Throws if it is not contained in a table. Read-only. * * [Api set: WordApi 1.3] */ parentTable: Word.Table; /** * - * Gets the table cell that contains this table. Returns a null object if it is not contained in a table cell. Read-only. + * Gets the table cell that contains this table. Throws if it is not contained in a table cell. Read-only. * * [Api set: WordApi 1.3] */ parentTableCell: Word.TableCell; + /** + * + * Gets the table cell that contains this table. Returns a null object if it is not contained in a table cell. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentTableCellOrNullObject: Word.TableCell; + /** + * + * Gets the table that contains this table. Returns a null object if it is not contained in a table. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentTableOrNullObject: Word.Table; /** * * Gets all of the table rows. Read-only. @@ -13127,13 +13489,6 @@ declare module Word { * [Api set: WordApi 1.3] */ headerRowCount: number; - /** - * - * Gets the height of the table in points. Read-only. - * - * [Api set: WordApi 1.3] - */ - height: number; /** * * Gets and sets the horizontal alignment of every cell in the table. The value can be 'left', 'centered', 'right', or 'justified'. @@ -13239,35 +13594,37 @@ declare module Word { * [Api set: WordApi 1.3] */ width: number; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.TableUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Table): void; /** * * Adds columns to the start or end of the table, using the first or last existing column as a template. This is applicable to uniform tables. The string values, if specified, are set in the newly inserted rows. * + * [Api set: WordApi 1.3] + * * @param insertLocation Required. It can be 'Start' or 'End', corresponding to the appropriate side of the table. * @param columnCount Required. Number of columns to add. * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. - * - * [Api set: WordApi 1.3] */ addColumns(insertLocation: string, columnCount: number, values?: Array>): void; /** * * Adds rows to the start or end of the table, using the first or last existing row as a template. The string values, if specified, are set in the newly inserted rows. * + * [Api set: WordApi 1.3] + * * @param insertLocation Required. It can be 'Start' or 'End'. * @param rowCount Required. Number of rows to add. * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. - * - * [Api set: WordApi 1.3] */ addRows(insertLocation: string, rowCount: number, values?: Array>): Word.TableRowCollection; - /** - * - * Autofits the table columns to the width of their contents. - * - * [Api set: WordApi 1.3] - */ - autoFitContents(): void; /** * * Autofits the table columns to the width of the window. @@ -13293,79 +13650,117 @@ declare module Word { * * Deletes specific columns. This is applicable to uniform tables. * + * [Api set: WordApi 1.3] + * * @param columnIndex Required. The first column to delete. * @param columnCount Optional. The number of columns to delete. Default 1. - * - * [Api set: WordApi 1.3] */ deleteColumns(columnIndex: number, columnCount?: number): void; /** * * Deletes specific rows. * + * [Api set: WordApi 1.3] + * * @param rowIndex Required. The first row to delete. * @param rowCount Optional. The number of rows to delete. Default 1. - * - * [Api set: WordApi 1.3] */ deleteRows(rowIndex: number, rowCount?: number): void; /** * - * Distributes the column widths evenly. + * Distributes the column widths evenly. This is applicable to uniform tables. * * [Api set: WordApi 1.3] */ distributeColumns(): void; - /** - * - * Distributes the row heights evenly. - * - * [Api set: WordApi 1.3] - */ - distributeRows(): void; /** * * Gets the border style for the specified border. * - * @param borderLocation Required. The border location. - * * [Api set: WordApi 1.3] + * + * @param borderLocation Required. The border location. */ getBorder(borderLocation: string): Word.TableBorder; /** * - * Gets the table cell at a specified row and column. + * Gets the table cell at a specified row and column. Throws if the specified table cell does not exist. + * + * [Api set: WordApi 1.3] * * @param rowIndex Required. The index of the row. * @param cellIndex Required. The index of the cell in the row. - * - * [Api set: WordApi 1.3] */ getCell(rowIndex: number, cellIndex: number): Word.TableCell; /** * - * Gets cell padding in points. - * - * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. + * Gets the table cell at a specified row and column. Returns a null object if the specified table cell does not exist. * * [Api set: WordApi 1.3] + * + * @param rowIndex Required. The index of the row. + * @param cellIndex Required. The index of the cell in the row. + */ + getCellOrNullObject(rowIndex: number, cellIndex: number): Word.TableCell; + /** + * + * Gets cell padding in points. + * + * [Api set: WordApi 1.3] + * + * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. */ getCellPadding(cellPaddingLocation: string): OfficeExtension.ClientResult; /** * - * Gets the next table. + * Gets the next table. Throws if this table is the last one. * * [Api set: WordApi 1.3] */ getNext(): Word.Table; /** * - * Gets the range that contains this table, or the range at the start or end of the table. - * - * @param rangeLocation Optional. The range location can be 'Whole', 'Start', 'End' or 'After'. + * Gets the next table. Returns a null object if this table is the last one. * * [Api set: WordApi 1.3] */ + getNextOrNullObject(): Word.Table; + /** + * + * Gets the paragraph after the table. Throws if there isn't a paragraph after the table. + * + * [Api set: WordApi 1.3] + */ + getParagraphAfter(): Word.Paragraph; + /** + * + * Gets the paragraph after the table. Returns a null object if there isn't a paragraph after the table. + * + * [Api set: WordApi 1.3] + */ + getParagraphAfterOrNullObject(): Word.Paragraph; + /** + * + * Gets the paragraph before the table. Throws if there isn't a paragraph before the table. + * + * [Api set: WordApi 1.3] + */ + getParagraphBefore(): Word.Paragraph; + /** + * + * Gets the paragraph before the table. Returns a null object if there isn't a paragraph before the table. + * + * [Api set: WordApi 1.3] + */ + getParagraphBeforeOrNullObject(): Word.Paragraph; + /** + * + * Gets the range that contains this table, or the range at the start or end of the table. + * + * [Api set: WordApi 1.3] + * + * @param rangeLocation Optional. The range location can be 'Whole', 'Start', 'End' or 'After'. + */ getRange(rangeLocation?: string): Word.Range; /** * @@ -13378,32 +13773,32 @@ declare module Word { * * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.3] + * * @param paragraphText Required. The paragraph text to be inserted. * @param insertLocation Required. The value can be 'Before' or 'After'. - * - * [Api set: WordApi 1.3] */ insertParagraph(paragraphText: string, insertLocation: string): Word.Paragraph; /** * * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.3] + * * @param rowCount Required. The number of rows in the table. * @param columnCount Required. The number of columns in the table. * @param insertLocation Required. The value can be 'Before' or 'After'. * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. - * - * [Api set: WordApi 1.3] */ insertTable(rowCount: number, columnCount: number, insertLocation: string, values?: Array>): Word.Table; /** * * Performs a search with the specified searchOptions on the scope of the table object. The search results are a collection of range objects. * + * [Api set: WordApi 1.3] + * * @param searchText Required. The search text. * @param searchOptions Optional. Options for the search. - * - * [Api set: WordApi 1.3] */ search(searchText: string, searchOptions?: Word.SearchOptions | { ignorePunct?: boolean; @@ -13418,18 +13813,19 @@ declare module Word { * * Selects the table, or the position at the start or end of the table, and navigates the Word UI to it. * - * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. - * * [Api set: WordApi 1.3] + * + * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. */ select(selectionMode?: string): void; /** * * Sets cell padding in points. * - * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. - * * [Api set: WordApi 1.3] + * + * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. + * @param cellPadding Required. The cell padding. */ setCellPadding(cellPaddingLocation: string, cellPadding: number): void; /** @@ -13441,14 +13837,13 @@ declare module Word { */ track(): Word.Table; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.Table; toJSON(): { "alignment": string; "font": Font; "headerRowCount": number; - "height": number; "horizontalAlignment": string; "isUniform": boolean; "nestingLevel": number; @@ -13477,11 +13872,18 @@ declare module Word { items: Array; /** * - * Gets the first table in this collection. + * Gets the first table in this collection. Throws if this collection is empty. * * [Api set: WordApi 1.3] */ getFirst(): Word.Table; + /** + * + * Gets the first table in this collection. Returns a null object if this collection is empty. + * + * [Api set: WordApi 1.3] + */ + getFirstOrNullObject(): Word.Table; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -13491,7 +13893,7 @@ declare module Word { */ track(): Word.TableCollection; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.TableCollection; toJSON(): {}; @@ -13568,11 +13970,11 @@ declare module Word { shadingColor: string; /** * - * Gets and sets the text values in the row, as a 1D Javascript array. + * Gets and sets the text values in the row, as a 2D Javascript array. * * [Api set: WordApi 1.3] */ - values: Array; + values: Array>; /** * * Gets and sets the vertical alignment of the cells in the row. The value can be 'top', 'center' or 'bottom'. @@ -13580,6 +13982,15 @@ declare module Word { * [Api set: WordApi 1.3] */ verticalAlignment: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.TableRowUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: TableRow): void; /** * * Clears the contents of the row. @@ -13598,46 +14009,53 @@ declare module Word { * * Gets the border style of the cells in the row. * - * @param borderLocation Required. The border location. - * * [Api set: WordApi 1.3] + * + * @param borderLocation Required. The border location. */ getBorder(borderLocation: string): Word.TableBorder; /** * * Gets cell padding in points. * - * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. - * * [Api set: WordApi 1.3] + * + * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. */ getCellPadding(cellPaddingLocation: string): OfficeExtension.ClientResult; /** * - * Gets the next row. + * Gets the next row. Throws if this row is the last one. * * [Api set: WordApi 1.3] */ getNext(): Word.TableRow; + /** + * + * Gets the next row. Returns a null object if this row is the last one. + * + * [Api set: WordApi 1.3] + */ + getNextOrNullObject(): Word.TableRow; /** * * Inserts rows using this row as a template. If values are specified, inserts the values into the new rows. * + * [Api set: WordApi 1.3] + * * @param insertLocation Required. Where the new rows should be inserted, relative to the current row. It can be 'Before' or 'After'. * @param rowCount Required. Number of rows to add * @param values Optional. Strings to insert in the new rows, specified as a 2D array. The number of cells in each row must not exceed the number of cells in the existing row. - * - * [Api set: WordApi 1.3] */ insertRows(insertLocation: string, rowCount: number, values?: Array>): Word.TableRowCollection; /** * * Performs a search with the specified searchOptions on the scope of the row. The search results are a collection of range objects. * + * [Api set: WordApi 1.3] + * * @param searchText Required. The search text. * @param searchOptions Optional. Options for the search. - * - * [Api set: WordApi 1.3] */ search(searchText: string, searchOptions?: Word.SearchOptions | { ignorePunct?: boolean; @@ -13652,18 +14070,19 @@ declare module Word { * * Selects the row and navigates the Word UI to it. * - * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. - * * [Api set: WordApi 1.3] + * + * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. */ select(selectionMode?: string): void; /** * * Sets cell padding in points. * - * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. - * * [Api set: WordApi 1.3] + * + * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. + * @param cellPadding Required. The cell padding. */ setCellPadding(cellPaddingLocation: string, cellPadding: number): void; /** @@ -13675,7 +14094,7 @@ declare module Word { */ track(): Word.TableRow; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.TableRow; toJSON(): { @@ -13686,7 +14105,7 @@ declare module Word { "preferredHeight": number; "rowIndex": number; "shadingColor": string; - "values": string[]; + "values": string[][]; "verticalAlignment": string; }; } @@ -13701,11 +14120,18 @@ declare module Word { items: Array; /** * - * Gets the first row in this collection. + * Gets the first row in this collection. Throws if this collection is empty. * * [Api set: WordApi 1.3] */ getFirst(): Word.TableRow; + /** + * + * Gets the first row in this collection. Returns a null object if this collection is empty. + * + * [Api set: WordApi 1.3] + */ + getFirstOrNullObject(): Word.TableRow; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -13715,7 +14141,7 @@ declare module Word { */ track(): Word.TableRowCollection; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.TableRowCollection; toJSON(): {}; @@ -13804,6 +14230,15 @@ declare module Word { * [Api set: WordApi 1.3] */ width: number; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.TableCellUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: TableCell): void; /** * * Deletes the column containing this cell. This is applicable to uniform tables. @@ -13822,56 +14257,64 @@ declare module Word { * * Gets the border style for the specified border. * - * @param borderLocation Required. The border location. - * * [Api set: WordApi 1.3] + * + * @param borderLocation Required. The border location. */ getBorder(borderLocation: string): Word.TableBorder; /** * * Gets cell padding in points. * - * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. - * * [Api set: WordApi 1.3] + * + * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. */ getCellPadding(cellPaddingLocation: string): OfficeExtension.ClientResult; /** * - * Gets the next cell. + * Gets the next cell. Throws if this cell is the last one. * * [Api set: WordApi 1.3] */ getNext(): Word.TableCell; + /** + * + * Gets the next cell. Returns a null object if this cell is the last one. + * + * [Api set: WordApi 1.3] + */ + getNextOrNullObject(): Word.TableCell; /** * * Adds columns to the left or right of the cell, using the cell's column as a template. This is applicable to uniform tables. The string values, if specified, are set in the newly inserted rows. * + * [Api set: WordApi 1.3] + * * @param insertLocation Required. It can be 'Before' or 'After'. * @param columnCount Required. Number of columns to add * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. - * - * [Api set: WordApi 1.3] */ insertColumns(insertLocation: string, columnCount: number, values?: Array>): void; /** * * Inserts rows above or below the cell, using the cell's row as a template. The string values, if specified, are set in the newly inserted rows. * + * [Api set: WordApi 1.3] + * * @param insertLocation Required. It can be 'Before' or 'After'. * @param rowCount Required. Number of rows to add. * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. - * - * [Api set: WordApi 1.3] */ insertRows(insertLocation: string, rowCount: number, values?: Array>): Word.TableRowCollection; /** * * Sets cell padding in points. * - * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. - * * [Api set: WordApi 1.3] + * + * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. + * @param cellPadding Required. The cell padding. */ setCellPadding(cellPaddingLocation: string, cellPadding: number): void; /** @@ -13883,7 +14326,7 @@ declare module Word { */ track(): Word.TableCell; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.TableCell; toJSON(): { @@ -13909,11 +14352,18 @@ declare module Word { items: Array; /** * - * Gets the first table cell in this collection. + * Gets the first table cell in this collection. Throws if this collection is empty. * * [Api set: WordApi 1.3] */ getFirst(): Word.TableCell; + /** + * + * Gets the first table cell in this collection. Returns a null object if this collection is empty. + * + * [Api set: WordApi 1.3] + */ + getFirstOrNullObject(): Word.TableCell; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -13923,7 +14373,7 @@ declare module Word { */ track(): Word.TableCellCollection; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.TableCellCollection; toJSON(): {}; @@ -13956,6 +14406,15 @@ declare module Word { * [Api set: WordApi 1.3] */ width: number; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.TableBorderUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: TableBorder): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -13965,7 +14424,7 @@ declare module Word { */ track(): Word.TableBorder; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.TableBorder; toJSON(): { @@ -13980,7 +14439,7 @@ declare module Word { * * [Api set: WordApi] */ - module ContentControlType { + namespace ContentControlType { var unknown: string; var richTextInline: string; var richTextParagraphs: string; @@ -14005,7 +14464,7 @@ declare module Word { * * [Api set: WordApi] */ - module ContentControlAppearance { + namespace ContentControlAppearance { var boundingBox: string; var tags: string; var hidden: string; @@ -14016,7 +14475,7 @@ declare module Word { * * [Api set: WordApi] */ - module UnderlineType { + namespace UnderlineType { var mixed: string; var none: string; /** @@ -14053,7 +14512,7 @@ declare module Word { * * [Api set: WordApi] */ - module BreakType { + namespace BreakType { /** * * Page break. @@ -14102,7 +14561,7 @@ declare module Word { * * [Api set: WordApi] */ - module InsertLocation { + namespace InsertLocation { var before: string; var after: string; var start: string; @@ -14112,7 +14571,7 @@ declare module Word { /** * [Api set: WordApi] */ - module Alignment { + namespace Alignment { var mixed: string; var unknown: string; var left: string; @@ -14123,7 +14582,7 @@ declare module Word { /** * [Api set: WordApi] */ - module HeaderFooterType { + namespace HeaderFooterType { var primary: string; var firstPage: string; var evenPages: string; @@ -14131,7 +14590,7 @@ declare module Word { /** * [Api set: WordApi] */ - module BodyType { + namespace BodyType { var unknown: string; var mainDoc: string; var section: string; @@ -14142,7 +14601,7 @@ declare module Word { /** * [Api set: WordApi] */ - module SelectionMode { + namespace SelectionMode { var select: string; var start: string; var end: string; @@ -14150,7 +14609,7 @@ declare module Word { /** * [Api set: WordApi] */ - module ImageFormat { + namespace ImageFormat { var unsupported: string; var undefined: string; var bmp: string; @@ -14169,7 +14628,7 @@ declare module Word { /** * [Api set: WordApi] */ - module RangeLocation { + namespace RangeLocation { var whole: string; var start: string; var end: string; @@ -14180,7 +14639,7 @@ declare module Word { /** * [Api set: WordApi] */ - module LocationRelation { + namespace LocationRelation { var unrelated: string; var equal: string; var containsStart: string; @@ -14199,7 +14658,7 @@ declare module Word { /** * [Api set: WordApi] */ - module BorderLocation { + namespace BorderLocation { var top: string; var left: string; var bottom: string; @@ -14213,7 +14672,7 @@ declare module Word { /** * [Api set: WordApi] */ - module CellPaddingLocation { + namespace CellPaddingLocation { var top: string; var left: string; var bottom: string; @@ -14222,7 +14681,7 @@ declare module Word { /** * [Api set: WordApi] */ - module BorderType { + namespace BorderType { var mixed: string; var none: string; var single: string; @@ -14251,7 +14710,7 @@ declare module Word { /** * [Api set: WordApi] */ - module VerticalAlignment { + namespace VerticalAlignment { var mixed: string; var top: string; var center: string; @@ -14260,7 +14719,7 @@ declare module Word { /** * [Api set: WordApi] */ - module ListLevelType { + namespace ListLevelType { var bullet: string; var number: string; var picture: string; @@ -14268,7 +14727,7 @@ declare module Word { /** * [Api set: WordApi] */ - module ListBullet { + namespace ListBullet { var custom: string; var solid: string; var hollow: string; @@ -14280,7 +14739,7 @@ declare module Word { /** * [Api set: WordApi] */ - module ListNumbering { + namespace ListNumbering { var none: string; var arabic: string; var upperRoman: string; @@ -14291,7 +14750,7 @@ declare module Word { /** * [Api set: WordApi] */ - module Style { + namespace Style { /** * * Mixed styles or other style not in this list. @@ -14504,19 +14963,776 @@ declare module Word { /** * [Api set: WordApi] */ - module DocumentPropertyType { + namespace DocumentPropertyType { var string: string; var number: string; var date: string; var boolean: string; } - module ErrorCodes { + namespace ErrorCodes { var accessDenied: string; var generalException: string; var invalidArgument: string; var itemNotFound: string; var notImplemented: string; } + module Interfaces { + /** An interface for updating data on the Body object, for use in "body.set({ ... })". */ + interface BodyUpdateData { + /** + * + * Gets the text format of the body. Use this to get and set font name, size, color and other properties. + * + * [Api set: WordApi 1.1] + */ + font?: Word.Interfaces.FontUpdateData; + /** + * + * Gets or sets the style name for the body. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. + * + * [Api set: WordApi 1.1] + */ + style?: string; + /** + * + * Gets or sets the built-in style name for the body. Use this property for built-in styles that are portable between locales. To use custom styles or localized style names, see the "style" property. + * + * [Api set: WordApi 1.3] + */ + styleBuiltIn?: string; + } + /** An interface for updating data on the ContentControl object, for use in "contentControl.set({ ... })". */ + interface ContentControlUpdateData { + /** + * + * Gets the text format of the content control. Use this to get and set font name, size, color, and other properties. + * + * [Api set: WordApi 1.1] + */ + font?: Word.Interfaces.FontUpdateData; + /** + * + * Gets or sets the appearance of the content control. The value can be 'boundingBox', 'tags' or 'hidden'. + * + * [Api set: WordApi 1.1] + */ + appearance?: string; + /** + * + * Gets or sets a value that indicates whether the user can delete the content control. Mutually exclusive with removeWhenEdited. + * + * [Api set: WordApi 1.1] + */ + cannotDelete?: boolean; + /** + * + * Gets or sets a value that indicates whether the user can edit the contents of the content control. + * + * [Api set: WordApi 1.1] + */ + cannotEdit?: boolean; + /** + * + * Gets or sets the color of the content control. Color is specified in '#RRGGBB' format or by using the color name. + * + * [Api set: WordApi 1.1] + */ + color?: string; + /** + * + * Gets or sets the placeholder text of the content control. Dimmed text will be displayed when the content control is empty. + * + * [Api set: WordApi 1.1] + */ + placeholderText?: string; + /** + * + * Gets or sets a value that indicates whether the content control is removed after it is edited. Mutually exclusive with cannotDelete. + * + * [Api set: WordApi 1.1] + */ + removeWhenEdited?: boolean; + /** + * + * Gets or sets the style name for the content control. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. + * + * [Api set: WordApi 1.1] + */ + style?: string; + /** + * + * Gets or sets the built-in style name for the content control. Use this property for built-in styles that are portable between locales. To use custom styles or localized style names, see the "style" property. + * + * [Api set: WordApi 1.3] + */ + styleBuiltIn?: string; + /** + * + * Gets or sets a tag to identify a content control. + * + * [Api set: WordApi 1.1] + */ + tag?: string; + /** + * + * Gets or sets the title for a content control. + * + * [Api set: WordApi 1.1] + */ + title?: string; + } + /** An interface for updating data on the CustomProperty object, for use in "customProperty.set({ ... })". */ + interface CustomPropertyUpdateData { + /** + * + * Gets or sets the value of the custom property. + * + * [Api set: WordApi 1.3] + */ + value?: any; + } + /** An interface for updating data on the Document object, for use in "document.set({ ... })". */ + interface DocumentUpdateData { + /** + * + * Gets the body object of the document. The body is the text that excludes headers, footers, footnotes, textboxes, etc.. + * + * [Api set: WordApi 1.1] + */ + body?: Word.Interfaces.BodyUpdateData; + /** + * + * Gets the properties of the current document. + * + * [Api set: WordApi 1.3] + */ + properties?: Word.Interfaces.DocumentPropertiesUpdateData; + } + /** An interface for updating data on the DocumentProperties object, for use in "documentProperties.set({ ... })". */ + interface DocumentPropertiesUpdateData { + /** + * + * Gets or sets the author of the document. + * + * [Api set: WordApi 1.3] + */ + author?: string; + /** + * + * Gets or sets the category of the document. + * + * [Api set: WordApi 1.3] + */ + category?: string; + /** + * + * Gets or sets the comments of the document. + * + * [Api set: WordApi 1.3] + */ + comments?: string; + /** + * + * Gets or sets the company of the document. + * + * [Api set: WordApi 1.3] + */ + company?: string; + /** + * + * Gets or sets the format of the document. + * + * [Api set: WordApi 1.3] + */ + format?: string; + /** + * + * Gets or sets the keywords of the document. + * + * [Api set: WordApi 1.3] + */ + keywords?: string; + /** + * + * Gets or sets the manager of the document. + * + * [Api set: WordApi 1.3] + */ + manager?: string; + /** + * + * Gets or sets the subject of the document. + * + * [Api set: WordApi 1.3] + */ + subject?: string; + /** + * + * Gets or sets the title of the document. + * + * [Api set: WordApi 1.3] + */ + title?: string; + } + /** An interface for updating data on the Font object, for use in "font.set({ ... })". */ + interface FontUpdateData { + /** + * + * Gets or sets a value that indicates whether the font is bold. True if the font is formatted as bold, otherwise, false. + * + * [Api set: WordApi 1.1] + */ + bold?: boolean; + /** + * + * Gets or sets the color for the specified font. You can provide the value in the '#RRGGBB' format or the color name. + * + * [Api set: WordApi 1.1] + */ + color?: string; + /** + * + * Gets or sets a value that indicates whether the font has a double strike through. True if the font is formatted as double strikethrough text, otherwise, false. + * + * [Api set: WordApi 1.1] + */ + doubleStrikeThrough?: boolean; + /** + * + * Gets or sets the highlight color. To set it, use a value either in the '#RRGGBB' format or the color name. To remove highlight color, set it to null. The returned highlight color can be in the '#RRGGBB' format, or an empty string for mixed highlight colors, or null for no highlight color. + * + * [Api set: WordApi 1.1] + */ + highlightColor?: string; + /** + * + * Gets or sets a value that indicates whether the font is italicized. True if the font is italicized, otherwise, false. + * + * [Api set: WordApi 1.1] + */ + italic?: boolean; + /** + * + * Gets or sets a value that represents the name of the font. + * + * [Api set: WordApi 1.1] + */ + name?: string; + /** + * + * Gets or sets a value that represents the font size in points. + * + * [Api set: WordApi 1.1] + */ + size?: number; + /** + * + * Gets or sets a value that indicates whether the font has a strike through. True if the font is formatted as strikethrough text, otherwise, false. + * + * [Api set: WordApi 1.1] + */ + strikeThrough?: boolean; + /** + * + * Gets or sets a value that indicates whether the font is a subscript. True if the font is formatted as subscript, otherwise, false. + * + * [Api set: WordApi 1.1] + */ + subscript?: boolean; + /** + * + * Gets or sets a value that indicates whether the font is a superscript. True if the font is formatted as superscript, otherwise, false. + * + * [Api set: WordApi 1.1] + */ + superscript?: boolean; + /** + * + * Gets or sets a value that indicates the font's underline type. 'None' if the font is not underlined. + * + * [Api set: WordApi 1.1] + */ + underline?: string; + } + /** An interface for updating data on the InlinePicture object, for use in "inlinePicture.set({ ... })". */ + interface InlinePictureUpdateData { + /** + * + * Gets or sets a string that represents the alternative text associated with the inline image + * + * [Api set: WordApi 1.1] + */ + altTextDescription?: string; + /** + * + * Gets or sets a string that contains the title for the inline image. + * + * [Api set: WordApi 1.1] + */ + altTextTitle?: string; + /** + * + * Gets or sets a number that describes the height of the inline image. + * + * [Api set: WordApi 1.1] + */ + height?: number; + /** + * + * Gets or sets a hyperlink on the image. Use a '#' to separate the address part from the optional location part. + * + * [Api set: WordApi 1.1] + */ + hyperlink?: string; + /** + * + * Gets or sets a value that indicates whether the inline image retains its original proportions when you resize it. + * + * [Api set: WordApi 1.1] + */ + lockAspectRatio?: boolean; + /** + * + * Gets or sets a number that describes the width of the inline image. + * + * [Api set: WordApi 1.1] + */ + width?: number; + } + /** An interface for updating data on the ListItem object, for use in "listItem.set({ ... })". */ + interface ListItemUpdateData { + /** + * + * Gets or sets the level of the item in the list. + * + * [Api set: WordApi 1.3] + */ + level?: number; + } + /** An interface for updating data on the Paragraph object, for use in "paragraph.set({ ... })". */ + interface ParagraphUpdateData { + /** + * + * Gets the text format of the paragraph. Use this to get and set font name, size, color, and other properties. + * + * [Api set: WordApi 1.1] + */ + font?: Word.Interfaces.FontUpdateData; + /** + * + * Gets the ListItem for the paragraph. Throws if the paragraph is not part of a list. + * + * [Api set: WordApi 1.3] + */ + listItem?: Word.Interfaces.ListItemUpdateData; + /** + * + * Gets the ListItem for the paragraph. Returns a null object if the paragraph is not part of a list. + * + * [Api set: WordApi 1.3] + */ + listItemOrNullObject?: Word.Interfaces.ListItemUpdateData; + /** + * + * Gets or sets the alignment for a paragraph. The value can be 'left', 'centered', 'right', or 'justified'. + * + * [Api set: WordApi 1.1] + */ + alignment?: string; + /** + * + * Gets or sets the value, in points, for a first line or hanging indent. Use a positive value to set a first-line indent, and use a negative value to set a hanging indent. + * + * [Api set: WordApi 1.1] + */ + firstLineIndent?: number; + /** + * + * Gets or sets the left indent value, in points, for the paragraph. + * + * [Api set: WordApi 1.1] + */ + leftIndent?: number; + /** + * + * Gets or sets the line spacing, in points, for the specified paragraph. In the Word UI, this value is divided by 12. + * + * [Api set: WordApi 1.1] + */ + lineSpacing?: number; + /** + * + * Gets or sets the amount of spacing, in grid lines. after the paragraph. + * + * [Api set: WordApi 1.1] + */ + lineUnitAfter?: number; + /** + * + * Gets or sets the amount of spacing, in grid lines, before the paragraph. + * + * [Api set: WordApi 1.1] + */ + lineUnitBefore?: number; + /** + * + * Gets or sets the outline level for the paragraph. + * + * [Api set: WordApi 1.1] + */ + outlineLevel?: number; + /** + * + * Gets or sets the right indent value, in points, for the paragraph. + * + * [Api set: WordApi 1.1] + */ + rightIndent?: number; + /** + * + * Gets or sets the spacing, in points, after the paragraph. + * + * [Api set: WordApi 1.1] + */ + spaceAfter?: number; + /** + * + * Gets or sets the spacing, in points, before the paragraph. + * + * [Api set: WordApi 1.1] + */ + spaceBefore?: number; + /** + * + * Gets or sets the style name for the paragraph. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. + * + * [Api set: WordApi 1.1] + */ + style?: string; + /** + * + * Gets or sets the built-in style name for the paragraph. Use this property for built-in styles that are portable between locales. To use custom styles or localized style names, see the "style" property. + * + * [Api set: WordApi 1.3] + */ + styleBuiltIn?: string; + } + /** An interface for updating data on the Range object, for use in "range.set({ ... })". */ + interface RangeUpdateData { + /** + * + * Gets the text format of the range. Use this to get and set font name, size, color, and other properties. + * + * [Api set: WordApi 1.1] + */ + font?: Word.Interfaces.FontUpdateData; + /** + * + * Gets the first hyperlink in the range, or sets a hyperlink on the range. All hyperlinks in the range are deleted when you set a new hyperlink on the range. Use a '#' to separate the address part from the optional location part. + * + * [Api set: WordApi 1.3] + */ + hyperlink?: string; + /** + * + * Gets or sets the style name for the range. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. + * + * [Api set: WordApi 1.1] + */ + style?: string; + /** + * + * Gets or sets the built-in style name for the range. Use this property for built-in styles that are portable between locales. To use custom styles or localized style names, see the "style" property. + * + * [Api set: WordApi 1.3] + */ + styleBuiltIn?: string; + } + /** An interface for updating data on the SearchOptions object, for use in "searchOptions.set({ ... })". */ + interface SearchOptionsUpdateData { + /** + * + * Gets or sets a value that indicates whether to ignore all punctuation characters between words. Corresponds to the Ignore punctuation check box in the Find and Replace dialog box. + * + * [Api set: WordApi 1.1] + */ + ignorePunct?: boolean; + /** + * + * Gets or sets a value that indicates whether to ignore all whitespace between words. Corresponds to the Ignore whitespace characters check box in the Find and Replace dialog box. + * + * [Api set: WordApi 1.1] + */ + ignoreSpace?: boolean; + /** + * + * Gets or sets a value that indicates whether to perform a case sensitive search. Corresponds to the Match case check box in the Find and Replace dialog box (Edit menu). + * + * [Api set: WordApi 1.1] + */ + matchCase?: boolean; + /** + * + * Gets or sets a value that indicates whether to match words that begin with the search string. Corresponds to the Match prefix check box in the Find and Replace dialog box. + * + * [Api set: WordApi 1.1] + */ + matchPrefix?: boolean; + /** + * + * Gets or sets a value that indicates whether to match words that end with the search string. Corresponds to the Match suffix check box in the Find and Replace dialog box. + * + * [Api set: WordApi 1.1] + */ + matchSuffix?: boolean; + /** + * + * Gets or sets a value that indicates whether to find operation only entire words, not text that is part of a larger word. Corresponds to the Find whole words only check box in the Find and Replace dialog box. + * + * [Api set: WordApi 1.1] + */ + matchWholeWord?: boolean; + /** + * + * Gets or sets a value that indicates whether the search will be performed using special search operators. Corresponds to the Use wildcards check box in the Find and Replace dialog box. + * + * [Api set: WordApi 1.1] + */ + matchWildcards?: boolean; + } + /** An interface for updating data on the Section object, for use in "section.set({ ... })". */ + interface SectionUpdateData { + /** + * + * Gets the body object of the section. This does not include the header/footer and other section metadata. + * + * [Api set: WordApi 1.1] + */ + body?: Word.Interfaces.BodyUpdateData; + } + /** An interface for updating data on the Table object, for use in "table.set({ ... })". */ + interface TableUpdateData { + /** + * + * Gets the font. Use this to get and set font name, size, color, and other properties. + * + * [Api set: WordApi 1.3] + */ + font?: Word.Interfaces.FontUpdateData; + /** + * + * Gets or sets the alignment of the table against the page column. The value can be 'left', 'centered' or 'right'. + * + * [Api set: WordApi 1.3] + */ + alignment?: string; + /** + * + * Gets and sets the number of header rows. + * + * [Api set: WordApi 1.3] + */ + headerRowCount?: number; + /** + * + * Gets and sets the horizontal alignment of every cell in the table. The value can be 'left', 'centered', 'right', or 'justified'. + * + * [Api set: WordApi 1.3] + */ + horizontalAlignment?: string; + /** + * + * Gets and sets the shading color. + * + * [Api set: WordApi 1.3] + */ + shadingColor?: string; + /** + * + * Gets or sets the style name for the table. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. + * + * [Api set: WordApi 1.3] + */ + style?: string; + /** + * + * Gets and sets whether the table has banded columns. + * + * [Api set: WordApi 1.3] + */ + styleBandedColumns?: boolean; + /** + * + * Gets and sets whether the table has banded rows. + * + * [Api set: WordApi 1.3] + */ + styleBandedRows?: boolean; + /** + * + * Gets or sets the built-in style name for the table. Use this property for built-in styles that are portable between locales. To use custom styles or localized style names, see the "style" property. + * + * [Api set: WordApi 1.3] + */ + styleBuiltIn?: string; + /** + * + * Gets and sets whether the table has a first column with a special style. + * + * [Api set: WordApi 1.3] + */ + styleFirstColumn?: boolean; + /** + * + * Gets and sets whether the table has a last column with a special style. + * + * [Api set: WordApi 1.3] + */ + styleLastColumn?: boolean; + /** + * + * Gets and sets whether the table has a total (last) row with a special style. + * + * [Api set: WordApi 1.3] + */ + styleTotalRow?: boolean; + /** + * + * Gets and sets the text values in the table, as a 2D Javascript array. + * + * [Api set: WordApi 1.3] + */ + values?: Array>; + /** + * + * Gets and sets the vertical alignment of every cell in the table. The value can be 'top', 'center' or 'bottom'. + * + * [Api set: WordApi 1.3] + */ + verticalAlignment?: string; + /** + * + * Gets and sets the width of the table in points. + * + * [Api set: WordApi 1.3] + */ + width?: number; + } + /** An interface for updating data on the TableRow object, for use in "tableRow.set({ ... })". */ + interface TableRowUpdateData { + /** + * + * Gets the font. Use this to get and set font name, size, color, and other properties. + * + * [Api set: WordApi 1.3] + */ + font?: Word.Interfaces.FontUpdateData; + /** + * + * Gets and sets the horizontal alignment of every cell in the row. The value can be 'left', 'centered', 'right', or 'justified'. + * + * [Api set: WordApi 1.3] + */ + horizontalAlignment?: string; + /** + * + * Gets and sets the preferred height of the row in points. + * + * [Api set: WordApi 1.3] + */ + preferredHeight?: number; + /** + * + * Gets and sets the shading color. + * + * [Api set: WordApi 1.3] + */ + shadingColor?: string; + /** + * + * Gets and sets the text values in the row, as a 2D Javascript array. + * + * [Api set: WordApi 1.3] + */ + values?: Array>; + /** + * + * Gets and sets the vertical alignment of the cells in the row. The value can be 'top', 'center' or 'bottom'. + * + * [Api set: WordApi 1.3] + */ + verticalAlignment?: string; + } + /** An interface for updating data on the TableCell object, for use in "tableCell.set({ ... })". */ + interface TableCellUpdateData { + /** + * + * Gets the body object of the cell. + * + * [Api set: WordApi 1.3] + */ + body?: Word.Interfaces.BodyUpdateData; + /** + * + * Gets and sets the width of the cell's column in points. This is applicable to uniform tables. + * + * [Api set: WordApi 1.3] + */ + columnWidth?: number; + /** + * + * Gets and sets the horizontal alignment of the cell. The value can be 'left', 'centered', 'right', or 'justified'. + * + * [Api set: WordApi 1.3] + */ + horizontalAlignment?: string; + /** + * + * Gets or sets the shading color of the cell. Color is specified in "#RRGGBB" format or by using the color name. + * + * [Api set: WordApi 1.3] + */ + shadingColor?: string; + /** + * + * Gets and sets the text of the cell. + * + * [Api set: WordApi 1.3] + */ + value?: string; + /** + * + * Gets and sets the vertical alignment of the cell. The value can be 'top', 'center' or 'bottom'. + * + * [Api set: WordApi 1.3] + */ + verticalAlignment?: string; + } + /** An interface for updating data on the TableBorder object, for use in "tableBorder.set({ ... })". */ + interface TableBorderUpdateData { + /** + * + * Gets or sets the table border color, as a hex value or name. + * + * [Api set: WordApi 1.3] + */ + color?: string; + /** + * + * Gets or sets the type of the table border. + * + * [Api set: WordApi 1.3] + */ + type?: string; + /** + * + * Gets or sets the width, in points, of the table border. Not applicable to table border types that have fixed widths. + * + * [Api set: WordApi 1.3] + */ + width?: number; + } + } } declare module Word { /** @@ -14525,7 +15741,6 @@ declare module Word { class RequestContext extends OfficeExtension.ClientRequestContext { constructor(url?: string); document: Document; - application: Application; } /** * Executes a batch script that performs actions on the Word object model, using a new RequestContext. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. diff --git a/on-finished/on-finished-tests.ts b/on-finished/on-finished-tests.ts index 57040531fc..081e2cd37b 100644 --- a/on-finished/on-finished-tests.ts +++ b/on-finished/on-finished-tests.ts @@ -1,5 +1,3 @@ -/// - import events = require('events'); import onFinished = require('on-finished'); diff --git a/onoff/onoff-tests.ts b/onoff/onoff-tests.ts index cd39dc4a8d..21b47e7f99 100644 --- a/onoff/onoff-tests.ts +++ b/onoff/onoff-tests.ts @@ -1,5 +1,3 @@ - -/// import * as onoff from 'onoff'; var led:onoff.Gpio = new onoff.Gpio(17, 'out'); diff --git a/opener/tsconfig.json b/opener/tsconfig.json index c607aac672..5452230c75 100644 --- a/opener/tsconfig.json +++ b/opener/tsconfig.json @@ -19,4 +19,4 @@ "index.d.ts", "opener-tests.ts" ] -} \ No newline at end of file +} diff --git a/openfin/openfin-tests.ts b/openfin/openfin-tests.ts index 63a53f7cb5..cb08f60a62 100644 --- a/openfin/openfin-tests.ts +++ b/openfin/openfin-tests.ts @@ -1,4 +1,4 @@ -function test_application() { +function test_application() { let application: fin.OpenFinApplication; // constructor application = new fin.desktop.Application({ diff --git a/openfin/v15/openfin-tests.ts b/openfin/v15/openfin-tests.ts index 69b024ce90..c3c1ef1cc6 100644 --- a/openfin/v15/openfin-tests.ts +++ b/openfin/v15/openfin-tests.ts @@ -1,4 +1,3 @@ - function test_application() { let application: fin.OpenFinApplication; // constructor diff --git a/openlayers/index.d.ts b/openlayers/index.d.ts index f81e964b4d..2b721ab7ca 100644 --- a/openlayers/index.d.ts +++ b/openlayers/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for OpenLayers v3.20.0 +// Type definitions for OpenLayers v4.0.1 // Project: http://openlayers.org/ // Definitions by: Olivier Sechet // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -10,55 +10,6 @@ declare type GlobalObject = Object; * @namespace ol */ declare module ol { - /** - * The animation static methods are designed to be used with the - * {@link ol.Map#beforeRender} method. For example: - * - * var map = new ol.Map({ ... }); - * var zoom = ol.animation.zoom({ - * resolution: map.getView().getResolution() - * }); - * map.beforeRender(zoom); - * map.getView().setResolution(map.getView().getResolution() * 2); - * - * @namespace ol.animation - */ - module animation { - /** - * Generate an animated transition that will "bounce" the resolution as it - * approaches the final value. - * @param {olx.animation.BounceOptions} options Bounce options. - * @return {ol.PreRenderFunction} Pre-render function. - * @api - */ - function bounce(options: olx.animation.BounceOptions): ol.PreRenderFunction; - - /** - * Generate an animated transition while updating the view center. - * @param {olx.animation.PanOptions} options Pan options. - * @return {ol.PreRenderFunction} Pre-render function. - * @api - */ - function pan(options: olx.animation.PanOptions): ol.PreRenderFunction; - - /** - * Generate an animated transition while updating the view rotation. - * @param {olx.animation.RotateOptions} options Rotate options. - * @return {ol.PreRenderFunction} Pre-render function. - * @api - */ - function rotate(options: olx.animation.RotateOptions): ol.PreRenderFunction; - - /** - * Generate an animated transition while updating the view resolution. - * @param {olx.animation.ZoomOptions} options Zoom options. - * @return {ol.PreRenderFunction} Pre-render function. - * @api - */ - function zoom(options: olx.animation.ZoomOptions): ol.PreRenderFunction; - - } - /** * Error object thrown when an assertion failed. This is an ECMA-262 Error, * extended with a `code` property. @@ -2765,7 +2716,110 @@ declare module ol { } module filter { - interface Filter { } + /** + * Create a `` operator to test whether a geometry-valued property + * intersects a given geometry. + * + * @param {!string} geometryName Geometry name to use. + * @param {!ol.geom.Geometry} geometry Geometry. + * @param {string=} opt_srsName SRS name. No srsName attribute will be + * set on geometries when this is not provided. + * @returns {!ol.format.filter.Intersects} `` operator. + * @api + */ + function intersects(geometryName: string, geometry: ol.geom.Geometry, opt_srsName?: string): ol.format.filter.Intersects; + + /** + * @classdesc + * Abstract class; normally only used for creating subclasses and not instantiated in apps. + * Base class for WFS GetFeature filters. + * + * @constructor + * @param {!string} tagName The XML tag name for this filter. + * @struct + * @api + */ + class Filter { + /** + * @classdesc + * Abstract class; normally only used for creating subclasses and not instantiated in apps. + * Base class for WFS GetFeature filters. + * + * @constructor + * @param {!string} tagName The XML tag name for this filter. + * @struct + * @api + */ + constructor(tagName: string); + + /** + * The XML tag name for a filter. + * @returns {!string} Name. + */ + getTagName(): string; + } + + /** + * @classdesc + * Represents a spatial operator to test whether a geometry-valued property + * relates to a given geometry. + * + * @constructor + * @param {!string} tagName The XML tag name for this filter. + * @param {!string} geometryName Geometry name to use. + * @param {!ol.geom.Geometry} geometry Geometry. + * @param {string=} opt_srsName SRS name. No srsName attribute will be + * set on geometries when this is not provided. + * @extends {ol.format.filter.Filter} + * @api + */ + class Spatial extends ol.format.filter.Filter { + /** + * @classdesc + * Represents a spatial operator to test whether a geometry-valued property + * relates to a given geometry. + * + * @constructor + * @param {!string} tagName The XML tag name for this filter. + * @param {!string} geometryName Geometry name to use. + * @param {!ol.geom.Geometry} geometry Geometry. + * @param {string=} opt_srsName SRS name. No srsName attribute will be + * set on geometries when this is not provided. + * @extends {ol.format.filter.Filter} + * @api + */ + constructor(tagName: string, geometryName: string, geometry: ol.geom.Geometry, opt_srsName?: string); + } + + /** + * @classdesc + * Represents a `` operator to test whether a geometry-valued property + * intersects a given geometry. + * + * @constructor + * @param {!string} geometryName Geometry name to use. + * @param {!ol.geom.Geometry} geometry Geometry. + * @param {string=} opt_srsName SRS name. No srsName attribute will be + * set on geometries when this is not provided. + * @extends {ol.format.filter.Spatial} + * @api + */ + class Intersects extends ol.format.filter.Spatial { + /** + * @classdesc + * Represents a `` operator to test whether a geometry-valued property + * intersects a given geometry. + * + * @constructor + * @param {!string} geometryName Geometry name to use. + * @param {!ol.geom.Geometry} geometry Geometry. + * @param {string=} opt_srsName SRS name. No srsName attribute will be + * set on geometries when this is not provided. + * @extends {ol.format.filter.Spatial} + * @api + */ + constructor(geometryName: string, geometry: ol.geom.Geometry, opt_srsName?: string); + } } /** @@ -4761,50 +4815,6 @@ declare module ol { */ function inherits(childCtor: (() => any), parentCtor: (() => any)): void; - /** - * @classdesc - * Events emitted by {@link ol.interaction.DragBox} instances are instances of - * this type. - * - * @param {string} type The event type. - * @param {ol.Coordinate} coordinate The event coordinate. - * @param {ol.MapBrowserEvent} mapBrowserEvent Originating event. - * @extends {ol.events.Event} - * @constructor - * @implements {oli.DragBoxEvent} - */ - class DragBoxEvent extends ol.events.Event { - /** - * @classdesc - * Events emitted by {@link ol.interaction.DragBox} instances are instances of - * this type. - * - * @param {string} type The event type. - * @param {ol.Coordinate} coordinate The event coordinate. - * @param {ol.MapBrowserEvent} mapBrowserEvent Originating event. - * @extends {ol.events.Event} - * @constructor - * @implements {oli.DragBoxEvent} - */ - constructor(type: string, coordinate: ol.Coordinate, mapBrowserEvent: ol.MapBrowserEvent); - - /** - * The coordinate of the drag event. - * @const - * @type {ol.Coordinate} - * @api stable - */ - coordinate: ol.Coordinate; - - /** - * @const - * @type {ol.MapBrowserEvent} - * @api - */ - mapBrowserEvent: ol.MapBrowserEvent; - - } - /** * @namespace ol.interaction */ @@ -4878,19 +4888,9 @@ declare module ol { } /** - * @classdesc - * Events emitted by {@link ol.interaction.DragAndDrop} instances are instances - * of this type. - * - * @constructor - * @extends {ol.events.Event} - * @implements {oli.interaction.DragAndDropEvent} - * @param {ol.interaction.DragAndDropEventType} type Type. - * @param {File} file File. - * @param {Array.=} opt_features Features. - * @param {ol.proj.Projection=} opt_projection Projection. + * @namespace ol.interaction.DragAndDrop */ - class DragAndDropEvent extends ol.events.Event { + module DragAndDrop { /** * @classdesc * Events emitted by {@link ol.interaction.DragAndDrop} instances are instances @@ -4904,28 +4904,44 @@ declare module ol { * @param {Array.=} opt_features Features. * @param {ol.proj.Projection=} opt_projection Projection. */ - constructor(type: ol.interaction.DragAndDropEventType, file: File, opt_features?: ol.Feature[], opt_projection?: ol.proj.Projection); - - /** - * The features parsed from dropped data. - * @type {Array.|undefined} - * @api stable - */ - features: ol.Feature[]; - - /** - * The dropped file. - * @type {File} - * @api stable - */ - file: File; - - /** - * The feature projection. - * @type {ol.proj.Projection|undefined} - * @api - */ - projection: ol.proj.Projection; + class Event extends ol.events.Event { + /** + * @classdesc + * Events emitted by {@link ol.interaction.DragAndDrop} instances are instances + * of this type. + * + * @constructor + * @extends {ol.events.Event} + * @implements {oli.interaction.DragAndDropEvent} + * @param {ol.interaction.DragAndDropEventType} type Type. + * @param {File} file File. + * @param {Array.=} opt_features Features. + * @param {ol.proj.Projection=} opt_projection Projection. + */ + constructor(type: ol.interaction.DragAndDropEventType, file: File, opt_features?: ol.Feature[], opt_projection?: ol.proj.Projection); + + /** + * The features parsed from dropped data. + * @type {Array.|undefined} + * @api stable + */ + features: ol.Feature[]; + + /** + * The dropped file. + * @type {File} + * @api stable + */ + file: File; + + /** + * The feature projection. + * @type {ol.proj.Projection|undefined} + * @api + */ + projection: ol.proj.Projection; + + } } @@ -4977,6 +4993,58 @@ declare module ol { } + /** + * @namespace ol.interaction.DragBox + */ + module DragBox { + /** + * @classdesc + * Events emitted by {@link ol.interaction.DragBox} instances are instances of + * this type. + * + * @param {string} type The event type. + * @param {ol.Coordinate} coordinate The event coordinate. + * @param {ol.MapBrowserEvent} mapBrowserEvent Originating event. + * @extends {ol.events.Event} + * @constructor + * @implements {oli.DragBoxEvent} + */ + class Event extends ol.events.Event { + /** + * @classdesc + * Events emitted by {@link ol.interaction.DragBox} instances are instances of + * this type. + * + * @param {string} type The event type. + * @param {ol.Coordinate} coordinate The event coordinate. + * @param {ol.MapBrowserEvent} mapBrowserEvent Originating event. + * @extends {ol.events.Event} + * @constructor + * @implements {oli.DragBoxEvent} + */ + constructor(type: string, coordinate: ol.Coordinate, mapBrowserEvent: ol.MapBrowserEvent); + + /** + * The coordinate of the drag event. + * @const + * @type {ol.Coordinate} + * @api stable + */ + coordinate: ol.Coordinate; + + /** + * @const + * @type {ol.MapBrowserEvent} + * @api + */ + mapBrowserEvent: ol.MapBrowserEvent; + + } + + } + + type DragBoxEventType = string; + /** * @classdesc * Allows the user to pan the map by dragging the map. @@ -5100,17 +5168,9 @@ declare module ol { } /** - * @classdesc - * Events emitted by {@link ol.interaction.Draw} instances are instances of - * this type. - * - * @constructor - * @extends {ol.events.Event} - * @implements {oli.DrawEvent} - * @param {ol.interaction.DrawEventType} type Type. - * @param {ol.Feature} feature The feature drawn. + * @namespace ol.interaction.Draw */ - class DrawEvent extends ol.events.Event { + module Draw { /** * @classdesc * Events emitted by {@link ol.interaction.Draw} instances are instances of @@ -5122,14 +5182,28 @@ declare module ol { * @param {ol.interaction.DrawEventType} type Type. * @param {ol.Feature} feature The feature drawn. */ - constructor(type: ol.interaction.DrawEventType, feature: ol.Feature); - - /** - * The feature being drawn. - * @type {ol.Feature} - * @api stable - */ - feature: ol.Feature; + class Event extends ol.events.Event { + /** + * @classdesc + * Events emitted by {@link ol.interaction.Draw} instances are instances of + * this type. + * + * @constructor + * @extends {ol.events.Event} + * @implements {oli.DrawEvent} + * @param {ol.interaction.DrawEventType} type Type. + * @param {ol.Feature} feature The feature drawn. + */ + constructor(type: ol.interaction.DrawEventType, feature: ol.Feature); + + /** + * The feature being drawn. + * @type {ol.Feature} + * @api stable + */ + feature: ol.Feature; + + } } @@ -5386,19 +5460,9 @@ declare module ol { } /** - * @classdesc - * Events emitted by {@link ol.interaction.Modify} instances are instances of - * this type. - * - * @constructor - * @extends {ol.events.Event} - * @implements {oli.ModifyEvent} - * @param {ol.ModifyEventType} type Type. - * @param {ol.Collection.} features The features modified. - * @param {ol.MapBrowserPointerEvent} mapBrowserPointerEvent Associated - * {@link ol.MapBrowserPointerEvent}. + * @namespace ol.interaction.Modify */ - class ModifyEvent extends ol.events.Event { + module Modify { /** * @classdesc * Events emitted by {@link ol.interaction.Modify} instances are instances of @@ -5412,21 +5476,37 @@ declare module ol { * @param {ol.MapBrowserPointerEvent} mapBrowserPointerEvent Associated * {@link ol.MapBrowserPointerEvent}. */ - constructor(type: ol.ModifyEventType, features: ol.Collection, mapBrowserPointerEvent: ol.MapBrowserPointerEvent); - - /** - * The features being modified. - * @type {ol.Collection.} - * @api - */ - features: ol.Collection; - - /** - * Associated {@link ol.MapBrowserEvent}. - * @type {ol.MapBrowserEvent} - * @api - */ - mapBrowserEvent: ol.MapBrowserEvent; + class Event extends ol.events.Event { + /** + * @classdesc + * Events emitted by {@link ol.interaction.Modify} instances are instances of + * this type. + * + * @constructor + * @extends {ol.events.Event} + * @implements {oli.ModifyEvent} + * @param {ol.ModifyEventType} type Type. + * @param {ol.Collection.} features The features modified. + * @param {ol.MapBrowserPointerEvent} mapBrowserPointerEvent Associated + * {@link ol.MapBrowserPointerEvent}. + */ + constructor(type: ol.ModifyEventType, features: ol.Collection, mapBrowserPointerEvent: ol.MapBrowserPointerEvent); + + /** + * The features being modified. + * @type {ol.Collection.} + * @api + */ + features: ol.Collection; + + /** + * Associated {@link ol.MapBrowserEvent}. + * @type {ol.MapBrowserEvent} + * @api + */ + mapBrowserEvent: ol.MapBrowserEvent; + + } } @@ -5600,20 +5680,9 @@ declare module ol { } /** - * @classdesc - * Events emitted by {@link ol.interaction.Select} instances are instances of - * this type. - * - * @param {string} type The event type. - * @param {Array.} selected Selected features. - * @param {Array.} deselected Deselected features. - * @param {ol.MapBrowserEvent} mapBrowserEvent Associated - * {@link ol.MapBrowserEvent}. - * @implements {oli.SelectEvent} - * @extends {ol.events.Event} - * @constructor + * @namespace ol.interaction.Select */ - class SelectEvent extends ol.events.Event { + module Select { /** * @classdesc * Events emitted by {@link ol.interaction.Select} instances are instances of @@ -5628,28 +5697,45 @@ declare module ol { * @extends {ol.events.Event} * @constructor */ - constructor(type: string, selected: ol.Feature[], deselected: ol.Feature[], mapBrowserEvent: ol.MapBrowserEvent); - - /** - * Selected features array. - * @type {Array.} - * @api - */ - selected: ol.Feature[]; - - /** - * Deselected features array. - * @type {Array.} - * @api - */ - deselected: ol.Feature[]; - - /** - * Associated {@link ol.MapBrowserEvent}. - * @type {ol.MapBrowserEvent} - * @api - */ - mapBrowserEvent: ol.MapBrowserEvent; + class Event extends ol.events.Event { + /** + * @classdesc + * Events emitted by {@link ol.interaction.Select} instances are instances of + * this type. + * + * @param {string} type The event type. + * @param {Array.} selected Selected features. + * @param {Array.} deselected Deselected features. + * @param {ol.MapBrowserEvent} mapBrowserEvent Associated + * {@link ol.MapBrowserEvent}. + * @implements {oli.SelectEvent} + * @extends {ol.events.Event} + * @constructor + */ + constructor(type: string, selected: ol.Feature[], deselected: ol.Feature[], mapBrowserEvent: ol.MapBrowserEvent); + + /** + * Selected features array. + * @type {Array.} + * @api + */ + selected: ol.Feature[]; + + /** + * Deselected features array. + * @type {Array.} + * @api + */ + deselected: ol.Feature[]; + + /** + * Associated {@link ol.MapBrowserEvent}. + * @type {ol.MapBrowserEvent} + * @api + */ + mapBrowserEvent: ol.MapBrowserEvent; + + } } @@ -5798,18 +5884,9 @@ declare module ol { } /** - * @classdesc - * Events emitted by {@link ol.interaction.Translate} instances are instances of - * this type. - * - * @constructor - * @extends {ol.events.Event} - * @implements {oli.interaction.TranslateEvent} - * @param {ol.interaction.TranslateEventType} type Type. - * @param {ol.Collection.} features The features translated. - * @param {ol.Coordinate} coordinate The event coordinate. + * @namespace ol.interaction.Translate */ - class TranslateEvent extends ol.events.Event { + module Translate { /** * @classdesc * Events emitted by {@link ol.interaction.Translate} instances are instances of @@ -5822,22 +5899,37 @@ declare module ol { * @param {ol.Collection.} features The features translated. * @param {ol.Coordinate} coordinate The event coordinate. */ - constructor(type: ol.interaction.TranslateEventType, features: ol.Collection, coordinate: ol.Coordinate); - - /** - * The features being translated. - * @type {ol.Collection.} - * @api - */ - features: ol.Collection; - - /** - * The coordinate of the drag event. - * @const - * @type {ol.Coordinate} - * @api - */ - coordinate: ol.Coordinate; + class Event extends ol.events.Event { + /** + * @classdesc + * Events emitted by {@link ol.interaction.Translate} instances are instances of + * this type. + * + * @constructor + * @extends {ol.events.Event} + * @implements {oli.interaction.TranslateEvent} + * @param {ol.interaction.TranslateEventType} type Type. + * @param {ol.Collection.} features The features translated. + * @param {ol.Coordinate} coordinate The event coordinate. + */ + constructor(type: ol.interaction.TranslateEventType, features: ol.Collection, coordinate: ol.Coordinate); + + /** + * The features being translated. + * @type {ol.Collection.} + * @api + */ + features: ol.Collection; + + /** + * The coordinate of the drag event. + * @const + * @type {ol.Coordinate} + * @api + */ + coordinate: ol.Coordinate; + + } } @@ -6645,15 +6737,6 @@ declare module ol { */ addOverlay(overlay: ol.Overlay): void; - /** - * Add functions to be called before rendering. This can be used for attaching - * animations before updating the map's view. The {@link ol.animation} - * namespace provides several static methods for creating prerender functions. - * @param {...ol.PreRenderFunction} var_args Any number of pre-render functions. - * @api - */ - beforeRender(var_args: ol.PreRenderFunction): void; - /** * Detect features that intersect a pixel on the viewport, and execute a * callback with each intersecting feature. Layers included in the detection can @@ -7367,18 +7450,6 @@ declare module ol { * @api stable */ un(type: (string | string[]), listener: Function, opt_this?: GlobalObject): void; - - /** - * Removes an event listener using the key returned by `on()` or `once()`. - * Note that using the {@link ol.Observable.unByKey} static function is to - * be preferred. - * @param {ol.EventsKey|Array.} key The key returned by `on()` - * or `once()` (or an array of keys). - * @function - * @api stable - */ - unByKey(key: (ol.EventsKey | ol.EventsKey[])): void; - } /** @@ -7387,7 +7458,7 @@ declare module ol { * `'top-center'`, `'top-right'` * @enum {string} */ - type OverlayPositioning = "bottom-left" | "bottom-center" | "bottom-right" | "center-left" | "center-center" | "center-right" | "top-left" | "top-center" | "top-right"; + type OverlayPositioning = "bottom-left" | "bottom-center" | "bottom-right" | "center-left" | "center-center" | "center-right" | "top-left" | "top-center" | "top-right"; /** * @classdesc @@ -10563,7 +10634,7 @@ declare module ol { * @api */ setGeometry(geometry: (string | ol.geom.Geometry | ol.StyleGeometryFunction)): void; - + /** * Set the image style. * @param {ol.style.Image} image Image style. @@ -10577,7 +10648,7 @@ declare module ol { * @api */ setStroke(stroke: ol.style.Stroke): void; - + /** * Set the text style. * @param {ol.style.Text} text Text style. @@ -11672,11 +11743,10 @@ declare module ol { * In most cases you will want to use the map size, that is `map.getSize()`. * Takes care of the map angle. * @param {ol.geom.SimpleGeometry|ol.Extent} geometry Geometry. - * @param {ol.Size} size Box pixel size. * @param {olx.view.FitOptions=} opt_options Options. * @api */ - fit(geometry: (ol.geom.SimpleGeometry | ol.Extent), size: ol.Size, opt_options?: olx.view.FitOptions): void; + fit(geometry: (ol.geom.SimpleGeometry | ol.Extent), opt_options?: olx.view.FitOptions): void; /** * Center on coordinate and view position. @@ -11729,7 +11799,7 @@ declare module ol { /** * Animate the view. The view's center, zoom (or resolution), and * rotation can be animated for smooth transitions between view states. - * @param {olx.AnimateOptions} var_args Animation options. + * @param {olx.AnimateOptions} var_args Animation options. * @param {olx.AnimateOptions | (completed: boolean) => void } restArgs * @api experimental */ @@ -13535,6 +13605,7 @@ declare module olx { offsetX?: number; offsetY?: number; scale?: number; + rotateWithView?: boolean; rotation?: number; text?: string; textAlign?: string; @@ -13775,18 +13846,24 @@ declare module olx { module view { /** * @typedef {{ + * size: (ol.Size|undefined), * padding: (!Array.|undefined), * constrainResolution: (boolean|undefined), + * duration: (number|undefined), * nearest: (boolean|undefined), * maxZoom: (number|undefined), - * minResolution: (number|undefined)}} + * minResolution: (number|undefined), + * easing: (function(t: number) => number) }} */ interface FitOptions { + size?: ol.Size, padding?: number[]; constrainResolution?: boolean; nearest?: boolean; - maxZoom?: number; minResolution?: number; + maxZoom?: number; + duration?: number; + easing?: ((t: number) => number); } } @@ -13823,7 +13900,7 @@ declare module olx { zoom?: number; zoomFactor?: number; } - + /** * Object literal with options for the {@link ol.Map#forEachFeatureAtPixel} and * {@link ol.Map#hasFeatureAtPixel} methods. diff --git a/openlayers/openlayers-tests.ts b/openlayers/openlayers-tests.ts index 1add5f64ed..ca74a6bbc2 100644 --- a/openlayers/openlayers-tests.ts +++ b/openlayers/openlayers-tests.ts @@ -431,8 +431,6 @@ eventKeyMixed = observable.once(stringValue, fn); eventKeyMixed = observable.once([stringValue, stringValue], fn, {}); voidValue = observable.un(stringValue, fn); voidValue = observable.un([stringValue, stringValue], fn, {}); -voidValue = observable.unByKey(eventKey); -voidValue = observable.unByKey(eventKeyArray); // // ol.proj @@ -462,7 +460,6 @@ let map: ol.Map = new ol.Map({ layers: [tileLayer], target: stringValue }); -voidValue = map.beforeRender(preRenderFunction); // // ol.source.ImageWMS @@ -508,39 +505,6 @@ let wmts: ol.source.WMTS = new ol.source.WMTS({ wrapX: true, }); -// -// ol.animation -// -let bounceOptions: olx.animation.BounceOptions; -bounceOptions.duration = numberValue; -bounceOptions.start = numberValue; -bounceOptions.resolution = numberValue; -bounceOptions.easing = easingFunction; -preRenderFunction = ol.animation.bounce(bounceOptions); - -let panOptions: olx.animation.PanOptions; -panOptions.duration = numberValue; -panOptions.start = numberValue; -panOptions.source = coordinate; -panOptions.easing = easingFunction; -preRenderFunction = ol.animation.pan(panOptions); - -let rotateOptions: olx.animation.RotateOptions; -rotateOptions.duration = numberValue; -rotateOptions.start = numberValue; -rotateOptions.anchor = coordinate; -rotateOptions.rotation = numberValue; -rotateOptions.easing = easingFunction; -preRenderFunction = ol.animation.rotate(rotateOptions); - -let zoomOptions: olx.animation.ZoomOptions; -zoomOptions.duration = numberValue; -zoomOptions.start = numberValue; -zoomOptions.resolution = numberValue; -zoomOptions.easing = easingFunction; -preRenderFunction = ol.animation.zoom(zoomOptions); -voidValue = map.beforeRender(preRenderFunction); - // // ol.coordinate // diff --git a/openui5/openui5-tests.ts b/openui5/openui5-tests.ts index 8dc19922ee..bb411a9a1e 100644 --- a/openui5/openui5-tests.ts +++ b/openui5/openui5-tests.ts @@ -1,7 +1,3 @@ -/// -/// -/// - sap.ui.getCore().attachInit(function () { new sap.m.Text({ text: "Hello World" diff --git a/optics-agent/index.d.ts b/optics-agent/index.d.ts index ba1e930739..4d27ac71ae 100644 --- a/optics-agent/index.d.ts +++ b/optics-agent/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for optics-agent 1.0 +// Type definitions for optics-agent 1.1 // Project: https://github.com/apollostack/optics-agent-js#readme // Definitions by: Crevil // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,6 +6,7 @@ import { GraphQLSchema } from "graphql"; import { Request, Response } from "express"; import { Server } from "hapi"; +import { Context } from "koa"; export interface Options { /** @@ -57,6 +58,11 @@ export interface Options { * Send the query variables along with traces. Defaults to true. */ reportVariables?: boolean; + + /** + * Send statistics when the process exits. Defaults to true. + */ + shutdownGracefully?: boolean; } export class Agent { @@ -64,6 +70,7 @@ export class Agent { configureAgent(options: Options): Agent; instrumentSchema(schema: GraphQLSchema): void; + koaMiddleware(): (context: Context, next: () => Promise) => void; middleware(): (req: Request, res: Response, next?: any) => void; instrumentHapiServer(server: Server): void; context(req: Request): any; @@ -71,6 +78,7 @@ export class Agent { export function configureAgent(options: Options): Agent; export function instrumentSchema(schema: GraphQLSchema): void; +export function koaMiddleware(): (context: Context, next: () => Promise) => void; export function middleware(): (req: Request, res: Response, next?: any) => void; export function instrumentHapiServer(server: Server): void; export function context(req: Request): any; @@ -78,6 +86,7 @@ export function context(req: Request): any; export default { configureAgent, instrumentSchema, + koaMiddleware, middleware, instrumentHapiServer, context, diff --git a/optics-agent/optics-agent-tests.ts b/optics-agent/optics-agent-tests.ts index 758b374efa..cb4cb60051 100644 --- a/optics-agent/optics-agent-tests.ts +++ b/optics-agent/optics-agent-tests.ts @@ -4,12 +4,14 @@ import OpticsAgent, { middleware, instrumentHapiServer, context, + Options, } from 'optics-agent'; import { GraphQLSchema } from 'graphql'; import * as express from 'express'; import * as hapi from 'hapi'; +import * as KoaServer from 'koa'; -const configOptions = { +const configOptions: Options = { apiKey: "", reportTraces: false, reportVariables: false, @@ -18,6 +20,7 @@ const configOptions = { endpointUrl: "", proxyUrl: "", reportIntervalMs: 1, + shutdownGracefully: false, }; OpticsAgent.configureAgent(configOptions); @@ -27,6 +30,9 @@ expressServer.use(OpticsAgent.middleware()); const hapiServer = new hapi.Server(); OpticsAgent.instrumentHapiServer(hapiServer); +const koaServer = new KoaServer(); +koaServer.use(OpticsAgent.koaMiddleware()); + const req = {} as express.Request; OpticsAgent.context(req); diff --git a/optimize-css-assets-webpack-plugin/index.d.ts b/optimize-css-assets-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..af484b05d2 --- /dev/null +++ b/optimize-css-assets-webpack-plugin/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for optimize-css-assets-webpack-plugin 1.3 +// Project: https://github.com/NMFR/optimize-css-assets-webpack-plugin +// Definitions by: Armando Meziat +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Plugin } from 'webpack'; + +export = OptimizeCssAssetsPlugin; + +declare namespace OptimizeCssAssetsPlugin { + + export interface Options { + assetNameRegExp?: RegExp; + cssProcessor?: any; + cssProcessorOptions?: any; + canPrint?: boolean; + } + +} + +declare class OptimizeCssAssetsPlugin extends Plugin { + constructor(options?: OptimizeCssAssetsPlugin.Options); +} diff --git a/optimize-css-assets-webpack-plugin/optimize-css-assets-webpack-plugin-tests.ts b/optimize-css-assets-webpack-plugin/optimize-css-assets-webpack-plugin-tests.ts new file mode 100644 index 0000000000..74cf685649 --- /dev/null +++ b/optimize-css-assets-webpack-plugin/optimize-css-assets-webpack-plugin-tests.ts @@ -0,0 +1,6 @@ +import * as OptimizeCssAssets from 'optimize-css-assets-webpack-plugin'; + +const ocap: OptimizeCssAssets = new OptimizeCssAssets({ + assetNameRegExp: /\.min\.css$/, + canPrint: true +}); diff --git a/optimize-css-assets-webpack-plugin/tsconfig.json b/optimize-css-assets-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..8693d603ec --- /dev/null +++ b/optimize-css-assets-webpack-plugin/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "optimize-css-assets-webpack-plugin-tests.ts" + ] +} diff --git a/optimize-css-assets-webpack-plugin/tslint.json b/optimize-css-assets-webpack-plugin/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/optimize-css-assets-webpack-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/oracledb/oracledb-tests.ts b/oracledb/oracledb-tests.ts index 15446df243..b4d1cf5fe9 100644 --- a/oracledb/oracledb-tests.ts +++ b/oracledb/oracledb-tests.ts @@ -1,5 +1,3 @@ -/// - import * as OracleDB from 'oracledb'; OracleDB.getConnection( diff --git a/owlcarousel/owlcarousel-tests.ts b/owlcarousel/owlcarousel-tests.ts index 3d9ed9a69b..0d2e1b6118 100644 --- a/owlcarousel/owlcarousel-tests.ts +++ b/owlcarousel/owlcarousel-tests.ts @@ -1,6 +1,3 @@ -/// - - $(".className").owlCarousel(); $(".className").owlCarousel({ diff --git a/paper/index.d.ts b/paper/index.d.ts index e463d730c0..41b958fd50 100644 --- a/paper/index.d.ts +++ b/paper/index.d.ts @@ -285,7 +285,7 @@ declare module 'paper' { * Transforms a point and returns the result. * @param point - the point to be transformed */ - transform(point: Point): Matrix; + transform(point: Point): Point; /** * Transforms an array of coordinates by this matrix and stores the results into the destination array, which is also returned. @@ -299,7 +299,7 @@ declare module 'paper' { * Inverse transforms a point and returns the result. * @param point - the point to be transformed */ - inverseTransform(point: Point): Matrix; + inverseTransform(point: Point): Point; /** * Attempts to decompose the affine transformation described by this matrix into scaling, rotation and shearing, and returns an object with these properties if it succeeded, null otherwise. diff --git a/parse-unit/index.d.ts b/parse-unit/index.d.ts new file mode 100644 index 0000000000..238f3cfc06 --- /dev/null +++ b/parse-unit/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for parse-unit 1.0 +// Project: https://github.com/mattdesl/parse-unit +// Definitions by: Jack Works +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function parse(value: string): [number, string]; +export = parse; diff --git a/parse-unit/parse-unit-tests.ts b/parse-unit/parse-unit-tests.ts new file mode 100644 index 0000000000..772641c302 --- /dev/null +++ b/parse-unit/parse-unit-tests.ts @@ -0,0 +1,4 @@ +import parse = require('parse-unit') +let [number, length] = parse('10px') +number === 50 +length === 'px' diff --git a/parse-unit/tsconfig.json b/parse-unit/tsconfig.json new file mode 100644 index 0000000000..4f0a626508 --- /dev/null +++ b/parse-unit/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "parse-unit-tests.ts" + ] +} diff --git a/parse-unit/tslint.json b/parse-unit/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/parse-unit/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/passport-beam/passport-beam-tests.ts b/passport-beam/passport-beam-tests.ts index edfa3f1396..4448dad045 100644 --- a/passport-beam/passport-beam-tests.ts +++ b/passport-beam/passport-beam-tests.ts @@ -1,5 +1,3 @@ -/// - /** * Created by AtlasDev on 4/10/2016. */ diff --git a/passport-facebook/index.d.ts b/passport-facebook/index.d.ts index 4e84b4996b..320a2169ba 100644 --- a/passport-facebook/index.d.ts +++ b/passport-facebook/index.d.ts @@ -31,12 +31,31 @@ interface IStrategyOption { scopeSeparator?: string; enableProof?: boolean; profileFields?: string[]; - passReqToCallback?: boolean; +} + +interface IStrategyOptionWithRequest { + clientID: string; + clientSecret: string; + callbackURL: string; + + scopeSeparator?: string; + enableProof?: boolean; + profileFields?: string[]; + passReqToCallback: boolean; +} + +interface VerifyFunction { + (accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void): void; +} + +interface VerifyFunctionWithRequest { + (req: express.Request, accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void): void; } declare class Strategy implements passport.Strategy { - constructor(options: IStrategyOption, - verify: (accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void); + constructor(options: IStrategyOptionWithRequest, verify: VerifyFunctionWithRequest); + constructor(options: IStrategyOption, verify: VerifyFunction); + name: string; authenticate: (req: express.Request, options?: Object) => void; } diff --git a/passport-http/passport-http-tests.ts b/passport-http/passport-http-tests.ts index 22a486e6ec..4a70d30b89 100644 --- a/passport-http/passport-http-tests.ts +++ b/passport-http/passport-http-tests.ts @@ -1,5 +1,3 @@ -/// - /** * Created by Christophe Vidal */ diff --git a/paymentrequest/paymentrequest-tests.ts b/paymentrequest/paymentrequest-tests.ts index 62c2721bfb..c8772b115c 100644 --- a/paymentrequest/paymentrequest-tests.ts +++ b/paymentrequest/paymentrequest-tests.ts @@ -1,5 +1,3 @@ -/// - /// Code examples derived from /// https://developers.google.com/web/fundamentals/discovery-and-monetization/payment-request/ diff --git a/pdfkit/index.d.ts b/pdfkit/index.d.ts index 8bd1c7014e..053aa7f029 100644 --- a/pdfkit/index.d.ts +++ b/pdfkit/index.d.ts @@ -269,7 +269,7 @@ declare namespace PDFKit { new (options?: PDFDocumentOptions): PDFDocument; addPage(options?: PDFDocumentOptions): PDFDocument; - bufferedPageRanges(): { start: number; count: number }; + bufferedPageRange(): { start: number; count: number }; switchToPage(n?: number): PDFPage; flushPages(): void; ref(data: {}): PDFKitReference; diff --git a/peerjs/peerjs-tests.ts b/peerjs/peerjs-tests.ts index 373df3ba2f..2246e6a8fd 100644 --- a/peerjs/peerjs-tests.ts +++ b/peerjs/peerjs-tests.ts @@ -1,5 +1,3 @@ -/// - var peerByOption: PeerJs.Peer = new Peer({ key: 'peerKey', debug: 3, diff --git a/phantomcss/index.d.ts b/phantomcss/index.d.ts index 451c250372..688c706199 100644 --- a/phantomcss/index.d.ts +++ b/phantomcss/index.d.ts @@ -3,8 +3,8 @@ // Definitions by: Amaury Bauzac // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import { Casper } from 'casperjs'; /// +import { Casper } from 'casperjs'; declare global { namespace PhantomCSS { diff --git a/phantomcss/phantomcss-tests.ts b/phantomcss/phantomcss-tests.ts index 8478bbd323..ee16832fae 100644 --- a/phantomcss/phantomcss-tests.ts +++ b/phantomcss/phantomcss-tests.ts @@ -1,7 +1,3 @@ - -/// -/// - // phantomCSS 0.11.1 is based on resemblejs 1.2.1, phantomJS 1.9.2 , casperJS 1.1.0-DEV var options: PhantomCSS.PhantomCSSOptions = { @@ -39,8 +35,8 @@ var options: PhantomCSS.PhantomCSSOptions = { }); }, - fileNameGetter: function(root:string,filename:string){ - + fileNameGetter: function(root:string,filename:string){ + return root+filename; }, @@ -65,7 +61,7 @@ declare var phantomcss:PhantomCSS.PhantomCSS; phantomcss.turnOffAnimations(); phantomcss.init(options); -phantomcss.compareAll('exclude.test'); +phantomcss.compareAll('exclude.test'); phantomcss.compareMatched('include.test', 'exclude.test'); phantomcss.compareMatched( new RegExp('include.test'), new RegExp('exclude.test')); phantomcss.compareSession(); diff --git a/phonon/index.d.ts b/phonon/index.d.ts index bd41d448c8..ce07b5a19b 100644 --- a/phonon/index.d.ts +++ b/phonon/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Kévin SERIN // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace Phonon { /*** Main object ***/ @@ -28,7 +28,7 @@ declare namespace Phonon { popover(id?: string): PhononPopoverComponent; preloader(element: string | Element): PhononPreloaderComponent; tab(): PhononTabComponent; - autocomplete(input: Element | HTMLElement | string, o?: AwesompleteOptions): Awesomplete; + autocomplete(input: Element | HTMLElement | string, o?: Awesomplete.Options): Awesomplete; } interface PhononDeviceObject { os: string; diff --git a/phonon/phonon-tests.ts b/phonon/phonon-tests.ts index 0d5df50b4e..6b9851b642 100644 --- a/phonon/phonon-tests.ts +++ b/phonon/phonon-tests.ts @@ -1,5 +1,3 @@ -/// - // Code examples from http://phonon.quarkdev.com/docs/navigator phonon.options({ navigator: { @@ -19,23 +17,22 @@ phonon.options({ }); phonon.navigator().on({ - page: 'pagename', - content: 'content.html', - preventClose: false, - readyDelay: 1 -}, function(activity) { - activity.onCreate(function() {}); - activity.onReady(function() {}); - activity.onTransitionEnd(function() {}); - activity.onClose(function(self) {}); - activity.onHidden(function() {}); - activity.onHashChanged(function(req1, req2) {}); - activity.onTabChanged(function() {}) + page: 'pagename', + content: 'content.html', + preventClose: false, + readyDelay: 1 +}, activity => { + activity.onCreate(() => {}); + activity.onReady(() => {}); + activity.onTransitionEnd(() => {}); + activity.onClose(self => {}); + activity.onHidden(() => {}); + activity.onHashChanged((req1, req2) => {}); + activity.onTabChanged(() => {}); }); -phonon.navigator().onPage('home').addEvent('create', function () { -}); -phonon.navigator().onPage('home').addEvent('close', function (api) { +phonon.navigator().onPage('home').addEvent('create', () => {}); +phonon.navigator().onPage('home').addEvent('close', api => { api.close(); }); @@ -47,11 +44,11 @@ page = phonon.navigator().previousPage; let ev = document.createEvent(''); -document.on('pagecreated', function(event) { - console.log('global state pagecreated: ' + event.detail.page) +document.on('pagecreated', event => { + console.log('global state pagecreated: ' + event.detail.page); }); -document.on('pagehash', function(event) { - console.log('global state pagehash: ' + event.detail.page) +document.on('pagehash', event => { + console.log('global state pagehash: ' + event.detail.page); console.log(event.detail.req[0]); console.log(event.detail.req[1]); console.log(event.detail.req[2]); @@ -60,13 +57,13 @@ document.on('pagehash', function(event) { // Code examples from http://phonon.quarkdev.com/docs/i18n let element = document.createElement(''); phonon.i18n().bind(); -phonon.i18n().bind(function() {}); +phonon.i18n().bind(() => {}); phonon.i18n().bind(element); -phonon.i18n().bind(element, function() {}); +phonon.i18n().bind(element, () => {}); -phonon.i18n().getAll(function(json) {}); -phonon.i18n().get('my_key', function(value) {}); -phonon.i18n().get(['my_key_1', 'my_key_two'], function(values) {}); +phonon.i18n().getAll(json => {}); +phonon.i18n().get('my_key', value => {}); +phonon.i18n().get(['my_key_1', 'my_key_two'], values => {}); phonon.updateLocale('new-language'); phonon.i18n().setPreference("fr"); @@ -86,10 +83,10 @@ var req = phonon.ajax({ 'header-name1': 'value1', 'header-name2': 'value2' }, - success: function(res, xhr) { + success(res, xhr) { console.log(res); }, - error: function(res, flagError, xhr) { + error(res, flagError, xhr) { console.error(flagError); console.log(res); } @@ -104,14 +101,14 @@ let browsername: string = phonon.browser.name; let browserVersion: string = phonon.browser.version; // Code examples from http://phonon.quarkdev.com/docs/events -element.on('tap', function() {}); -phonon.onReady(function() {}); -document.querySelectorAll('.elements').on('tap', function() {}); +element.on('tap', () => {}); +phonon.onReady(() => {}); +document.querySelectorAll('.elements').on('tap', () => {}); -element.off('tap', function() {}); -document.querySelectorAll('.elements').off('tap', function() {}); +element.off('tap', () => {}); +document.querySelectorAll('.elements').off('tap', () => {}); -document.on('pageopened', function(evt) { +document.on('pageopened', evt => { console.log(evt.detail.page + ' is opened'); }); @@ -128,22 +125,22 @@ phonon.sidePanel('#side-panel-id').close(); // Code examples from http://phonon.quarkdev.com/docs/dialogs let pAlert = phonon.alert("text", "title", true, "textOk"); -pAlert.on('confirm', function() {}); +pAlert.on('confirm', () => {}); var pconfirm = phonon.confirm("text", "title", true, "textOk", "textCancel"); -pconfirm.on('confirm', function() {}) -pconfirm.on('cancel', function() {}); +pconfirm.on('confirm', () => {}); +pconfirm.on('cancel', () => {}); let pPrompt = phonon.prompt("text", "title", true, "textOk", "textCancel"); -pPrompt.on('confirm', function(inputValue) {}) -pPrompt.on('cancel', function() {}); +pPrompt.on('confirm', inputValue => {}); +pPrompt.on('cancel', () => {}); phonon.indicator("title", true); let myDialog = phonon.dialog('#my-dialog'); myDialog.open(); myDialog.close(); -myDialog.on('confirm', function() {}); +myDialog.on('confirm', () => {}); // Code examples from http://phonon.quarkdev.com/docs/notifications let notif = phonon.notif('Hello', 3000, true, 'CANCEL'); @@ -168,7 +165,7 @@ popover.setList([ value: 'tg' } ]); -popover.setList(['a', 'b', 'c'], function (item) { +popover.setList(['a', 'b', 'c'], item => { var text = typeof item === 'string' ? item : item.text; var value = typeof item === 'string' ? item : item.value; return '
            • ' + text + '
            • '; @@ -180,18 +177,18 @@ popover.attachButton(element, true); popover.openFrom('.button-for-popover'); popover.openFrom(element); -popover.onItemChanged(function (data) { - console.log('onItemChanged') - console.error(data) +popover.onItemChanged(data => { + console.log('onItemChanged'); + console.error(data); }); -element.on('itemchanged', function(event) { +element.on('itemchanged', event => { console.log(event.detail); }); popover = phonon.popover() .setList(['a', 'b', 'c']) .attachButton('.my-button', true) - .onItemChanged(function (data) { + .onItemChanged(data => { console.log(data); }).openFrom('.my-button'); @@ -220,39 +217,39 @@ phonon.options({ let app = phonon.navigator(); app.on({page: 'home', preventClose: false, content: null}); -app.on({page: 'pagetwo', preventClose: true, content: 'pagetwo.html', readyDelay: 1}, function(activity) { +app.on({page: 'pagetwo', preventClose: true, content: 'pagetwo.html', readyDelay: 1}, activity => { let action: string | null = null; - var onAction = function(evt: any) { + var onAction = (evt: any) => { var target = evt.target; action = 'ok'; - if(target.getAttribute('data-order') === 'order') { + if (target.getAttribute('data-order') === 'order') { phonon.alert('Thank you for your order!', 'Dear customer'); } else { phonon.alert('Your order has been canceled.', 'Dear customer'); } }; - activity.onCreate(function() { - let order = document.querySelector('.order'); + activity.onCreate(() => { + const order = document.querySelector('.order'); if (order != null) { order.on('tap', onAction); } - let cancel = document.querySelector('.cancel'); + const cancel = document.querySelector('.cancel'); if (cancel != null) { cancel.on('tap', onAction); } }); - activity.onClose(function(self) { - if(action !== null) { + activity.onClose(self => { + if (action !== null) { self.close(); } else { phonon.alert('Before leaving this page, you must perform an action.', 'Action required'); } }); - activity.onHidden(function() { + activity.onHidden(() => { action = null; }); - activity.onHashChanged(function(pizza) { - let pizzaElt = document.querySelector('.pizza'); + activity.onHashChanged(pizza => { + const pizzaElt = document.querySelector('.pizza'); if (pizzaElt != null) { pizzaElt.textContent = pizza; } @@ -262,66 +259,66 @@ app.start(); // Code example from http://phonon.quarkdev.com/App/public/phonon/kitchen-sink/index.html phonon.options({ - navigator: { - defaultPage: 'home', - animatePages: true, - templateRootDirectory: 'contents/', - enableBrowserBackButton: true // should be disabled on Cordova - }, - i18n: { - directory: 'lang/', - localeFallback: 'en', - localePreferred: 'en-US' - } + navigator: { + defaultPage: 'home', + animatePages: true, + templateRootDirectory: 'contents/', + enableBrowserBackButton: true // should be disabled on Cordova + }, + i18n: { + directory: 'lang/', + localeFallback: 'en', + localePreferred: 'en-US' + } }); var app2 = phonon.navigator(); app2.on({page: 'home', content: 'home.html'}); -app2.on({page: 'pagedialog', content: 'pagedialog.html'}, function(activity) { - activity.onCreate(function() { - let showAlert = document.querySelector('#show-alert'); - if (showAlert) { - showAlert.on('tap', function() { - phonon.alert('Example', 'Hello'); - }); - } +app2.on({page: 'pagedialog', content: 'pagedialog.html'}, activity => { + activity.onCreate(() => { + const showAlert = document.querySelector('#show-alert'); + if (showAlert) { + showAlert.on('tap', () => { + phonon.alert('Example', 'Hello'); + }); + } - let showConfirm = document.querySelector('#show-confirm'); - if (showConfirm) { - showConfirm.on('tap', function() { - let confirm = phonon.confirm('Example', 'Hello'); - confirm.on('confirm', function() { - phonon.alert('Confirmed!'); - }); - confirm.on('cancel', function(value) { - phonon.alert('Canceled!'); - }); - }); - } + const showConfirm = document.querySelector('#show-confirm'); + if (showConfirm) { + showConfirm.on('tap', () => { + const confirm = phonon.confirm('Example', 'Hello'); + confirm.on('confirm', () => { + phonon.alert('Confirmed!'); + }); + confirm.on('cancel', value => { + phonon.alert('Canceled!'); + }); + }); + } - let showPrompt = document.querySelector('#show-prompt'); - if (showPrompt) { - showPrompt.on('tap', function() { - var prompt = phonon.prompt('Example', 'Hello'); - prompt.on('confirm', function(value) { - phonon.alert(value, 'Inserted Value'); + const showPrompt = document.querySelector('#show-prompt'); + if (showPrompt) { + showPrompt.on('tap', () => { + var prompt = phonon.prompt('Example', 'Hello'); + prompt.on('confirm', value => { + phonon.alert(value, 'Inserted Value'); + }); + prompt.on('cancel', () => { + phonon.alert('Prompt Canceled'); + }); }); - prompt.on('cancel', function() { - phonon.alert('Prompt Canceled'); - }); - }); - } + } - let showIndicator = document.querySelector('#show-indicator'); - if (showIndicator) { - showIndicator.on('tap', function() { - let indicator = phonon.indicator('Please wait 3 seconds', false); - window.setTimeout(function() { - indicator.close(); - }, 3000); - }); - } - }); + const showIndicator = document.querySelector('#show-indicator'); + if (showIndicator) { + showIndicator.on('tap', () => { + const indicator = phonon.indicator('Please wait 3 seconds', false); + window.setTimeout(() => { + indicator.close(); + }, 3000); + }); + } + }); }); app2.on({page: 'pageform', content: 'pageform.html'}); @@ -331,69 +328,66 @@ app2.on({page: 'pagegrid', content: 'pagegrid.html'}); app2.on({page: 'pagelist', content: 'pagelist.html'}); app2.on({page: 'pageaccordion', content: 'pageaccordion.html'}); -app2.on({page: 'pagenotif', content: 'pagenotif.html', readyDelay: 500}, function(activity) { +app2.on({page: 'pagenotif', content: 'pagenotif.html', readyDelay: 500}, activity => { + activity.onCreate(() => { + const showAutoNotif = document.querySelector('#show-auto-notif'); + if (showAutoNotif) { + showAutoNotif.on('tap', () => { + phonon.notif('HELLO', 3000, false); + }); + } - activity.onCreate(function() { - let showAutoNotif = document.querySelector('#show-auto-notif'); - if (showAutoNotif) { - showAutoNotif.on('tap', function() { - phonon.notif('HELLO', 3000, false); - }); - } + const showNotif = document.querySelector('#show-notif'); + if (showNotif) { + showNotif.on('tap', () => { + phonon.notif('#notif-example').show(); + }); + } - let showNotif = document.querySelector('#show-notif'); - if (showNotif) { - showNotif.on('tap', function() { - phonon.notif('#notif-example').show(); - }); - } + const showNotifButton = document.querySelector('#show-notif-button'); + if (showNotifButton) { + showNotifButton.on('tap', () => { + phonon.notif('HELLO', 3000, true, 'Bye'); + }); + } + }); - let showNotifButton = document.querySelector('#show-notif-button'); - if (showNotifButton) { - showNotifButton.on('tap', function() { - phonon.notif('HELLO', 3000, true, 'Bye'); - }); - } - }); - - activity.onReady(function() { - phonon.notif('Welcome!', 3000, true); - - }); + activity.onReady(() => { + phonon.notif('Welcome!', 3000, true); + }); }); app2.on({page: 'pagepanel', content: 'pagepanel.html'}); app2.on({page: 'pagepopover', content: 'pagepopover.html'}); -app2.on({page: 'pagepreloader', content: 'pagepreloader.html'}, function(activity) { +app2.on({page: 'pagepreloader', content: 'pagepreloader.html'}, activity => { + activity.onReady(() => { + const myCircle = document.querySelector('#my-circle'); + if (myCircle) { + phonon.preloader(myCircle).show(); + } + const myDeterminate = document.querySelector('#my-determinate'); + if (myDeterminate) { + phonon.preloader(myDeterminate).show(); + } + }); - activity.onReady(function() { - let myCircle = document.querySelector('#my-circle'); - if (myCircle) { - phonon.preloader(myCircle).show(); - } - let myDeterminate = document.querySelector('#my-determinate'); - if (myDeterminate) { - phonon.preloader(myDeterminate).show(); - } - }); - - activity.onHidden(function() { - let myCircle = document.querySelector('#my-circle'); - if (myCircle) { - phonon.preloader(myCircle).hide(); - } - let myDeterminate = document.querySelector('#my-determinate'); - if (myDeterminate) { - phonon.preloader(myDeterminate).hide(); - } - }); + activity.onHidden(() => { + const myCircle = document.querySelector('#my-circle'); + if (myCircle) { + phonon.preloader(myCircle).hide(); + } + const myDeterminate = document.querySelector('#my-determinate'); + if (myDeterminate) { + phonon.preloader(myDeterminate).hide(); + } + }); }); app2.on({page: 'pagesidepanel', content: 'pagesidepanel.html'}); app2.on({page: 'pagetable', content: 'pagetable.html'}); -app2.on({page: 'pagetabs', content: 'pagetabs.html'}, function(activity) { - activity.onTabChanged(function(tabNumber) { - let tab = document.querySelector('.tab-number'); +app2.on({page: 'pagetabs', content: 'pagetabs.html'}, activity => { + activity.onTabChanged(tabNumber => { + const tab = document.querySelector('.tab-number'); if (tab) { tab.innerHTML = tabNumber + ""; } @@ -417,29 +411,27 @@ phonon.options({ }, i18n: null }); -phonon.navigator().on({ page: 'home' }, function(activity) { - activity.onReady(function(){ - // input where user typed words to query - let input = document.querySelector( '#searchJS' ); +phonon.navigator().on({ page: 'home' }, activity => { + activity.onReady(() => { + // input where user typed words to query + const input = document.querySelector( '#searchJS' ); let list = ''; // external autocomplete var req = phonon.ajax({ method: "GET", - url: 'https://restcountries.eu/rest/v1/lang/en', - dataType: "json", - success: function( res, xhr ){ - list = res.map( function(i: any){ - return i.name; - }); - // initialize autocomplete + url: 'https://restcountries.eu/rest/v1/lang/en', + dataType: "json", + success(res, xhr) { + list = res.map((i: any) => i.name); + // initialize autocomplete if (input) { - phonon.autocomplete( input, {list:list} ); + phonon.autocomplete(input, {list}); } - }, - error: function( res, flagError, xhr ){ + }, + error(res, flagError, xhr) { console.error(flagError); - console.log(res); - } + console.log(res); + } }); }); }); @@ -457,23 +449,23 @@ phonon.options({ }); let app3 = phonon.navigator(); -app3.on({page: 'home', content: null}, function(activity) { - activity.onCreate(function() { +app3.on({page: 'home', content: null}, activity => { + activity.onCreate(() => { let element = document.querySelector('#show-alert'); if (element) { - element.on('tap', function() { + element.on('tap', () => { phonon.alert('Example', 'Hello'); }); } element = document.querySelector('#show-confirm'); if (element) { - element.on('tap', function() { + element.on('tap', () => { var confirm = phonon.confirm('Example', 'Hello'); - confirm.on('confirm', function() { + confirm.on('confirm', () => { phonon.alert('Confirmed!'); }); - confirm.on('cancel', function(value) { + confirm.on('cancel', value => { phonon.alert('Canceled!'); }); }); @@ -481,12 +473,12 @@ app3.on({page: 'home', content: null}, function(activity) { element = document.querySelector('#show-prompt'); if (element) { - element.on('tap', function() { + element.on('tap', () => { var prompt = phonon.prompt('Example', 'Hello'); - prompt.on('confirm', function(value) { + prompt.on('confirm', value => { phonon.alert(value, 'Inserted Value'); }); - prompt.on('cancel', function() { + prompt.on('cancel', () => { phonon.alert('Prompt Canceled'); }); }); @@ -494,11 +486,11 @@ app3.on({page: 'home', content: null}, function(activity) { element = document.querySelector('#show-indicator'); if (element) { - element.on('tap', function() { + element.on('tap', () => { var indicator = phonon.indicator('Please wait 3 seconds', false); - window.setTimeout(function() { + window.setTimeout(() => { indicator.close(); - },3000); + }, 3000); }); } }); @@ -516,27 +508,27 @@ let elSetEnUs = document.querySelector('.set-en-us'); let defaultLocale = 'fr'; function setupHTML() { - let pref = (phonon.i18n().getPreference() ? phonon.i18n().getPreference() : 'not used'); - if (elPrefLang) { - elPrefLang.textContent = 'Preferred language : ' + pref; - } - if (elLang) { - elLang.textContent = 'Locale language : ' + phonon.i18n().getLocale(); - } - if (elDefault) { - elDefault.textContent = 'Default language : ' + defaultLocale; - } + const pref = (phonon.i18n().getPreference() ? phonon.i18n().getPreference() : 'not used'); + if (elPrefLang) { + elPrefLang.textContent = 'Preferred language : ' + pref; + } + if (elLang) { + elLang.textContent = 'Locale language : ' + phonon.i18n().getLocale(); + } + if (elDefault) { + elDefault.textContent = 'Default language : ' + defaultLocale; + } - // The parameter is optional, if you pass nothing, i18n will bind all the document - phonon.i18n().bind(); + // The parameter is optional, if you pass nothing, i18n will bind all the document + phonon.i18n().bind(); } -var setPreference = function (evt: any) { - var target = evt.target; - var lang = target.getAttribute('data-l'); - if(lang) { - phonon.updateLocale(lang); - } +var setPreference = (evt: any) => { + var target = evt.target; + var lang = target.getAttribute('data-l'); + if (lang) { + phonon.updateLocale(lang); + } }; if (elSetFr) { @@ -553,9 +545,9 @@ phonon.options({ defaultPage: 'home', }, i18n: { - directory: 'res/lang/', - localeFallback: defaultLocale, - localePreferred: 'en' + directory: 'res/lang/', + localeFallback: defaultLocale, + localePreferred: 'en' } }); setupHTML(); diff --git a/piwik-tracker/piwik-tracker-tests.ts b/piwik-tracker/piwik-tracker-tests.ts index 3e7506d5fd..f1545a843a 100644 --- a/piwik-tracker/piwik-tracker-tests.ts +++ b/piwik-tracker/piwik-tracker-tests.ts @@ -1,22 +1,20 @@ -/// - // Example code taken from https://www.npmjs.com/package/piwik-tracker var PiwikTracker = require('piwik-tracker'); - -// Initialize with your site ID and Piwik URL + +// Initialize with your site ID and Piwik URL var piwik = new PiwikTracker(1, 'http://mywebsite.com/piwik.php'); - -// Optional: Respond to tracking errors + +// Optional: Respond to tracking errors piwik.on('error', function(err : Error) { console.log('error tracking request: ', err) }) - -// Track a request URL: -// Either as a simple string … + +// Track a request URL: +// Either as a simple string … piwik.track('http://example.com/track/this/url'); - -// … or provide further options: + +// … or provide further options: piwik.track({ url: 'http://example.com/track/this/url', action_name: 'This will be shown in your dashboard', diff --git a/pixi-spine/index.d.ts b/pixi-spine/index.d.ts deleted file mode 100644 index deb614c749..0000000000 --- a/pixi-spine/index.d.ts +++ /dev/null @@ -1,1042 +0,0 @@ -// Type definitions for Pixi-spine 1.3 -// Project: https://github.com/pixijs/pixi-spine/tree/master -// Definitions by: Ivan Popelyshev -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -import * as PPP from "pixi.js"; - -declare module "pixi.js" { - namespace spine.core { - class Animation { - name: string; - timelines: Timeline[]; - duration: number; - constructor(name: string, timelines: Timeline[], duration: number); - apply(skeleton: Skeleton, lastTime: number, time: number, loop: boolean, events: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; - static binarySearch(values: ArrayLike, target: number, step?: number): number; - static linearSearch(values: ArrayLike, target: number, step: number): number; - } - interface Timeline { - apply(skeleton: Skeleton, lastTime: number, time: number, events: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; - getPropertyId(): number; - } - enum TimelineType { - rotate = 0, - translate = 1, - scale = 2, - shear = 3, - attachment = 4, - color = 5, - deform = 6, - event = 7, - drawOrder = 8, - ikConstraint = 9, - transformConstraint = 10, - pathConstraintPosition = 11, - pathConstraintSpacing = 12, - pathConstraintMix = 13, - } - abstract class CurveTimeline implements Timeline { - static LINEAR: number; - static STEPPED: number; - static BEZIER: number; - static BEZIER_SIZE: number; - private curves; - abstract getPropertyId(): number; - constructor(frameCount: number); - getFrameCount(): number; - setLinear(frameIndex: number): void; - setStepped(frameIndex: number): void; - getCurveType(frameIndex: number): number; - setCurve(frameIndex: number, cx1: number, cy1: number, cx2: number, cy2: number): void; - getCurvePercent(frameIndex: number, percent: number): number; - abstract apply(skeleton: Skeleton, lastTime: number, time: number, events: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; - } - class RotateTimeline extends CurveTimeline { - static ENTRIES: number; - static PREV_TIME: number; - static PREV_ROTATION: number; - static ROTATION: number; - boneIndex: number; - frames: ArrayLike; - constructor(frameCount: number); - getPropertyId(): number; - setFrame(frameIndex: number, time: number, degrees: number): void; - apply(skeleton: Skeleton, lastTime: number, time: number, events: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; - } - class TranslateTimeline extends CurveTimeline { - static ENTRIES: number; - static PREV_TIME: number; - static PREV_X: number; - static PREV_Y: number; - static X: number; - static Y: number; - boneIndex: number; - frames: ArrayLike; - constructor(frameCount: number); - getPropertyId(): number; - setFrame(frameIndex: number, time: number, x: number, y: number): void; - apply(skeleton: Skeleton, lastTime: number, time: number, events: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; - } - class ScaleTimeline extends TranslateTimeline { - constructor(frameCount: number); - getPropertyId(): number; - apply(skeleton: Skeleton, lastTime: number, time: number, events: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; - } - class ShearTimeline extends TranslateTimeline { - constructor(frameCount: number); - getPropertyId(): number; - apply(skeleton: Skeleton, lastTime: number, time: number, events: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; - } - class ColorTimeline extends CurveTimeline { - static ENTRIES: number; - static PREV_TIME: number; - static PREV_R: number; - static PREV_G: number; - static PREV_B: number; - static PREV_A: number; - static R: number; - static G: number; - static B: number; - static A: number; - slotIndex: number; - frames: ArrayLike; - constructor(frameCount: number); - getPropertyId(): number; - setFrame(frameIndex: number, time: number, r: number, g: number, b: number, a: number): void; - apply(skeleton: Skeleton, lastTime: number, time: number, events: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; - } - class AttachmentTimeline implements Timeline { - slotIndex: number; - frames: ArrayLike; - attachmentNames: string[]; - constructor(frameCount: number); - getPropertyId(): number; - getFrameCount(): number; - setFrame(frameIndex: number, time: number, attachmentName: string): void; - apply(skeleton: Skeleton, lastTime: number, time: number, events: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; - } - class DeformTimeline extends CurveTimeline { - slotIndex: number; - attachment: VertexAttachment; - frames: ArrayLike; - frameVertices: Array>; - constructor(frameCount: number); - getPropertyId(): number; - setFrame(frameIndex: number, time: number, vertices: ArrayLike): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; - } - class EventTimeline implements Timeline { - frames: ArrayLike; - events: Event[]; - constructor(frameCount: number); - getPropertyId(): number; - getFrameCount(): number; - setFrame(frameIndex: number, event: Event): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; - } - class DrawOrderTimeline implements Timeline { - frames: ArrayLike; - drawOrders: number[][]; - constructor(frameCount: number); - getPropertyId(): number; - getFrameCount(): number; - setFrame(frameIndex: number, time: number, drawOrder: number[]): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; - } - class IkConstraintTimeline extends CurveTimeline { - static ENTRIES: number; - static PREV_TIME: number; - static PREV_MIX: number; - static PREV_BEND_DIRECTION: number; - static MIX: number; - static BEND_DIRECTION: number; - ikConstraintIndex: number; - frames: ArrayLike; - constructor(frameCount: number); - getPropertyId(): number; - setFrame(frameIndex: number, time: number, mix: number, bendDirection: number): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; - } - class TransformConstraintTimeline extends CurveTimeline { - static ENTRIES: number; - static PREV_TIME: number; - static PREV_ROTATE: number; - static PREV_TRANSLATE: number; - static PREV_SCALE: number; - static PREV_SHEAR: number; - static ROTATE: number; - static TRANSLATE: number; - static SCALE: number; - static SHEAR: number; - transformConstraintIndex: number; - frames: ArrayLike; - constructor(frameCount: number); - getPropertyId(): number; - setFrame(frameIndex: number, time: number, rotateMix: number, translateMix: number, scaleMix: number, shearMix: number): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; - } - class PathConstraintPositionTimeline extends CurveTimeline { - static ENTRIES: number; - static PREV_TIME: number; - static PREV_VALUE: number; - static VALUE: number; - pathConstraintIndex: number; - frames: ArrayLike; - constructor(frameCount: number); - getPropertyId(): number; - setFrame(frameIndex: number, time: number, value: number): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; - } - class PathConstraintSpacingTimeline extends PathConstraintPositionTimeline { - constructor(frameCount: number); - getPropertyId(): number; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; - } - class PathConstraintMixTimeline extends CurveTimeline { - static ENTRIES: number; - static PREV_TIME: number; - static PREV_ROTATE: number; - static PREV_TRANSLATE: number; - static ROTATE: number; - static TRANSLATE: number; - pathConstraintIndex: number; - frames: ArrayLike; - constructor(frameCount: number); - getPropertyId(): number; - setFrame(frameIndex: number, time: number, rotateMix: number, translateMix: number): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; - } - } - namespace spine.core { - class AnimationState { - static emptyAnimation: Animation; - data: AnimationStateData; - tracks: TrackEntry[]; - events: Event[]; - listeners: AnimationStateListener2[]; - queue: EventQueue; - propertyIDs: IntSet; - animationsChanged: boolean; - timeScale: number; - trackEntryPool: Pool; - constructor(data: AnimationStateData); - update(delta: number): void; - updateMixingFrom(entry: TrackEntry, delta: number, canEnd: boolean): void; - apply(skeleton: Skeleton): void; - applyMixingFrom(entry: TrackEntry, skeleton: Skeleton): number; - applyRotateTimeline(timeline: Timeline, skeleton: Skeleton, time: number, alpha: number, setupPose: boolean, timelinesRotation: number[], i: number, firstFrame: boolean): void; - queueEvents(entry: TrackEntry, animationTime: number): void; - clearTracks(): void; - clearTrack(trackIndex: number): void; - setCurrent(index: number, current: TrackEntry): void; - setAnimation(trackIndex: number, animationName: string, loop: boolean): TrackEntry; - setAnimationWith(trackIndex: number, animation: Animation, loop: boolean): TrackEntry; - addAnimation(trackIndex: number, animationName: string, loop: boolean, delay: number): TrackEntry; - addAnimationWith(trackIndex: number, animation: Animation, loop: boolean, delay: number): TrackEntry; - setEmptyAnimation(trackIndex: number, mixDuration: number): TrackEntry; - addEmptyAnimation(trackIndex: number, mixDuration: number, delay: number): TrackEntry; - setEmptyAnimations(mixDuration: number): void; - expandToIndex(index: number): TrackEntry; - trackEntry(trackIndex: number, animation: Animation, loop: boolean, last: TrackEntry): TrackEntry; - disposeNext(entry: TrackEntry): void; - _animationsChanged(): void; - setTimelinesFirst(entry: TrackEntry): void; - checkTimelinesFirst(entry: TrackEntry): void; - checkTimelinesUsage(entry: TrackEntry, usageArray: boolean[]): void; - getCurrent(trackIndex: number): TrackEntry; - addListener(listener: AnimationStateListener2): void; - removeListener(listener: AnimationStateListener2): void; - clearListeners(): void; - clearListenerNotifications(): void; - onComplete: (trackIndex: number, loopCount: number) => any; - onEvent: (trackIndex: number, event: Event) => any; - onStart: (trackIndex: number) => any; - onEnd: (trackIndex: number) => any; - private static deprecatedWarning1; - setAnimationByName(trackIndex: number, animationName: string, loop: boolean): void; - private static deprecatedWarning2; - addAnimationByName(trackIndex: number, animationName: string, loop: boolean, delay: number): void; - private static deprecatedWarning3; - hasAnimationByName(animationName: string): boolean; - } - class TrackEntry { - animation: Animation; - next: TrackEntry; - mixingFrom: TrackEntry; - listener: AnimationStateListener2; - trackIndex: number; - loop: boolean; - eventThreshold: number; - attachmentThreshold: number; - drawOrderThreshold: number; - animationStart: number; - animationEnd: number; - animationLast: number; - nextAnimationLast: number; - delay: number; - trackTime: number; - trackLast: number; - nextTrackLast: number; - trackEnd: number; - timeScale: number; - alpha: number; - mixTime: number; - mixDuration: number; - mixAlpha: number; - timelinesFirst: boolean[]; - timelinesRotation: number[]; - reset(): void; - getAnimationTime(): number; - setAnimationLast(animationLast: number): void; - isComplete(): boolean; - resetRotationDirections(): void; - onComplete: (trackIndex: number, loopCount: number) => any; - onEvent: (trackIndex: number, event: Event) => any; - onStart: (trackIndex: number) => any; - onEnd: (trackIndex: number) => any; - private static deprecatedWarning1; - private static deprecatedWarning2; - time: number; - endTime: number; - loopsCount(): number; - } - class EventQueue { - objects: any[]; - drainDisabled: boolean; - animState: AnimationState; - constructor(animState: AnimationState); - start(entry: TrackEntry): void; - interrupt(entry: TrackEntry): void; - end(entry: TrackEntry): void; - dispose(entry: TrackEntry): void; - complete(entry: TrackEntry): void; - event(entry: TrackEntry, event: Event): void; - private static deprecatedWarning1; - deprecateStuff(): boolean; - drain(): void; - clear(): void; - } - enum EventType { - start = 0, - interrupt = 1, - end = 2, - dispose = 3, - complete = 4, - event = 5, - } - interface AnimationStateListener2 { - start(entry: TrackEntry): void; - interrupt(entry: TrackEntry): void; - end(entry: TrackEntry): void; - dispose(entry: TrackEntry): void; - complete(entry: TrackEntry): void; - event(entry: TrackEntry, event: Event): void; - } - abstract class AnimationStateAdapter2 implements AnimationStateListener2 { - start(entry: TrackEntry): void; - interrupt(entry: TrackEntry): void; - end(entry: TrackEntry): void; - dispose(entry: TrackEntry): void; - complete(entry: TrackEntry): void; - event(entry: TrackEntry, event: Event): void; - } - } - namespace spine.core { - class AnimationStateData { - skeletonData: SkeletonData; - animationToMixTime: Map; - defaultMix: number; - constructor(skeletonData: SkeletonData); - setMix(fromName: string, toName: string, duration: number): void; - private static deprecatedWarning1; - setMixByName(fromName: string, toName: string, duration: number): void; - setMixWith(from: Animation, to: Animation, duration: number): void; - getMix(from: Animation, to: Animation): number; - } - } - namespace spine.core { - class AtlasAttachmentLoader implements AttachmentLoader { - atlas: TextureAtlas; - constructor(atlas: TextureAtlas); - newRegionAttachment(skin: Skin, name: string, path: string): RegionAttachment; - newMeshAttachment(skin: Skin, name: string, path: string): MeshAttachment; - newBoundingBoxAttachment(skin: Skin, name: string): BoundingBoxAttachment; - newPathAttachment(skin: Skin, name: string): PathAttachment; - } - } - namespace spine.core { - abstract class Attachment { - name: string; - constructor(name: string); - } - abstract class VertexAttachment extends Attachment { - bones: number[]; - vertices: ArrayLike; - worldVerticesLength: number; - constructor(name: string); - computeWorldVertices(slot: Slot, worldVertices: ArrayLike): void; - computeWorldVerticesWith(slot: Slot, start: number, count: number, worldVertices: ArrayLike, offset: number): void; - applyDeform(sourceAttachment: VertexAttachment): boolean; - } - } - namespace spine.core { - interface AttachmentLoader { - newRegionAttachment(skin: Skin, name: string, path: string): RegionAttachment; - newMeshAttachment(skin: Skin, name: string, path: string): MeshAttachment; - newBoundingBoxAttachment(skin: Skin, name: string): BoundingBoxAttachment; - newPathAttachment(skin: Skin, name: string): PathAttachment; - } - } - namespace spine.core { - enum AttachmentType { - Region = 0, - BoundingBox = 1, - Mesh = 2, - LinkedMesh = 3, - Path = 4, - } - } - namespace spine.core { - class BoundingBoxAttachment extends VertexAttachment { - color: Color; - constructor(name: string); - } - } - namespace spine.core { - class MeshAttachment extends VertexAttachment { - region: TextureRegion; - path: string; - regionUVs: ArrayLike; - triangles: number[]; - color: Color; - hullLength: number; - private parentMesh; - inheritDeform: boolean; - tempColor: Color; - constructor(name: string); - updateWorldVertices(slot: Slot, premultipliedAlpha: boolean): ArrayLike; - updateUVs(region: TextureRegion, uvs: ArrayLike): ArrayLike; - applyDeform(sourceAttachment: VertexAttachment): boolean; - getParentMesh(): MeshAttachment; - setParentMesh(parentMesh: MeshAttachment): void; - } - } - namespace spine.core { - class PathAttachment extends VertexAttachment { - lengths: number[]; - closed: boolean; - constantSpeed: boolean; - color: Color; - constructor(name: string); - } - } - namespace spine.core { - class RegionAttachment extends Attachment { - x: number; - y: number; - scaleX: number; - scaleY: number; - rotation: number; - width: number; - height: number; - color: Color; - path: string; - region: TextureRegion; - constructor(name: string); - updateWorldVertices(slot: Slot, premultipliedAlpha: boolean): ArrayLike; - } - } - namespace spine.core { - enum BlendMode { - Normal = 0, - Additive = 1, - Multiply = 2, - Screen = 3, - } - } - namespace spine.core { - class Bone implements Updatable { - static yDown: boolean; - matrix: Matrix; - readonly worldX: number; - readonly worldY: number; - data: BoneData; - skeleton: Skeleton; - parent: Bone; - children: Bone[]; - x: number; - y: number; - rotation: number; - scaleX: number; - scaleY: number; - shearX: number; - shearY: number; - ax: number; - ay: number; - arotation: number; - ascaleX: number; - ascaleY: number; - ashearX: number; - ashearY: number; - appliedValid: boolean; - sorted: boolean; - constructor(data: BoneData, skeleton: Skeleton, parent: Bone); - update(): void; - updateWorldTransform(): void; - updateWorldTransformWith(x: number, y: number, rotation: number, scaleX: number, scaleY: number, shearX: number, shearY: number): void; - setToSetupPose(): void; - getWorldRotationX(): number; - getWorldRotationY(): number; - getWorldScaleX(): number; - getWorldScaleY(): number; - worldToLocalRotationX(): number; - worldToLocalRotationY(): number; - rotateWorld(degrees: number): void; - updateAppliedTransform(): void; - worldToLocal(world: Vector2): Vector2; - localToWorld(local: Vector2): Vector2; - } - } - namespace spine.core { - class BoneData { - index: number; - name: string; - parent: BoneData; - length: number; - x: number; - y: number; - rotation: number; - scaleX: number; - scaleY: number; - shearX: number; - shearY: number; - transformMode: TransformMode; - constructor(index: number, name: string, parent: BoneData); - } - enum TransformMode { - Normal = 0, - OnlyTranslation = 1, - NoRotationOrReflection = 2, - NoScale = 3, - NoScaleOrReflection = 4, - } - } - namespace spine.core { - interface Constraint extends Updatable { - getOrder(): number; - } - } - namespace spine.core { - class Event { - data: EventData; - intValue: number; - floatValue: number; - stringValue: string; - time: number; - constructor(time: number, data: EventData); - } - } - namespace spine.core { - class EventData { - name: string; - intValue: number; - floatValue: number; - stringValue: string; - constructor(name: string); - } - } - namespace spine.core { - class IkConstraint implements Constraint { - data: IkConstraintData; - bones: Bone[]; - target: Bone; - mix: number; - bendDirection: number; - level: number; - constructor(data: IkConstraintData, skeleton: Skeleton); - getOrder(): number; - apply(): void; - update(): void; - apply1(bone: Bone, targetX: number, targetY: number, alpha: number): void; - apply2(parent: Bone, child: Bone, targetX: number, targetY: number, bendDir: number, alpha: number): void; - } - } - namespace spine.core { - class IkConstraintData { - name: string; - order: number; - bones: BoneData[]; - target: BoneData; - bendDirection: number; - mix: number; - constructor(name: string); - } - } - namespace spine.core { - class PathConstraint implements Constraint { - static NONE: number; - static BEFORE: number; - static AFTER: number; - data: PathConstraintData; - bones: Bone[]; - target: Slot; - position: number; - spacing: number; - rotateMix: number; - translateMix: number; - spaces: number[]; - positions: number[]; - world: number[]; - curves: number[]; - lengths: number[]; - segments: number[]; - constructor(data: PathConstraintData, skeleton: Skeleton); - apply(): void; - update(): void; - computeWorldPositions(path: PathAttachment, spacesCount: number, tangents: boolean, percentPosition: boolean, percentSpacing: boolean): number[]; - addBeforePosition(p: number, temp: number[], i: number, out: number[], o: number): void; - addAfterPosition(p: number, temp: number[], i: number, out: number[], o: number): void; - addCurvePosition(p: number, x1: number, y1: number, cx1: number, cy1: number, cx2: number, cy2: number, x2: number, y2: number, out: number[], o: number, tangents: boolean): void; - getOrder(): number; - } - } - namespace spine.core { - class PathConstraintData { - name: string; - order: number; - bones: BoneData[]; - target: SlotData; - positionMode: PositionMode; - spacingMode: SpacingMode; - rotateMode: RotateMode; - offsetRotation: number; - position: number; - spacing: number; - rotateMix: number; - translateMix: number; - constructor(name: string); - } - enum PositionMode { - Fixed = 0, - Percent = 1, - } - enum SpacingMode { - Length = 0, - Fixed = 1, - Percent = 2, - } - enum RotateMode { - Tangent = 0, - Chain = 1, - ChainScale = 2, - } - } - namespace spine.core { - class Skeleton { - data: SkeletonData; - bones: Bone[]; - slots: Slot[]; - drawOrder: Slot[]; - ikConstraints: IkConstraint[]; - transformConstraints: TransformConstraint[]; - pathConstraints: PathConstraint[]; - _updateCache: Updatable[]; - updateCacheReset: Updatable[]; - skin: Skin; - color: Color; - time: number; - flipX: boolean; - flipY: boolean; - x: number; - y: number; - constructor(data: SkeletonData); - updateCache(): void; - sortIkConstraint(constraint: IkConstraint): void; - sortPathConstraint(constraint: PathConstraint): void; - sortTransformConstraint(constraint: TransformConstraint): void; - sortPathConstraintAttachment(skin: Skin, slotIndex: number, slotBone: Bone): void; - sortPathConstraintAttachmentWith(attachment: Attachment, slotBone: Bone): void; - sortBone(bone: Bone): void; - sortReset(bones: Bone[]): void; - updateWorldTransform(): void; - setToSetupPose(): void; - setBonesToSetupPose(): void; - setSlotsToSetupPose(): void; - getRootBone(): Bone; - findBone(boneName: string): Bone; - findBoneIndex(boneName: string): number; - findSlot(slotName: string): Slot; - findSlotIndex(slotName: string): number; - setSkinByName(skinName: string): void; - setSkin(newSkin: Skin): void; - getAttachmentByName(slotName: string, attachmentName: string): Attachment; - getAttachment(slotIndex: number, attachmentName: string): Attachment; - setAttachment(slotName: string, attachmentName: string): void; - findIkConstraint(constraintName: string): IkConstraint; - findTransformConstraint(constraintName: string): TransformConstraint; - findPathConstraint(constraintName: string): PathConstraint; - getBounds(offset: Vector2, size: Vector2): void; - update(delta: number): void; - } - } - namespace spine.core { - class SkeletonBounds { - minX: number; - minY: number; - maxX: number; - maxY: number; - boundingBoxes: BoundingBoxAttachment[]; - polygons: Array>; - private polygonPool; - update(skeleton: Skeleton, updateAabb: boolean): void; - aabbCompute(): void; - aabbContainsPoint(x: number, y: number): boolean; - aabbIntersectsSegment(x1: number, y1: number, x2: number, y2: number): boolean; - aabbIntersectsSkeleton(bounds: SkeletonBounds): boolean; - containsPoint(x: number, y: number): BoundingBoxAttachment; - containsPointPolygon(polygon: ArrayLike, x: number, y: number): boolean; - intersectsSegment(x1: number, y1: number, x2: number, y2: number): BoundingBoxAttachment; - intersectsSegmentPolygon(polygon: ArrayLike, x1: number, y1: number, x2: number, y2: number): boolean; - getPolygon(boundingBox: BoundingBoxAttachment): ArrayLike; - getWidth(): number; - getHeight(): number; - } - } - namespace spine.core { - class SkeletonData { - name: string; - bones: BoneData[]; - slots: SlotData[]; - skins: Skin[]; - defaultSkin: Skin; - events: EventData[]; - animations: Animation[]; - ikConstraints: IkConstraintData[]; - transformConstraints: TransformConstraintData[]; - pathConstraints: PathConstraintData[]; - width: number; - height: number; - version: string; - hash: string; - fps: number; - imagesPath: string; - findBone(boneName: string): BoneData; - findBoneIndex(boneName: string): number; - findSlot(slotName: string): SlotData; - findSlotIndex(slotName: string): number; - findSkin(skinName: string): Skin; - findEvent(eventDataName: string): EventData; - findAnimation(animationName: string): Animation; - findIkConstraint(constraintName: string): IkConstraintData; - findTransformConstraint(constraintName: string): TransformConstraintData; - findPathConstraint(constraintName: string): PathConstraintData; - findPathConstraintIndex(pathConstraintName: string): number; - } - } - namespace spine.core { - class SkeletonJson { - attachmentLoader: AttachmentLoader; - scale: number; - private linkedMeshes; - constructor(attachmentLoader: AttachmentLoader); - readSkeletonData(json: string | any): SkeletonData; - readAttachment(map: any, skin: Skin, slotIndex: number, name: string): Attachment; - readVertices(map: any, attachment: VertexAttachment, verticesLength: number): void; - readAnimation(map: any, name: string, skeletonData: SkeletonData): void; - readCurve(map: any, timeline: CurveTimeline, frameIndex: number): void; - getValue(map: any, prop: string, defaultValue: any): any; - static blendModeFromString(str: string): number; - static positionModeFromString(str: string): PositionMode; - static spacingModeFromString(str: string): SpacingMode; - static rotateModeFromString(str: string): RotateMode; - static transformModeFromString(str: string): TransformMode; - static transformModeLegacy(inheritRotation: boolean, inheritScale: boolean): TransformMode; - } - } - namespace spine.core { - class Skin { - name: string; - attachments: Array>; - constructor(name: string); - addAttachment(slotIndex: number, name: string, attachment: Attachment): void; - getAttachment(slotIndex: number, name: string): Attachment; - attachAll(skeleton: Skeleton, oldSkin: Skin): void; - } - } - namespace spine.core { - class Slot { - currentMesh: any; - currentSprite: any; - meshes: any; - currentMeshName: string; - sprites: any; - currentSpriteName: string; - blendMode: number; - tempRegion: TextureRegion; - tempAttachment: Attachment; - data: SlotData; - bone: Bone; - color: Color; - attachment: Attachment; - private attachmentTime; - attachmentVertices: number[]; - constructor(data: SlotData, bone: Bone); - getAttachment(): Attachment; - setAttachment(attachment: Attachment): void; - setAttachmentTime(time: number): void; - getAttachmentTime(): number; - setToSetupPose(): void; - } - } - namespace spine.core { - class SlotData { - index: number; - name: string; - boneData: BoneData; - color: Color; - attachmentName: string; - blendMode: number; - constructor(index: number, name: string, boneData: BoneData); - } - } - namespace spine.core { - abstract class Texture { - protected _image: HTMLImageElement; - constructor(image: HTMLImageElement); - getImage(): HTMLImageElement; - abstract setFilters(minFilter: TextureFilter, magFilter: TextureFilter): void; - abstract setWraps(uWrap: TextureWrap, vWrap: TextureWrap): void; - abstract dispose(): void; - static filterFromString(text: string): TextureFilter; - static wrapFromString(text: string): TextureWrap; - } - enum TextureFilter { - Nearest = 9728, - Linear = 9729, - MipMap = 9987, - MipMapNearestNearest = 9984, - MipMapLinearNearest = 9985, - MipMapNearestLinear = 9986, - MipMapLinearLinear = 9987, - } - enum TextureWrap { - MirroredRepeat = 33648, - ClampToEdge = 33071, - Repeat = 10497, - } - class TextureRegion { - texture: Texture; - size: Rectangle; - readonly width: number; - readonly height: number; - readonly u: number; - readonly v: number; - readonly u2: number; - readonly v2: number; - readonly offsetX: number; - readonly offsetY: number; - readonly pixiOffsetY: number; - readonly spineOffsetY: number; - readonly originalWidth: number; - readonly originalHeight: number; - readonly x: number; - readonly y: number; - readonly rotate: boolean; - } - } - namespace spine.core { - class TextureAtlas implements Disposable { - pages: TextureAtlasPage[]; - regions: TextureAtlasRegion[]; - constructor(atlasText: string, textureLoader: (path: string, loaderFunction: (tex: BaseTexture) => any) => any, callback: (obj: TextureAtlas) => any); - addTexture(name: string, texture: Texture): TextureAtlasRegion; - addTextureHash(textures: Map, stripExtension: boolean): void; - addSpineAtlas(atlasText: string, textureLoader: (path: string, loaderFunction: (tex: BaseTexture) => any) => any, callback: (obj: TextureAtlas) => any): void; - private load(atlasText, textureLoader, callback); - findRegion(name: string): TextureAtlasRegion; - dispose(): void; - } - class TextureAtlasPage { - name: string; - minFilter: TextureFilter; - magFilter: TextureFilter; - uWrap: TextureWrap; - vWrap: TextureWrap; - baseTexture: BaseTexture; - width: number; - height: number; - setFilters(): void; - } - class TextureAtlasRegion extends TextureRegion { - page: TextureAtlasPage; - name: string; - index: number; - } - } - namespace spine.core { - class TransformConstraint implements Constraint { - data: TransformConstraintData; - bones: Bone[]; - target: Bone; - rotateMix: number; - translateMix: number; - scaleMix: number; - shearMix: number; - temp: Vector2; - constructor(data: TransformConstraintData, skeleton: Skeleton); - apply(): void; - update(): void; - getOrder(): number; - } - } - namespace spine.core { - class TransformConstraintData { - name: string; - order: number; - bones: BoneData[]; - target: BoneData; - rotateMix: number; - translateMix: number; - scaleMix: number; - shearMix: number; - offsetRotation: number; - offsetX: number; - offsetY: number; - offsetScaleX: number; - offsetScaleY: number; - offsetShearY: number; - constructor(name: string); - } - } - namespace spine.core { - interface Updatable { - update(): void; - } - } - namespace spine.core { - interface Map { - [key: string]: T; - } - class IntSet { - array: number[]; - add(value: number): boolean; - contains(value: number): boolean; - remove(value: number): void; - clear(): void; - } - interface Disposable { - dispose(): void; - } - class Color { - r: number; - g: number; - b: number; - a: number; - static WHITE: Color; - static RED: Color; - static GREEN: Color; - static BLUE: Color; - static MAGENTA: Color; - constructor(r?: number, g?: number, b?: number, a?: number); - set(r: number, g: number, b: number, a: number): this; - setFromColor(c: Color): this; - setFromString(hex: string): this; - add(r: number, g: number, b: number, a: number): this; - clamp(): this; - } - class MathUtils { - static PI: number; - static PI2: number; - static radiansToDegrees: number; - static radDeg: number; - static degreesToRadians: number; - static degRad: number; - static clamp(value: number, min: number, max: number): number; - static cosDeg(degrees: number): number; - static sinDeg(degrees: number): number; - static signum(value: number): number; - static toInt(x: number): number; - static cbrt(x: number): number; - } - class Utils { - static SUPPORTS_TYPED_ARRAYS: boolean; - static arrayCopy(source: ArrayLike, sourceStart: number, dest: ArrayLike, destStart: number, numElements: number): void; - static setArraySize(array: T[], size: number, value?: any): T[]; - static ensureArrayCapacity(array: T[], size: number, value?: any): T[]; - static newArray(size: number, defaultValue: T): T[]; - static newFloatArray(size: number): ArrayLike; - static toFloatArray(array: number[]): number[] | Float32Array; - } - class DebugUtils { - static logBones(skeleton: Skeleton): void; - } - class Pool { - private items; - private instantiator; - constructor(instantiator: () => T); - obtain(): T; - free(item: T): void; - freeAll(items: ArrayLike): void; - clear(): void; - } - class Vector2 { - x: number; - y: number; - constructor(x?: number, y?: number); - set(x: number, y: number): Vector2; - length(): number; - normalize(): this; - } - class TimeKeeper { - maxDelta: number; - framesPerSecond: number; - delta: number; - totalTime: number; - private lastTime; - private frameCount; - private frameTime; - update(): void; - } - interface ArrayLike { - length: number; - [n: number]: T; - } - } - namespace spine { - function atlasParser(): (resource: loaders.Resource, next: () => any) => any; - function imageLoaderAdapter(loader: any, namePrefix: any, baseUrl: any, imageOptions: any): (line: string, callback: (baseTexture: BaseTexture) => any) => void; - function syncImageLoaderAdapter(baseUrl: any, crossOrigin: any): (line: any, callback: any) => void; - } - namespace spine { - class SpineSprite extends Sprite { - region: core.TextureRegion; - constructor(tex: Texture); - } - class SpineMesh extends mesh.Mesh { - region: core.TextureRegion; - constructor(texture: Texture, vertices?: Float32Array, uvs?: Float32Array, indices?: Uint16Array, drawMode?: number); - } - class Spine extends Container { - static globalAutoUpdate: boolean; - tintRgb: ArrayLike; - spineData: core.SkeletonData; - skeleton: core.Skeleton; - stateData: core.AnimationStateData; - state: core.AnimationState; - slotContainers: Container[]; - constructor(spineData: core.SkeletonData); - autoUpdate: boolean; - tint: number; - update(dt: number): void; - private setSpriteRegion(attachment, sprite, region); - private setMeshRegion(attachment, mesh, region); - protected lastTime: number; - autoUpdateTransform(): void; - createSprite(slot: core.Slot, attachment: core.RegionAttachment, defName: string): SpineSprite; - createMesh(slot: core.Slot, attachment: core.MeshAttachment): SpineMesh; - hackTextureBySlotIndex(slotIndex: number, texture?: Texture, size?: Rectangle): boolean; - hackTextureBySlotName: (slotName: string, texture?: Texture, size?: Rectangle) => any; - } - } -} diff --git a/pixi-spine/pixi-spine-tests.ts b/pixi-spine/pixi-spine-tests.ts deleted file mode 100644 index 51e4c7806f..0000000000 --- a/pixi-spine/pixi-spine-tests.ts +++ /dev/null @@ -1,311 +0,0 @@ -import * as PIXI from "pixi.js"; - -namespace Spine { - - export class Dragon { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private dragon: PIXI.spine.Spine; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - PIXI.loader.add('dragon', '../../_assets/spine/dragon.json').load(this.onAssetsLoaded); - - } - - private onAssetsLoaded = (loader: PIXI.loaders.Loader, res: any): void => { - - // initiate the spine animation - this.dragon = new PIXI.spine.Spine(res.dragon.spineData); - this.dragon.skeleton.setToSetupPose(); - this.dragon.update(0); - this.dragon.autoUpdate = false; - - // create a container for the spin animation and add the animation to it - var dragonCage: PIXI.Container = new PIXI.Container(); - dragonCage.addChild(this.dragon); - - // measure the spine animation and position it inside its container to align it to the origin - var localRect: PIXI.Rectangle = this.dragon.getLocalBounds(); - this.dragon.position.set(-localRect.x, -localRect.y); - - // now we can scale, position and rotate the container as any other display object - var scale = Math.min((this.renderer.width * 0.7) / dragonCage.width, (this.renderer.height * 0.7) / dragonCage.height); - dragonCage.scale.set(scale, scale); - dragonCage.position.set((this.renderer.width - dragonCage.width) * 0.5, (this.renderer.height - dragonCage.height) * 0.5); - - // add the container to the stage - this.stage.addChild(dragonCage); - - // once position and scaled, set the animation to play - this.dragon.state.setAnimation(0, 'flying', true); - - this.animate(); - - } - - private animate = (): void => { - - requestAnimationFrame(this.animate); - - // update the spine animation, only needed if dragon.autoupdate is set to false - this.dragon.update(0.01666666666667); // HARDCODED FRAMERATE! - - this.renderer.render(this.stage); - - } - - } - -} - -namespace Spine { - - export class Goblin { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private goblin: PIXI.spine.Spine; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - this.stage.interactive = true; - - PIXI.loader.add('goblins', '../../_assets/spine/goblins.json').load(this.onAssetsLoaded); - - } - - private onAssetsLoaded = (loader: PIXI.loaders.Loader, res: any): void => { - - // initiate the spine animation - this.goblin = new PIXI.spine.Spine(res.goblins.spineData); - this.goblin.skeleton.setSkinByName('goblin'); - this.goblin.skeleton.setSlotsToSetupPose(); - - this.goblin.position.x = 400; - this.goblin.position.y = 600; - this.goblin.scale.set(1.5); - - this.goblin.state.setAnimationByName(0, 'walk', true); - - this.stage.addChild(this.goblin); - - this.stage.on('click', () => { - - // change current skin - var currentSkinName = this.goblin.skeleton.skin.name; - var newSkinName = (currentSkinName === 'goblin' ? 'goblingirl' : 'goblin'); - this.goblin.skeleton.setSkinByName(newSkinName); - this.goblin.skeleton.setSlotsToSetupPose(); - - }); - - this.animate(); - - } - - private animate = (): void => { - - requestAnimationFrame(this.animate); - - this.renderer.render(this.stage); - - } - - } - -} - -namespace Spine { - - export class Pixie { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private pixie: PIXI.spine.Spine; - - private position: number; - private background: PIXI.Sprite; - private background2: PIXI.Sprite; - private foreground: PIXI.Sprite; - private foreground2: PIXI.Sprite; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - this.stage.interactive = true; - - PIXI.loader.add('pixie', '../../_assets/spine/pixie.json').load(this.onAssetsLoaded); - - } - - private onAssetsLoaded = (loader: PIXI.loaders.Loader, res: any): void => { - - this.background = PIXI.Sprite.fromImage('../../_assets/spine/iP4_BGtile.jpg'); - this.background2 = PIXI.Sprite.fromImage('../../_assets/spine/iP4_BGtile.jpg'); - this.stage.addChild(this.background); - this.stage.addChild(this.background2); - - this.foreground = PIXI.Sprite.fromImage('../../_assets/spine/iP4_ground.png'); - this.foreground2 = PIXI.Sprite.fromImage('../../_assets/spine/iP4_ground.png'); - this.stage.addChild(this.foreground); - this.stage.addChild(this.foreground2); - this.foreground.position.y = this.foreground2.position.y = 640 - this.foreground2.height; - - this.pixie = new PIXI.spine.Spine(res.pixie.spineData); - - var scale = 0.3; - - this.pixie.position.x = 1024 / 3; - this.pixie.position.y = 500; - - this.pixie.scale.x = this.pixie.scale.y = scale; - - this.stage.addChild(this.pixie); - - this.pixie.stateData.setMix('running', 'jump', 0.2); - this.pixie.stateData.setMix('jump', 'running', 0.4); - - this.pixie.state.setAnimation(0, 'running', true); - - this.stage.on('mousedown', this.onTouchStart); - this.stage.on('touchstart', this.onTouchStart); - - this.animate(); - - } - - private onTouchStart = (): void => { - - this.pixie.state.setAnimation(0, 'jump', false); - this.pixie.state.addAnimation(0, 'running', true, 0); - - } - - private animate = (): void => { - - this.position += 10; - - this.background.position.x = -(this.position * 0.6); - this.background.position.x %= 1286 * 2; - if (this.background.position.x < 0) { - this.background.position.x += 1286 * 2; - } - this.background.position.x -= 1286; - - this.background2.position.x = -(this.position * 0.6) + 1286; - this.background2.position.x %= 1286 * 2; - if (this.background2.position.x < 0) { - this.background2.position.x += 1286 * 2; - } - this.background2.position.x -= 1286; - - this.foreground.position.x = -this.position; - this.foreground.position.x %= 1286 * 2; - if (this.foreground.position.x < 0) { - this.foreground.position.x += 1286 * 2; - } - this.foreground.position.x -= 1286; - - this.foreground2.position.x = -this.position + 1286; - this.foreground2.position.x %= 1286 * 2; - if (this.foreground2.position.x < 0) { - this.foreground2.position.x += 1286 * 2; - } - this.foreground2.position.x -= 1286; - - requestAnimationFrame(this.animate); - - this.renderer.render(this.stage); - - } - - } - - namespace Spine { - - export class SpineBoy { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private spineboy: PIXI.spine.Spine; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - this.stage.interactive = true; - - PIXI.loader.add('spineboy', '../../_assets/spine/spineboy.json').load(this.onAssetsLoaded); - - } - - private onAssetsLoaded = (loader: PIXI.loaders.Loader, res: any): void => { - - // initiate the spine animation - this.spineboy = new PIXI.spine.Spine(res.spineboy.spineData); - this.spineboy.position.x = this.renderer.width / 2; - this.spineboy.position.y = this.renderer.height; - this.spineboy.scale.set(1.5); - - // set up the mixes! - this.spineboy.stateData.setMix('walk', 'jump', 0.2); - this.spineboy.stateData.setMix('jump', 'walk', 0.4); - - // play animation - this.spineboy.state.setAnimation(0, 'walk', true); - - this.stage.addChild(this.spineboy); - - - this.stage.on('click', () => { - - this.spineboy.state.setAnimation(0, 'jump', false); - this.spineboy.state.addAnimation(0, 'walk', true, 0); - - }); - - this.animate(); - - } - - private animate = (): void => { - - requestAnimationFrame(this.animate); - - this.renderer.render(this.stage); - - } - - } - - } - -} diff --git a/pixi-spine/tslint.json b/pixi-spine/tslint.json deleted file mode 100644 index c21d1d3fb1..0000000000 --- a/pixi-spine/tslint.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "extends": "../tslint.json", - "rules": {} -} diff --git a/pixi.js/index.d.ts b/pixi.js/index.d.ts index bacdfd23aa..cccbc1fbd9 100644 --- a/pixi.js/index.d.ts +++ b/pixi.js/index.d.ts @@ -1,2891 +1,3122 @@ -// Type definitions for Pixi.js 4.3 -// Project: https://github.com/pixijs/pixi.js/ -// Definitions by: Clark Stevenson +// Type definitions for Pixi.js 4.4 +// Project: https://github.com/pixijs/pixi.js/tree/dev +// Definitions by: clark-stevenson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +declare namespace PIXI { + + // from CONST + export const VERSION: typeof CONST.VERSION; + export const PI_2: typeof CONST.PI_2; + export const RAD_TO_DEG: typeof CONST.RAD_TO_DEG; + export const DEG_TO_RAD: typeof CONST.DEG_TO_RAD; + export const RENDERER_TYPE: typeof CONST.RENDERER_TYPE; + export const BLEND_MODES: typeof CONST.BLEND_MODES; + export const DRAW_MODES: typeof CONST.DRAW_MODES; + export const SCALE_MODES: typeof CONST.SCALE_MODES; + export const WRAP_MODES: typeof CONST.WRAP_MODES; + export const TRANSFORM_MODE: typeof CONST.TRANSFORM_MODE; + export const PRECISION: typeof CONST.PRECISION; + export const GC_MODES: typeof CONST.GC_MODES; + export const SHAPES: typeof CONST.SHAPES; + export const TEXT_GRADIENT: typeof CONST.TEXT_GRADIENT; + + export function autoDetectRenderer(width: number, height: number, options?: PIXI.IRendererOptions, noWebGL?: boolean): PIXI.WebGLRenderer | PIXI.CanvasRenderer; + export const loader: PIXI.loaders.Loader; + + ////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////SETTINGS/////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + export namespace settings { + export let TARGET_FPMS: number; + export let MIPMAP_TEXTURES: boolean; + export let RESOLUTION: number; + export let FILTER_RESOLUTION: number; + export let SPRITE_MAX_TEXTURES: number; + export let SPRITE_BATCH_SIZE: number; + export let RETINA_PREFIX: RegExp; + export const RENDER_OPTIONS: { + view: HTMLCanvasElement | null, + antialias: boolean, + forceFXAA: boolean, + autoResize: boolean, + transparent: boolean, + backgroundColor: number, + clearBeforeRender: boolean, + preserveDrawingBuffer: boolean, + roundPixels: boolean + }; + export let TRANSFORM_MODE: number; + export let GC_MODE: number; + export let GC_MAX_IDLE: number; + export let GC_MAX_CHECK_COUNT: number; + export let WRAP_MODE: number; + export let SCALE_MODE: number; + export let PRECISION: string; + export let UPLOADS_PER_FRAME: number; + export let CAN_UPLOAD_SAME_BUFFER: boolean; + } + + ////////////////////////////////////////////////////////////////////////////// + /////////////////////////////ACCESSIBILITY//////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + export namespace accessibility { + + // accessibility + export class AccessibilityManager { + + constructor(renderer: CanvasRenderer | WebGLRenderer); + + protected div: HTMLElement; + protected pool: HTMLElement[]; + protected renderId: number; + debug: boolean; + renderer: SystemRenderer; + protected children: IAccessibleTarget[]; + protected isActive: boolean; + + protected activate(): void; + protected deactivate(): void; + protected updateAccessibleObjects(displayObject: DisplayObject): void; + protected update(): void; + protected capHitArea(hitArea: IHitArea): void; + protected addChild(displayObject: DisplayObject): void; + protected _onClick(e: interaction.InteractionEvent): void; + protected _onFocus(e: interaction.InteractionEvent): void; + protected _onFocusOut(e: interaction.InteractionEvent): void; + protected _onKeyDown(e: interaction.InteractionEvent): void; + protected _onMouseMove(): void; + + destroy(): void; + + } + export interface IAccessibleTarget { + + accessible: boolean; + accessibleTitle: string | null; + accessibleHint: string | null; + tabIndex: number; + + } + + } + + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////CORE////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + // const + + export namespace CONST { + export const VERSION: string; + export const PI_2: number; + export const RAD_TO_DEG: number; + export const DEG_TO_RAD: number; + export const TARGET_FPMS: number; + export const RENDERER_TYPE: { + UNKNOWN: number; + WEBGL: number; + CANVAS: number; + }; + export const BLEND_MODES: { + NORMAL: number; + ADD: number; + MULTIPLY: number; + SCREEN: number; + OVERLAY: number; + DARKEN: number; + LIGHTEN: number; + COLOR_DODGE: number; + COLOR_BURN: number; + HARD_LIGHT: number; + SOFT_LIGHT: number; + DIFFERENCE: number; + EXCLUSION: number; + HUE: number; + SATURATION: number; + COLOR: number; + LUMINOSITY: number; + }; + export const DRAW_MODES: { + POINTS: number; + LINES: number; + LINE_LOOP: number; + LINE_STRIP: number; + TRIANGLES: number; + TRIANGLE_STRIP: number; + TRIANGLE_FAN: number; + }; + export const SCALE_MODES: { + LINEAR: number, + NEAREST: number + }; + export const GC_MODES: { + AUTO: number; + MANUAL: number; + }; + export const WRAP_MODES: { + CLAMP: number; + MIRRORED_REPEAT: number; + REPEAT: number; + }; + export const TRANSFORM_MODE: { + DEFAULT: number; + DYNAMIC: number; + STATIC: number; + }; + export const URL_FILE_EXTENSION: RegExp | string; + export const DATA_URI: RegExp | string; + export const SVG_SIZE: RegExp | string; + export const SHAPES: { + POLY: number; + RECT: number; + CIRC: number; + ELIP: number; + RREC: number; + }; + export const PRECISION: { + LOW: string; + MEDIUM: string; + HIGH: string; + }; + export const TEXT_GRADIENT: { + LINEAR_VERTICAL: number; + LINEAR_HORIZONTAL: number; + }; + } + + // display + + export interface IApplicationOptions extends IRendererOptions { + + view?: HTMLCanvasElement; + transparent?: boolean; + autoResize?: boolean; + antialias?: boolean; + resolution?: number; + clearBeforeRender?: boolean; + backgroundColor?: number; + roundPixels?: boolean; + context?: WebGLRenderingContext; + preserveDrawingBuffer?: boolean; + legacy?: boolean; + + } + + export class Application { + + constructor(width?: number, height?: number, options?: IApplicationOptions, noWebGL?: boolean, useSharedTicker?: boolean); + + private _ticker: ticker.Ticker; + + renderer: PIXI.WebGLRenderer | PIXI.CanvasRenderer; + stage: Container; + ticker: ticker.Ticker; + readonly screen: Rectangle; + + stop(): void; + start(): void; + render(): void; + destroy(removeView?: boolean): void; + readonly view: HTMLCanvasElement; + + } + + export interface IDestroyOptions { + children?: boolean; + texture?: boolean; + baseTexture?: boolean; + } + export class Bounds { + + minX: number; + minY: number; + maxX: number; + maxY: number; + rect: Rectangle; + + isEmpty(): boolean; + clear(): void; + + getRectangle(rect?: Rectangle): Rectangle; + addPoint(point: Point): void; + addQuad(vertices: number[]): Bounds | undefined; + addFrame(transform: Transform, x0: number, y0: number, x1: number, y1: number): void; + addVertices(transform: Transform, vertices: number[], beginOffset: number, endOffset: number): void; + addBounds(bounds: Bounds): void; + addBoundsMask(bounds: Bounds, mask: Bounds): void; + addBoundsArea(bounds: Bounds, area: Rectangle): void; + + } + export class Container extends DisplayObject { + + // begin extras.getChildByName + getChildByName(name: string): DisplayObject; + // end extras.getChildByName + + children: DisplayObject[]; + width: number; + height: number; + + protected onChildrenChange: (...args: any[]) => void; + addChild(child: T, ...additionalChildren: DisplayObject[]): T; + addChildAt(child: T, index: number): T; + swapChildren(child: DisplayObject, child2: DisplayObject): void; + getChildIndex(child: DisplayObject): number; + setChildIndex(child: DisplayObject, index: number): void; + getChildAt(index: number): DisplayObject; + removeChild(child: DisplayObject): DisplayObject; + removeChildAt(index: number): DisplayObject; + removeChildren(beginIndex?: number, endIndex?: number): DisplayObject[]; + updateTransform(): void; + calculateBounds(): void; + protected _calculateBounds(): void; + protected containerUpdateTransform(): void; + renderWebGL(renderer: WebGLRenderer): void; + renderAdvancedWebGL(renderer: WebGLRenderer): void; + protected _renderWebGL(renderer: WebGLRenderer): void; + protected _renderCanvas(renderer: CanvasRenderer): void; + renderCanvas(renderer: CanvasRenderer): void; + destroy(options?: IDestroyOptions | boolean): void; + + once(event: "added", fn: (displayObject: DisplayObject) => void, context?: any): this; + once(event: "removed", fn: (DisplayObject: DisplayObject) => void, context?: any): this; + once(event: string, fn: Function, context?: any): this; + on(event: "added", fn: (displayObject: DisplayObject) => void, context?: any): this; + on(event: "removed", fn: (DisplayObject: DisplayObject) => void, context?: any): this; + on(event: string, fn: Function, context?: any): this; + off(event: string, fn: Function, context?: any): this; + + } + export class DisplayObject extends utils.EventEmitter implements interaction.InteractiveTarget, accessibility.IAccessibleTarget { + + // begin extras.cacheAsBitmap + protected _cacheAsBitmap: boolean; + protected _cacheData: boolean; + cacheAsBitmap: boolean; + protected _renderCachedWebGL(renderer: WebGLRenderer): void; + protected _initCachedDisplayObject(renderer: WebGLRenderer): void; + protected _renderCachedCanvas(renderer: CanvasRenderer): void; + protected _initCachedDisplayObjectCanvas(renderer: CanvasRenderer): void; + protected _calculateCachedBounds(): Rectangle; + protected _getCachedLocalBounds(): Rectangle; + protected _destroyCachedDisplayObject(): void; + protected _cacheAsBitmapDestroy(): void; + // end extras.cacheAsBitmap + + // begin extras.getChildByName + name: string | null; + // end extras.getChildByName + + // begin extras.getGlobalPosition + getGlobalPosition(point?: Point, skipUpdate?: boolean): Point; + // end extras.getGlobalPosition + + // begin accessible target + accessible: boolean; + accessibleTitle: string | null; + accessibleHint: string | null; + tabIndex: number; + // end accessible target + + // begin interactive target + interactive: boolean; + interactiveChildren: boolean; + hitArea: PIXI.Rectangle | PIXI.Circle | PIXI.Ellipse | PIXI.Polygon | PIXI.RoundedRectangle; + buttonMode: boolean; + cursor: string; + trackedPointers(): { [key: number]: interaction.InteractionTrackingData; }; + // depricated + defaultCursor: string; + // end interactive target + + transform: TransformBase; + alpha: number; + visible: boolean; + renderable: boolean; + parent: Container; + worldAlpha: number; + filterArea: Rectangle; + protected _filters: Filter[] | null; + protected _enabledFilters: Filter[] | null; + protected _bounds: Bounds; + protected _boundsID: number; + protected _lastBoundsID: number; + protected _boundsRect: Rectangle; + protected _localBoundsRect: Rectangle; + protected _mask: PIXI.Graphics | PIXI.Sprite; + x: number; + y: number; + worldTransform: Matrix; + localTransform: Matrix; + position: Point; + scale: Point; + pivot: Point; + skew: Point; + rotation: number; + worldVisible: boolean; + mask: PIXI.Graphics | PIXI.Sprite; + filters: Filter[] | null; + + updateTransform(): void; + protected displayObjectUpdateTransform(): void; + protected _recursivePostUpdateTransform(): void; + getBounds(skipUpdate?: boolean, rect?: Rectangle): Rectangle; + getLocalBounds(rect?: Rectangle): Rectangle; + toGlobal(position: Point, point?: Point, skipUpdate?: boolean): Point; + toLocal(position: Point, from?: DisplayObject, point?: Point, skipUpdate?: boolean): Point; + renderWebGL(renderer: WebGLRenderer): void; + renderCanvas(renderer: CanvasRenderer): void; + setParent(container: Container): Container; + setTransform(x?: number, y?: number, scaleX?: number, scaleY?: number, rotation?: number, skewX?: number, skewY?: number, pivotX?: number, pivotY?: number): DisplayObject; + destroy(): void; + + on(event: string, fn: Function, context?: any): this; + once(event: string, fn: Function, context?: any): this; + off(event: string, fn: Function, context?: any): this; + + /* + on(event: 'click', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + on(event: 'mousedown', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + on(event: 'mouseout', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + on(event: 'mouseover', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + on(event: 'mouseup', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + on(event: 'mouseclick', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + on(event: 'mouseupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + on(event: 'rightclick', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + on(event: 'rightdown', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + on(event: 'rightup', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + on(event: 'rightupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + on(event: 'tap', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + on(event: 'touchend', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + on(event: 'touchendoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + on(event: 'touchmove', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + on(event: 'touchstart', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + + once(event: 'click', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + once(event: 'mousedown', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + once(event: 'mouseout', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + once(event: 'mouseover', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + once(event: 'mouseup', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + once(event: 'mouseclick', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + once(event: 'mouseupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + once(event: 'rightclick', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + once(event: 'rightdown', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + once(event: 'rightup', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + once(event: 'rightupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + once(event: 'tap', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + once(event: 'touchend', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + once(event: 'touchendoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + once(event: 'touchmove', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + once(event: 'touchstart', fn: (event: interaction.InteractionEvent) => void, context?: any): this; + */ + + } + + export class TransformBase { + + static IDENTITY: TransformBase; + + worldTransform: Matrix; + localTransform: Matrix; + protected _worldID: number; + updateLocalTransform(): void; + updateTransform(parentTransform: TransformBase): void; + updateWorldTransform(parentTransform: TransformBase): void; + + } + export class TransformStatic extends TransformBase { + + position: ObservablePoint; + scale: ObservablePoint; + pivot: ObservablePoint; + skew: ObservablePoint; + + protected _rotation: number; + protected _sr?: number; + protected _cr?: number; + protected _cy?: number; + protected _sy?: number; + protected _nsx?: number; + protected _cx?: number; + protected _currentLocalID: number; + + protected onChange(): void; + updateSkew(): void; + updateLocalTransform(): void; + updateTransform(parentTransform: TransformBase): void; + setFromMatrix(matrix: Matrix): void; + + rotation: number; + + } + export class Transform extends TransformBase { + + constructor(); + + position: Point; + scale: Point; + skew: ObservablePoint; + pivot: Point; + + protected _rotation: number; + protected _sr?: number; + protected _cr?: number; + protected _cy?: number; + protected _sy?: number; + protected _nsx?: number; + protected _cx?: number; + + updateSkew(): void; + setFromMatrix(matrix: Matrix): void; + + rotation: number; + + } + + // graphics + + export class GraphicsData { + + constructor(lineWidth: number, lineColor: number, lineAlpha: number, fillColor: number, fillAlpha: number, fill: boolean, nativeLines: boolean, shape: IShape | Circle | Rectangle | RoundedRectangle | Ellipse | Polygon); + + lineWidth: number; + nativeLines: boolean; + lineColor: number; + lineAlpha: number; + protected _lineTint: number; + fillColor: number; + fillAlpha: number; + protected _fillTint: number; + fill: boolean; + protected holes: IShape[]; + shape: IShape | Circle | Rectangle | RoundedRectangle | Ellipse | Polygon; + type?: number; + clone(): GraphicsData; + addHole(shape: IShape | Circle | Rectangle | RoundedRectangle | Ellipse | Polygon): void; + destroy(options?: IDestroyOptions | boolean): void; + + } + export class Graphics extends Container { + + constructor(nativeLines?: boolean); + + fillAlpha: number; + lineWidth: number; + nativeLines: boolean; + lineColor: number; + protected graphicsData: GraphicsData[]; + tint: number; + protected _prevTint: number; + blendMode: number; + currentPath: GraphicsData; + protected _webGL: any; + isMask: boolean; + boundsPadding: number; + protected _localBounds: Bounds; + dirty: boolean; + fastRectDirty: number; + clearDirty: number; + boundsDirty: number; + protected cachedSpriteDirty: boolean; + protected _spriteRect: Rectangle; + protected _fastRect: boolean; + + static _SPRITE_TEXTURE: Texture; + + clone(): Graphics; + lineStyle(lineWidth?: number, color?: number, alpha?: number): Graphics; + moveTo(x: number, y: number): Graphics; + lineTo(x: number, y: number): Graphics; + quadraticCurveTo(cpX: number, cpY: number, toX: number, toY: number): Graphics; + bezierCurveTo(cpX: number, cpY: number, cpX2: number, cpY2: number, toX: number, toY: number): Graphics; + arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): Graphics; + arc(cx: number, cy: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): Graphics; + beginFill(color: number, alpha?: number): Graphics; + endFill(): Graphics; + drawRect(x: number, y: number, width: number, height: number): Graphics; + drawRoundedRect(x: number, y: number, width: number, height: number, radius: number): Graphics; + drawCircle(x: number, y: number, radius: number): Graphics; + drawEllipse(x: number, y: number, width: number, height: number): Graphics; + drawPolygon(path: number[] | Point[]): Graphics; + clear(): Graphics; + isFastRect(): boolean; + protected _renderCanvas(renderer: CanvasRenderer): void; + protected _calculateBounds(): Rectangle; + protected _renderSpriteRect(renderer: PIXI.SystemRenderer): void; + containsPoint(point: Point): boolean; + updateLocalBounds(): void; + drawShape(shape: IShape | Circle | Rectangle | Ellipse | Polygon | RoundedRectangle): GraphicsData; + generateCanvasTexture(scaleMode?: number, resolution?: number): Texture; + protected closePath(): Graphics; + protected addHole(): Graphics; + destroy(options?: IDestroyOptions | boolean): void; + + } + export class CanvasGraphicsRenderer { + + constructor(renderer: SystemRenderer); + render(graphics: Graphics): void; + protected updateGraphicsTint(graphics: Graphics): void; + protected renderPolygon(points: Point[], close: boolean, context: CanvasRenderingContext2D): void; + destroy(): void; + + } + export class GraphicsRenderer extends ObjectRenderer { + + constructor(renderer: PIXI.CanvasRenderer); + + protected graphicsDataPool: GraphicsData[]; + protected primitiveShader: PrimitiveShader; + gl: WebGLRenderingContext; + + CONTEXT_UID: number; + + destroy(): void; + render(graphics: Graphics): void; + protected updateGraphics(graphics: PIXI.Graphics): void; + getWebGLData(webGL: WebGLRenderingContext, type: number): WebGLGraphicsData; + + } + export class WebGLGraphicsData { + + constructor(gl: WebGLRenderingContext, shader: glCore.GLShader, attribsState: glCore.IAttribState); + + gl: WebGLRenderingContext; + color: number[]; + points: Point[]; + indices: number[]; + buffer: WebGLBuffer; + indexBuffer: WebGLBuffer; + dirty: boolean; + glPoints: number[]; + glIndices: number[]; + shader: glCore.GLShader; + vao: glCore.VertexArrayObject; + + reset(): void; + upload(): void; + destroy(): void; + + } + export class PrimitiveShader extends glCore.GLShader { } + + // math + + export namespace GroupD8 { + + export const E: number; + export const SE: number; + export const S: number; + export const SW: number; + export const W: number; + export const NW: number; + export const N: number; + export const NE: number; + export const MIRROR_HORIZONTAL: number; + export const MIRROR_VERTICAL: number; + + export function uX(ind: number): number; + export function uY(ind: number): number; + export function vX(ind: number): number; + export function vY(ind: number): number; + export function inv(rotation: number): number; + export function add(rotationSecond: number, rotationFirst: number): number; + export function sub(rotationSecond: number, rotationFirst: number): number; + export function rotate180(rotation: number): number; + export function isSwapWidthHeight(rotation: number): boolean; + export function byDirection(dx: number, dy: number): number; + export function matrixAppendRotationInv(matrix: Matrix, rotation: number, tx: number, ty: number): void; + + } + export class Matrix { + + constructor(a?: number, b?: number, c?: number, d?: number, tx?: number, ty?: number); + + a: number; + b: number; + c: number; + d: number; + tx: number; + ty: number; + + fromArray(array: number[]): void; + set(a: number, b: number, c: number, d: number, tx: number, ty: number): Matrix; + toArray(transpose?: boolean, out?: number[]): number[]; + apply(pos: Point, newPos?: Point): Point; + applyInverse(pos: Point, newPos?: Point): Point; + translate(x: number, y: number): Matrix; + scale(x: number, y: number): Matrix; + rotate(angle: number): Matrix; + append(matrix: Matrix): Matrix; + setTransform(x: number, y: number, pivotX: number, pivotY: number, scaleX: number, scaleY: number, rotation: number, skewX: number, skewY: number): PIXI.Matrix; + prepend(matrix: Matrix): Matrix; + invert(): Matrix; + identity(): Matrix; + decompose(transform: TransformBase): TransformBase; + clone(): Matrix; + copy(matrix: Matrix): Matrix; + + static IDENTITY: Matrix; + static TEMP_MATRIX: Matrix; + + } + export class ObservablePoint { + + constructor(cb: Function, scope?: any, x?: number, y?: number); + + x: number; + y: number; + cb: () => any; + scope: any; + + set(x?: number, y?: number): void; + copy(point: Point | ObservablePoint): void; + + } + export class Point { + + constructor(x?: number, y?: number); + + x: number; + y: number; + + clone(): Point; + copy(p: Point): void; + equals(p: Point): boolean; + set(x?: number, y?: number): void; + + } + + export interface IShape { + } + export interface IHitArea extends IShape { + + contains(x: number, y: number): boolean; + + } + export class Circle { + + constructor(x?: number, y?: number, radius?: number); + + x: number; + y: number; + radius: number; + type: number; + + clone(): Circle; + contains(x: number, y: number): boolean; + getBounds(): Rectangle; + + } + export class Ellipse { + + constructor(x?: number, y?: number, width?: number, height?: number); + + x: number; + y: number; + width: number; + height: number; + type: number; + + clone(): Ellipse; + contains(x: number, y: number): boolean; + getBounds(): Rectangle; + + } + export class Polygon { + + constructor(points: Point[] | number[]); + constructor(...points: Point[]); + constructor(...points: number[]); + + closed: boolean; + points: number[]; + type: number; + + clone(): Polygon; + contains(x: number, y: number): boolean; + close(): void; + + } + export class Rectangle { + + constructor(x?: number, y?: number, width?: number, height?: number); + + x: number; + y: number; + width: number; + height: number; + type: number; + left: number; + right: number; + top: number; + bottom: number; + + static EMPTY: Rectangle; + + clone(): Rectangle; + copy(rectangle: Rectangle): Rectangle; + contains(x: number, y: number): boolean; + pad(paddingX: number, paddingY: number): void; + fit(rectangle: Rectangle): void; + enlarge(rectangle: Rectangle): void; + + } + export class RoundedRectangle { + + constructor(x?: number, y?: number, width?: number, height?: number, radius?: number); + + x: number; + y: number; + width: number; + height: number; + radius: number; + type: number; + + clone(): RoundedRectangle; + contains(x: number, y: number): boolean; + + } + + // renderers + + export interface IRendererOptions { + + view?: HTMLCanvasElement; + transparent?: boolean; + autoResize?: boolean; + antialias?: boolean; + resolution?: number; + clearBeforeRender?: boolean; + backgroundColor?: number; + roundPixels?: boolean; + context?: WebGLRenderingContext; + + } + export class SystemRenderer extends utils.EventEmitter { + + constructor(system: string, screenWidth?: number, screenHeight?: number, options?: IRendererOptions); + + type: number; + screen: Rectangle; + readonly width: number; + readonly height: number; + view: HTMLCanvasElement; + resolution: number; + transparent: boolean; + autoResize: boolean; + blendModes: any; // todo? + preserveDrawingBuffer: boolean; + clearBeforeRender: boolean; + roundPixels: boolean; + protected _backgroundColor: number; + protected _backgroundColorRgba: number[]; + protected _backgroundColorString: string; + protected _tempDisplayObjectParent: Container; + protected _lastObjectRendered: DisplayObject; + backgroundColor: number; + + resize(screenWidth: number, screenHeight: number): void; + generateTexture(displayObject: DisplayObject, scaleMode?: number, resolution?: number): RenderTexture; + render(...args: any[]): void; + destroy(removeView?: boolean): void; + + } + export class CanvasRenderer extends SystemRenderer { + + // plugintarget mixin start + static __plugins: Object; + static registerPlugin(pluginName: string, ctor: Function): void; + plugins: any; + initPlugins(): void; + destroyPlugins(): void; + // plugintarget mixin end + + // from InteractionManager + interaction?: interaction.InteractionManager; + + constructor(screenWidth?: number, screenHeight?: number, options?: IRendererOptions); + + rootContext: CanvasRenderingContext2D; + rootResolution?: number; + refresh: boolean; + maskManager: CanvasMaskManager; + smoothProperty: string; + extract: extract.CanvasExtract; + + context: CanvasRenderingContext2D | null; + + render(displayObject: PIXI.DisplayObject, renderTexture?: PIXI.RenderTexture, clear?: boolean, transform?: PIXI.Transform, skipUpdateTransform?: boolean): void + setBlendMode(blendMode: number): void; + destroy(removeView?: boolean): void; + clear(clearColor?: string): void; + + on(event: "prerender", fn: () => void, context?: any): this; + on(event: "postrender", fn: () => void, context?: any): this; + on(event: string, fn: Function, context?: any): this; + once(event: "prerender", fn: () => void, context?: any): this; + once(event: "postrender", fn: () => void, context?: any): this; + once(event: string, fn: Function, context?: any): this; + off(event: string, fn: Function, context?: any): this; + + } + export class CanvasMaskManager { + + constructor(renderer: CanvasRenderer); + + pushMask(maskData: any): void; + protected renderGraphicsShape(graphics: Graphics): void; + popMask(renderer: WebGLRenderer | CanvasRenderer): void; + destroy(): void; + + } + export class CanvasRenderTarget { + + constructor(width: number, height: number, resolution: number); + + canvas: HTMLCanvasElement; + context: CanvasRenderingContext2D; + resolution: number; + + width: number; + height: number; + + clear(): void; + resize(width: number, height: number): void; + destroy(): void; + + } + + export interface IWebGLRendererOptions { + + view?: HTMLCanvasElement; + transparent?: boolean; + autoResize?: boolean; + antialias?: boolean; + forceFXAA?: boolean; + resolution?: number; + clearBeforeRender?: boolean; + preserveDrawingBuffer?: boolean; + roundPixels?: boolean; + legacy?: boolean; + + } + export class WebGLRenderer extends SystemRenderer { + + // plugintarget mixin start + static __plugins: Object; + static registerPlugin(pluginName: string, ctor: Function): void; + plugins: any; + initPlugins(): void; + destroyPlugins(): void; + // plugintarget mixin end + + // from InteractionManager + interaction: interaction.InteractionManager; + + constructor(screenWidth?: number, screenHeight?: number, options?: IWebGLRendererOptions); + + protected _contextOptions: { + alpha: boolean; + antiAlias?: boolean; + premultipliedAlpha: boolean; + stencil: boolean; + preseveDrawingBuffer?: boolean; + }; + protected _backgroundColorRgba: number[]; + maskManager: MaskManager; + stencilManager?: StencilManager; + emptyRenderer: ObjectRenderer; + currentRenderer: ObjectRenderer; + gl: WebGLRenderingContext; + CONTEXT_UID: number; + state?: WebGLState; + renderingToScreen: boolean; + boundTextures: Texture[]; + filterManager: FilterManager; + textureManager?: TextureManager; + extract: extract.WebGLExtract; + protected drawModes: any; + protected _activeShader: Shader; + _activeRenderTarget: RenderTarget; + protected _initContext(): void; + + render(displayObject: PIXI.DisplayObject, renderTexture?: PIXI.RenderTexture, clear?: boolean, transform?: PIXI.Transform, skipUpdateTransform?: boolean): void + setObjectRenderer(objectRenderer: ObjectRenderer): void; + flush(): void; + setBlendMode(blendMode: number): void; + clear(clearColor?: number): void; + setTransform(matrix: Matrix): void; + clearRenderTexture(renderTexture: RenderTexture, clearColor?: number): WebGLRenderer; + bindRenderTexture(renderTexture: RenderTexture, transform: Transform): WebGLRenderer; + bindRenderTarget(renderTarget: RenderTarget): WebGLRenderer; + bindShader(shader: Shader, autoProject?: boolean): WebGLRenderer; + bindTexture(texture: Texture | BaseTexture, location?: number, forceLocation?: boolean): number; + unbindTexture(texture: Texture | BaseTexture): WebGLRenderer | undefined; + createVao(): glCore.VertexArrayObject; + bindVao(vao: glCore.VertexArrayObject): WebGLRenderer; + reset(): WebGLRenderer; + handleContextLost: (event: WebGLContextEvent) => void; + handleContextRestored: () => void; + destroy(removeView?: boolean): void; + + on(event: "context", fn: (gl: WebGLRenderingContext) => void, context?: any): this; + on(event: "prerender", fn: () => void, context?: any): this; + on(event: "postrender", fn: () => void, context?: any): this; + on(event: string, fn: Function, context?: any): this; + once(event: "context", fn: (gl: WebGLRenderingContext) => void, context?: any): this; + once(event: "prerender", fn: () => void, context?: any): this; + once(event: "postrender", fn: () => void, context?: any): this; + once(event: string, fn: Function, context?: any): this; + off(event: string, fn: Function, context?: any): this; + + } + export class WebGLState { + + constructor(gl: WebGLRenderingContext); + + activeState: number[]; + defaultState: number[]; + stackIndex: number; + stack: number[]; + gl: WebGLRenderingContext; + maxAttribs: number; + attribState: glCore.IAttribState; + nativeVaoExtension: any; + + push(): void; + pop(): void; + setState(state: number[]): void; + setBlend(value: number): void; + setBlendMode(value: number): void; + setDepthTest(value: number): void; + setCullFace(value: number): void; + setFrontFace(value: number): void; + resetAttributes(): void; + resetToDefault(): void; + + } + export class TextureManager { + + constructor(renderer: WebGLRenderer); + + renderer: WebGLRenderer; + gl: WebGLRenderingContext; + protected _managedTextures: WebGLTexture[]; + + bindTexture(): void; + getTexture(): WebGLTexture; + updateTexture(texture: BaseTexture | Texture): WebGLTexture; + destroyTexture(texture: BaseTexture, _skipRemove?: boolean): void; + removeAll(): void; + destroy(): void; + + } + export class TextureGarbageCollector { + + constructor(renderer: WebGLRenderer); + + renderer: WebGLRenderer; + count: number; + checkCount: number; + maxIdle: number; + checkCountMax: number; + mode: number; + + update(): void; + run(): void; + unload(): void; + + } + export abstract class ObjectRenderer extends WebGLManager { + + constructor(renderer: WebGLRenderer); + + start(): void; + stop(): void; + flush(): void; + + render(...args: any[]): void; + + } + export class Quad { + + constructor(gl: WebGLRenderingContext); + + gl: WebGLRenderingContext; + vertices: number[]; + uvs: number[]; + interleaved: number[]; + indices: number[]; + vertexBuffer: WebGLBuffer; + vao: glCore.VertexArrayObject; + initVao(shader: glCore.GLShader): void; + map(targetTextureFrame: Rectangle, destinationFrame: Rectangle): Quad; + upload(): Quad; + destroy(): void; + + } + export class RenderTarget { + + constructor(gl: WebGLRenderingContext, width: number, height: number, scaleMode: number, resolution: number, root?: boolean); + + gl: WebGLRenderingContext; + frameBuffer: glCore.GLFramebuffer; + texture: Texture; + clearColor: number[]; + size: Rectangle; + resolution: number; + projectionMatrix: Matrix; + transform: Matrix; + frame: Rectangle; + defaultFrame: Rectangle; + destinationFrame: Rectangle; + sourceFrame?: Rectangle; + stencilBuffer: glCore.GLFramebuffer; + stencilMaskStack: Graphics[]; + filterData: { + index: number, + stack: { + renderTarget: RenderTarget, + filter: any[]; + bounds: Rectangle + }[] + }; + scaleMode: number; + root: boolean; + + clear(clearColor?: number[]): void; + attachStencilBuffer(): void; + setFrame(destinationFrame: Rectangle, sourceFrame: Rectangle): void; + activate(): void; + calculateProjection(destinationFrame: Rectangle, sourceFrame: Rectangle): void; + resize(width: number, height: number): void; + destroy(): void; + + } + + export class BlendModeManager extends WebGLManager { + + constructor(renderer: WebGLRenderer); + + currentBlendMode: number; + + setBlendMode(blendMode: number): boolean; + + } + export class FilterManager extends WebGLManager { + + constructor(renderer: WebGLRenderer); + + gl: WebGLRenderingContext; + quad: Quad; + stack: { + renderTarget: RenderTarget; + sourceFrame: Rectangle; + destinationFrame: Rectangle; + filters: Filter[]; + target: any; + resolution: number; + }[]; + stackIndex: number; + shaderCache: any; + filterData: any; + + pushFilter(target: RenderTarget, filters: Filter[]): void; + popFilter(): void; + applyFilter(shader: glCore.GLShader | Filter, inputTarget: RenderTarget, outputTarget: RenderTarget, clear?: boolean): void; + syncUniforms(shader: glCore.GLShader, filter: Filter): void; + getRenderTarget(clear?: boolean, resolution?: number): RenderTarget; + returnRenderTarget(renderTarget: RenderTarget): RenderTarget; + calculateScreenSpaceMatrix(outputMatrix: Matrix): Matrix; + calculateNormalisedScreenSpaceMatrix(outputMatrix: Matrix): Matrix; + calculateSpriteMatrix(outputMatrix: Matrix, sprite: Sprite): Matrix; + destroy(): void; + emptyPool(): void; + getPotRenderTarget(gl: WebGLRenderingContext, minWidth: number, minHeight: number, resolution: number): RenderTarget; + freePotRenderTarget(renderTarget: RenderTarget): void; + + } + export class StencilMaskStack { + + stencilStack: any[]; + reverse: boolean; + count: number; + + } + export class MaskManager extends WebGLManager { + + scissor: boolean; + scissorData: any; + scissorRenderTarget: RenderTarget; + enableScissor: boolean; + alphaMaskPool: number[]; + alphaMaskIndex: number; + pushMask(target: RenderTarget, maskData: Sprite | Graphics): void; + popMask(target: RenderTarget, maskData: Sprite | Graphics): void; + pushSpriteMask(target: RenderTarget, maskData: Sprite | Graphics): void; + popSpriteMask(): void; + pushStencilMask(maskData: Sprite | Graphics): void; + popStencilMask(): void; + pushScissorMask(target: RenderTarget, maskData: Sprite | Graphics): void; + popScissorMask(): void; + + } + export class StencilManager extends WebGLManager { + + constructor(renderer: WebGLRenderer); + + stencilMaskStack: Graphics[]; + + setMaskStack(stencilMasStack: Graphics[]): void; + pushStencil(graphics: Graphics): void; + popStencil(): void; + destroy(): void; + + } + export class WebGLManager { + + constructor(renderer: WebGLRenderer); + + renderer: SystemRenderer; + onContextChange(): void; + destroy(): void; + + } + export interface IUniformData { + + type: string; + value: any; + + // name is set by pixi if uniforms were automatically extracted from shader code, but not used anywhere + name?: string; + + } + export class Filter { + + constructor(vertexSrc?: string, fragmentSrc?: string, uniforms?: { [name: string]: IUniformData }); + + vertextSrc?: string; + fragmentSrc: string; + blendMode: number; + protected uniformData: { [name: string]: IUniformData }; + uniforms: { [name: string]: any } | any; + glShaders: any; + glShaderKey?: number; + padding: number; + resolution: number; + enabled: boolean; + apply(filterManager: FilterManager, input: RenderTarget, output: RenderTarget, clear?: boolean): void; + + static defaultVertexSrc: string; + static defaultFragmentSrc: string; + + } + export class SpriteMaskFilter extends Filter { + + constructor(sprite: Sprite); + + maskSprite: Sprite; + maskMatrix: Matrix; + apply(filterManager: FilterManager, input: RenderTarget, output: RenderTarget): void; + + } + + // sprites + + export class Sprite extends Container { + + constructor(texture?: Texture); + + protected _anchor: ObservablePoint; + anchor: ObservablePoint; + protected _texture: Texture; + protected _transformTrimmedID: number; + protected _textureTrimmedID: number; + protected _width: number; + protected _height: number; + tint: number; + protected _tint: number; + protected _tintRGB: number; + blendMode: number; + pluginName: string; + protected cachedTint: number; + texture: Texture; + protected textureDirty: boolean; + protected _textureID: number; + protected _transformID: number; + protected vertexTrimmedData: Float32Array; + vertexData: Float32Array; + width: number; + height: number; + + protected _onTextureUpdate(): void; + calculateVertices(): void; + protected _calculateBounds(): void; + protected calculateTrimmedVertices(): void; + protected onAnchorUpdate(): void; + protected _renderWebGL(renderer: WebGLRenderer): void; + protected _renderCanvas(renderer: CanvasRenderer): void; + getLocalBounds(): Rectangle; + containsPoint(point: Point): boolean; + destroy(options?: IDestroyOptions | boolean): void; + + static from(source: number | string | BaseTexture | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement): Sprite; + static fromFrame(frameId: string): Sprite; + static fromImage(imageId: string, crossorigin?: boolean, scaleMode?: number): Sprite; + + } + export class BatchBuffer { + + vertices: ArrayBuffer; + float32View: number[]; + uint32View: number[]; + + destroy(): void; + + } + export class SpriteRenderer extends ObjectRenderer { + + constructor(renderer: PIXI.WebGLRenderer); + + vertSize: number; + vertByteSize: number; + size: number; + buffers: BatchBuffer[]; + indices: number[]; + shaders: Shader[]; + currentIndex: number; + tick: number; + groups: any[]; + sprites: Sprite[]; + vertexBuffers: number[]; + vaos: glCore.VertexArrayObject[]; + vaoMax: number; + vertexCount: number; + + protected onContextChanged: () => void; + protected onPrerender: () => void; + render(sprite: Sprite): void; + flush(): void; + start(): void; + stop(): void; + destroy(): void; + + } + export class CanvasSpriteRenderer extends ObjectRenderer { + + constructor(renderer: WebGLRenderer); + + render(sprite: Sprite): void; + destroy(): void; + + } + export namespace CanvasTinter { + + export function getTintedTexture(sprite: Sprite, color: number): HTMLCanvasElement; + export function tintWithMultiply(texture: Texture, color: number, canvas: HTMLCanvasElement): void; + export function tintWithOverlay(texture: Texture, color: number, canvas: HTMLCanvasElement): void; + export function tintWithPerPixel(texture: Texture, color: number, canvas: HTMLCanvasElement): void; + export function roundColor(color: number): number; + + export let cacheStepsPerColorChannel: number; + export let convertTintToImage: boolean; + export let canUseMultiply: boolean; + export let tintMethod: Function; + + } + + // text + export interface TextStyleOptions { + align?: string; + breakWords?: boolean; + dropShadow?: boolean; + dropShadowAlpha?: number; + dropShadowAngle?: number; + dropShadowBlur?: number; + dropShadowColor?: string | number; + dropShadowDistance?: number; + fill?: string | string[] | number | number[] | CanvasGradient | CanvasPattern; + fillGradientType?: number; + fillGradientStops?: number[]; + fontFamily?: string | string[]; + fontSize?: number | string; + fontStyle?: string; + fontVariant?: string; + fontWeight?: string; + letterSpacing?: number; + lineHeight?: number; + lineJoin?: string; + miterLimit?: number; + padding?: number; + stroke?: string | number; + strokeThickness?: number; + textBaseline?: string; + trim?: boolean; + wordWrap?: boolean; + wordWrapWidth?: number; + } + + export class TextStyle implements TextStyleOptions { + + constructor(style: TextStyleOptions) + + styleID: number; + + clone(): TextStyle; + reset(): void; + + protected _align: string; + align: string; + protected _breakWords: boolean; + breakWords: boolean; + protected _dropShadow: boolean; + dropShadow: boolean; + protected _dropShadowAlpha: number; + dropShadowAlpha: number; + protected _dropShadowAngle: number; + dropShadowAngle: number; + protected _dropShadowBlur: number; + dropShadowBlur: number; + protected _dropShadowColor: string | number; + dropShadowColor: string | number; + protected _dropShadowDistance: number; + dropShadowDistance: number; + protected _fill: string | string[] | number | number[] | CanvasGradient | CanvasPattern; + fill: string | string[] | number | number[] | CanvasGradient | CanvasPattern; + protected _fillGradientType: number; + fillGradientType: number; + protected _fillGradientStops: number[]; + fillGradientStops: number[]; + protected _fontFamily: string | string[]; + fontFamily: string | string[]; + protected _fontSize: number | string; + fontSize: number | string; + protected _fontStyle: string; + fontStyle: string; + protected _fontVariant: string; + fontVariant: string; + protected _fontWeight: string; + fontWeight: string; + protected _letterSpacing: number; + letterSpacing: number; + protected _lineHeight: number; + lineHeight: number; + protected _lineJoin: string; + lineJoin: string; + protected _miterLimit: number; + miterLimit: number; + protected _padding: number; + padding: number; + protected _stroke: string | number; + stroke: string | number; + protected _strokeThickness: number; + strokeThickness: number; + protected _textBaseline: string; + textBaseline: string; + protected _trim: boolean; + trim: boolean; + protected _wordWrap: boolean; + wordWrap: boolean; + protected _wordWrapWidth: number; + wordWrapWidth: number; + + } + + export class Text extends Sprite { + + static getFontStyle(style: TextStyleOptions): string; + static calculateFontProperties(style: string): any; + + constructor(text?: string, style?: TextStyleOptions, canvas?: HTMLCanvasElement); + + canvas: HTMLCanvasElement; + context: CanvasRenderingContext2D; + resolution: number; + protected _text: string; + protected _style: TextStyle; + protected _styleListener: Function; + protected _font: string; + protected localStyleID: number; + + static fontPropertiesCache: any; + static fontPropertiesCanvas: HTMLCanvasElement; + static fontPropertiesContext: CanvasRenderingContext2D; + + width: number; + height: number; + style: TextStyle; + text: string; + + protected updateText(respectDirty?: boolean): void; + protected drawLetterSpacing(text: string, x: number, y: number, isStroke?: boolean): void; + protected updateTexture(): void; + renderWebGL(renderer: WebGLRenderer): void; + protected _renderCanvas(renderer: CanvasRenderer): void; + protected wordWrap(text: string): string; + getLocalBounds(rect?: Rectangle): Rectangle; + protected _calculateBounds(): void; + protected _onStyleChange: () => void; + protected _generateFillStyle(style: TextStyle, lines: string[]): string | number | CanvasGradient; + destroy(options?: IDestroyOptions | boolean): void; + dirty: boolean; + + } + + // textures + + export class BaseRenderTexture extends BaseTexture { + + constructor(width?: number, height?: number, scaleMode?: number, resolution?: number); + + height: number; + width: number; + realHeight: number; + realWidth: number; + resolution: number; + scaleMode: number; + hasLoaded: boolean; + protected _glRenderTargets: { [n: number]: WebGLTexture; }; + protected _canvasRenderTarget: { [n: number]: WebGLTexture; }; + valid: boolean; + + resize(width: number, height: number): void; + destroy(): void; + + once(event: "update", fn: (baseRenderTexture: BaseRenderTexture) => void, context?: any): this; + once(event: string, fn: Function, context?: any): this; + on(event: "update", fn: (baseRenderTexture: BaseRenderTexture) => void, context?: any): this; + on(event: string, fn: Function, context?: any): this; + off(event: string, fn: Function, context?: any): this; + + } + export class BaseTexture extends utils.EventEmitter { + + static from(source: string | HTMLImageElement | HTMLCanvasElement, scaleMode?: number, sourceScale?: number): BaseTexture; + + constructor(source?: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, scaleMode?: number, resolution?: number); + + protected uuid?: number; + protected touched: number; + resolution: number; + width: number; + height: number; + realWidth: number; + realHeight: number; + scaleMode: number; + hasLoaded: boolean; + isLoading: boolean; + wrapMode: number; + source: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | null; + origSource: HTMLImageElement | null; + imageType: string | null; + sourceScale: number; + premultipliedAlpha: boolean; + imageUrl: string | null; + protected isPowerOfTwo: boolean; + mipmap: boolean; + wrap?: boolean; + protected _glTextures: any; + protected _enabled: number; + protected _id?: number; + + update(): void; + protected _updateDimensions(): void; + protected _updateImageType(): void; + protected _loadSvgSource(): void; + protected _loadSvgSourceUsingDataUri(dataUri: string): void; + protected _loadSvgSourceUsingXhr(): void; + protected _loadSvgSourceUsingString(svgString: string): void; + protected loadSource(source: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement): void; + protected _sourceLoaded(): void; + destroy(): void; + dispose(): void; + updateSourceImage(newSrc: string): void; + + static fromImage(imageUrl: string, crossorigin?: boolean, scaleMode?: number, sourceScale?: number): BaseTexture; + static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: number): BaseTexture; + + on(event: "update", fn: (baseTexture: BaseTexture) => void, context?: any): this; + on(event: "loaded", fn: (baseTexture: BaseTexture) => void, context?: any): this; + on(event: "error", fn: (baseTexture: BaseTexture) => void, context?: any): this; + on(event: "dispose", fn: (baseTexture: BaseTexture) => void, context?: any): this; + on(event: string, fn: Function, context?: any): this; + once(event: "update", fn: (baseTexture: BaseTexture) => void, context?: any): this; + once(event: "loaded", fn: (baseTexture: BaseTexture) => void, context?: any): this; + once(event: "error", fn: (baseTexture: BaseTexture) => void, context?: any): this; + once(event: "dispose", fn: (baseTexture: BaseTexture) => void, context?: any): this; + once(event: string, fn: Function, context?: any): this; + off(event: string, fn: Function, context?: any): this; + + } + export class RenderTexture extends Texture { + + constructor(baseRenderTexture: BaseRenderTexture, frame?: Rectangle); + + protected legacyRenderer: any; + valid: boolean; + + resize(width: number, height: number, doNotResizeBaseTexture?: boolean): void; + + static create(width?: number, height?: number, scaleMode?: number, resolution?: number): RenderTexture; + + } + export class Texture extends utils.EventEmitter { + + static from(source: number | string | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | PIXI.BaseTexture): Texture; + + constructor(baseTexture: BaseTexture, frame?: Rectangle, orig?: Rectangle, trim?: Rectangle, rotate?: number); + + noFrame: boolean; + baseTexture: BaseTexture; + protected _frame: Rectangle; + trim?: Rectangle; + valid: boolean; + requiresUpdate: boolean; + protected _uvs: TextureUvs; + orig: Rectangle; + protected _updateID: number; + transform: any; + + update(): void; + protected onBaseTextureLoaded(baseTexture: BaseTexture): void; + protected onBaseTextureUpdated(baseTexture: BaseTexture): void; + destroy(destroyBase?: boolean): void; + clone(): Texture; + protected _updateUvs(): void; + + static fromImage(imageUrl: string, crossOrigin?: boolean, scaleMode?: number, sourceScale?: number): Texture; + static fromFrame(frameId: string): Texture; + static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: number): Texture; + static fromVideo(video: HTMLVideoElement | string, scaleMode?: number): Texture; + static fromVideoUrl(videoUrl: string, scaleMode?: number): Texture; + static from(source: string | BaseTexture | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement): Texture; + static fromLoader(source: HTMLImageElement | HTMLCanvasElement, imageUrl: string, name?: string): Texture; + static addTextureToCache(texture: Texture, id: string): void; + static removeTextureFromCache(id: string): Texture | undefined; + + frame: Rectangle; + protected _rotate: boolean | 0; + rotate: number; + width: number; + height: number; + + static EMPTY: Texture; + + on(event: "update", fn: (texture: Texture) => void, context?: any): this; + on(event: string, fn: Function, context?: any): this; + once(event: "update", fn: (texture: Texture) => void, context?: any): this; + once(event: string, fn: Function, context?: any): this; + off(event: string, fn: Function, context?: any): this; + + } + export class TextureUvs { + + x0: number; + y0: number; + x1: number; + y1: number; + x2: number; + y2: number; + x3: number; + y3: number; + + uvsUint32: Uint32Array; + + protected set(frame: Rectangle, baseFrame: Rectangle, rotate: number): void; + + } -// from CONST -export var VERSION: typeof CONST.VERSION; -export var PI_2: typeof CONST.PI_2; -export var RAD_TO_DEG: typeof CONST.RAD_TO_DEG; -export var DEG_TO_RAD: typeof CONST.DEG_TO_RAD; -export var RENDERER_TYPE: typeof CONST.RENDERER_TYPE; -export var BLEND_MODES: typeof CONST.BLEND_MODES; -export var DRAW_MODES: typeof CONST.DRAW_MODES; -export var SCALE_MODES: typeof CONST.SCALE_MODES; -export var WRAP_MODES: typeof CONST.WRAP_MODES; -export var TRANSFORM_MODE: typeof CONST.TRANSFORM_MODE; -export var PRECISION: typeof CONST.PRECISION; -export var TEXT_STYLE_CHANGED: typeof CONST.TEXT_STYLE_CHANGED; -export var GC_MODES: typeof CONST.GC_MODES; -export var SHAPES: typeof CONST.SHAPES; -export var TEXT_GRADIENT: typeof CONST.TEXT_GRADIENT; - -export function autoDetectRenderer(width: number, height: number, options?: PIXI.IRendererOptions, noWebGL?: boolean): PIXI.WebGLRenderer | PIXI.CanvasRenderer; -export var loader: PIXI.loaders.Loader; - -////////////////////////////////////////////////////////////////////////////// -///////////////////////////////SETTINGS/////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - -export namespace settings { - export var TARGET_FPMS: number; - export var MIPMAP_TEXTURES: boolean; - export var RESOLUTION: number; - export var FILTER_RESOLUTION: number; - export var SPRITE_MAX_TEXTURES: number; - export var SPRITE_BATCH_SIZE: number; - export var RETINA_PREFIX: RegExp; - export var RENDER_OPTIONS: { - view: HTMLCanvasElement, - antialias: boolean, - forceFXAA: boolean, - autoResize: boolean, - transparent: boolean, - backgroundColor: number, - clearBeforeRender: boolean, - preserveDrawingBuffer: boolean, - roundPixels: boolean - }; - export var TRANSFORM_MODE: number; - export var GC_MODE: number; - export var GC_MAX_IDLE: number; - export var GC_MAX_CHECK_COUNT: number; - export var WRAP_MODE: number; - export var SCALE_MODE: number; - export var PRECISION: string; - export var UPLOADS_PER_FRAME: number; - export var CAN_UPLOAD_SAME_BUFFER: boolean; -} - -////////////////////////////////////////////////////////////////////////////// -/////////////////////////////ACCESSIBILITY//////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - -export namespace accessibility { - - // accessibility - export class AccessibilityManager { - - constructor(renderer: CanvasRenderer | WebGLRenderer); - - protected div: HTMLElement; - protected pool: HTMLElement[]; - protected renderId: number; - debug: boolean; - renderer: SystemRenderer; - protected children: IAccessibleTarget[]; - protected isActive: boolean; - - protected activate(): void; - protected deactivate(): void; - protected updateAccessibleObjects(displayObject: DisplayObject): void; - protected update(): void; - protected capHitArea(hitArea: IHitArea): void; - protected addChild(displayObject: DisplayObject): void; - protected _onClick(e: interaction.InteractionEvent): void; - protected _onFocus(e: interaction.InteractionEvent): void; - protected _onFocusOut(e: interaction.InteractionEvent): void; - protected _onKeyDown(e: interaction.InteractionEvent): void; - protected _onMouseMove(): void; - - destroy(): void; - - } - export interface IAccessibleTarget { - - accessible: boolean; - accessibleTitle: string; - accessibleHint: string; - tabIndex: number; - - } - -} - -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////CORE////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - -// const - -export namespace CONST { - export var VERSION: string; - export var PI_2: number; - export var RAD_TO_DEG: number; - export var DEG_TO_RAD: number; - export var TARGET_FPMS: number; - export var RENDERER_TYPE: { - UNKNOWN: number; - WEBGL: number; - CANVAS: number; - }; - export var BLEND_MODES: { - NORMAL: number; - ADD: number; - MULTIPLY: number; - SCREEN: number; - OVERLAY: number; - DARKEN: number; - LIGHTEN: number; - COLOR_DODGE: number; - COLOR_BURN: number; - HARD_LIGHT: number; - SOFT_LIGHT: number; - DIFFERENCE: number; - EXCLUSION: number; - HUE: number; - SATURATION: number; - COLOR: number; - LUMINOSITY: number; - }; - export var DRAW_MODES: { - POINTS: number; - LINES: number; - LINE_LOOP: number; - LINE_STRIP: number; - TRIANGLES: number; - TRIANGLE_STRIP: number; - TRIANGLE_FAN: number; - }; - export var SCALE_MODES: { - LINEAR: number, - NEAREST: number - }; - export var GC_MODES: { - AUTO: number; - MANUAL: number; - }; - export var WRAP_MODES: { - CLAMP: number; - MIRRORED_REPEAT: number; - REPEAT: number; - }; - export var TRANSFORM_MODE: { - DEFAULT: number; - DYNAMIC: number; - STATIC: number; - }; - export var URL_FILE_EXTENSION: RegExp | string; - export var DATA_URI: RegExp | string; - export var SVG_SIZE: RegExp | string; - export var SHAPES: { - POLY: number; - RECT: number; - CIRC: number; - ELIP: number; - RREC: number; - }; - export var PRECISION: { - LOW: string; - MEDIUM: string; - HIGH: string; - }; - export var TEXT_GRADIENT: { - LINEAR_VERTICAL: number; - LINEAR_HORIZONTAL: number; - }; - export var TEXT_STYLE_CHANGED: string; - -} - -// display - -export interface IDestroyOptions { - children?: boolean; - texture?: boolean; - baseTexture?: boolean; -} -export class Bounds { - - minX: number; - minY: number; - maxX: number; - maxY: number; - rect: Rectangle; - - isEmpty(): boolean; - clear(): void; - - getRectangle(rect?: Rectangle): Rectangle; - addPoint(point: Point): void; - addQuad(vertices: number[]): Bounds; - addFrame(transform: Transform, x0: number, y0: number, x1: number, y1: number): void; - addVertices(transform: Transform, vertices: number[], beginOffset: number, endOffset: number): void; - addBounds(bounds: Bounds): void; - addBoundsMask(bounds: Bounds, mask: Bounds): void; - addBoundsArea(bounds: Bounds, area: Rectangle): void; - -} -export class Container extends DisplayObject { - - // begin extras.getChildByName - getChildByName(name: string): DisplayObject; - // end extras.getChildByName - - children: DisplayObject[]; - width: number; - height: number; - - protected onChildrenChange: (...args: any[]) => void; - addChild(child: T, ...additionalChildren: DisplayObject[]): T; - addChildAt(child: T, index: number): T; - swapChildren(child: DisplayObject, child2: DisplayObject): void; - getChildIndex(child: DisplayObject): number; - setChildIndex(child: DisplayObject, index: number): void; - getChildAt(index: number): DisplayObject; - removeChild(child: DisplayObject): DisplayObject; - removeChildAt(index: number): DisplayObject; - removeChildren(beginIndex?: number, endIndex?: number): DisplayObject[]; - updateTransform(): void; - calculateBounds(): void; - protected _calculateBounds(): void; - protected containerUpdateTransform(): void; - renderWebGL(renderer: WebGLRenderer): void; - renderAdvancedWebGL(renderer: WebGLRenderer): void; - protected _renderWebGL(renderer: WebGLRenderer): void; - protected _renderCanvas(renderer: CanvasRenderer): void; - renderCanvas(renderer: CanvasRenderer): void; - destroy(options?: IDestroyOptions | boolean): void; - - once(event: "added", fn: (displayObject: DisplayObject) => void, context?: any): utils.EventEmitter; - once(event: "removed", fn: (DisplayObject: DisplayObject) => void, context?: any): utils.EventEmitter; - once(event: string, fn: Function, context?: any): utils.EventEmitter; - on(event: "added", fn: (displayObject: DisplayObject) => void, context?: any): utils.EventEmitter; - on(event: "removed", fn: (DisplayObject: DisplayObject) => void, context?: any): utils.EventEmitter; - on(event: string, fn: Function, context?: any): utils.EventEmitter; - off(event: string, fn: Function, context?: any): utils.EventEmitter; - -} -export class DisplayObject extends utils.EventEmitter implements interaction.InteractiveTarget { - - // begin extras.cacheAsBitmap - protected _cacheAsBitmap: boolean; - protected _cacheData: boolean; - cacheAsBitmap: boolean; - protected _renderCachedWebGL(renderer: WebGLRenderer): void; - protected _initCachedDisplayObject(renderer: WebGLRenderer): void; - protected _renderCachedCanvas(renderer: CanvasRenderer): void; - protected _initCachedDisplayObjectCanvas(renderer: CanvasRenderer): void; - protected _calculateCachedBounds(): Rectangle; - protected _getCachedLocalBounds(): Rectangle; - protected _destroyCachedDisplayObject(): void; - protected _cacheAsBitmapDestroy(): void; - // end extras.cacheAsBitmap - - // begin extras.getChildByName - name: string; - // end extras.getChildByName - - // begin extras.getGlobalPosition - getGlobalPosition(point?: Point, skipUpdate?: boolean): Point; - // end extras.getGlobalPosition - - // begin accessible target - accessible: boolean; - accessibleTitle: string; - accessibleHint: string; - tabIndex: number; - // end accessible target - - // begin interactive target - interactive: boolean; - buttonMode: boolean; - hitArea: IHitArea; - interactiveChildren: boolean; - defaultCursor: string; - _isRightDown: boolean; - _isLeftDown: boolean; - // end interactive target - - transform: TransformBase; - alpha: number; - visible: boolean; - renderable: boolean; - parent: Container; - worldAlpha: number; - filterArea: Rectangle; - protected _filters: Filter[]; - protected _enabledFilters: Filter[]; - protected _bounds: Bounds; - protected _boundsID: number; - protected _lastBoundsID: number; - protected _boundsRect: Rectangle; - protected _localBoundsRect: Rectangle; - protected _mask: Rectangle; - x: number; - y: number; - worldTransform: Matrix; - localTransform: Matrix; - position: Point; - scale: Point; - pivot: Point; - skew: Point; - rotation: number; - worldVisible: boolean; - mask: PIXI.Graphics | PIXI.Sprite; - filters: Filter[]; - - updateTransform(): void; - protected displayObjectUpdateTransform(): void; - protected _recursivePostUpdateTransform(): void; - getBounds(skipUpdate?: boolean, rect?: Rectangle): Rectangle; - getLocalBounds(rect?: Rectangle): Rectangle; - toGlobal(position: Point, point?: Point, skipUpdate?: boolean): Point; - toLocal(position: Point, from?: DisplayObject, point?: Point, skipUpdate?: boolean): Point; - protected renderWebGL(renderer: WebGLRenderer): void; - renderCanvas(renderer: CanvasRenderer): void; - setParent(container: Container): Container; - setTransform(x?: number, y?: number, scaleX?: number, scaleY?: number, rotation?: number, skewX?: number, skewY?: number, pivotX?: number, pivotY?: number): DisplayObject; - destroy(): void; - - on(event: string, fn: Function, context?: any): utils.EventEmitter; - once(event: string, fn: Function, context?: any): utils.EventEmitter; - off(event: string, fn: Function, context?: any): utils.EventEmitter; - - /* - on(event: 'click', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'mousedown', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'mouseout', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'mouseover', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'mouseup', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'mouseclick', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'mouseupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'rightclick', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'rightdown', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'rightup', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'rightupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'tap', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'touchend', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'touchendoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'touchmove', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'touchstart', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - - once(event: 'click', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'mousedown', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'mouseout', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'mouseover', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'mouseup', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'mouseclick', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'mouseupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'rightclick', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'rightdown', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'rightup', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'rightupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'tap', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'touchend', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'touchendoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'touchmove', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'touchstart', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - */ - -} - -export class TransformBase { - - static IDENTITY: TransformBase; - - worldTransform: Matrix; - localTransform: Matrix; - protected _worldID: number; - updateLocalTransform(): void; - updateTransform(parentTransform: TransformBase): void; - updateWorldTransform(parentTransform: TransformBase): void; - -} -export class TransformStatic extends TransformBase { - - position: ObservablePoint; - scale: ObservablePoint; - pivot: ObservablePoint; - skew: ObservablePoint; - - protected _rotation: number; - protected _sr: number; - protected _cr: number; - protected _cy: number; - protected _sy: number; - protected _nsx: number; - protected _cx: number; - protected _currentLocalID: number; - - protected onChange(): void; - updateSkew(): void; - updateLocalTransform(): void; - updateTransform(parentTransform: TransformBase): void; - setFromMatrix(matrix: Matrix): void; - - rotation: number; - -} -export class Transform extends TransformBase { - - constructor(); - - position: Point; - scale: Point; - skew: ObservablePoint; - pivot: Point; - - protected _rotation: number; - protected _sr: number; - protected _cr: number; - protected _cy: number; - protected _sy: number; - protected _nsx: number; - protected _cx: number; - - updateSkew(): void; - setFromMatrix(matrix: Matrix): void; - - rotation: number; - -} - -// graphics - -export class GraphicsData { - - constructor(lineWidth: number, lineColor: number, lineAlpha: number, fillColor: number, fillAlpha: number, fill: boolean, shape: IShape | Circle | Rectangle | RoundedRectangle | Ellipse | Polygon); - - lineWidth: number; - lineColor: number; - lineAlpha: number; - protected _lineTint: number; - fillColor: number; - fillAlpha: number; - protected _fillTint: number; - fill: boolean; - protected holes: IShape[]; - shape: IShape | Circle | Rectangle | RoundedRectangle | Ellipse | Polygon; - type: number; - clone(): GraphicsData; - addHole(shape: IShape | Circle | Rectangle | RoundedRectangle | Ellipse | Polygon): void; - destroy(options?: IDestroyOptions | boolean): void; - -} -export class Graphics extends Container { - - fillAlpha: number; - lineWidth: number; - lineColor: number; - protected graphicsData: GraphicsData[]; - tint: number; - protected _prevTint: number; - blendMode: number; - currentPath: GraphicsData; - protected _webGL: any; - isMask: boolean; - boundsPadding: number; - protected _localBounds: Bounds; - dirty: boolean; - fastRectDirty: number; - clearDirty: number; - boundsDirty: number; - protected cachedSpriteDirty: boolean; - protected _spriteRect: Rectangle; - protected _fastRect: boolean; - - static _SPRITE_TEXTURE: Texture; - - clone(): Graphics; - lineStyle(lineWidth?: number, color?: number, alpha?: number): Graphics; - moveTo(x: number, y: number): Graphics; - lineTo(x: number, y: number): Graphics; - quadraticCurveTo(cpX: number, cpY: number, toX: number, toY: number): Graphics; - bezierCurveTo(cpX: number, cpY: number, cpX2: number, cpY2: number, toX: number, toY: number): Graphics; - arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): Graphics; - arc(cx: number, cy: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): Graphics; - beginFill(color: number, alpha?: number): Graphics; - endFill(): Graphics; - drawRect(x: number, y: number, width: number, height: number): Graphics; - drawRoundedRect(x: number, y: number, width: number, height: number, radius: number): Graphics; - drawCircle(x: number, y: number, radius: number): Graphics; - drawEllipse(x: number, y: number, width: number, height: number): Graphics; - drawPolygon(path: number[] | Point[]): Graphics; - clear(): Graphics; - isFastRect(): boolean; - protected _renderCanvas(renderer: CanvasRenderer): void; - protected _calculateBounds(): Rectangle; - protected _renderSpriteRect(renderer: PIXI.SystemRenderer): void; - containsPoint(point: Point): boolean; - updateLocalBounds(): void; - drawShape(shape: IShape | Circle | Rectangle | Ellipse | Polygon | RoundedRectangle): GraphicsData; - generateCanvasTexture(scaleMode?: number, resolution?: number): Texture; - protected closePath(): Graphics; - protected addHole(): Graphics; - destroy(options?: IDestroyOptions | boolean): void; - -} -export class CanvasGraphicsRenderer { - - constructor(renderer: SystemRenderer); - render(graphics: Graphics): void; - protected updateGraphicsTint(graphics: Graphics): void; - protected renderPolygon(points: Point[], close: boolean, context: CanvasRenderingContext2D): void; - destroy(): void; - -} -export class GraphicsRenderer extends ObjectRenderer { - - constructor(renderer: PIXI.CanvasRenderer); - - protected graphicsDataPool: GraphicsData[]; - protected primitiveShader: PrimitiveShader; - gl: WebGLRenderingContext; - - CONTEXT_UID: number; - - destroy(): void; - render(graphics: Graphics): void; - protected updateGraphics(graphics: PIXI.Graphics): void; - getWebGLData(webGL: WebGLRenderingContext, type: number): WebGLGraphicsData; - -} -export class WebGLGraphicsData { - - constructor(gl: WebGLRenderingContext, shader: glCore.GLShader, attribsState: glCore.IAttribState); - - gl: WebGLRenderingContext; - color: number[]; - points: Point[]; - indices: number[]; - buffer: WebGLBuffer; - indexBuffer: WebGLBuffer; - dirty: boolean; - glPoints: number[]; - glIndices: number[]; - shader: glCore.GLShader; - vao: glCore.VertexArrayObject; - - reset(): void; - upload(): void; - destroy(): void; - -} -export class PrimitiveShader extends glCore.GLShader { } - -// math - -export namespace GroupD8 { - - export var E: number; - export var SE: number; - export var S: number; - export var SW: number; - export var W: number; - export var NW: number; - export var N: number; - export var NE: number; - export var MIRROR_HORIZONTAL: number; - export var MIRROR_VERTICAL: number; - - export function uX(ind: number): number; - export function uY(ind: number): number; - export function vX(ind: number): number; - export function vY(ind: number): number; - export function inv(rotation: number): number; - export function add(rotationSecond: number, rotationFirst: number): number; - export function sub(rotationSecond: number, rotationFirst: number): number; - export function rotate180(rotation: number): number; - export function isSwapWidthHeight(rotation: number): boolean; - export function byDirection(dx: number, dy: number): number; - export function matrixAppendRotationInv(matrix: Matrix, rotation: number, tx: number, ty: number): void; - -} -export class Matrix { - - a: number; - b: number; - c: number; - d: number; - tx: number; - ty: number; - - fromArray(array: number[]): void; - set(a: number, b: number, c: number, d: number, tx: number, ty: number): Matrix; - toArray(transpose?: boolean, out?: number[]): number[]; - apply(pos: Point, newPos?: Point): Point; - applyInverse(pos: Point, newPos?: Point): Point; - translate(x: number, y: number): Matrix; - scale(x: number, y: number): Matrix; - rotate(angle: number): Matrix; - append(matrix: Matrix): Matrix; - setTransform(x: number, y: number, pivotX: number, pivotY: number, scaleX: number, scaleY: number, rotation: number, skewX: number, skewY: number): PIXI.Matrix; - prepend(matrix: Matrix): Matrix; - invert(): Matrix; - identity(): Matrix; - decompose(transform: TransformBase): TransformBase; - clone(): Matrix; - copy(matrix: Matrix): Matrix; - - static IDENTITY: Matrix; - static TEMP_MATRIX: Matrix; - -} -export class ObservablePoint { - - constructor(cb: Function, scope?: any, x?: number, y?: number); - - x: number; - y: number; - cb: () => void; - scope: any; - - set(x?: number, y?: number): void; - copy(point: Point | ObservablePoint): void; - -} -export class Point { - - constructor(x?: number, y?: number); - - x: number; - y: number; - - clone(): Point; - copy(p: Point): void; - equals(p: Point): boolean; - set(x?: number, y?: number): void; - -} - -export interface IShape { -} -export interface IHitArea extends IShape { + export class Spritesheet { - contains(x: number, y: number): boolean; + static BATCH_SIZE: number; -} -export class Circle { - - constructor(x?: number, y?: number, radius?: number); - - x: number; - y: number; - radius: number; - type: number; - - clone(): Circle; - contains(x: number, y: number): boolean; - getBounds(): Rectangle; - -} -export class Ellipse { - - constructor(x?: number, y?: number, width?: number, height?: number); + constructor(baseTexture: BaseTexture, data: any, resolutionFilename?: string); - x: number; - y: number; - width: number; - height: number; - type: number; + baseTexture: BaseTexture; + textures: { [key: string]: Texture; }; + data: any; + resolution: number; + protected _frames: any; + protected _frameKeys: string; + protected _batchIndex: number; + protected _callback: (spriteSheet: this, textures: { [key: string]: Texture; }) => void; + protected _updateResolution(resolutionFilename: string): number; + parse(callback: (spriteSheet: this, textures: { [key: string]: Texture; }) => void): void; + protected _processFrames(initialFrameIndex: number): void; + protected _parseComplete(): void; + protected _nextBatch(): void; + destroy(destroyBase?: boolean): void; - clone(): Ellipse; - contains(x: number, y: number): boolean; - getBounds(): Rectangle; + } -} -export class Polygon { + export class VideoBaseTexture extends BaseTexture { - constructor(points: Point[] | number[]); - constructor(...points: Point[]); - constructor(...points: number[]); + constructor(source: HTMLVideoElement, scaleMode?: number); - closed: boolean; - points: number[]; - type: number; + autoUpdate: boolean; + autoPlay: boolean; + protected _isAutoUpdating: boolean; - clone(): Polygon; - contains(x: number, y: number): boolean; - close(): void; - -} -export class Rectangle { + update(): void; + protected _onCanPlay(): void; + protected _onPlayStart(): void; + protected _onPlayStop(): void; + destroy(): void; + protected _isSourcePlaying(): boolean; + protected _isSourceReady(): boolean; - constructor(x?: number, y?: number, width?: number, height?: number); + static fromVideo(video: HTMLVideoElement, scaleMode?: number): VideoBaseTexture; + static fromUrl(videoSrc: string | any | string[] | any[]): VideoBaseTexture; + static fromUrls(videoSrc: string | any | string[] | any[]): VideoBaseTexture; - x: number; - y: number; - width: number; - height: number; - type: number; - left: number; - right: number; - top: number; - bottom: number; - - static EMPTY: Rectangle; - - clone(): Rectangle; - copy(rectangle: Rectangle): Rectangle; - contains(x: number, y: number): boolean; - pad(paddingX: number, paddingY: number): void; - fit(rectangle: Rectangle): void; - enlarge(rect: Rectangle): void; - -} -export class RoundedRectangle { - - constructor(x?: number, y?: number, width?: number, height?: number, radius?: number); - - x: number; - y: number; - width: number; - height: number; - radius: number; - type: number; - - clone(): RoundedRectangle; - contains(x: number, y: number): boolean; - -} + source: HTMLVideoElement; + protected loadSource(source: HTMLVideoElement): void; + } -// renderers - -export interface IRendererOptions { - - view?: HTMLCanvasElement; - transparent?: boolean; - autoResize?: boolean; - antialias?: boolean; - resolution?: number; - clearBeforeRender?: boolean; - backgroundColor?: number; - roundPixels?: boolean; - context?: WebGLRenderingContext; - -} -export class SystemRenderer extends utils.EventEmitter { - - constructor(system: string, width?: number, height?: number, options?: IRendererOptions); - - type: number; - width: number; - height: number; - view: HTMLCanvasElement; - resolution: number; - transparent: boolean; - autoResize: boolean; - blendModes: any; // todo? - preserveDrawingBuffer: boolean; - clearBeforeRender: boolean; - roundPixels: boolean; - protected _backgroundColor: number; - protected _backgroundColorRgba: number[]; - protected _backgroundColorString: string; - protected _tempDisplayObjectParent: Container; - protected _lastObjectRendered: DisplayObject; - backgroundColor: number; - - resize(width: number, height: number): void; - generateTexture(displayObject: DisplayObject, scaleMode?: number, resolution?: number): RenderTexture; - render(...args: any[]): void; - destroy(removeView?: boolean): void; - -} -export class CanvasRenderer extends SystemRenderer { - - // plugintarget mixin start - static __plugins: any[]; - static registerPlugin(pluginName: string, ctor: Function): void; - plugins: any; - initPlugins(): void; - destroyPlugins(): void; - // plugintarget mixin end - - constructor(width?: number, height?: number, options?: IRendererOptions); - - rootContext: CanvasRenderingContext2D; - rootResolution: number; - refresh: boolean; - maskManager: CanvasMaskManager; - smoothProperty: string; - extract: extract.CanvasExtract; - - context: CanvasRenderingContext2D; - - render(displayObject: PIXI.DisplayObject, renderTexture?: PIXI.RenderTexture, clear?: boolean, transform?: PIXI.Transform, skipUpdateTransform?: boolean): void - setBlendMode(blendMode: number): void; - destroy(removeView?: boolean): void; - resize(w: number, h: number): void; - - on(event: "prerender", fn: () => void, context?: any): utils.EventEmitter; - on(event: "postrender", fn: () => void, context?: any): utils.EventEmitter; - on(event: string, fn: Function, context?: any): utils.EventEmitter; - once(event: "prerender", fn: () => void, context?: any): utils.EventEmitter; - once(event: "postrender", fn: () => void, context?: any): utils.EventEmitter; - once(event: string, fn: Function, context?: any): utils.EventEmitter; - off(event: string, fn: Function, context?: any): utils.EventEmitter; - -} -export class CanvasMaskManager { - - constructor(renderer: CanvasRenderer); - - pushMask(maskData: any): void; - protected renderGraphicsShape(graphics: Graphics): void; - popMask(renderer: WebGLRenderer | CanvasRenderer): void; - destroy(): void; - -} -export class CanvasRenderTarget { - - constructor(width: number, height: number, resolution: number); - - canvas: HTMLCanvasElement; - context: CanvasRenderingContext2D; - resolution: number; - - width: number; - height: number; - - clear(): void; - resize(width: number, height: number): void; - destroy(): void; - -} + // ticker -export interface IWebGLRendererOptions { + namespace ticker { - view?: HTMLCanvasElement; - transparent?: boolean; - autoResize?: boolean; - antialias?: boolean; - forceFXAA?: boolean; - resolution?: number; - clearBeforeRender?: boolean; - preserveDrawingBuffer?: boolean; - roundPixels?: boolean; + export const shared: Ticker; -} -export class WebGLRenderer extends SystemRenderer { - - // plugintarget mixin start - static __plugins: any[]; - static registerPlugin(pluginName: string, ctor: Function): void; - plugins: any; - initPlugins(): void; - destroyPlugins(): void; - // plugintarget mixin end - - constructor(width?: number, height?: number, options?: IWebGLRendererOptions); - - protected _contextOptions: { - alpha: boolean; - antiAlias: boolean; - premultipliedAlpha: boolean; - stencil: boolean; - preseveDrawingBuffer: boolean; - }; - protected _backgroundColorRgba: number[]; - maskManager: MaskManager; - stencilManager: StencilManager; - emptyRenderer: ObjectRenderer; - currentRenderer: ObjectRenderer; - gl: WebGLRenderingContext; - CONTEXT_UID: number; - state: WebGLState; - renderingToScreen: boolean; - boundTextures: Texture[]; - filterManager: FilterManager; - textureManager: TextureManager; - extract: extract.WebGLExtract; - protected drawModes: any; - protected _activeShader: Shader; - _activeRenderTarget: RenderTarget; - protected _initContext(): void; - - render(displayObject: PIXI.DisplayObject, renderTexture?: PIXI.RenderTexture, clear?: boolean, transform?: PIXI.Transform, skipUpdateTransform?: boolean): void - setObjectRenderer(objectRenderer: ObjectRenderer): void; - flush(): void; - resize(width: number, height: number): void; - setBlendMode(blendMode: number): void; - clear(clearColor?: number): void; - setTransform(matrix: Matrix): void; - bindRenderTexture(renderTexture: RenderTexture, transform: Transform): WebGLRenderer; - bindRenderTarget(renderTarget: RenderTarget): WebGLRenderer; - bindShader(shader: Shader): WebGLRenderer; - bindTexture(texture: Texture | BaseTexture, location?: number, forceLocation?: boolean): number; - unbindTexture(texture: Texture | BaseTexture): WebGLRenderer; - createVao(): glCore.VertexArrayObject; - bindVao(vao: glCore.VertexArrayObject): WebGLRenderer; - reset(): WebGLRenderer; - handleContextLost: (event: WebGLContextEvent) => void; - handleContextRestored: () => void; - destroy(removeView?: boolean): void; - - on(event: "context", fn: (gl: WebGLRenderingContext) => void, context?: any): utils.EventEmitter; - on(event: "prerender", fn: () => void, context?: any): utils.EventEmitter; - on(event: "postrender", fn: () => void, context?: any): utils.EventEmitter; - on(event: string, fn: Function, context?: any): utils.EventEmitter; - once(event: "context", fn: (gl: WebGLRenderingContext) => void, context?: any): utils.EventEmitter; - once(event: "prerender", fn: () => void, context?: any): utils.EventEmitter; - once(event: "postrender", fn: () => void, context?: any): utils.EventEmitter; - once(event: string, fn: Function, context?: any): utils.EventEmitter; - off(event: string, fn: Function, context?: any): utils.EventEmitter; + export class Ticker { -} -export class WebGLState { - - constructor(gl: WebGLRenderingContext); - - activeState: number[]; - defaultState: number[]; - stackIndex: number; - stack: number[]; - gl: WebGLRenderingContext; - maxAttribs: number; - attribState: glCore.IAttribState; - nativeVaoExtension: any; - - push(): void; - pop(): void; - setState(state: number[]): void; - setBlend(value: number): void; - setBlendMode(value: number): void; - setDepthTest(value: number): void; - setCullFace(value: number): void; - setFrontFace(value: number): void; - resetAttributes(): void; - resetToDefault(): void; + protected _tick(time: number): void; + protected _emitter: utils.EventEmitter; + protected _requestId: number | null; + protected _maxElapsedMS: number; -} -export class TextureManager { + protected _requestIfNeeded(): void; + protected _cancelIfNeeded(): void; + protected _startIfPossible(): void; - constructor(renderer: WebGLRenderer); + autoStart: boolean; + deltaTime: number; + elapsedMS: number; + lastTime: number; + speed: number; + started: boolean; - renderer: WebGLRenderer; - gl: WebGLRenderingContext; - protected _managedTextures: WebGLTexture[]; + FPS: number; + minFPS: number; - bindTexture(): void; - getTexture(): WebGLTexture; - updateTexture(texture: BaseTexture | Texture): WebGLTexture; - destroyTexture(texture: BaseTexture, _skipRemove?: boolean): void; - removeAll(): void; - destroy(): void; + add(fn: (deltaTime: number) => void, context?: any): Ticker; + addOnce(fn: (deltaTime: number) => void, context?: any): Ticker; + remove(fn: (deltaTime: number) => void, context?: any): Ticker; + start(): void; + stop(): void; + update(): void; -} -export class TextureGarbageCollector { + } - constructor(renderer: WebGLRenderer); + } - renderer: WebGLRenderer; - count: number; - checkCount: number; - maxIdle: number; - checkCountMax: number; - mode: number; + // shader - update(): void; - run(): void; - unload(): void; + export class Shader extends glCore.GLShader { } -} -export abstract class ObjectRenderer extends WebGLManager { + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////EXTRACT/////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// - constructor(renderer: WebGLRenderer); + export namespace extract { - start(): void; - stop(): void; - flush(): void; + export class CanvasExtract { - render(...args: any[]): void; + protected renderer: CanvasRenderer; + + constructor(renderer: CanvasRenderer); + + image(target?: DisplayObject | RenderTexture): HTMLImageElement; + base64(target?: DisplayObject | RenderTexture): string; + canvas(target?: DisplayObject | RenderTexture): HTMLCanvasElement; + pixels(renderTexture?: DisplayObject | RenderTexture): number[]; + + destroy(): void; + + } + export class WebGLExtract { + protected renderer: WebGLRenderer; + + constructor(renderer: WebGLRenderer); -} -export class Quad { - - constructor(gl: WebGLRenderingContext); - - gl: WebGLRenderingContext; - vertices: number[]; - uvs: number[]; - interleaved: number[]; - indices: number[]; - vertexBuffer: WebGLBuffer; - vao: glCore.VertexArrayObject; - initVao(shader: glCore.GLShader): void; - map(targetTextureFrame: Rectangle, destinationFrame: Rectangle): Quad; - upload(): Quad; - destroy(): void; + image(target?: DisplayObject | RenderTexture): HTMLImageElement; + base64(target?: DisplayObject | RenderTexture): string; + canvas(target?: DisplayObject | RenderTexture): HTMLCanvasElement; + pixels(renderTexture?: DisplayObject | RenderTexture): number[]; -} -export class RenderTarget { - - constructor(gl: WebGLRenderingContext, width: number, height: number, scaleMode: number, resolution: number, root?: boolean); - - gl: WebGLRenderingContext; - frameBuffer: glCore.GLFramebuffer; - texture: Texture; - clearColor: number[]; - size: Rectangle; - resolution: number; - projectionMatrix: Matrix; - transform: Matrix; - frame: Rectangle; - defaultFrame: Rectangle; - destinationFrame: Rectangle; - sourceFrame: Rectangle; - stencilBuffer: glCore.GLFramebuffer; - stencilMaskStack: Graphics[]; - filterData: { - index: number, - stack: Array<{ - renderTarget: RenderTarget, - filter: any[]; - bounds: Rectangle - }> - }; - scaleMode: number; - root: boolean; - - clear(clearColor?: number[]): void; - attachStencilBuffer(): void; - setFrame(destinationFrame: Rectangle, sourceFrame: Rectangle): void; - activate(): void; - calculateProjection(destinationFrame: Rectangle, sourceFrame: Rectangle): void; - resize(width: number, height: number): void; - destroy(): void; + destroy(): void; + } -} + } -export class BlendModeManager extends WebGLManager { + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////EXTRAS//////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// - constructor(renderer: WebGLRenderer); + export namespace extras { - currentBlendMode: number; + export interface IBitmapTextStyle { - setBlendMode(blendMode: number): boolean; + font?: string | { + name?: string; + size?: number; + }; + align?: string; + tint?: number; -} -export class FilterManager extends WebGLManager { - - constructor(renderer: WebGLRenderer); - - gl: WebGLRenderingContext; - quad: Quad; - stack: Array<{ - renderTarget: RenderTarget; - sourceFrame: Rectangle; - destinationFrame: Rectangle; - filters: Filter[]; - target: any; - resolution: number; - }>; - stackIndex: number; - shaderCache: any; - filterData: any; - - pushFilter(target: RenderTarget, filters: Filter[]): void; - popFilter(): void; - applyFilter(shader: glCore.GLShader | Filter, inputTarget: RenderTarget, outputTarget: RenderTarget, clear?: boolean): void; - syncUniforms(shader: glCore.GLShader, filter: Filter): void; - getRenderTarget(clear?: boolean, resolution?: number): RenderTarget; - returnRenderTarget(renderTarget: RenderTarget): RenderTarget; - calculateScreenSpaceMatrix(outputMatrix: Matrix): Matrix; - calculateNormalisedScreenSpaceMatrix(outputMatrix: Matrix): Matrix; - calculateSpriteMatrix(outputMatrix: Matrix, sprite: Sprite): Matrix; - destroy(): void; - emptyPool(): void; - getPotRenderTarget(gl: WebGLRenderingContext, minWidth: number, minHeight: number, resolution: number): RenderTarget; - freePotRenderTarget(renderTarget: RenderTarget): void; + } + export class BitmapText extends Container { -} -export class StencilMaskStack { + static registerFont(xml: XMLDocument, texture: Texture): any; - stencilStack: any[]; - reverse: boolean; - count: number; + constructor(text: string, style?: IBitmapTextStyle); -} -export class MaskManager extends WebGLManager { - - scissor: boolean; - scissorData: any; - scissorRenderTarget: RenderTarget; - enableScissor: boolean; - alphaMaskPool: number[]; - alphaMaskIndex: number; - pushMask(target: RenderTarget, maskData: Sprite | Graphics): void; - popMask(target: RenderTarget, maskData: Sprite | Graphics): void; - pushSpriteMask(target: RenderTarget, maskData: Sprite | Graphics): void; - popSpriteMask(): void; - pushStencilMask(maskData: Sprite | Graphics): void; - popStencilMask(): void; - pushScissorMask(target: RenderTarget, maskData: Sprite | Graphics): void; - popScissorMask(): void; + protected _textWidth: number; + protected _textHeight: number; + textWidth: number; + textHeight: number; + protected _glyphs: Sprite[]; + protected _font: string | { + name?: string; + size?: number; + }; + font: string | { + name?: string; + size?: number; + }; + protected _text: string; + maxWidth: number; + maxLineHeight: number; + protected _anchor: ObservablePoint; + dirty: boolean; + tint: number; + align: string; + text: string; + anchor: PIXI.Point | number; -} -export class StencilManager extends WebGLManager { + protected updateText(): void; + updateTransform(): void; + getLocalBounds(): Rectangle; + protected validate(): void; - constructor(renderer: WebGLRenderer); + static fonts: any; - stencilMaskStack: Graphics[]; + } + export class AnimatedSprite extends Sprite { - setMaskStack(stencilMasStack: Graphics[]): void; - pushStencil(graphics: Graphics): void; - popStencil(): void; - destroy(): void; + constructor(textures: Texture[] | { texture: Texture, time?: number }[], autoUpdate?: boolean); -} -export class WebGLManager { + protected _autoUpdate: boolean; + protected _textures: Texture[]; + protected _durations: number[]; + textures: Texture[] | { texture: Texture, time?: number }[]; + animationSpeed: number; + loop: boolean; + onComplete: () => void; + onFrameChange: (currentFrame: number) => void; + protected _currentTime: number; + playing: boolean; + totalFrames: number; + currentFrame: number; + stop(): void; + play(): void; + gotoAndStop(frameNumber: number): void; + gotoAndPlay(frameNumber: number): void; + protected update(deltaTime: number): void; + destroy(): void; + + static fromFrames(frame: string[]): AnimatedSprite; + static fromImages(images: string[]): AnimatedSprite; + + } + export class TextureTransform { - constructor(renderer: WebGLRenderer); + constructor(texture: Texture, clampMargin?: number); - renderer: WebGLRenderer; - onContextChange(): void; - destroy(): void; + protected _texture: Texture; + protected mapCoord: Matrix; + protected uClampFrame: Float32Array; + protected uClampOffset: Float32Array; + protected _lastTextureID: number; + + clampOffset: number; + clampMargin: number; + + texture: Texture; -} -export interface IUniformData { + update(forceUpdate?: boolean): void; + + } + export class TilingSprite extends Sprite { + + constructor(texture: Texture, width?: number, height?: number); + + tileTransform: TransformStatic; + protected _width: number; + protected _height: number; + protected _canvasPattern: CanvasPattern; + uvTransform: TextureTransform; + uvRespectAnchor: boolean; + + clampMargin: number; + tileScale: Point | ObservablePoint; + tilePosition: Point | ObservablePoint; + + protected _onTextureUpdate(): void; + protected _renderWebGL(renderer: WebGLRenderer): void; + protected _renderCanvas(renderer: CanvasRenderer): void; + protected _calculateBounds(): void; + getLocalBounds(rect?: Rectangle): Rectangle; + containsPoint(point: Point): boolean; + destroy(): void; + + static from(source: number | string | BaseTexture | HTMLCanvasElement | HTMLVideoElement, width?: number, height?: number): TilingSprite; + static fromFrame(frameId: string, width?: number, height?: number): TilingSprite; + // if you remove the next line, the class will break. https://github.com/pixijs/pixi-typescript/issues/96 + static fromImage(imageId: string, crossorigin?: boolean, scaleMode?: number): Sprite; + static fromImage(imageId: string, width?: number, height?: number, crossorigin?: boolean, scaleMode?: number): TilingSprite; + + width: number; + height: number; + + } + export class TilingSpriteRenderer extends ObjectRenderer { + + constructor(renderer: WebGLRenderer); + + render(ts: TilingSprite): void; + + } + + } + + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////FILTERS/////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// - type: string; - value: any; + export namespace filters { - // name is set by pixi if uniforms were automatically extracted from shader code, but not used anywhere - name?: string; + export class FXAAFilter extends Filter { } + export class BlurFilter extends Filter { -} -export class Filter { - - // param uniforms should be an object matching type {[name: string]: IUniformData}; - // left untyped as there's no way to define the type without requiring an index signature or making this class generic - constructor(vertexSrc?: string, fragmentSrc?: string, uniforms?: any); - - vertextSrc: string; - fragmentSrc: string; - protected uniformData: { [name: string]: IUniformData }; - uniforms: { [name: string]: any }; - glShaders: any; - glShaderKey: string; - padding: number; - resolution: number; - blendMode: number; - enabled: boolean; - apply(filterManager: FilterManager, input: RenderTarget, output: RenderTarget, clear?: boolean): void; - - static defaultVertexSrc: string; - static defaultFragmentSrc: string; + constructor(strength?: number, quality?: number, resolution?: number, kernelSize?: number); -} -export class SpriteMaskFilter extends Filter { + blurXFilter: BlurXFilter; + blurYFilter: BlurYFilter; + resolution: number; + padding: number; + passes: number; + blur: number; + blurX: number; + blurY: number; + quality: number; - constructor(sprite: Sprite); + } + export class BlurXFilter extends Filter { - maskSprite: Sprite; - maskMatrix: Matrix; - apply(filterManager: FilterManager, input: RenderTarget, output: RenderTarget): void; + constructor(strength?: number, quality?: number, resolution?: number, kernelSize?: number); -} + protected _quality: number; -// sprites - -export class Sprite extends Container { - - constructor(texture?: Texture); - - protected _anchor: ObservablePoint; - anchor: ObservablePoint; - protected _texture: Texture; - protected _width: number; - protected _height: number; - tint: number; - protected _tint: number; - protected _tintRGB: number; - blendMode: number; - pluginName: string; - protected cachedTint: number; - texture: Texture; - protected textureDirty: boolean; - protected _textureID: number; - protected _transformID: number; - protected vertexTrimmedData: Float32Array; - vertexData: Float32Array; - width: number; - height: number; - - protected _onTextureUpdate(): void; - calculateVertices(): void; - protected _calculateBounds(): void; - protected calculateTrimmedVertices(): void; - protected onAnchorUpdate(): void; - protected _renderWebGL(renderer: WebGLRenderer): void; - protected _renderCanvas(renderer: CanvasRenderer): void; - getLocalBounds(): Rectangle; - containsPoint(point: Point): boolean; - destroy(options?: IDestroyOptions | boolean): void; - - static from(source: number | string | BaseTexture | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement): Sprite; - static fromFrame(frameId: string): Sprite; - static fromImage(imageId: string, crossorigin?: boolean, scaleMode?: number): Sprite; + quality: number; + passes: number; + resolution: number; + strength: number; + firstRun: boolean; + blur: number; -} -export class BatchBuffer { + } + export class BlurYFilter extends Filter { - vertices: ArrayBuffer; - float32View: number[]; - uint32View: number[]; + constructor(strength?: number, quality?: number, resolution?: number, kernelSize?: number); - destroy(): void; + protected _quality: number; -} -export class SpriteRenderer extends ObjectRenderer { - - constructor(renderer: PIXI.WebGLRenderer); - - vertSize: number; - vertByteSize: number; - size: number; - buffers: BatchBuffer[]; - indices: number[]; - shaders: Shader[]; - currentIndex: number; - tick: number; - groups: any[]; - sprites: Sprite[]; - vertexBuffers: number[]; - vaos: glCore.VertexArrayObject[]; - vaoMax: number; - vertexCount: number; - - protected onContextChanged: () => void; - protected onPrerender: () => void; - render(sprite: Sprite): void; - flush(): void; - start(): void; - stop(): void; - destroy(): void; + quality: number; + passes: number; + resolution: number; + strength: number; + firstRun: boolean; + blur: number; -} -export class CanvasSpriteRenderer extends ObjectRenderer { + } + export class ColorMatrixFilter extends Filter { - constructor(renderer: WebGLRenderer); + constructor(); - render(sprite: Sprite): void; - destroy(): void; + protected _loadMatrix(matrix: number[], multiply?: boolean): void; + protected _multiply(out: number[], a: number[], b: number[]): void; + protected _colorMatrix(matrix: number[]): void; -} -export namespace CanvasTinter { + matrix: number[]; - export function getTintedTexture(sprite: Sprite, color: number): HTMLCanvasElement; - export function tintWithMultiply(texture: Texture, color: number, canvas: HTMLCanvasElement): void; - export function tintWithOverlay(texture: Texture, color: number, canvas: HTMLCanvasElement): void; - export function tintWithPerPixel(texture: Texture, color: number, canvas: HTMLCanvasElement): void; - export function roundColor(color: number): number; + brightness(b: number, multiply?: boolean): void; + greyscale(scale: number, multiply?: boolean): void; + blackAndWhite(multiply?: boolean): void; + hue(rotation: number, multiply?: boolean): void; + contrast(amount: number, multiply?: boolean): void; + saturate(amount: number, multiply?: boolean): void; + desaturate(multiply?: boolean): void; + negative(multiply?: boolean): void; + sepia(multiply?: boolean): void; + technicolor(multiply?: boolean): void; + polaroid(multiply?: boolean): void; + toBGR(multiply?: boolean): void; + kodachrome(multiply?: boolean): void; + browni(multiply?: boolean): void; + vintage(multiply?: boolean): void; + colorTone(desaturation: number, toned: number, lightColor: string, darkColor: string, multiply?: boolean): void; + night(intensity: number, multiply?: boolean): void; + predator(amount: number, multiply?: boolean): void; + lsd(multiply?: boolean): void; + reset(): void; + + } + export class DisplacementFilter extends Filter { + + constructor(sprite: Sprite, scale?: number); + + scale: Point; + map: Texture; + + } + export class VoidFilter extends Filter { + glShaderKey: number; + } + + // pixi-filters.d.ts todo + // https://github.com/pixijs/pixi-filters/ + export class NoiseFilter extends Filter { + + noise: number; + + } + + } + + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////INTERACTION/////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + export namespace interaction { + + export interface InteractiveTarget { + + interactive: boolean; + interactiveChildren: boolean; + hitArea: PIXI.Rectangle | PIXI.Circle | PIXI.Ellipse | PIXI.Polygon | PIXI.RoundedRectangle; + buttonMode: boolean; + cursor: string; + trackedPointers(): { [key: number]: InteractionTrackingData; }; + + // depricated + defaultCursor: string; + + } + export interface InteractionTrackingData { + + readonly pointerId: number; + flags: number; + none: number; + over: boolean; + rightDown: boolean; + leftDown: boolean; + + } + export interface InteractionEvent { + + stopped: boolean; + target: DisplayObject; + currentTarget: DisplayObject; + type: string; + data: InteractionData; + stopPropagation(): void; + + } + export class InteractionData { + + global: Point; + target: DisplayObject; + originalEvent: Event; + identifier?: number; + + getLocalPosition(displayObject: DisplayObject, point?: Point, globalPos?: Point): Point; + + } + export interface InteractionManagerOptions { + autoPreventDefault?: boolean; + interactionFrequency?: number; + } + export class InteractionManager extends utils.EventEmitter { + + constructor(renderer: CanvasRenderer | WebGLRenderer | SystemRenderer, options?: InteractionManagerOptions); + + renderer: SystemRenderer; + autoPreventDefault: boolean; + interactionFrequency: number; + mouse: InteractionData; + activeInteractionData: { [key: number]: InteractionData; }; + interactionDataPool: InteractionData[]; + eventData: InteractionEvent; + protected interactionDOMElement: HTMLElement; + moveWhenInside: boolean; + eventsAdded: boolean; + protected mouseOverRenderer: boolean; + readonly supportsTouchEvents: boolean; + readonly supportsPointerEvents: boolean; + protected onPointerUp: (event: PointerEvent) => void; + protected processPointerUp: (interactionEvent: InteractionEvent, displayObject: Container | PIXI.Sprite | PIXI.extras.TilingSprite, hit: boolean) => void; + protected onPointerCancel: (event: PointerEvent) => void; + protected processPointerCancel: (interactionEvent: InteractionEvent, displayObject: PIXI.Container | PIXI.Sprite | PIXI.extras.TilingSprite) => void; + protected onPointerDown: (event: PointerEvent) => void; + protected processPointerDown: (interactionEvent: InteractionEvent, displayObject: PIXI.Container | PIXI.Sprite | PIXI.extras.TilingSprite, hit: boolean) => void; + protected onPointerMove: (event: PointerEvent) => void; + protected processPointerMove: (interactionEvent: InteractionEvent, displayObject: PIXI.Container | PIXI.Sprite | PIXI.extras.TilingSprite, hit: boolean) => void; + protected onPointerOut: (event: PointerEvent) => void; + protected processPointerOverOut: (interactionEvent: InteractionEvent, displayObject: PIXI.Container | PIXI.Sprite | PIXI.extras.TilingSprite, hit: boolean) => void; + protected onPointerOver: (event: PointerEvent) => void; + cursorStyles: { + default: string; + pointer: string; + }; + currentCursorMode: string; + cursor: string; + protected _tempPoint: Point; + resolution: number; + protected setTargetElement(element: HTMLCanvasElement, resolution?: number): void; + protected addEvents(): void; + protected removeEvents(): void; + update(deltaTime?: number): void; + setCursorMode(mode: string): void; + protected dispatchEvent(displayObject: Container | Sprite | extras.TilingSprite, eventString: string, eventData: any): void; + mapPositionToPoint(point: Point, x: number, y: number): void; + protected processInteractive(interactionEvent: InteractionEvent, displayObject: PIXI.Container | PIXI.Sprite | PIXI.extras.TilingSprite, func?: Function, hitTest?: boolean, interactive?: boolean): boolean; + protected onPointerComplete(originalEvent: PointerEvent, cancelled: boolean, func: Function): void; + protected getInteractionDataForPointerId(pointerId: number): InteractionData; + protected releaseInteractionDataForPointerId(pointerId: number): void; + protected configureInteractionEventForDOMEvent(interactionEvent: InteractionEvent, pointerEvent: PointerEvent, interactionData: InteractionData): InteractionEvent; + protected normalizeToPointerData(event: TouchEvent | MouseEvent | PointerEvent): PointerEvent[]; + destroy(): void; + + // depricated + defaultCursorStyle: string; + currentCursorStyle: string; + + } + + } + + ////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////LOADER///////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + // pixi loader extends + // https://github.com/englercj/resource-loader/ + // 2.0.6 + + class MiniSignalBinding { + + constructor(fn: Function, once?: boolean, thisArg?: any); + + protected _fn: Function; + protected _once: boolean; + protected _thisArg: any; + protected _next: MiniSignalBinding; + protected _prev: MiniSignalBinding; + protected _owner: MiniSignal; + + detach(): boolean; + + } + class MiniSignal { + + constructor(); + + protected _head: MiniSignalBinding; + protected _tail: MiniSignalBinding; + + handlers(exists?: boolean): MiniSignalBinding[] | boolean; + handlers(exists?: true): boolean; + handlers(exists?: false): MiniSignalBinding[]; + + has(node: MiniSignalBinding): boolean; + dispatch(): boolean; + add(fn: Function, thisArg?: any): any; + once(fn: Function, thisArg?: any): any; + detach(node: MiniSignalBinding): MiniSignal; + detachAll(): MiniSignal; + + } + + export namespace loaders { + + export interface ILoaderOptions { + + crossOrigin?: boolean | string; + loadType?: number; + xhrType?: string; + metaData?: any; + loadElement?: HTMLImageElement | HTMLAudioElement | HTMLVideoElement; + skipSource?: boolean; + + } + export interface IResourceDictionary { + + [index: string]: PIXI.loaders.Resource; + + } + + // As of ResourceLoader v2 we no longer require EventEmitter + // However, for depreciation reasons, it remains. + export class Loader extends utils.EventEmitter { + + // pixi overrides here + static addPixiMiddleware(fn: Function): void; + + // below this line is the original non-pixi loader + + static Resource: any; + static async: any; + static base64: any; + + constructor(baseUrl?: string, concurrency?: number); + + baseUrl: string; + progress: number; + loading: boolean; + defaultQueryString: string; + + protected _beforeMiddleware: Function[]; + protected _afterMiddleware: Function[]; + protected _resourcesParsing: Resource[]; + protected _boundLoadResource: (r: Resource, d: Function) => void; + protected _queue: any; + + resources: IResourceDictionary; + + onProgress: MiniSignal; + onError: MiniSignal; + onLoad: MiniSignal; + onStart: MiniSignal; + onComplete: MiniSignal; + + add(...params: any[]): this; + add(name: string, url: string, options?: ILoaderOptions, cb?: Function): this; + add(url: string, options?: ILoaderOptions, cb?: Function): this; + add(obj: any | any[], options?: ILoaderOptions, cb?: Function): this; + + pre(fn: Function): this; + use(fn: Function): this; + reset(): this; + load(cb?: Function): this; + + protected _prepareUrl(url: string): string; + protected _loadResource(resource: Resource, dequeue: Function): void; + protected _onComplete(): void; + protected _onLoad(resource: Resource): void; + + // depreciation + + on(event: "complete", fn: (loader: loaders.Loader, object: any) => void, context?: any): this; + on(event: "error", fn: (error: Error, loader: loaders.Loader, resource: Resource) => void, context?: any): this; + on(event: "load", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): this; + on(event: "progress", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): this; + on(event: "start", fn: (loader: loaders.Loader) => void, context?: any): this; + on(event: string, fn: Function, context?: any): this; + + once(event: "complete", fn: (loader: loaders.Loader, object: any) => void, context?: any): this; + once(event: "error", fn: (error: Error, loader: loaders.Loader, resource: Resource) => void, context?: any): this; + once(event: "load", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): this; + once(event: "progress", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): this; + once(event: "start", fn: (loader: loaders.Loader) => void, context?: any): this; + once(event: string, fn: Function, context?: any): this; + + } + export interface ITextureDictionary { + [index: string]: PIXI.Texture; + } + export class Resource { + + static setExtensionLoadType(extname: string, loadType: number): void; + static setExtensionXhrType(extname: string, xhrType: string): void; + + constructor(name: string, url: string | string[], options?: ILoaderOptions); + + protected _flags: number; + + name: string; + url: string; + extension: string; + data: any; + crossOrigin: boolean | string; + loadType: number; + xhrType: string; + metadata: any; + error: Error; + xhr: XMLHttpRequest | null; + children: Resource[]; + type: number; + progressChunk: number; + + protected _dequeue: Function; + protected _onLoadBinding: Function; + protected _boundComplete: Function; + protected _boundOnError: Function; + protected _boundOnProgress: Function; + protected _boundXhrOnError: Function; + protected _boundXhrOnAbort: Function; + protected _boundXhrOnLoad: Function; + protected _boundXdrOnTimeout: Function; + + onStart: MiniSignal; + onProgress: MiniSignal; + onComplete: MiniSignal; + onAfterMiddleware: MiniSignal; + + isDataUrl: boolean; + isComplete: boolean; + isLoading: boolean; + complete(): void; + abort(message?: string): void; + load(cb?: Function): void; + + protected _hasFlag(flag: number): boolean; + protected _setFlag(flag: number, value: boolean): void; + protected _loadElement(type: string): void; + protected _loadSourceElement(type: string): void; + protected _loadXhr(): void; + protected _loadXdr(): void; + protected _createSource(type: string, url: string, mime?: string): HTMLSourceElement; + protected _onError(event?: any): void; + protected _onProgress(event?: any): void; + protected _xhrOnError(): void; + protected _xhrOnAbort(): void; + protected _xdrOnTimeout(): void; + protected _xhrOnLoad(): void; + protected _determineCrossOrigin(url: string, loc: any): string; + protected _determineXhrType(): number; + protected _determineLoadType(): number; + protected _getExtension(): string; + protected _getMimeXhrType(type: number): string; + + static STATUS_FLAGS: { + NONE: number; + DATA_URL: number; + COMPLETE: number; + LOADING: number; + }; + + static TYPE: { + UNKNOWN: number; + JSON: number; + XML: number; + IMAGE: number; + AUDIO: number; + VIDEO: number; + TEXT: number; + }; + + static LOAD_TYPE: { + XHR: number; + IMAGE: number; + AUDIO: number; + VIDEO: number; + }; + + static XHR_RESPONSE_TYPE: { + DEFAULT: string; + BUFFER: string; + BLOB: string; + DOCUMENT: string; + JSON: string; + TEXT: string; + }; + + static EMPTY_GIF: string; + + texture: Texture; + spineAtlas: any; + spineData: any; + textures?: ITextureDictionary; + } + } + + ////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////MESH/////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + export namespace mesh { + + export class Mesh extends Container { + + constructor(texture: Texture, vertices?: Float32Array, uvs?: Float32Array, indices?: Uint16Array, drawMode?: number); + + protected _texture: Texture; + uvs: Float32Array; + vertices: Float32Array; + indices: Uint16Array; + dirty: number; + indexDirty: number; + dirtyVertex: boolean; + protected _geometryVersion: number; + blendMode: number; + pluginName: string; + canvasPadding: number; + drawMode: number; + texture: Texture; + tintRgb: Float32Array; + protected _glDatas: { [n: number]: any; }; + protected _renderWebGL(renderer: WebGLRenderer): void; + protected _renderCanvas(renderer: CanvasRenderer): void; + protected _onTextureUpdate(): void; + protected _calculateBounds(): void; + containsPoint(point: Point): boolean; + tint: number; + + static DRAW_MODES: { + TRIANGLE_MESH: number; + TRIANGLES: number; + }; + + } + + export class CanvasMeshRenderer { + + constructor(renderer: CanvasRenderer); + + renderer: CanvasRenderer; + + render(mesh: Mesh): void; + protected _renderTriangleMesh(mesh: Mesh): void; + protected _renderTriangles(mesh: Mesh): void; + protected _renderDrawTriangle(mesh: Mesh, index0: number, index1: number, index2: number): void; + protected renderMeshFlat(mesh: Mesh): void; + + destroy(): void; + + } + + export class MeshRenderer extends ObjectRenderer { + + constructor(renderer: WebGLRenderer); + + shader: Shader; + render(mesh: Mesh): void; - export var cacheStepsPerColorChannel: number; - export var convertTintToImage: boolean; - export var canUseMultiply: boolean; - export var tintMethod: Function; + } -} + export class Plane extends Mesh { + + constructor(texture: Texture, verticesX?: number, verticesY?: number); + protected _ready: boolean; + verticesX: number; + verticesY: number; + drawMode: number; + + refresh(): void; -// text -export interface TextStyleOptions { - align?: string; - breakWords?: boolean; - dropShadow?: boolean; - dropShadowAngle?: number; - dropShadowBlur?: number; - dropShadowColor?: string | number; - dropShadowDistance?: number; - fill?: string | string[] | number | number[] | CanvasGradient | CanvasPattern; - fillGradientType?: number; - fontFamily?: string; - fontSize?: number | string; - fontStyle?: string; - fontVariant?: string; - fontWeight?: string; - letterSpacing?: number; - lineHeight?: number; - lineJoin?: string; - miterLimit?: number; - padding?: number; - stroke?: string | number; - strokeThickness?: number; - styleID?: number; - textBaseline?: string; - wordWrap?: boolean; - wordWrapWidth?: number; -} + protected _onTexureUpdate(): void; -export class TextStyle implements TextStyleOptions { - align: string; - breakWords: boolean; - dropShadow: boolean; - dropShadowAngle: number; - dropShadowBlur: number; - dropShadowColor: string | number; - dropShadowDistance: number; - fill: string | string[] | number | number[] | CanvasGradient | CanvasPattern; - fillGradientType: number; - fontFamily: string; - fontSize: number | string; - fontStyle: string; - fontVariant: string; - fontWeight: string; - letterSpacing: number; - lineHeight: number; - lineJoin: string; - miterLimit: number; - padding: number; - stroke: string | number; - strokeThickness: number; - styleID: number; - textBaseline: string; - wordWrap: boolean; - wordWrapWidth: number; - constructor(style?: TextStyleOptions); - clone(): TextStyle; - reset(): void; -} + } -export class Text extends Sprite { - - static getFontStyle(style: TextStyleOptions): string; - static calculateFontProperties(style: string): any; - - constructor(text?: string, style?: TextStyleOptions); - - canvas: HTMLCanvasElement; - context: CanvasRenderingContext2D; - resolution: number; - protected _text: string; - protected _style: TextStyle; - protected _styleListener: Function; - protected _font: string; - protected localStyleID: number; - - static fontPropertiesCache: any; - static fontPropertiesCanvas: HTMLCanvasElement; - static fontPropertiesContext: CanvasRenderingContext2D; - - width: number; - height: number; - style: TextStyle; - text: string; - - protected updateText(respectDirty?: boolean): void; - protected drawLetterSpacing(text: string, x: number, y: number, isStroke?: boolean): void; - protected updateTexture(): void; - renderWebGL(renderer: WebGLRenderer): void; - protected _renderCanvas(renderer: CanvasRenderer): void; - protected wordWrap(text: string): string; - protected _calculateBounds(): void; - protected _onStyleChange: () => void; - protected _generateFillStyle(style: TextStyle, lines: string[]): string | number | CanvasGradient; - destroy(options?: IDestroyOptions | boolean): void; - dirty: boolean; + export class NineSlicePlane extends Plane { -} + constructor(texture: Texture, leftWidth?: number, topHeight?: number, rightWidth?: number, bottomHeight?: number); -// textures + width: number; + height: number; + leftWidth: number; + rightWidth: number; + topHeight: number; + bottomHeight: number; -export class BaseRenderTexture extends BaseTexture { + protected _leftWidth: number; + protected _rightWidth: number; + protected _topHeight: number; + protected _bottomHeight: number; + protected _height: number; + protected _width: number; + protected _origHeight: number; + protected _origWidth: number; + protected _uvh: number; + protected _uvw: number; - constructor(width?: number, height?: number, scaleMode?: number, resolution?: number); + updateHorizontalVertices(): void; + updateVerticalVertices(): void; + protected drawSegment(context: CanvasRenderingContext2D | WebGLRenderingContext, textureSource: any, w: number, h: number, x1: number, y1: number, x2: number, y2: number): void; - height: number; - width: number; - realHeight: number; - realWidth: number; - resolution: number; - scaleMode: number; - hasLoaded: boolean; - protected _glRenderTargets: { [n: number]: WebGLTexture; }; - protected _canvasRenderTarget: { [n: number]: WebGLTexture; }; - valid: boolean; + } - resize(width: number, height: number): void; - destroy(): void; + export class Rope extends Mesh { - once(event: "update", fn: (baseRenderTexture: BaseRenderTexture) => void, context?: any): utils.EventEmitter; - once(event: string, fn: Function, context?: any): utils.EventEmitter; - on(event: "update", fn: (baseRenderTexture: BaseRenderTexture) => void, context?: any): utils.EventEmitter; - on(event: string, fn: Function, context?: any): utils.EventEmitter; - off(event: string, fn: Function, context?: any): utils.EventEmitter; + constructor(texture: Texture, points: Point[]); -} -export class BaseTexture extends utils.EventEmitter { - - constructor(source?: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, scaleMode?: number, resolution?: number); - - protected uuid: number; - protected touched: number; - resolution: number; - width: number; - height: number; - realWidth: number; - realHeight: number; - scaleMode: number; - hasLoaded: boolean; - isLoading: boolean; - wrapMode: number; - source: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement; - origSource: HTMLImageElement; - imageType: string; - sourceScale: number; - premultipliedAlpha: boolean; - imageUrl: string; - protected isPowerOfTwo: boolean; - mipmap: boolean; - wrap: boolean; - protected _glTextures: any; - protected _enabled: number; - protected _id: number; - - update(): void; - protected _updateImageType(): void; - protected _loadSvgSource(): void; - protected _loadSvgSourceUsingDataUri(dataUri: string): void; - protected _loadSvgSourceUsingXhr(): void; - protected _loadSvgSourceUsingString(svgString: string): void; - protected loadSource(source: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement): void; - protected _sourceLoaded(): void; - destroy(): void; - dispose(): void; - updateSourceImage(newSrc: string): void; - - static fromImage(imageUrl: string, crossorigin?: boolean, scaleMode?: number, sourceScale?: number): BaseTexture; - static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: number): BaseTexture; - - on(event: "update", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; - on(event: "loaded", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; - on(event: "error", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; - on(event: "dispose", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; - on(event: string, fn: Function, context?: any): utils.EventEmitter; - once(event: "update", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; - once(event: "loaded", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; - once(event: "error", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; - once(event: "dispose", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; - once(event: string, fn: Function, context?: any): utils.EventEmitter; - off(event: string, fn: Function, context?: any): utils.EventEmitter; + points: Point[]; + colors: number[]; + protected _ready: boolean; + refresh(): void; -} -export class RenderTexture extends Texture { + protected _onTextureUpdate(): void; + updateTransform(): void; - constructor(baseRenderTexture: BaseRenderTexture, frame?: Rectangle); + } + } - protected legacyRenderer: any; - valid: boolean; + ////////////////////////////////////////////////////////////////////////////// + /////////////////////////////PARTICLES//////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// - resize(width: number, height: number, doNotResizeBaseTexture?: boolean): void; + export namespace particles { - static create(width?: number, height?: number, scaleMode?: number, resolution?: number): RenderTexture; + export interface IParticleContainerProperties { -} -export class Texture extends utils.EventEmitter { - - constructor(baseTexture: BaseTexture, frame?: Rectangle, orig?: Rectangle, trim?: Rectangle, rotate?: number); - - noFrame: boolean; - baseTexture: BaseTexture; - protected _frame: Rectangle; - trim: Rectangle; - valid: boolean; - requiresUpdate: boolean; - protected _uvs: TextureUvs; - orig: Rectangle; - protected _updateID: number; - transform: any; - - update(): void; - protected onBaseTextureLoaded(baseTexture: BaseTexture): void; - protected onBaseTextureUpdated(baseTexture: BaseTexture): void; - destroy(destroyBase?: boolean): void; - clone(): Texture; - protected _updateUvs(): void; - - static fromImage(imageUrl: string, crossOrigin?: boolean, scaleMode?: number, sourceScale?: number): Texture; - static fromFrame(frameId: string): Texture; - static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: number): Texture; - static fromVideo(video: HTMLVideoElement | string, scaleMode?: number): Texture; - static fromVideoUrl(videoUrl: string, scaleMode?: number): Texture; - static from(source: number | string | BaseTexture | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement): Texture; - static addTextureToCache(texture: Texture, id: string): void; - static removeTextureFromCache(id: string): Texture; - - frame: Rectangle; - protected _rotate: boolean; - rotate: number; - width: number; - height: number; - - static EMPTY: Texture; - - on(event: "update", fn: (texture: Texture) => void, context?: any): utils.EventEmitter; - on(event: string, fn: Function, context?: any): utils.EventEmitter; - once(event: "update", fn: (texture: Texture) => void, context?: any): utils.EventEmitter; - once(event: string, fn: Function, context?: any): utils.EventEmitter; - off(event: string, fn: Function, context?: any): utils.EventEmitter; + scale?: boolean; + position?: boolean; + rotation?: boolean; + uvs?: boolean; + alpha?: boolean; -} -export class TextureUvs { + } + export class ParticleContainer extends Container { - x0: number; - y0: number; - x1: number; - y1: number; - x2: number; - y2: number; - x3: number; - y3: number; + constructor(size?: number, properties?: IParticleContainerProperties, batchSize?: number); - uvsUint32: Uint32Array; + protected _properties: boolean[]; + protected _maxSize: number; + protected _batchSize: number; + protected _glBuffers: { [n: number]: WebGLBuffer; }; + protected _bufferToUpdate: number; + interactiveChildren: boolean; + blendMode: number; + roundPixels: boolean; + baseTexture: BaseTexture; - protected set(frame: Rectangle, baseFrame: Rectangle, rotate: number): void; + setProperties(properties: IParticleContainerProperties): void; + protected onChildrenChange: (smallestChildIndex?: number) => void; -} -export class VideoBaseTexture extends BaseTexture { + destroy(options?: IDestroyOptions | boolean): void; - constructor(source: HTMLVideoElement, scaleMode?: number); + } + export class ParticleBuffer { - autoUpdate: boolean; - autoPlay: boolean; - protected _isAutoUpdating: boolean; + constructor(gl: WebGLRenderingContext, properties: any, dynamicPropertyFlags: any[], size: number); - update(): void; - protected _onCanPlay(): void; - protected _onPlayStart(): void; - protected _onPlayStop(): void; - destroy(): void; - protected _isSourcePlaying(): boolean; - protected _isSourceReady(): boolean; + gl: WebGLRenderingContext; + vertSize: number; + vertByteSize: number; + size: number; + dynamicProperties: any[]; + staticProperties: any[]; + staticStride: number; + staticBuffer: any; + staticData: any; + dynamicStride: number; + dynamicBuffer: any; + dynamicData: any; - static fromVideo(video: HTMLVideoElement, scaleMode?: number): VideoBaseTexture; - static fromUrl(videoSrc: string | any | string[] | any[]): VideoBaseTexture; - static fromUrls(videoSrc: string | any | string[] | any[]): VideoBaseTexture; + destroy(): void; - source: HTMLVideoElement; - protected loadSource(source: HTMLVideoElement): void; + } + export interface IParticleRendererProperty { + attribute: number; + size: number; + uploadFunction: (children: PIXI.DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number) => void; + offset: number; + } + export class ParticleRenderer extends ObjectRenderer { + + constructor(renderer: WebGLRenderer); + + shader: glCore.GLShader; + indexBuffer: WebGLBuffer; + properties: IParticleRendererProperty[]; + protected tempMatrix: Matrix; + + start(): void; + generateBuffers(container: ParticleContainer): ParticleBuffer[]; + uploadVertices(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; + uploadPosition(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; + uploadRotation(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; + uploadUvs(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; + uploadAlpha(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; + destroy(): void; + + indices: Uint16Array; + + } + export interface IParticleShader extends glCore.GLShader { } + + } + + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////PREPARE/////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + export namespace prepare { + + interface AddHook { + (item: any, queue: any[]): boolean; + } + interface UploadHook { + (prepare: UploadHookSource, item: any): boolean; + } + export abstract class BasePrepare{ + + constructor(renderer: SystemRenderer); + + limiter: CountLimiter | TimeLimiter; + protected renderer: SystemRenderer; + protected uploadHookHelper: UploadHookSource; + protected queue: any[]; + protected addHooks: AddHook[]; + protected uploadHooks: UploadHook[]; + protected completes: Function[]; + protected ticking: boolean; + protected delayedTick: () => void; + + upload(item: Function | DisplayObject | Container | BaseTexture | Texture | Graphics | Text | any, done?: () => void): void; + protected tick(): void; + protected prepareItems(): void; + register(addHook?: AddHook, uploadHook?: UploadHook): this; + add(item: PIXI.DisplayObject | PIXI.Container | PIXI.BaseTexture | PIXI.Texture | PIXI.Graphics | PIXI.Text | any): this; + destroy(): void; + + } + export class CanvasPrepare extends BasePrepare { + + constructor(renderer: CanvasRenderer); + + protected canvas: HTMLCanvasElement; + protected ctx: CanvasRenderingContext2D; + + } + export class WebGLPrepare extends BasePrepare { + + constructor(renderer: WebGLRenderer); + + } + export class CountLimiter { + + constructor(maxItemsPerFrame: number); + + protected maxItemsPerFrame: number; + protected itemsLeft: number; + + } + export class TimeLimiter { + + constructor(maxMilliseconds: number); + + protected maxMilliseconds: number; + protected frameStart: number; + + } + + } + + ////////////////////////////////////////////////////////////////////////////// + /////////////////////////////pixi-gl-core///////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + // pixi-gl-core https://github.com/pixijs/pixi-gl-core + // sharedArrayBuffer as a type is not available yet. + // need to fully define what an `Attrib` is. + export namespace glCore { + + export interface IContextOptions { + /** + * Boolean that indicates if the canvas contains an alpha buffer. + */ + alpha?: boolean; + /** + * Boolean that indicates that the drawing buffer has a depth buffer of at least 16 bits. + */ + depth?: boolean; + /** + * Boolean that indicates that the drawing buffer has a stencil buffer of at least 8 bits. + */ + stencil?: boolean; + /** + * Boolean that indicates whether or not to perform anti-aliasing. + */ + antialias?: boolean; + /** + * Boolean that indicates that the page compositor will assume the drawing buffer contains colors with pre-multiplied alpha. + */ + premultipliedAlpha?: boolean; + /** + * If the value is true the buffers will not be cleared and will preserve their values until cleared or overwritten by the author. + */ + preserveDrawingBuffer?: boolean; + /** + * Boolean that indicates if a context will be created if the system performance is low. + */ + failIfMajorPerformanceCaveat?: boolean; + } + export function createContext(view: HTMLCanvasElement, options?: IContextOptions): WebGLRenderingContext; + export function setVertexAttribArrays(gl: WebGLRenderingContext, attribs: IAttrib[], state?: WebGLState): WebGLRenderingContext | undefined; + export class GLBuffer { + + constructor(gl: WebGLRenderingContext, type: number, data: ArrayBuffer | ArrayBufferView | any, drawType: number); + + protected _updateID?: number; + gl: WebGLRenderingContext; + buffer: WebGLBuffer; + type: number; + drawType: number; + data: ArrayBuffer | ArrayBufferView | any; + + upload(data: ArrayBuffer | ArrayBufferView | any, offset?: number, dontBind?: boolean): void; + bind(): void; + + static createVertexBuffer(gl: WebGLRenderingContext, data: ArrayBuffer | ArrayBufferView | any, drawType: number): GLBuffer; + static createIndexBuffer(gl: WebGLRenderingContext, data: ArrayBuffer | ArrayBufferView | any, drawType: number): GLBuffer; + static create(gl: WebGLRenderingContext, type: number, data: ArrayBuffer | ArrayBufferView | any, drawType: number): GLBuffer; + + destroy(): void; + + } + export class GLFramebuffer { + + constructor(gl: WebGLRenderingContext, width: number, height: number); + + gl: WebGLRenderingContext; + frameBuffer: WebGLFramebuffer; + stencil: WebGLRenderbuffer; + texture: GLTexture; + width: number; + height: number; + + enableTexture(texture: GLTexture): void; + enableStencil(): void; + clear(r: number, g: number, b: number, a: number): void; + bind(): void; + unbind(): void; + resize(width: number, height: number): void; + destroy(): void; + + static createRGBA(gl: WebGLRenderingContext, width: number, height: number, data: ArrayBuffer | ArrayBufferView | any): GLFramebuffer; + static createFloat32(gl: WebGLRenderingContext, width: number, height: number, data: ArrayBuffer | ArrayBufferView | any): GLFramebuffer; + + } + export class GLShader { + + constructor(gl: WebGLRenderingContext, vertexSrc: string | string[], fragmentSrc: string | string[], precision: string, attributeLocations: { [key: string]: number }); + + gl: WebGLRenderingContext; + program?: WebGLProgram | null; + uniformData: any; + uniforms: any; + attributes: any; + + bind(): void; + destroy(): void; + + } + export class GLTexture { + + constructor(gl: WebGLRenderingContext, width?: number, height?: number, format?: number, type?: number); + + gl: WebGLRenderingContext; + texture: WebGLTexture; + mipmap: boolean; + premultiplyAlpha: boolean; + width: number; + height: number; + format: number; + type: number; + + upload(source: HTMLImageElement | ImageData | HTMLVideoElement | HTMLCanvasElement): void; + uploadData(data: number, width: number, height: number): void; + bind(location?: number): void; + unbind(): void; + minFilter(linear: boolean): void; + magFilter(linear: boolean): void; + enableMipmap(): void; + enableLinearScaling(): void; + enableNearestScaling(): void; + enableWrapClamp(): void; + enableWrapRepeat(): void; + enableWrapMirrorRepeat(): void; + destroy(): void; + + static fromSource(gl: WebGLRenderingContext, source: HTMLImageElement | ImageData | HTMLVideoElement | HTMLCanvasElement, premultipleAlpha?: boolean): GLTexture; + static fromData(gl: WebGLRenderingContext, data: number[], width: number, height: number): GLTexture; + + } + export interface IAttrib { + + attribute: { + location: boolean; + size: number; + }; + normalized: boolean; + stride: number; + start: number; + buffer: ArrayBuffer; + + } + export interface IWebGLRenderingContextAttribute { + + buffer: WebGLBuffer; + attribute: any; + type: number; + normalized: boolean; + stride: number; + start: number; + + } + export interface IAttribState { + tempAttribState: IAttrib[]; + attribState: IAttrib[]; + } + + export class VertexArrayObject { + + static FORCE_NATIVE: boolean; + + constructor(gl: WebGLRenderingContext, state: WebGLState); + + protected nativeVaoExtension: any; + protected nativeState: IAttribState; + protected nativeVao: VertexArrayObject; + gl: WebGLRenderingContext; + attributes: IAttrib[]; + indexBuffer: GLBuffer; + dirty: boolean; + + bind(): VertexArrayObject; + unbind(): VertexArrayObject; + activate(): VertexArrayObject; + addAttribute(buffer: GLBuffer, attribute: IAttrib, type: number, normalized: boolean, stride: number, start: number): VertexArrayObject; + addIndex(buffer: GLBuffer, options?: any): VertexArrayObject; + clear(): VertexArrayObject; + draw(type: number, size: number, start: number): VertexArrayObject; + destroy(): void; + + } + + } + + ////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////UTILS////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + export interface IDecomposedDataUri { + mediaType: string; + subType: string; + encoding: string; + data: any; + } + + export namespace utils { + + export function uid(): number; + export function hex2rgb(hex: number, out?: number[]): number[]; + export function hex2string(hex: number): string; + export function rgb2hex(rgb: Number[]): number; + export function canUseNewCanvasBlendModes(): boolean; + export function getResolutionOfUrl(url: string, defaultValue?: number): number; + export function getSvgSize(svgString: string): any; + export function decomposeDataUri(dataUri: string): IDecomposedDataUri | void; + export function getUrlFileExtension(url: string): string | void; + export function sayHello(type: string): void; + export function skipHello(): void; + export function isWebGLSupported(): boolean; + export function sign(n: number): number; + export function removeItems(arr: T[], startIdx: number, removeCount: number): void; + export const TextureCache: any; + export const BaseTextureCache: any; + + // https://github.com/kaimallea/isMobile + export namespace isMobile { + export const apple: { + phone: boolean; + ipod: boolean; + tablet: boolean; + device: boolean; + }; + export const android: { + phone: boolean; + tablet: boolean; + device: boolean; + }; + export const amazon: { + phone: boolean; + tablet: boolean; + device: boolean; + }; + export const windows: { + phone: boolean; + tablet: boolean; + device: boolean; + }; + export const seven_inch: boolean; + export const other: { + blackberry10: boolean; + blackberry: boolean; + opera: boolean; + firefox: boolean; + chrome: boolean; + device: boolean; + }; + export const any: boolean; + export const phone: boolean; + export const tablet: boolean; + } + + // https://github.com/primus/eventemitter3 + export class EventEmitter { + + listeners(event: string, exists?: boolean): Function[]; + emit(event: string, ...args: any[]): boolean; + on(event: string, fn: Function, context?: any): this; + once(event: string, fn: Function, context?: any): this; + removeListener(event: string, fn: Function, context?: any, once?: boolean): this; + removeAllListeners(event?: string): this; + eventNames(): string[]; + + off(event: string, fn: Function, context?: any, once?: boolean): this; + addListener(event: string, fn: Function, context?: any): this; + + } + + } + + ////////////////////////////////////////////////////////////////////////////// + /////////////////////////////depreciation///////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + // not sure how to handle blendmodes scalemodes basetexturecache + namespace core { + + /** + * @class + * @private + * @name SpriteBatch + * @memberof PIXI + * @see PIXI.ParticleContainer + * @throws {ReferenceError} SpriteBatch does not exist any more, please use the new ParticleContainer instead. + * @deprecated since version 3.0.0 + */ + type SpriteBatch = ParticleContainer; + + /** + * @class + * @private + * @name AssetLoader + * @memberof PIXI + * @see PIXI.loaders.Loader + * @throws {ReferenceError} The loader system was overhauled in pixi v3, please see the new PIXI.loaders.Loader class. + * @deprecated since version 3.0.0 + */ + type AssetLoader = loaders.Loader; + + /** + * @class + * @private + * @name Stage + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + type Stage = Container; + + /** + * @class + * @private + * @name DisplayObjectContainer + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + type DisplayObjectContainer = Container; + + /** + * @class + * @private + * @name Strip + * @memberof PIXI + * @see PIXI.mesh.Mesh + * @deprecated since version 3.0.0 + */ + type Strip = mesh.Mesh; + + /** + * @class + * @private + * @name Rope + * @memberof PIXI + * @see PIXI.mesh.Rope + * @deprecated since version 3.0.0 + */ + type Rope = mesh.Rope; + + /** + * @class + * @private + * @name ParticleContainer + * @memberof PIXI + * @see PIXI.particles.ParticleContainer + * @deprecated since version 4.0.0 + */ + type ParticleContainer = particles.ParticleContainer; + + /** + * @class + * @private + * @name MovieClip + * @memberof PIXI + * @see PIXI.extras.MovieClip + * @deprecated since version 3.0.0 + */ + type MovieClip = extras.AnimatedSprite; + + /** + * @class + * @private + * @name TilingSprite + * @memberof PIXI + * @see PIXI.extras.TilingSprite + * @deprecated since version 3.0.0 + */ + type TilingSprite = extras.TilingSprite; + + /** + * @class + * @private + * @name BitmapText + * @memberof PIXI + * @see PIXI.extras.BitmapText + * @deprecated since version 3.0.0 + */ + type BitmapText = extras.BitmapText; + + /** + * @namespace + * @private + * @name math + * @memberof PIXI + * @see PIXI + * @deprecated since version 3.0.6 + */ + type math = any; + + /** + * @class + * @private + * @name PIXI.AbstractFilter + * @see PIXI.Filter + * @deprecated since version 3.0.6 + */ + type AbstractFilter = Filter; + + /** + * @class + * @private + * @name PIXI.TransformManual + * @see PIXI.TransformBase + * @deprecated since version 4.0.0 + */ + type TransformManual = TransformBase; + + /** + * @static + * @constant + * @name PIXI.TARGET_FPMS + * @see PIXI.settings.TARGET_FPMS + * @deprecated since version 4.2.0 + */ + type TARGET_FPMS = number; + + /** + * @static + * @constant + * @name PIXI.FILTER_RESOLUTION + * @see PIXI.settings.FILTER_RESOLUTION + * @deprecated since version 4.2.0 + */ + type FILTER_RESOLUTION = number; + + /** + * @static + * @constant + * @name PIXI.RESOLUTION + * @see PIXI.settings.RESOLUTION + * @deprecated since version 4.2.0 + */ + type RESOLUTION = number; + + /** + * @static + * @constant + * @name PIXI.MIPMAP_TEXTURES + * @see PIXI.settings.MIPMAP_TEXTURES + * @deprecated since version 4.2.0 + */ + type MIPMAP_TEXTURES = any; + + /** + * @static + * @constant + * @name PIXI.SPRITE_BATCH_SIZE + * @see PIXI.settings.SPRITE_BATCH_SIZE + * @deprecated since version 4.2.0 + */ + type SPRITE_BATCH_SIZE = number; + + /** + * @static + * @constant + * @name PIXI.SPRITE_MAX_TEXTURES + * @see PIXI.settings.SPRITE_MAX_TEXTURES + * @deprecated since version 4.2.0 + */ + type SPRITE_MAX_TEXTURES = number; + + /** + * @static + * @constant + * @name PIXI.RETINA_PREFIX + * @see PIXI.settings.RETINA_PREFIX + * @deprecated since version 4.2.0 + */ + type RETINA_PREFIX = RegExp | string; + + /** + * @static + * @constant + * @name PIXI.DEFAULT_RENDER_OPTIONS + * @see PIXI.settings.RENDER_OPTIONS + * @deprecated since version 4.2.0 + */ + type DEFAULT_RENDER_OPTIONS = number; + + } + + export namespace extras { + + /** + * @class + * @name MovieClip + * @memberof PIXI.extras + * @see PIXI.extras.AnimatedSprite + * @deprecated since version 4.2.0 + */ + type MovieClip = extras.AnimatedSprite; + + } + +} + +declare namespace pixi { + export const gl: typeof PIXI.glCore; +} + +declare module "pixi.js" { + export = PIXI; } - -// ticker - -export namespace ticker { - - export var shared: Ticker; - - export class Ticker { - - protected _tick(time: number): void; - protected _emitter: utils.EventEmitter; - protected _requestId: number; - protected _maxElapsedMS: number; - - protected _requestIfNeeded(): void; - protected _cancelIfNeeded(): void; - protected _startIfPossible(): void; - - autoStart: boolean; - deltaTime: number; - elapsedMS: number; - lastTime: number; - speed: number; - started: boolean; - - FPS: number; - minFPS: number; - - add(fn: (deltaTime: number) => void, context?: any): Ticker; - addOnce(fn: (deltaTime: number) => void, context?: any): Ticker; - remove(fn: (deltaTime: number) => void, context?: any): Ticker; - start(): void; - stop(): void; - update(): void; - - } - -} - -// shader - -export class Shader extends glCore.GLShader { } - -////////////////////////////////////////////////////////////////////////////// -////////////////////////////EXTRACT/////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - -export namespace extract { - - export class CanvasExtract { - - protected renderer: CanvasRenderer; - - constructor(renderer: CanvasRenderer); - - image(target?: DisplayObject | RenderTexture): HTMLImageElement; - base64(target?: DisplayObject | RenderTexture): string; - canvas(target?: DisplayObject | RenderTexture): HTMLCanvasElement; - pixels(renderTexture?: DisplayObject | RenderTexture): number[]; - - destroy(): void; - - } - export class WebGLExtract { - protected renderer: WebGLRenderer; - - constructor(renderer: WebGLRenderer); - - image(target?: DisplayObject | RenderTexture): HTMLImageElement; - base64(target?: DisplayObject | RenderTexture): string; - canvas(target?: DisplayObject | RenderTexture): HTMLCanvasElement; - pixels(renderTexture?: DisplayObject | RenderTexture): number[]; - - destroy(): void; - } - -} - -////////////////////////////////////////////////////////////////////////////// -////////////////////////////EXTRAS//////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - -export namespace extras { - - export interface IBitmapTextStyle { - - font?: string | { - - name?: string; - size?: number; - - }; - align?: string; - tint?: number; - - } - export class BitmapText extends Container { - - constructor(text: string, style?: IBitmapTextStyle); - - textWidth: number; - textHeight: number; - protected _glyphs: Sprite[]; - protected _font: string | { - name?: string; - size?: number; - }; - font: string | { - name?: string; - size?: number; - }; - protected _text: string; - maxWidth: number; - maxLineHeight: number; - dirty: boolean; - tint: number; - align: string; - text: string; - anchor: PIXI.Point | number; - - protected updateText(): void; - updateTransform(): void; - getLocalBounds(): Rectangle; - validate(): void; - - static fonts: any; - - } - export class AnimatedSprite extends Sprite { - - constructor(textures: Texture[] | Array<{ texture: Texture, time?: number }>); - - protected _textures: Texture[]; - protected _durations: number[]; - textures: Texture[] | Array<{ texture: Texture, time?: number }>; - animationSpeed: number; - loop: boolean; - onComplete: () => void; - onFrameChange: (currentFrame: number) => void; - protected _currentTime: number; - playing: boolean; - totalFrames: number; - currentFrame: number; - stop(): void; - play(): void; - gotoAndStop(frameNumber: number): void; - gotoAndPlay(frameNumber: number): void; - protected update(deltaTime: number): void; - destroy(): void; - - static fromFrames(frame: string[]): AnimatedSprite; - static fromImages(images: string[]): AnimatedSprite; - - } - export class TextureTransform { - - constructor(texture: Texture, clampMargin?: number); - - protected _texture: Texture; - protected mapCoord: Matrix; - protected uClampFrame: Float32Array; - protected uClampOffset: Float32Array; - protected _lastTextureID: number; - - clampOffset: number; - clampMargin: number; - - texture: Texture; - - update(forceUpdate?: boolean): void; - - } - export class TilingSprite extends Sprite { - - constructor(texture: Texture, width?: number, height?: number); - - tileTransform: TransformStatic; - protected _width: number; - protected _height: number; - protected _canvasPattern: CanvasPattern; - uvTransform: TextureTransform; - - clampMargin: number; - tileScale: Point | ObservablePoint; - tilePosition: Point | ObservablePoint; - - protected _onTextureUpdate(): void; - protected _renderWebGL(renderer: WebGLRenderer): void; - protected _renderCanvas(renderer: CanvasRenderer): void; - protected _calculateBounds(): void; - getLocalBounds(rect?: Rectangle): Rectangle; - containsPoint(point: Point): boolean; - destroy(): void; - - static from(source: number | string | BaseTexture | HTMLCanvasElement | HTMLVideoElement, width?: number, height?: number): TilingSprite; - static fromFrame(frameId: string, width?: number, height?: number): TilingSprite; - // if you remove the next line, the class will break. https://github.com/pixijs/pixi-typescript/issues/96 - static fromImage(imageId: string, crossorigin?: boolean, scaleMode?: number): Sprite; - static fromImage(imageId: string, width?: number, height?: number, crossorigin?: boolean, scaleMode?: number): TilingSprite; - - width: number; - height: number; - - } - export class TilingSpriteRenderer extends ObjectRenderer { - - constructor(renderer: WebGLRenderer); - - render(ts: TilingSprite): void; - - } - -} - -////////////////////////////////////////////////////////////////////////////// -////////////////////////////FILTERS/////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - -export namespace filters { - - export class FXAAFilter extends Filter { } - export class BlurFilter extends Filter { - - constructor(strength?: number, quality?: number, resolution?: number, kernelSize?: number); - - blurXFilter: BlurXFilter; - blurYFilter: BlurYFilter; - resolution: number; - padding: number; - passes: number; - blur: number; - blurX: number; - blurY: number; - quality: number; - - } - export class BlurXFilter extends Filter { - - constructor(strength?: number, quality?: number, resolution?: number, kernelSize?: number); - - protected _quality: number; - - quality: number; - passes: number; - resolution: number; - strength: number; - firstRun: boolean; - blur: number; - - } - export class BlurYFilter extends Filter { - - constructor(strength?: number, quality?: number, resolution?: number, kernelSize?: number); - - protected _quality: number; - - quality: number; - passes: number; - resolution: number; - strength: number; - firstRun: boolean; - blur: number; - - } - export class ColorMatrixFilter extends Filter { - - constructor(); - - protected _loadMatrix(matrix: number[], multiply?: boolean): void; - protected _multiply(out: number[], a: number[], b: number[]): void; - protected _colorMatrix(matrix: number[]): void; - - matrix: number[]; - - brightness(b: number, multiply?: boolean): void; - greyscale(scale: number, multiply?: boolean): void; - blackAndWhite(multiply?: boolean): void; - hue(rotation: number, multiply?: boolean): void; - contrast(amount: number, multiply?: boolean): void; - saturate(amount: number, multiply?: boolean): void; - desaturate(multiply?: boolean): void; - negative(multiply?: boolean): void; - sepia(multiply?: boolean): void; - technicolor(multiply?: boolean): void; - polaroid(multiply?: boolean): void; - toBGR(multiply?: boolean): void; - kodachrome(multiply?: boolean): void; - browni(multiply?: boolean): void; - vintage(multiply?: boolean): void; - colorTone(desaturation: number, toned: number, lightColor: string, darkColor: string, multiply?: boolean): void; - night(intensity: number, multiply?: boolean): void; - predator(amount: number, multiply?: boolean): void; - lsd(multiply?: boolean): void; - reset(): void; - - } - export class DisplacementFilter extends Filter { - - constructor(sprite: Sprite, scale?: number); - - scale: Point; - map: Texture; - - } - export class VoidFilter extends Filter { - glShaderKey: string; - } - - // pixi-filters.d.ts todo - // https://github.com/pixijs/pixi-filters/ - export class NoiseFilter extends Filter { - - noise: number; - - } - -} - -////////////////////////////////////////////////////////////////////////////// -////////////////////////////INTERACTION/////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - -export namespace interaction { - - export interface InteractionEvent { - - stopped: boolean; - target: DisplayObject; - currentTarget: DisplayObject; - type: string; - data: InteractionData; - stopPropagation(): void; - - } - export class InteractionData { - - global: Point; - - protected _target: DisplayObject; - target: DisplayObject; - targetProxy: DisplayObject; - originalEvent: Event; - - getLocalPosition(displayObject: DisplayObject, point?: Point, globalPos?: Point): Point; - - } - export class InteractionManager extends utils.EventEmitter { - - constructor(renderer: SystemRenderer, options?: { autoPreventDefault?: boolean; interactionFrequency?: number; }); - - renderer: SystemRenderer; - autoPreventDefault: boolean; - interactionFrequency: number; - mouse: InteractionData; - pointer: InteractionData; - eventData: { - stopped: boolean; - target: any; - type: any; - data: InteractionData; - stopPropagination(): void; - }; - interactiveDataPool: InteractionData[]; - protected interactionDOMElement: HTMLElement; - protected moveWhenInside: boolean; - protected eventsAdded: boolean; - mouseOverRenderer: boolean; - supportsTouchEvents: boolean; - supportsPointerEvents: boolean; - normalizeTouchEvents: boolean; - normalizeMouseEvents: boolean; - - protected onMouseUp: (event: MouseEvent) => void; - protected processMouseUp: (displayObject: DisplayObject, hit: boolean) => void; - protected onMouseDown: (event: MouseEvent) => void; - protected processMouseDown: (displayObject: DisplayObject, hit: boolean) => void; - protected onMouseMove: (event: MouseEvent) => void; - protected processMouseMove: (displayObject: DisplayObject, hit: boolean) => void; - protected onMouseOut: (event: MouseEvent) => void; - protected processMouseOverOut: (displayObject: DisplayObject, hit: boolean) => void; - protected onMouseOver: (event: MouseEvent) => void; - - protected onPointerUp: (event: PointerEvent) => void; - protected processPointerUp: (displayObject: DisplayObject, hit: boolean) => void; - protected onPointerDown: (event: PointerEvent) => void; - protected processPointerDown: (displayObject: DisplayObject, hit: boolean) => void; - protected onPointerMove: (event: PointerEvent) => void; - protected processPointerMove: (displayObject: DisplayObject, hit: boolean) => void; - protected onPointerOut: (event: PointerEvent) => void; - protected processPointerOut: (displayObject: DisplayObject, hit: boolean) => void; - protected onPointerOver: (event: PointerEvent) => void; - - protected onTouchStart: (event: TouchEvent) => void; - protected processTouchStart: (DisplayObject: DisplayObject, hit: boolean) => void; - protected onTouchEnd: (event: TouchEvent) => void; - protected processTouchEnd: (displayObject: DisplayObject, hit: boolean) => void; - protected onTouchMove: (event: TouchEvent) => void; - protected processTouchMove: (displayObject: DisplayObject, hit: boolean) => void; - defaultCursorStyle: string; - currentCursorStyle: string; - protected _tempPoint: Point; - resolution: number; - protected setTargetElement(element: HTMLElement, resolution: number): void; - protected addEvents(): void; - protected removeEvents(): void; - update(deltaTime: number): void; - protected dispatchEvent(displayObject: DisplayObject, eventString: string, eventData: any): void; - mapPositionToPoint(point: Point, x: number, y: number): void; - protected processInteractive(point: Point, displayObject: DisplayObject, func: (displayObject: DisplayObject, hit: boolean) => void, hitTest: boolean, interactive: boolean): boolean; - protected _startInteractionProcess(): void; - protected _queueAdd(displayObject: DisplayObject, order: number): void; - protected _finishInteractionProcess(func: Function): void; - protected getTouchData(touchEvent: InteractionData): InteractionData; - protected returnTouchData(touchData: InteractionData): void; - protected normalizeToPointerData(Event: Event): void; - - destroy(): void; - - } - export interface InteractiveTarget { - - interactive: boolean; - interactiveChildren: boolean; - hitArea: IHitArea; - buttonMode: boolean; - defaultCursor: string; - - } - export interface InteractiveTargetProxy extends InteractiveTarget { - } - -} - -////////////////////////////////////////////////////////////////////////////// -///////////////////////////////LOADER///////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// -// extends -// https://github.com/englercj/resource-loader/ -// 1.6.4 - -export namespace loaders { - - export interface ILoaderOptions { - - crossOrigin?: boolean | string; - loadType?: number; - xhrType?: string; - metaData?: any; - - } - export interface IResourceDictionary { - - [index: string]: PIXI.loaders.Resource; - - } - export class Loader extends utils.EventEmitter { - - protected static _pixiMiddleware: Function[]; - static addPixiMiddleware(fn: Function): void; - - constructor(baseUrl?: string, concurrency?: number); - - baseUrl: string; - progress: number; - loading: boolean; - resources: IResourceDictionary; - - add(name: string, url: string, options?: ILoaderOptions, cb?: () => void): Loader; - add(url: string, options?: ILoaderOptions, cb?: () => void): Loader; - // todo I am not sure of object literal notional (or its options) so just allowing any but would love to improve this - add(obj: any, options?: ILoaderOptions, cb?: () => void): Loader; - - on(event: "complete", fn: (loader: loaders.Loader, object: any) => void, context?: any): utils.EventEmitter; - on(event: "error", fn: (error: Error, loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; - on(event: "load", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; - on(event: "progress", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; - on(event: "start", fn: (loader: loaders.Loader) => void, context?: any): utils.EventEmitter; - on(event: string, fn: Function, context?: any): utils.EventEmitter; - - once(event: "complete", fn: (loader: loaders.Loader, object: any) => void, context?: any): utils.EventEmitter; - once(event: "error", fn: (error: Error, loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; - once(event: "load", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; - once(event: "progress", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; - once(event: "start", fn: (loader: loaders.Loader) => void, context?: any): utils.EventEmitter; - once(event: string, fn: Function, context?: any): utils.EventEmitter; - - before(fn: Function): Loader; - pre(fn: Function): Loader; - - after(fn: Function): Loader; - use(fn: Function): Loader; - - reset(): void; - - load(cb?: (loader: loaders.Loader, object: any) => void): Loader; - - } - export interface ITextureDictionary { - [index: string]: PIXI.Texture; - } - - export class Resource extends utils.EventEmitter { - - static LOAD_TYPE: { - XHR: number; - IMAGE: number; - AUDIO: number; - VIDEO: number; - }; - - static XHR_READ_STATE: { - UNSENT: number; - OPENED: number; - HEADERS_RECIEVED: number; - LOADING: number; - DONE: number; - }; - - static XHR_RESPONSE_TYPE: { - DEFAULT: number; - BUFFER: number; - BLOB: number; - DOCUMENT: number; - JSON: number; - TEXT: number; - }; - - constructor(name?: string, url?: string | string[], options?: ILoaderOptions); - - protected _loadSourceElement(type: string): void; - isLoading: boolean; - isComplete: boolean; - - isJson: boolean; - isXml: boolean; - isImage: boolean; - isAudio: boolean; - isVideo: boolean; - - name: string; - texture: Texture; - textures: ITextureDictionary; - url: string; - data: any; - crossOrigin: boolean | string; - loadType: number; - xhrType: string; - error: Error; - xhr: XMLHttpRequest; - SVGMetadataElement: any; - - metadata: any; - spineAtlas: any; - spineData: any; - - complete(): void; - load(cb?: () => void): void; - abort(message: string): void; - - } -} - -////////////////////////////////////////////////////////////////////////////// -///////////////////////////////MESH/////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - -export namespace mesh { - - export class Mesh extends Container { - - constructor(texture: Texture, vertices?: Float32Array, uvs?: Float32Array, indices?: Uint16Array, drawMode?: number); - - protected _texture: Texture; - uvs: Float32Array; - vertices: Float32Array; - indices: Uint16Array; - dirty: number; - indexDirty: number; - dirtyVertex: boolean; - protected _geometryVersion: number; - blendMode: number; - pluginName: string; - canvasPadding: number; - drawMode: number; - texture: Texture; - tintRgb: Float32Array; - protected _glDatas: { [n: number]: any; }; - protected _renderWebGL(renderer: WebGLRenderer): void; - protected _renderCanvas(renderer: CanvasRenderer): void; - protected _onTextureUpdate(): void; - protected _calculateBounds(): void; - containsPoint(point: Point): boolean; - tint: number; - - static DRAW_MODES: { - TRIANGLE_MESH: number; - TRIANGLES: number; - }; - - } - - export class CanvasMeshRenderer { - - constructor(renderer: CanvasRenderer); - - renderer: CanvasRenderer; - - render(mesh: Mesh): void; - protected _renderTriangleMesh(mesh: Mesh): void; - protected _renderTriangles(mesh: Mesh): void; - protected _renderDrawTriangle(mesh: Mesh, index0: number, index1: number, index2: number): void; - protected renderMeshFlat(mesh: Mesh): void; - - destroy(): void; - - } - - export class MeshRenderer extends ObjectRenderer { - - constructor(renderer: WebGLRenderer); - - shader: Shader; - render(mesh: Mesh): void; - - } - - export class Plane extends Mesh { - - constructor(texture: Texture, verticesX?: number, verticesY?: number); - protected _ready: boolean; - verticesX: number; - verticesY: number; - drawMode: number; - - refresh(): void; - - protected _onTexureUpdate(): void; - - } - - export class NineSlicePlane extends Plane { - - constructor(texture: Texture, leftWidth?: number, topHeight?: number, rightWidth?: number, bottomHeight?: number); - - width: number; - height: number; - leftWidth: number; - rightWidth: number; - topHeight: number; - bottomHeight: number; - - protected _leftWidth: number; - protected _rightWidth: number; - protected _topHeight: number; - protected _bottomHeight: number; - protected _height: number; - protected _width: number; - protected _origHeight: number; - protected _origWidth: number; - protected _uvh: number; - protected _uvw: number; - - updateHorizontalVertices(): void; - updateVerticalVertices(): void; - protected drawSegment(context: CanvasRenderingContext2D | WebGLRenderingContext, textureSource: any, w: number, h: number, x1: number, y1: number, x2: number, y2: number): void; - - } - - export class Rope extends Mesh { - - constructor(texture: Texture, points: Point[]); - - points: Point[]; - colors: number[]; - protected _ready: boolean; - refresh(): void; - - protected _onTextureUpdate(): void; - updateTransform(): void; - - } -} - -////////////////////////////////////////////////////////////////////////////// -/////////////////////////////PARTICLES//////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - -export namespace particles { - - export interface IParticleContainerProperties { - - scale?: boolean; - position?: boolean; - rotation?: boolean; - uvs?: boolean; - alpha?: boolean; - - } - export class ParticleContainer extends Container { - - constructor(size?: number, properties?: IParticleContainerProperties, batchSize?: number); - - protected _properties: boolean[]; - protected _maxSize: number; - protected _batchSize: number; - protected _glBuffers: { [n: number]: WebGLBuffer; }; - protected _bufferToUpdate: number; - interactiveChildren: boolean; - blendMode: number; - roundPixels: boolean; - baseTexture: BaseTexture; - - setProperties(properties: IParticleContainerProperties): void; - protected onChildrenChange: (smallestChildIndex?: number) => void; - - destroy(options?: IDestroyOptions | boolean): void; - - } - export class ParticleBuffer { - - constructor(gl: WebGLRenderingContext, properties: any, dynamicPropertyFlags: any[], size: number); - - gl: WebGLRenderingContext; - vertSize: number; - vertByteSize: number; - size: number; - dynamicProperties: any[]; - staticProperties: any[]; - staticStride: number; - staticBuffer: any; - staticData: any; - dynamicStride: number; - dynamicBuffer: any; - dynamicData: any; - - destroy(): void; - - } - export interface IParticleRendererProperty { - attribute: number; - size: number; - uploadFunction: (children: PIXI.DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number) => void; - offset: number; - } - export class ParticleRenderer extends ObjectRenderer { - - constructor(renderer: WebGLRenderer); - - shader: glCore.GLShader; - indexBuffer: WebGLBuffer; - properties: IParticleRendererProperty[]; - protected tempMatrix: Matrix; - - start(): void; - generateBuffers(container: ParticleContainer): ParticleBuffer[]; - uploadVertices(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; - uploadPosition(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; - uploadRotation(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; - uploadUvs(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; - uploadAlpha(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; - destroy(): void; - - indices: Uint16Array; - - } - export interface IParticleShader extends glCore.GLShader { } - -} - -////////////////////////////////////////////////////////////////////////////// -////////////////////////////PREPARE/////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - -export namespace prepare { - - type addHook = (item: any, queue: any[]) => boolean; - type uploadHook = (prepare: UploadHookSource, item: any) => boolean; - export abstract class BasePrepare{ - - constructor(renderer: SystemRenderer); - - limiter: CountLimiter | TimeLimiter; - protected renderer: SystemRenderer; - protected uploadHookHelper: UploadHookSource; - protected queue: any[]; - protected addHooks: addHook[]; - protected uploadHooks: Array>; - protected completes: Function[]; - protected ticking: boolean; - protected delayedTick: () => void; - - upload(item: Function | DisplayObject | BaseTexture | TextStyle | any, done?: () => void): void; - protected tick(): void; - protected prepareItems(): void; - register(addHook?: addHook, uploadHook?: uploadHook): this; - add(item: DisplayObject | any): this; - destroy(): void; - - } - export class CanvasPrepare extends BasePrepare { - - constructor(renderer: CanvasRenderer); - - protected canvas: HTMLCanvasElement; - protected ctx: CanvasRenderingContext2D; - - } - export class WebGLPrepare extends BasePrepare { - - constructor(renderer: WebGLRenderer); - - } - export class CountLimiter { - - constructor(maxItemsPerFrame: number); - - protected maxItemsPerFrame: number; - protected itemsLeft: number; - - } - export class TimeLimiter { - - constructor(maxMilliseconds: number); - - protected maxMilliseconds: number; - protected frameStart: number; - - } - -} - -////////////////////////////////////////////////////////////////////////////// -/////////////////////////////pixi-gl-core///////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// -// pixi-gl-core https://github.com/pixijs/pixi-gl-core -// sharedArrayBuffer as a type is not available yet. -// need to fully define what an `Attrib` is. -export namespace glCore { - - export interface IContextOptions { - /** - * Boolean that indicates if the canvas contains an alpha buffer. - */ - alpha?: boolean; - /** - * Boolean that indicates that the drawing buffer has a depth buffer of at least 16 bits. - */ - depth?: boolean; - /** - * Boolean that indicates that the drawing buffer has a stencil buffer of at least 8 bits. - */ - stencil?: boolean; - /** - * Boolean that indicates whether or not to perform anti-aliasing. - */ - antialias?: boolean; - /** - * Boolean that indicates that the page compositor will assume the drawing buffer contains colors with pre-multiplied alpha. - */ - premultipliedAlpha?: boolean; - /** - * If the value is true the buffers will not be cleared and will preserve their values until cleared or overwritten by the author. - */ - preserveDrawingBuffer?: boolean; - /** - * Boolean that indicates if a context will be created if the system performance is low. - */ - failIfMajorPerformanceCaveat?: boolean; - } - export function createContext(view: HTMLCanvasElement, options?: IContextOptions): WebGLRenderingContext; - export function setVertexAttribArrays(gl: WebGLRenderingContext, attribs: IAttrib[], state?: WebGLState): WebGLRenderingContext; - export class GLBuffer { - - static EMPTY_ARRAY_BUFFER: ArrayBuffer; - - constructor(gl: WebGLRenderingContext, type: number, data: ArrayBuffer | ArrayBufferView | any, drawType: number); - - protected _updateID: number; - gl: WebGLRenderingContext; - buffer: WebGLBuffer; - type: number; - drawType: number; - data: ArrayBuffer | ArrayBufferView | any; - - upload(data: ArrayBuffer | ArrayBufferView | any, offset?: number, dontBind?: boolean): void; - bind(): void; - - static createVertexBuffer(gl: WebGLRenderingContext, data: ArrayBuffer | ArrayBufferView | any, drawType: number): GLBuffer; - static createIndexBuffer(gl: WebGLRenderingContext, data: ArrayBuffer | ArrayBufferView | any, drawType: number): GLBuffer; - static create(gl: WebGLRenderingContext, type: number, data: ArrayBuffer | ArrayBufferView | any, drawType: number): GLBuffer; - - destroy(): void; - - } - export class GLFramebuffer { - - constructor(gl: WebGLRenderingContext, width: number, height: number); - - gl: WebGLRenderingContext; - frameBuffer: WebGLFramebuffer; - stencil: WebGLRenderbuffer; - texture: GLTexture; - width: number; - height: number; - - enableTexture(texture: GLTexture): void; - enableStencil(): void; - clear(r: number, g: number, b: number, a: number): void; - bind(): void; - unbind(): void; - resize(width: number, height: number): void; - destroy(): void; - - static createRGBA(gl: WebGLRenderingContext, width: number, height: number, data: ArrayBuffer | ArrayBufferView | any): GLFramebuffer; - static createFloat32(gl: WebGLRenderingContext, width: number, height: number, data: ArrayBuffer | ArrayBufferView | any): GLFramebuffer; - - } - export class GLShader { - - constructor(gl: WebGLRenderingContext, vertexSrc: string | string[], fragmentSrc: string | string[]); - - gl: WebGLRenderingContext; - program: WebGLProgram; - uniforms: any; - attributes: any; - - bind(): void; - destroy(): void; - - } - export class GLTexture { - - constructor(gl: WebGLRenderingContext, width?: number, height?: number, format?: number, type?: number); - - gl: WebGLRenderingContext; - texture: WebGLTexture; - mipmap: boolean; - premultiplyAlpha: boolean; - width: number; - height: number; - format: number; - type: number; - - upload(source: HTMLImageElement | ImageData | HTMLVideoElement | HTMLCanvasElement): void; - uploadData(data: number, width: number, height: number): void; - bind(location?: number): void; - unbind(): void; - minFilter(linear: boolean): void; - magFilter(linear: boolean): void; - enableMipmap(): void; - enableLinearScaling(): void; - enableNearestScaling(): void; - enableWrapClamp(): void; - enableWrapRepeat(): void; - enableWrapMirrorRepeat(): void; - destroy(): void; - - static fromSource(gl: WebGLRenderingContext, source: HTMLImageElement | ImageData | HTMLVideoElement | HTMLCanvasElement, premultipleAlpha?: boolean): GLTexture; - static fromData(gl: WebGLRenderingContext, data: number[], width: number, height: number): GLTexture; - - } - export interface IAttrib { - - attribute: { - location: boolean; - size: number; - }; - normalized: boolean; - stride: number; - start: number; - buffer: ArrayBuffer; - - } - export interface IWebGLRenderingContextAttribute { - - buffer: WebGLBuffer; - attribute: any; - type: number; - normalized: boolean; - stride: number; - start: number; - - } - export interface IAttribState { - tempAttribState: IAttrib[]; - attribState: IAttrib[]; - } - - export class VertexArrayObject { - - static FORCE_NATIVE: boolean; - - constructor(gl: WebGLRenderingContext, state: WebGLState); - - protected nativeVaoExtension: any; - protected nativeState: IAttribState; - protected nativeVao: VertexArrayObject; - gl: WebGLRenderingContext; - attributes: IAttrib[]; - indexBuffer: GLBuffer; - dirty: boolean; - - bind(): VertexArrayObject; - unbind(): VertexArrayObject; - activate(): VertexArrayObject; - addAttribute(buffer: GLBuffer, attribute: IAttrib, type: number, normalized: boolean, stride: number, start: number): VertexArrayObject; - addIndex(buffer: GLBuffer, options?: any): VertexArrayObject; - clear(): VertexArrayObject; - draw(type: number, size: number, start: number): VertexArrayObject; - destroy(): void; - - } - -} - -////////////////////////////////////////////////////////////////////////////// -///////////////////////////////UTILS////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - -export interface IDecomposedDataUri { - mediaType: string; - subType: string; - encoding: string; - data: any; -} - -export namespace utils { - - export function uid(): number; - export function hex2rgb(hex: number, out?: number[]): number[]; - export function hex2string(hex: number): string; - export function rgb2hex(rgb: Number[]): number; - export function canUseNewCanvasBlendModes(): boolean; - export function getResolutionOfUrl(url: string, defaultValue?: number): number; - export function getSvgSize(svgString: string): any; - export function decomposeDataUri(dataUri: string): IDecomposedDataUri; - export function getUrlFileExtension(url: string): string; - export function sayHello(type: string): void; - export function skipHello(): void; - export function isWebGLSupported(): boolean; - export function sign(n: number): number; - export function removeItems(arr: T[], startIdx: number, removeCount: number): void; - export var TextureCache: any; - export var BaseTextureCache: any; - - // https://github.com/kaimallea/isMobile - export namespace isMobile { - export var apple: { - phone: boolean; - ipod: boolean; - tablet: boolean; - device: boolean; - }; - export var android: { - phone: boolean; - tablet: boolean; - device: boolean; - }; - export var amazon: { - phone: boolean; - table: boolean; - device: boolean; - }; - export var windows: { - phone: boolean; - tablet: boolean; - device: boolean; - }; - export var seven_inch: boolean; - export var other: { - blackberry_10: boolean; - blackberry: boolean; - opera: boolean; - firefox: boolean; - chrome: boolean; - device: boolean; - }; - export var any: boolean; - export var phone: boolean; - export var tablet: boolean; - } - - // https://github.com/primus/eventemitter3 - export class EventEmitter { - - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - on(event: string, fn: Function, context?: any): EventEmitter; - once(event: string, fn: Function, context?: any): EventEmitter; - removeListener(event: string, fn: Function, context?: any, once?: boolean): EventEmitter; - removeAllListeners(event: string): EventEmitter; - eventNames(): string[]; - - off(event: string, fn: Function, context?: any, once?: boolean): EventEmitter; - addListener(event: string, fn: Function, context?: any): EventEmitter; - - } - -} - -////////////////////////////////////////////////////////////////////////////// -/////////////////////////////depreciation///////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// -// not sure how to handle blendmodes scalemodes basetexturecache -export namespace core { - - /** - * @class - * @private - * @name SpriteBatch - * @memberof PIXI - * @see PIXI.ParticleContainer - * @throws {ReferenceError} SpriteBatch does not exist any more, please use the new ParticleContainer instead. - * @deprecated since version 3.0.0 - */ - type SpriteBatch = ParticleContainer; - - /** - * @class - * @private - * @name AssetLoader - * @memberof PIXI - * @see PIXI.loaders.Loader - * @throws {ReferenceError} The loader system was overhauled in pixi v3, please see the new PIXI.loaders.Loader class. - * @deprecated since version 3.0.0 - */ - type AssetLoader = loaders.Loader; - - /** - * @class - * @private - * @name Stage - * @memberof PIXI - * @see PIXI.Container - * @deprecated since version 3.0.0 - */ - type Stage = Container; - - /** - * @class - * @private - * @name DisplayObjectContainer - * @memberof PIXI - * @see PIXI.Container - * @deprecated since version 3.0.0 - */ - type DisplayObjectContainer = Container; - - /** - * @class - * @private - * @name Strip - * @memberof PIXI - * @see PIXI.mesh.Mesh - * @deprecated since version 3.0.0 - */ - type Strip = mesh.Mesh; - - /** - * @class - * @private - * @name Rope - * @memberof PIXI - * @see PIXI.mesh.Rope - * @deprecated since version 3.0.0 - */ - type Rope = mesh.Rope; - - /** - * @class - * @private - * @name ParticleContainer - * @memberof PIXI - * @see PIXI.particles.ParticleContainer - * @deprecated since version 4.0.0 - */ - type ParticleContainer = particles.ParticleContainer; - - /** - * @class - * @private - * @name MovieClip - * @memberof PIXI - * @see PIXI.extras.MovieClip - * @deprecated since version 3.0.0 - */ - type MovieClip = extras.AnimatedSprite; - - /** - * @class - * @private - * @name TilingSprite - * @memberof PIXI - * @see PIXI.extras.TilingSprite - * @deprecated since version 3.0.0 - */ - type TilingSprite = extras.TilingSprite; - - /** - * @class - * @private - * @name BitmapText - * @memberof PIXI - * @see PIXI.extras.BitmapText - * @deprecated since version 3.0.0 - */ - type BitmapText = extras.BitmapText; - - /** - * @namespace - * @private - * @name math - * @memberof PIXI - * @see PIXI - * @deprecated since version 3.0.6 - */ - type math = any; - - /** - * @class - * @private - * @name PIXI.AbstractFilter - * @see PIXI.Filter - * @deprecated since version 3.0.6 - */ - type AbstractFilter = Filter; - - /** - * @class - * @private - * @name PIXI.TransformManual - * @see PIXI.TransformBase - * @deprecated since version 4.0.0 - */ - type TransformManual = TransformBase; - - /** - * @static - * @constant - * @name PIXI.TARGET_FPMS - * @see PIXI.settings.TARGET_FPMS - * @deprecated since version 4.2.0 - */ - type TARGET_FPMS = number; - - /** - * @static - * @constant - * @name PIXI.FILTER_RESOLUTION - * @see PIXI.settings.FILTER_RESOLUTION - * @deprecated since version 4.2.0 - */ - type FILTER_RESOLUTION = number; - - /** - * @static - * @constant - * @name PIXI.RESOLUTION - * @see PIXI.settings.RESOLUTION - * @deprecated since version 4.2.0 - */ - type RESOLUTION = number; - - /** - * @static - * @constant - * @name PIXI.MIPMAP_TEXTURES - * @see PIXI.settings.MIPMAP_TEXTURES - * @deprecated since version 4.2.0 - */ - type MIPMAP_TEXTURES = any; - - /** - * @static - * @constant - * @name PIXI.SPRITE_BATCH_SIZE - * @see PIXI.settings.SPRITE_BATCH_SIZE - * @deprecated since version 4.2.0 - */ - type SPRITE_BATCH_SIZE = number; - - /** - * @static - * @constant - * @name PIXI.SPRITE_MAX_TEXTURES - * @see PIXI.settings.SPRITE_MAX_TEXTURES - * @deprecated since version 4.2.0 - */ - type SPRITE_MAX_TEXTURES = number; - - /** - * @static - * @constant - * @name PIXI.RETINA_PREFIX - * @see PIXI.settings.RETINA_PREFIX - * @deprecated since version 4.2.0 - */ - type RETINA_PREFIX = RegExp | string; - - /** - * @static - * @constant - * @name PIXI.DEFAULT_RENDER_OPTIONS - * @see PIXI.settings.RENDER_OPTIONS - * @deprecated since version 4.2.0 - */ - type DEFAULT_RENDER_OPTIONS = number; - -} - -export namespace extras { - - /** - * @class - * @name MovieClip - * @memberof PIXI.extras - * @see PIXI.extras.AnimatedSprite - * @deprecated since version 4.2.0 - */ - type MovieClip = extras.AnimatedSprite; - -} - -declare global { - namespace pixi { - export var gl: typeof glCore; - } -} - -export as namespace PIXI; diff --git a/pixi.js/pixi.js-tests.ts b/pixi.js/pixi.js-tests.ts index 313ad7740e..8cea83df3f 100644 --- a/pixi.js/pixi.js-tests.ts +++ b/pixi.js/pixi.js-tests.ts @@ -1,217 +1,124 @@ -import PIXI = require("pixi.js"); namespace basics { export class Basics { - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; + private app: PIXI.Application; private bunny: PIXI.Sprite; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); + this.app = new PIXI.Application(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.app.view); - // create the root of the scene graph - this.stage = new PIXI.Container(); + this.bunny = PIXI.Sprite.fromImage("required/assets/basics/bunny.png"); + this.bunny.anchor.set(0.5); + this.bunny.x = this.app.renderer.width / 2; + this.bunny.y = this.app.renderer.height / 2; + this.app.stage.addChild(this.bunny); - // create a texture from an image path - var texture: PIXI.Texture = PIXI.Texture.fromImage("../../_assets/basics/bunny.png"); - - // create a new Sprite using the texture - this.bunny = new PIXI.Sprite(texture); - - // center the sprite's anchor point - this.bunny.anchor.x = 0.5; - this.bunny.anchor.y = 0.5; - - // move the sprite to the center of the screen - this.bunny.position.x = 200; - this.bunny.position.y = 150; - - // add it to the stage - this.stage.addChild(this.bunny); - - this.animate(); - - } - - private animate = (): void => { - - requestAnimationFrame(this.animate); - - this.bunny.rotation += 0.1; - - this.renderer.render(this.stage); + this.app.ticker.add((delta: number): void => { + this.bunny.rotation += 0.1 / delta; + }); } } -} - -namespace basics { - export class Click { - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; + private app: PIXI.Application; private sprite: PIXI.Sprite; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); + this.app = new PIXI.Application(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.app.view); - // create the root of the scene graph - this.stage = new PIXI.Container(); - - this.sprite = PIXI.Sprite.fromImage('../../_assets/basics/bunny.png'); - this.sprite.position.set(230, 264); + this.sprite = PIXI.Sprite.fromImage("../../_assets/basics/bunny.png"); + this.sprite.texture.baseTexture.scaleMode = PIXI.SCALE_MODES.NEAREST; + this.sprite.anchor.set(0.5); + this.sprite.x = this.app.renderer.width / 2; + this.sprite.y = this.app.renderer.height / 2; this.sprite.interactive = true; - this.sprite.on('mousedown', this.onDown, this); - this.sprite.on('touchstart', this.onDown, this); - - // add it to the stage - this.stage.addChild(this.sprite); - - // start animatng - this.animate(); + this.sprite.buttonMode = true; + this.sprite.on("pointerdown", (): void => { + this.sprite.scale.x *= 1.25; + this.sprite.scale.y *= 1.25; + }); + this.app.stage.addChild(this.sprite); } - - private onDown = (eventData: PIXI.interaction.InteractionData): void => { - - this.sprite.scale.x += 0.3; - this.sprite.scale.y += 0.3; - - } - - private animate = (): void => { - - requestAnimationFrame(this.animate); - - this.renderer.render(this.stage); - - } - } -} - -namespace basics { - - export class Container { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; + export class ContainerPivot { + private app: PIXI.Application; private container: PIXI.Container; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); + this.app = new PIXI.Application(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.app.view); this.container = new PIXI.Container(); + this.app.stage.addChild(this.container); - this.stage.addChild(this.container); + let texture = PIXI.Texture.fromImage("../../_assets/basics/bunny.png"); + + for (let i = 0; i < 25; i++) { + + let bunny = new PIXI.Sprite(texture); + bunny.anchor.set(0.5); + bunny.x = (i % 5) * 40; + bunny.y = Math.floor(i / 5) * 40; + this.container.addChild(bunny); - for (var j = 0; j < 5; j++) { - for (var i = 0; i < 5; i++) { - var bunny: PIXI.Sprite = PIXI.Sprite.fromImage('../../_assets/basics/bunny.png'); - bunny.x = 40 * i; - bunny.y = 40 * j; - this.container.addChild(bunny); - } } - /* - * All the bunnies are added to the container with the addChild method - * when you do this, all the bunnies become children of the container, and when a container moves, - * so do all its children. - * This gives you a lot of flexibility and makes it easier to position elements on the screen - */ - this.container.x = 100; - this.container.y = 60; + this.container.x = this.app.renderer.width / 2; + this.container.y = this.app.renderer.height / 2; - // start animating - this.animate(); + this.container.pivot.x = this.container.width / 2; + this.container.pivot.y = this.container.height / 2; + + this.app.ticker.add((delta: number): void => { + this.container.rotation -= 0.01 / delta; + }); } - - private animate = (): void => { - - requestAnimationFrame(this.animate); - - this.renderer.render(this.stage); - - } - } -} + export class Container { -namespace basics { - - export class CustomFilter { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private background: PIXI.Sprite; - - private filter: CustomizedFilter; + private app: PIXI.Application; + private container: PIXI.Container; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); + this.app = new PIXI.Application(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.app.view); - // create the root of the scene graph - this.stage = new PIXI.Container(); + this.container = new PIXI.Container(); + this.app.stage.addChild(this.container); - this.background = PIXI.Sprite.fromImage('../../_assets/bkg-grass.jpg'); - this.background.scale.set(1.3, 1); - this.stage.addChild(this.background); + let texture = PIXI.Texture.fromImage("../../_assets/basics/bunny.png"); + for (let i = 0; i < 25; i++) { - PIXI.loader.add('shader', '../../_assets/basics/shader.frag'); - PIXI.loader.once('complete', this.onLoaded, this); - PIXI.loader.load(); + let bunny = new PIXI.Sprite(texture); + bunny.anchor.set(0.5); + bunny.x = (i % 5) * 40; + bunny.y = Math.floor(i / 5) * 40; + this.container.addChild(bunny); + + } + + this.container.x = this.app.renderer.width / 2; + this.container.y = this.app.renderer.height / 2; } - - private onLoaded(loader: PIXI.loaders.Loader, res: any) { - - var fragmentSrc = res.shader.data; - - this.filter = new CustomizedFilter(fragmentSrc); - this.background.filters = [this.filter]; - - this.animate(); - - - } - - private animate = (): void => { - - this.filter.uniforms['customUniform'].value += 0.04; - - this.renderer.render(this.stage); - requestAnimationFrame(this.animate); - - } - } export class CustomizedFilter extends PIXI.Filter { @@ -219,469 +126,361 @@ namespace basics { constructor(fragmentSource: string) { super(null, fragmentSource, { customUniform: { - type: '1f', + type: "1f", value: 0 } }); } } + export class CustomFilter { -} + private app: PIXI.Application; + private background: PIXI.Sprite; + private filter: CustomizedFilter; -namespace basics { + constructor() { + + this.app = new PIXI.Application(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.app.view); + + this.background = PIXI.Sprite.fromImage("required/assets/bkg-grass.jpg"); + this.background.width = this.app.renderer.width; + this.background.height = this.app.renderer.height; + this.app.stage.addChild(this.background); + + this.app.stop(); + + PIXI.loader.add("shader", "_assets/basics/shader.frag") + + .load((loader: PIXI.loaders.Loader, resource: any): void => { + + this.filter = new PIXI.Filter(null, resource.shader.data); + this.background.filters = [this.filter]; + this.app.start(); + + this.app.ticker.add((delta: number) => { + this.filter.uniforms.customUniform += 0.04 / delta; + }); + + }); + + } + } export class Graphics { - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - + private app: PIXI.Application; private graphics: PIXI.Graphics; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); + this.app = new PIXI.Application(800, 600, { antialias: true }); + document.body.appendChild(this.app.view); - // create the root of the scene graph - this.stage = new PIXI.Container(); - this.stage.interactive = true; + let graphics = new PIXI.Graphics(); - this.graphics = new PIXI.Graphics(); + // set a fill and line style + graphics.beginFill(0xFF3300); + graphics.lineStyle(4, 0xffd900, 1); // draw a shape - this.graphics.moveTo(50, 50); - this.graphics.lineTo(250, 50); - this.graphics.lineTo(100, 100); - this.graphics.lineTo(50, 50); - this.graphics.endFill(); + graphics.moveTo(50, 50); + graphics.lineTo(250, 50); + graphics.lineTo(100, 100); + graphics.lineTo(50, 50); + graphics.endFill(); // set a fill and a line style again and draw a rectangle - this.graphics.lineStyle(2, 0x0000FF, 1); - this.graphics.beginFill(0xFF700B, 1); - this.graphics.drawRect(50, 250, 120, 120); + graphics.lineStyle(2, 0x0000FF, 1); + graphics.beginFill(0xFF700B, 1); + graphics.drawRect(50, 250, 120, 120); // draw a rounded rectangle - this.graphics.lineStyle(2, 0xFF00FF, 1); - this.graphics.beginFill(0xFF00BB, 0.25); - this.graphics.drawRoundedRect(150, 450, 300, 100, 15); - this.graphics.endFill(); + graphics.lineStyle(2, 0xFF00FF, 1); + graphics.beginFill(0xFF00BB, 0.25); + graphics.drawRoundedRect(150, 450, 300, 100, 15); + graphics.endFill(); - // draw a circle, set the lineStyle to zero so the circle doesn't have an outline - this.graphics.lineStyle(0); - this.graphics.beginFill(0xFFFF0B, 0.5); - this.graphics.drawCircle(470, 90, 60); - this.graphics.endFill(); + // draw a circle, set the lineStyle to zero so the circle doesn"t have an outline + graphics.lineStyle(0); + graphics.beginFill(0xFFFF0B, 0.5); + graphics.drawCircle(470, 90, 60); + graphics.endFill(); - this.stage.addChild(this.graphics); - - // start animating - this.animate(); + this.graphics = graphics; + this.app.stage.addChild(this.graphics); } - - private animate = (): void => { - - requestAnimationFrame(this.animate); - - this.renderer.render(this.stage); - - } - } -} - -namespace basics { - export class RenderTexture { - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - + private app: PIXI.Application; private container: PIXI.Container; - private renderTexture: PIXI.RenderTexture; - private sprite: PIXI.Sprite; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); + this.app = new PIXI.Application(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.app.view); this.container = new PIXI.Container(); + this.app.stage.addChild(this.container); - this.stage.addChild(this.container); + let texture = PIXI.Texture.fromImage("required/assets/basics/bunny.png"); - for (var j = 0; j < 5; j++) { - for (var i = 0; i < 5; i++) { - var bunny: PIXI.Sprite = PIXI.Sprite.fromImage('../../_assets/basics/bunny.png'); - bunny.x = 40 * i; - bunny.y = 40 * j; - bunny.rotation = Math.random() * (Math.PI * 2); - this.container.addChild(bunny); - } + for (let i = 0; i < 25; i++) { + let bunny = new PIXI.Sprite(texture); + bunny.x = (i % 5) * 30; + bunny.y = Math.floor(i / 5) * 30; + bunny.rotation = Math.random() * (Math.PI * 2); + this.container.addChild(bunny); } - this.renderTexture = PIXI.RenderTexture.create(300, 200, PIXI.SCALE_MODES.LINEAR, 0.1); + let brt = new PIXI.BaseRenderTexture(300, 300, PIXI.SCALE_MODES.LINEAR, 1); + let rt = new PIXI.RenderTexture(brt); - this.sprite = new PIXI.Sprite(this.renderTexture); + this.sprite = new PIXI.Sprite(rt); this.sprite.x = 450; this.sprite.y = 60; - this.stage.addChild(this.sprite); + this.app.stage.addChild(this.sprite); this.container.x = 100; this.container.y = 60; - // start animating - this.animate(); + this.app.ticker.add((delta: number) => { + this.app.renderer.render(this.container, rt); + }); } + } - private animate = (): void => { + export class SpriteSheet { - this.renderer.render(this.container, this.renderTexture); + private app: PIXI.Application; + private anim: PIXI.extras.AnimatedSprite; - requestAnimationFrame(this.animate); + constructor() { - this.renderer.render(this.stage); + PIXI.loader + .add("required/assets/basics/fighter.json") + .load((loader: PIXI.loaders.Loader, resource: any) => { + + let frames = []; + + for (let i = 0; i < 30; i++) { + + let val = i < 10 ? "0" + i : i; + + frames.push(PIXI.Texture.fromFrame("rollSequence00" + val + ".png")); + + } + + this.anim = new PIXI.extras.AnimatedSprite(frames); + + this.anim.x = this.app.renderer.width / 2; + this.anim.y = this.app.renderer.height / 2; + this.anim.anchor.set(0.5); + this.anim.animationSpeed = 0.5; + this.anim.play(); + + this.app.stage.addChild(this.anim); + + this.app.ticker.add((deltaTime: number) => { + this.anim.rotation += 0.01; + }); + + }); + } + + } + + export class Text { + + private app: PIXI.Application; + private basicText: PIXI.Text; + private richText: PIXI.Text; + + constructor() { + + this.app = new PIXI.Application(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.app.view); + + this.basicText = new PIXI.Text("Basic text in pixi"); + this.basicText.x = 30; + this.basicText.y = 90; + this.app.stage.addChild(this.basicText); + + let style = new PIXI.TextStyle({ + fontFamily: "Arial", + fontSize: 36, + fontStyle: "italic", + fontWeight: "bold", + fill: ["#ffffff", "#fff0b5"], + stroke: "#4a1850", + strokeThickness: 5, + dropShadow: true, + dropShadowColor: "#000000", + dropShadowBlur: 4, + dropShadowAngle: Math.PI / 6, + dropShadowDistance: 6, + wordWrap: true, + wordWrapWidth: 440 + }); + + this.richText = new PIXI.Text("Rich text with a lot of options and across multiple lines", style); + this.richText.x = 30; + this.richText.y = 180; + this.app.stage.addChild(this.richText); } } -} + export class TexturedMesh { -namespace basics { - - export class SpriteSheet { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private movie: PIXI.extras.AnimatedSprite; + private app: PIXI.Application; + private count: number; + private points: PIXI.Point[]; + private strip: PIXI.mesh.Rope; + private graphics: PIXI.Graphics; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); + let ropeLength = 918 / 20; - // create the root of the scene graph - this.stage = new PIXI.Container(); + for (let i = 0; i < 25; i++) { + this.points.push(new PIXI.Point(i * ropeLength, 0)); + } - PIXI.loader.add('../../_assets/basics/fighter.json').load((loader: PIXI.loaders.Loader, object: any): void => { + this.strip = new PIXI.mesh.Rope(PIXI.Texture.fromImage("required/assets/snake.png"), this.points); + this.strip.x = -40; + this.strip.y = 300; + this.app.stage.addChild(this.strip); - // create an array of textures from an image path - var frames: PIXI.Texture[] = []; + this.graphics = new PIXI.Graphics(); + this.graphics.x = this.strip.x; + this.graphics.y = this.strip.y; + this.app.stage.addChild(this.graphics); - for (var i = 0; i < 30; i++) { + // start animating + this.app.ticker.add((deltaTime: number) => { - var val = i < 10 ? '0' + i : i; + this.count += 0.1; - // magically works since the spritesheet was loaded with the pixi loader - frames.push(PIXI.Texture.fromFrame('rollSequence00' + val + '.png')); + // make the snake + for (let i = 0; i < this.points.length; i++) { + this.points[i].y = Math.sin((i * 0.5) + this.count) * 30; + this.points[i].x = i * ropeLength + Math.cos((i * 0.3) + this.count) * 20; } - - - // create a AnimatedSprite (brings back memories from the days of Flash, right ?) - this.movie = new PIXI.extras.AnimatedSprite(frames); - - /* - * A AnimatedSprite inherits all the properties of a PIXI sprite - * so you can change its position, its anchor, mask it, etc - */ - this.movie.position.set(300); - this.movie.anchor.set(0.5); - this.movie.animationSpeed = 0.5; - this.movie.play(); - - this.stage.addChild(this.movie); - - this.animate(); + this.renderPoints(); }); } - private animate = (): void => { - - this.movie.rotation += 0.01; - - // render the stage container - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); - - } - - } - -} - -namespace basics { - - export class Text { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private basicText: PIXI.Text; - - private richText: PIXI.Text; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - this.basicText = new PIXI.Text('Basic Text in Pixi'); - this.basicText.x = 30; - this.basicText.y = 90; - - this.stage.addChild(this.basicText); - - var style: PIXI.TextStyleOptions = { - fontSize: 36, - fontFamily: 'Arial', - fontWeight: 'bold', - fontStyle: 'italic', - fill: '#F7EDCA', - stroke: '#4a1850', - strokeThickness: 5, - dropShadow: true, - dropShadowColor: '#000000', - dropShadowAngle: Math.PI / 6, - dropShadowDistance: 6, - wordWrap: true, - wordWrapWidth: 440 - }; - - this.richText = new PIXI.Text('Rich Text with a lot of options and across multiple lines', style); - this.richText.x = 30; - this.richText.y = 180; - - this.stage.addChild(this.richText); - - // start animating - this.animate(); - - } - - private animate = (): void => { - - requestAnimationFrame(this.animate); - - this.renderer.render(this.stage); - - } - - } - -} - -namespace basics { - - export class TexturedMesh { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private strip: PIXI.mesh.Rope; - - private graphics: PIXI.Graphics; - - private count: number; - - private points: PIXI.Point[]; - - private ropeLength: number; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - this.count = 0; - - this.ropeLength = 918 / 20; - this.ropeLength = 45; - - this.points = []; - - for (var i = 0; i < 25; i++) { - this.points.push(new PIXI.Point(i * this.ropeLength, 0)); - } - - this.strip = new PIXI.mesh.Rope(PIXI.Texture.fromImage('../../_assets/snake.png'), this.points); - this.strip.position.x = -40; - this.strip.position.y = 300; - this.stage.addChild(this.strip); - - this.graphics = new PIXI.Graphics(); - this.graphics.x = this.strip.x; - this.graphics.y = this.strip.y; - this.stage.addChild(this.graphics); - - // start animating - this.animate(); - - } - - private animate = (): void => { - - this.count += 0.1; - - // make the snake - for (var i = 0; i < this.points.length; i++) { - this.points[i].y = Math.sin((i * 0.5) + this.count) * 30; - this.points[i].x = i * this.ropeLength + Math.cos((i * 0.3) + this.count) * 20; - } - - // render the stage - this.renderer.render(this.stage); - - this.renderPoints(); - - requestAnimationFrame(this.animate); - - } - private renderPoints(): void { - this.graphics.clear(); + this.graphics.clear(); this.graphics.lineStyle(2, 0xffc2c2); this.graphics.moveTo(this.points[0].x, this.points[0].y); - for (var i = 1; i < this.points.length; i++) { + for (let i = 1; i < this.points.length; i++) { this.graphics.lineTo(this.points[i].x, this.points[i].y); } - for (var i = 1; i < this.points.length; i++) { + for (let i = 1; i < this.points.length; i++) { this.graphics.beginFill(0xff0022); this.graphics.drawCircle(this.points[i].x, this.points[i].y, 10); this.graphics.endFill(); } + } } -} - -namespace basics { - export class TilingSprite { - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private texture: PIXI.Texture; - + private app: PIXI.Application; private tilingSprite: PIXI.extras.TilingSprite; - private count: number; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); + this.app = new PIXI.Application(); + document.body.appendChild(this.app.view); - // create the root of the scene graph - this.stage = new PIXI.Container(); + let texture = PIXI.Texture.fromImage("required/assets/p2.jpeg"); - // create a texture from an image path - this.texture = PIXI.Texture.fromImage('../../_assets/p2.jpeg'); - - /* create a tiling sprite ... - * requires a texture, a width and a height - * in WebGL the image size should preferably be a power of two - */ - this.tilingSprite = new PIXI.extras.TilingSprite(this.texture, this.renderer.width, this.renderer.height); - this.stage.addChild(this.tilingSprite); + this.tilingSprite = new PIXI.extras.TilingSprite( + texture, + this.app.renderer.width, + this.app.renderer.height + ); + this.app.stage.addChild(this.tilingSprite); this.count = 0; - this.animate(); + this.app.ticker.add((deltaTime: number): void => { - } + this.count += 0.005; - private animate = (): void => { + this.tilingSprite.tileScale.x = 2 + Math.sin(this.count); + this.tilingSprite.tileScale.y = 2 + Math.cos(this.count); + this.tilingSprite.tilePosition.x += 1; + this.tilingSprite.tilePosition.y += 1; - this.count += 0.005; - - this.tilingSprite.tileScale.x = 2 + Math.sin(this.count); - this.tilingSprite.tileScale.y = 2 + Math.cos(this.count); - - this.tilingSprite.tilePosition.x += 1; - this.tilingSprite.tilePosition.y += 1; - - // render the root container - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); + }); } } -} - -namespace basics { - export class Video { - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private texture: PIXI.Texture; - + private app: PIXI.Application; + private button: PIXI.Graphics; private videoSprite: PIXI.Sprite; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); + this.app = new PIXI.Application(800, 600, { transparent: true }); + document.body.appendChild(this.app.view); - // create the root of the scene graph - this.stage = new PIXI.Container(); + this.button = new PIXI.Graphics() + .beginFill(0x0, 0.5) + .drawRoundedRect(0, 0, 100, 100, 10) + .endFill() + .beginFill(0xffffff) + .moveTo(36, 30) + .lineTo(36, 70) + .lineTo(70, 50); - // create a video texture from a path - this.texture = PIXI.Texture.fromVideo('../../_assets/testVideo.mp4'); + // Position the button + this.button.x = (this.app.renderer.width - this.button.width) / 2; + this.button.y = (this.app.renderer.height - this.button.height) / 2; - // create a new sprite using the video texture (yes it's that easy) - this.videoSprite = new PIXI.Sprite(this.texture); - this.videoSprite.width = this.renderer.width; - this.videoSprite.height = this.renderer.height; - this.stage.addChild(this.videoSprite); + // Enable interactivity on the button + this.button.interactive = true; + this.button.buttonMode = true; - this.stage.addChild(this.videoSprite); + // Add to the stage + this.app.stage.addChild(this.button); - this.animate(); + this.button.on("pointertap", (): void => { - } + this.button.destroy(); - private animate = (): void => { + let texture = PIXI.Texture.fromVideo("required/assets/testVideo.mp4"); - // render the stage - this.renderer.render(this.stage); + this.videoSprite = new PIXI.Sprite(texture); + this.videoSprite.width = this.app.renderer.width; + this.videoSprite.height = this.app.renderer.height; + this.app.stage.addChild(this.videoSprite); - requestAnimationFrame(this.animate); + }); } @@ -693,49 +492,48 @@ namespace demos { export class AlphaMask { - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private background: PIXI.Container; - + private app: PIXI.Application; + private bg: PIXI.Container; private cells: PIXI.Sprite; - private mask: PIXI.Sprite; - private target: PIXI.Point; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); + this.app = new PIXI.Application(); + this.app.stage.interactive = true; + document.body.appendChild(this.app.view); - // create the root of the scene graph - this.stage = new PIXI.Container(); - this.stage.interactive = true; + this.bg = PIXI.Sprite.fromImage("required/assets/bkg.jpg"); + this.app.stage.addChild(this.bg); - this.background = PIXI.Sprite.fromImage('../../_assets/bkg.jpg'); - this.stage.addChild(this.background); + this.cells = PIXI.Sprite.fromImage("required/assets/cells.png"); + this.cells.scale.set(1.5); - this.cells = PIXI.Sprite.fromImage('../../_assets/cells.png'); - this.cells.scale.set(1.5, 1.5); - - this.mask = PIXI.Sprite.fromImage('../../_assets/flowerTop.png'); + this.mask = PIXI.Sprite.fromImage("required/assets/flowerTop.png"); this.mask.anchor.set(0.5); - this.mask.position.x = 310; - this.mask.position.y = 190; + this.mask.x = 310; + this.mask.y = 190; this.cells.mask = this.mask; - this.stage.addChild(this.mask); - - this.stage.addChild(this.cells); + this.app.stage.addChild(this.mask, this.cells); this.target = new PIXI.Point(); this.reset(); - this.animate(); + this.app.ticker.add((deltaTime: number): void => { + + this.mask.position.x += (this.target.x - this.mask.x) * 0.1; + this.mask.position.y += (this.target.y - this.mask.y) * 0.1; + + if (Math.abs(this.mask.x - this.target.x) < 1) { + this.reset(); + } + + + }); } @@ -746,492 +544,300 @@ namespace demos { } - private animate = (): void => { + } - this.mask.position.x += (this.target.x - this.mask.x) * 0.1; - this.mask.position.y += (this.target.y - this.mask.y) * 0.1; + export class AnimatedSpriteDemo { - if (Math.abs(this.mask.x - this.target.x) < 1) { - this.reset(); - } + private app: PIXI.Application; - this.renderer.render(this.stage); + constructor() { - requestAnimationFrame(this.animate); + this.app = new PIXI.Application(); + this.app.stop(); + document.body.appendChild(this.app.view); + + PIXI.loader + .add("spritesheet", "required/assets/mc.json") + .load((): void => { + + let explosionTextures: PIXI.Texture[] = []; + let i: number; + + for (i = 0; i < 26; i++) { + let texture = PIXI.Texture.fromFrame("Explosion_Sequence_A " + (i + 1) + ".png"); + explosionTextures.push(texture); + } + + for (i = 0; i < 50; i++) { + + let explosion = new PIXI.extras.AnimatedSprite(explosionTextures); + + explosion.x = Math.random() * this.app.renderer.width; + explosion.y = Math.random() * this.app.renderer.height; + explosion.anchor.set(0.5); + explosion.rotation = Math.random() * Math.PI; + explosion.scale.set(0.75 + Math.random() * 0.5); + explosion.gotoAndPlay(Math.random() * 27); + this.app.stage.addChild(explosion); + } + + this.app.start(); + + }); } } -} - -namespace demos { - export class Batch { - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - + private app: PIXI.Application; private sprites: PIXI.particles.ParticleContainer; - - private maggots: BatchDude[]; - - private tick: number; - + private maggots: Dude[]; private dudeBounds: PIXI.Rectangle; + private tick: number; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); + this.app = new PIXI.Application(); + document.body.appendChild(this.app.view); this.sprites = new PIXI.particles.ParticleContainer(10000, { - scale: true, position: true, rotation: true, uvs: true, alpha: true - }); - this.stage.addChild(this.sprites); + this.app.stage.addChild(this.sprites); - // create an array to store all the sprites this.maggots = []; - var totalSprites = this.renderer instanceof PIXI.WebGLRenderer ? 10000 : 100; + let totalSprites = this.app.renderer instanceof PIXI.WebGLRenderer ? 10000 : 100; - for (var i = 0; i < totalSprites; i++) { + let dudeTexture = PIXI.Texture.fromImage("required/assets/tinyMaggot.png"); - // create a new Sprite - var dude = new BatchDude(PIXI.Texture.fromImage('../../_assets/tinyMaggot.png')); + for (let i = 0; i < totalSprites; i++) { + let dude = new Dude(dudeTexture); dude.tint = Math.random() * 0xE8D4CD; - - // set the anchor point so the texture is centerd on the sprite dude.anchor.set(0.5); - - // different maggots, different sizes dude.scale.set(0.8 + Math.random() * 0.3); - - // scatter them all - dude.x = Math.random() * this.renderer.width; - dude.y = Math.random() * this.renderer.height; - - dude.tint = Math.random() * 0x808080; - - // create a random direction in radians + dude.x = Math.random() * this.app.renderer.width; + dude.y = Math.random() * this.app.renderer.height; dude.direction = Math.random() * Math.PI * 2; - - // this number will be used to modify the direction of the sprite over time dude.turningSpeed = Math.random() - 0.8; - - // create a random speed between 0 - 2, and these maggots are slooww dude.speed = (2 + Math.random() * 2) * 0.2; - dude.offset = Math.random() * 100; - // finally we push the dude into the maggots array so it it can be easily accessed later this.maggots.push(dude); - this.sprites.addChild(dude); } - // create a bounding box box for the little maggots - var dudeBoundsPadding = 100; - this.dudeBounds = new PIXI.Rectangle(-dudeBoundsPadding, + let dudeBoundsPadding = 100; + this.dudeBounds = new PIXI.Rectangle( -dudeBoundsPadding, - this.renderer.width + dudeBoundsPadding * 2, - this.renderer.height + dudeBoundsPadding * 2); + -dudeBoundsPadding, + this.app.renderer.width + dudeBoundsPadding * 2, + this.app.renderer.height + dudeBoundsPadding * 2 + ); this.tick = 0; - // start animating - this.animate(); + this.app.ticker.add((): void => { - } + for (let i = 0; i < this.maggots.length; i++) { - private animate = (): void => { + let dude = this.maggots[i]; + dude.scale.y = 0.95 + Math.sin(this.tick + dude.offset) * 0.05; + dude.direction += dude.turningSpeed * 0.01; + dude.x += Math.sin(dude.direction) * (dude.speed * dude.scale.y); + dude.y += Math.cos(dude.direction) * (dude.speed * dude.scale.y); + dude.rotation = -dude.direction + Math.PI; - // iterate through the sprites and update their position - for (const dude of this.maggots) { - dude.scale.y = 0.95 + Math.sin(this.tick + dude.offset) * 0.05; - dude.direction += dude.turningSpeed * 0.01; - dude.position.x += Math.sin(dude.direction) * (dude.speed * dude.scale.y); - dude.position.y += Math.cos(dude.direction) * (dude.speed * dude.scale.y); - dude.rotation = -dude.direction + Math.PI; + // wrap the maggots + if (dude.x < this.dudeBounds.x) { + dude.x += this.dudeBounds.width; + } + else if (dude.x > this.dudeBounds.x + this.dudeBounds.width) { + dude.x -= this.dudeBounds.width; + } - // wrap the maggots - if (dude.position.x < this.dudeBounds.x) { - dude.position.x += this.dudeBounds.width; - } else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { - dude.position.x -= this.dudeBounds.width; + if (dude.y < this.dudeBounds.y) { + dude.y += this.dudeBounds.height; + } + else if (dude.y > this.dudeBounds.y + this.dudeBounds.height) { + dude.y -= this.dudeBounds.height; + } } - if (dude.position.y < this.dudeBounds.y) { - dude.position.y += this.dudeBounds.height; - } else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { - dude.position.y -= this.dudeBounds.height; - } - } + this.tick += 0.1; - // increment the ticker - this.tick += 0.1; - - // time to render the stage ! - this.renderer.render(this.stage); - - // request another animation frame... - requestAnimationFrame(this.animate); + }); } } + export class Dude extends PIXI.Sprite { - export class BatchDude extends PIXI.Sprite { - - direction: number; - speed: number; - turningSpeed: number; - offset: number; + direction: number = 0; + speed: number = 0; + turningSpeed: number = 0; + offset: number = 0; constructor(texture: PIXI.Texture) { - super(texture); - } } -} - -namespace demos { - export class BlendModes { - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - + private app: PIXI.Application; private background: PIXI.Sprite; - - private dudeArray: BlendModesDude[]; - - private totalDudes: number; - + private dudeArray: Dude[]; private dudeBounds: PIXI.Rectangle; - private tick: number; - constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); + this.app = new PIXI.Application(); + document.body.appendChild(this.app.view); - // create the root of the scene graph - this.stage = new PIXI.Container(); + this.background = PIXI.Sprite.fromImage("required/assets/BGrotate.jpg"); + this.app.stage.addChild(this.background); - // create a new background sprite - this.background = PIXI.Sprite.fromImage('../../_assets/BGrotate.jpg'); - this.stage.addChild(this.background); - - // create an array to store a reference to the dudes this.dudeArray = []; - this.totalDudes = 20; + let totalDudes = 20; + let dudeTexture = PIXI.Texture.fromImage("required/assets/flowerTop.png"); - for (var i = 0; i < this.totalDudes; i++) { - - // create a new Sprite that uses the image name that we just generated as its source - var dude = new BlendModesDude(PIXI.Texture.fromImage('../../_assets/flowerTop.png')); + for (let i = 0; i < totalDudes; i++) { + let dude = new Dude(dudeTexture); dude.anchor.set(0.5); - - // set a random scale for the dude dude.scale.set(0.8 + Math.random() * 0.3); - - // finally let's set the dude to be at a random position... - dude.position.x = Math.floor(Math.random() * this.renderer.width); - dude.position.y = Math.floor(Math.random() * this.renderer.height); - - // The important bit of this example, this is how you change the default blend mode of the sprite + dude.x = Math.floor(Math.random() * this.app.renderer.width); + dude.y = Math.floor(Math.random() * this.app.renderer.height); dude.blendMode = PIXI.BLEND_MODES.ADD; - - // create some extra properties that will control movement dude.direction = Math.random() * Math.PI * 2; - - // this number will be used to modify the direction of the dude over time dude.turningSpeed = Math.random() - 0.8; - - // create a random speed for the dude between 0 - 2 dude.speed = 2 + Math.random() * 2; - // finally we push the dude into the dudeArray so it it can be easily accessed later this.dudeArray.push(dude); - - this.stage.addChild(dude); + this.app.stage.addChild(dude); } - // create a bounding box box for the little maggots - var dudeBoundsPadding = 100; - this.dudeBounds = new PIXI.Rectangle(-dudeBoundsPadding, + let dudeBoundsPadding = 100; + this.dudeBounds = new PIXI.Rectangle( -dudeBoundsPadding, - this.renderer.width + dudeBoundsPadding * 2, - this.renderer.height + dudeBoundsPadding * 2); + -dudeBoundsPadding, + this.app.renderer.width + dudeBoundsPadding * 2, + this.app.renderer.height + dudeBoundsPadding * 2 + ); - this.tick = 0; + this.app.ticker.add((): void => { - // start animating - this.animate(); + for (let i = 0; i < this.dudeArray.length; i++) { - } + let dude = this.dudeArray[i]; + dude.direction += dude.turningSpeed * 0.01; + dude.x += Math.sin(dude.direction) * dude.speed; + dude.y += Math.cos(dude.direction) * dude.speed; + dude.rotation = -dude.direction - Math.PI / 2; - private animate = (): void => { + // wrap the dudes by testing their bounds... + if (dude.x < this.dudeBounds.x) { + dude.x += this.dudeBounds.width; + } + else if (dude.x > this.dudeBounds.x + this.dudeBounds.width) { + dude.x -= this.dudeBounds.width; + } - // iterate through the dudes and update the positions - for (const dude of this.dudeArray) { - dude.direction += dude.turningSpeed * 0.01; - dude.position.x += Math.sin(dude.direction) * dude.speed; - dude.position.y += Math.cos(dude.direction) * dude.speed; - dude.rotation = -dude.direction - Math.PI / 2; - - // wrap the dudes by testing their bounds... - if (dude.position.x < this.dudeBounds.x) { - dude.position.x += this.dudeBounds.width; - } else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { - dude.position.x -= this.dudeBounds.width; + if (dude.y < this.dudeBounds.y) { + dude.y += this.dudeBounds.height; + } + else if (dude.y > this.dudeBounds.y + this.dudeBounds.height) { + dude.y -= this.dudeBounds.height; + } } - if (dude.position.y < this.dudeBounds.y) { - dude.position.y += this.dudeBounds.height; - } else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { - dude.position.y -= this.dudeBounds.height; - } - } - - // increment the ticker - this.tick += 0.1; - - // time to render the stage ! - this.renderer.render(this.stage); - - // request another animation frame... - requestAnimationFrame(this.animate); + }); } } - export class BlendModesDude extends PIXI.Sprite { - - direction: number; - speed: number; - turningSpeed: number; - offset: number; - - constructor(texture: PIXI.Texture) { - - super(texture); - - } - - } - -} - -namespace demos { - export class CacheAsBitmap { - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - + private app: PIXI.Application; private aliens: PIXI.Sprite[]; - - private alienContainer: PIXI.Container; - private count: number; + private alienContainer: PIXI.Container; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); + this.app = new PIXI.Application(); + this.app.stage.interactive = true; + document.body.appendChild(this.app.view); - // create the root of the scene graph - this.stage = new PIXI.Container(); + this.app.stop(); - // load resources - PIXI.loader - .add('spritesheet', '../../_assets/monsters.json') - .load(this.onAssetsLoaded); - - // holder to store aliens this.aliens = []; + let alienFrames = [ + "eggHead.png", + "flowerTop.png", + "helmlok.png", + "skully.png" + ]; this.count = 0; - // create an empty container this.alienContainer = new PIXI.Container(); - this.alienContainer.position.x = 400; - this.alienContainer.position.y = 300; + this.alienContainer.x = 400; + this.alienContainer.y = 300; + this.app.stage.addChild(this.alienContainer); - // make the stage interactive - this.stage.interactive = true; + PIXI.loader + .add("spritesheet", "required/assets/monsters.json") + .load((): void => { - this.stage.addChild(this.alienContainer); + for (let i = 0; i < 100; i++) { - this.stage.on('click', this.onClick); - this.stage.on('tap', this.onClick); + let frameName = alienFrames[i % 4]; - } + let alien = PIXI.Sprite.fromFrame(frameName); + alien.tint = Math.random() * 0xFFFFFF; + alien.x = Math.random() * 800 - 400; + alien.y = Math.random() * 600 - 300; + alien.anchor.x = 0.5; + alien.anchor.y = 0.5; + this.aliens.push(alien); + this.alienContainer.addChild(alien); + } + this.app.start(); - private onClick = (event: PIXI.interaction.InteractionEvent): void => { + this.app.stage.on("pointerTap", (event: PIXI.interaction.InteractionEvent): void => { + this.alienContainer.cacheAsBitmap = !this.alienContainer.cacheAsBitmap; + }); + this.app.ticker.add((): void => { - this.alienContainer.cacheAsBitmap = !this.alienContainer.cacheAsBitmap; + // let"s rotate the aliens a little bit + for (let i = 0; i < 100; i++) { + let alien = this.aliens[i]; + alien.rotation += 0.1; + } - // feel free to play with what's below - // var sprite = new PIXI.Sprite(this.alienContainer.generateTexture()); - // this.stage.addChild(sprite); - // sprite.position.x = Math.random() * 800; - // sprite.position.y = Math.random() * 600; + this.count += 0.01; - } + this.alienContainer.scale.x = Math.sin(this.count); + this.alienContainer.scale.y = Math.sin(this.count); + this.alienContainer.rotation += 0.01; - private onAssetsLoaded = (): void => { + }); - // add a bunch of aliens with textures from image paths - - var alienFrames = ['eggHead.png', 'flowerTop.png', 'helmlok.png', 'skully.png']; - - for (var i = 0; i < 100; i++) { - - var frameName = alienFrames[i % 4]; - - // create an alien using the frame name.. - var alien = PIXI.Sprite.fromFrame(frameName); - alien.tint = Math.random() * 0xFFFFFF; - - /* - * fun fact for the day :) - * another way of doing the above would be - * var texture = PIXI.Texture.fromFrame(frameName); - * var alien = new PIXI.Sprite(texture); - */ - alien.position.x = Math.random() * 800 - 400; - alien.position.y = Math.random() * 600 - 300; - alien.anchor.x = 0.5; - alien.anchor.y = 0.5; - this.aliens.push(alien); - this.alienContainer.addChild(alien); - - } - - // start animating - this.animate(); - - } - - private animate = (): void => { - - // let's rotate the aliens a little bit - for (var i = 0; i < 100; i++) { - var alien = this.aliens[i]; - alien.rotation += 0.1; - } - - this.count += 0.01; - - this.alienContainer.scale.x = Math.sin(this.count); - this.alienContainer.scale.y = Math.sin(this.count); - - this.alienContainer.rotation += 0.01; - - // render the stage - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); - - } - - } - -} - -namespace demos { - - export class DraggableBunny extends PIXI.Sprite { - - // todo I dont know what event.data is at this time - private data: any; - - private dragging: boolean; - - constructor(texture?: PIXI.Texture) { - - super(texture); - - // enable the bunny to be interactive... this will allow it to respond to mouse and touch events - this.interactive = true; - - // this button mode will mean the hand cursor appears when you roll over the bunny with your mouse - this.buttonMode = true; - - // center the bunny's anchor point - this.anchor.set(0.5); - - // make it a bit bigger, so it's easier to grab - this.scale.set(3); - - // setup events - this - // events for drag start - .on('mousedown', this.onDragStart) - .on('touchstart', this.onDragStart) - // events for drag end - .on('mouseup', this.onDragEnd) - .on('mouseupoutside', this.onDragEnd) - .on('touchend', this.onDragEnd) - .on('touchendoutside', this.onDragEnd) - // events for drag move - .on('mousemove', this.onDragMove) - .on('touchmove', this.onDragMove); - - } - - private onDragStart = (event: PIXI.interaction.InteractionEvent): void => { - - // store a reference to the data - // the reason for this is because of multitouch - // we want to track the movement of this particular touch - this.data = event.data; - this.alpha = 0.5; - this.dragging = true; - - } - - private onDragEnd = (event: PIXI.interaction.InteractionEvent): void => { - - // set interactiondata to null - this.data = null; - this.alpha = 1; - this.dragging = false; - - } - - private onDragMove = (event: PIXI.interaction.InteractionEvent): void => { - - if (this.dragging) { - var newPosition = this.data.getLocalPosition(this.parent); - this.position.x = newPosition.x; - this.position.y = newPosition.y; - } + }); } @@ -1239,212 +845,191 @@ namespace demos { export class Dragging { - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private texture: PIXI.Texture; - + private app: PIXI.Application; private data: PIXI.interaction.InteractionData; + private dragging: boolean; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); + this.app = new PIXI.Application(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.app.view); - // create the root of the scene graph - this.stage = new PIXI.Container(); + let texture = PIXI.Texture.fromImage("required/assets/bunny.png"); + texture.baseTexture.scaleMode = PIXI.SCALE_MODES.NEAREST; - // create a texture from an image - this.texture = PIXI.Texture.fromImage('../../_assets/bunny.png'); - - for (var i = 0; i < 10; i++) { - this.createBunny(Math.floor(Math.random() * 800), Math.floor(Math.random() * 600)); + for (let i = 0; i < 10; i++) { + this.createBunny( + texture, + Math.floor(Math.random() * this.app.renderer.width), + Math.floor(Math.random() * this.app.renderer.height) + ); } - // start animating - this.animate(); - } - private createBunny(x: number, y: number): void { + private createBunny(texture: PIXI.Texture, x: number, y: number): void { - // create our little bunny friend.. - var bunny = new DraggableBunny(this.texture); + let bunny = new PIXI.Sprite(texture); + bunny.interactive = true; + bunny.buttonMode = true; + bunny.anchor.set(0.5); + bunny.scale.set(3); + bunny + .on("pointerdown", (event: PIXI.interaction.InteractionEvent): void => { - // move the sprite to its designated position - bunny.position.x = x; - bunny.position.y = y; + this.data = event.data; + bunny.alpha = 0.5; + this.dragging = true; - // add it to the stage - this.stage.addChild(bunny); + }) + .on("pointerup", (event: PIXI.interaction.InteractionEvent): void => { - } + this.data = null; + bunny.alpha = 0.5; + this.dragging = false; - private animate = (): void => { + }) + .on("pointerupoutside", (event: PIXI.interaction.InteractionEvent): void => { - requestAnimationFrame(this.animate); + this.data = null; + bunny.alpha = 0.5; + this.dragging = false; - this.renderer.render(this.stage); + }) + .on("pointermove", (event: PIXI.interaction.InteractionEvent): void => { + + if (this.dragging) { + let newPosition = this.data.getLocalPosition(bunny); + bunny.x = newPosition.x; + bunny.y = newPosition.y; + } + + }); + + bunny.x = x; + bunny.y = y; + + this.app.stage.addChild(bunny); } } -} - -namespace demos { - export class GraphicsDemo { - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private thing: PIXI.Graphics; - + private app: PIXI.Application; private graphics: PIXI.Graphics; - + private thing: PIXI.Graphics; private count: number; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); + this.app = new PIXI.Application(800, 600, { antialias: true }); + this.app.stage.interactive = true; + document.body.appendChild(this.app.view); - // create the root of the scene graph - this.stage = new PIXI.Container(); - this.stage.interactive = true; + let graphics = new PIXI.Graphics(); - this.graphics = new PIXI.Graphics(); + graphics.beginFill(0xFF3300); + graphics.lineStyle(10, 0xffd900, 1); - // set a fill and line style - this.graphics.beginFill(0xFF3300); - this.graphics.lineStyle(10, 0xffd900, 1); + graphics.moveTo(50, 50); + graphics.lineTo(250, 50); + graphics.lineTo(100, 100); + graphics.lineTo(250, 220); + graphics.lineTo(50, 220); + graphics.lineTo(50, 50); + graphics.endFill(); - // draw a shape - this.graphics.moveTo(50, 50); - this.graphics.lineTo(250, 50); - this.graphics.lineTo(100, 100); - this.graphics.lineTo(250, 220); - this.graphics.lineTo(50, 220); - this.graphics.lineTo(50, 50); - this.graphics.endFill(); + graphics.lineStyle(10, 0xFF0000, 0.8); + graphics.beginFill(0xFF700B, 1); - // set a fill and line style again - this.graphics.lineStyle(10, 0xFF0000, 0.8); - this.graphics.beginFill(0xFF700B, 1); + graphics.moveTo(210, 300); + graphics.lineTo(450, 320); + graphics.lineTo(570, 350); + graphics.quadraticCurveTo(600, 0, 480, 100); + graphics.lineTo(330, 120); + graphics.lineTo(410, 200); + graphics.lineTo(210, 300); + graphics.endFill(); - // draw a second shape - this.graphics.moveTo(210, 300); - this.graphics.lineTo(450, 320); - this.graphics.lineTo(570, 350); - this.graphics.quadraticCurveTo(600, 0, 480, 100); - this.graphics.lineTo(330, 120); - this.graphics.lineTo(410, 200); - this.graphics.lineTo(210, 300); - this.graphics.endFill(); + graphics.lineStyle(2, 0x0000FF, 1); + graphics.drawRect(50, 250, 100, 100); - // draw a rectangle - this.graphics.lineStyle(2, 0x0000FF, 1); - this.graphics.drawRect(50, 250, 100, 100); + graphics.lineStyle(0); + graphics.beginFill(0xFFFF0B, 0.5); + graphics.drawCircle(470, 200, 100); + graphics.endFill(); - // draw a circle - this.graphics.lineStyle(0); - this.graphics.beginFill(0xFFFF0B, 0.5); - this.graphics.drawCircle(470, 200, 100); - this.graphics.endFill(); + graphics.lineStyle(20, 0x33FF00); + graphics.moveTo(30, 30); + graphics.lineTo(600, 300); - this.graphics.lineStyle(20, 0x33FF00); - this.graphics.moveTo(30, 30); - this.graphics.lineTo(600, 300); + this.graphics = graphics; - this.stage.addChild(this.graphics); + this.app.stage.addChild(this.graphics); - // let's create a moving shape this.thing = new PIXI.Graphics(); - this.stage.addChild(this.thing); - this.thing.position.x = 620 / 2; - this.thing.position.y = 380 / 2; + this.thing.x = 800 / 2; + this.thing.y = 600 / 2; + this.app.stage.addChild(this.thing); this.count = 0; - // Just click on the stage to draw random lines - this.stage.on('click', this.onClick); - this.stage.on('tap', this.onClick); + this.app.stage.on("pointertap", (): void => { - // start animating - this.animate(); + this.graphics.lineStyle(Math.random() * 30, Math.random() * 0xFFFFFF, 1); + this.graphics.moveTo(Math.random() * 800, Math.random() * 600); + this.graphics.bezierCurveTo( + Math.random() * 800, Math.random() * 600, + Math.random() * 800, Math.random() * 600, + Math.random() * 800, Math.random() * 600 + ); - } + }); - private onClick = (event: PIXI.interaction.InteractionEvent): void => { + this.app.ticker.add((): void => { - this.graphics.lineStyle(Math.random() * 30, Math.random() * 0xFFFFFF, 1); - this.graphics.moveTo(Math.random() * 620, Math.random() * 380); - this.graphics.bezierCurveTo(Math.random() * 620, Math.random() * 380, - Math.random() * 620, Math.random() * 380, - Math.random() * 620, Math.random() * 380); - } + this.count += 0.1; - private animate = (): void => { + this.thing.clear(); + this.thing.lineStyle(10, 0xff0000, 1); + this.thing.beginFill(0xffFF00, 0.5); - this.thing.clear(); + this.thing.moveTo(-120 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); + this.thing.lineTo(120 + Math.cos(this.count) * 20, -100 + Math.sin(this.count) * 20); + this.thing.lineTo(120 + Math.sin(this.count) * 20, 100 + Math.cos(this.count) * 20); + this.thing.lineTo(-120 + Math.cos(this.count) * 20, 100 + Math.sin(this.count) * 20); + this.thing.lineTo(-120 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); - this.count += 0.1; + this.thing.rotation = this.count * 0.1; - this.thing.clear(); - this.thing.lineStyle(10, 0xff0000, 1); - this.thing.beginFill(0xffFF00, 0.5); + }); - this.thing.moveTo(-120 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); - this.thing.lineTo(120 + Math.cos(this.count) * 20, -100 + Math.sin(this.count) * 20); - this.thing.lineTo(120 + Math.sin(this.count) * 20, 100 + Math.cos(this.count) * 20); - this.thing.lineTo(-120 + Math.cos(this.count) * 20, 100 + Math.sin(this.count) * 20); - this.thing.lineTo(-120 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); - - this.thing.rotation = this.count * 0.1; - - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); } } -} - -namespace demos { - export class Interactivity { - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - + private app: PIXI.Application; private background: PIXI.Sprite; - - private buttons: InteractivityButton[]; + private buttons: PIXI.Sprite[]; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); + this.app = new PIXI.Application(); + document.body.appendChild(this.app.view); - // create the root of the scene graph - this.stage = new PIXI.Container(); - - // create a background... - this.background = PIXI.Sprite.fromImage('../../_assets/button_test_BG.jpg'); - this.background.width = this.renderer.width; - this.background.height = this.renderer.height; - - // add background to stage... - this.stage.addChild(this.background); + let background = PIXI.Sprite.fromImage("required/assets/button_test_BG.jpg"); + background.width = this.app.renderer.width; + background.height = this.app.renderer.height; + this.background = background; + this.app.stage.addChild(this.background); this.buttons = []; - var buttonPositions = [ + let buttonPositions = [ 175, 75, 655, 75, 410, 325, @@ -1452,376 +1037,149 @@ namespace demos { 685, 445 ]; - function noop(): void { - console.log('click'); - } + let textureButton = PIXI.Texture.fromImage("../../_assets/button.png"); + let textureButtonDown = PIXI.Texture.fromImage("../../_assets/buttonDown.png"); + let textureButtonOver = PIXI.Texture.fromImage("../../_assets/buttonOver.png"); - // create some textures from an image path - var textureButton = PIXI.Texture.fromImage('../../_assets/button.png'); - var textureButtonDown = PIXI.Texture.fromImage('../../_assets/buttonDown.png'); - var textureButtonOver = PIXI.Texture.fromImage('../../_assets/buttonOver.png'); + for (let i = 0; i < 5; i++) { - for (var i = 0; i < 5; i++) { + let button = new PIXI.Sprite(textureButton); + button.anchor.set(0.5); + button.x = buttonPositions[i * 2]; + button.y = buttonPositions[i * 2 + 1]; + button.interactive = true; + button.buttonMode = true; - var button = new InteractivityButton(textureButton, textureButtonDown, textureButtonOver); + button + .on("pointerdown", (): void => { + // blah + }) + .on("pointerup", (): void => { + // blah + }) + .on("pointerupoutside", (): void => { + // blah + }) + .on("pointerover", (): void => { + // blah + }) + .on("pointerout", (): void => { + // blah + }); - button.position.x = buttonPositions[i * 2]; - button.position.y = buttonPositions[i * 2 + 1]; - - button.tap = noop; - button.click = noop; - - // add it to the stage - this.stage.addChild(button); - - // add button to array + this.app.stage.addChild(button); this.buttons.push(button); - } - // set some silly values... this.buttons[0].scale.set(1.2); - this.buttons[2].rotation = Math.PI / 10; - this.buttons[3].scale.set(0.8); - this.buttons[4].scale.set(0.8, 1.2); this.buttons[4].rotation = Math.PI; - // start animating - this.animate(); - - } - - private animate = (): void => { - - requestAnimationFrame(this.animate); - - this.renderer.render(this.stage); - } } - export class InteractivityButton extends PIXI.Sprite { - - private textureButton: PIXI.Texture; - private textureButtonDown: PIXI.Texture; - private textureButtonOver: PIXI.Texture; - - tap: Function; - click: Function; - - isdown: boolean; - isOver: boolean; - - constructor(textureButton: PIXI.Texture, textureButtonDown: PIXI.Texture, textureButtonOver: PIXI.Texture) { - - super(textureButton); - - // create some textures from an image path - this.textureButton = textureButton; - this.textureButtonDown = textureButtonDown; - this.textureButtonOver = textureButtonOver; - - this.buttonMode = true; - this.anchor.set(0.5); - - // make the button interactive... - this.interactive = true; - - this - // set the mousedown and touchstart callback... - .on('mousedown', this.onButtonDown) - .on('touchstart', this.onButtonDown) - - // set the mouseup and touchend callback... - .on('mouseup', this.onButtonUp) - .on('touchend', this.onButtonUp) - .on('mouseupoutside', this.onButtonUp) - .on('touchendoutside', this.onButtonUp) - - // set the mouseover callback... - .on('mouseover', this.onButtonOver) - - // set the mouseout callback... - .on('mouseout', this.onButtonOut); - - // you can also listen to click and tap events : - // .on('click', this.noop) - - } - - private onButtonDown = (event: PIXI.interaction.InteractionEvent): void => { - - this.isdown = true; - this.texture = this.textureButtonDown; - this.alpha = 1; - - } - - private onButtonUp = (event: PIXI.interaction.InteractionEvent): void => { - - this.isdown = false; - - if (this.isOver) { - this.texture = this.textureButtonOver; - } else { - this.texture = this.textureButton; - } - } - - private onButtonOver = (event: PIXI.interaction.InteractionEvent): void => { - - this.isOver = true; - - if (this.isdown) { - return; - } - - this.texture = this.textureButtonOver; - - } - - private onButtonOut = (event: PIXI.interaction.InteractionEvent): void => { - - this.isOver = false; - - if (this.isdown) { - return; - } - - this.texture = this.textureButton; - } - - } - -} - -namespace demos { - export class Masking { - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - + private app: PIXI.Application; private bg: PIXI.Sprite; - private container: PIXI.Container; - private bgFront: PIXI.Sprite; - private light1: PIXI.Sprite; - private light2: PIXI.Sprite; - private panda: PIXI.Sprite; - private thing: PIXI.Graphics; - private count: number; - private help: PIXI.Text; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb, antialias: true }); - document.body.appendChild(this.renderer.view); + this.app = new PIXI.Application(800, 600, { antialias: true }); + this.app.stage.interactive = true; + document.body.appendChild(this.app.view); - // create the root of the scene graph - this.stage = new PIXI.Container(); - this.stage.interactive = true; - - this.bg = PIXI.Sprite.fromImage('../../_assets/BGrotate.jpg'); - this.bg.anchor.x = 0.5; - this.bg.anchor.y = 0.5; - - this.bg.position.x = this.renderer.width / 2; - this.bg.position.y = this.renderer.height / 2; - - this.stage.addChild(this.bg); + this.bg = PIXI.Sprite.fromImage("required/assets/BGrotate.jpg"); + this.bg.anchor.set(0.5); + this.bg.x = this.app.renderer.width / 2; + this.bg.y = this.app.renderer.height / 2; + this.app.stage.addChild(this.bg); this.container = new PIXI.Container(); - this.container.position.x = this.renderer.width / 2; - this.container.position.y = this.renderer.height / 2; + this.container.x = this.app.renderer.width / 2; + this.container.y = this.app.renderer.height / 2; + this.app.stage.addChild(this.container); - // add a bunch of sprites + this.bgFront = PIXI.Sprite.fromImage("required/assets/SceneRotate.jpg"); + this.bgFront.anchor.set(0.5); - this.bgFront = PIXI.Sprite.fromImage('../../_assets/SceneRotate.jpg'); - this.bgFront.anchor.x = 0.5; - this.bgFront.anchor.y = 0.5; + this.light2 = PIXI.Sprite.fromImage("required/assets/LightRotate2.png"); + this.light2.anchor.set(0.5); - this.container.addChild(this.bgFront); + this.light1 = PIXI.Sprite.fromImage("required/assets/LightRotate1.png"); + this.light1.anchor.set(0.5); - this.light2 = PIXI.Sprite.fromImage('../../_assets/LightRotate2.png'); - this.light2.anchor.x = 0.5; - this.light2.anchor.y = 0.5; - this.container.addChild(this.light2); + this.panda = PIXI.Sprite.fromImage("required/assets/panda.png"); + this.panda.anchor.set(0.5); - this.light1 = PIXI.Sprite.fromImage('../../_assets/LightRotate1.png'); - this.light1.anchor.x = 0.5; - this.light1.anchor.y = 0.5; - this.container.addChild(this.light1); + this.container.addChild(this.bgFront, this.light2, this.light1, this.panda); - this.panda = PIXI.Sprite.fromImage('../../_assets/panda.png'); - this.panda.anchor.x = 0.5; - this.panda.anchor.y = 0.5; + this.app.stage.addChild(this.container); - this.container.addChild(this.panda); - - this.stage.addChild(this.container); - - // let's create a moving shape this.thing = new PIXI.Graphics(); - this.stage.addChild(this.thing); - this.thing.position.x = this.renderer.width / 2; - this.thing.position.y = this.renderer.height / 2; + this.app.stage.addChild(this.thing); + this.thing.x = this.app.renderer.width / 2; + this.thing.y = this.app.renderer.height / 2; this.thing.lineStyle(0); - this.container.mask = this.thing; this.count = 0; - this.stage.on('click', this.onClick); - this.stage.on('tap', this.onClick); + this.app.stage.on("pointertap", (): void => { + if (!this.container.mask) { + this.container.mask = this.thing; + } + else { + this.container.mask = null; + } + }); - this.help = new PIXI.Text('Click to turn masking on / off.', { fontFamily: 'Arial', fontSize: 12, fontWeight: 'bold', fill: 'white' }); - this.help.position.y = this.renderer.height - 26; - this.help.position.x = 10; - this.stage.addChild(this.help); + this.app.ticker.add((): void => { - // start animating - this.animate(); + this.bg.rotation += 0.01; + this.bgFront.rotation -= 0.01; + + this.light1.rotation += 0.02; + this.light2.rotation += 0.01; + + this.panda.scale.x = 1 + Math.sin(this.count) * 0.04; + this.panda.scale.y = 1 + Math.cos(this.count) * 0.04; + + this.count += 0.1; + + this.thing.clear(); + + this.thing.beginFill(0x8bc5ff, 0.4); + this.thing.moveTo(-120 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); + this.thing.lineTo(-320 + Math.cos(this.count) * 20, 100 + Math.sin(this.count) * 20); + this.thing.lineTo(120 + Math.cos(this.count) * 20, -100 + Math.sin(this.count) * 20); + this.thing.lineTo(120 + Math.sin(this.count) * 20, 100 + Math.cos(this.count) * 20); + this.thing.lineTo(-120 + Math.cos(this.count) * 20, 100 + Math.sin(this.count) * 20); + this.thing.lineTo(-120 + Math.sin(this.count) * 20, -300 + Math.cos(this.count) * 20); + this.thing.lineTo(-320 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); + this.thing.rotation = this.count * 0.1; + + }); } - private animate = (): void => { - - this.bg.rotation += 0.01; - this.bgFront.rotation -= 0.01; - - this.light1.rotation += 0.02; - this.light2.rotation += 0.01; - - this.panda.scale.x = 1 + Math.sin(this.count) * 0.04; - this.panda.scale.y = 1 + Math.cos(this.count) * 0.04; - - this.count += 0.1; - - this.thing.clear(); - - this.thing.beginFill(0x8bc5ff, 0.4); - this.thing.moveTo(-120 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); - this.thing.lineTo(-320 + Math.cos(this.count) * 20, 100 + Math.sin(this.count) * 20); - this.thing.lineTo(120 + Math.cos(this.count) * 20, -100 + Math.sin(this.count) * 20); - this.thing.lineTo(120 + Math.sin(this.count) * 20, 100 + Math.cos(this.count) * 20); - this.thing.lineTo(-120 + Math.cos(this.count) * 20, 100 + Math.sin(this.count) * 20); - this.thing.lineTo(-120 + Math.sin(this.count) * 20, -300 + Math.cos(this.count) * 20); - this.thing.lineTo(-320 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); - this.thing.rotation = this.count * 0.1; - - requestAnimationFrame(this.animate); - - this.renderer.render(this.stage); - - } - - private onClick = (event: PIXI.interaction.InteractionEvent): void => { - - if (!this.container.mask) { - this.container.mask = this.thing; - } else { - this.container.mask = null; - } - } } -} - -namespace demos { - - export class AnimatedSpriteDemo { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - PIXI.loader - .add('spritesheet', '../../_assets/mc.json') - .load(this.onAssetsLoaded); - - // start animating - this.animate(); - - } - - private onAssetsLoaded = (loader: PIXI.loaders.Loader): void => { - - // create an array to store the textures - var explosionTextures: PIXI.Texture[] = []; - var i: number; - - for (i = 0; i < 26; i++) { - - var texture = PIXI.Texture.fromFrame('Explosion_Sequence_A ' + (i + 1) + '.png'); - explosionTextures.push(texture); - - } - - for (i = 0; i < 50; i++) { - - // create an explosion AnimatedSprite - var explosion = new PIXI.extras.AnimatedSprite(explosionTextures); - - explosion.position.x = Math.random() * 800; - explosion.position.y = Math.random() * 600; - explosion.anchor.x = 0.5; - explosion.anchor.y = 0.5; - - explosion.rotation = Math.random() * Math.PI; - - explosion.scale.set(0.75 + Math.random() * 0.5); - - explosion.gotoAndPlay(Math.random() * 27); - - this.stage.addChild(explosion); - - } - - // start animating - this.animate(); - } - - private animate = (): void => { - - requestAnimationFrame(this.animate); - - this.renderer.render(this.stage); - - } - - } - -} - -namespace demos { - export class RenderTextureDemo { - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; + private app: PIXI.Application; private renderTexture: PIXI.RenderTexture; private renderTexture2: PIXI.RenderTexture; @@ -1829,539 +1187,421 @@ namespace demos { private outputSprite: PIXI.Sprite; private stuffContainer: PIXI.Container; + private items: PIXI.Sprite[]; private count: number; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); + this.app = new PIXI.Application(); + document.body.appendChild(this.app.view); - // create the root of the scene graph - this.stage = new PIXI.Container(); - - // create two render textures... these dynamic textures will be used to draw the scene into itself - this.renderTexture = PIXI.RenderTexture.create(this.renderer.width, this.renderer.height); - this.renderTexture2 = PIXI.RenderTexture.create(this.renderer.width, this.renderer.height); + this.renderTexture = PIXI.RenderTexture.create( + this.app.renderer.width, + this.app.renderer.height + ); + this.renderTexture2 = PIXI.RenderTexture.create( + this.app.renderer.width, + this.app.renderer.height + ); this.currentTexture = this.renderTexture; - // create a new sprite that uses the render texture we created above this.outputSprite = new PIXI.Sprite(this.currentTexture); - - // align the sprite - this.outputSprite.position.x = 400; - this.outputSprite.position.y = 300; + this.outputSprite.x = 400; + this.outputSprite.y = 300; this.outputSprite.anchor.set(0.5); - - // add to stage - this.stage.addChild(this.outputSprite); + this.app.stage.addChild(this.outputSprite); this.stuffContainer = new PIXI.Container(); + this.stuffContainer.x = 400; + this.stuffContainer.y = 300; + this.app.stage.addChild(this.stuffContainer); - this.stuffContainer.position.x = 400; - this.stuffContainer.position.y = 300; - - this.stage.addChild(this.stuffContainer); - - // create an array of image ids.. - var fruits = [ - '../../_assets/spinObj_01.png', - '../../_assets/spinObj_02.png', - '../../_assets/spinObj_03.png', - '../../_assets/spinObj_04.png', - '../../_assets/spinObj_05.png', - '../../_assets/spinObj_06.png', - '../../_assets/spinObj_07.png', - '../../_assets/spinObj_08.png' + let fruits = [ + "required/assets/spinObj_01.png", + "required/assets/spinObj_02.png", + "required/assets/spinObj_03.png", + "required/assets/spinObj_04.png", + "required/assets/spinObj_05.png", + "required/assets/spinObj_06.png", + "required/assets/spinObj_07.png", + "required/assets/spinObj_08.png" ]; - // create an array of items this.items = []; - // now create some items and randomly position them in the stuff container - for (var i = 0; i < 20; i++) { - - var item = PIXI.Sprite.fromImage(fruits[i % fruits.length]); - item.position.x = Math.random() * 400 - 200; - item.position.y = Math.random() * 400 - 200; - + for (let i = 0; i < 20; i++) { + let item = PIXI.Sprite.fromImage(fruits[i % fruits.length]); + item.x = Math.random() * 400 - 200; + item.y = Math.random() * 400 - 200; item.anchor.set(0.5); - this.stuffContainer.addChild(item); - this.items.push(item); - } - // used for spinning! this.count = 0; - // start animating - this.animate(); + this.app.ticker.add((): void => { - } + for (let i = 0; i < this.items.length; i++) { + let item = this.items[i]; + item.rotation += 0.1; + } - private animate = (): void => { + this.count += 0.01; - for (const item of this.items) { - // rotate each item - item.rotation += 0.1; - } + let temp = this.renderTexture; + this.renderTexture = this.renderTexture2; + this.renderTexture2 = temp; - this.count += 0.01; + this.outputSprite.texture = this.renderTexture; - // swap the buffers ... - var temp = this.renderTexture; - this.renderTexture = this.renderTexture2; - this.renderTexture2 = temp; + this.stuffContainer.rotation -= 0.01; + this.outputSprite.scale.set(1 + Math.sin(this.count) * 0.2); - // set the new texture - this.outputSprite.texture = this.renderTexture; + this.app.renderer.render(this.app.stage, this.renderTexture2, false); - // twist this up! - this.stuffContainer.rotation -= 0.01; - this.outputSprite.scale.set(1 + Math.sin(this.count) * 0.2); - - // render the stage to the texture - // the 'true' clears the texture before the content is rendered - this.renderer.render(this.stage, this.renderTexture2, false); - - // and finally render the stage - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); + }); } } -} - -namespace demos { - export class StripDemo { - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - + private app: PIXI.Application; private count: number; - private points: PIXI.Point[]; - private strip: PIXI.mesh.Rope; - private snakeContainer: PIXI.Container; - private ropeLength: number; - constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); + this.app = new PIXI.Application(); + document.body.appendChild(this.app.view); this.count = 0; - // build a rope! - this.ropeLength = 918 / 20; + let ropeLength = 918 / 20; this.points = []; - for (var i = 0; i < 20; i++) { - this.points.push(new PIXI.Point(i * this.ropeLength, 0)); + for (let i = 0; i < 20; i++) { + this.points.push(new PIXI.Point(i * ropeLength, 0)); } - this.strip = new PIXI.mesh.Rope(PIXI.Texture.fromImage('../../_assets/snake.png'), this.points); + this.strip = new PIXI.mesh.Rope(PIXI.Texture.fromImage("required/assets/snake.png"), this.points); this.strip.x = -459; this.snakeContainer = new PIXI.Container(); this.snakeContainer.position.x = 400; this.snakeContainer.position.y = 300; - this.snakeContainer.scale.set(800 / 1100); - this.stage.addChild(this.snakeContainer); - this.snakeContainer.addChild(this.strip); + this.app.stage.addChild(this.snakeContainer); - // start animating - this.animate(); - - } - - private animate = (): void => { - - this.count += 0.1; - - // make the snake - for (var i = 0; i < this.points.length; i++) { - - this.points[i].y = Math.sin((i * 0.5) + this.count) * 30; - - this.points[i].x = i * this.ropeLength + Math.cos((i * 0.3) + this.count) * 20; - - } - - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); + this.app.ticker.add((): void => { + this.count += 0.1; + for (let i = 0; i < this.points.length; i++) { + this.points[i].y = Math.sin((i * 0.5) + this.count) * 30; + this.points[i].x = i * ropeLength + Math.cos((i * 0.3) + this.count) * 20; + } + }); } } -} - -namespace demos { - export class TextDemo { - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - + private app: PIXI.Application; private bitmapFontText: PIXI.extras.BitmapText; - private background: PIXI.Sprite; - private textSample: PIXI.Text; - private spinningText: PIXI.Text; - private countingText: PIXI.Text; - private count: number; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); + this.app = new PIXI.Application(); + document.body.appendChild(this.app.view); PIXI.loader - .add('desyrel', '../../_assets/desyrel.xml') - .load(this.onAssetsLoaded); + .add("desyrel", "required/assets/desyrel.xml") + .load((): void => { - // start animating - this.animate(); + this.bitmapFontText = new PIXI.extras.BitmapText("bitmap fonts are\n now supported!", { font: "35px Desyrel", align: "right" }); + this.bitmapFontText.x = this.app.renderer.width - this.bitmapFontText.textWidth - 20; + this.bitmapFontText.y = 20; + this.app.stage.addChild(this.bitmapFontText); - } + }); - private onAssetsLoaded = (): void => { + this.background = PIXI.Sprite.fromImage("required/assets/textDemoBG.jpg"); + this.background.width = this.app.renderer.width; + this.background.height = this.app.renderer.height; + this.app.stage.addChild(this.background); - this.bitmapFontText = new PIXI.extras.BitmapText('bitmap fonts are\n now supported!', { font: '35px Desyrel', align: 'right' }); - - this.bitmapFontText.position.x = 600 - this.bitmapFontText.textWidth; - this.bitmapFontText.position.y = 20; - - this.stage.addChild(this.bitmapFontText); - - // add a shiny background... - this.background = PIXI.Sprite.fromImage('../../_assets/textDemoBG.jpg'); - this.stage.addChild(this.background); - - // create some white text using the Snippet webfont - this.textSample = new PIXI.Text('Pixi.js can has\n multiline text!', { fontSize: 35, fontFamily: 'Snippet', fill: 'white', align: 'left' }); + this.textSample = new PIXI.Text("Pixi.js can has\n multiline text!", { + fontFamily: "Snippet", + fontSize: 35, + fill: "white", + align: "left" + }); this.textSample.position.set(20); - // create a text object with a nice stroke - this.spinningText = new PIXI.Text('I\'m fun!', { fontWeight: 'bold', fontSize: 60, fontFamily: 'Arial', fill: '#cc00ff', align: 'center', stroke: '#FFFFFF', strokeThickness: 6 }); - - // setting the anchor point to 0.5 will center align the text... great for spinning! + this.spinningText = new PIXI.Text("I\"m fun!", { + fontWeight: "bold", + fontSize: 60, + fontFamily: "Arial", + fill: "#cc00ff", + align: "center", + stroke: "#FFFFFF", + strokeThickness: 6 + }); this.spinningText.anchor.set(0.5); - this.spinningText.position.x = 310; - this.spinningText.position.y = 200; + this.spinningText.x = this.app.renderer.width / 2; + this.spinningText.y = this.app.renderer.height / 2; - // create a text object that will be updated... - this.countingText = new PIXI.Text('COUNT 4EVAR: 0', { - fontWeight: 'bold', - fontStyle: 'italic', - fontSize: 60, fontFamily: - 'Arvo', fill: '#3e1707', - align: 'center', - stroke: '#a4410e', + this.countingText = new PIXI.Text("COUNT 4Elet: 0", { + fontWeight: "bold", + fontStyle: "italic", + fontSize: 60, + fontFamily: "Arvo", + fill: "#3e1707", + align: "center", + stroke: "#a4410e", strokeThickness: 7 }); - this.countingText.position.x = 310; - this.countingText.position.y = 320; + this.countingText.x = this.app.renderer.width / 2; + this.countingText.y = 500; this.countingText.anchor.x = 0.5; - this.stage.addChild(this.textSample); - this.stage.addChild(this.spinningText); - this.stage.addChild(this.countingText); + this.app.stage.addChild(this.textSample, this.spinningText, this.countingText); this.count = 0; - } + this.app.ticker.add((): void => { - private animate = (): void => { + this.count += 0.05; + this.countingText.text = "COUNT 4Elet: " + Math.floor(this.count); + this.spinningText.rotation += 0.03; - this.renderer.render(this.stage); + }); - this.count += 0.05; - - // update the text with a new string - this.countingText.text = 'COUNT 4EVAR: ' + Math.floor(this.count); - - // let's spin the spinning text - this.spinningText.rotation += 0.03; - - requestAnimationFrame(this.animate); } } -} - -namespace demos { - - export class TextureSwap { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; + export class TextureRotate { + private app: PIXI.Application; private bol: boolean; - private texture: PIXI.Texture; private secondTexture: PIXI.Texture; - private dude: PIXI.Sprite; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); + this.app = new PIXI.Application(); + document.body.appendChild(this.app.view); this.bol = false; - // an image path - this.texture = PIXI.Texture.fromImage('../../_assets/flowerTop.png'); + PIXI.loader.add("flowerTop", "required/assets/flowerTop.png"); + PIXI.loader.load((loader: PIXI.loaders.Loader, resources: any) => { + this.texture = resources.flowerTop.texture; + this.init(); + }); - // create a second texture - this.secondTexture = PIXI.Texture.fromImage('../../_assets/eggHead.png'); + } + + private init(): void { + + let textures = [this.texture]; + let D8 = PIXI.GroupD8; + for (let rotate = 1; rotate < 16; rotate++) { + let h = D8.isSwapWidthHeight(rotate) ? this.texture.frame.width : this.texture.frame.height; + let w = D8.isSwapWidthHeight(rotate) ? this.texture.frame.height : this.texture.frame.width; + + let frame = this.texture.frame; + let crop = new PIXI.Rectangle(this.texture.frame.x, this.texture.frame.y, w, h); + let trim = crop; + let rotatedTexture: PIXI.Texture; + if (rotate % 2 === 0) { + rotatedTexture = new PIXI.Texture(this.texture.baseTexture, frame, crop, trim, rotate); + } else { + rotatedTexture = new PIXI.Texture(this.texture.baseTexture, frame, crop, trim, rotate - 1); + rotatedTexture.rotate++; + } + textures.push(rotatedTexture); + } + + let offsetX = this.app.renderer.width / 16 | 0; + let offsetY = this.app.renderer.height / 8 | 0; + let gridW = this.app.renderer.width / 4 | 0; + let gridH = this.app.renderer.height / 5 | 0; + + for (let i = 0; i < 16; i++) { + + let dude = new PIXI.Sprite(textures[i < 8 ? i * 2 : (i - 8) * 2 + 1]); + dude.scale.x = 0.5; + dude.scale.y = 0.5; + dude.x = offsetX + gridW * (i % 4); + dude.y = offsetY + gridH * (i / 4 | 0); + this.app.stage.addChild(dude); + + let text = new PIXI.Text("rotate = " + dude.texture.rotate, { fontFamily: "Courier New", fontSize: "12px", fill: "white", align: "left" }); + text.x = dude.x; + text.y = dude.y - 20; + this.app.stage.addChild(text); + + } + + } + + } + + export class TextureSwap { + + private app: PIXI.Application; + private bol: boolean; + private texture: PIXI.Texture; + private secondTexture: PIXI.Texture; + private dude: PIXI.Sprite; + + constructor() { + + this.app = new PIXI.Application(); + document.body.appendChild(this.app.view); + + this.bol = false; + + this.texture = PIXI.Texture.fromImage("required/assets/flowerTop.png"); + + this.secondTexture = PIXI.Texture.fromImage("required/assets/eggHead.png"); - // create a new Sprite using the texture this.dude = new PIXI.Sprite(this.texture); - - // center the sprites anchor point this.dude.anchor.set(0.5); - - // move the sprite to the center of the screen - this.dude.position.x = this.renderer.width / 2; - this.dude.position.y = this.renderer.height / 2; - - this.stage.addChild(this.dude); - - // make the sprite interactive + this.dude.x = this.app.renderer.width / 2; + this.dude.y = this.app.renderer.height / 2; this.dude.interactive = true; + this.dude.buttonMode = true; + this.app.stage.addChild(this.dude); - this.dude.on('click', (): void => { + this.dude.on("pointertap", (): void => { this.bol = !this.bol; - if (this.bol) { this.dude.texture = this.secondTexture; - } else { + } + else { this.dude.texture = this.texture; } }); - // start animating - this.animate(); - - } - - private animate = (): void => { - - // just for fun, let's rotate mr rabbit a little - this.dude.rotation += 0.1; - - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); + this.app.ticker.add((): void => { + this.dude.rotation += 0.1; + }); } } -} - -namespace demos { - export class Tinting { - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private totalDudes: number = 10; - private aliens: TintingDude[]; - - private dudeBounds: PIXI.Rectangle; - - private tick: number; + private app: PIXI.Application; + private aliens: Dude[]; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); + this.app = new PIXI.Application(); + document.body.appendChild(this.app.view); - // create the root of the scene graph - this.stage = new PIXI.Container(); - - // holder to store the aliens this.aliens = []; - this.tick = 0; + let totalDudes = 20; - for (var i = 0; i < this.totalDudes; i++) { + let dudeTexture = PIXI.Texture.fromImage("required/assets/eggHead.png"); - // create a new Sprite that uses the image name that we just generated as its source - var dude = new TintingDude(); + for (let i = 0; i < totalDudes; i++) { - // set the anchor point so the texture is centerd on the sprite + let dude = new Dude(dudeTexture); dude.anchor.set(0.5); - - // set a random scale for the dude - no point them all being the same size! dude.scale.set(0.8 + Math.random() * 0.3); - - // finally lets set the dude to be at a random position.. - dude.position.x = Math.random() * this.renderer.width; - dude.position.y = Math.random() * this.renderer.height; - + dude.x = Math.random() * this.app.renderer.width; + dude.y = Math.random() * this.app.renderer.height; dude.tint = Math.random() * 0xFFFFFF; - - // create some extra properties that will control movement : - // create a random direction in radians. This is a number between 0 and PI*2 which is the equivalent of 0 - 360 degrees dude.direction = Math.random() * Math.PI * 2; - - // this number will be used to modify the direction of the dude over time dude.turningSpeed = Math.random() - 0.8; - - // create a random speed for the dude between 0 - 2 dude.speed = 2 + Math.random() * 2; - // finally we push the dude into the aliens array so it it can be easily accessed later this.aliens.push(dude); - - this.stage.addChild(dude); + this.app.stage.addChild(dude); } - // create a bounding box for the little dudes - var dudeBoundsPadding = 100; - this.dudeBounds = new PIXI.Rectangle(-dudeBoundsPadding, + let dudeBoundsPadding = 100; + let dudeBounds = new PIXI.Rectangle(-dudeBoundsPadding, -dudeBoundsPadding, - this.renderer.width + dudeBoundsPadding * 2, - this.renderer.height + dudeBoundsPadding * 2); + this.app.renderer.width + dudeBoundsPadding * 2, + this.app.renderer.height + dudeBoundsPadding * 2); - // start animating - this.animate(); + this.app.ticker.add((): void => { - } + for (let i = 0; i < this.aliens.length; i++) { - private animate = (): void => { + let dude = this.aliens[i]; + dude.direction += dude.turningSpeed * 0.01; + dude.x += Math.sin(dude.direction) * dude.speed; + dude.y += Math.cos(dude.direction) * dude.speed; + dude.rotation = -dude.direction - Math.PI / 2; - // iterate through the dudes and update their position - for (const dude of this.aliens) { - dude.direction += dude.turningSpeed * 0.01; - dude.position.x += Math.sin(dude.direction) * dude.speed; - dude.position.y += Math.cos(dude.direction) * dude.speed; - dude.rotation = -dude.direction - Math.PI / 2; + if (dude.x < dudeBounds.x) { + dude.x += dudeBounds.width; + } + else if (dude.x > dudeBounds.x + dudeBounds.width) { + dude.x -= dudeBounds.width; + } - // wrap the dudes by testing their bounds... - if (dude.position.x < this.dudeBounds.x) { - dude.position.x += this.dudeBounds.width; - } else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { - dude.position.x -= this.dudeBounds.width; + if (dude.y < dudeBounds.y) { + dude.y += dudeBounds.height; + } + else if (dude.y > dudeBounds.y + dudeBounds.height) { + dude.y -= dudeBounds.height; + } } - if (dude.position.y < this.dudeBounds.y) { - dude.position.y += this.dudeBounds.height; - } else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { - dude.position.y -= this.dudeBounds.height; - } - - } - - // increment the ticker - this.tick += 0.1; - - requestAnimationFrame(this.animate); - - this.renderer.render(this.stage); - + }); } } - export class TintingDude extends PIXI.Sprite { - - direction: number; - speed: number; - turningSpeed: number; - - constructor() { - super(PIXI.Texture.fromImage('../../_assets/eggHead.png')); - } - - } - -} - -namespace demos { - export class TransparentBackground { - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - + private app: PIXI.Application; private bunny: PIXI.Sprite; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb, transparent: true }); - document.body.appendChild(this.renderer.view); + this.app = new PIXI.Application(800, 600, { transparent: true }); + document.body.appendChild(this.app.view); - // create the root of the scene graph - this.stage = new PIXI.Container(); + this.bunny = PIXI.Sprite.fromImage("required/assets/bunny.png"); - // create a new Sprite from an image path. - this.bunny = PIXI.Sprite.fromImage('../../_assets/bunny.png'); - - // center the sprite's anchor point this.bunny.anchor.set(0.5); - // move the sprite to the center of the screen - this.bunny.position.x = 200; - this.bunny.position.y = 150; + this.bunny.x = this.app.renderer.width / 2; + this.bunny.y = this.app.renderer.height / 2; - this.stage.addChild(this.bunny); + this.app.stage.addChild(this.bunny); - // start animating - this.animate(); - - } - - private animate = (): void => { - - // just for fun, let's rotate mr rabbit a little - this.bunny.rotation += 0.1; - - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); + this.app.ticker.add((): void => { + this.bunny.rotation += 0.1; + }); } @@ -2371,44 +1611,35 @@ namespace demos { namespace filters { - export class Blur { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; + export class BlurFilter { + private app: PIXI.Application; private bg: PIXI.Sprite; - private littleDudes: PIXI.Sprite; private littleRobot: PIXI.Sprite; - private blurFilter1: PIXI.filters.BlurFilter; private blurFilter2: PIXI.filters.BlurFilter; - private count: number; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600); - document.body.appendChild(this.renderer.view); + this.app = new PIXI.Application(800, 600); + document.body.appendChild(this.app.view); - // create the root of the scene graph - this.stage = new PIXI.Container(); + this.bg = PIXI.Sprite.fromImage("required/assets/depth_blur_BG.jpg"); + this.bg.width = this.app.renderer.width; + this.bg.height = this.app.renderer.height; + this.app.stage.addChild(this.bg); - this.bg = PIXI.Sprite.fromImage('../../_assets/depth_blur_BG.jpg'); - this.bg.width = this.renderer.width; - this.bg.height = this.renderer.height; - this.stage.addChild(this.bg); + this.littleDudes = PIXI.Sprite.fromImage("required/assets/depth_blur_dudes.jpg"); + this.littleDudes.x = (this.app.renderer.width / 2) - 315; + this.littleDudes.y = 200; + this.app.stage.addChild(this.littleDudes); - this.littleDudes = PIXI.Sprite.fromImage('../../_assets/depth_blur_dudes.jpg'); - this.littleDudes.position.x = (this.renderer.width / 2) - 315; - this.littleDudes.position.y = 200; - this.stage.addChild(this.littleDudes); - - this.littleRobot = PIXI.Sprite.fromImage('../../_assets/depth_blur_moby.jpg'); - this.littleRobot.position.x = (this.renderer.width / 2) - 200; - this.littleRobot.position.y = 100; - this.stage.addChild(this.littleRobot); + this.littleRobot = PIXI.Sprite.fromImage("required/assets/depth_blur_moby.jpg"); + this.littleRobot.x = (this.app.renderer.width / 2) - 200; + this.littleRobot.y = 100; + this.app.stage.addChild(this.littleRobot); this.blurFilter1 = new PIXI.filters.BlurFilter(); this.blurFilter2 = new PIXI.filters.BlurFilter(); @@ -2418,77 +1649,54 @@ namespace filters { this.count = 0; - // nimate - this.animate(); + this.app.ticker.add((): void => { - } + this.count += 0.005; - private animate = (): void => { + let blurAmount = Math.cos(this.count); + let blurAmount2 = Math.sin(this.count); - this.count += 0.005; + this.blurFilter1.blur = 20 * (blurAmount); + this.blurFilter2.blur = 20 * (blurAmount2); - var blurAmount = Math.cos(this.count); - var blurAmount2 = Math.sin(this.count); - - this.blurFilter1.blur = 20 * (blurAmount); - this.blurFilter2.blur = 20 * (blurAmount2); - - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); + }); } } -} - -namespace filters { - export class DisplacementMap { - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - + private app: PIXI.Application; private container: PIXI.Container; - - private padding: number; - - private bounds: PIXI.Rectangle; - private maggots: DisplacementMapDude[]; - private displacementSprite: PIXI.Sprite; - private displacementFilter: PIXI.filters.DisplacementFilter; - private ring: PIXI.Sprite; - private bg: PIXI.Sprite; - private count: number; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - this.stage.interactive = true; + this.app = new PIXI.Application(800, 600); + this.app.stage.interactive = true; + document.body.appendChild(this.app.view); this.container = new PIXI.Container(); - this.stage.addChild(this.container); + this.app.stage.addChild(this.container); - this.padding = 100; - - this.bounds = new PIXI.Rectangle(-this.padding, -this.padding, this.renderer.width + this.padding * 2, this.renderer.height + this.padding * 2); + let padding = 100; + let bounds = new PIXI.Rectangle( + -padding, + -padding, + this.app.renderer.width + padding * 2, + this.app.renderer.height + padding * 2 + ); this.maggots = []; - for (var i = 0; i < 20; i++) { + for (let i = 0; i < 20; i++) { - var maggot = new DisplacementMapDude(); + let maggot = new DisplacementMapDude(); maggot.anchor.set(0.5); this.container.addChild(maggot); @@ -2496,8 +1704,8 @@ namespace filters { maggot.speed = 1; maggot.turnSpeed = Math.random() - 0.8; - maggot.position.x = Math.random() * this.bounds.width; - maggot.position.y = Math.random() * this.bounds.height; + maggot.position.x = Math.random() * bounds.width; + maggot.position.y = Math.random() * bounds.height; maggot.scale.set(1 + Math.random() * 0.3); maggot.original = maggot.scale.clone(); @@ -2505,234 +1713,185 @@ namespace filters { } - this.displacementSprite = PIXI.Sprite.fromImage('../../_assets/displace.png'); - this.displacementFilter = new PIXI.filters.DisplacementFilter(this.displacementSprite); + this.displacementSprite = PIXI.Sprite.fromImage("required/assets/displace.png"); + let displacementFilter = new PIXI.filters.DisplacementFilter(this.displacementSprite); + this.app.stage.addChild(this.displacementSprite); - this.stage.addChild(this.displacementSprite); + this.container.filters = [displacementFilter]; - this.container.filters = [this.displacementFilter]; - - this.displacementFilter.scale.x = 110; - this.displacementFilter.scale.y = 110; - - this.ring = PIXI.Sprite.fromImage('../../_assets/ring.png'); + displacementFilter.scale.x = 110; + displacementFilter.scale.y = 110; + this.ring = PIXI.Sprite.fromImage("required/assets/ring.png"); this.ring.anchor.set(0.5); - this.ring.visible = false; + this.app.stage.addChild(this.ring); - this.stage.addChild(this.ring); - - this.bg = PIXI.Sprite.fromImage('../../_assets/bkg-grass.jpg'); - this.bg.width = this.renderer.width; - this.bg.height = this.renderer.height; - + this.bg = PIXI.Sprite.fromImage("required/assets/bkg-grass.jpg"); + this.bg.width = this.app.renderer.width; + this.bg.height = this.app.renderer.height; this.bg.alpha = 0.4; - this.container.addChild(this.bg); - this.stage - .on('mousemove', this.onPointerMove) - .on('touchmove', this.onPointerMove); - this.count = 0; - this.animate(); + this.app.stage + .on("mousemove", this.onPointerMove) + .on("touchmove", this.onPointerMove); + + this.app.ticker.add((): void => { + + this.count += 0.05; + + for (let i = 0; i < this.maggots.length; i++) { + + let maggot = this.maggots[i]; + + maggot.direction += maggot.turnSpeed * 0.01; + maggot.x += Math.sin(maggot.direction) * maggot.speed; + maggot.y += Math.cos(maggot.direction) * maggot.speed; + + maggot.rotation = -maggot.direction - Math.PI / 2; + maggot.scale.x = maggot.original.x + Math.sin(this.count) * 0.2; + + if (maggot.x < bounds.x) { + maggot.x += bounds.width; + } + else if (maggot.x > bounds.x + bounds.width) { + maggot.x -= bounds.width; + } + + if (maggot.y < bounds.y) { + maggot.y += bounds.height; + } + else if (maggot.y > bounds.y + bounds.height) { + maggot.y -= bounds.height; + } + } + + }); } private onPointerMove = (eventData: PIXI.interaction.InteractionEvent): void => { this.ring.visible = true; - this.displacementSprite.x = eventData.data.global.x - 100; this.displacementSprite.y = eventData.data.global.y - this.displacementSprite.height / 2; - - this.ring.position.x = eventData.data.global.x - 25; - this.ring.position.y = eventData.data.global.y; - - } - - private animate = (): void => { - - this.count += 0.05; - - for (const maggot of this.maggots) { - maggot.direction += maggot.turnSpeed * 0.01; - maggot.position.x += Math.sin(maggot.direction) * maggot.speed; - maggot.position.y += Math.cos(maggot.direction) * maggot.speed; - - maggot.rotation = -maggot.direction - Math.PI / 2; - - maggot.scale.x = maggot.original.x + Math.sin(this.count) * 0.2; - - // wrap the maggots around as the crawl - if (maggot.position.x < this.bounds.x) { - maggot.position.x += this.bounds.width; - } else if (maggot.position.x > this.bounds.x + this.bounds.width) { - maggot.position.x -= this.bounds.width; - } - - if (maggot.position.y < this.bounds.y) { - maggot.position.y += this.bounds.height; - } else if (maggot.position.y > this.bounds.y + this.bounds.height) { - maggot.position.y -= this.bounds.height; - } - } - - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); + this.ring.x = eventData.data.global.x - 25; + this.ring.y = eventData.data.global.y; } } - export class DisplacementMapDude extends PIXI.Sprite { - direction: number; - speed: number; - turnSpeed: number; - original: PIXI.Point; + direction: number = 0; + speed: number = 0; + turnSpeed: number = 0; + original: PIXI.Point = new PIXI.Point(); constructor() { - super(PIXI.Texture.fromImage('../../_assets/maggot.png')); + super(PIXI.Texture.fromImage("../../_assets/maggot.png")); } } -} - -namespace filters { - export class Filter { - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private background: PIXI.Sprite; - + private app: PIXI.Application; + private bg: PIXI.Sprite; private filter: PIXI.filters.ColorMatrixFilter; - private container: PIXI.Container; - private bgFront: PIXI.Sprite; private light2: PIXI.Sprite; private light1: PIXI.Sprite; private panda: PIXI.Sprite; - private count: number; - private switchy: boolean; - + private enabled: boolean; private help: PIXI.Text; constructor() { - this.renderer = PIXI.autoDetectRenderer(800, 600); - document.body.appendChild(this.renderer.view); + this.app = new PIXI.Application(); + this.app.stage.interactive = true; + document.body.appendChild(this.app.view); - // create the root of the scene graph - this.stage = new PIXI.Container(); - this.stage.interactive = true; - - // create a texture from an image path - var texture: PIXI.Texture = PIXI.Texture.fromImage("../../_assets/basics/bunny.png"); - - this.background = PIXI.Sprite.fromImage('_assets/BGrotate.jpg'); - this.background.anchor.set(0.5); - - this.background.position.x = this.renderer.width / 2; - this.background.position.y = this.renderer.height / 2; + this.bg = PIXI.Sprite.fromImage("required/assets/BGrotate.jpg"); + this.bg.anchor.set(0.5); + this.bg.x = this.app.renderer.width / 2; + this.bg.y = this.app.renderer.height / 2; this.filter = new PIXI.filters.ColorMatrixFilter(); this.container = new PIXI.Container(); - this.container.position.x = this.renderer.width / 2; - this.container.position.y = this.renderer.height / 2; + this.container.position.x = this.app.renderer.width / 2; + this.container.position.y = this.app.renderer.height / 2; + this.app.stage.addChild(this.container); - this.bgFront = PIXI.Sprite.fromImage('../../_assets/SceneRotate.jpg'); + this.bgFront = PIXI.Sprite.fromImage("required/assets/SceneRotate.jpg"); this.bgFront.anchor.set(0.5); - this.container.addChild(this.bgFront); - this.light2 = PIXI.Sprite.fromImage('../../_assets/LightRotate2.png'); + this.light2 = PIXI.Sprite.fromImage("required/assets/LightRotate2.png"); this.light2.anchor.set(0.5); this.container.addChild(this.light2); - this.light1 = PIXI.Sprite.fromImage('../../_assets/LightRotate1.png'); + this.light1 = PIXI.Sprite.fromImage("../../_assets/LightRotate1.png"); this.light1.anchor.set(0.5); this.container.addChild(this.light1); - this.panda = PIXI.Sprite.fromImage('../../_assets/panda.png'); + this.panda = PIXI.Sprite.fromImage("required/assets/panda.png"); this.panda.anchor.set(0.5); - this.container.addChild(this.panda); - this.stage.addChild(this.container); - - this.stage.filters = [this.filter]; + this.app.stage.filters = [this.filter]; this.count = 0; - this.switchy = false; + this.enabled = true; - this.stage.on('click', this.onClick); - this.stage.on('tap', this.onClick); + this.app.stage.on("pointertap", (): void => { + this.enabled = !this.enabled; + this.app.stage.filters = this.enabled ? [this.filter] : null; + }); + this.help = new PIXI.Text("Click or tap to turn filters on / off.", { + fontFamily: "Arial", + fontSize: 12, + fontWeight: "bold", + fill: "white" + }); + this.help.y = this.app.renderer.height - 25; + this.help.x = 10; + this.app.stage.addChild(this.help); - this.help = new PIXI.Text('Click to turn filters on / off.', { fontWeight: 'bold', fontSize: 12, fontFamily: 'Arial', fill: 'white' }); - this.help.position.y = this.renderer.height - 25; - this.help.position.x = 10; + this.app.ticker.add((delta: number): void => { - this.stage.addChild(this.help); + this.bg.rotation += 0.01; + this.bgFront.rotation -= 0.01; + this.light1.rotation += 0.02; + this.light2.rotation += 0.01; - // animate - this.animate(); + this.panda.scale.x = 1 + Math.sin(this.count) * 0.04; + this.panda.scale.y = 1 + Math.cos(this.count) * 0.04; - } + this.count += 0.1; - private onClick = (): void => { + let matrix = this.filter.matrix; - this.switchy = !this.switchy; + matrix[1] = Math.sin(this.count) * 3; + matrix[2] = Math.cos(this.count); + matrix[3] = Math.cos(this.count) * 1.5; + matrix[4] = Math.sin(this.count / 3) * 2; + matrix[5] = Math.sin(this.count / 2); + matrix[6] = Math.sin(this.count / 4); - if (!this.switchy) { - this.stage.filters = [this.filter]; - } else { - this.stage.filters = null; - } - - } - - private animate = (): void => { - - this.background.rotation += 0.01; - this.bgFront.rotation -= 0.01; - - this.light1.rotation += 0.02; - this.light2.rotation += 0.01; - - this.panda.scale.x = 1 + Math.sin(this.count) * 0.04; - this.panda.scale.y = 1 + Math.cos(this.count) * 0.04; - - this.count += 0.1; - - var matrix = this.filter.matrix; - - matrix[1] = Math.sin(this.count) * 3; - matrix[2] = Math.cos(this.count); - matrix[3] = Math.cos(this.count) * 1.5; - matrix[4] = Math.sin(this.count / 3) * 2; - matrix[5] = Math.sin(this.count / 2); - matrix[6] = Math.sin(this.count / 4); - - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); + }); } } -} +} \ No newline at end of file diff --git a/pixi.js/tslint.json b/pixi.js/tslint.json index 56ba128af1..1c78047f30 100644 --- a/pixi.js/tslint.json +++ b/pixi.js/tslint.json @@ -1,9 +1,98 @@ { - "extends": "../tslint.json", + "jsRules": { + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "indent": [ + true, + "spaces" + ], + "no-duplicate-variable": true, + "no-eval": true, + "no-trailing-whitespace": true, + "no-unsafe-finally": true, + "one-line": [ + true, + "check-open-brace", + "check-whitespace" + ], + "quotemark": [ + true, + "double" + ], + "semicolon": [ + true, + "always" + ], + "triple-equals": [ + true, + "allow-null-check" + ], + "variable-name": [ + true, + "ban-keywords" + ], + "whitespace": [ + true, + "check-branch", + "check-decl", + "check-operator", + "check-separator", + "check-type" + ] + }, "rules": { - "forbidden-types": false, - "interface-name": false, - "no-empty-interface": false, - "unified-signatures": false + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "indent": [ + true, + "spaces" + ], + "no-eval": true, + "no-internal-module": true, + "no-trailing-whitespace": true, + "no-unsafe-finally": true, + "no-var-keyword": true, + "one-line": [ + true, + "check-open-brace", + "check-whitespace" + ], + "quotemark": [ + true, + "double" + ], + "semicolon": [ + true, + "always" + ], + "triple-equals": [ + true, + "allow-null-check" + ], + "typedef-whitespace": [ + true, + { + "call-signature": "nospace", + "index-signature": "nospace", + "parameter": "nospace", + "property-declaration": "nospace", + "variable-declaration": "nospace" + } + ], + "variable-name": false, + "whitespace": [ + true, + "check-branch", + "check-decl", + "check-operator", + "check-separator", + "check-type" + ] } -} +} \ No newline at end of file diff --git a/pixi.js/v3/index.d.ts b/pixi.js/v3/index.d.ts deleted file mode 100644 index aa573b2201..0000000000 --- a/pixi.js/v3/index.d.ts +++ /dev/null @@ -1,1747 +0,0 @@ -// Type definitions for Pixi.js 3.0 -// Project: https://github.com/GoodBoyDigital/pixi.js/ -// Definitions by: clark-stevenson -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = PIXI; -export as namespace PIXI; - -declare class PIXI { - - static VERSION: string; - static PI_2: number; - static RAD_TO_DEG: number; - static DEG_TO_RAD: number; - static TARGET_FPMS: number; - static RENDERER_TYPE: { - UNKNOWN: number; - WEBGL: number; - CANVAS: number; - }; - static BLEND_MODES: { - NORMAL: number; - ADD: number; - MULTIPLY: number; - SCREEN: number; - OVERLAY: number; - DARKEN: number; - LIGHTEN: number; - COLOR_DODGE: number; - COLOR_BURN: number; - HARD_LIGHT: number; - SOFT_LIGHT: number; - DIFFERENCE: number; - EXCLUSION: number; - HUE: number; - SATURATION: number; - COLOR: number; - LUMINOSITY: number; - - }; - static DRAW_MODES: { - POINTS: number; - LINES: number; - LINE_LOOP: number; - LINE_STRIP: number; - TRIANGLES: number; - TRIANGLE_STRIP: number; - TRIANGLE_FAN: number; - }; - static SCALE_MODES: { - DEFAULT: number; - LINEAR: number; - NEAREST: number; - }; - static RETINA_PREFIX: string; - static RESOLUTION: number; - static FILTER_RESOLUTION: number; - static DEFAULT_RENDER_OPTIONS: { - view: HTMLCanvasElement; - resolution: number; - antialias: boolean; - forceFXAA: boolean; - autoResize: boolean; - transparent: boolean; - backgroundColor: number; - clearBeforeRender: boolean; - preserveDrawingBuffer: boolean; - roundPixels: boolean; - }; - static SHAPES: { - POLY: number; - RECT: number; - CIRC: number; - ELIP: number; - RREC: number; - }; - static SPRITE_BATCH_SIZE: number; - -} - -declare namespace PIXI { - - export function autoDetectRenderer(width: number, height: number, options?: PIXI.RendererOptions, noWebGL?: boolean): PIXI.WebGLRenderer | PIXI.CanvasRenderer; - export var loader: PIXI.loaders.Loader; - - // https://github.com/primus/eventemitter3 - export class EventEmitter { - - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - on(event: string, fn: Function, context?: any): EventEmitter; - once(event: string, fn: Function, context?: any): EventEmitter; - removeListener(event: string, fn?: Function, context?: any, once?: boolean): EventEmitter; - removeAllListeners(event?: string): EventEmitter; - - off(event: string, fn?: Function, context?: any, once?: boolean): EventEmitter; - addListener(event: string, fn: Function, context?: any): EventEmitter; - - } - - ////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////CORE////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - - // display - - export class DisplayObject extends EventEmitter implements interaction.InteractiveTarget { - - // begin extras.cacheAsBitmap see https://github.com/pixijs/pixi-typescript/commit/1207b7f4752d79a088d6a9a465a3ec799906b1db - protected _originalRenderWebGL: WebGLRenderer; - protected _originalRenderCanvas: CanvasRenderer; - protected _originalUpdateTransform: boolean; - protected _originalHitTest: any; - protected _cachedSprite: any; - protected _originalDestroy: any; - - cacheAsBitmap: boolean; - - protected _renderCachedWebGL(renderer: WebGLRenderer): void; - protected _initCachedDisplayObject(renderer: WebGLRenderer): void; - protected _renderCachedCanvas(renderer: CanvasRenderer): void; - protected _initCachedDisplayObjectCanvas(renderer: CanvasRenderer): void; - protected _getCachedBounds(): Rectangle; - protected _destroyCachedDisplayObject(): void; - protected _cacheAsBitmapDestroy(): void; - // end extras.cacheAsBitmap - - protected _sr: number; - protected _cr: number; - protected _bounds: Rectangle; - protected _currentBounds: Rectangle; - protected _mask: Rectangle; - protected _cachedObject: any; - - updateTransform(): void; - - position: Point; - scale: Point; - pivot: Point; - rotation: number; - renderable: boolean; - alpha: number; - visible: boolean; - parent: Container; - worldAlpha: number; - worldTransform: Matrix; - filterArea: Rectangle; - - x: number; - y: number; - worldVisible: boolean; - mask: Graphics | Sprite; - filters: AbstractFilter[]; - name: string; - - getBounds(matrix?: Matrix): Rectangle; - getLocalBounds(): Rectangle; - toGlobal(position: Point): Point; - toLocal(position: Point, from?: DisplayObject): Point; - generateTexture(renderer: CanvasRenderer | WebGLRenderer, scaleMode: number, resolution: number): Texture; - setParent(container: Container): Container; - setTransform(x?: number, y?: number, scaleX?: number, scaleY?: number, rotation?: number, skewX?: number, skewY?: number, pivotX?: number, pivotY?: number): DisplayObject; - destroy(): void; - getChildByName(name: string): DisplayObject; - getGlobalPosition(point: Point): Point; - - interactive: boolean; - buttonMode: boolean; - interactiveChildren: boolean; - defaultCursor: string; - hitArea: HitArea; - - on(event: 'click', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'mousedown', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'mouseout', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'mouseover', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'mouseup', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'mouseclick', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'mouseupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'rightclick', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'rightdown', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'rightup', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'rightupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'tap', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'touchend', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'touchendoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'touchmove', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'touchstart', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: string, fn: Function, context?: any): EventEmitter; - - once(event: 'click', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'mousedown', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'mouseout', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'mouseover', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'mouseup', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'mouseclick', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'mouseupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'rightclick', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'rightdown', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'rightup', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'rightupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'tap', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'touchend', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'touchendoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'touchmove', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'touchstart', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: string, fn: Function, context?: any): EventEmitter; - - } - - export class Container extends DisplayObject { - - protected _renderWebGL(renderer: WebGLRenderer): void; - protected _renderCanvas(renderer: CanvasRenderer): void; - - protected onChildrenChange: () => void; - - children: DisplayObject[]; - - width: number; - height: number; - - addChild(...child: DisplayObject[]): DisplayObject; - addChildAt(child: DisplayObject, index: number): DisplayObject; - swapChildren(child: DisplayObject, child2: DisplayObject): void; - getChildIndex(child: DisplayObject): number; - setChildIndex(child: DisplayObject, index: number): void; - getChildAt(index: number): DisplayObject; - removeChild(child: DisplayObject): DisplayObject; - removeChildAt(index: number): DisplayObject; - removeChildren(beginIndex?: number, endIndex?: number): DisplayObject[]; - destroy(destroyChildren?: boolean): void; - generateTexture(renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer, resolution?: number, scaleMode?: number): Texture; - - renderWebGL(renderer: WebGLRenderer): void; - renderCanvas(renderer: CanvasRenderer): void; - - once(event: 'added', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: string, fn: Function, context?: any): EventEmitter; - once(event: 'removed', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: string, fn: Function, context?: any): EventEmitter; - on(event: 'added', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: string, fn: Function, context?: any): EventEmitter; - on(event: 'removed', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: string, fn: Function, context?: any): EventEmitter; - - } - - // graphics - - export class GraphicsData { - - constructor(lineWidth: number, lineColor: number, lineAlpha: number, fillColor: number, fillAlpha: number, fill: boolean, shape: Circle | Rectangle | Ellipse | Polygon); - - lineWidth: number; - lineColor: number; - lineAlpha: number; - fillColor: number; - fillAlpha: number; - fill: boolean; - shape: Circle | Rectangle | Ellipse | Polygon; - type: number; - - clone(): GraphicsData; - - protected _lineTint: number; - protected _fillTint: number; - - } - export class Graphics extends Container { - - protected boundsDirty: boolean; - protected dirty: boolean; - protected glDirty: boolean; - - fillAlpha: number; - lineWidth: number; - lineColor: number; - tint: number; - blendMode: number; - isMask: boolean; - boundsPadding: number; - - clone(): Graphics; - lineStyle(lineWidth?: number, color?: number, alpha?: number): Graphics; - moveTo(x: number, y: number): Graphics; - lineTo(x: number, y: number): Graphics; - quadraticCurveTo(cpX: number, cpY: number, toX: number, toY: number): Graphics; - bezierCurveTo(cpX: number, cpY: number, cpX2: number, cpY2: number, toX: number, toY: number): Graphics; - arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): Graphics; - arc(cx: number, cy: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): Graphics; - beginFill(color: number, alpha?: number): Graphics; - endFill(): Graphics; - drawRect(x: number, y: number, width: number, height: number): Graphics; - drawRoundedRect(x: number, y: number, width: number, height: number, radius: number): Graphics; - drawCircle(x: number, y: number, radius: number): Graphics; - drawEllipse(x: number, y: number, width: number, height: number): Graphics; - drawPolygon(path: number[] | Point[]): Graphics; - clear(): Graphics; - // todo - generateTexture(renderer: WebGLRenderer | CanvasRenderer, resolution?: number, scaleMode?: number): Texture; - getBounds(matrix?: Matrix): Rectangle; - containsPoint(point: Point): boolean; - updateLocalBounds(): void; - drawShape(shape: Circle | Rectangle | Ellipse | Polygon): GraphicsData; - - } - export interface GraphicsRenderer extends ObjectRenderer { - // yikes todo - } - export interface WebGLGraphicsData { - // yikes todo! - } - - // math - - export class Point { - - x: number; - y: number; - - constructor(x?: number, y?: number); - - clone(): Point; - copy(p: Point): void; - equals(p: Point): boolean; - set(x?: number, y?: number): void; - - } - export class Matrix { - - a: number; - b: number; - c: number; - d: number; - tx: number; - ty: number; - - fromArray(array: number[]): void; - toArray(transpose?: boolean, out?: number[]): number[]; - apply(pos: Point, newPos?: Point): Point; - applyInverse(pos: Point, newPos?: Point): Point; - translate(x: number, y: number): Matrix; - scale(x: number, y: number): Matrix; - rotate(angle: number): Matrix; - append(matrix: Matrix): Matrix; - prepend(matrix: Matrix): Matrix; - invert(): Matrix; - identity(): Matrix; - clone(): Matrix; - copy(matrix: Matrix): Matrix; - set(a: number, b: number, c: number, d: number, tx: number, ty: number): Matrix; - setTransform(a: number, b: number, c: number, d: number, sr: number, cr: number, cy: number, sy: number, nsx: number, cs: number): PIXI.Matrix; - - static IDENTITY: Matrix; - static TEMP_MATRIX: Matrix; - - } - - export interface HitArea { - - contains(x: number, y: number): boolean; - - } - - export class Circle implements HitArea { - - constructor(x?: number, y?: number, radius?: number); - - x: number; - y: number; - radius: number; - type: number; - - clone(): Circle; - contains(x: number, y: number): boolean; - getBounds(): Rectangle; - - } - export class Ellipse implements HitArea { - - constructor(x?: number, y?: number, width?: number, height?: number); - - x: number; - y: number; - width: number; - height: number; - type: number; - - clone(): Ellipse; - contains(x: number, y: number): boolean; - getBounds(): Rectangle; - - } - export class Polygon implements HitArea { - - constructor(points: Point[]); - constructor(points: number[]); - constructor(...points: Point[]); - constructor(...points: number[]); - - closed: boolean; - points: number[]; - type: number; - - clone(): Polygon; - contains(x: number, y: number): boolean; - - - } - export class Rectangle implements HitArea { - - constructor(x?: number, y?: number, width?: number, height?: number); - - x: number; - y: number; - width: number; - height: number; - type: number; - - static EMPTY: Rectangle; - - clone(): Rectangle; - contains(x: number, y: number): boolean; - - } - export class RoundedRectangle implements HitArea { - - constructor(x?: number, y?: number, width?: number, height?: number, radius?: number); - - x: number; - y: number; - width: number; - height: number; - radius: number; - type: number; - - static EMPTY: Rectangle; - - clone(): Rectangle; - contains(x: number, y: number): boolean; - - } - - // particles - - export interface ParticleContainerProperties { - - scale?: boolean; - position?: boolean; - rotation?: boolean; - uvs?: boolean; - alpha?: boolean; - - } - export class ParticleContainer extends Container { - - constructor(size?: number, properties?: ParticleContainerProperties, batchSize?: number); - - protected _maxSize: number; - protected _batchSize: number; - protected _properties: boolean[]; - protected _buffers: WebGLBuffer[]; - protected _bufferToUpdate: number; - - protected onChildrenChange: (smallestChildIndex?: number) => void; - - interactiveChildren: boolean; - blendMode: number; - roundPixels: boolean; - - setProperties(properties: ParticleContainerProperties): void; - - } - export interface ParticleBuffer { - - gl: WebGLRenderingContext; - vertSize: number; - vertByteSize: number; - size: number; - dynamicProperties: any[]; - staticProperties: any[]; - - staticStride: number; - staticBuffer: any; - staticData: any; - dynamicStride: number; - dynamicBuffer: any; - dynamicData: any; - - initBuffers(): void; - bind(): void; - destroy(): void; - - } - export interface ParticleRenderer { - - } - export interface ParticleShader { - - } - - // renderers - - export interface RendererOptions { - - view?: HTMLCanvasElement; - transparent?: boolean; - antialias?: boolean; - autoResize?: boolean; - resolution?: number; - clearBeforeRendering?: boolean; - preserveDrawingBuffer?: boolean; - forceFXAA?: boolean; - roundPixels?: boolean; - backgroundColor?: number; - - } - export class SystemRenderer extends EventEmitter { - - protected _backgroundColor: number; - protected _backgroundColorRgb: number[]; - protected _backgroundColorString: string; - protected _tempDisplayObjectParent: any; - protected _lastObjectRendered: DisplayObject; - - constructor(system: string, width?: number, height?: number, options?: RendererOptions); - - type: number; - width: number; - height: number; - view: HTMLCanvasElement; - resolution: number; - transparent: boolean; - autoResize: boolean; - blendModes: any; // todo? - preserveDrawingBuffer: boolean; - clearBeforeRender: boolean; - roundPixels: boolean; - backgroundColor: number; - - render(object: DisplayObject): void; - resize(width: number, height: number): void; - destroy(removeView?: boolean): void; - - } - export class CanvasRenderer extends SystemRenderer { - - protected renderDisplayObject(displayObject: DisplayObject, context: CanvasRenderingContext2D): void; - protected _mapBlendModes(): void; - - constructor(width?: number, height?: number, options?: RendererOptions); - - context: CanvasRenderingContext2D; - refresh: boolean; - maskManager: CanvasMaskManager; - roundPixels: boolean; - smoothProperty: string; - - render(object: DisplayObject): void; - resize(w: number, h: number): void; - - } - export class CanvasBuffer { - - protected clear(): void; - - constructor(width: number, height: number); - - canvas: HTMLCanvasElement; - context: CanvasRenderingContext2D; - - width: number; - height: number; - - resize(width: number, height: number): void; - destroy(): void; - - } - export class CanvasGraphics { - - static renderGraphicsMask(graphics: Graphics, context: CanvasRenderingContext2D): void; - static updateGraphicsTint(graphics: Graphics): void; - - static renderGraphics(graphics: Graphics, context: CanvasRenderingContext2D): void; - - } - export class CanvasMaskManager { - - pushMask(maskData: any, renderer: WebGLRenderer | CanvasRenderer): void; - popMask(renderer: WebGLRenderer | CanvasRenderer): void; - destroy(): void; - - } - export class CanvasTinter { - - static getTintedTexture(sprite: DisplayObject, color: number): HTMLCanvasElement; - static tintWithMultiply(texture: Texture, color: number, canvas: HTMLDivElement): void; - static tintWithOverlay(texture: Texture, color: number, canvas: HTMLCanvasElement): void; - static tintWithPerPixel(texture: Texture, color: number, canvas: HTMLCanvasElement): void; - static roundColor(color: number): number; - static cacheStepsPerColorChannel: number; - static convertTintToImage: boolean; - static vanUseMultiply: boolean; - static tintMethod: Function; - - } - export class WebGLRenderer extends SystemRenderer { - - protected _useFXAA: boolean; - protected _FXAAFilter: filters.FXAAFilter; - protected _contextOptions: { - alpha: boolean; - antiAlias: boolean; - premultipliedAlpha: boolean; - stencil: boolean; - preseveDrawingBuffer: boolean; - }; - protected _renderTargetStack: RenderTarget[]; - - protected _initContext(): void; - protected _createContext(): void; - protected handleContextLost: (event: WebGLContextEvent) => void; - protected _mapGlModes(): void; - protected _managedTextures: Texture[]; - - constructor(width?: number, height?: number, options?: RendererOptions); - - drawCount: number; - shaderManager: ShaderManager; - maskManager: MaskManager; - stencilManager: StencilManager; - filterManager: FilterManager; - blendModeManager: BlendModeManager; - currentRenderTarget: RenderTarget; - currentRenderer: ObjectRenderer; - - render(object: DisplayObject): void; - renderDisplayObject(displayObject: DisplayObject, renderTarget: RenderTarget, clear: boolean): void; - setObjectRenderer(objectRenderer: ObjectRenderer): void; - setRenderTarget(renderTarget: RenderTarget): void; - updateTexture(texture: BaseTexture | Texture): BaseTexture | Texture; - destroyTexture(texture: BaseTexture | Texture, _skipRemove?: boolean): void; - - } - export class AbstractFilter { - - protected vertexSrc: string[]; - protected fragmentSrc: string[]; - - constructor(vertexSrc?: string | string[], fragmentSrc?: string | string[], uniforms?: any); - - uniforms: any; - - padding: number; - - getShader(renderer: WebGLRenderer): Shader; - applyFilter(renderer: WebGLRenderer, input: RenderTarget, output: RenderTarget, clear?: boolean): void; - syncUniform(uniform: WebGLUniformLocation): void; - - } - export class SpriteMaskFilter extends AbstractFilter { - - constructor(sprite: Sprite); - - maskSprite: Sprite; - maskMatrix: Matrix; - - applyFilter(renderer: WebGLRenderbuffer, input: RenderTarget, output: RenderTarget): void; - map: Texture; - offset: Point; - - } - export class BlendModeManager extends WebGLManager { - - constructor(renderer: WebGLRenderer); - - setBlendMode(blendMode: number): boolean; - - } - - export class FilterManager extends WebGLManager { - - constructor(renderer: WebGLRenderer); - - filterStack: any[]; - renderer: WebGLRenderer; - texturePool: any[]; - - onContextChange: () => void; - setFilterStack(filterStack: any[]): void; - pushFilter(target: RenderTarget, filters: any[]): void; - popFilter(): AbstractFilter; - getRenderTarget(clear?: boolean): RenderTarget; - protected returnRenderTarget(renderTarget: RenderTarget): void; - applyFilter(shader: Shader | AbstractFilter, inputTarget: RenderTarget, outputTarget: RenderTarget, clear?: boolean): void; - calculateMappedMatrix(filterArea: Rectangle, sprite: Sprite, outputMatrix?: Matrix): Matrix; - capFilterArea(filterArea: Rectangle): void; - resize(width: number, height: number): void; - destroy(): void; - - } - - export class MaskManager extends WebGLManager { - - stencilStack: StencilMaskStack; - reverse: boolean; - count: number; - alphaMaskPool: any[]; - - pushMask(target: RenderTarget, maskData: any): void; - popMask(target: RenderTarget, maskData: any): void; - pushSpriteMask(target: RenderTarget, maskData: any): void; - popSpriteMask(): void; - pushStencilMask(target: RenderTarget, maskData: any): void; - popStencilMask(target: RenderTarget, maskData: any): void; - - } - export class ShaderManager extends WebGLManager { - - protected _currentId: number; - protected currentShader: Shader; - - constructor(renderer: WebGLRenderer); - - maxAttibs: number; - attribState: any[]; - tempAttribState: any[]; - stack: any[]; - - setAttribs(attribs: any[]): void; - setShader(shader: Shader): boolean; - destroy(): void; - - } - export class StencilManager extends WebGLManager { - - constructor(renderer: WebGLRenderer); - - setMaskStack(stencilMaskStack: StencilMaskStack): void; - pushStencil(graphics: Graphics, webGLData: WebGLGraphicsData): void; - bindGraphics(graphics: Graphics, webGLData: WebGLGraphicsData): void; - popStencil(graphics: Graphics, webGLData: WebGLGraphicsData): void; - destroy(): void; - pushMask(maskData: any[]): void; - popMask(maskData: any[]): void; - - } - export class WebGLManager { - - protected onContextChange: () => void; - - constructor(renderer: WebGLRenderer); - - renderer: WebGLRenderer; - - destroy(): void; - - } - export class Shader { - - protected attributes: any; - protected textureCount: number; - protected uniforms: any; - - protected _glCompile(type: any, src: any): Shader; - - constructor(shaderManager: ShaderManager, vertexSrc: string, fragmentSrc: string, uniforms: any, attributes: any); - - uuid: number; - gl: WebGLRenderingContext; - shaderManager: ShaderManager; - program: WebGLProgram; - vertexSrc: string; - fragmentSrc: string; - - init(): void; - cacheUniformLocations(keys: string[]): void; - cacheAttributeLocations(keys: string[]): void; - compile(): WebGLProgram; - syncUniform(uniform: any): void; - syncUniforms(): void; - initSampler2D(uniform: any): void; - destroy(): void; - - } - export class ComplexPrimitiveShader extends Shader { - - constructor(shaderManager: ShaderManager); - - } - export class PrimitiveShader extends Shader { - - constructor(shaderManager: ShaderManager); - - } - export class TextureShader extends Shader { - - constructor(shaderManager: ShaderManager, vertexSrc?: string, fragmentSrc?: string, customUniforms?: any, customAttributes?: any); - - } - export interface StencilMaskStack { - - stencilStack: any[]; - reverse: boolean; - count: number; - - } - export class ObjectRenderer extends WebGLManager { - - start(): void; - stop(): void; - flush(): void; - render(object?: any): void; - - } - export class RenderTarget { - - constructor(gl: WebGLRenderingContext, width: number, height: number, scaleMode: number, resolution: number, root: boolean); - - gl: WebGLRenderingContext; - frameBuffer: WebGLFramebuffer; - texture: Texture; - size: Rectangle; - resolution: number; - projectionMatrix: Matrix; - transform: Matrix; - frame: Rectangle; - stencilBuffer: WebGLRenderbuffer; - stencilMaskStack: StencilMaskStack; - filterStack: any[]; - scaleMode: number; - root: boolean; - - clear(bind?: boolean): void; - attachStencilBuffer(): void; - activate(): void; - calculateProjection(protectionFrame: Matrix): void; - resize(width: number, height: number): void; - destroy(): void; - - } - export interface Quad { - - gl: WebGLRenderingContext; - vertices: number[]; - uvs: number[]; - colors: number[]; - indices: number[]; - vertexBuffer: WebGLBuffer; - indexBuffer: WebGLBuffer; - - map(rect: Rectangle, rect2: Rectangle): void; - upload(): void; - destroy(): void; - - } - - // sprites - - export class Sprite extends Container { - - static fromFrame(frameId: string): Sprite; - static fromImage(imageId: string, crossorigin?: boolean, scaleMode?: number): Sprite; - - protected _texture: Texture; - protected _width: number; - protected _height: number; - protected cachedTint: number; - - protected _onTextureUpdate(): void; - - constructor(texture?: Texture); - - anchor: Point; - tint: number; - blendMode: number; - shader: Shader | AbstractFilter; - texture: Texture; - - width: number; - height: number; - - getBounds(matrix?: Matrix): Rectangle; - getLocalBounds(): Rectangle; - containsPoint(point: Point): boolean; - destroy(destroyTexture?: boolean, destroyBaseTexture?: boolean): void; - - } - export class SpriteRenderer extends ObjectRenderer { - - protected renderBatch(texture: Texture, size: number, startIndex: number): void; - - vertSize: number; - vertByteSize: number; - size: number; - vertices: number[]; - positions: number[]; - colors: number[]; - indices: number[]; - currentBatchSize: number; - sprites: Sprite[]; - shader: Shader | AbstractFilter; - - render(sprite: Sprite): void; - flush(): void; - start(): void; - destroy(): void; - - } - - // text - - export interface TextStyle { - - font?: string; - fill?: string | number; - align?: string; - stroke?: string | number; - strokeThickness?: number; - wordWrap?: boolean; - wordWrapWidth?: number; - lineHeight?: number; - dropShadow?: boolean; - dropShadowColor?: string | number; - dropShadowAngle?: number; - dropShadowDistance?: number; - padding?: number; - textBaseline?: string; - lineJoin?: string; - miterLimit?: number; - - } - export class Text extends Sprite { - - static fontPropertiesCache: any; - static fontPropertiesCanvas: HTMLCanvasElement; - static fontPropertiesContext: CanvasRenderingContext2D; - - protected _text: string; - protected _style: TextStyle; - - protected updateText(): void; - protected updateTexture(): void; - protected determineFontProperties(fontStyle: TextStyle): TextStyle; - protected wordWrap(text: string): boolean; - - constructor(text?: string, style?: TextStyle, resolution?: number); - - canvas: HTMLCanvasElement; - context: CanvasRenderingContext2D; - dirty: boolean; - resolution: number; - text: string; - style: TextStyle; - - width: number; - height: number; - - } - - // textures - - export class BaseTexture extends EventEmitter { - - static fromImage(imageUrl: string, crossorigin?: boolean, scaleMode?: number): BaseTexture; - static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: number): BaseTexture; - - protected _glTextures: any; - - protected _sourceLoaded(): void; - - constructor(source: HTMLImageElement | HTMLCanvasElement, scaleMode?: number, resolution?: number); - - uuid: number; - resolution: number; - width: number; - height: number; - realWidth: number; - realHeight: number; - scaleMode: number; - hasLoaded: boolean; - isLoading: boolean; - source: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement; - premultipliedAlpha: boolean; - imageUrl: string; - isPowerOfTwo: boolean; - mipmap: boolean; - - update(): void; - loadSource(source: HTMLImageElement | HTMLCanvasElement): void; - destroy(): void; - dispose(): void; - updateSourceImage(newSrc: string): void; - - on(event: 'dispose', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; - on(event: 'error', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; - on(event: 'loaded', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; - on(event: 'update', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; - on(event: string, fn: Function, context?: any): EventEmitter; - - once(event: 'dispose', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; - once(event: 'error', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; - once(event: 'loaded', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; - once(event: 'update', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; - once(event: string, fn: Function, context?: any): EventEmitter; - - } - export class RenderTexture extends Texture { - - protected renderWebGL(displayObject: DisplayObject, matrix?: Matrix, clear?: boolean, updateTransform?: boolean): void; - protected renderCanvas(displayObject: DisplayObject, matrix?: Matrix, clear?: boolean, updateTransform?: boolean): void; - - constructor(renderer: CanvasRenderer | WebGLRenderer, width?: number, height?: number, scaleMode?: number, resolution?: number); - - width: number; - height: number; - resolution: number; - renderer: CanvasRenderer | WebGLRenderer; - valid: boolean; - - render(displayObject: DisplayObject, matrix?: Matrix, clear?: boolean, updateTransform?: boolean): void; - resize(width: number, height: number, updateBase?: boolean): void; - clear(): void; - destroy(): void; - getImage(): HTMLImageElement; - getPixels(): number[]; - getPixel(x: number, y: number): number[]; - getBase64(): string; - getCanvas(): HTMLCanvasElement; - - } - export class Texture extends BaseTexture { - - static fromImage(imageUrl: string, crossOrigin?: boolean, scaleMode?: number): Texture; - static fromFrame(frameId: string): Texture; - static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: number): Texture; - static fromVideo(video: HTMLVideoElement | string, scaleMode?: number): Texture; - static fromVideoUrl(videoUrl: string, scaleMode?: number): Texture; - static addTextureToCache(texture: Texture, id: string): void; - static removeTextureFromCache(id: string): Texture; - static EMPTY: Texture; - - protected _frame: Rectangle; - protected _uvs: TextureUvs; - - protected onBaseTextureUpdated(baseTexture: BaseTexture): void; - protected onBaseTextureLoaded(baseTexture: BaseTexture): void; - protected _updateUvs(): void; - - constructor(baseTexture: BaseTexture, frame?: Rectangle, crop?: Rectangle, trim?: Rectangle, rotate?: boolean); - - noFrame: boolean; - baseTexture: BaseTexture; - trim: Rectangle; - valid: boolean; - requiresUpdate: boolean; - width: number; - height: number; - crop: Rectangle; - rotate: boolean; - - frame: Rectangle; - - update(): void; - destroy(destroyBase?: boolean): void; - clone(): Texture; - - } - export class TextureUvs { - - x0: number; - y0: number; - x1: number; - y1: number; - x2: number; - y2: number; - x3: number; - y3: number; - - set(frame: Rectangle, baseFrame: Rectangle, rotate: boolean): void; - - } - export class VideoBaseTexture extends BaseTexture { - - static fromVideo(video: HTMLVideoElement, scaleMode?: number): VideoBaseTexture; - static fromUrl(videoSrc: string | any | string[] | any[]): VideoBaseTexture; - - protected _loaded: boolean; - protected _onUpdate(): void; - protected _onPlayStart(): void; - protected _onPlayStop(): void; - protected _onCanPlay(): void; - - constructor(source: HTMLVideoElement, scaleMode?: number); - - autoUpdate: boolean; - - destroy(): void; - - } - - // utils - - export class utils { - - static uuid(): number; - static hex2rgb(hex: number, out?: number[]): number[]; - static hex2string(hex: number): string; - static rgb2hex(rgb: Number[]): number; - static canUseNewCanvasBlendModel(): boolean; - static getNextPowerOfTwo(number: number): number; - static isPowerOfTwo(width: number, height: number): boolean; - static getResolutionOfUrl(url: string): number; - static sayHello(type: string): void; - static isWebGLSupported(): boolean; - static sign(n: number): number; - static TextureCache: any; - static BaseTextureCache: any; - - } - - ////////////////////////////////////////////////////////////////////////////// - ////////////////////////////EXTRAS//////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - - export namespace extras { - - export interface BitmapTextStyle { - - font?: string | { - - name?: string; - size?: number; - - }; - align?: string; - tint?: number; - - } - export class BitmapText extends Container { - - static fonts: any; - - protected _glyphs: Sprite[]; - protected _font: string | { - tint: number; - align: string; - name: string; - size: number; - }; - protected _text: string; - - protected updateText(): void; - - constructor(text: string, style?: BitmapTextStyle); - - textWidth: number; - textHeight: number; - maxWidth: number; - maxLineHeight: number; - dirty: boolean; - - tint: number; - align: string; - font: string | { - tint: number; - align: string; - name: string; - size: number; - }; - text: string; - - } - export class MovieClip extends Sprite { - - static fromFrames(frame: string[]): MovieClip; - static fromImages(images: string[]): MovieClip; - - protected _textures: Texture[]; - protected _durations: number[]; - protected _currentTime: number; - - protected update(deltaTime: number): void; - - constructor(textures: Texture[]); - - animationSpeed: number; - loop: boolean; - onComplete: () => void; - currentFrame: number; - playing: boolean; - - totalFrames: number; - textures: Texture[]; - - stop(): void; - play(): void; - gotoAndStop(frameName: number): void; - gotoAndPlay(frameName: number): void; - destroy(): void; - - } - export class TilingSprite extends Sprite { - - // This is really unclean but is the only way :( - // See http://stackoverflow.com/questions/29593905/typescript-declaration-extending-class-with-static-method/29595798#29595798 - // Thanks bas! - static fromFrame(frameId: string): Sprite; - static fromFrame(frameId: string, width?: number, height?: number): TilingSprite; - - static fromImage(imageId: string, crossorigin?: boolean, scaleMode?: number): Sprite; - static fromImage(imageId: string, width?: number, height?: number, crossorigin?: boolean, scaleMode?: number): TilingSprite; - - protected _tileScaleOffset: Point; - protected _tilingTexture: boolean; - protected _refreshTexture: boolean; - protected _uvs: TextureUvs[]; - - constructor(texture: Texture, width: number, height: number); - - tileScale: Point; - tilePosition: Point; - - width: number; - height: number; - originalTexture: Texture; - - getBounds(): Rectangle; - generateTilingTexture(renderer: WebGLRenderer | CanvasRenderer, texture: Texture, forcePowerOfTwo?: boolean): Texture; - containsPoint(point: Point): boolean; - destroy(): void; - - } - - } - - ////////////////////////////////////////////////////////////////////////////// - ///////////////////////////////FILTERS//////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - - namespace filters { - - export class AsciiFilter extends AbstractFilter { - size: number; - } - export class BloomFilter extends AbstractFilter { - - blur: number; - blurX: number; - blurY: number; - - } - export class BlurFilter extends AbstractFilter { - - protected blurXFilter: BlurXFilter; - protected blurYFilter: BlurYFilter; - - blur: number; - passes: number; - blurX: number; - blurY: number; - - } - export class BlurXFilter extends AbstractFilter { - - passes: number; - strength: number; - blur: number; - - } - export class BlurYFilter extends AbstractFilter { - - passes: number; - strength: number; - blur: number; - - } - export class SmartBlurFilter extends AbstractFilter { - - } - export class ColorMatrixFilter extends AbstractFilter { - - protected _loadMatrix(matrix: number[], multiply: boolean): void; - protected _multiply(out: number[], a: number[], b: number[]): void; - protected _colorMatrix(matrix: number[]): void; - - matrix: number[]; - - brightness(b: number, multiply?: boolean): void; - greyscale(scale: number, multiply?: boolean): void; - blackAndWhite(multiply?: boolean): void; - hue(rotation: number, multiply?: boolean): void; - contrast(amount: number, multiply?: boolean): void; - saturate(amount: number, multiply?: boolean): void; - desaturate(multiply?: boolean): void; - negative(multiply?: boolean): void; - sepia(multiply?: boolean): void; - technicolor(multiply?: boolean): void; - polaroid(multiply?: boolean): void; - toBGR(multiply?: boolean): void; - kodachrome(multiply?: boolean): void; - browni(multiply?: boolean): void; - vintage(multiply?: boolean): void; - colorTone(desaturation: number, toned: number, lightColor: string, darkColor: string, multiply?: boolean): void; - night(intensity: number, multiply?: boolean): void; - predator(amount: number, multiply?: boolean): void; - lsd(multiply?: boolean): void; - reset(): void; - - } - export class ColorStepFilter extends AbstractFilter { - - step: number; - - } - export class ConvolutionFilter extends AbstractFilter { - - constructor(matrix: number[], width: number, height: number); - - matrix: number[]; - width: number; - height: number; - - } - export class CrossHatchFilter extends AbstractFilter { - - } - export class DisplacementFilter extends AbstractFilter { - - constructor(sprite: Sprite, scale?: number); - - map: Texture; - - scale: Point; - - } - export class DotScreenFilter extends AbstractFilter { - - scale: number; - angle: number; - - } - export class BlurYTintFilter extends AbstractFilter { - - blur: number; - - } - export class DropShadowFilter extends AbstractFilter { - - blur: number; - blurX: number; - blurY: number; - color: number; - alpha: number; - distance: number; - angle: number; - - } - export class GrayFilter extends AbstractFilter { - - gray: number; - - } - export class InvertFilter extends AbstractFilter { - - invert: number; - - } - export class NoiseFilter extends AbstractFilter { - - noise: number; - - } - export class PixelateFilter extends AbstractFilter { - - size: Point; - - } - export class RGBSplitFilter extends AbstractFilter { - - red: number; - green: number; - blue: number; - - } - export class SepiaFilter extends AbstractFilter { - - sepia: number; - - } - export class ShockwaveFilter extends AbstractFilter { - - center: number[]; - params: any; - time: number; - - } - export class TiltShiftAxisFilter extends AbstractFilter { - - blur: number; - gradientBlur: number; - start: number; - end: number; - - updateDelta(): void; - - } - export class TiltShiftFilter extends AbstractFilter { - - blur: number; - gradientBlur: number; - start: number; - end: number; - - } - export class TiltShiftXFilter extends AbstractFilter { - - updateDelta(): void; - - } - export class TiltShiftYFilter extends AbstractFilter { - - updateDelta(): void; - - } - export class TwistFilter extends AbstractFilter { - - offset: Point; - radius: number; - angle: number; - - } - export class FXAAFilter extends AbstractFilter { - - applyFilter(renderer: WebGLRenderer, input: RenderTarget, output: RenderTarget): void; - - } - } - - ////////////////////////////////////////////////////////////////////////////// - ////////////////////////////INTERACTION/////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - - export namespace interaction { - - export interface InteractionEvent { - - stopped: boolean; - target: any; - type: string; - data: InteractionData; - stopPropagation(): void; - - } - - export class InteractionData { - - global: Point; - target: DisplayObject; - originalEvent: Event; - identifier: number; - - getLocalPosition(displayObject: DisplayObject, point?: Point, globalPos?: Point): Point; - - } - - export class InteractionManager { - - protected interactionDOMElement: HTMLElement; - protected eventsAdded: boolean; - protected _tempPoint: Point; - - protected setTargetElement(element: HTMLElement, resolution: number): void; - protected addEvents(): void; - protected removeEvents(): void; - protected dispatchEvent(displayObject: DisplayObject, eventString: string, eventData: any): void; - protected onMouseDown: (event: Event) => void; - protected processMouseDown: (displayObject: DisplayObject, hit: boolean) => void; - protected onMouseUp: (event: Event) => void; - protected processMouseUp: (displayObject: DisplayObject, hit: boolean) => void; - protected onMouseMove: (event: Event) => void; - protected processMouseMove: (displayObject: DisplayObject, hit: boolean) => void; - protected onMouseOut: (event: Event) => void; - protected processMouseOverOut: (displayObject: DisplayObject, hit: boolean) => void; - protected onTouchStart: (event: Event) => void; - protected processTouchStart: (DisplayObject: DisplayObject, hit: boolean) => void; - protected onTouchEnd: (event: Event) => void; - protected processTouchEnd: (displayObject: DisplayObject, hit: boolean) => void; - protected onTouchMove: (event: Event) => void; - protected processTouchMove: (displayObject: DisplayObject, hit: boolean) => void; - protected getTouchData(touchEvent: InteractionData): InteractionData; - protected returnTouchData(touchData: InteractionData): void; - - constructor(renderer: CanvasRenderer | WebGLRenderer, options?: { autoPreventDefault?: boolean; interactionFrequence?: number; }); - - renderer: CanvasRenderer | WebGLRenderer; - autoPreventDefault: boolean; - interactionFrequency: number; - mouse: InteractionData; - eventData: { - stopped: boolean; - target: any; - type: any; - data: InteractionData; - }; - interactiveDataPool: InteractionData[]; - last: number; - currentCursorStyle: string; - resolution: number; - update(deltaTime: number): void; - - mapPositionToPoint(point: Point, x: number, y: number): void; - processInteractive(point: Point, displayObject: DisplayObject, func: (displayObject: DisplayObject, hit: boolean) => void, hitTest: boolean, interactive: boolean): boolean; - destroy(): void; - - } - - export interface InteractiveTarget { - - interactive: boolean; - buttonMode: boolean; - interactiveChildren: boolean; - defaultCursor: string; - hitArea: HitArea; - - } - - } - - ////////////////////////////////////////////////////////////////////////////// - ///////////////////////////////LOADER///////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - // https://github.com/englercj/resource-loader/blob/master/src/Loader.js - - export namespace loaders { - export interface LoaderOptions { - - crossOrigin?: boolean; - loadType?: number; - xhrType?: string; - - } - export interface ResourceDictionary { - - [index: string]: PIXI.loaders.Resource; - } - export class Loader extends EventEmitter { - - constructor(baseUrl?: string, concurrency?: number); - - baseUrl: string; - progress: number; - loading: boolean; - resources: ResourceDictionary; - - add(name: string, url: string, options?: LoaderOptions, cb?: () => void): Loader; - add(url: string, options?: LoaderOptions, cb?: () => void): Loader; - // todo I am not sure of object literal notional (or its options) so just allowing any but would love to improve this - add(obj: any, options?: LoaderOptions, cb?: () => void): Loader; - - on(event: 'complete', fn: (loader: loaders.Loader, object: any) => void, context?: any): EventEmitter; - on(event: 'error', fn: (error: Error, loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; - on(event: 'load', fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; - on(event: 'progress', fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; - on(event: 'start', fn: (loader: loaders.Loader) => void, context?: any): EventEmitter; - on(event: string, fn: Function, context?: any): EventEmitter; - - once(event: 'complete', fn: (loader: loaders.Loader, object: any) => void, context?: any): EventEmitter; - once(event: 'error', fn: (error: Error, loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; - once(event: 'load', fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; - once(event: 'progress', fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; - once(event: 'start', fn: (loader: loaders.Loader) => void, context?: any): EventEmitter; - once(event: string, fn: Function, context?: any): EventEmitter; - - before(fn: Function): Loader; - pre(fn: Function): Loader; - - after(fn: Function): Loader; - use(fn: Function): Loader; - - reset(): void; - - load(cb?: (loader: loaders.Loader, object: any) => void): Loader; - - } - export class Resource extends EventEmitter { - - static LOAD_TYPE: { - XHR: number; - IMAGE: number; - AUDIO: number; - VIDEO: number; - }; - - static XHR_READ_STATE: { - UNSENT: number; - OPENED: number; - HEADERS_RECIEVED: number; - LOADING: number; - DONE: number; - }; - - static XHR_RESPONSE_TYPE: { - DEFAULT: number; - BUFFER: number; - BLOB: number; - DOCUMENT: number; - JSON: number; - TEXT: number; - }; - - constructor(name?: string, url?: string | string[], options?: LoaderOptions); - - name: string; - texture: Texture; - textures: Texture[]; - url: string; - data: any; - crossOrigin: string; - loadType: number; - xhrType: string; - error: Error; - xhr: XMLHttpRequest; - - complete(): void; - load(cb?: () => void): void; - - } - } - - ////////////////////////////////////////////////////////////////////////////// - ///////////////////////////////MESH/////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - - export namespace mesh { - - export class Mesh extends Container { - - static DRAW_MODES: { - TRIANGLE_MESH: number; - TRIANGLES: number; - }; - - constructor(texture: Texture, vertices?: number[], uvs?: number[], indices?: number[], drawMode?: number); - - texture: Texture; - uvs: number[]; - vertices: number[]; - indices: number[]; - dirty: boolean; - blendMode: number; - canvasPadding: number; - drawMode: number; - shader: Shader | AbstractFilter; - - getBounds(matrix?: Matrix): Rectangle; - containsPoint(point: Point): boolean; - - protected _texture: Texture; - - protected _renderCanvasTriangleMesh(context: CanvasRenderingContext2D): void; - protected _renderCanvasTriangles(context: CanvasRenderingContext2D): void; - protected _renderCanvasDrawTriangle(context: CanvasRenderingContext2D, vertices: number, uvs: number, index0: number, index1: number, index2: number): void; - protected renderMeshFlat(Mesh: Mesh): void; - protected _onTextureUpdate(): void; - - } - export class Rope extends Mesh { - - protected _ready: boolean; - - protected getTextureUvs(): TextureUvs; - - constructor(texture: Texture, points: Point[]); - - points: Point[]; - colors: number[]; - - refresh(): void; - - } - export class Plane extends Mesh { - - segmentsX: number; - segmentsY: number; - - constructor(texture: Texture, segmentsX?: number, segmentsY?: number); - - } - - - export class MeshRenderer extends ObjectRenderer { - - protected _initWebGL(mesh: Mesh): void; - - indices: number[]; - - constructor(renderer: WebGLRenderer); - - render(mesh: Mesh): void; - flush(): void; - start(): void; - destroy(): void; - - } - - export interface MeshShader extends Shader { } - - } - - namespace ticker { - - export var shared: Ticker; - - export class Ticker { - - protected _tick(time: number): void; - protected _emitter: EventEmitter; - protected _requestId: number; - protected _maxElapsedMS: number; - - protected _requestIfNeeded(): void; - protected _cancelIfNeeded(): void; - protected _startIfPossible(): void; - - autoStart: boolean; - deltaTime: number; - elapsedMS: number; - lastTime: number; - speed: number; - started: boolean; - - FPS: number; - minFPS: number; - - add(fn: (deltaTime: number) => void, context?: any): Ticker; - addOnce(fn: (deltaTime: number) => void, context?: any): Ticker; - remove(fn: (deltaTime: number) => void, context?: any): Ticker; - start(): void; - stop(): void; - update(): void; - - } - - } -} diff --git a/pixi.js/v3/pixi.js-tests.ts b/pixi.js/v3/pixi.js-tests.ts deleted file mode 100644 index ec4c5329c0..0000000000 --- a/pixi.js/v3/pixi.js-tests.ts +++ /dev/null @@ -1,2739 +0,0 @@ -namespace basics { - - export class Basics { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private bunny: PIXI.Sprite; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - // create a texture from an image path - var texture: PIXI.Texture = PIXI.Texture.fromImage("../../_assets/basics/bunny.png"); - - // create a new Sprite using the texture - this.bunny = new PIXI.Sprite(texture); - - // center the sprite's anchor point - this.bunny.anchor.x = 0.5; - this.bunny.anchor.y = 0.5; - - // move the sprite to the center of the screen - this.bunny.position.x = 200; - this.bunny.position.y = 150; - - // add it to the stage - this.stage.addChild(this.bunny); - - this.animate(); - - } - - private animate = (): void => { - - requestAnimationFrame(this.animate); - - this.bunny.rotation += 0.1; - - this.renderer.render(this.stage); - - } - - } - -} - -namespace basics { - - export class Click { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private sprite: PIXI.Sprite; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - this.sprite = PIXI.Sprite.fromImage('../../_assets/basics/bunny.png'); - this.sprite.position.set(230, 264); - this.sprite.interactive = true; - this.sprite.on('mousedown', this.onDown, this); - this.sprite.on('touchstart', this.onDown, this); - - // add it to the stage - this.stage.addChild(this.sprite); - - // start animatng - this.animate(); - - } - - private onDown = (eventData: PIXI.interaction.InteractionData): void => { - - this.sprite.scale.x += 0.3; - this.sprite.scale.y += 0.3; - - } - - private animate = (): void => { - - requestAnimationFrame(this.animate); - - this.renderer.render(this.stage); - - } - - } - -} - -namespace basics { - - export class Container { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private container: PIXI.Container; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - this.container = new PIXI.Container(); - - this.stage.addChild(this.container); - - for (var j = 0; j < 5; j++) { - - for (var i = 0; i < 5; i++) { - - var bunny: PIXI.Sprite = PIXI.Sprite.fromImage('../../_assets/basics/bunny.png'); - bunny.x = 40 * i; - bunny.y = 40 * j; - this.container.addChild(bunny); - - } - - } - - /* - * All the bunnies are added to the container with the addChild method - * when you do this, all the bunnies become children of the container, and when a container moves, - * so do all its children. - * This gives you a lot of flexibility and makes it easier to position elements on the screen - */ - this.container.x = 100; - this.container.y = 60; - - // start animating - this.animate(); - - } - - private animate = (): void => { - - requestAnimationFrame(this.animate); - - this.renderer.render(this.stage); - - } - - } - -} - -namespace basics { - - export class CustomFilter { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private background: PIXI.Sprite; - - private filter: CustomizedFilter; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - this.background = PIXI.Sprite.fromImage('../../_assets/bkg-grass.jpg'); - this.background.scale.set(1.3, 1); - this.stage.addChild(this.background); - - - PIXI.loader.add('shader', '../../_assets/basics/shader.frag'); - PIXI.loader.once('complete', this.onLoaded, this); - PIXI.loader.load(); - - } - - private onLoaded(loader: PIXI.loaders.Loader, res: any) { - - var fragmentSrc = res.shader.data; - - this.filter = new CustomizedFilter(fragmentSrc); - this.background.filters = [this.filter]; - - this.animate(); - - - } - - private animate = (): void => { - - this.filter.uniforms.customUniform.value += 0.04; - - this.renderer.render(this.stage); - requestAnimationFrame(this.animate); - - } - - } - - export class CustomizedFilter extends PIXI.AbstractFilter { - - constructor(fragmentSource: string | string[]) { - super(null, fragmentSource, { - customUniform: { - type: '1f', - value: 0 - } - }); - } - - } - -} - -namespace basics { - - export class Graphics { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private graphics: PIXI.Graphics; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - this.stage.interactive = true; - - this.graphics = new PIXI.Graphics(); - - // draw a shape - this.graphics.moveTo(50, 50); - this.graphics.lineTo(250, 50); - this.graphics.lineTo(100, 100); - this.graphics.lineTo(50, 50); - this.graphics.endFill(); - - // set a fill and a line style again and draw a rectangle - this.graphics.lineStyle(2, 0x0000FF, 1); - this.graphics.beginFill(0xFF700B, 1); - this.graphics.drawRect(50, 250, 120, 120); - - // draw a rounded rectangle - this.graphics.lineStyle(2, 0xFF00FF, 1); - this.graphics.beginFill(0xFF00BB, 0.25); - this.graphics.drawRoundedRect(150, 450, 300, 100, 15); - this.graphics.endFill(); - - // draw a circle, set the lineStyle to zero so the circle doesn't have an outline - this.graphics.lineStyle(0); - this.graphics.beginFill(0xFFFF0B, 0.5); - this.graphics.drawCircle(470, 90, 60); - this.graphics.endFill(); - - this.stage.addChild(this.graphics); - - // start animating - this.animate(); - - } - - private animate = (): void => { - - requestAnimationFrame(this.animate); - - this.renderer.render(this.stage); - - } - - } - -} - -namespace basics { - - export class RenderTexture { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private container: PIXI.Container; - - private renderTexture: PIXI.RenderTexture; - - private sprite: PIXI.Sprite; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - this.container = new PIXI.Container(); - - this.stage.addChild(this.container); - - for (var j = 0; j < 5; j++) { - - for (var i = 0; i < 5; i++) { - - var bunny: PIXI.Sprite = PIXI.Sprite.fromImage('../../_assets/basics/bunny.png'); - bunny.x = 40 * i; - bunny.y = 40 * j; - bunny.rotation = Math.random() * (Math.PI * 2); - this.container.addChild(bunny); - - } - - } - - this.renderTexture = new PIXI.RenderTexture(this.renderer, 300, 200, PIXI.SCALE_MODES.LINEAR, 0.1); - - this.sprite = new PIXI.Sprite(this.renderTexture); - this.sprite.x = 450; - this.sprite.y = 60; - this.stage.addChild(this.sprite); - - this.container.x = 100; - this.container.y = 60; - - // start animating - this.animate(); - - } - - private animate = (): void => { - - this.renderTexture.render(this.container); - - requestAnimationFrame(this.animate); - - this.renderer.render(this.stage); - - } - - } - -} - -namespace basics { - - export class SpriteSheet { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private movie: PIXI.extras.MovieClip; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - PIXI.loader.add('../../_assets/basics/fighter.json').load((loader: PIXI.loaders.Loader, object: any): void => { - - // create an array of textures from an image path - var frames: PIXI.Texture[] = []; - - for (var i = 0; i < 30; i++) { - - var val = i < 10 ? '0' + i : i; - - // magically works since the spritesheet was loaded with the pixi loader - frames.push(PIXI.Texture.fromFrame('rollSequence00' + val + '.png')); - } - - - // create a MovieClip (brings back memories from the days of Flash, right ?) - this.movie = new PIXI.extras.MovieClip(frames); - - /* - * A MovieClip inherits all the properties of a PIXI sprite - * so you can change its position, its anchor, mask it, etc - */ - this.movie.position.set(300); - this.movie.anchor.set(0.5); - this.movie.animationSpeed = 0.5; - this.movie.play(); - - this.stage.addChild(this.movie); - - this.animate(); - - }); - - } - - private animate = (): void => { - - this.movie.rotation += 0.01; - - // render the stage container - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); - - } - - } - -} - -namespace basics { - - export class Text { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private basicText: PIXI.Text; - - private richText: PIXI.Text; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - this.basicText = new PIXI.Text('Basic Text in Pixi'); - this.basicText.x = 30; - this.basicText.y = 90; - - this.stage.addChild(this.basicText); - - var style: PIXI.TextStyle = { - font: '36px Arial bold italic', - fill: PIXI.utils.hex2string(0xF7EDCA), - stroke: '#4a1850', - strokeThickness: 5, - dropShadow: true, - dropShadowColor: '#000000', - dropShadowAngle: Math.PI / 6, - dropShadowDistance: 6, - wordWrap: true, - wordWrapWidth: 440 - }; - - this.richText = new PIXI.Text('Rich Text with a lot of options and across multiple lines', style); - this.richText.x = 30; - this.richText.y = 180; - - this.stage.addChild(this.richText); - - // start animating - this.animate(); - - } - - private animate = (): void => { - - requestAnimationFrame(this.animate); - - this.renderer.render(this.stage); - - } - - } - -} - -namespace basics { - - export class TexturedMesh { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private strip: PIXI.mesh.Rope; - - private graphics: PIXI.Graphics; - - private count: number; - - private points: PIXI.Point[]; - - private ropeLength: number; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - this.count = 0; - - this.ropeLength = 918 / 20; - this.ropeLength = 45; - - this.points = []; - - for (var i = 0; i < 25; i++) { - this.points.push(new PIXI.Point(i * this.ropeLength, 0)); - } - - this.strip = new PIXI.mesh.Rope(PIXI.Texture.fromImage('../../_assets/snake.png'), this.points); - this.strip.position.x = -40; - this.strip.position.y = 300; - this.stage.addChild(this.strip); - - this.graphics = new PIXI.Graphics(); - this.graphics.x = this.strip.x; - this.graphics.y = this.strip.y; - this.stage.addChild(this.graphics); - - // start animating - this.animate(); - - } - - private animate = (): void => { - - this.count += 0.1; - - // make the snake - for (var i = 0; i < this.points.length; i++) { - - this.points[i].y = Math.sin((i * 0.5) + this.count) * 30; - - this.points[i].x = i * this.ropeLength + Math.cos((i * 0.3) + this.count) * 20; - - } - - // render the stage - this.renderer.render(this.stage); - - this.renderPoints(); - - requestAnimationFrame(this.animate); - - } - - private renderPoints(): void { - - this.graphics.clear(); - - this.graphics.lineStyle(2, 0xffc2c2); - this.graphics.moveTo(this.points[0].x, this.points[0].y); - - for (var i = 1; i < this.points.length; i++) { - this.graphics.lineTo(this.points[i].x, this.points[i].y); - } - - for (var i = 1; i < this.points.length; i++) { - this.graphics.beginFill(0xff0022); - this.graphics.drawCircle(this.points[i].x, this.points[i].y, 10); - this.graphics.endFill(); - } - - } - - } - -} - -namespace basics { - - export class TilingSprite { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private texture: PIXI.Texture; - - private tilingSprite: PIXI.extras.TilingSprite; - - private count: number; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - // create a texture from an image path - this.texture = PIXI.Texture.fromImage('../../_assets/p2.jpeg'); - - /* create a tiling sprite ... - * requires a texture, a width and a height - * in WebGL the image size should preferably be a power of two - */ - this.tilingSprite = new PIXI.extras.TilingSprite(this.texture, this.renderer.width, this.renderer.height); - this.stage.addChild(this.tilingSprite); - - this.count = 0; - - this.animate(); - - } - - private animate = (): void => { - - this.count += 0.005; - - this.tilingSprite.tileScale.x = 2 + Math.sin(this.count); - this.tilingSprite.tileScale.y = 2 + Math.cos(this.count); - - this.tilingSprite.tilePosition.x += 1; - this.tilingSprite.tilePosition.y += 1; - - // render the root container - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); - - } - - } - -} - -namespace basics { - - export class Video { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private texture: PIXI.Texture; - - private videoSprite: PIXI.Sprite; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - // create a video texture from a path - this.texture = PIXI.Texture.fromVideo('../../_assets/testVideo.mp4'); - - // create a new sprite using the video texture (yes it's that easy) - this.videoSprite = new PIXI.Sprite(this.texture); - this.videoSprite.width = this.renderer.width; - this.videoSprite.height = this.renderer.height; - this.stage.addChild(this.videoSprite); - - this.stage.addChild(this.videoSprite); - - this.animate(); - - } - - private animate = (): void => { - - // render the stage - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); - - } - - } - -} - -namespace demos { - - export class AlphaMask { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private background: PIXI.Container; - - private cells: PIXI.Sprite; - - private mask: PIXI.Sprite; - - private target: PIXI.Point; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - this.stage.interactive = true; - - this.background = PIXI.Sprite.fromImage('../../_assets/bkg.jpg'); - this.stage.addChild(this.background); - - this.cells = PIXI.Sprite.fromImage('../../_assets/cells.png'); - this.cells.scale.set(1.5, 1.5); - - this.mask = PIXI.Sprite.fromImage('../../_assets/flowerTop.png'); - this.mask.anchor.set(0.5); - this.mask.position.x = 310; - this.mask.position.y = 190; - - this.cells.mask = this.mask; - - this.stage.addChild(this.mask); - - this.stage.addChild(this.cells); - - this.target = new PIXI.Point(); - - this.reset(); - - this.animate(); - - } - - private reset(): void { - - this.target.x = Math.floor(Math.random() * 550); - this.target.y = Math.floor(Math.random() * 300); - - } - - private animate = (): void => { - - this.mask.position.x += (this.target.x - this.mask.x) * 0.1; - this.mask.position.y += (this.target.y - this.mask.y) * 0.1; - - if (Math.abs(this.mask.x - this.target.x) < 1) { - this.reset(); - } - - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); - - } - - } - -} - -namespace demos { - - export class Batch { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private sprites: PIXI.ParticleContainer; - - private maggots: BatchDude[]; - - private tick: number; - - private dudeBounds: PIXI.Rectangle; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - this.sprites = new PIXI.ParticleContainer(10000, { - - scale: true, - position: true, - rotation: true, - uvs: true, - alpha: true - - }); - this.stage.addChild(this.sprites); - - // create an array to store all the sprites - this.maggots = []; - - var totalSprites = this.renderer instanceof PIXI.WebGLRenderer ? 10000 : 100; - - for (var i = 0; i < totalSprites; i++) { - - // create a new Sprite - var dude = new BatchDude(PIXI.Texture.fromImage('../../_assets/tinyMaggot.png')); - - dude.tint = Math.random() * 0xE8D4CD; - - // set the anchor point so the texture is centerd on the sprite - dude.anchor.set(0.5); - - // different maggots, different sizes - dude.scale.set(0.8 + Math.random() * 0.3); - - // scatter them all - dude.x = Math.random() * this.renderer.width; - dude.y = Math.random() * this.renderer.height; - - dude.tint = Math.random() * 0x808080; - - // create a random direction in radians - dude.direction = Math.random() * Math.PI * 2; - - // this number will be used to modify the direction of the sprite over time - dude.turningSpeed = Math.random() - 0.8; - - // create a random speed between 0 - 2, and these maggots are slooww - dude.speed = (2 + Math.random() * 2) * 0.2; - - dude.offset = Math.random() * 100; - - // finally we push the dude into the maggots array so it it can be easily accessed later - this.maggots.push(dude); - - this.sprites.addChild(dude); - - } - - // create a bounding box box for the little maggots - var dudeBoundsPadding = 100; - this.dudeBounds = new PIXI.Rectangle(-dudeBoundsPadding, - -dudeBoundsPadding, - this.renderer.width + dudeBoundsPadding * 2, - this.renderer.height + dudeBoundsPadding * 2); - - this.tick = 0; - - // start animating - this.animate(); - - } - - private animate = (): void => { - - // iterate through the sprites and update their position - for (const dude of this.maggots) { - dude.scale.y = 0.95 + Math.sin(this.tick + dude.offset) * 0.05; - dude.direction += dude.turningSpeed * 0.01; - dude.position.x += Math.sin(dude.direction) * (dude.speed * dude.scale.y); - dude.position.y += Math.cos(dude.direction) * (dude.speed * dude.scale.y); - dude.rotation = -dude.direction + Math.PI; - - // wrap the maggots - if (dude.position.x < this.dudeBounds.x) { - dude.position.x += this.dudeBounds.width; - } else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { - dude.position.x -= this.dudeBounds.width; - } - - if (dude.position.y < this.dudeBounds.y) { - dude.position.y += this.dudeBounds.height; - } else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { - dude.position.y -= this.dudeBounds.height; - } - } - - // increment the ticker - this.tick += 0.1; - - // time to render the stage ! - this.renderer.render(this.stage); - - // request another animation frame... - requestAnimationFrame(this.animate); - - } - - } - - export class BatchDude extends PIXI.Sprite { - - direction: number; - speed: number; - turningSpeed: number; - offset: number; - - constructor(texture: PIXI.Texture) { - - super(texture); - - } - - } - -} - -namespace demos { - - export class BlendModes { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private background: PIXI.Sprite; - - private dudeArray: BlendModesDude[]; - - private totalDudes: number; - - private dudeBounds: PIXI.Rectangle; - - private tick: number; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - // create a new background sprite - this.background = PIXI.Sprite.fromImage('../../_assets/BGrotate.jpg'); - this.stage.addChild(this.background); - - // create an array to store a reference to the dudes - this.dudeArray = []; - - this.totalDudes = 20; - - for (var i = 0; i < this.totalDudes; i++) { - - // create a new Sprite that uses the image name that we just generated as its source - var dude = new BlendModesDude(PIXI.Texture.fromImage('../../_assets/flowerTop.png')); - - dude.anchor.set(0.5); - - // set a random scale for the dude - dude.scale.set(0.8 + Math.random() * 0.3); - - // finally let's set the dude to be at a random position... - dude.position.x = Math.floor(Math.random() * this.renderer.width); - dude.position.y = Math.floor(Math.random() * this.renderer.height); - - // The important bit of this example, this is how you change the default blend mode of the sprite - dude.blendMode = PIXI.BLEND_MODES.ADD; - - // create some extra properties that will control movement - dude.direction = Math.random() * Math.PI * 2; - - // this number will be used to modify the direction of the dude over time - dude.turningSpeed = Math.random() - 0.8; - - // create a random speed for the dude between 0 - 2 - dude.speed = 2 + Math.random() * 2; - - // finally we push the dude into the dudeArray so it it can be easily accessed later - this.dudeArray.push(dude); - - this.stage.addChild(dude); - - } - - // create a bounding box box for the little maggots - var dudeBoundsPadding = 100; - this.dudeBounds = new PIXI.Rectangle(-dudeBoundsPadding, - -dudeBoundsPadding, - this.renderer.width + dudeBoundsPadding * 2, - this.renderer.height + dudeBoundsPadding * 2); - - this.tick = 0; - - // start animating - this.animate(); - - } - - private animate = (): void => { - - // iterate through the dudes and update the positions - for (const dude of this.dudeArray) { - dude.direction += dude.turningSpeed * 0.01; - dude.position.x += Math.sin(dude.direction) * dude.speed; - dude.position.y += Math.cos(dude.direction) * dude.speed; - dude.rotation = -dude.direction - Math.PI / 2; - - // wrap the dudes by testing their bounds... - if (dude.position.x < this.dudeBounds.x) { - dude.position.x += this.dudeBounds.width; - } else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { - dude.position.x -= this.dudeBounds.width; - } - - if (dude.position.y < this.dudeBounds.y) { - dude.position.y += this.dudeBounds.height; - } else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { - dude.position.y -= this.dudeBounds.height; - } - } - - // increment the ticker - this.tick += 0.1; - - // time to render the stage ! - this.renderer.render(this.stage); - - // request another animation frame... - requestAnimationFrame(this.animate); - - } - - } - - export class BlendModesDude extends PIXI.Sprite { - - direction: number; - speed: number; - turningSpeed: number; - offset: number; - - constructor(texture: PIXI.Texture) { - - super(texture); - - } - - } - -} - -namespace demos { - - export class CacheAsBitmap { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private aliens: PIXI.Sprite[]; - - private alienContainer: PIXI.Container; - - private count: number; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - // load resources - PIXI.loader - .add('spritesheet', '../../_assets/monsters.json') - .load(this.onAssetsLoaded); - - // holder to store aliens - this.aliens = []; - - this.count = 0; - - // create an empty container - this.alienContainer = new PIXI.Container(); - this.alienContainer.position.x = 400; - this.alienContainer.position.y = 300; - - // make the stage interactive - this.stage.interactive = true; - - this.stage.addChild(this.alienContainer); - - this.stage.on('click', this.onClick); - this.stage.on('tap', this.onClick); - - } - - private onClick = (event: PIXI.interaction.InteractionEvent): void => { - - this.alienContainer.cacheAsBitmap = !this.alienContainer.cacheAsBitmap; - - // feel free to play with what's below - // var sprite = new PIXI.Sprite(this.alienContainer.generateTexture()); - // this.stage.addChild(sprite); - // sprite.position.x = Math.random() * 800; - // sprite.position.y = Math.random() * 600; - - } - - private onAssetsLoaded = (): void => { - - // add a bunch of aliens with textures from image paths - - var alienFrames = ['eggHead.png', 'flowerTop.png', 'helmlok.png', 'skully.png']; - - for (var i = 0; i < 100; i++) { - - var frameName = alienFrames[i % 4]; - - // create an alien using the frame name.. - var alien = PIXI.Sprite.fromFrame(frameName); - alien.tint = Math.random() * 0xFFFFFF; - - /* - * fun fact for the day :) - * another way of doing the above would be - * var texture = PIXI.Texture.fromFrame(frameName); - * var alien = new PIXI.Sprite(texture); - */ - alien.position.x = Math.random() * 800 - 400; - alien.position.y = Math.random() * 600 - 300; - alien.anchor.x = 0.5; - alien.anchor.y = 0.5; - this.aliens.push(alien); - this.alienContainer.addChild(alien); - - } - - // start animating - this.animate(); - - } - - private animate = (): void => { - - // let's rotate the aliens a little bit - for (var i = 0; i < 100; i++) { - var alien = this.aliens[i]; - alien.rotation += 0.1; - } - - this.count += 0.01; - - this.alienContainer.scale.x = Math.sin(this.count); - this.alienContainer.scale.y = Math.sin(this.count); - - this.alienContainer.rotation += 0.01; - - // render the stage - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); - - } - - } - -} - -namespace demos { - - export class DraggableBunny extends PIXI.Sprite { - - // todo I dont know what event.data is at this time - private data: any; - - private dragging: boolean; - - constructor(texture?: PIXI.Texture) { - - super(texture); - - // enable the bunny to be interactive... this will allow it to respond to mouse and touch events - this.interactive = true; - - // this button mode will mean the hand cursor appears when you roll over the bunny with your mouse - this.buttonMode = true; - - // center the bunny's anchor point - this.anchor.set(0.5); - - // make it a bit bigger, so it's easier to grab - this.scale.set(3); - - // setup events - this - // events for drag start - .on('mousedown', this.onDragStart) - .on('touchstart', this.onDragStart) - // events for drag end - .on('mouseup', this.onDragEnd) - .on('mouseupoutside', this.onDragEnd) - .on('touchend', this.onDragEnd) - .on('touchendoutside', this.onDragEnd) - // events for drag move - .on('mousemove', this.onDragMove) - .on('touchmove', this.onDragMove); - - } - - private onDragStart = (event: PIXI.interaction.InteractionEvent): void => { - - // store a reference to the data - // the reason for this is because of multitouch - // we want to track the movement of this particular touch - this.data = event.data; - this.alpha = 0.5; - this.dragging = true; - - } - - private onDragEnd = (event: PIXI.interaction.InteractionEvent): void => { - - // set interactiondata to null - this.data = null; - this.alpha = 1; - this.dragging = false; - - } - - private onDragMove = (event: PIXI.interaction.InteractionEvent): void => { - - if (this.dragging) { - var newPosition = this.data.getLocalPosition(this.parent); - this.position.x = newPosition.x; - this.position.y = newPosition.y; - } - - } - - } - - export class Dragging { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private texture: PIXI.Texture; - - private data: PIXI.interaction.InteractionData; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - // create a texture from an image - this.texture = PIXI.Texture.fromImage('../../_assets/bunny.png'); - - for (var i = 0; i < 10; i++) { - this.createBunny(Math.floor(Math.random() * 800), Math.floor(Math.random() * 600)); - } - - // start animating - this.animate(); - - } - - private createBunny(x: number, y: number): void { - - // create our little bunny friend.. - var bunny = new DraggableBunny(this.texture); - - // move the sprite to its designated position - bunny.position.x = x; - bunny.position.y = y; - - // add it to the stage - this.stage.addChild(bunny); - - } - - private animate = (): void => { - - requestAnimationFrame(this.animate); - - this.renderer.render(this.stage); - - } - - } - -} - -namespace demos { - - export class GraphicsDemo { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private thing: PIXI.Graphics; - - private graphics: PIXI.Graphics; - - private count: number; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - this.stage.interactive = true; - - this.graphics = new PIXI.Graphics(); - - // set a fill and line style - this.graphics.beginFill(0xFF3300); - this.graphics.lineStyle(10, 0xffd900, 1); - - // draw a shape - this.graphics.moveTo(50, 50); - this.graphics.lineTo(250, 50); - this.graphics.lineTo(100, 100); - this.graphics.lineTo(250, 220); - this.graphics.lineTo(50, 220); - this.graphics.lineTo(50, 50); - this.graphics.endFill(); - - // set a fill and line style again - this.graphics.lineStyle(10, 0xFF0000, 0.8); - this.graphics.beginFill(0xFF700B, 1); - - // draw a second shape - this.graphics.moveTo(210, 300); - this.graphics.lineTo(450, 320); - this.graphics.lineTo(570, 350); - this.graphics.quadraticCurveTo(600, 0, 480, 100); - this.graphics.lineTo(330, 120); - this.graphics.lineTo(410, 200); - this.graphics.lineTo(210, 300); - this.graphics.endFill(); - - // draw a rectangle - this.graphics.lineStyle(2, 0x0000FF, 1); - this.graphics.drawRect(50, 250, 100, 100); - - // draw a circle - this.graphics.lineStyle(0); - this.graphics.beginFill(0xFFFF0B, 0.5); - this.graphics.drawCircle(470, 200, 100); - this.graphics.endFill(); - - this.graphics.lineStyle(20, 0x33FF00); - this.graphics.moveTo(30, 30); - this.graphics.lineTo(600, 300); - - this.stage.addChild(this.graphics); - - // let's create a moving shape - this.thing = new PIXI.Graphics(); - this.stage.addChild(this.thing); - this.thing.position.x = 620 / 2; - this.thing.position.y = 380 / 2; - - this.count = 0; - - // Just click on the stage to draw random lines - this.stage.on('click', this.onClick); - this.stage.on('tap', this.onClick); - - // start animating - this.animate(); - - } - - private onClick = (event: PIXI.interaction.InteractionEvent): void => { - - this.graphics.lineStyle(Math.random() * 30, Math.random() * 0xFFFFFF, 1); - this.graphics.moveTo(Math.random() * 620, Math.random() * 380); - this.graphics.bezierCurveTo(Math.random() * 620, Math.random() * 380, - Math.random() * 620, Math.random() * 380, - Math.random() * 620, Math.random() * 380); - } - - private animate = (): void => { - - this.thing.clear(); - - this.count += 0.1; - - this.thing.clear(); - this.thing.lineStyle(10, 0xff0000, 1); - this.thing.beginFill(0xffFF00, 0.5); - - this.thing.moveTo(-120 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); - this.thing.lineTo(120 + Math.cos(this.count) * 20, -100 + Math.sin(this.count) * 20); - this.thing.lineTo(120 + Math.sin(this.count) * 20, 100 + Math.cos(this.count) * 20); - this.thing.lineTo(-120 + Math.cos(this.count) * 20, 100 + Math.sin(this.count) * 20); - this.thing.lineTo(-120 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); - - this.thing.rotation = this.count * 0.1; - - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); - } - - } - -} - -namespace demos { - - export class Interactivity { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private background: PIXI.Sprite; - - private buttons: InteractivityButton[]; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - // create a background... - this.background = PIXI.Sprite.fromImage('../../_assets/button_test_BG.jpg'); - this.background.width = this.renderer.width; - this.background.height = this.renderer.height; - - // add background to stage... - this.stage.addChild(this.background); - - this.buttons = []; - - var buttonPositions = [ - 175, 75, - 655, 75, - 410, 325, - 150, 465, - 685, 445 - ]; - - function noop(): void { - console.log('click'); - } - - // create some textures from an image path - var textureButton = PIXI.Texture.fromImage('../../_assets/button.png'); - var textureButtonDown = PIXI.Texture.fromImage('../../_assets/buttonDown.png'); - var textureButtonOver = PIXI.Texture.fromImage('../../_assets/buttonOver.png'); - - for (var i = 0; i < 5; i++) { - - var button = new InteractivityButton(textureButton, textureButtonDown, textureButtonOver); - - button.position.x = buttonPositions[i * 2]; - button.position.y = buttonPositions[i * 2 + 1]; - - button.tap = noop; - button.click = noop; - - // add it to the stage - this.stage.addChild(button); - - // add button to array - this.buttons.push(button); - - } - - // set some silly values... - this.buttons[0].scale.set(1.2); - - this.buttons[2].rotation = Math.PI / 10; - - this.buttons[3].scale.set(0.8); - - this.buttons[4].scale.set(0.8, 1.2); - this.buttons[4].rotation = Math.PI; - - // start animating - this.animate(); - - } - - private animate = (): void => { - - requestAnimationFrame(this.animate); - - this.renderer.render(this.stage); - - } - - } - - export class InteractivityButton extends PIXI.Sprite { - - private textureButton: PIXI.Texture; - private textureButtonDown: PIXI.Texture; - private textureButtonOver: PIXI.Texture; - - tap: Function; - click: Function; - - isdown: boolean; - isOver: boolean; - - constructor(textureButton: PIXI.Texture, textureButtonDown: PIXI.Texture, textureButtonOver: PIXI.Texture) { - - super(textureButton); - - // create some textures from an image path - this.textureButton = textureButton; - this.textureButtonDown = textureButtonDown; - this.textureButtonOver = textureButtonOver; - - this.buttonMode = true; - this.anchor.set(0.5); - - // make the button interactive... - this.interactive = true; - - this - // set the mousedown and touchstart callback... - .on('mousedown', this.onButtonDown) - .on('touchstart', this.onButtonDown) - - // set the mouseup and touchend callback... - .on('mouseup', this.onButtonUp) - .on('touchend', this.onButtonUp) - .on('mouseupoutside', this.onButtonUp) - .on('touchendoutside', this.onButtonUp) - - // set the mouseover callback... - .on('mouseover', this.onButtonOver) - - // set the mouseout callback... - .on('mouseout', this.onButtonOut); - - // you can also listen to click and tap events : - // .on('click', this.noop) - - } - - private onButtonDown = (event: PIXI.interaction.InteractionEvent): void => { - - this.isdown = true; - this.texture = this.textureButtonDown; - this.alpha = 1; - - } - - private onButtonUp = (event: PIXI.interaction.InteractionEvent): void => { - - this.isdown = false; - - if (this.isOver) { - this.texture = this.textureButtonOver; - } else { - this.texture = this.textureButton; - } - } - - private onButtonOver = (event: PIXI.interaction.InteractionEvent): void => { - - this.isOver = true; - - if (this.isdown) { - return; - } - - this.texture = this.textureButtonOver; - - } - - private onButtonOut = (event: PIXI.interaction.InteractionEvent): void => { - - this.isOver = false; - - if (this.isdown) { - return; - } - - this.texture = this.textureButton; - } - - } - -} - -namespace demos { - - export class Masking { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private bg: PIXI.Sprite; - - private container: PIXI.Container; - - private bgFront: PIXI.Sprite; - - private light1: PIXI.Sprite; - - private light2: PIXI.Sprite; - - private panda: PIXI.Sprite; - - private thing: PIXI.Graphics; - - private count: number; - - private help: PIXI.Text; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb, antialias: true }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - this.stage.interactive = true; - - this.bg = PIXI.Sprite.fromImage('../../_assets/BGrotate.jpg'); - this.bg.anchor.x = 0.5; - this.bg.anchor.y = 0.5; - - this.bg.position.x = this.renderer.width / 2; - this.bg.position.y = this.renderer.height / 2; - - this.stage.addChild(this.bg); - - this.container = new PIXI.Container(); - this.container.position.x = this.renderer.width / 2; - this.container.position.y = this.renderer.height / 2; - - // add a bunch of sprites - - this.bgFront = PIXI.Sprite.fromImage('../../_assets/SceneRotate.jpg'); - this.bgFront.anchor.x = 0.5; - this.bgFront.anchor.y = 0.5; - - this.container.addChild(this.bgFront); - - this.light2 = PIXI.Sprite.fromImage('../../_assets/LightRotate2.png'); - this.light2.anchor.x = 0.5; - this.light2.anchor.y = 0.5; - this.container.addChild(this.light2); - - this.light1 = PIXI.Sprite.fromImage('../../_assets/LightRotate1.png'); - this.light1.anchor.x = 0.5; - this.light1.anchor.y = 0.5; - this.container.addChild(this.light1); - - this.panda = PIXI.Sprite.fromImage('../../_assets/panda.png'); - this.panda.anchor.x = 0.5; - this.panda.anchor.y = 0.5; - - this.container.addChild(this.panda); - - this.stage.addChild(this.container); - - // let's create a moving shape - this.thing = new PIXI.Graphics(); - this.stage.addChild(this.thing); - this.thing.position.x = this.renderer.width / 2; - this.thing.position.y = this.renderer.height / 2; - this.thing.lineStyle(0); - - this.container.mask = this.thing; - - this.count = 0; - - this.stage.on('click', this.onClick); - this.stage.on('tap', this.onClick); - - this.help = new PIXI.Text('Click to turn masking on / off.', { font: 'bold 12pt Arial', fill: 'white' }); - this.help.position.y = this.renderer.height - 26; - this.help.position.x = 10; - this.stage.addChild(this.help); - - // start animating - this.animate(); - - } - - private animate = (): void => { - - this.bg.rotation += 0.01; - this.bgFront.rotation -= 0.01; - - this.light1.rotation += 0.02; - this.light2.rotation += 0.01; - - this.panda.scale.x = 1 + Math.sin(this.count) * 0.04; - this.panda.scale.y = 1 + Math.cos(this.count) * 0.04; - - this.count += 0.1; - - this.thing.clear(); - - this.thing.beginFill(0x8bc5ff, 0.4); - this.thing.moveTo(-120 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); - this.thing.lineTo(-320 + Math.cos(this.count) * 20, 100 + Math.sin(this.count) * 20); - this.thing.lineTo(120 + Math.cos(this.count) * 20, -100 + Math.sin(this.count) * 20); - this.thing.lineTo(120 + Math.sin(this.count) * 20, 100 + Math.cos(this.count) * 20); - this.thing.lineTo(-120 + Math.cos(this.count) * 20, 100 + Math.sin(this.count) * 20); - this.thing.lineTo(-120 + Math.sin(this.count) * 20, -300 + Math.cos(this.count) * 20); - this.thing.lineTo(-320 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); - this.thing.rotation = this.count * 0.1; - - requestAnimationFrame(this.animate); - - this.renderer.render(this.stage); - - } - - private onClick = (event: PIXI.interaction.InteractionEvent): void => { - - if (!this.container.mask) { - this.container.mask = this.thing; - } else { - this.container.mask = null; - } - } - - } - -} - -namespace demos { - - export class MovieClipDemo { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - PIXI.loader - .add('spritesheet', '../../_assets/mc.json') - .load(this.onAssetsLoaded); - - // start animating - this.animate(); - - } - - private onAssetsLoaded = (loader: PIXI.loaders.Loader): void => { - - // create an array to store the textures - var explosionTextures: PIXI.Texture[] = []; - var i: number; - - for (i = 0; i < 26; i++) { - - var texture = PIXI.Texture.fromFrame('Explosion_Sequence_A ' + (i + 1) + '.png'); - explosionTextures.push(texture); - - } - - for (i = 0; i < 50; i++) { - - // create an explosion MovieClip - var explosion = new PIXI.extras.MovieClip(explosionTextures); - - explosion.position.x = Math.random() * 800; - explosion.position.y = Math.random() * 600; - explosion.anchor.x = 0.5; - explosion.anchor.y = 0.5; - - explosion.rotation = Math.random() * Math.PI; - - explosion.scale.set(0.75 + Math.random() * 0.5); - - explosion.gotoAndPlay(Math.random() * 27); - - this.stage.addChild(explosion); - - } - - // start animating - this.animate(); - } - - private animate = (): void => { - - requestAnimationFrame(this.animate); - - this.renderer.render(this.stage); - - } - - } - -} - -namespace demos { - - export class RenderTextureDemo { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private renderTexture: PIXI.RenderTexture; - private renderTexture2: PIXI.RenderTexture; - private currentTexture: PIXI.RenderTexture; - - private outputSprite: PIXI.Sprite; - private stuffContainer: PIXI.Container; - private items: PIXI.Sprite[]; - - private count: number; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - // create two render textures... these dynamic textures will be used to draw the scene into itself - this.renderTexture = new PIXI.RenderTexture(this.renderer, this.renderer.width, this.renderer.height); - this.renderTexture2 = new PIXI.RenderTexture(this.renderer, this.renderer.width, this.renderer.height); - this.currentTexture = this.renderTexture; - - // create a new sprite that uses the render texture we created above - this.outputSprite = new PIXI.Sprite(this.currentTexture); - - // align the sprite - this.outputSprite.position.x = 400; - this.outputSprite.position.y = 300; - this.outputSprite.anchor.set(0.5); - - // add to stage - this.stage.addChild(this.outputSprite); - - this.stuffContainer = new PIXI.Container(); - - this.stuffContainer.position.x = 400; - this.stuffContainer.position.y = 300; - - this.stage.addChild(this.stuffContainer); - - // create an array of image ids.. - var fruits = [ - '../../_assets/spinObj_01.png', - '../../_assets/spinObj_02.png', - '../../_assets/spinObj_03.png', - '../../_assets/spinObj_04.png', - '../../_assets/spinObj_05.png', - '../../_assets/spinObj_06.png', - '../../_assets/spinObj_07.png', - '../../_assets/spinObj_08.png' - ]; - - // create an array of items - this.items = []; - - // now create some items and randomly position them in the stuff container - for (var i = 0; i < 20; i++) { - - var item = PIXI.Sprite.fromImage(fruits[i % fruits.length]); - item.position.x = Math.random() * 400 - 200; - item.position.y = Math.random() * 400 - 200; - - item.anchor.set(0.5); - - this.stuffContainer.addChild(item); - - this.items.push(item); - - } - - // used for spinning! - this.count = 0; - - // start animating - this.animate(); - - } - - private animate = (): void => { - - for (const item of this.items) { - // rotate each item - item.rotation += 0.1; - } - - this.count += 0.01; - - // swap the buffers ... - var temp = this.renderTexture; - this.renderTexture = this.renderTexture2; - this.renderTexture2 = temp; - - // set the new texture - this.outputSprite.texture = this.renderTexture; - - // twist this up! - this.stuffContainer.rotation -= 0.01; - this.outputSprite.scale.set(1 + Math.sin(this.count) * 0.2); - - // render the stage to the texture - // the 'true' clears the texture before the content is rendered - this.renderTexture2.render(this.stage, null, false); - - // and finally render the stage - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); - - } - - } - -} - -namespace demos { - - export class StripDemo { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private count: number; - - private points: PIXI.Point[]; - - private strip: PIXI.mesh.Rope; - - private snakeContainer: PIXI.Container; - - private ropeLength: number; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - this.count = 0; - - // build a rope! - this.ropeLength = 918 / 20; - - this.points = []; - - for (var i = 0; i < 20; i++) { - this.points.push(new PIXI.Point(i * this.ropeLength, 0)); - } - - this.strip = new PIXI.mesh.Rope(PIXI.Texture.fromImage('../../_assets/snake.png'), this.points); - this.strip.x = -459; - - this.snakeContainer = new PIXI.Container(); - this.snakeContainer.position.x = 400; - this.snakeContainer.position.y = 300; - - this.snakeContainer.scale.set(800 / 1100); - this.stage.addChild(this.snakeContainer); - - this.snakeContainer.addChild(this.strip); - - // start animating - this.animate(); - - } - - private animate = (): void => { - - this.count += 0.1; - - // make the snake - for (var i = 0; i < this.points.length; i++) { - - this.points[i].y = Math.sin((i * 0.5) + this.count) * 30; - - this.points[i].x = i * this.ropeLength + Math.cos((i * 0.3) + this.count) * 20; - - } - - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); - - } - - } - -} - -namespace demos { - - export class TextDemo { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private bitmapFontText: PIXI.extras.BitmapText; - - private background: PIXI.Sprite; - - private textSample: PIXI.Text; - - private spinningText: PIXI.Text; - - private countingText: PIXI.Text; - - private count: number; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - PIXI.loader - .add('desyrel', '../../_assets/desyrel.xml') - .load(this.onAssetsLoaded); - - // start animating - this.animate(); - - } - - private onAssetsLoaded = (): void => { - - this.bitmapFontText = new PIXI.extras.BitmapText('bitmap fonts are\n now supported!', { font: '35px Desyrel', align: 'right' }); - - this.bitmapFontText.position.x = 600 - this.bitmapFontText.textWidth; - this.bitmapFontText.position.y = 20; - - this.stage.addChild(this.bitmapFontText); - - // add a shiny background... - this.background = PIXI.Sprite.fromImage('../../_assets/textDemoBG.jpg'); - this.stage.addChild(this.background); - - // create some white text using the Snippet webfont - this.textSample = new PIXI.Text('Pixi.js can has\n multiline text!', { font: '35px Snippet', fill: 'white', align: 'left' }); - this.textSample.position.set(20); - - // create a text object with a nice stroke - this.spinningText = new PIXI.Text('I\'m fun!', { font: 'bold 60px Arial', fill: '#cc00ff', align: 'center', stroke: '#FFFFFF', strokeThickness: 6 }); - - // setting the anchor point to 0.5 will center align the text... great for spinning! - this.spinningText.anchor.set(0.5); - this.spinningText.position.x = 310; - this.spinningText.position.y = 200; - - // create a text object that will be updated... - this.countingText = new PIXI.Text('COUNT 4EVAR: 0', { font: 'bold italic 60px Arvo', fill: '#3e1707', align: 'center', stroke: '#a4410e', strokeThickness: 7 }); - - this.countingText.position.x = 310; - this.countingText.position.y = 320; - this.countingText.anchor.x = 0.5; - - this.stage.addChild(this.textSample); - this.stage.addChild(this.spinningText); - this.stage.addChild(this.countingText); - - this.count = 0; - - } - - private animate = (): void => { - - - this.renderer.render(this.stage); - - this.count += 0.05; - - // update the text with a new string - this.countingText.text = 'COUNT 4EVAR: ' + Math.floor(this.count); - - // let's spin the spinning text - this.spinningText.rotation += 0.03; - - requestAnimationFrame(this.animate); - } - - } - -} - -namespace demos { - - export class TextureSwap { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private bol: boolean; - - private texture: PIXI.Texture; - private secondTexture: PIXI.Texture; - - private dude: PIXI.Sprite; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - this.bol = false; - - // an image path - this.texture = PIXI.Texture.fromImage('../../_assets/flowerTop.png'); - - // create a second texture - this.secondTexture = PIXI.Texture.fromImage('../../_assets/eggHead.png'); - - // create a new Sprite using the texture - this.dude = new PIXI.Sprite(this.texture); - - // center the sprites anchor point - this.dude.anchor.set(0.5); - - // move the sprite to the center of the screen - this.dude.position.x = this.renderer.width / 2; - this.dude.position.y = this.renderer.height / 2; - - this.stage.addChild(this.dude); - - // make the sprite interactive - this.dude.interactive = true; - - this.dude.on('click', (): void => { - this.bol = !this.bol; - - if (this.bol) { - this.dude.texture = this.secondTexture; - } else { - this.dude.texture = this.texture; - } - }); - - // start animating - this.animate(); - - } - - private animate = (): void => { - - // just for fun, let's rotate mr rabbit a little - this.dude.rotation += 0.1; - - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); - - } - - } - -} - -namespace demos { - - export class Tinting { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private totalDudes: number = 10; - private aliens: TintingDude[]; - - private dudeBounds: PIXI.Rectangle; - - private tick: number; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - // holder to store the aliens - this.aliens = []; - - this.tick = 0; - - for (var i = 0; i < this.totalDudes; i++) { - - // create a new Sprite that uses the image name that we just generated as its source - var dude = new TintingDude(); - - // set the anchor point so the texture is centerd on the sprite - dude.anchor.set(0.5); - - // set a random scale for the dude - no point them all being the same size! - dude.scale.set(0.8 + Math.random() * 0.3); - - // finally lets set the dude to be at a random position.. - dude.position.x = Math.random() * this.renderer.width; - dude.position.y = Math.random() * this.renderer.height; - - dude.tint = Math.random() * 0xFFFFFF; - - // create some extra properties that will control movement : - // create a random direction in radians. This is a number between 0 and PI*2 which is the equivalent of 0 - 360 degrees - dude.direction = Math.random() * Math.PI * 2; - - // this number will be used to modify the direction of the dude over time - dude.turningSpeed = Math.random() - 0.8; - - // create a random speed for the dude between 0 - 2 - dude.speed = 2 + Math.random() * 2; - - // finally we push the dude into the aliens array so it it can be easily accessed later - this.aliens.push(dude); - - this.stage.addChild(dude); - - } - - // create a bounding box for the little dudes - var dudeBoundsPadding = 100; - this.dudeBounds = new PIXI.Rectangle(-dudeBoundsPadding, - -dudeBoundsPadding, - this.renderer.width + dudeBoundsPadding * 2, - this.renderer.height + dudeBoundsPadding * 2); - - // start animating - this.animate(); - - } - - private animate = (): void => { - - // iterate through the dudes and update their position - for (const dude of this.aliens) { - dude.direction += dude.turningSpeed * 0.01; - dude.position.x += Math.sin(dude.direction) * dude.speed; - dude.position.y += Math.cos(dude.direction) * dude.speed; - dude.rotation = -dude.direction - Math.PI / 2; - - // wrap the dudes by testing their bounds... - if (dude.position.x < this.dudeBounds.x) { - dude.position.x += this.dudeBounds.width; - } else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { - dude.position.x -= this.dudeBounds.width; - } - - if (dude.position.y < this.dudeBounds.y) { - dude.position.y += this.dudeBounds.height; - } else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { - dude.position.y -= this.dudeBounds.height; - } - - } - - // increment the ticker - this.tick += 0.1; - - requestAnimationFrame(this.animate); - - this.renderer.render(this.stage); - - } - - } - - export class TintingDude extends PIXI.Sprite { - - direction: number; - speed: number; - turningSpeed: number; - - constructor() { - super(PIXI.Texture.fromImage('../../_assets/eggHead.png')); - } - - } - -} - -namespace demos { - - export class TransparentBackground { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private bunny: PIXI.Sprite; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb, transparent: true }); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - // create a new Sprite from an image path. - this.bunny = PIXI.Sprite.fromImage('../../_assets/bunny.png'); - - // center the sprite's anchor point - this.bunny.anchor.set(0.5); - - // move the sprite to the center of the screen - this.bunny.position.x = 200; - this.bunny.position.y = 150; - - this.stage.addChild(this.bunny); - - // start animating - this.animate(); - - } - - private animate = (): void => { - - // just for fun, let's rotate mr rabbit a little - this.bunny.rotation += 0.1; - - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); - - } - - } - -} - -namespace filters { - - export class Blur { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private bg: PIXI.Sprite; - - private littleDudes: PIXI.Sprite; - private littleRobot: PIXI.Sprite; - - private blurFilter1: PIXI.filters.BlurFilter; - private blurFilter2: PIXI.filters.BlurFilter; - - private count: number; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - - this.bg = PIXI.Sprite.fromImage('../../_assets/depth_blur_BG.jpg'); - this.bg.width = this.renderer.width; - this.bg.height = this.renderer.height; - this.stage.addChild(this.bg); - - this.littleDudes = PIXI.Sprite.fromImage('../../_assets/depth_blur_dudes.jpg'); - this.littleDudes.position.x = (this.renderer.width / 2) - 315; - this.littleDudes.position.y = 200; - this.stage.addChild(this.littleDudes); - - this.littleRobot = PIXI.Sprite.fromImage('../../_assets/depth_blur_moby.jpg'); - this.littleRobot.position.x = (this.renderer.width / 2) - 200; - this.littleRobot.position.y = 100; - this.stage.addChild(this.littleRobot); - - this.blurFilter1 = new PIXI.filters.BlurFilter(); - this.blurFilter2 = new PIXI.filters.BlurFilter(); - - this.littleDudes.filters = [this.blurFilter1]; - this.littleRobot.filters = [this.blurFilter2]; - - this.count = 0; - - // nimate - this.animate(); - - } - - private animate = (): void => { - - this.count += 0.005; - - var blurAmount = Math.cos(this.count); - var blurAmount2 = Math.sin(this.count); - - this.blurFilter1.blur = 20 * (blurAmount); - this.blurFilter2.blur = 20 * (blurAmount2); - - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); - - } - - } - -} - -namespace filters { - - export class DisplacementMap { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private container: PIXI.Container; - - private padding: number; - - private bounds: PIXI.Rectangle; - - private maggots: DisplacementMapDude[]; - - private displacementSprite: PIXI.Sprite; - - private displacementFilter: PIXI.filters.DisplacementFilter; - - private ring: PIXI.Sprite; - - private bg: PIXI.Sprite; - - private count: number; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - this.stage.interactive = true; - - this.container = new PIXI.Container(); - this.stage.addChild(this.container); - - this.padding = 100; - - this.bounds = new PIXI.Rectangle(-this.padding, -this.padding, this.renderer.width + this.padding * 2, this.renderer.height + this.padding * 2); - this.maggots = []; - - for (var i = 0; i < 20; i++) { - - var maggot = new DisplacementMapDude(); - maggot.anchor.set(0.5); - this.container.addChild(maggot); - - maggot.direction = Math.random() * Math.PI * 2; - maggot.speed = 1; - maggot.turnSpeed = Math.random() - 0.8; - - maggot.position.x = Math.random() * this.bounds.width; - maggot.position.y = Math.random() * this.bounds.height; - - maggot.scale.set(1 + Math.random() * 0.3); - maggot.original = maggot.scale.clone(); - this.maggots.push(maggot); - - } - - this.displacementSprite = PIXI.Sprite.fromImage('../../_assets/displace.png'); - this.displacementFilter = new PIXI.filters.DisplacementFilter(this.displacementSprite); - - this.stage.addChild(this.displacementSprite); - - this.container.filters = [this.displacementFilter]; - - this.displacementFilter.scale.x = 110; - this.displacementFilter.scale.y = 110; - - this.ring = PIXI.Sprite.fromImage('../../_assets/ring.png'); - - this.ring.anchor.set(0.5); - - this.ring.visible = false; - - this.stage.addChild(this.ring); - - this.bg = PIXI.Sprite.fromImage('../../_assets/bkg-grass.jpg'); - this.bg.width = this.renderer.width; - this.bg.height = this.renderer.height; - - this.bg.alpha = 0.4; - - this.container.addChild(this.bg); - - this.stage - .on('mousemove', this.onPointerMove) - .on('touchmove', this.onPointerMove); - - this.count = 0; - - this.animate(); - - } - - private onPointerMove = (eventData: PIXI.interaction.InteractionEvent): void => { - - this.ring.visible = true; - - this.displacementSprite.x = eventData.data.global.x - 100; - this.displacementSprite.y = eventData.data.global.y - this.displacementSprite.height / 2; - - this.ring.position.x = eventData.data.global.x - 25; - this.ring.position.y = eventData.data.global.y; - - } - - private animate = (): void => { - - this.count += 0.05; - - for (const maggot of this.maggots) { - maggot.direction += maggot.turnSpeed * 0.01; - maggot.position.x += Math.sin(maggot.direction) * maggot.speed; - maggot.position.y += Math.cos(maggot.direction) * maggot.speed; - - maggot.rotation = -maggot.direction - Math.PI / 2; - - maggot.scale.x = maggot.original.x + Math.sin(this.count) * 0.2; - - // wrap the maggots around as the crawl - if (maggot.position.x < this.bounds.x) { - maggot.position.x += this.bounds.width; - } else if (maggot.position.x > this.bounds.x + this.bounds.width) { - maggot.position.x -= this.bounds.width; - } - - if (maggot.position.y < this.bounds.y) { - maggot.position.y += this.bounds.height; - } else if (maggot.position.y > this.bounds.y + this.bounds.height) { - maggot.position.y -= this.bounds.height; - } - } - - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); - - } - - } - - export class DisplacementMapDude extends PIXI.Sprite { - - direction: number; - speed: number; - turnSpeed: number; - original: PIXI.Point; - - constructor() { - - super(PIXI.Texture.fromImage('../../_assets/maggot.png')); - - } - - } - -} - -namespace filters { - - export class Filter { - - private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - - private stage: PIXI.Container; - - private background: PIXI.Sprite; - - private filter: PIXI.filters.ColorMatrixFilter; - - private container: PIXI.Container; - - private bgFront: PIXI.Sprite; - private light2: PIXI.Sprite; - private light1: PIXI.Sprite; - private panda: PIXI.Sprite; - - private count: number; - private switchy: boolean; - - private help: PIXI.Text; - - constructor() { - - this.renderer = PIXI.autoDetectRenderer(800, 600); - document.body.appendChild(this.renderer.view); - - // create the root of the scene graph - this.stage = new PIXI.Container(); - this.stage.interactive = true; - - // create a texture from an image path - var texture: PIXI.Texture = PIXI.Texture.fromImage("../../_assets/basics/bunny.png"); - - this.background = PIXI.Sprite.fromImage('_assets/BGrotate.jpg'); - this.background.anchor.set(0.5); - - this.background.position.x = this.renderer.width / 2; - this.background.position.y = this.renderer.height / 2; - - this.filter = new PIXI.filters.ColorMatrixFilter(); - - this.container = new PIXI.Container(); - this.container.position.x = this.renderer.width / 2; - this.container.position.y = this.renderer.height / 2; - - this.bgFront = PIXI.Sprite.fromImage('../../_assets/SceneRotate.jpg'); - this.bgFront.anchor.set(0.5); - - this.container.addChild(this.bgFront); - - this.light2 = PIXI.Sprite.fromImage('../../_assets/LightRotate2.png'); - this.light2.anchor.set(0.5); - this.container.addChild(this.light2); - - this.light1 = PIXI.Sprite.fromImage('../../_assets/LightRotate1.png'); - this.light1.anchor.set(0.5); - this.container.addChild(this.light1); - - this.panda = PIXI.Sprite.fromImage('../../_assets/panda.png'); - this.panda.anchor.set(0.5); - - this.container.addChild(this.panda); - - this.stage.addChild(this.container); - - this.stage.filters = [this.filter]; - - this.count = 0; - this.switchy = false; - - this.stage.on('click', this.onClick); - this.stage.on('tap', this.onClick); - - - this.help = new PIXI.Text('Click to turn filters on / off.', { font: 'bold 12pt Arial', fill: 'white' }); - this.help.position.y = this.renderer.height - 25; - this.help.position.x = 10; - - this.stage.addChild(this.help); - - // animate - this.animate(); - - } - - private onClick = (): void => { - - this.switchy = !this.switchy; - - if (!this.switchy) { - this.stage.filters = [this.filter]; - } else { - this.stage.filters = null; - } - - } - - private animate = (): void => { - - this.background.rotation += 0.01; - this.bgFront.rotation -= 0.01; - - this.light1.rotation += 0.02; - this.light2.rotation += 0.01; - - this.panda.scale.x = 1 + Math.sin(this.count) * 0.04; - this.panda.scale.y = 1 + Math.cos(this.count) * 0.04; - - this.count += 0.1; - - var matrix = this.filter.matrix; - - matrix[1] = Math.sin(this.count) * 3; - matrix[2] = Math.cos(this.count); - matrix[3] = Math.cos(this.count) * 1.5; - matrix[4] = Math.sin(this.count / 3) * 2; - matrix[5] = Math.sin(this.count / 2); - matrix[6] = Math.sin(this.count / 4); - - this.renderer.render(this.stage); - - requestAnimationFrame(this.animate); - - } - - } - -} diff --git a/pixi.js/v3/tsconfig.json b/pixi.js/v3/tsconfig.json deleted file mode 100644 index 3fd699ff88..0000000000 --- a/pixi.js/v3/tsconfig.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "baseUrl": "../../", - "typeRoots": [ - "../../" - ], - "types": [], - "paths": { - "pixi.js": [ - "pixi.js/v3" - ] - }, - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "pixi.js-tests.ts" - ] -} \ No newline at end of file diff --git a/pkcs11js/pkcs11js-tests.ts b/pkcs11js/pkcs11js-tests.ts index 52ffd4e8f8..30501be11f 100644 --- a/pkcs11js/pkcs11js-tests.ts +++ b/pkcs11js/pkcs11js-tests.ts @@ -1,5 +1,3 @@ -/// - import * as pkcs11js from "pkcs11js"; const libPath = "C:\\tmp\\rtpkcs11ecp.dll"; diff --git a/pouchdb-find/pouchdb-find-tests.ts b/pouchdb-find/pouchdb-find-tests.ts index 8d677276fc..bebdc58cc1 100644 --- a/pouchdb-find/pouchdb-find-tests.ts +++ b/pouchdb-find/pouchdb-find-tests.ts @@ -1,5 +1,3 @@ -/// - namespace PouchDBFindTests { function testFind() { diff --git a/pouchdb-replication/pouchdb-replication-tests.ts b/pouchdb-replication/pouchdb-replication-tests.ts index 6ff426bd0c..3cb6d6bc17 100644 --- a/pouchdb-replication/pouchdb-replication-tests.ts +++ b/pouchdb-replication/pouchdb-replication-tests.ts @@ -1,5 +1,3 @@ -/// - namespace PouchDBReplicationTests { /** @todo make some real tests */ diff --git a/printf/index.d.ts b/printf/index.d.ts new file mode 100644 index 0000000000..e136eed929 --- /dev/null +++ b/printf/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for printf 0.2 +// Project: https://github.com/adaltas/node-printf +// Definitions by: Aluísio Augusto Silva Gonçalves +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export = printf; +declare function printf(format: string, ...args: any[]): string; +declare function printf(writeStream: NodeJS.WritableStream, format: string, ...args: any[]): void; diff --git a/printf/printf-tests.ts b/printf/printf-tests.ts new file mode 100644 index 0000000000..d116d45f76 --- /dev/null +++ b/printf/printf-tests.ts @@ -0,0 +1,9 @@ +import printf = require("printf"); + +printf('%c', 0x7f).charCodeAt(0); +printf('%2$s: %1$O', {hello: 'Node'}, 'Test'); +printf('%(temperature)s %(crevace)ss', { + temperature: 'Hot', + crevace: 'Pocket', +}); +printf(process.stdout, '%2$s: %1$O', {hello: 'Node'}, 'Test'); diff --git a/printf/tsconfig.json b/printf/tsconfig.json new file mode 100644 index 0000000000..e937977428 --- /dev/null +++ b/printf/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "printf-tests.ts" + ] +} diff --git a/printf/tslint.json b/printf/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/printf/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/proj4/index.d.ts b/proj4/index.d.ts index d59063f51b..ff2b8334de 100644 --- a/proj4/index.d.ts +++ b/proj4/index.d.ts @@ -1,102 +1,67 @@ -// Type definitions for proj4 2.3.15 +// Type definitions for proj4 2.3 // Project: https://github.com/proj4js/proj4js // Definitions by: Denis Carriere // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "proj4" { - const TemplateCoordinates: Array | InterfaceCoordinates; +declare namespace proj4 { + type TemplateCoordinates = number[] | InterfaceCoordinates; interface InterfaceCoordinates { - x: number, - y: number, - z?: number, - m?: number + x: number; + y: number; + z?: number; + m?: number; } interface InterfaceDatum { - datum_type: number - a: number - b: number - es: number - ep2: number + datum_type: number; + a: number; + b: number; + es: number; + ep2: number; } - interface Proj4Static { - forward(coordinates: typeof TemplateCoordinates): Array - inverse(coordinates: typeof TemplateCoordinates): Array + interface Static { + forward(coordinates: TemplateCoordinates): number[]; + inverse(coordinates: TemplateCoordinates): number[]; } interface InterfaceProjection { - datum: string - b: number - rf: number - sphere: number - es: number - e: number - ep2: number - forward(coordinates: typeof TemplateCoordinates): Array - inverse(coordinates: typeof TemplateCoordinates): Array + datum: string; + b: number; + rf: number; + sphere: number; + es: number; + e: number; + ep2: number; + forward(coordinates: TemplateCoordinates): number[]; + inverse(coordinates: TemplateCoordinates): number[]; } - namespace proj4 { - /** - * @name defaultDatum - */ - export const defaultDatum: string; + export const defaultDatum: string; - /** - * @name Proj - */ - export function Proj(srsCode:any, callback?: any): InterfaceProjection; - - /** - * @name WGS84 - */ - export const WGS84: any; + export function Proj(srsCode: any, callback?: any): InterfaceProjection; - /** - * Depecrated v3 - * @name Point - */ - export function Point(x: number, y: number, z?: number): InterfaceCoordinates; - export function Point(coordinates: Array): InterfaceCoordinates; - export function Point(coordinates: InterfaceCoordinates): InterfaceCoordinates; - export function Point(coordinates: string): InterfaceCoordinates; - - /** - * @name toPoint - */ - export function toPoint(array: Array): InterfaceCoordinates; - - /** - * @name defs - */ - export function defs(name: string): any; - export function defs(name: string, projection: string): any; - export function defs(name: Array>): any; - - /** - * @name transform - */ - export function transform(source: InterfaceProjection, dest: InterfaceProjection, point: typeof TemplateCoordinates): any; - - /** - * @name mgrs - */ - export function mgrs(coordinates: Array, accuracy: number): string; - - /** - * @name version - */ - export const version: string; - } + export const WGS84: any; /** - * @name proj4 + * Depecrated v3 */ - function proj4(fromProjection: string): Proj4Static; - function proj4(fromProjection: string, toProjection: string): Proj4Static; - function proj4(fromProjection: string, coordinates: typeof TemplateCoordinates): Array; - function proj4(fromProjection: string, toProjection: string, coordinates: typeof TemplateCoordinates): Array; - export = proj4 + export function Point(x: number, y: number, z?: number): InterfaceCoordinates; + export function Point(coordinates: TemplateCoordinates | string): InterfaceCoordinates; + + export function toPoint(array: number[]): InterfaceCoordinates; + + export function defs(name: string, projection?: string): any; + export function defs(name: string[][]): any; + + export function transform(source: InterfaceProjection, dest: InterfaceProjection, point: TemplateCoordinates): any; + + export function mgrs(coordinates: number[], accuracy: number): string; + + export const version: string; } + +declare function proj4(fromProjection: string, toProjection?: string, coordinates?: proj4.TemplateCoordinates): proj4.Static; +declare function proj4(fromProjection: string, coordinates: proj4.TemplateCoordinates): number[]; +export = proj4; diff --git a/proj4/proj4-tests.ts b/proj4/proj4-tests.ts index 72fa804c6e..2c658b8f24 100644 --- a/proj4/proj4-tests.ts +++ b/proj4/proj4-tests.ts @@ -1,49 +1,49 @@ -import * as proj4 from 'proj4' +import * as proj4 from 'proj4'; /////////////////////////////////////////// // Tests data initialisation /////////////////////////////////////////// -const name = 'WGS84' +const name = 'WGS84'; const epsg = { 4269: '+title=NAD83 (long/lat) +proj=longlat +a=6378137.0 +b=6356752.31414036 +ellps=GRS80 +datum=NAD83 +units=degrees', 4326: '+title=WGS 84 (long/lat) +proj=longlat +ellps=WGS84 +datum=WGS84 +units=degrees', -} -const point1 = [-71, 41] -const point2 = {x: 2, y: 5} -const mgrs = "24XWT783908" +}; +const point1 = [-71, 41]; +const point2 = {x: 2, y: 5}; +const mgrs = "24XWT783908"; /////////////////////////////////////////// // Tests Measurement /////////////////////////////////////////// -proj4(epsg['4269'], epsg['4326'], point1) -proj4(epsg['4269'], point1) -proj4(epsg['4269'], epsg['4326']).forward(point2) -proj4(epsg['4269'], epsg['4326']).inverse(point2) +proj4(epsg['4269'], epsg['4326'], point1); +proj4(epsg['4269'], point1); +proj4(epsg['4269'], epsg['4326']).forward(point2); +proj4(epsg['4269'], epsg['4326']).inverse(point2); /////////////////////////////////// // Named Projections /////////////////////////////////// -proj4.defs('WGS84', epsg['4326']) +proj4.defs('WGS84', epsg['4326']); proj4.defs([ ['EPSG:4326', epsg['4326']], ['EPSG:4269', epsg['4269']] -]) -proj4.defs('urn:x-ogc:def:crs:EPSG:4326', proj4.defs('EPSG:4326')) +]); +proj4.defs('urn:x-ogc:def:crs:EPSG:4326', proj4.defs('EPSG:4326')); /////////////////////////////////// // Utils /////////////////////////////////// // WGS84 -proj4.WGS84 +proj4.WGS84; // Proj -proj4.Proj('WGS84') +proj4.Proj('WGS84'); // toPoint -proj4.toPoint([1, 2]) -proj4.toPoint([1, 2, 3]) -proj4.toPoint([1, 2, 3, 4]) +proj4.toPoint([1, 2]); +proj4.toPoint([1, 2, 3]); +proj4.toPoint([1, 2, 3, 4]); // Point // WARNING: Deprecated in v3 -proj4.Point([1, 2, 3, 4]) \ No newline at end of file +proj4.Point([1, 2, 3, 4]); \ No newline at end of file diff --git a/proj4/tslint.json b/proj4/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/proj4/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/project-oxford/project-oxford-tests.ts b/project-oxford/project-oxford-tests.ts index d04a77a762..ea2849d986 100644 --- a/project-oxford/project-oxford-tests.ts +++ b/project-oxford/project-oxford-tests.ts @@ -1,6 +1,3 @@ - -/// -/// /// import oxford = require("project-oxford"); diff --git a/promised-temp/promised-temp-tests.ts b/promised-temp/promised-temp-tests.ts index 2b77184e25..ec14855d8b 100644 --- a/promised-temp/promised-temp-tests.ts +++ b/promised-temp/promised-temp-tests.ts @@ -1,6 +1,3 @@ - -/// - import * as fs from "fs"; import temp from 'promised-temp'; import { AffixOptions, OpenFile, Stats } from "promised-temp"; @@ -9,8 +6,7 @@ function testCleanup() { temp.cleanup().then((result: boolean | Stats) => { if (typeof result === "boolean") { const x = result === true; - } - else { + } else { const { files, dirs } = result; files.toPrecision(4); } diff --git a/promptly/promptly-tests.ts b/promptly/promptly-tests.ts index 05b8bf70ed..fbd1fd5bb7 100644 --- a/promptly/promptly-tests.ts +++ b/promptly/promptly-tests.ts @@ -1,5 +1,3 @@ -/// - import promptly = require('promptly'); process.stdin diff --git a/prosemirror-collab/index.d.ts b/prosemirror-collab/index.d.ts new file mode 100644 index 0000000000..a04c72ecf8 --- /dev/null +++ b/prosemirror-collab/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for prosemirror-collab 0.18 +// Project: https://github.com/ProseMirror/prosemirror-collab +// Definitions by: David Hahn +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Plugin } from 'prosemirror-state' +import { EditorState } from 'prosemirror-state' +import { Step } from 'prosemirror-transform' +import { Transaction } from 'prosemirror-state' + +declare module "prosemirror-collab" { + export function collab(config?: { version?: number, clientID?: number }): Plugin + export function receiveTransaction(state: EditorState, steps: Step[], clientIDs: number[]): Transaction + export function sendableSteps(state: EditorState): { version: number, steps: Step[], clientID: number, origins: Transaction[] } | void + export function getVersion(state: EditorState): number + +} \ No newline at end of file diff --git a/prosemirror-collab/prosemirror-collab-tests.ts b/prosemirror-collab/prosemirror-collab-tests.ts new file mode 100644 index 0000000000..43071590d6 --- /dev/null +++ b/prosemirror-collab/prosemirror-collab-tests.ts @@ -0,0 +1,5 @@ +import * as collab from 'prosemirror-collab'; +import {EditorState} from 'prosemirror-state'; + +let state = new EditorState(); +let version = collab.getVersion(state); diff --git a/prosemirror-collab/tsconfig.json b/prosemirror-collab/tsconfig.json new file mode 100644 index 0000000000..f3d733cd97 --- /dev/null +++ b/prosemirror-collab/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "prosemirror-collab-tests.ts" + ] +} \ No newline at end of file diff --git a/prosemirror-commands/index.d.ts b/prosemirror-commands/index.d.ts new file mode 100644 index 0000000000..662f43a045 --- /dev/null +++ b/prosemirror-commands/index.d.ts @@ -0,0 +1,35 @@ +// Type definitions for prosemirror-commands 0.18 +// Project: https://github.com/ProseMirror/prosemirror-commands +// Definitions by: David Hahn +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +import { EditorState } from 'prosemirror-state' +import { Transaction } from 'prosemirror-state' +import { EditorView } from 'prosemirror-view' +import { NodeType } from 'prosemirror-model' +import { MarkType } from 'prosemirror-model' +import { ProsemirrorNode } from 'prosemirror-model' + +declare module "prosemirror-commands" { + export function deleteSelection(state: EditorState, dispatch?: (tr: Transaction) => void): boolean + export function joinBackward(state: EditorState, dispatch?: (tr: Transaction) => void, view?: EditorView): boolean + export function joinForward(state: EditorState, dispatch?: (tr: Transaction) => void, view?: EditorView): boolean + export function joinUp(state: EditorState, dispatch?: (tr: Transaction) => void): boolean + export function joinDown(state: EditorState, dispatch?: (tr: Transaction) => void): boolean + export function lift(state: EditorState, dispatch?: (tr: Transaction) => void): boolean + export function newlineInCode(state: EditorState, dispatch?: (tr: Transaction) => void): boolean + export function exitCode(state: EditorState, dispatch?: (tr: Transaction) => void): boolean + export function createParagraphNear(state: EditorState, dispatch?: (tr: Transaction) => void): boolean + export function liftEmptyBlock(state: EditorState, dispatch?: (tr: Transaction) => void): boolean + export function splitBlock(state: EditorState, dispatch?: (tr: Transaction) => void): boolean + export function splitBlockKeepMarks(state: EditorState, dispatch?: (tr: Transaction) => void): boolean + export function selectParentNode(state: EditorState, dispatch?: (tr: Transaction) => void): boolean + export function wrapIn(nodeType: NodeType, attrs?: Object): (state: EditorState, dispatch?: (tr: Transaction) => void) => boolean + export function setBlockType(nodeType: NodeType, attrs?: Object): (state: EditorState, dispatch?: (tr: Transaction) => void) => boolean + export function toggleMark(markType: MarkType, attrs?: Object): (state: EditorState, dispatch?: (tr: Transaction) => void) => boolean + export function autoJoin(command: (state: EditorState, fn?: (tr: Transaction) => void) => boolean, isJoinable: ((before: ProsemirrorNode, after: ProsemirrorNode) => boolean) | string[]): (state: EditorState, fn?: (tr: Transaction) => void) => boolean + export function chainCommands(...commands: ((p1: EditorState, fn?: (tr: Transaction) => void) => boolean)[]): (p1: EditorState, fn?: (tr: Transaction) => void) => boolean + export let baseKeymap: Object; + +} \ No newline at end of file diff --git a/prosemirror-commands/prosemirror-commands-tests.ts b/prosemirror-commands/prosemirror-commands-tests.ts new file mode 100644 index 0000000000..f013a51d79 --- /dev/null +++ b/prosemirror-commands/prosemirror-commands-tests.ts @@ -0,0 +1,5 @@ +import * as commands from 'prosemirror-commands'; +import {EditorState} from 'prosemirror-state'; + +let state = new EditorState(); +commands.deleteSelection(state); diff --git a/prosemirror-commands/tsconfig.json b/prosemirror-commands/tsconfig.json new file mode 100644 index 0000000000..ff55c68fa5 --- /dev/null +++ b/prosemirror-commands/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "prosemirror-commands-tests.ts" + ] +} \ No newline at end of file diff --git a/prosemirror-history/index.d.ts b/prosemirror-history/index.d.ts new file mode 100644 index 0000000000..4eee0f42dc --- /dev/null +++ b/prosemirror-history/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for prosemirror-history 0.18 +// Project: https://github.com/ProseMirror/prosemirror-history +// Definitions by: David Hahn +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Plugin } from 'prosemirror-state' +import { EditorState } from 'prosemirror-state' +import { Transaction } from 'prosemirror-state' + +declare module "prosemirror-history" { + export function history(config?: { depth?: number, newGroupDelay: number, preserveItems?: boolean }): Plugin + export function undo(state: EditorState, dispatch?: (tr: Transaction) => void): boolean + export function redo(state: EditorState, dispatch?: (tr: Transaction) => void): boolean + export function undoDepth(state: EditorState): number + export function redoDepth(state: EditorState): number + +} \ No newline at end of file diff --git a/prosemirror-history/prosemirror-history-tests.ts b/prosemirror-history/prosemirror-history-tests.ts new file mode 100644 index 0000000000..3beccd390b --- /dev/null +++ b/prosemirror-history/prosemirror-history-tests.ts @@ -0,0 +1,5 @@ +import * as history from 'prosemirror-history'; +import {EditorState} from 'prosemirror-state'; + +let state = new EditorState(); +history.undo(state); diff --git a/prosemirror-history/tsconfig.json b/prosemirror-history/tsconfig.json new file mode 100644 index 0000000000..d9410dcf2e --- /dev/null +++ b/prosemirror-history/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "prosemirror-history-tests.ts" + ] +} \ No newline at end of file diff --git a/prosemirror-inputrules/index.d.ts b/prosemirror-inputrules/index.d.ts new file mode 100644 index 0000000000..252ba59b2b --- /dev/null +++ b/prosemirror-inputrules/index.d.ts @@ -0,0 +1,35 @@ +// Type definitions for prosemirror-inputrules 0.18 +// Project: https://github.com/ProseMirror/prosemirror-inputrules +// Definitions by: David Hahn +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +import { EditorState } from 'prosemirror-state' +import { Transaction } from 'prosemirror-state' +import { Plugin } from 'prosemirror-state' +import { NodeType } from 'prosemirror-model' +import { ProsemirrorNode } from 'prosemirror-model' + +declare module "prosemirror-inputrules" { + export class InputRule { + constructor(match: RegExp, handler: string | ((state: EditorState, match: string[], start: number, end: number) => Transaction)) + + } + export function inputRules(config: { rules: InputRule[] }): Plugin + export let emDash: InputRule; + export let ellipsis: InputRule; + export let openDoubleQuote: InputRule; + export let closeDoubleQuote: InputRule; + export let openSingleQuote: InputRule; + export let closeSingleQuote: InputRule; + export let smartQuotes: InputRule[]; + export let allInputRules: InputRule[]; + export function wrappingInputRule(regexp: RegExp, nodeType: NodeType, getAttrs?: Object | ((p: string[]) => Object | void), joinPredicate?: (p1: string[], p2: ProsemirrorNode) => boolean): InputRule + export function textblockTypeInputRule(regexp: RegExp, nodeType: NodeType, getAttrs?: Object | ((p: string[]) => Object | void)): InputRule + export function blockQuoteRule(nodeType: NodeType): InputRule + export function orderedListRule(nodeType: NodeType): InputRule + export function bulletListRule(nodeType: NodeType): InputRule + export function codeBlockRule(nodeType: NodeType): InputRule + export function headingRule(nodeType: NodeType, maxLevel: number): InputRule + +} \ No newline at end of file diff --git a/prosemirror-inputrules/prosemirror-inputrules-tests.ts b/prosemirror-inputrules/prosemirror-inputrules-tests.ts new file mode 100644 index 0000000000..85317eaa4c --- /dev/null +++ b/prosemirror-inputrules/prosemirror-inputrules-tests.ts @@ -0,0 +1,5 @@ +import * as inputrules from 'prosemirror-inputrules'; +import { NodeType } from 'prosemirror-model' + +let nodeType = new NodeType(); +let rule = inputrules.blockQuoteRule(nodeType); diff --git a/prosemirror-inputrules/tsconfig.json b/prosemirror-inputrules/tsconfig.json new file mode 100644 index 0000000000..6c1ea1cab4 --- /dev/null +++ b/prosemirror-inputrules/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "prosemirror-inputrules-tests.ts" + ] +} \ No newline at end of file diff --git a/prosemirror-keymap/index.d.ts b/prosemirror-keymap/index.d.ts new file mode 100644 index 0000000000..8ae14961c5 --- /dev/null +++ b/prosemirror-keymap/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for prosemirror-keymap 0.18 +// Project: https://github.com/ProseMirror/prosemirror-keymap +// Definitions by: David Hahn +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Plugin } from 'prosemirror-state' +import { EditorView } from 'prosemirror-view' + +declare module "prosemirror-keymap" { + export function keymap(bindings: Object): Plugin + export function keydownHandler(bindings: Object): (view: EditorView, event: Event) => boolean + +} \ No newline at end of file diff --git a/prosemirror-keymap/prosemirror-keymap-tests.ts b/prosemirror-keymap/prosemirror-keymap-tests.ts new file mode 100644 index 0000000000..47e5f75633 --- /dev/null +++ b/prosemirror-keymap/prosemirror-keymap-tests.ts @@ -0,0 +1,3 @@ +import * as keymap from 'prosemirror-keymap'; + +keymap.keymap({}); diff --git a/prosemirror-keymap/tsconfig.json b/prosemirror-keymap/tsconfig.json new file mode 100644 index 0000000000..b96daa75b6 --- /dev/null +++ b/prosemirror-keymap/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "prosemirror-keymap-tests.ts" + ] +} \ No newline at end of file diff --git a/prosemirror-menu/index.d.ts b/prosemirror-menu/index.d.ts new file mode 100644 index 0000000000..4d78e8ce62 --- /dev/null +++ b/prosemirror-menu/index.d.ts @@ -0,0 +1,68 @@ +// Type definitions for prosemirror-menu 0.18 +// Project: https://github.com/ProseMirror/prosemirror-menu +// Definitions by: David Hahn +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +import { ProsemirrorNode } from 'prosemirror-model' +import { EditorView } from 'prosemirror-view' +import { EditorState } from 'prosemirror-state' +import { Transaction } from 'prosemirror-state' +import { NodeType } from 'prosemirror-model' +import { EditorProps } from 'prosemirror-view' + +declare module "prosemirror-menu" { + export interface MenuElement { + render(pm: any): Node + + } + export class MenuItem { + constructor(spec: MenuItemSpec) + spec: MenuItemSpec; + render(view: EditorView): Node + + } + export interface MenuItemSpec { + run(p1: EditorState, fn: (p: Transaction) => void, p2: EditorView): void + select?(p: EditorState): boolean + onDeselect?: string; + active?(p: EditorState): boolean + render?(p: EditorView): Node + icon?: Object; + label?: string; + title?: string; + class: string; + css: string; + execEvent: string; + + } + export class Dropdown { + constructor(content: MenuElement[], options?: Object) + render(view: EditorView): Node + + } + export class DropdownSubmenu { + constructor(content: MenuElement[], options?: Object) + render(view: EditorView): Node + + } + export function renderGrouped(view: EditorView, content: MenuElement | MenuElement[][]): DocumentFragment + export let icons: Object; + export let joinUpItem: MenuItem; + export let liftItem: MenuItem; + export let selectParentNodeItem: MenuItem; + export function undoItem(p: Object): MenuItem + export function redoItem(p: Object): MenuItem + export function wrapItem(nodeType: NodeType, options: Object): MenuItem + export function blockTypeItem(nodeType: NodeType, options: Object): MenuItem + export class MenuBarEditorView { + wrapper: Node; + editor: EditorView; + props: EditorProps; + update(props: EditorProps): void + updateState(state: EditorState): void + destroy(): void + + } + +} \ No newline at end of file diff --git a/prosemirror-menu/prosemirror-menu-tests.ts b/prosemirror-menu/prosemirror-menu-tests.ts new file mode 100644 index 0000000000..3cd253c94d --- /dev/null +++ b/prosemirror-menu/prosemirror-menu-tests.ts @@ -0,0 +1,3 @@ +import * as menu from 'prosemirror-menu'; + +let editorView = new menu.MenuBarEditorView(); \ No newline at end of file diff --git a/prosemirror-menu/tsconfig.json b/prosemirror-menu/tsconfig.json new file mode 100644 index 0000000000..567612296f --- /dev/null +++ b/prosemirror-menu/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "prosemirror-menu-tests.ts" + ] +} \ No newline at end of file diff --git a/prosemirror-model/index.d.ts b/prosemirror-model/index.d.ts new file mode 100644 index 0000000000..ff281cb2f9 --- /dev/null +++ b/prosemirror-model/index.d.ts @@ -0,0 +1,266 @@ +// Type definitions for prosemirror-model 0.18 +// Project: https://github.com/ProseMirror/prosemirror-model +// Definitions by: David Hahn +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type OrderedMap = T; + +declare module "prosemirror-model" { + export class ContentMatch { + matchNode(node: ProsemirrorNode): ContentMatch + matchType(type: NodeType, attrs?: Object, marks?: Mark[]): ContentMatch + matchFragment(fragment: Fragment, from?: number, to?: number): ContentMatch | boolean + matchToEnd(fragment: Fragment, start?: number, end?: number): boolean + validEnd(): boolean + fillBefore(after: Fragment, toEnd: boolean, startIndex?: number): Fragment + allowsMark(markType: MarkType): boolean + findWrapping(target: NodeType, targetAttrs?: Object, targetMarks?: Mark[]): { type: NodeType, attrs: Object }[] + findWrappingFor(node: ProsemirrorNode): { type: NodeType, attrs: Object }[] + + } + export class Fragment { + append(other: Fragment): Fragment + cut(from: number, to?: number): Fragment + replaceChild(index: number, node: ProsemirrorNode): Fragment + eq(other: Fragment): boolean + firstChild?: ProsemirrorNode; + lastChild?: ProsemirrorNode; + childCount: number; + child(index: number): ProsemirrorNode + offsetAt(index: number): number + maybeChild(index: number): ProsemirrorNode + forEach(f: (node: ProsemirrorNode, offset: number, index: number) => void): void + findDiffStart(other: Fragment): number + findDiffEnd(other: ProsemirrorNode): { a: number, b: number } | void + toString(): string + toJSON(): Object | void + static fromJSON(schema: Schema, value?: Object): Fragment + static fromArray(array: ProsemirrorNode[]): Fragment + static from(nodes?: Fragment | ProsemirrorNode | ProsemirrorNode[]): Fragment + static empty: Fragment; + + } + export interface ParseRule { + tag?: string; + style?: string; + context?: string; + node?: string; + mark?: string; + priority?: number; + ignore?: boolean; + skip?: boolean; + attrs?: Object; + getAttrs?(p: Node | string): boolean | Object + contentElement?: string; + getContent?(p: Node): Fragment + preserveWhitespace?: boolean; + + } + export class DOMParser { + constructor(schema: Schema, rules: ParseRule[]) + schema: Schema; + rules: ParseRule[]; + parse(dom: Node, options?: { preserveWhitespace?: boolean, findPositions?: { node: Node, offset: number }[], from?: number, to?: number, topNode?: ProsemirrorNode, topStart?: number, context?: ResolvedPos }): ProsemirrorNode + parseSlice(dom: Node, options?: Object): Slice + static schemaRules(schema: Schema): ParseRule[] + static fromSchema(schema: Schema): DOMParser + + } + export class Mark { + type: MarkType; + attrs: Object; + addToSet(set: Mark[]): Mark[] + removeFromSet(set: Mark[]): Mark[] + isInSet(set: Mark[]): boolean + eq(other: Mark): boolean + toJSON(): Object + static fromJSON(schema: Schema, json: Object): Mark + static sameSet(a: Mark[], b: Mark[]): boolean + static setFrom(marks?: Mark | Mark[]): Mark[] + static none: Mark[]; + + } + export class ProsemirrorNode { + type: NodeType; + attrs: Object; + content: Fragment; + marks: Mark[]; + text?: string; + nodeSize: number; + childCount: number; + child(index: number): ProsemirrorNode + maybeChild(index: number): ProsemirrorNode + forEach(f: (node: ProsemirrorNode, offset: number, index: number) => void): void + nodesBetween(from: number |  void, to: number |  void, f: (node: ProsemirrorNode, pos: number, parent: ProsemirrorNode, index: number) => void): void + descendants(f: (node: ProsemirrorNode, pos: number, parent: ProsemirrorNode) => void): void + textContent: string; + textBetween(from: number, to: number, blockSeparator?: string, leafText?: string): string + firstChild?: ProsemirrorNode; + lastChild?: ProsemirrorNode; + eq(other: ProsemirrorNode): boolean + sameMarkup(other: ProsemirrorNode): boolean + hasMarkup(type: NodeType, attrs?: Object, marks?: Mark[]): boolean + copy(content?: Fragment): ProsemirrorNode + mark(marks: Mark[]): ProsemirrorNode + cut(from: number, to?: number): ProsemirrorNode + slice(from: number, to?: number): Slice + replace(from: number, to: number, slice: Slice): ProsemirrorNode + nodeAt(pos: number): ProsemirrorNode + childAfter(pos: number): { node?: ProsemirrorNode, index: number, offset: number } + childBefore(pos: number): { node?: ProsemirrorNode, index: number, offset: number } + resolve(pos: number): ResolvedPos + rangeHasMark(from: number |  void, to: number |  void, type: MarkType): boolean + isBlock: boolean; + isTextblock: boolean; + isInline: boolean; + isText: boolean; + isLeaf: boolean; + isAtom: boolean; + toString(): string + contentMatchAt(index: number): ContentMatch + canReplace(from: number, to: number, replacement?: Fragment, start?: number, end?: number): boolean + canReplaceWith(from: number, to: number, type: NodeType, attrs?: Mark[]): boolean + canAppend(other: ProsemirrorNode): boolean + check(): void + toJSON(): Object + static fromJSON(schema: Schema, json: Object): ProsemirrorNode + + } + export class ReplaceError extends Error { + + } + export class Slice { + constructor(content: Fragment, openLeft: number, openRight: number) + content: Fragment; + openLeft: number; + openRight: number; + size: number; + toJSON(): Object | void + static fromJSON(schema: Schema, json?: Object): Slice + static maxOpen(fragment: Fragment): Slice + static empty: Slice; + + } + export class ResolvedPos { + pos: number; + depth: number; + parentOffset: number; + parent: ProsemirrorNode; + node(depth?: number): ProsemirrorNode + index(depth?: number): number + indexAfter(depth?: number): number + start(depth?: number): number + end(depth?: number): number + before(depth?: number): number + after(depth?: number): number + textOffset: number; + nodeAfter?: ProsemirrorNode; + nodeBefore?: ProsemirrorNode; + marks(after?: boolean): Mark[] + sharedDepth(pos: number): number + blockRange(other?: ResolvedPos, pred?: (p: ProsemirrorNode) => boolean): NodeRange + sameParent(other: ResolvedPos): boolean + + } + export class NodeRange { + $from: ResolvedPos; + $to: ResolvedPos; + depth: number; + start: number; + end: number; + parent: ProsemirrorNode; + startIndex: number; + endIndex: number; + + } + export class NodeType { + name: string; + schema: Schema; + spec: NodeSpec; + isBlock: boolean; + isText: boolean; + isInline: boolean; + isTextblock: boolean; + isLeaf: boolean; + isAtom: boolean; + create(attrs?: Object, content?: Fragment | ProsemirrorNode | ProsemirrorNode[], marks?: Mark[]): ProsemirrorNode + createChecked(attrs?: Object, content?: Fragment | ProsemirrorNode | ProsemirrorNode[], marks?: Mark[]): ProsemirrorNode + createAndFill(attrs?: Object, content?: Fragment | ProsemirrorNode | ProsemirrorNode[], marks?: Mark[]): ProsemirrorNode + validContent(content: Fragment, attrs?: Object): boolean + + } + export class MarkType { + name: string; + schema: Schema; + spec: MarkSpec; + create(attrs?: Object): Mark + removeFromSet(set: Mark[]): Mark[] + isInSet(set: Mark[]): Mark + excludes: MarkType; + + } + export interface SchemaSpec { + nodes: Object | OrderedMap; + marks?: Object | OrderedMap; + topNode?: string; + + } + export interface NodeSpec { + content?: string; + group?: string; + inline?: boolean; + atom?: boolean; + attrs?: Object; + selectable?: boolean; + draggable?: boolean; + code?: boolean; + defining?: boolean; + toDOM?(p: ProsemirrorNode): DOMOutputSpec + parseDOM?: ParseRule[]; + + } + export interface MarkSpec { + attrs?: Object; + inclusiveRight?: boolean; + excludes?: string; + group?: string; + toDOM?(mark: Mark): DOMOutputSpec + parseDOM?: ParseRule[]; + + } + export interface AttributeSpec { + default?: any; + compute?(): any + + } + export class Schema { + constructor(spec: SchemaSpec) + spec: SchemaSpec; + nodes: Object; + marks: Object; + cached: Object; + topNodeType: NodeType; + node(type: string | NodeType, attrs?: Object, content?: Fragment | ProsemirrorNode | ProsemirrorNode[], marks?: Mark[]): ProsemirrorNode + text(text: string, marks?: Mark[]): ProsemirrorNode + mark(type: string | MarkType, attrs?: Object): Mark + nodeFromJSON(json: Object): ProsemirrorNode + markFromJSON(json: Object): Mark + + } + export interface DOMOutputSpec { + + } + export class DOMSerializer { + constructor(nodes: Object, marks: Object) + nodes: Object; + marks: Object; + serializeFragment(fragment: Fragment, options?: Object): DocumentFragment + serializeNode(node: ProsemirrorNode, options?: Object): Node + static renderSpec(doc: Document, structure: DOMOutputSpec): { dom: Node, contentDOM?: Node } + static fromSchema(schema: Schema): DOMSerializer + static nodesFromSchema(schema: Schema): Object + static marksFromSchema(schema: Schema): Object + + } + +} \ No newline at end of file diff --git a/prosemirror-model/prosemirror-model-tests.ts b/prosemirror-model/prosemirror-model-tests.ts new file mode 100644 index 0000000000..1850a259e9 --- /dev/null +++ b/prosemirror-model/prosemirror-model-tests.ts @@ -0,0 +1,3 @@ +import * as model from 'prosemirror-model'; + +let fragment = new model.Fragment(); diff --git a/prosemirror-model/tsconfig.json b/prosemirror-model/tsconfig.json new file mode 100644 index 0000000000..ecd6628430 --- /dev/null +++ b/prosemirror-model/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "prosemirror-model-tests.ts" + ] +} \ No newline at end of file diff --git a/prosemirror-state/index.d.ts b/prosemirror-state/index.d.ts new file mode 100644 index 0000000000..8a71756edb --- /dev/null +++ b/prosemirror-state/index.d.ts @@ -0,0 +1,109 @@ +// Type definitions for prosemirror-state 0.18 +// Project: https://github.com/ProseMirror/prosemirror-state +// Definitions by: David Hahn +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { EditorProps } from 'prosemirror-view' +import { EditorView } from 'prosemirror-view' +import { ResolvedPos } from 'prosemirror-model' +import { ProsemirrorNode } from 'prosemirror-model' +import { Mappable } from 'prosemirror-transform' +import { Mark } from 'prosemirror-model' +import { Schema } from 'prosemirror-model' +import { Transform } from 'prosemirror-transform' +import { Slice } from 'prosemirror-model' +import { MarkType } from 'prosemirror-model' + +declare module "prosemirror-state" { + export type PluginSpec = { props?: EditorProps, state?: StateField, key?: PluginKey, view?(p: EditorView): { update?(view: EditorView, prevState: EditorState): void, destroy?(): void }, filterTransaction?(p1: Transaction, p2: EditorState): boolean, appendTransaction?(transactions: Transaction[], oldState: EditorState, newState: EditorState): Transaction }; + export class Plugin { + constructor(spec: PluginSpec) + props: EditorProps; + spec: Object; + getState(state: EditorState): any + + } + export interface StateField { + init(config: Object, instance: EditorState): T + apply(tr: Transaction, value: T, oldState: EditorState, newState: EditorState): T + toJSON?(value: T): any + fromJSON?(config: Object, value: any, state: EditorState): T + + } + export class PluginKey { + constructor(name?: string) + get(state: EditorState): Plugin + getState(state: EditorState): any + + } + export class Selection { + from: number; + to: number; + $from: ResolvedPos; + $to: ResolvedPos; + empty: boolean; + eq(other: Selection): boolean + map(doc: ProsemirrorNode, mapping: Mappable): Selection + toJSON(): Object + static findFrom($pos: ResolvedPos, dir: number, textOnly?: boolean): Selection + static near($pos: ResolvedPos, bias?: number, textOnly?: boolean): Selection + static atStart(doc: ProsemirrorNode, textOnly?: boolean): Selection + static atEnd(doc: ProsemirrorNode, textOnly?: boolean): Selection + static between($anchor: ResolvedPos, $head: ResolvedPos, bias?: number): Selection + static fromJSON(doc: ProsemirrorNode, json: Object): Selection + + } + export class TextSelection extends Selection { + constructor($anchor: ResolvedPos, $head?: ResolvedPos) + anchor: number; + head: number; + $anchor: ResolvedPos; + $head: ResolvedPos; + static create(doc: ProsemirrorNode, anchor: number, head?: number): TextSelection + + } + export class NodeSelection extends Selection { + constructor($from: ResolvedPos) + node: ProsemirrorNode; + static create(doc: ProsemirrorNode, from: number, p1?: number): TextSelection + static isSelectable(node: ProsemirrorNode): boolean + + } + export class EditorState { + doc: ProsemirrorNode; + selection: Selection; + storedMarks?: Mark[]; + schema: Schema; + plugins: Plugin[]; + apply(tr: Transaction): EditorState + applyTransaction(tr: Transaction): { state: EditorState, transactions: Transaction[] } + tr: Transaction; + reconfigure(config: Object): EditorState + toJSON(pluginFields?: Object): Object + static create(config: Object): EditorState + static fromJSON(config: Object, json: Object, pluginFields?: Object): EditorState + + } + export class Transaction extends Transform { + time: number; + storedMarks?: Mark[]; + selection: Selection; + setSelection(selection: Selection): Transaction + selectionSet: boolean; + setStoredMarks(marks?: Mark[]): Transaction + storedMarksSet: boolean; + setTime(time: number): Transaction + replaceSelection(slice: Slice): Transaction + replaceSelectionWith(node: ProsemirrorNode, inheritMarks?: boolean): Transaction + deleteSelection(): Transaction + insertText(text: string, from?: number, to?: number): Transaction + setMeta(key: string | Plugin | PluginKey, value: any): Transaction + getMeta(key: string | Plugin | PluginKey): any + isGeneric: boolean; + scrollIntoView(): Transaction + addStoredMark(mark: Mark): Transaction + removeStoredMark(mark: Mark | MarkType): Transaction + + } + +} \ No newline at end of file diff --git a/prosemirror-state/prosemirror-state-tests.ts b/prosemirror-state/prosemirror-state-tests.ts new file mode 100644 index 0000000000..9daf2b56c5 --- /dev/null +++ b/prosemirror-state/prosemirror-state-tests.ts @@ -0,0 +1,4 @@ +import * as state from 'prosemirror-state'; + +let spec: state.PluginSpec = {}; +let plugin = new state.Plugin(spec); diff --git a/prosemirror-state/tsconfig.json b/prosemirror-state/tsconfig.json new file mode 100644 index 0000000000..2c704a320a --- /dev/null +++ b/prosemirror-state/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "prosemirror-state-tests.ts" + ] +} \ No newline at end of file diff --git a/prosemirror-transform/index.d.ts b/prosemirror-transform/index.d.ts new file mode 100644 index 0000000000..26c912ccd7 --- /dev/null +++ b/prosemirror-transform/index.d.ts @@ -0,0 +1,120 @@ +// Type definitions for prosemirror-transform 0.18 +// Project: https://github.com/ProseMirror/prosemirror-transform +// Definitions by: David Hahn +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +import { ProsemirrorNode } from 'prosemirror-model' +import { Mark } from 'prosemirror-model' +import { MarkType } from 'prosemirror-model' +import { Slice } from 'prosemirror-model' +import { Fragment } from 'prosemirror-model' +import { NodeRange } from 'prosemirror-model' +import { NodeType } from 'prosemirror-model' +import { Schema } from 'prosemirror-model' + +declare module "prosemirror-transform" { + export interface Mappable { + map(pos: number, assoc?: number): number + mapResult(pos: number, assoc?: number): MapResult + + } + export class MapResult { + pos: number; + deleted: boolean; + + } + export class StepMap { + constructor(ranges: number[]) + mapResult(pos: number, assoc?: number): MapResult + map(pos: number, assoc?: number): number + forEach(f: (oldStart: number, oldEnd: number, newStart: number, newEnd: number) => void): void + invert(): StepMap + + } + export class Mapping { + constructor(maps?: StepMap[]) + maps: StepMap[]; + from: number; + to: number; + slice(from?: number, to?: number): Mapping + appendMap(map: StepMap, mirrors?: number): void + appendMapping(mapping: Mapping): void + appendMappingInverted(mapping: Mapping): void + map(pos: number, assoc?: number): number + mapResult(pos: number, assoc?: number): MapResult + + } + export class Transform { + constructor(doc: ProsemirrorNode) + addMark(from: number, to: number, mark: Mark): Transform + removeMark(from: number, to: number, mark?: Mark | MarkType): Transform + clearMarkup(from: number, to: number): Transform + replaceRange(from: number, to: number, slice: Slice): Transform + replaceRangeWith(from: number, to: number, node: ProsemirrorNode): Transform + deleteRange(from: number, to: number): Transform + delete(from: number, to: number): Transform + replace(from: number, to?: number, slice?: Slice): Transform + replaceWith(from: number, to: number, content: Fragment | ProsemirrorNode | ProsemirrorNode[]): Transform + insert(pos: number, content: Fragment | ProsemirrorNode | ProsemirrorNode[]): Transform + lift(range: NodeRange, target: number): Transform + wrap(range: NodeRange, wrappers: { type: NodeType, attrs?: Object }[]): Transform + setBlockType(from: number, to: number |  void, type: NodeType, attrs?: Object): Transform + setNodeType(pos: number, type?: NodeType, attrs?: Object, marks?: Mark[]): Transform + split(pos: number, depth?: number, typesAfter?: { type: NodeType, attrs?: Object }[]): Transform + join(pos: number, depth?: number, p1?: boolean): Transform + doc: ProsemirrorNode; + steps: Step[]; + docs: ProsemirrorNode[]; + mapping: Mapping; + before: ProsemirrorNode; + step(step: Step): Transform + maybeStep(step: Step): StepResult + docChanged: boolean; + + } + export class AddMarkStep extends Step { + constructor(from: number, to: number, mark: Mark) + + } + export class RemoveMarkStep extends Step { + constructor(from: number, to: number, mark: Mark) + + } + export function replaceStep(doc: ProsemirrorNode, from: number, to?: number, slice?: Slice): Step + export class ReplaceStep extends Step { + constructor(from: number, to: number, slice: Slice, structure?: boolean) + + } + export class ReplaceAroundStep extends Step { + constructor(from: number, to: number, gapFrom: number, gapTo: number, slice: Slice, insert: number, structure?: boolean) + + } + export class Step { + apply(doc: ProsemirrorNode): StepResult + getMap(): StepMap + invert(doc: ProsemirrorNode): Step + map(mapping: Mappable): Step + merge(other: Step): Step + offset(n: number): Step + toJSON(): Object + static fromJSON(schema: Schema, json: Object): Step + static jsonID(id: string, stepClass: Step): void + + } + export class StepResult { + doc?: ProsemirrorNode; + failed?: string; + static ok(doc: ProsemirrorNode): StepResult + static fail(message: string): StepResult + static fromReplace(doc: ProsemirrorNode, from: number, to: number, slice: Slice): StepResult + + } + export function liftTarget(range: NodeRange): number + export function findWrapping(range: NodeRange, nodeType: NodeType, attrs?: Object): { type: NodeType, attrs?: Object }[] + export function canSplit(doc: ProsemirrorNode, pos: number, depth?: { type: NodeType, attrs?: Object }[]): boolean + export function canJoin(doc: ProsemirrorNode, pos: number): boolean + export function joinPoint(doc: ProsemirrorNode, pos: number, dir?: number): number + export function insertPoint(doc: ProsemirrorNode, pos: number, nodeType: NodeType, attrs?: Object): number + +} \ No newline at end of file diff --git a/prosemirror-transform/prosemirror-transform-tests.ts b/prosemirror-transform/prosemirror-transform-tests.ts new file mode 100644 index 0000000000..3db8edbb8d --- /dev/null +++ b/prosemirror-transform/prosemirror-transform-tests.ts @@ -0,0 +1,3 @@ +import * as transform from 'prosemirror-transform'; + +let stepmap = new transform.StepMap([]); diff --git a/prosemirror-transform/tsconfig.json b/prosemirror-transform/tsconfig.json new file mode 100644 index 0000000000..2526e2d213 --- /dev/null +++ b/prosemirror-transform/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "prosemirror-transform-tests.ts" + ] +} \ No newline at end of file diff --git a/prosemirror-view/index.d.ts b/prosemirror-view/index.d.ts new file mode 100644 index 0000000000..7e0fc118e0 --- /dev/null +++ b/prosemirror-view/index.d.ts @@ -0,0 +1,100 @@ +// Type definitions for prosemirror-view 0.18 +// Project: https://github.com/ProseMirror/prosemirror-view +// Definitions by: David Hahn +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +import { ProsemirrorNode } from 'prosemirror-model' +import { Mapping } from 'prosemirror-transform' +import { EditorState } from 'prosemirror-state' +import { Transaction } from 'prosemirror-state' +import { DOMParser } from 'prosemirror-model' +import { Slice } from 'prosemirror-model' +import { DOMSerializer } from 'prosemirror-model' + +declare module "prosemirror-view" { + export class Decoration { + spec: Object; + static widget(pos: number, dom: Node, spec?: { associative?: string, stopEvent?(event: Event): boolean, key?: string }): Decoration + static inline(from: number, to: number, attrs: DecorationAttrs, spec?: { inclusiveLeft?: boolean, inclusiveRight?: boolean }): Decoration + static node(from: number, to: number, attrs: DecorationAttrs, spec?: Object): Decoration + + } + export interface DecorationAttrs { + class?: string; + style?: string; + nodeName?: string; + + } + export class DecorationSet { + find(start?: number, end?: number): Decoration[] + map(mapping: Mapping, doc: ProsemirrorNode, options?: { onRemove?(decorationSpec: Object): void }): DecorationSet + add(doc: ProsemirrorNode, decorations: Decoration[]): DecorationSet + remove(decorations: Decoration[]): DecorationSet + static create(doc: ProsemirrorNode, decorations: Decoration[]): DecorationSet + static empty: DecorationSet; + + } + export class EditorView { + constructor(place: Node | ((p: Node) => void) | { mount: Node } |  void, props: EditorProps) + state: EditorState; + dom: Element; + props: EditorProps; + update(props: EditorProps): void + setProps(props: EditorProps): void + updateState(state: EditorState): void + hasFocus(): boolean + someProp(propName: string, f: (prop: any) => any): any + focus(): void + root: Document | DocumentFragment; + posAtCoords(coords: { left: number, top: number }): { pos: number, inside: number } | void + coordsAtPos(pos: number): { left: number, right: number, top: number, bottom: number } + endOfTextblock(dir: "up" | "down" | "left" | "right" | "forward" | "backward", state?: EditorState): boolean + destroy(): void + dispatch(tr: Transaction): void + + } + export interface EditorProps { + state: EditorState; + dispatchTransaction?(tr: Transaction): void + handleDOMEvents?: Object; + handleKeyDown?(view: EditorView, event: KeyboardEvent): boolean + handleKeyPress?(view: EditorView, event: KeyboardEvent): boolean + handleTextInput?(view: EditorView, from: number, to: number, text: string): boolean + handleClickOn?(view: EditorView, pos: number, node: ProsemirrorNode, nodePos: number, event: MouseEvent, direct: boolean): boolean + handleClick?(view: EditorView, pos: number, event: MouseEvent): boolean + handleDoubleClickOn?(view: EditorView, pos: number, node: ProsemirrorNode, nodePos: number, event: MouseEvent, direct: boolean): boolean + handleDoubleClick?(view: EditorView, pos: number, event: MouseEvent): boolean + handleTripleClickOn?(view: EditorView, pos: number, node: ProsemirrorNode, nodePos: number, event: MouseEvent, direct: boolean): boolean + handleTripleClick?(view: EditorView, pos: number, event: MouseEvent): boolean + handleContextMenu?(view: EditorView, pos: number, event: MouseEvent): boolean + onFocus?(view: EditorView, event: Event): void + onBlur?(view: EditorView, event: Event): void + domParser?: DOMParser; + clipboardParser?: DOMParser; + transformPasted?(p: Slice): Slice + transformPastedHTML?(p: string): string + transformPastedText?(p: string): string + nodeViews?: Object; + clipboardSerializer?: DOMSerializer; + decorations?(p: EditorState): DecorationSet + editable?(p: EditorState): boolean + attributes?: Object | ((p: EditorState) => Object | void); + scrollThreshold?: number; + scrollMargin?: number; + + } + export interface NodeView { + dom?: Node; + contentDOM?: Node; + update?(node: ProsemirrorNode, decorations: Decoration[]): boolean + selectNode?(): void + deselectNode?(): void + setSelection?(anchor: number, head: number, root: Document): void + stopEvent?(event: Event): boolean + ignoreMutation?(p: MutationRecord): boolean + destroy?(): void + + } + +} \ No newline at end of file diff --git a/prosemirror-view/prosemirror-view-tests.ts b/prosemirror-view/prosemirror-view-tests.ts new file mode 100644 index 0000000000..113da070ea --- /dev/null +++ b/prosemirror-view/prosemirror-view-tests.ts @@ -0,0 +1,3 @@ +import * as view from 'prosemirror-view'; + +let decoration = new view.Decoration(); diff --git a/prosemirror-view/tsconfig.json b/prosemirror-view/tsconfig.json new file mode 100644 index 0000000000..25af93cd0b --- /dev/null +++ b/prosemirror-view/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "prosemirror-view-tests.ts" + ] +} \ No newline at end of file diff --git a/protractor-browser-logs/protractor-browser-logs-tests.ts b/protractor-browser-logs/protractor-browser-logs-tests.ts index 8e2e0ac015..75af9eb039 100644 --- a/protractor-browser-logs/protractor-browser-logs-tests.ts +++ b/protractor-browser-logs/protractor-browser-logs-tests.ts @@ -4,7 +4,7 @@ import * as webdriver from 'selenium-webdriver'; import Entry = webdriver.logging.Entry; function colored(entries: Entry[]) { - let colors: any = { INFO: 35 /* magenta */, WARNING: 33 /* yellow */, SEVERE: 31 /* red */}; + const colors: any = { INFO: 35 /* magenta */, WARNING: 33 /* yellow */, SEVERE: 31 /* red */}; entries.forEach((entry: Entry) => { console.log('\u001b[' + (colors[entry.level.name] || 37) + 'm' + [entry.level.name, entry.message].join(': ') + '\u001b[39m'); }); @@ -17,7 +17,7 @@ function testCreateFunction() { } function testLogLevels() { - let logs = browserLogs(browser); + const logs = browserLogs(browser); logs.ignore(logs.ERROR); logs.expect(logs.WARNING); @@ -27,48 +27,48 @@ function testLogLevels() { } function testPredicateFunctions() { - let logs = browserLogs(browser); + const logs = browserLogs(browser); logs.ignore(logs.or(logs.ERROR, logs.WARNING)); logs.expect(logs.and(logs.DEBUG, logs.INFO)); } function testRegExp() { - let logs = browserLogs(browser); + const logs = browserLogs(browser); logs.ignore(/foo/i); logs.expect(new RegExp('/foo/i')); } function testString() { - let logs = browserLogs(browser); + const logs = browserLogs(browser); logs.ignore('foo'); logs.expect('foo'); } function testMatchFunction() { - let logs = browserLogs(browser); - let filter = (entry: Entry) => entry.message === "foo"; + const logs = browserLogs(browser); + const filter = (entry: Entry) => entry.message === "foo"; logs.ignore(filter); logs.expect(filter); } function testReset() { - let logs = browserLogs(browser); + const logs = browserLogs(browser); logs.reset(); } function testLogs() { - let logs = browserLogs(browser); + const logs = browserLogs(browser); - let entries: Entry[] = logs.logs(); + const entries: Entry[] = logs.logs(); } function testVerify() { - let logs = browserLogs(browser); + const logs = browserLogs(browser); logs.verify(); } diff --git a/protractor-helpers/index.d.ts b/protractor-helpers/index.d.ts index 3ab4691778..92215ce4eb 100644 --- a/protractor-helpers/index.d.ts +++ b/protractor-helpers/index.d.ts @@ -2,8 +2,10 @@ // Project: https://github.com/wix/protractor-helpers // Definitions by: John Cant // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// +/// // ElementArrayFinder diff --git a/protractor-helpers/package.json b/protractor-helpers/package.json index 3e6da0a22e..2939ff6d12 100644 --- a/protractor-helpers/package.json +++ b/protractor-helpers/package.json @@ -1,6 +1,6 @@ { "dependencies": { "@types/jasmine": "^2.2.34", - "@types/selenium-webdriver": "~2.44.28" + "@types/selenium-webdriver": "2.44.28" } } diff --git a/protractor-http-mock/index.d.ts b/protractor-http-mock/index.d.ts index 5f9dbcd79a..110883a8d3 100644 --- a/protractor-http-mock/index.d.ts +++ b/protractor-http-mock/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Crevil // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import * as webdriver from 'selenium-webdriver'; declare namespace mock { interface ProtractorHttpMock { diff --git a/protractor-http-mock/tsconfig.json b/protractor-http-mock/tsconfig.json index 1280c748d3..486d3cff30 100644 --- a/protractor-http-mock/tsconfig.json +++ b/protractor-http-mock/tsconfig.json @@ -9,6 +9,9 @@ "strictNullChecks": false, "baseUrl": "../", "types": [], + "paths": { + "selenium-webdriver": ["selenium-webdriver/v2"] + }, "noEmit": true, "forceConsistentCasingInFileNames": true }, diff --git a/pump/tsconfig.json b/pump/tsconfig.json index 80be4c4034..ac0fb7fe1c 100644 --- a/pump/tsconfig.json +++ b/pump/tsconfig.json @@ -19,4 +19,4 @@ "index.d.ts", "pump-tests.ts" ] -} \ No newline at end of file +} diff --git a/qrcode.react/index.d.ts b/qrcode.react/index.d.ts new file mode 100644 index 0000000000..c7a6b85d72 --- /dev/null +++ b/qrcode.react/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for qrcode.react 0.6 +// Project: https://github.com/zpao/qrcode.react +// Definitions by: Mleko +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +declare namespace qrcode { + export interface QRCodeProps { + value: string; + size?: number; + bgColor?: string; + fgColor?: string; + level?: "L"|"M"|"Q"|"H"; + } + + export type QRCode = React.ComponentClass; +} + +declare const qrcode: qrcode.QRCode; +export = qrcode; diff --git a/qrcode.react/qrcode.react-tests.tsx b/qrcode.react/qrcode.react-tests.tsx new file mode 100644 index 0000000000..ffae551b01 --- /dev/null +++ b/qrcode.react/qrcode.react-tests.tsx @@ -0,0 +1,12 @@ +import * as QRCode from "qrcode.react"; +import * as React from "react"; + +const qrcodes = [ + , + , + , + , + , + , + , +]; diff --git a/qrcode.react/tsconfig.json b/qrcode.react/tsconfig.json new file mode 100644 index 0000000000..c9938f0730 --- /dev/null +++ b/qrcode.react/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "qrcode.react-tests.tsx" + ] +} diff --git a/qrcode.react/tslint.json b/qrcode.react/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/qrcode.react/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/query-string/index.d.ts b/query-string/index.d.ts index 9cd6d8df1e..dcc9bfafb5 100644 --- a/query-string/index.d.ts +++ b/query-string/index.d.ts @@ -13,7 +13,7 @@ declare module "query-string" { * Leading ? or # are ignored, so you can pass location.search or location.hash directly. * @param str */ - export function parse(str: string): { [key: string]: string | string[] }; + export function parse(str: string): { [key: string]: string | string[] | null }; /** * Stringify an object into a query string, sorting the keys. diff --git a/query-string/query-string-tests.ts b/query-string/query-string-tests.ts index c39c2f4982..c5ec7b624d 100644 --- a/query-string/query-string-tests.ts +++ b/query-string/query-string-tests.ts @@ -21,7 +21,7 @@ namespace stringify_tests { } namespace parse_tests { - let result: { [key: string]: string | string[] }; + let result: { [key: string]: string | string[] | null }; result = qs.parse('?foo=bar'); result = qs.parse('#foo=bar'); result = qs.parse('&foo=bar&foo=baz'); diff --git a/query-string/tsconfig.json b/query-string/tsconfig.json index c0a4860fb8..3dd890dac3 100644 --- a/query-string/tsconfig.json +++ b/query-string/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/radius/radius-tests.ts b/radius/radius-tests.ts index c3b50db8ec..36e9ea618d 100644 --- a/radius/radius-tests.ts +++ b/radius/radius-tests.ts @@ -1,6 +1,3 @@ - -/// - import radius = require('radius'); var radius_secret: string = "shhhh" diff --git a/ramda/index.d.ts b/ramda/index.d.ts index 114ba38d6d..3e79c3cd4c 100644 --- a/ramda/index.d.ts +++ b/ramda/index.d.ts @@ -185,8 +185,8 @@ declare namespace R { * Returns a new list, composed of n-tuples of consecutive elements If n is greater than the length of the list, * an empty list is returned. */ - aperture(n: number, list: T): T[][]; - aperture(n: number): (list: T) => T[][]; + aperture(n: number, list: T[]): T[][]; + aperture(n: number): (list: T[]) => T[][]; /** * Returns a new list containing the contents of the given list, followed by the given element. diff --git a/rangyinputs/rangyinputs-tests.ts b/rangyinputs/rangyinputs-tests.ts index cb627d85b1..14f769a9fe 100644 --- a/rangyinputs/rangyinputs-tests.ts +++ b/rangyinputs/rangyinputs-tests.ts @@ -1,5 +1,3 @@ -/// - let $obj: JQuery = $('meh'); let selection: RangyInputs.Selection = $obj.getSelection(); diff --git a/raty/raty-tests.ts b/raty/raty-tests.ts index bb2f731038..51b510b0a3 100644 --- a/raty/raty-tests.ts +++ b/raty/raty-tests.ts @@ -1,7 +1,3 @@ -/// - - - var $element: JQuery = $('
              '); $element.raty(); diff --git a/raven-js/index.d.ts b/raven-js/index.d.ts deleted file mode 100644 index 7b54ec7372..0000000000 --- a/raven-js/index.d.ts +++ /dev/null @@ -1,338 +0,0 @@ -// Type definitions for Raven.js -// Project: https://github.com/getsentry/raven-js -// Definitions by: Santi Albo , Benjamin Pannell , Gary Blackwood , Rich Rout , Ben Vinegar , Ilya Pirogov , Eli White , David Cramer , Connor Peet , comaz , Luca Vazzano -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -declare let Raven: RavenStatic; -export default Raven; - -interface RavenStatic { - /** Raven.js version. */ - VERSION: string; - - /** A list of currently active plugins. */ - Plugins: { [id: string]: RavenPlugin }; - - /** - * Allow Raven to be configured as soon as it is loaded. - * It uses a global RavenConfig = {dsn: '...', config: {}} - */ - afterLoad(): void; - - /** - * Allow multiple versions of Raven to be installed. - * Strip Raven from the global context and returns the instance. - */ - noConflict(): RavenStatic; - - /** - * Configure Raven with a DSN and extra options - * - * @param dsn The public Sentry DSN - * @param options Optional set of of global options - */ - config(dsn: string, options?: RavenGlobalOptions): RavenStatic; - - /** - * Set the DSN (can be called multiple times, unlike config) - * - * @param dsn The public Sentry DSN - */ - setDSN(dsn: string): RavenStatic; - - /** - * Installs a global window.onerror error handler to capture and report uncaught exceptions. - * At this point, install() is required to be called due to the way TraceKit is set up. - */ - install(): RavenStatic; - - /** - * Adds a plugin to Raven - */ - addPlugin(plugin: RavenPlugin, ...pluginArgs: any[]): RavenStatic; - - /** - * Wrap code within a context so Raven can capture errors reliably across domains that is - * executed immediately. - * - * @param options A specific set of options for this context - * @param func The callback to be immediately executed within the context - * @param args An array of arguments to be called with the callback - */ - context(func: Function, ...args: any[]): void; - context(options: RavenWrapOptions, func: Function, ...args: any[]): void; - - /** - * Wrap code within a context and returns back a new function to be executed - * - * @param options A specific set of options for this context - * @param func The function to be wrapped in a new context - * @return The newly wrapped functions with a context - */ - wrap(func: Function): Function; - wrap(options: RavenWrapOptions, func: Function): Function; - wrap(func: T): T; - wrap(options: RavenWrapOptions, func: T): T; - - /** - * Uninstalls the global error handler. - */ - uninstall(): RavenStatic; - - /** - * Manually capture an exception and send it over to Sentry - * - * @param ex An exception to be logged - * @param options A specific set of options for this error - */ - captureException(ex: Error, options?: RavenOptions): RavenStatic; - - /* - * Manually send a message to Sentry - * - * @param msg A plain message to be captured in Sentry - * @param options A specific set of options for this message - */ - captureMessage(msg: string, options?: RavenOptions): RavenStatic; - - /** - * Add a breadcrumb - * @param crumb The trail which should be added to the trail - */ - captureBreadcrumb(crumb: RavenBreadcrumb): RavenStatic; - - /** - * Set a user to be sent along with payloads. - * - * @param user The definition of the currently active user's unique identity - */ - setUserContext(user: RavenUserContext): RavenStatic; - - /** - * Clear the user context, removing the user data that would be sent to Sentry. - */ - setUserContext(): RavenStatic; - - /** - * Add arbitrary data to be sent along with the payload. - * @param extra data of an arbitrary, nested type which will be added - */ - setExtraContext(extra: { [prop: string]: any }): RavenStatic; - - /** - * Add additional tags to be sent along with payloads. - * @param tags A key/value-pair which will be added - */ - setTagsContext(tags: { [id: string]: string }): RavenStatic; - - /** - * Clear the whole currently set context. - */ - clearContext(): RavenStatic; - - /** - * Get a copy of the current context. - */ - getContext(): Object; - - /** - * Set environment of application - * @param environment Typically something like 'production' - */ - setEnvironment(environment: string): RavenStatic; - - /** - * Set release version of application - * @param release Typically something like a git SHA to identify the current version - */ - setRelease(release: string): RavenStatic; - - /** - * Specify a function that can mutate the payload right before it is being sent to Sentry. - * @param callback The function which can mutate the data - */ - setDataCallback(callback: (data: any, orig?: string) => any): RavenStatic; - - /** - * Specify a callback function that can mutate or filter breadcrumbs when they are captured. - * @param callback The function which applies the filter - */ - setBreadcrumbCallback(callback :(data: any, orig?: string) => any): RavenStatic; - - /** - * Specify a callback function that determines if the given message should be sent to Sentry. - * @param callback The function which determines if the given blob should be sent - */ - setShouldSendCallback(callback: (data: any, orig?: string) => boolean): RavenStatic; - - /** - * Override the default HTTP data transport handler. - * @param transport The function which will be invoked to handle the data transmission - */ - setTransport(transport: (options: RavenTransportOptions) => void): RavenStatic; - - /** - * Get the latest raw exception that was captured by Raven. - */ - lastException(): Error; - - /** - * Get the ID of the last Event captured by Raven. - */ - lastEventId(): string; - - /** - * Determine if Raven is setup and ready to go. - */ - isSetup(): boolean; - - /** - * Show the User Feedback Dialog of Sentry - * @param RavenReportDialogOptions Optional Options to set for the User Feedback - */ - showReportDialog(options?: RavenReportDialogOptions): void; -} - - -// --- Helper Interfaces for Options -------------- -export interface RavenBreadcrumOptions { - /** Whether to collect XHR calls, defaults to true */ - xhr?: boolean; - - /** Whether to collect console logs, defaults to true */ - console?: boolean; - - /** Whether to collect dom events, defaults to true */ - dom?: boolean; - - /** Whether to record window location and navigation, defaults to true */ - location?: boolean; -} - -export interface CommonRavenOptions { - /** The environment of the application you are monitoring with Sentry */ - environment?: string; - - /** The release version of the application you are monitoring with Sentry */ - release?: string; - - /** Additional key/value-data to be tagged onto the error. */ - tags?: { [id: string]: string }; - - /** Additional, arbitrary metadata to collect */ - extra?: { [prop: string]: any }; - - /** The name of the logger used by Sentry. Default: javascript */ - logger?: string; - - /** set to true to get the strack trace of your message */ - stacktrace?: boolean; -} - -export interface RavenOptions extends CommonRavenOptions { - /** The name of the server or device that the client is running on */ - server_name?: string; - - /** The log level associated with this event. Default: error */ - level?: string; - - /** In some cases you may see issues where Sentry groups multiple events together when they - * should be separate entities. In other cases, Sentry simply doesn’t group events together - * because they’re so sporadic that they never look the same. */ - fingerprint?: string[]; - - /** Number of frames to trim off the stacktrace. Default: 1 */ - trimHeadFrames?: number; - - /** The name of the device platform. Default: "javascript" */ - platform?: string; -} - -export interface RavenGlobalOptions extends CommonRavenOptions { - /** The name of the server or device that the client is running on */ - serverName?: string; - - /** Configures which breadcrumbs are collected automatically */ - autoBreadcrumbs?: boolean | RavenBreadcrumOptions; - - /** Whether to collect errors on the window via TraceKit.collectWindowErrors. Default: true. */ - collectWindowErrors?: boolean; - - /** Max number of breadcrumbs to collect. Default: 100 */ - maxBreadcrumbs?: number; - - /** Exclude messages which match one of the given RegEx-Patterns from being sent to Sentry. */ - ignoreErrors?: (RegExp | string)[]; - - /** Exclude messages which come from whole urls matching one of the given RegEx patterns. */ - ignoreUrls?: (RegExp | string)[]; - - /** Only report messages which come from whole urls matching one of the given RegEx patterns. */ - whitelistUrls?: (RegExp | string)[]; - - /** An array of RegEx patterns to indicate which urls are a part of your app. */ - includePaths?: (RegExp | string)[]; - - /** Maximum amount of stack frames to collect. Default: Infinity */ - stackTraceLimit?: number; - - /** Override the default HTTP data transport handler. */ - transport?: (options: RavenTransportOptions) => void; - - /** Limit the maxium length of a message to this number of characters. Default: Infinity */ - maxMessageLength?: number; - - /** Allows you to apply your own filters to determine if the message should be sent to Sentry. */ - shouldSendCallback?: (data: any) => boolean; - - /** A function which allows mutation of the data payload right before being sent to Sentry */ - dataCallback?: (data: any) => any; -} - -export interface RavenWrapOptions extends RavenOptions { - /** Whether to run the wrap recursively. Default: false. */ - deep?: boolean; -} - -export interface RavenTransportOptions { - url: string; - data: any; - auth: { - sentry_version: string; - sentry_client: string; - sentry_key: string; - }; - onSuccess: () => void; - onFailure: () => void; -} - -export interface RavenReportDialogOptions { - eventId?: number, - dsn?: string, - user?: { - name?: string, - email?: string - } -} - - -// --- Helper Interfaces for complex Data Structures -------------- -export interface RavenPlugin { - (raven: RavenStatic, ...args: any[]): RavenStatic; -} - -export interface RavenUserContext { - id?: string; - username?: string; - email?: string; - ip_address?: string; - extra?: { [prop: string]: any }; -} - -export interface RavenBreadcrumb { - message: string; - data: { [id: string]: string }; - category: string; - level: string; -} diff --git a/raven-js/raven-js-tests.ts b/raven-js/raven-js-tests.ts deleted file mode 100644 index bbd3285e1e..0000000000 --- a/raven-js/raven-js-tests.ts +++ /dev/null @@ -1,61 +0,0 @@ -import RavenJS from 'raven-js'; - -RavenJS.config('https://public@getsentry.com/1').install(); - - -RavenJS.config( - 'https://public@getsentry.com/1', - { - logger: 'my-logger', - ignoreUrls: [ - /graph\.facebook\.com/i - ], - ignoreErrors: [ - 'fb_xd_fragment' - ], - includePaths: [ - /https?:\/\/(www\.)?getsentry\.com/, - /https?:\/\/d3nslu0hdya83q\.cloudfront\.net/ - ] - } -).install(); - -var throwsError = () => { - throw new Error('broken'); -}; - -try { - throwsError(); -} catch(e) { - RavenJS.captureException(e); - RavenJS.captureException(e, {tags: { key: "value" }}); -} - -RavenJS.context(throwsError); -RavenJS.context({tags: { key: "value" }}, throwsError); -RavenJS.context({extra: {planet: {name: 'Earth'}}}, throwsError); - -setTimeout(RavenJS.wrap(throwsError), 1000); -RavenJS.wrap({logger: "my.module"}, throwsError)(); -RavenJS.wrap({tags: {git_commit: 'c0deb10c4'}}, throwsError)(); - -RavenJS.setUserContext({ - email: 'matt@example.com', - id: '123' -}); - -RavenJS.captureMessage('Broken!'); -RavenJS.captureMessage('Broken!', {tags: { key: "value" }}); - -RavenJS.showReportDialog({ - eventId: 0815, - dsn:'1337asdf', - user: { - name: 'DefenitelyTyped', - email: 'df@ts.ms' - } -}); - -RavenJS.setTagsContext({ key: "value" }); - -RavenJS.setExtraContext({ foo: "bar" }); diff --git a/rc-select/rc-select-tests.ts b/rc-select/rc-select-tests.ts index f2ec85ae09..976d789c2c 100644 --- a/rc-select/rc-select-tests.ts +++ b/rc-select/rc-select-tests.ts @@ -1,10 +1,7 @@ - -/// - import React = require('react'); import RcSelect = require('rc-select'); -class Component extends React.Component { +class Component extends React.Component { private onChange(value: any) { console.log('selected', value); @@ -54,7 +51,7 @@ class Component extends React.Component { className: "option", disabled: true, key: "option-0", - value: "option-0" + value: "option-0" }; private createOptions(count: number) { @@ -75,7 +72,7 @@ class Component extends React.Component { let options = this.createOptions(10); - let optionGroup = React.createElement(RcSelect.OptGroup, this.defaultOptGroupProps, options); + let optionGroup = React.createElement(RcSelect.OptGroup, this.defaultOptGroupProps, options); let select = React.createElement(RcSelect.default, this.defaultSelectProps, optionGroup); diff --git a/rc-slider/README.md b/rc-slider/README.md new file mode 100644 index 0000000000..7000e34358 --- /dev/null +++ b/rc-slider/README.md @@ -0,0 +1,13 @@ +# Installation +> `npm install --save @types/rc-select` + +# Summary +This package contains type definitions for rc-slider (https://github.com/react-component/slider). + +Additional Details + * Last updated: Tue, 24 Feb 2017 + * Dependencies: react + * Global values: none + +# Credits +These definitions were written by Marcinkus Mantas diff --git a/rc-slider/index.d.ts b/rc-slider/index.d.ts new file mode 100644 index 0000000000..704412eda6 --- /dev/null +++ b/rc-slider/index.d.ts @@ -0,0 +1,156 @@ +// Type definitions for rc-slider 6.1 +// Project: https://github.com/react-component/slider +// Definitions by: Marcinkus Mantas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +import * as React from 'react'; + +declare namespace RcSliderClass { + export interface Marks { + [number: number]: JSX.Element | string | { style: any, label: string | JSX.Element }; + } + + export interface CommonApiProps { + /** + * Additional CSS class for the root DOM node + * @default '' + */ + className?: string; + /** + * The minimum value of the slider + * @default 0 + */ + min?: number; + /** + * The maximum value of the slider + * @default 100 + */ + max?: number; + /** + * Marks on the slider. The key determines the position, and the value determines what will show. + * If you want to set the style of a specific mark point, the value should be an object which contains style and label properties. + * @default '{}' | {number: { style, label }} + */ + marks?: Marks; + /** + * Value to be added or subtracted on each step the slider makes. Must be greater than zero, and max - min should be evenly divisible by the step value. + * @default 1 + */ + step?: number; + /** + * If vertical is true, the slider will be vertical. + * @default false + */ + vertical?: boolean; + /** + * A handle generator which could be used to customized handle. + */ + handle?(props: any): React.ReactNode; + /** + * If the value is true, it means a continuous value interval, otherwise, it is a independent value. + * @default true + */ + included?: boolean; + /** + * If true, handles can't be moved. + * @default false + */ + disabled?: boolean; + /** + * When the step value is greater than 1, you can set the dots to true if you want to render the slider with dots. + * @default false + */ + dots?: boolean; + /** + * onBeforeChange will be triggered when ontouchstart or onmousedown is triggered. + */ + onBeforeChange?: (value: any) => any | undefined; + /** + * onChange will be triggered while the value of Slider changing. + */ + onChange?: (value: any) => any | undefined; + /** + * onAfterChange will be triggered when ontouchend or onmouseup is triggered. + */ + onAfterChange?: (value: any) => any | undefined; + + /** + * @deprecated in version ^6.0.0. Use rc-tooltip + * Tooltip transition class name + */ + tipTransitionName?: string; + + /** + * @deprecated in version ^6.0.0. Use rc-tooltip + * Tooltip formatter + */ + tipFormatter?: ((value: any) => any | undefined) | null; + } + + interface SliderProps extends CommonApiProps { + /** + * Set initial value of slider. + * @default 0 + */ + defaultValue?: number; + /** + * Set current value of slider. + */ + value?: number; + } + + + export interface RangeProps extends CommonApiProps { + /** + * Set initial positions of handles. + * @default [0,0] + */ + defaultValue?: number[]; + /** + * Set current positions of handles. + */ + value?: number[]; + /** + * Determine how many ranges to render, and multiple handles will be rendered (number + 1). + * @default 1 + */ + count?: number; + /** + * allowCross could be set as true to allow those handles to cross. + * @default true + */ + allowCross?: boolean; + /** + * pushable could be set as true to allow pushing of surrounding handles when moving an handle. When set to a number, the number will be the minimum ensured distance between handles. + * @default true + */ + pushable?: boolean; + } + + export interface HandleProps extends CommonApiProps { + /** + * Class name + */ + className: string; + /** + * Styling if true, then bottom: {offset} else left: {offset} + * @default False + */ + vertical: boolean; + /** + * Styling option offset + */ + offset: number; + } +} + +declare class RcSliderClass extends React.Component { } + +declare namespace RcSliderClass { + class Range extends React.Component { } + class Handle extends React.Component { } +} + + +export = RcSliderClass; diff --git a/rc-slider/rc-slider-tests.tsx b/rc-slider/rc-slider-tests.tsx new file mode 100644 index 0000000000..f6e2442558 --- /dev/null +++ b/rc-slider/rc-slider-tests.tsx @@ -0,0 +1,48 @@ +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import * as Slider from 'rc-slider'; +import { Range, Handle } from 'rc-slider'; + +ReactDOM.render( + , + document.querySelector('.app') +); + +ReactDOM.render( + , + document.querySelector('.another-app') +); +ReactDOM.render( + { return }} + included={true} + disabled={false} + dots={true} + onBeforeChange={() => { }} + onChange={() => { }} + onAfterChange={() => { }} + defaultValue={0.1} + value={0.1} + />, + document.querySelector('.another-app') +); + +ReactDOM.render( + , + document.querySelector('.app') +); \ No newline at end of file diff --git a/rc-slider/tsconfig.json b/rc-slider/tsconfig.json new file mode 100644 index 0000000000..d6a3a4e288 --- /dev/null +++ b/rc-slider/tsconfig.json @@ -0,0 +1,24 @@ + { + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "rc-slider-tests.tsx" + ] +} \ No newline at end of file diff --git a/rc-slider/tslint.json b/rc-slider/tslint.json new file mode 100644 index 0000000000..fdc7cdc370 --- /dev/null +++ b/rc-slider/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} \ No newline at end of file diff --git a/react-autosuggest/index.d.ts b/react-autosuggest/index.d.ts index d0d6bec839..7199fefcdb 100644 --- a/react-autosuggest/index.d.ts +++ b/react-autosuggest/index.d.ts @@ -1,11 +1,16 @@ -// Type definitions for react-autosuggest 7.0 +// Type definitions for react-autosuggest 8.0 // Project: http://react-autosuggest.js.org/ -// Definitions by: Nicolas Schmitt , Philip Ottesen , Robert Essig +// Definitions by: Nicolas Schmitt , Philip Ottesen , Robert Essig , Terry Bayne // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -import * as React from 'react'; +import * as React from 'react'; +declare class Autosuggest extends React.Component {} + +export = Autosuggest; + +declare namespace Autosuggest { interface SuggestionsFetchRequest { value: string; reason: string; @@ -31,7 +36,7 @@ import * as React from 'react'; onBlur?: (event: React.FormEvent, params?: BlurEvent) => void; } - export interface SuggestionSelectedEventData { + export interface SuggestionSelectedEventData { method: 'click' | 'enter'; sectionIndex: number | null; suggestion: TSuggestion; @@ -71,4 +76,4 @@ import * as React from 'react'; id?: string; } - export class Autosuggest extends React.Component {} +} diff --git a/react-autosuggest/react-autosuggest-tests.tsx b/react-autosuggest/react-autosuggest-tests.tsx index 3eaee3e4e7..f5ecaedc63 100644 --- a/react-autosuggest/react-autosuggest-tests.tsx +++ b/react-autosuggest/react-autosuggest-tests.tsx @@ -1,42 +1,69 @@ // region Imports import React = require('react'); import ReactDOM = require('react-dom'); -import { Autosuggest, SuggestionSelectedEventData } from 'react-autosuggest'; +import Autosuggest = require('react-autosuggest'); // endregion interface Language { - name: string; - year: number; + name : string; + year : number; } -// https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions#Using_Special_Characters -function escapeRegexCharacters(str: string): string { +// https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expression +// s#Using_Special_Characters +function escapeRegexCharacters(str : string) : string { return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } export class ReactAutosuggestBasicTest extends React.Component { // region Fields - static languages: Language[] = [ - {name: 'C', year: 1972}, - {name: 'C#', year: 2000}, - {name: 'C++', year: 1983}, - {name: 'Clojure', year: 2007}, - {name: 'Elm', year: 2012}, - {name: 'Go', year: 2009}, - {name: 'Haskell', year: 1990}, - {name: 'Java', year: 1995}, - {name: 'Javascript', year: 1995}, - {name: 'Perl', year: 1987}, - {name: 'PHP', year: 1995}, - {name: 'Python', year: 1991}, - {name: 'Ruby', year: 1995}, - {name: 'Scala', year: 2003} + static languages : Language[] = [ + { + name: 'C', + year: 1972 + }, { + name: 'C#', + year: 2000 + }, { + name: 'C++', + year: 1983 + }, { + name: 'Clojure', + year: 2007 + }, { + name: 'Elm', + year: 2012 + }, { + name: 'Go', + year: 2009 + }, { + name: 'Haskell', + year: 1990 + }, { + name: 'Java', + year: 1995 + }, { + name: 'Javascript', + year: 1995 + }, { + name: 'Perl', + year: 1987 + }, { + name: 'PHP', + year: 1995 + }, { + name: 'Python', + year: 1991 + }, { + name: 'Ruby', + year: 1995 + }, { + name: 'Scala', + year: 2003 + } ]; - // endregion - - - // region Constructor - constructor(props: any) { + // endregion region Constructor + constructor(props : any) { super(props); this.state = { @@ -44,15 +71,15 @@ export class ReactAutosuggestBasicTest extends React.Component { suggestions: this.getSuggestions('') }; } - // endregion - - // region Rendering methods - render(): JSX.Element { + // endregion region Rendering methods + render() : JSX.Element { const {value, suggestions} = this.state; const inputProps = { placeholder: `Type 'c'`, value, - onChange: this.onChange.bind(this) + onChange: this + .onChange + .bind(this) }; const theme = { @@ -61,42 +88,38 @@ export class ReactAutosuggestBasicTest extends React.Component { suggestionFocused: 'active' }; - return ; + return ; } - protected onSuggestionsSelected(event: React.FormEvent, data: SuggestionSelectedEventData): void { + protected onSuggestionsSelected(event : React.FormEvent, data : Autosuggest.SuggestionSelectedEventData) : void { alert(`Selected language is ${data.suggestion.name} (${data.suggestion.year}).`); } - protected renderSuggestion(suggestion: Language): JSX.Element { + protected renderSuggestion(suggestion : Language) : JSX.Element { return {suggestion.name}; } - // endregion - - // region Event handlers - protected onChange(event: React.FormEvent, {newValue, method}: any): void { - this.setState({ - value: newValue - }); + // endregion region Event handlers + protected onChange(event : React.FormEvent, {newValue, method} : any) : void { + this.setState({value: newValue}); } - protected onSuggestionsFetchRequested({ value }: any): void { + protected onSuggestionsFetchRequested({value}: any) : void { this.setState({ suggestions: this.getSuggestions(value) }); } - // endregion - - // region Helper methods - protected getSuggestions(value: string): Language[] { + // endregion region Helper methods + protected getSuggestions(value: string) : Language[] { const escapedValue = escapeRegexCharacters(value.trim()); if (escapedValue === '') { @@ -105,69 +128,97 @@ export class ReactAutosuggestBasicTest extends React.Component { const regex = new RegExp('^' + escapedValue, 'i'); - return ReactAutosuggestBasicTest.languages.filter(language => regex.test(language.name)); + return ReactAutosuggestBasicTest + .languages + .filter(language => regex.test(language.name)); } - protected getSuggestionValue(suggestion: Language): string { - return suggestion.name; - } + protected getSuggestionValue(suggestion: Language) : string {return suggestion.name;} // endregion } -ReactDOM.render(, document.getElementById('app')); +ReactDOM.render( + , document.getElementById('app')); interface LanguageGroup { - title: string; - languages: Language[]; + title : string; + languages : Language[]; } -export class ReactAutosuggestMultipleTest extends React.Component { +export class ReactAutosuggestMultipleTest extends React.Component { // region Fields - static languages: LanguageGroup[] = [ + static languages : LanguageGroup[] = [ { title: '1970s', languages: [ - {name: 'C', year: 1972} + { + name: 'C', + year: 1972 + } ] - }, - { + }, { title: '1980s', languages: [ - {name: 'C++', year: 1983}, - {name: 'Perl', year: 1987} + { + name: 'C++', + year: 1983 + }, { + name: 'Perl', + year: 1987 + } ] - }, - { + }, { title: '1990s', languages: [ - {name: 'Haskell', year: 1990}, - {name: 'Python', year: 1991}, - {name: 'Java', year: 1995}, - {name: 'Javascript', year: 1995}, - {name: 'PHP', year: 1995}, - {name: 'Ruby', year: 1995} + { + name: 'Haskell', + year: 1990 + }, { + name: 'Python', + year: 1991 + }, { + name: 'Java', + year: 1995 + }, { + name: 'Javascript', + year: 1995 + }, { + name: 'PHP', + year: 1995 + }, { + name: 'Ruby', + year: 1995 + } ] - }, - { + }, { title: '2000s', languages: [ - {name: 'C#', year: 2000}, - {name: 'Scala', year: 2003}, - {name: 'Clojure', year: 2007}, - {name: 'Go', year: 2009} + { + name: 'C#', + year: 2000 + }, { + name: 'Scala', + year: 2003 + }, { + name: 'Clojure', + year: 2007 + }, { + name: 'Go', + year: 2009 + } ] - }, - { + }, { title: '2010s', languages: [ - {name: 'Elm', year: 2012} + { + name: 'Elm', + year: 2012 + } ] } ]; - // endregion - - // region Constructor - constructor(props: any) { + // endregion region Constructor + constructor(props : any) { super(props); this.state = { @@ -175,59 +226,56 @@ export class ReactAutosuggestMultipleTest extends React.Component { suggestions: this.getSuggestions('') }; } - // endregion - - // region Rendering methods - render(): JSX.Element { - const { value, suggestions } = this.state; + // endregion region Rendering methods + render() : JSX.Element { + const {value, suggestions} = this.state; const inputProps = { placeholder: `Type 'c'`, value, - onChange: this.onChange.bind(this) + onChange: this + .onChange + .bind(this) }; - return ; + return ; } - protected onSuggestionSelected(event: React.FormEvent, data: SuggestionSelectedEventData): void { + protected onSuggestionSelected(event : React.FormEvent, data : Autosuggest.SuggestionSelectedEventData) : void { const language = data.suggestion as Language; alert(`Selected language is ${language.name} (${language.year}).`); } - protected renderSuggestion(suggestion: Language): JSX.Element { + protected renderSuggestion(suggestion : Language) : JSX.Element { return {suggestion.name}; } - protected renderSectionTitle(section: LanguageGroup): JSX.Element { + protected renderSectionTitle(section : LanguageGroup) : JSX.Element { return {section.title}; } - // endregion - - // region Event handlers - protected onChange(event: React.FormEvent, { newValue, method }: any): void { - this.setState({ - value: newValue - }); + // endregion region Event handlers + protected onChange(event : React.FormEvent, {newValue, method} : any) : void { + this.setState({value: newValue}); } - protected onSuggestionsFetchRequested({ value }: any): void { + protected onSuggestionsFetchRequested({value} : any) : void { this.setState({ suggestions: this.getSuggestions(value) }); } - // endregion - - // region Helper methods - protected getSuggestions(value: string): LanguageGroup[] { + // endregion region Helper methods + protected getSuggestions(value : string) : LanguageGroup[] { const escapedValue = escapeRegexCharacters(value.trim()); if (escapedValue === '') { @@ -236,46 +284,61 @@ export class ReactAutosuggestMultipleTest extends React.Component { const regex = new RegExp('^' + escapedValue, 'i'); - return ReactAutosuggestMultipleTest.languages + return ReactAutosuggestMultipleTest + .languages .map(section => { return { title: section.title, - languages: section.languages.filter(language => regex.test(language.name)) + languages: section + .languages + .filter(language => regex.test(language.name)) }; }) .filter(section => section.languages.length > 0); } - protected getSuggestionValue(suggestion: Language) { + protected getSuggestionValue(suggestion : Language) { return suggestion.name; } - protected getSectionSuggestions(section: LanguageGroup) { + protected getSectionSuggestions(section : LanguageGroup) { return section.languages; } // endregion } -ReactDOM.render(, document.getElementById('app')); +ReactDOM.render( + , document.getElementById('app')); interface Person { - first: string; - last: string; - twitter: string; + first : string; + last : string; + twitter : string; } -export class ReactAutosuggestCustomTest extends React.Component { +export class ReactAutosuggestCustomTest extends React.Component { // region Fields - static people: Person[] = [ - {first: 'Charlie', last: 'Brown', twitter: 'dancounsell'}, - {first: 'Charlotte', last: 'White', twitter: 'mtnmissy'}, - {first: 'Chloe', last: 'Jones', twitter: 'ladylexy'}, - {first: 'Cooper', last: 'King', twitter: 'steveodom'} + static people : Person[] = [ + { + first: 'Charlie', + last: 'Brown', + twitter: 'dancounsell' + }, { + first: 'Charlotte', + last: 'White', + twitter: 'mtnmissy' + }, { + first: 'Chloe', + last: 'Jones', + twitter: 'ladylexy' + }, { + first: 'Cooper', + last: 'King', + twitter: 'steveodom' + } ]; - // endregion - - // region Constructor - constructor(props: any) { + // endregion region Constructor + constructor(props : any) { super(props); this.state = { @@ -283,64 +346,62 @@ export class ReactAutosuggestCustomTest extends React.Component { suggestions: this.getSuggestions('') }; } - // endregion - - // region Rendering methods - render(): JSX.Element { - const { value, suggestions } = this.state; + // endregion region Rendering methods + render() : JSX.Element { + const {value, suggestions} = this.state; const inputProps = { placeholder: "Type 'c'", value, - onChange: this.onChange.bind(this) + onChange: this + .onChange + .bind(this) }; - return ; + return; } - protected renderSuggestion(suggestion: Person, { value, valueBeforeUpDown }: any): JSX.Element { + protected renderSuggestion(suggestion : Person, {value, valueBeforeUpDown} : any) : JSX.Element { const suggestionText = `${suggestion.first} ${suggestion.last}`; const query = (valueBeforeUpDown || value).trim(); - const parts = suggestionText.split(' ').map((part: string) => { - return { - highlight: (Math.ceil(Math.random() * 10)) % 2, - text: part - }; - }); + const parts = suggestionText + .split(' ') + .map((part : string) => { + return { + highlight: (Math.ceil(Math.random() * 10)) % 2, + text: part + }; + }); - return - - { - parts.map((part, index) => { - const className = part.highlight ? 'highlight' : undefined; + return + + {parts.map((part, index) => { + const className = part.highlight + ? 'highlight' + : undefined; - return {part.text}; - }) - } - - ; + return{part.text}; + }) +} + + ; } - // endregion - - // region Event handlers - protected onChange(event: React.FormEvent, {newValue, method}: any): void { - this.setState({ - value: newValue - }); + // endregion region Event handlers + protected onChange(event : React.FormEvent, {newValue, method} : any) : void { + this.setState({value: newValue}); } - protected onSuggestionsFetchRequested({ value }: any): void { + protected onSuggestionsFetchRequested({value} : any) : void { this.setState({ suggestions: this.getSuggestions(value) }); } - // endregion - - // region Helper methods - protected getSuggestions(value: string): Person[] { + // endregion region Helper methods + protected getSuggestions(value : string) : Person[] { const escapedValue = escapeRegexCharacters(value.trim()); if (escapedValue === '') { @@ -349,13 +410,14 @@ export class ReactAutosuggestCustomTest extends React.Component { const regex = new RegExp('\\b' + escapedValue, 'i'); - return ReactAutosuggestCustomTest.people.filter(person => regex.test(this.getSuggestionValue(person))); + return ReactAutosuggestCustomTest + .people + .filter(person => regex.test(this.getSuggestionValue(person))); } - protected getSuggestionValue(suggestion: Person): string { - return `${suggestion.first} ${suggestion.last}`; - } + protected getSuggestionValue(suggestion : Person) : string {return `${suggestion.first} ${suggestion.last}`;} // endregion } -ReactDOM.render(, document.getElementById('app')); +ReactDOM.render( + , document.getElementById('app')); diff --git a/react-big-calendar/index.d.ts b/react-big-calendar/index.d.ts index c55a3c126c..75508cae5e 100644 --- a/react-big-calendar/index.d.ts +++ b/react-big-calendar/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-big-calendar 0.11 +// Type definitions for react-big-calendar 0.12.3 // Project: https://github.com/intljusticemission/react-big-calendar // Definitions by: Piotr Witek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -26,10 +26,10 @@ declare module 'react-big-calendar' { step?: number; rtl?: boolean; eventPropGetter?: (event: Object, start: stringOrDate, end: stringOrDate, isSelected: boolean) => void; - titleAccessor?: string; - allDayAccessor?: boolean; - startAccessor?: stringOrDate; - endAccessor?: stringOrDate; + titleAccessor?: string | ((row: Object) => string); + allDayAccessor?: string | ((row: Object) => boolean); + startAccessor?: string | ((row: Object) => Date); + endAccessor?: string | ((row: Object) => Date); min?: stringOrDate; max?: stringOrDate; scrollToTime?: stringOrDate; @@ -38,6 +38,8 @@ declare module 'react-big-calendar' { messages?: Object; timeslots?: number; defaultView?: string; + className?: string; + elementProps?: React.HTMLAttributes; } class BigCalendar extends React.Component { diff --git a/react-big-calendar/react-big-calendar-tests.tsx b/react-big-calendar/react-big-calendar-tests.tsx index 9e492462ae..2ca939c0a6 100644 --- a/react-big-calendar/react-big-calendar-tests.tsx +++ b/react-big-calendar/react-big-calendar-tests.tsx @@ -58,10 +58,10 @@ const FullAPIExample = React.createClass({ step={20} rtl={true} eventPropGetter={(event, start, end, isSelected) => { } } - titleAccessor={'string'} - allDayAccessor={true} - startAccessor={new Date()} - endAccessor={new Date()} + titleAccessor={'title'} + allDayAccessor={(row:any) => !!row.allDay} + startAccessor={'start'} + endAccessor={(row:any) => row.end || row.start} min={new Date()} max={new Date()} scrollToTime={new Date()} @@ -70,6 +70,8 @@ const FullAPIExample = React.createClass({ messages={{}} timeslots={24} defaultView={'month'} + className={'my-calendar'} + elementProps={{id: 'myCalendar'}} /> ); } diff --git a/react-bootstrap-table/index.d.ts b/react-bootstrap-table/index.d.ts index 566019ab94..9adfacf8c8 100644 --- a/react-bootstrap-table/index.d.ts +++ b/react-bootstrap-table/index.d.ts @@ -356,7 +356,7 @@ export interface Options { /** Background color on expanded rows. */ - expandRowBgColor?: string; + expandRowBgColor?: string; /** Assign a callback function which will be called when mouse enter into the table. */ @@ -475,6 +475,13 @@ export interface TableHeaderColumnProps extends Props { This function taking one arguments: order which present the sort order currently. */ caretRender?: Function; + /** + Give an Object like following to able to customize your own editing component. + This Object should contain these two property: + getElement(REQUIRED): Accept a callback function and take two arguments: onUpdate and props. + customEditorParameters: Another extra data for custom cell edit component. + */ + customEditor?: {getElement: (onUpdate: any, props: any) => ReactElement, customEditorParameters?: Object} ; /** To customize the column. This callback function should return a String or a React Component. In addition, this function taking two argument: cell and row. @@ -568,6 +575,11 @@ export interface Editable { cols?: number; rows?: number; } +export type SetFilterCallback = (targetValue: any) => boolean; +export interface ApplyFilterParameter { + callback: SetFilterCallback; +} + export type FilterType = 'TextFilter' | 'RegexFilter' | 'SelectFilter' | 'NumberFilter' | 'DateFilter' | 'CustomFilter'; export interface Filter { /** @@ -590,6 +602,26 @@ export interface Filter { * Only work on NumberFilter. Accept an array which conatin the filter condition, like: ['<','>','='] */ numberComparators?: string[]; + + /** + * Options for the filter. + */ + options?: any; + + /** + * Comparison condition for the NumberFilter + */ + condition?: string; + + /** + * Get element which represent filter. + */ + getElement?: (filterHandler: (parameters?: ApplyFilterParameter) => void, filterParameters: any) => JSX.Element; + + /** + * Parameters for custom filter + */ + customFilterParameters?: any; } export interface TableHeaderColumn extends ComponentClass { } diff --git a/react-bootstrap-table/react-bootstrap-table-tests.tsx b/react-bootstrap-table/react-bootstrap-table-tests.tsx index 47682dd36a..2151f14c78 100644 --- a/react-bootstrap-table/react-bootstrap-table-tests.tsx +++ b/react-bootstrap-table/react-bootstrap-table-tests.tsx @@ -2,7 +2,7 @@ import * as React from 'react'; import { render } from 'react-dom'; -import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; +import { BootstrapTable, TableHeaderColumn, ApplyFilterParameter } from 'react-bootstrap-table'; var products = [{ id: 1, @@ -27,3 +27,56 @@ render( , document.getElementById("app") ); + +const qualityType = { + 0: 'good', + 1: 'bad', + 2: 'unknown' +}; + +function enumFormatter(cell: any, row: any, enumObject: any) { + return enumObject[cell]; +} + +class SelectFilterWithDefaultValue extends React.Component { + render() { + return ( + + Product ID + Product Name + Product Quality + + ); + } +} + +class TextFilterWithCondition extends React.Component { + render() { + return ( + + Product ID + Product Name + Product Price + + ); + } +} + +function getCustomFilter(filterHandler: (parameters?: ApplyFilterParameter) => void, customFilterParameters: any) { + return ( +
              + ); +} + +class CustomFilter extends React.Component { + render() { + return ( + + Product ID + Product Name + Product Is In Stock + + ); + } +} diff --git a/react-bootstrap/index.d.ts b/react-bootstrap/index.d.ts index 6c17fb4cee..500babd6cf 100644 --- a/react-bootstrap/index.d.ts +++ b/react-bootstrap/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for react-bootstrap // Project: https://github.com/react-bootstrap/react-bootstrap -// Definitions by: Walker Burgin , Vincent Siao , Danilo Barros , Batbold Gansukh , Raymond May Jr. +// Definitions by: Walker Burgin , Vincent Siao , Danilo Barros , Batbold Gansukh , Raymond May Jr. , Cheng Sieu Ly // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -867,6 +867,15 @@ declare namespace ReactBootstrap { type Image = React.ClassicComponent; var Image: React.ClassicComponentClass; + // + interface ResponsiveEmbedProps extends React.HTMLProps { + a16by9?: boolean; + a4by3?: boolean; + bsClass?: string; + } + class ResponsiveEmbed extends React.Component { + } + // interface PageHeaderProps extends React.HTMLProps { } diff --git a/react-bootstrap/react-bootstrap-tests.tsx b/react-bootstrap/react-bootstrap-tests.tsx index f3772d0fef..432636559b 100644 --- a/react-bootstrap/react-bootstrap-tests.tsx +++ b/react-bootstrap/react-bootstrap-tests.tsx @@ -1,9 +1,3 @@ -// React-Bootstrap Test -// ================================================================================ -/// - -// Imports -// -------------------------------------------------------------------------------- import * as React from 'react'; import { Component, CSSProperties } from 'react'; import { @@ -14,7 +8,7 @@ import { Nav, NavItem, Navbar, NavDropdown, Tabs, Tab, Pager, PageItem, Pagination, Alert, Carousel, SafeAnchor, - Grid, Row, Col, Thumbnail, Image, + Grid, Row, Col, Thumbnail, Image, ResponsiveEmbed, Label, Badge, Jumbotron, PageHeader, Glyphicon, Table, Form, FormGroup, ControlLabel, FormControl, HelpBlock, @@ -845,6 +839,20 @@ export class ReactBootstrapTest extends Component {
              +
              +
              + + Embedded Content + + + Embedded Content + + + Embedded Content + +
              +
              +
              Example page header Subtext for header
              diff --git a/react-color/index.d.ts b/react-color/index.d.ts index bed3ae46ff..798f44d6eb 100644 --- a/react-color/index.d.ts +++ b/react-color/index.d.ts @@ -1,249 +1,58 @@ -// Type definitions for react-color v2.3.4 -// Project: https://casesandberg.github.io/react-color/ +// Type definitions for react-color 2.11 +// Project: https://github.com/casesandberg/react-color/ // Definitions by: Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -/// +import { ComponentClass, ClassAttributes, StatelessComponent, ReactNode } from "react"; -declare namespace ReactColor { - interface HSLColor { - a?: number - h: number - l: number - s: number - } - - interface RGBColor { - a?: number - b: number - g: number - r: number - } - - type Color = string | HSLColor | RGBColor - - interface ColorResult { - hex: string - hsl: HSLColor - rgb: RGBColor - } - - type ColorChangeHandler = (color: ColorResult) => void - - interface ColorPickerProps extends React.ClassAttributes { - color?: Color - onChange?: ColorChangeHandler - onChangeComplete?: ColorChangeHandler - } - - /* Predefined pickers */ - interface AlphaPickerProps extends ColorPickerProps { - height?: string - width?: string - } - interface AlphaPicker extends React.ComponentClass {} - const AlphaPicker: AlphaPicker - - interface BlockPickerProps extends ColorPickerProps { - colors?: Array - width?: string - } - interface BlockPicker extends React.ComponentClass {} - const BlockPicker: BlockPicker - - interface ChromePickerProps extends ColorPickerProps { - disableAlpha?: boolean - } - interface ChromePicker extends React.ComponentClass {} - const ChromePicker: ChromePicker - - interface CirclePickerProps extends ColorPickerProps { - colors?: Array - width?: string - } - interface CirclePicker extends React.ComponentClass {} - const CirclePicker: CirclePicker - - interface CompactPickerProps extends ColorPickerProps { - colors?: Array - } - interface CompactPicker extends React.ComponentClass {} - const CompactPicker: CompactPicker - - interface GithubPickerProps extends ColorPickerProps { - colors?: Array - width?: string - } - interface GithubPicker extends React.ComponentClass {} - const GithubPicker: GithubPicker - - interface HuePickerProps extends ColorPickerProps { - height?: string - width?: string - } - interface HuePicker extends React.ComponentClass {} - const HuePicker: HuePicker - - interface MaterialPickerProps extends ColorPickerProps {} - interface MaterialPicker extends React.ComponentClass {} - const MaterialPicker: MaterialPicker - - interface PhotoshopPickerProps extends ColorPickerProps { - header?: string - onAccept?: ColorChangeHandler - onCancel?: ColorChangeHandler - } - interface PhotoshopPicker extends React.ComponentClass {} - const PhotoshopPicker: PhotoshopPicker - - interface SketchPickerProps extends ColorPickerProps { - disableAlpha?: boolean - presetColors?: Array - width?: string - } - interface SketchPicker extends React.ComponentClass {} - const SketchPicker: SketchPicker - - interface SliderPickerProps extends ColorPickerProps {} - interface SliderPicker extends React.ComponentClass {} - const SliderPicker: SliderPicker - - interface SwatchesPickerProps extends ColorPickerProps { - colors?: Array> - height?: number - width?: number - } - interface SwatchesPicker extends React.ComponentClass {} - const SwatchesPicker: SwatchesPicker - - interface TwitterPickerProps extends ColorPickerProps {} - interface TwitterPicker extends React.ComponentClass {} - const TwitterPicker: TwitterPicker - - /* For custom picker */ - interface InjectedColorProps { - hex?: string - hsl?: HSLColor - rgb?: RGBColor - onChange?: ColorChangeHandler - } - - function CustomPicker(component: React.ComponentClass | React.StatelessComponent): React.ComponentClass - - interface CustomPickerProps extends React.ClassAttributes { - color?: Color - pointer?: React.ReactNode - onChange?: ColorChangeHandler - } - - interface AlphaProps extends CustomPickerProps {} - interface Alpha extends React.ComponentClass {} - const Alpha: Alpha - - interface EditableInputStyles { - input?: React.CSSProperties - label?: React.CSSProperties - wrap?: React.CSSProperties - } - interface EditableInputProps extends React.ClassAttributes { - color?: Color - label?: string - onChange?: ColorChangeHandler - styles?: EditableInputStyles - value?: any - } - interface EditableInput extends React.ComponentClass {} - const EditableInput: EditableInput - - interface HueProps extends CustomPickerProps { - direction?: "horizontal" | "vertical" - } - interface Hue extends React.ComponentClass {} - const Hue: Hue - - interface SaturationProps extends CustomPickerProps {} - interface Saturation extends React.ComponentClass {} - const Saturation: Saturation - - interface CheckboardProps extends React.ClassAttributes { - grey?: string - size?: number - white?: string - } - interface Checkboard extends React.ComponentClass {} - const Checkboard: Checkboard +export interface HSLColor { + a?: number; + h: number; + l: number; + s: number; } -declare module "react-color/lib/components/common/Alpha" { export default ReactColor.Alpha } -declare module "react-color/lib/components/common/Checkboard" { export default ReactColor.Checkboard } -declare module "react-color/lib/components/common/EditableInput" { export default ReactColor.EditableInput } -declare module "react-color/lib/components/common/Hue" { export default ReactColor.Hue } -declare module "react-color/lib/components/common/Saturation" { export default ReactColor.Saturation } -declare module "react-color/lib/components/common/ColorWrap" { export default ReactColor.CustomPicker } - -declare module "react-color/lib/components/common" { - import Alpha from "react-color/lib/components/common/Alpha" - import Checkboard from "react-color/lib/components/common/Checkboard" - import EditableInput from "react-color/lib/components/common/EditableInput" - import Hue from "react-color/lib/components/common/Hue" - import Saturation from "react-color/lib/components/common/Saturation" - - export { - Alpha, - Checkboard, - EditableInput, - Hue, - Saturation - } +export interface RGBColor { + a?: number; + b: number; + g: number; + r: number; } -declare module "react-color/lib/components/alpha/Alpha" { export default ReactColor.AlphaPicker } -declare module "react-color/lib/components/block/Block" { export default ReactColor.BlockPicker } -declare module "react-color/lib/components/chrome/Chrome" { export default ReactColor.ChromePicker } -declare module "react-color/lib/components/circle/Circle" { export default ReactColor.CirclePicker } -declare module "react-color/lib/components/compact/Compact" { export default ReactColor.CompactPicker } -declare module "react-color/lib/components/github/Github" { export default ReactColor.GithubPicker } -declare module "react-color/lib/components/hue/Hue" { export default ReactColor.HuePicker } -declare module "react-color/lib/components/meterial/Material" { export default ReactColor.MaterialPicker } -declare module "react-color/lib/components/photoshop/Photoshop" { export default ReactColor.PhotoshopPicker } -declare module "react-color/lib/components/sketch/Sketch" { export default ReactColor.SketchPicker } -declare module "react-color/lib/components/slider/Slider" { export default ReactColor.SliderPicker } -declare module "react-color/lib/components/swatches/Swatches" { export default ReactColor.SwatchesPicker } -declare module "react-color/lib/components/twitter/Twitter" { export default ReactColor.TwitterPicker } +export type Color = string | HSLColor | RGBColor; -declare module "react-color" { - import AlphaPicker from "react-color/lib/components/alpha/Alpha" - import BlockPicker from "react-color/lib/components/block/Block" - import ChromePicker from "react-color/lib/components/chrome/Chrome" - import CirclePicker from "react-color/lib/components/circle/Circle" - import CompactPicker from "react-color/lib/components/compact/Compact" - import GithubPicker from "react-color/lib/components/github/Github" - import HuePicker from "react-color/lib/components/hue/Hue" - import MaterialPicker from "react-color/lib/components/meterial/Material" - import PhotoshopPicker from "react-color/lib/components/photoshop/Photoshop" - import SketchPicker from "react-color/lib/components/sketch/Sketch" - import SliderPicker from "react-color/lib/components/slider/Slider" - import SwatchesPicker from "react-color/lib/components/swatches/Swatches" - import TwitterPicker from "react-color/lib/components/twitter/Twitter" - import CustomPicker from "react-color/lib/components/common/ColorWrap" - - export type CustomPickerProps = ReactColor.CustomPickerProps - - export { - AlphaPicker, - BlockPicker, - ChromePicker, - CirclePicker, - CompactPicker, - GithubPicker, - HuePicker, - MaterialPicker, - PhotoshopPicker, - SketchPicker, - SliderPicker, - SwatchesPicker, - TwitterPicker, - CustomPicker - } +export interface ColorResult { + hex: string; + hsl: HSLColor; + rgb: RGBColor; } + +export type ColorChangeHandler = (color: ColorResult) => void; + +export interface ColorPickerProps extends ClassAttributes { + color?: Color; + onChange?: ColorChangeHandler; + onChangeComplete?: ColorChangeHandler; +} + +export interface CustomPickerProps extends ClassAttributes { + color?: Color; + pointer?: ReactNode; + onChange: ColorChangeHandler; +} + +export { default as AlphaPicker, AlphaPickerProps } from "react-color/lib/components/alpha/Alpha"; +export { default as BlockPicker, BlockPickerProps } from "react-color/lib/components/block/Block"; +export { default as ChromePicker, ChromePickerProps } from "react-color/lib/components/chrome/Chrome"; +export { default as CirclePicker, CirclePickerProps } from "react-color/lib/components/circle/Circle"; +export { default as CompactPicker, CompactPickerProps } from "react-color/lib/components/compact/Compact"; +export { default as GithubPicker, GithubPickerProps } from "react-color/lib/components/github/Github"; +export { default as HuePicker, HuePickerProps } from "react-color/lib/components/hue/Hue"; +export { default as MaterialPicker, MaterialPickerProps } from "react-color/lib/components/material/Material"; +export { default as PhotoshopPicker, PhotoshopPickerProps } from "react-color/lib/components/photoshop/Photoshop"; +export { default as SketchPicker, SketchPickerProps } from "react-color/lib/components/sketch/Sketch"; +export { default as SliderPicker, SliderPickerProps } from "react-color/lib/components/slider/Slider"; +export { default as SwatchesPicker, SwatchesPickerProps } from "react-color/lib/components/swatches/Swatches"; +export { default as TwitterPicker, TwitterPickerProps } from "react-color/lib/components/twitter/Twitter"; +export { default as CustomPicker, InjectedColorProps } from "react-color/lib/components/common/ColorWrap"; diff --git a/react-color/lib/components/alpha/Alpha.d.ts b/react-color/lib/components/alpha/Alpha.d.ts new file mode 100644 index 0000000000..2856f077b9 --- /dev/null +++ b/react-color/lib/components/alpha/Alpha.d.ts @@ -0,0 +1,9 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface AlphaPickerProps extends ColorPickerProps { + height?: string; + width?: string; +} + +export default class AlphaPicker extends Component {} diff --git a/react-color/lib/components/block/Block.d.ts b/react-color/lib/components/block/Block.d.ts new file mode 100644 index 0000000000..edb3c72347 --- /dev/null +++ b/react-color/lib/components/block/Block.d.ts @@ -0,0 +1,9 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface BlockPickerProps extends ColorPickerProps { + colors?: string[]; + width?: string; +} + +export default class BlockPicker extends Component {} diff --git a/react-color/lib/components/chrome/Chrome.d.ts b/react-color/lib/components/chrome/Chrome.d.ts new file mode 100644 index 0000000000..fa214d1b14 --- /dev/null +++ b/react-color/lib/components/chrome/Chrome.d.ts @@ -0,0 +1,8 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface ChromePickerProps extends ColorPickerProps { + disableAlpha?: boolean; +} + +export default class ChromePicker extends Component {} diff --git a/react-color/lib/components/circle/Circle.d.ts b/react-color/lib/components/circle/Circle.d.ts new file mode 100644 index 0000000000..204842d72a --- /dev/null +++ b/react-color/lib/components/circle/Circle.d.ts @@ -0,0 +1,9 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface CirclePickerProps extends ColorPickerProps { + colors?: string[]; + width?: string; +} + +export default class CirclePicker extends Component {} diff --git a/react-color/lib/components/common/Alpha.d.ts b/react-color/lib/components/common/Alpha.d.ts new file mode 100644 index 0000000000..da20010497 --- /dev/null +++ b/react-color/lib/components/common/Alpha.d.ts @@ -0,0 +1,6 @@ +import { Component } from "react"; +import { CustomPickerProps } from "react-color"; + +export type AlphaProps = CustomPickerProps; + +export default class Alpha extends Component {} diff --git a/react-color/lib/components/common/Checkboard.d.ts b/react-color/lib/components/common/Checkboard.d.ts new file mode 100644 index 0000000000..40d8f26913 --- /dev/null +++ b/react-color/lib/components/common/Checkboard.d.ts @@ -0,0 +1,9 @@ +import { Component, ClassAttributes } from "react"; + +export interface CheckboardProps extends ClassAttributes { + grey?: string; + size?: number; + white?: string; +} + +export default class Checkboard extends Component {} diff --git a/react-color/lib/components/common/ColorWrap.d.ts b/react-color/lib/components/common/ColorWrap.d.ts new file mode 100644 index 0000000000..94a8f5b789 --- /dev/null +++ b/react-color/lib/components/common/ColorWrap.d.ts @@ -0,0 +1,11 @@ +import { ComponentClass, StatelessComponent } from "react"; +import { HSLColor, RGBColor, ColorChangeHandler } from "react-color"; + +export interface InjectedColorProps { + hex?: string; + hsl?: HSLColor; + rgb?: RGBColor; + onChange?: ColorChangeHandler; +} + +export default function CustomPicker(component: ComponentClass | StatelessComponent): ComponentClass; diff --git a/react-color/lib/components/common/EditableInput.d.ts b/react-color/lib/components/common/EditableInput.d.ts new file mode 100644 index 0000000000..78df9473f2 --- /dev/null +++ b/react-color/lib/components/common/EditableInput.d.ts @@ -0,0 +1,19 @@ +import { Component, ClassAttributes, CSSProperties } from "react"; +import { Color, ColorChangeHandler } from "react-color"; + +export interface EditableInputStyles { + input?: CSSProperties; + label?: CSSProperties; + wrap?: CSSProperties; +} + +export interface EditableInputProps extends ClassAttributes { + color?: Color; + label?: string; + onChange?: ColorChangeHandler; + styles?: EditableInputStyles; + value?: any; +} + +export default class EditableInput extends Component {} + diff --git a/react-color/lib/components/common/Hue.d.ts b/react-color/lib/components/common/Hue.d.ts new file mode 100644 index 0000000000..1f61841107 --- /dev/null +++ b/react-color/lib/components/common/Hue.d.ts @@ -0,0 +1,8 @@ +import { Component } from "react"; +import { CustomPickerProps } from "react-color"; + +export interface HueProps extends CustomPickerProps { + direction?: "horizontal" | "vertical"; +} + +export default class Hue extends Component {} diff --git a/react-color/lib/components/common/Saturation.d.ts b/react-color/lib/components/common/Saturation.d.ts new file mode 100644 index 0000000000..c90a7d9685 --- /dev/null +++ b/react-color/lib/components/common/Saturation.d.ts @@ -0,0 +1,6 @@ +import { Component } from "react"; +import { CustomPickerProps } from "react-color"; + +export type SaturationProps = CustomPickerProps; + +export default class Saturation extends Component {} diff --git a/react-color/lib/components/common/index.d.ts b/react-color/lib/components/common/index.d.ts new file mode 100644 index 0000000000..ed5af44bdf --- /dev/null +++ b/react-color/lib/components/common/index.d.ts @@ -0,0 +1,5 @@ +export { default as Alpha } from "react-color/lib/components/common/Alpha"; +export { default as Checkboard } from "react-color/lib/components/common/Checkboard"; +export { default as EditableInput } from "react-color/lib/components/common/EditableInput"; +export { default as Hue } from "react-color/lib/components/common/Hue"; +export { default as Saturation } from "react-color/lib/components/common/Saturation"; diff --git a/react-color/lib/components/compact/Compact.d.ts b/react-color/lib/components/compact/Compact.d.ts new file mode 100644 index 0000000000..3f9ff74f60 --- /dev/null +++ b/react-color/lib/components/compact/Compact.d.ts @@ -0,0 +1,8 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface CompactPickerProps extends ColorPickerProps { + colors?: string[]; +} + +export default class CompactPicker extends Component {} diff --git a/react-color/lib/components/github/Github.d.ts b/react-color/lib/components/github/Github.d.ts new file mode 100644 index 0000000000..fd1479abad --- /dev/null +++ b/react-color/lib/components/github/Github.d.ts @@ -0,0 +1,9 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface GithubPickerProps extends ColorPickerProps { + colors?: string[]; + width?: string; +} + +export default class GithubPicker extends Component {} diff --git a/react-color/lib/components/hue/Hue.d.ts b/react-color/lib/components/hue/Hue.d.ts new file mode 100644 index 0000000000..6aab83baea --- /dev/null +++ b/react-color/lib/components/hue/Hue.d.ts @@ -0,0 +1,9 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface HuePickerProps extends ColorPickerProps { + height?: string; + width?: string; +} + +export default class HuePicker extends Component {} diff --git a/react-color/lib/components/material/Material.d.ts b/react-color/lib/components/material/Material.d.ts new file mode 100644 index 0000000000..4ae849b910 --- /dev/null +++ b/react-color/lib/components/material/Material.d.ts @@ -0,0 +1,6 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export type MaterialPickerProps = ColorPickerProps; + +export default class MaterialPicker extends Component {} diff --git a/react-color/lib/components/photoshop/Photoshop.d.ts b/react-color/lib/components/photoshop/Photoshop.d.ts new file mode 100644 index 0000000000..c3abaf0ccd --- /dev/null +++ b/react-color/lib/components/photoshop/Photoshop.d.ts @@ -0,0 +1,10 @@ +import { Component } from "react"; +import { ColorChangeHandler, ColorPickerProps } from "react-color"; + +export interface PhotoshopPickerProps extends ColorPickerProps { + header?: string; + onAccept?: ColorChangeHandler; + onCancel?: ColorChangeHandler; +} + +export default class PhotoshopPicker extends Component {} diff --git a/react-color/lib/components/sketch/Sketch.d.ts b/react-color/lib/components/sketch/Sketch.d.ts new file mode 100644 index 0000000000..229b2b2b51 --- /dev/null +++ b/react-color/lib/components/sketch/Sketch.d.ts @@ -0,0 +1,10 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface SketchPickerProps extends ColorPickerProps { + disableAlpha?: boolean; + presetColors?: string[]; + width?: string; +} + +export default class SketchPicker extends Component {} diff --git a/react-color/lib/components/slider/Slider.d.ts b/react-color/lib/components/slider/Slider.d.ts new file mode 100644 index 0000000000..913f30692a --- /dev/null +++ b/react-color/lib/components/slider/Slider.d.ts @@ -0,0 +1,6 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export type SliderPickerProps = ColorPickerProps; + +export default class SliderPicker extends Component {} diff --git a/react-color/lib/components/swatches/Swatches.d.ts b/react-color/lib/components/swatches/Swatches.d.ts new file mode 100644 index 0000000000..22e9d1704c --- /dev/null +++ b/react-color/lib/components/swatches/Swatches.d.ts @@ -0,0 +1,10 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface SwatchesPickerProps extends ColorPickerProps { + colors?: string[][]; + height?: number; + width?: number; +} + +export default class SwatchesPicker extends Component {} diff --git a/react-color/lib/components/twitter/Twitter.d.ts b/react-color/lib/components/twitter/Twitter.d.ts new file mode 100644 index 0000000000..b4e6bb2308 --- /dev/null +++ b/react-color/lib/components/twitter/Twitter.d.ts @@ -0,0 +1,6 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export type TwitterPickerProps = ColorPickerProps; + +export default class TwitterPicker extends Component {} diff --git a/react-color/react-color-tests.tsx b/react-color/react-color-tests.tsx index 7969047569..e4e6f2348b 100644 --- a/react-color/react-color-tests.tsx +++ b/react-color/react-color-tests.tsx @@ -5,16 +5,19 @@ import { AlphaPicker, BlockPicker, ChromePicker, CirclePicker, CompactPicker, GithubPicker, HuePicker, MaterialPicker, PhotoshopPicker, SketchPicker, SliderPicker, SwatchesPicker, - TwitterPicker, CustomPicker + TwitterPicker, CustomPicker, InjectedColorProps, ColorResult, + Color } from "react-color" import { Alpha, Checkboard, EditableInput, Hue, Saturation } from "react-color/lib/components/common" -interface CustomProps extends ReactColor.InjectedColorProps { - color?: ReactColor.Color +interface CustomProps extends InjectedColorProps { + color?: Color } var CustomComponent: StatelessComponent = (props: CustomProps) => { - function onChange (color: ReactColor.ColorResult) {} + function onChange (color: ColorResult) { + console.log(color) + } return (
              diff --git a/react-color/tsconfig.json b/react-color/tsconfig.json index a88182ffbc..26e01d85c6 100644 --- a/react-color/tsconfig.json +++ b/react-color/tsconfig.json @@ -15,10 +15,32 @@ "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true, - "jsx": "react" + "jsx": "react", + "noUnusedParameters": true, + "noUnusedLocals": true }, "files": [ "index.d.ts", + "lib/components/alpha/Alpha.d.ts", + "lib/components/block/Block.d.ts", + "lib/components/chrome/Chrome.d.ts", + "lib/components/circle/Circle.d.ts", + "lib/components/common/Alpha.d.ts", + "lib/components/common/Checkboard.d.ts", + "lib/components/common/ColorWrap.d.ts", + "lib/components/common/EditableInput.d.ts", + "lib/components/common/Hue.d.ts", + "lib/components/common/index.d.ts", + "lib/components/common/Saturation.d.ts", + "lib/components/compact/Compact.d.ts", + "lib/components/github/Github.d.ts", + "lib/components/hue/Hue.d.ts", + "lib/components/material/Material.d.ts", + "lib/components/photoshop/Photoshop.d.ts", + "lib/components/sketch/Sketch.d.ts", + "lib/components/slider/Slider.d.ts", + "lib/components/swatches/Swatches.d.ts", + "lib/components/twitter/Twitter.d.ts", "react-color-tests.tsx" ] -} \ No newline at end of file +} diff --git a/react-color/tslint.json b/react-color/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/react-color/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/react-copy-to-clipboard/index.d.ts b/react-copy-to-clipboard/index.d.ts new file mode 100644 index 0000000000..1b0c9e942e --- /dev/null +++ b/react-copy-to-clipboard/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for react-copy-to-clipboard 4.2 +// Project: https://github.com/nkbt/react-copy-to-clipboard +// Definitions by: Meno Abels +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +import * as React from "react"; + +export as namespace CopyToClipboard; + +export = CopyToClipboard; + +declare namespace CopyToClipboard { + + export interface Options { + debug: boolean; + message: string; + } + + export interface Props { + text: string; + onCopy?: (a: string) => void, + options?: Options; + } + +} + +declare class CopyToClipboard extends React.Component { +} + diff --git a/react-copy-to-clipboard/react-copy-to-clipboard-tests.tsx b/react-copy-to-clipboard/react-copy-to-clipboard-tests.tsx new file mode 100644 index 0000000000..195e7a8ceb --- /dev/null +++ b/react-copy-to-clipboard/react-copy-to-clipboard-tests.tsx @@ -0,0 +1,14 @@ + +import * as React from "react"; +import * as CopyToClipboard from "react-copy-to-clipboard"; + +export class Test extends React.Component { + render() { + return ( + {}}> + Copy to clipboard with span + + ); + } +} diff --git a/react-copy-to-clipboard/tsconfig.json b/react-copy-to-clipboard/tsconfig.json new file mode 100644 index 0000000000..a4e09d1242 --- /dev/null +++ b/react-copy-to-clipboard/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-copy-to-clipboard-tests.tsx" + ] +} diff --git a/react-copy-to-clipboard/tslint.json b/react-copy-to-clipboard/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/react-copy-to-clipboard/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/react-datagrid/react-datagrid-tests.tsx b/react-datagrid/react-datagrid-tests.tsx index 061be471f4..bdbca39f01 100644 --- a/react-datagrid/react-datagrid-tests.tsx +++ b/react-datagrid/react-datagrid-tests.tsx @@ -1,6 +1,3 @@ - -/// - import * as React from "react"; import ReactDataGrid = require("react-datagrid"); diff --git a/react-datepicker/index.d.ts b/react-datepicker/index.d.ts index ae33a5c24f..0cbe0ba202 100644 --- a/react-datepicker/index.d.ts +++ b/react-datepicker/index.d.ts @@ -29,6 +29,7 @@ declare module "react-datepicker" { name?: string; onBlur?(event: React.FocusEvent): void; onChange(date: moment.Moment | null, event: React.SyntheticEvent | undefined): any; + onChangeRaw?(event: React.FocusEvent): void; onFocus?(event: React.FocusEvent): void; peekNextMonth?: boolean; placeholderText?: string; diff --git a/react-dates/index.d.ts b/react-dates/index.d.ts new file mode 100644 index 0000000000..e3ca801887 --- /dev/null +++ b/react-dates/index.d.ts @@ -0,0 +1,364 @@ +// Type definitions for react-dates v7.0.1 +// Project: https://github.com/airbnb/react-dates +// Definitions by: Artur Ampilogov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +import * as React from "react"; +import * as moment from "moment"; + +export = ReactDates; + +declare namespace momentPropTypes{ + type momentObj = any; + type momentString = any; + type momentDurationObj = any; +} + + +declare namespace ReactDates{ + type AnchorDirectionShape = 'left' | 'right'; + type FocusedInputShape = 'startDate' | 'endDate'; + type OrientationShape = 'horizontal' | 'vertical'; + type ScrollableOrientationShape = 'horizontal' | 'vertical' | 'verticalScrollable'; + + + interface DateRangePickerShape{ + startDate?: momentPropTypes.momentObj, + endDate?: momentPropTypes.momentObj, + focusedInput?: FocusedInputShape, + screenReaderInputMessage?: string, + minimumNights?: number, + isDayBlocked?: (day: any) => boolean, + isOutsideRange?: (day: any) => boolean, + enableOutsideDays?: boolean, + reopenPickerOnClearDates?: boolean, + keepOpenOnDateSelect?: boolean, + numberOfMonths?: number, + showClearDates?: boolean, + disabled?: boolean, + required?: boolean, + showDefaultInputIcon?: boolean, + + orientation?: OrientationShape, + anchorDirection?: AnchorDirectionShape, + horizontalMargin?: number, + // portal options + withPortal?: boolean, + withFullScreenPortal?: boolean, + + startDateId?: string, + startDatePlaceholderText?: string, + endDateId?: string, + endDatePlaceholderText?: string, + + initialVisibleMonth?: () => moment.Moment, + onDatesChange?: (arg: { startDate: any, endDate: any }) => void, + onFocusChange?: (arg: FocusedInputShape) => void, + onPrevMonthClick?: (e: React.EventHandler>) => void, + onNextMonthClick?: (e: React.EventHandler>) => void, + + renderDay?: (day: any) => (string | JSX.Element), + + // i18n + displayFormat?: (string | (()=> string)), + monthFormat?: string, + phrases?: { + closeDatePicker: string | JSX.Element, + clearDates: string | JSX.Element, + } + } + + type DateRangePicker = React.ClassicComponentClass; + var DateRangePicker: React.ClassicComponentClass; + + interface SingleDatePickerShape{ + id: string, + placeholder?: string, + date?: momentPropTypes.momentObj, + focused?: boolean, + showClearDate?: boolean, + reopenPickerOnClearDates?: boolean, + keepOpenOnDateSelect?: boolean, + disabled?: boolean, + required?: boolean, + screenReaderInputMessage?: string, + + onDateChange?: (date: any) => void, + onFocusChange?: (arg: { focused: boolean | null }) => void, + + isDayBlocked?: (day: any) => boolean, + isOutsideRange?: (day: any) => boolean, + enableOutsideDays?: boolean, + numberOfMonths?: number, + orientation?: OrientationShape, + initialVisibleMonth?: () => moment.Moment, + anchorDirection?: AnchorDirectionShape, + horizontalMargin?: number, + + navPrev?: string | JSX.Element, + navNext?: string | JSX.Element, + + // portal options + withPortal?: boolean, + withFullScreenPortal?: boolean, + + onPrevMonthClick?: (e: React.EventHandler>) => void, + onNextMonthClick?: (e: React.EventHandler>) => void, + + renderDay?: (day: any) => (string | JSX.Element), + + // i18n + displayFormat?: (string | (()=> string)), + monthFormat?: string, + phrases?: { + closeDatePicker: string | JSX.Element, + }, + } + type SingleDatePicker = React.ClassicComponentClass; + var SingleDatePicker: React.ClassicComponentClass; + + + + interface DateRangePickerInputControllerShape { + startDate?: momentPropTypes.momentObj, + startDateId?: string, + startDatePlaceholderText?: string, + isStartDateFocused?: boolean, + + endDate?: momentPropTypes.momentObj, + endDateId?: string, + endDatePlaceholderText?: string, + isEndDateFocused?: boolean, + + screenReaderMessage?: string, + showClearDates?: boolean, + showCaret?: boolean, + showDefaultInputIcon?: boolean, + disabled?: boolean, + required?: boolean, + + keepOpenOnDateSelect?: boolean, + reopenPickerOnClearDates?: boolean, + withFullScreenPortal?: boolean, + isOutsideRange?: (day: any) => boolean, + displayFormat?: (string | (()=> string)), + + onFocusChange?: (arg: FocusedInputShape) => void, + onDatesChange?: (arg: { startDate: any, endDate: any }) => void, + + customInputIcon?: string | JSX.Element, + customArrowIcon?: string | JSX.Element, + + // i18n + phrases?: { + clearDates: string | JSX.Element, + } + } + type DateRangePickerInputController = React.ClassicComponentClass; + var DateRangePickerInputController: React.ClassicComponentClass; + + + + interface DateRangePickerInputShape{ + startDateId?: string, + startDatePlaceholderText?: string, + screenReaderMessage?: string, + + endDateId?: string, + endDatePlaceholderText?: string, + + onStartDateFocus?: (e: React.EventHandler>) => void, + onEndDateFocus?: (e: React.EventHandler>) => void, + onStartDateChange?: (e: React.EventHandler>) => void, + onEndDateChange?: (e: React.EventHandler>) => void, + onStartDateShiftTab?: (e: React.EventHandler>) => void, + onEndDateTab?: (e: React.EventHandler>) => void, + onClearDates?: (e: React.EventHandler>) => void, + + startDate?: string, + startDateValue?: string, + endDate?: string, + endDateValue?: string, + + isStartDateFocused?: boolean, + isEndDateFocused?: boolean, + showClearDates?: boolean, + disabled?: boolean, + required?: boolean, + showCaret?: boolean, + showDefaultInputIcon?: boolean, + customInputIcon?: string | JSX.Element, + customArrowIcon?: string | JSX.Element, + + // i18n + phrases?:{ + clearDates: string | JSX.Element, + }, + } + type DateRangePickerInput = React.ClassicComponentClass; + var DateRangePickerInput: React.ClassicComponentClass; + + + + interface SingleDatePickerInputShape{ + id: string, + placeholder?: string, // also used as label + displayValue?: string, + inputValue?: string, + screenReaderMessage?: string, + focused?: boolean, + disabled?: boolean, + required?: boolean, + showCaret?: boolean, + showClearDate?: boolean, + + onChange?: (e: React.EventHandler>) => void, + onClearDate?: (e: React.EventHandler>) => void, + onFocus?: (e: React.EventHandler>) => void, + onKeyDownShiftTab?: (e: React.EventHandler>) => void, + onKeyDownTab?: (e: React.EventHandler>) => void, + + // i18n + phrases?: { + clearDate: string | JSX.Element, + } + } + type SingleDatePickerInput = React.ClassicComponentClass; + var SingleDatePickerInput: React.ClassicComponentClass; + + + + + interface DayPickerShape{ + enableOutsideDays?: boolean, + numberOfMonths?: number, + modifiers?: any, + orientation?: ScrollableOrientationShape, + withPortal?: boolean, + hidden?: boolean, + initialVisibleMonth?: () => moment.Moment, + + navPrev?: string | JSX.Element, + navNext?: string | JSX.Element, + + onDayClick?: (day: any, e: React.EventHandler>) => void, + onDayMouseEnter?: (day: any, e: React.EventHandler>) => void, + onDayMouseLeave?: (day: any, e: React.EventHandler>) => void, + onPrevMonthClick?: (e: React.EventHandler>) => void, + onNextMonthClick?: (e: React.EventHandler>) => void, + onOutsideClick?: (e: MouseEvent) => void, + + renderDay?: (day: any) => (string | JSX.Element), + + // i18n + monthFormat?: string, + } + type DayPicker = React.ClassicComponentClass; + var DayPicker: React.ClassicComponentClass; + + + + interface DayPickerRangeControllerShape{ + startDate?: momentPropTypes.momentObj, + endDate?: momentPropTypes.momentObj, + onDatesChange?: (arg: { startDate: any, endDate: any }) => void, + + focusedInput?: FocusedInputShape, + onFocusChange?: (arg: FocusedInputShape) => void, + + keepOpenOnDateSelect?: boolean, + minimumNights?: number, + isOutsideRange?: (day: any) => boolean, + isDayBlocked?: (day: any) => boolean, + isDayHighlighted?: (day: any) => boolean, + + // DayPicker props + enableOutsideDays?: boolean, + numberOfMonths?: number, + orientation?: ScrollableOrientationShape, + withPortal?: boolean, + hidden?: boolean, + initialVisibleMonth?: () => moment.Moment, + + navPrev?: string | JSX.Element, + navNext?: string | JSX.Element, + + onPrevMonthClick?: (e: React.EventHandler>) => void, + onNextMonthClick?: (e: React.EventHandler>) => void, + onOutsideClick?: (e: MouseEvent) => void, + renderDay?: (day: any) => (string | JSX.Element), + + // i18n + monthFormat?: string, + } + type DayPickerRangeController = React.ClassicComponentClass; + var DayPickerRangeController: React.ClassicComponentClass; + + + interface CalendarMonthGridShape{ + enableOutsideDays?: boolean, + firstVisibleMonthIndex?: number, + initialMonth?: momentPropTypes.momentObj, + isAnimating?: boolean, + numberOfMonths?: number, + modifiers?: any, + orientation?: ScrollableOrientationShape, + onDayClick?: (day: any, e: React.EventHandler>) => void, + onDayMouseEnter?: (day: any, e: React.EventHandler>) => void, + onDayMouseLeave?: (day: any, e: React.EventHandler>) => void, + onMonthTransitionEnd?: ()=> void, + renderDay?: (day: any) => (string | JSX.Element), + transformValue?: string, + + // i18n + monthFormat?: string, + } + type CalendarMonthGrid = React.ClassicComponentClass; + var CalendarMonthGrid: React.ClassicComponentClass; + + + + interface CalendarMonthShape{ + month?: momentPropTypes.momentObj, + isVisible?: boolean, + enableOutsideDays?: boolean, + modifiers?: any, + orientation?: ScrollableOrientationShape, + onDayClick?: (day: any, e: React.EventHandler>) => void, + onDayMouseEnter?: (day: any, e: React.EventHandler>) => void, + onDayMouseLeave?: (day: any, e: React.EventHandler>) => void, + renderDay?: (day: any) => (string | JSX.Element), + + // i18n + monthFormat?: string, + } + type CalendarMonth = React.ClassicComponentClass; + var CalendarMonth: React.ClassicComponentClass; + + + interface CalendarDayShape{ + day?: momentPropTypes.momentObj, + isOutsideDay?: boolean, + modifiers?: any, + onDayClick?: (day: any, e: React.EventHandler>) => void, + onDayMouseEnter?: (day: any, e: React.EventHandler>) => void, + onDayMouseLeave?: (day: any, e: React.EventHandler>) => void, + renderDay?: (day: any) => (string | JSX.Element), + } + type CalendarDay = React.ClassicComponentClass; + var CalendarDay: React.ClassicComponentClass; + + + + + var isInclusivelyAfterDay: (a: moment.Moment, b: moment.Moment) => boolean; + var isInclusivelyBeforeDay: (a: moment.Moment, b: moment.Moment) => boolean; + var isNextDay: (a: moment.Moment, b: moment.Moment) => boolean; + var isSameDay: (a: moment.Moment, b: moment.Moment) => boolean; + + var toISODateString: (date: moment.MomentInput, currentFormat: moment.MomentFormatSpecification) => string | null; + var toLocalizedDateString: (date: moment.MomentInput, currentFormat: moment.MomentFormatSpecification) => string | null; + + var toMomentObject: (dateString: moment.MomentInput, customFormat: moment.MomentFormatSpecification) => moment.Moment | null; +} diff --git a/react-dates/package.json b/react-dates/package.json new file mode 100644 index 0000000000..d5ac741601 --- /dev/null +++ b/react-dates/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "moment": ">=2.17.1" + } +} \ No newline at end of file diff --git a/react-dates/react-dates-tests.tsx b/react-dates/react-dates-tests.tsx new file mode 100644 index 0000000000..b975b1124b --- /dev/null +++ b/react-dates/react-dates-tests.tsx @@ -0,0 +1,357 @@ +import * as React from "react"; +import * as moment from "moment"; + +import { + CalendarDay, + CalendarMonth, + CalendarMonthGrid, + SingleDatePickerInput, + SingleDatePicker, + DayPicker, + DayPickerRangeController, + DateRangePickerInput, + DateRangePickerInputController, + DateRangePicker, + isInclusivelyAfterDay, + isInclusivelyBeforeDay, + isNextDay, + isSameDay, + toISODateString, + toLocalizedDateString, + toMomentObject} from "react-dates"; + + +class CalendarDayRenderingMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class CalendarDayRenderingFullTest extends React.Component<{}, {}> { + render() { + return day.toString()} + onDayClick={(day,e) => {}} + onDayMouseEnter={(day,e) => {}} + onDayMouseLeave={(day,e) => {}} + /> + } +} + +class CalendarMonthMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class CalendarMonthFullTest extends React.Component<{}, {}> { + render() { + return day.toString()} + onDayClick={(day,e) => {}} + onDayMouseEnter={(day,e) => {}} + onDayMouseLeave={(day,e) => {}} + /> + } +} + + + + +class SingleDatePickerInputMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class SingleDatePickerInputFullTest extends React.Component<{}, {}> { + render() { + return {}} + onClearDate={e => {}} + onFocus={e => {}} + onKeyDownShiftTab={e => {}} + onKeyDownTab={e => {}} + phrases={{clearDate: "clear"}} + placeholder="test" + required={false} + screenReaderMessage="arial-test" + showCaret={true} + showClearDate={true} + /> + } +} + + + + +class SingleDatePickerMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class SingleDatePickerFullTest extends React.Component<{}, {}> { + render() { + return moment()} + placeholder="test" + required={false} + showClearDate={true} + isDayBlocked={(day:any)=> false} + isOutsideRange={(day:any)=> false} + keepOpenOnDateSelect={true} + navNext="next" + navPrev="prev" + withPortal={false} + onDateChange={d => {}} + focused={false} + phrases={{closeDatePicker: Close}} + reopenPickerOnClearDates={true} + screenReaderInputMessage="arial-test" + withFullScreenPortal={true} + onFocusChange={arg => {}} + onNextMonthClick={e => {}} + onPrevMonthClick={e => {}} + numberOfMonths={2} + orientation="horizontal" + monthFormat="MM" + renderDay={day => day.toString()} + /> + } +} + + + +class DayPickerRangeControllerMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class DayPickerRangeControllerFullTest extends React.Component<{}, {}> { + render() { + return moment()} + hidden={false} + isDayBlocked={(day:any)=> false} + isDayHighlighted={(day:any)=> false} + isOutsideRange={(day:any)=> false} + keepOpenOnDateSelect={true} + minimumNights={3} + navNext="next" + navPrev="prev" + withPortal={false} + onDatesChange={arg => {}} + onFocusChange={arg => {}} + onNextMonthClick={e => {}} + onPrevMonthClick={e => {}} + onOutsideClick={e => {}} + enableOutsideDays={true} + numberOfMonths={2} + orientation="horizontal" + monthFormat="MM" + renderDay={day => day.toString()} + /> + } +} + + +class DayPickerTest extends React.Component<{}, {}> { + render() { + return + } +} + +class DayPickerFullTest extends React.Component<{}, {}> { + render() { + return {}} + onDayMouseEnter={(day,e)=>{}} + onDayMouseLeave={(day,e)=>{}} + initialVisibleMonth={() => moment()} + hidden={false} + navNext="next" + navPrev="prev" + withPortal={false} + onNextMonthClick={e => {}} + onPrevMonthClick={e => {}} + onOutsideClick={e => {}} + enableOutsideDays={true} + numberOfMonths={2} + orientation="horizontal" + monthFormat="MM" + renderDay={day => day.toString()} + /> + } +} + + + + +class DateRangePickerInputMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class DateRangePickerInputFullTest extends React.Component<{}, {}> { + render() { + return {}} + onEndDateChange={e => {}} + onEndDateFocus={e => {}} + onEndDateTab={e => {}} + onStartDateChange={e => {}} + onStartDateFocus={e => {}} + onStartDateShiftTab={e => {}} + showDefaultInputIcon={true} + required={false} + screenReaderMessage="arial-test" + showCaret={true} + showClearDates={true} + phrases={{clearDates: "clear"}} + /> + } +} + + + + + +class DateRangePickerInputControllerMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class DateRangePickerInputControllerFullTest extends React.Component<{}, {}> { + render() { + return {}} + onEndDateChange={e => {}} + onEndDateFocus={e => {}} + onEndDateTab={e => {}} + onStartDateChange={e => {}} + onStartDateFocus={e => {}} + onStartDateShiftTab={e => {}} + showDefaultInputIcon={true} + required={false} + screenReaderMessage="arial-test" + showCaret={true} + showClearDates={true} + phrases={{clearDates: "clear"}} + startDate="1.1.2020" + endDate="1.1.2020" + /> + } +} + + + + + + + + + + + +class DateRangePickerMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class DateRangePickerFullTest extends React.Component<{}, {}> { + render() { + return {arg.startDate; arg.endDate;}} + displayFormat="dd.mm.yyyy" + enableOutsideDays={true} + horizontalMargin={20} + initialVisibleMonth={() => moment()} + isDayBlocked={(day:any)=> false} + isOutsideRange={(day:any)=> false} + keepOpenOnDateSelect={true} + withPortal={false} + reopenPickerOnClearDates={true} + screenReaderInputMessage="arial-test" + withFullScreenPortal={true} + onFocusChange={arg => {}} + onNextMonthClick={e => {}} + onPrevMonthClick={e => {}} + numberOfMonths={2} + orientation="horizontal" + monthFormat="MM" + renderDay={day => day.toString()} + /> + } +} + + +const isInclusivelyAfterDayResult: boolean = isInclusivelyAfterDay(moment(),moment()); +const isInclusivelyBeforeDayResult: boolean = isInclusivelyBeforeDay(moment(),moment()); +const isNextDayDayResult: boolean = isNextDay(moment(),moment()); +const isSameDayResult: boolean = isSameDay(moment(),moment()); +const toISODateStringResult: string | null = toISODateString(moment(), "dd.mm.yyyy"); +const toLocalizedDateStringResult: string | null = toLocalizedDateString(moment(), "dd.mm.yyyy"); +const toMomentObjectResult: moment.Moment | null = toMomentObject(moment(), "dd.mm.yyyy"); + + \ No newline at end of file diff --git a/react-dates/tsconfig.json b/react-dates/tsconfig.json new file mode 100644 index 0000000000..7d246baede --- /dev/null +++ b/react-dates/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-dates-tests.tsx" + ] +} diff --git a/react-dnd-html5-backend/react-dnd-html5-backend-tests.ts b/react-dnd-html5-backend/react-dnd-html5-backend-tests.ts index 83ee1bc9ba..68703d062d 100644 --- a/react-dnd-html5-backend/react-dnd-html5-backend-tests.ts +++ b/react-dnd-html5-backend/react-dnd-html5-backend-tests.ts @@ -1,5 +1,3 @@ -"use strict"; - // Test adapted from the ReactDnD chess game tutorial: // http://gaearon.github.io/react-dnd/docs-tutorial.html diff --git a/react-dnd/UNUSED_FILES.txt b/react-dnd/UNUSED_FILES.txt deleted file mode 100644 index ff694923a2..0000000000 --- a/react-dnd/UNUSED_FILES.txt +++ /dev/null @@ -1 +0,0 @@ -react-dnd-test-backend.d.ts \ No newline at end of file diff --git a/react-dnd/react-dnd-test-backend.d.ts b/react-dnd/react-dnd-test-backend.d.ts deleted file mode 100644 index 095c890483..0000000000 --- a/react-dnd/react-dnd-test-backend.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -// Type definitions for React DnD HTML 5 Backend v2.0.0 -// Project: https://github.com/gaearon/react-dnd -// Definitions by: Asana -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module "react-dnd-test-backend" { - class TestBackend { - setup(): void; - teardown(): void; - connectDragSource(): void; - connectDropTarget(): void; - simulateBeginDrag(sourceIds: __ReactDnd.Identifier[], options?: {}): void; - simulatePublishDragSource(): void; - simulateHover(targetIds: __ReactDnd.Identifier[], options?: {}): void; - simulateDrop(): void; - simulateEndDrag(): void; - } - - export { TestBackend as default }; -} diff --git a/react-dnd/react-dnd-tests.ts b/react-dnd/react-dnd-tests.ts index fdef2b727c..0aabefd26e 100644 --- a/react-dnd/react-dnd-tests.ts +++ b/react-dnd/react-dnd-tests.ts @@ -1,6 +1,3 @@ -/// -"use strict"; - // Test adapted from the ReactDnD chess game tutorial: // http://gaearon.github.io/react-dnd/docs-tutorial.html @@ -14,7 +11,17 @@ import DropTarget = ReactDnd.DropTarget; import DragLayer = ReactDnd.DragLayer; import DragDropContext = ReactDnd.DragDropContext; import HTML5Backend, { getEmptyImage, NativeTypes } from "react-dnd-html5-backend"; -import TestBackend from "react-dnd-test-backend"; +declare class TestBackend { + setup(): void; + teardown(): void; + connectDragSource(): void; + connectDropTarget(): void; + simulateBeginDrag(sourceIds: __ReactDnd.Identifier[], options?: {}): void; + simulatePublishDragSource(): void; + simulateHover(targetIds: __ReactDnd.Identifier[], options?: {}): void; + simulateDrop(): void; + simulateEndDrag(): void; +} // Game Component // ---------------------------------------------------------------------- diff --git a/react-dropzone/react-dropzone-tests.tsx b/react-dropzone/react-dropzone-tests.tsx index 322fd82e8c..ec6d5fa763 100644 --- a/react-dropzone/react-dropzone-tests.tsx +++ b/react-dropzone/react-dropzone-tests.tsx @@ -1,5 +1,3 @@ -/// -/// import * as React from 'react'; import * as Dropzone from 'react-dropzone'; diff --git a/react-ga/react-ga-tests.tsx b/react-ga/react-ga-tests.tsx index 10770f04f5..0db1be21c2 100644 --- a/react-ga/react-ga-tests.tsx +++ b/react-ga/react-ga-tests.tsx @@ -1,7 +1,8 @@ -/// - import * as ga from "react-ga"; +declare function describe(desc: string, f: () => void): void; +declare function it(desc: string, f: () => void): void; + describe("Testing react-ga initialize object", () => { it("Able to initialize react-ga object", () => { ga.initialize("UA-65432-1"); diff --git a/react-helmet/react-helmet-tests.tsx b/react-helmet/react-helmet-tests.tsx index 3a4a3f09d7..e6b78955b3 100644 --- a/react-helmet/react-helmet-tests.tsx +++ b/react-helmet/react-helmet-tests.tsx @@ -1,6 +1,3 @@ - -/// - import * as React from 'react'; import * as Helmet from 'react-helmet'; diff --git a/react-highlighter/index.d.ts b/react-highlighter/index.d.ts index 74468c9b7c..6e34a4dbe3 100644 --- a/react-highlighter/index.d.ts +++ b/react-highlighter/index.d.ts @@ -2,6 +2,9 @@ // Project: https://github.com/helior/react-highlighter // Definitions by: Pedro Pereira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// declare var Highlight: any; export = Highlight; diff --git a/react-infinite/react-infinite-tests.tsx b/react-infinite/react-infinite-tests.tsx index 807fc67498..ea68999afc 100644 --- a/react-infinite/react-infinite-tests.tsx +++ b/react-infinite/react-infinite-tests.tsx @@ -1,6 +1,3 @@ -/// -/// - import * as React from 'react'; import Infinite = require('react-infinite'); diff --git a/react-input-calendar/react-input-calendar-tests.tsx b/react-input-calendar/react-input-calendar-tests.tsx index aaab1dc398..4cd465d9c5 100644 --- a/react-input-calendar/react-input-calendar-tests.tsx +++ b/react-input-calendar/react-input-calendar-tests.tsx @@ -1,6 +1,3 @@ -/// -/// - import * as ReactInputCalendar from 'react-input-calendar'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; diff --git a/react-intl/index.d.ts b/react-intl/index.d.ts index a9629c4009..ed0b639f92 100644 --- a/react-intl/index.d.ts +++ b/react-intl/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-intl 2.2.0 +// Type definitions for react-intl 2.2.1 // Project: http://formatjs.io/react/ // Definitions by: Bruno Grieder , Christian Droulers , Fedor Nezhivoi , Till Wolff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -14,7 +14,7 @@ declare namespace ReactIntl { pluralRuleFunction?: (n: number, ord: boolean) => string; } - function injectIntl | React.StatelessComponent>(component: T): T; + function injectIntl(component: React.ComponentClass | React.StatelessComponent): React.ComponentClass; function addLocaleData(data: Locale[] | Locale): void; @@ -47,7 +47,7 @@ declare namespace ReactIntl { } interface InjectedIntlProps { - intl?: InjectedIntl + intl: InjectedIntl } namespace IntlComponent { diff --git a/react-intl/react-intl-tests.tsx b/react-intl/react-intl-tests.tsx index 160a37bc0f..d3477aaa11 100644 --- a/react-intl/react-intl-tests.tsx +++ b/react-intl/react-intl-tests.tsx @@ -3,14 +3,13 @@ * Updated by Fedor Nezhivoi */ -/// - import * as React from "react" import * as reactMixin from "react-mixin" import { IntlProvider, InjectedIntl, + InjectedIntlProps, addLocaleData, hasLocaleData, injectIntl, @@ -31,11 +30,35 @@ addLocaleData(reactIntlEn); console.log(hasLocaleData("en")); interface SomeComponentProps { - className: string, - intl?: InjectedIntl + className: string } -class SomeComponent extends React.Component { +const SomeFunctionalComponentWithIntl = injectIntl(({ + intl: { + formatDate, + formatHTMLMessage, + formatNumber, + formatMessage, + formatPlural, + formatRelative, + formatTime + }, + className +}) => { + const formattedDate = formatDate(new Date(), { format: "short" }); + const formattedTime = formatTime(new Date(), { format: "short" }); + const formattedRelative = formatRelative(new Date().getTime(), { format: "short" }); + const formattedNumber = formatNumber(123, { format: "short" }); + const formattedPlural = formatPlural(1, { one: "hai!" }); + const formattedMessage = formatMessage({ id: "hello", defaultMessage: "Hello {name}!" }, { name: "Roger" }); + const formattedHTMLMessage = formatHTMLMessage({ id: "hello", defaultMessage: "Hello {name}!" }, { name: "Roger" }); + return ( +
              +
              + ); +}); + +class SomeComponent extends React.Component { static propTypes: React.ValidationMap = { intl: intlShape.isRequired }; @@ -145,7 +168,7 @@ class SomeComponent extends React.Component { } } -const SomeComponentWithIntl = injectIntl(SomeComponent); +const SomeComponentWithIntl: React.ComponentClass = injectIntl(SomeComponent); class TestApp extends React.Component<{}, {}> { public render(): React.ReactElement<{}> { @@ -162,6 +185,7 @@ class TestApp extends React.Component<{}, {}> { return ( + ); } diff --git a/react-intl/v1/react-intl-tests.tsx b/react-intl/v1/react-intl-tests.tsx index 6abebe36cd..c7834b6583 100644 --- a/react-intl/v1/react-intl-tests.tsx +++ b/react-intl/v1/react-intl-tests.tsx @@ -2,8 +2,6 @@ * Created by Bruno Grieder */ -/// - import * as React from 'react' import * as reactMixin from 'react-mixin' diff --git a/react-jsonschema-form/index.d.ts b/react-jsonschema-form/index.d.ts index 6786862ea8..6ac5f40109 100644 --- a/react-jsonschema-form/index.d.ts +++ b/react-jsonschema-form/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for react-jsonschema-form 0.38.1 +// Type definitions for react-jsonschema-form 0.43.0 // Project: https://github.com/mozilla-services/react-jsonschema-form -// Definitions by: Dan Fox +// Definitions by: Dan Fox , Jon Surrell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -14,6 +14,7 @@ declare module "react-jsonschema-form" { widgets?: {}; fields?: {}; noValidate?: boolean; + noHtml5Validate?: boolean; showErrorList?: boolean; validate?: (formData: any, errors: any) => any; onChange?: (e: IChangeEvent) => any; diff --git a/react-jsonschema-form/react-jsonschema-form-tests.tsx b/react-jsonschema-form/react-jsonschema-form-tests.tsx index 9f2c05086d..c8d49a7628 100644 --- a/react-jsonschema-form/react-jsonschema-form-tests.tsx +++ b/react-jsonschema-form/react-jsonschema-form-tests.tsx @@ -78,6 +78,7 @@ export class Example extends React.Component { uiSchema={uiSchema} showErrorList={false} noValidate={false} + noHtml5Validate={false} formData={this.state} onChange={(formData) => this.setState({formData})} /> }
              diff --git a/react-leaflet/index.d.ts b/react-leaflet/index.d.ts index 2399947c7d..eff286623a 100644 --- a/react-leaflet/index.d.ts +++ b/react-leaflet/index.d.ts @@ -111,7 +111,7 @@ interface LayerProps extends LeafletInteractionEvents { interface MarkerProps extends LayerProps, LeafletDraggingEvents { position: Leaflet.LatLngExpression; draggable?: boolean; - icon?: Leaflet.Icon; + icon?: Leaflet.BaseIcon; zIndexOffset?: number; opacity?: number; } diff --git a/react-leaflet/react-leaflet-tests.tsx b/react-leaflet/react-leaflet-tests.tsx index bb78ac7264..763e719de1 100644 --- a/react-leaflet/react-leaflet-tests.tsx +++ b/react-leaflet/react-leaflet-tests.tsx @@ -179,6 +179,18 @@ export class CustomComponent extends Component { } } +export class MarkerWithDivIconExample extends Component { + render() { + return ( + + + + ) + } +} + // draggable-marker.js export class DraggableExample extends Component { state = { diff --git a/react-mdl/index.d.ts b/react-mdl/index.d.ts index 9f962d0156..6265f11ec1 100644 --- a/react-mdl/index.d.ts +++ b/react-mdl/index.d.ts @@ -615,4 +615,6 @@ declare namespace __ReactMDL { title?: string; } class Tooltip extends __MDLComponent { } + + class MDLComponent extends React.Component<{ recursive?: boolean }, {}> { } } diff --git a/react-mdl/react-mdl-tests.tsx b/react-mdl/react-mdl-tests.tsx index 88ef81a7a4..9243eaa32c 100644 --- a/react-mdl/react-mdl-tests.tsx +++ b/react-mdl/react-mdl-tests.tsx @@ -22,7 +22,8 @@ import {Chip, ChipContact, Switch, Tabs, Tab, Textfield, - Tooltip} from 'react-mdl'; + Tooltip, + MDLComponent} from 'react-mdl'; // all tests are from the examples provided here: https://tleunen.github.io/react-mdl/ @@ -1071,3 +1072,14 @@ React.createClass({ ); } }); + +// MDLComponent tests +React.createClass({ + render: function() { + return ( + +
              + + ) + } +}); diff --git a/react-mixin/react-mixin-tests.tsx b/react-mixin/react-mixin-tests.tsx index 04f6f4b202..f275869a9e 100644 --- a/react-mixin/react-mixin-tests.tsx +++ b/react-mixin/react-mixin-tests.tsx @@ -1,6 +1,3 @@ - -/// - import reactMixin = require('react-mixin'); import * as React from 'react'; diff --git a/react-modal/index.d.ts b/react-modal/index.d.ts index 4e038b416c..afec7250e2 100644 --- a/react-modal/index.d.ts +++ b/react-modal/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for react-modal 1.6 // Project: https://github.com/reactjs/react-modal -// Definitions by: Rajab Shakirov , Drew Noakes +// Definitions by: Rajab Shakirov , Drew Noakes , Thomas B Homburg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -12,13 +12,11 @@ export = ReactModal; declare namespace ReactModal { export interface Styles { - style?: { - content?: { - [key: string]: any; - }; - overlay?: { - [key: string]: any; - }; + content?: { + [key: string]: any; + }; + overlay?: { + [key: string]: any; }; } @@ -32,7 +30,7 @@ declare namespace ReactModal { /* Function that will be run after the modal has opened. */ onAfterOpen?: () => void; /* Function that will be run when the modal is requested to be closed, prior to actually closing. */ - onRequestClose?: () => void; + onRequestClose?: (event: (MouseEvent | KeyboardEvent)) => void; /* Number indicating the milliseconds to wait before closing the modal. Defaults to zero (no timeout). */ closeTimeoutMS?: number; /* Boolean indicating if the appElement should be hidden. Defaults to true. */ diff --git a/react-native/index.d.ts b/react-native/index.d.ts index 2f95939db6..e120301923 100644 --- a/react-native/index.d.ts +++ b/react-native/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-native 0.37 +// Type definitions for react-native 0.42 // Project: https://github.com/facebook/react-native // Definitions by: Needs A Maintainer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -1098,7 +1098,7 @@ declare module "react" { /** * Callback that is called when the text input's text changes. */ - onChange?: (event: { nativeEvent: { text: string } }) => void + onChange?: (event: { nativeEvent: { text: string, contentSize: { width: number, height: number }, target: number, eventCount: number } }) => void /** * Callback that is called when the text input's text changes. @@ -1849,13 +1849,13 @@ declare module "react" { /** * The style of the content container(View) when behavior is 'position'. */ - contentContainerStyle: ViewStyle + contentContainerStyle?: ViewStyle /** * This is the distance between the top of the user screen and the react native view, * may be non-zero in some use cases. */ - keyboardVerticalOffset: number + keyboardVerticalOffset?: number ref?: Ref } @@ -4917,7 +4917,7 @@ declare module "react" { interface PlatformStatic { OS: PlatformOSType - Version?: number + Version: number /** * @see https://facebook.github.io/react-native/docs/platform-specific-code.html#content @@ -5413,11 +5413,6 @@ declare module "react" { */ onScrollAnimationEnd?: () => void - /** - * When false, the content does not scroll. The default value is true - */ - scrollEnabled?: boolean // true - /** * This controls how often the scroll event will be fired while scrolling (in events per seconds). * A higher number yields better accuracy for code that is tracking the scroll position, @@ -5452,7 +5447,7 @@ declare module "react" { * This can be used for paginating through children that have lengths smaller than the scroll view. * Used in combination with snapToAlignment. */ - snapToInterval?: number + snapToInterval?: number[] /** * An array of child indices determining which children get docked to the @@ -5489,6 +5484,15 @@ declare module "react" { */ scrollPerfTag?: string + /** + * Used to override default value of overScroll mode. + + * Possible values: + * - 'auto' - Default value, allow a user to over-scroll this view only if the content is large enough to meaningfully scroll. + * - 'always' - Always allow a user to over-scroll this view. + * - 'never' - Never allow a user to over-scroll this view. + */ + overScrollMode?: 'auto' | 'always' | 'never' } export interface ScrollViewProperties extends ViewProperties, ScrollViewPropertiesIOS, ScrollViewPropertiesAndroid, Touchable, React.Props { @@ -5524,7 +5528,7 @@ declare module "react" { * and moves in synchrony with the touch; dragging upwards cancels the * dismissal. */ - keyboardDismissMode?: string + keyboardDismissMode?: 'none' | 'interactive' | 'on-drag' /** * When false tapping outside of the focused text input when the keyboard @@ -5532,16 +5536,16 @@ declare module "react" { * taps and the keyboard will not dismiss automatically. The default value * is false. */ - keyboardShouldPersistTaps?: boolean - - /** - * Called when scrollable content view of the ScrollView changes. - * Handler function is passed the content width and content height as parameters: (contentWidth, contentHeight) - * It's implemented using onLayout handler attached to the content container which this ScrollView renders. - * - */ - onContentSizeChange?: (w: number, h: number) => void - + keyboardShouldPersistTaps?: boolean | 'always' | 'never' | 'handled' + + /** + * Called when scrollable content view of the ScrollView changes. + * Handler function is passed the content width and content height as parameters: (contentWidth, contentHeight) + * It's implemented using onLayout handler attached to the content container which this ScrollView renders. + * + */ + onContentSizeChange?: (w: number, h: number) => void + /** * Fires at most once per frame during scrolling. * The frequency of the events can be contolled using the scrollEventThrottle prop. @@ -5575,6 +5579,11 @@ declare module "react" { */ pagingEnabled?: boolean + /** + * When false, the content does not scroll. The default value is true + */ + scrollEnabled?: boolean // true + /** * Experimental: When true offscreen child views (whose `overflow` value is * `hidden`) are removed from their native backing superview when offscreen. @@ -7635,7 +7644,7 @@ declare module "react" { onNavigateBack?(): void; } - type SubViewRenderer = (subViewProps: SubViewProps) => JSX.Element; + type SubViewRenderer = (subViewProps: SubViewProps) => JSX.Element | null; export interface NavigationHeaderProps extends NavigationSceneRendererProps { onNavigateBack?(): void, @@ -7964,6 +7973,34 @@ declare module "react" { */ cropImage( uri: string, cropData: ImageCropData, success: (uri: string) => void, failure: (error: Object) => void ): void } + + export interface ARTShapeProps { + d: string, + strokeWidth: number, + strokeDash?: number[], + stroke: string + } + + export interface ARTSurfaceProps { + style: ViewStyle, + width: number, + height: number + } + + export interface ShapeStatic extends React.ComponentClass { + } + + export interface SurfaceStatic extends React.ComponentClass { + } + + export interface ARTStatic { + Shape: ShapeStatic, + Surface: SurfaceStatic + } + + export interface KeyboardStatic extends NativeEventEmitter { + dismiss: ()=>void + } ////////////////////////////////////////////////////////////////////////// // @@ -7973,6 +8010,8 @@ declare module "react" { // TODO: The following components need to be added // - [ ] ART + export var ART: ARTStatic + export type ART = ARTStatic export var ActivityIndicator: ActivityIndicatorStatic export type ActivityIndicator = ActivityIndicatorStatic @@ -8153,7 +8192,7 @@ declare module "react" { export var IntentAndroid: IntentAndroidStatic export type IntentAndroid = IntentAndroidStatic - export var Keyboard: NativeEventEmitter + export var Keyboard: KeyboardStatic export var KeyboardAvoidingView: KeyboardAvoidingViewStatic export type KeyboardAvoidingView = KeyboardAvoidingViewStatic @@ -8314,11 +8353,11 @@ declare module "react" { declare global { const global: React.GlobalStatic; function require(name: string): any; -} -/** - * This variable is set to true when react-native is running in Dev mode - * Typical usage: - * if (__DEV__) console.log('Running in dev mode') - */ -declare var __DEV__: boolean + /** + * This variable is set to true when react-native is running in Dev mode + * Typical usage: + * if (__DEV__) console.log('Running in dev mode') + */ + var __DEV__: boolean +} diff --git a/react-native/test/animated.tsx b/react-native/test/animated.tsx index 632f2c0151..3b3457384c 100644 --- a/react-native/test/animated.tsx +++ b/react-native/test/animated.tsx @@ -1,5 +1,3 @@ -/// - import * as React from 'react-native' import { diff --git a/react-native/test/index.tsx b/react-native/test/index.tsx index 6e05cdeabe..32bcbe931b 100644 --- a/react-native/test/index.tsx +++ b/react-native/test/index.tsx @@ -1,8 +1,4 @@ - /* - -Note: This must be compiled with the target set to ES6 - The content of index.io.js could be something like 'use strict'; @@ -12,13 +8,8 @@ The content of index.io.js could be something like AppRegistry.registerComponent('MopNative', () => Welcome); - For a list of complete Typescript examples: check https://github.com/bgrieder/RNTSExplorer - - */ - -/// - +*/ import * as React from 'react-native' import { diff --git a/react-onclickoutside/react-onclickoutside-tests.tsx b/react-onclickoutside/react-onclickoutside-tests.tsx index dabba332b1..fc782bb68c 100644 --- a/react-onclickoutside/react-onclickoutside-tests.tsx +++ b/react-onclickoutside/react-onclickoutside-tests.tsx @@ -1,8 +1,3 @@ -// React onClickOutside Test -// ================================================================================ - -// Imports -// -------------------------------------------------------------------------------- import * as React from "react" import { Component, StatelessComponent, MouseEvent } from "react" import { render } from "react-dom" diff --git a/react-props-decorators/react-props-decorators-tests.ts b/react-props-decorators/react-props-decorators-tests.ts index 562d4f3d12..654c2df98f 100644 --- a/react-props-decorators/react-props-decorators-tests.ts +++ b/react-props-decorators/react-props-decorators-tests.ts @@ -1,6 +1,3 @@ - -/// - import * as React from 'react'; import { propTypes, defaultProps } from 'react-props-decorators'; diff --git a/react-redux/index.d.ts b/react-redux/index.d.ts index 2d76aaac00..8daa310b51 100644 --- a/react-redux/index.d.ts +++ b/react-redux/index.d.ts @@ -49,14 +49,9 @@ export interface InferableComponentDecorator { export declare function connect(): InferableComponentDecorator; export declare function connect( - mapStateToProps: FuncOrSelf>, - mapDispatchToProps?: FuncOrSelf | MapDispatchToPropsObject> -): ComponentDecorator; - -export declare function connect( - mapStateToProps: FuncOrSelf>, - mapDispatchToProps: FuncOrSelf | MapDispatchToPropsObject>, - mergeProps: MergeProps, + mapStateToProps?: FuncOrSelf>, + mapDispatchToProps?: FuncOrSelf | MapDispatchToPropsObject>, + mergeProps?: MergeProps, options?: Options ): ComponentDecorator; diff --git a/react-redux/react-redux-tests.tsx b/react-redux/react-redux-tests.tsx index bbe84289ff..5d1f32765f 100644 --- a/react-redux/react-redux-tests.tsx +++ b/react-redux/react-redux-tests.tsx @@ -258,8 +258,9 @@ function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProp connect(mapStateToProps2, actionCreators, mergeProps)(TodoApp); - - +//https://github.com/DefinitelyTyped/DefinitelyTyped/issues/14622#issuecomment-279820358 +//Allow for undefined mapStateToProps +connect(undefined, mapDispatchToProps6)(TodoApp); interface TestProp { property1: number; diff --git a/react-relay/index.d.ts b/react-relay/index.d.ts index 9c45ed9c7c..a693527e3e 100644 --- a/react-relay/index.d.ts +++ b/react-relay/index.d.ts @@ -7,13 +7,15 @@ declare module "react-relay" { import * as React from "react"; + type ClientMutationID = string; + /** Fragments are a hash of functions */ interface Fragments { [query: string]: ((variables?: RelayVariables) => string) } interface CreateContainerOpts { - initialVariables?: Object + initialVariables?: any fragments: Fragments prepareVariables?(prevVariables: RelayVariables): RelayVariables } @@ -31,6 +33,24 @@ declare module "react-relay" { response: any } + type RelayMutationStatus = + 'UNCOMMITTED' | // Transaction hasn't yet been sent to the server. Transaction can be committed or rolled back. + 'COMMIT_QUEUED' | // Transaction was committed but another transaction with the same collision key is pending, so the transaction has been queued to send to the server. + 'COLLISION_COMMIT_FAILED' | //Transaction was queued for commit but another transaction with the same collision key failed. All transactions in the collision queue, including this one, have been failed. Transaction can be recommitted or rolled back. + 'COMMITTING' | // Transaction is waiting for the server to respond. + 'COMMIT_FAILED'; + + class RelayMutationTransaction { + applyOptimistic(): RelayMutationTransaction; + commit(): RelayMutationTransaction | null; + recommit(): void; + rollback(): void; + getError(): Error; + getStatus(): RelayMutationStatus; + getHash(): string; + getID(): ClientMutationID; + } + interface RelayMutationRequest { getQueryString(): string getVariables(): RelayVariables @@ -104,7 +124,7 @@ declare module "react-relay" { renderFailure?(error: Error, retry: Function): JSX.Element } - type ReadyStateEvent = + type ReadyStateEvent = 'ABORT' | 'CACHE_RESTORED_REQUIRED' | 'CACHE_RESTORE_FAILED' | @@ -128,7 +148,13 @@ declare module "react-relay" { } interface RelayProp { - variables: any - setVariables(variables: Object, onReadyStateChange?: OnReadyStateChange): void + readonly route: { name: string; }; // incomplete, also has params and queries + readonly variables: any; + readonly pendingVariables?: any | null; + setVariables(variables: any, onReadyStateChange?: OnReadyStateChange): void; + forceFetch(variables: any, onReadyStateChange?: OnReadyStateChange): void; + hasOptimisticUpdate(record: any): boolean; + getPendingTransactions(record: any): RelayMutationTransaction[]; + commitUpdate: (mutation: Mutation, callbacks?: StoreUpdateCallbacks) => any; } } diff --git a/react-relay/react-relay-tests.tsx b/react-relay/react-relay-tests.tsx index 7160e60b0a..091909cabd 100644 --- a/react-relay/react-relay-tests.tsx +++ b/react-relay/react-relay-tests.tsx @@ -74,10 +74,17 @@ class StubbedArtwork extends React.Component { const props = { artwork: { title: "CHAMPAGNE FORMICA FLAG" }, relay: { + route: { + name: "champagne" + }, variables: { artworkID: "champagne-formica-flag", }, setVariables: () => {}, + forceFetch: () => {}, + hasOptimisticUpdate: () => false, + getPendingTransactions: (): Relay.RelayMutationTransaction[] => undefined, + commitUpdate: () => {}, } } return diff --git a/react-router-bootstrap/react-router-bootstrap-tests.tsx b/react-router-bootstrap/react-router-bootstrap-tests.tsx index d4f8733c03..7816933fe6 100644 --- a/react-router-bootstrap/react-router-bootstrap-tests.tsx +++ b/react-router-bootstrap/react-router-bootstrap-tests.tsx @@ -1,16 +1,8 @@ -// React-Router-Bootstrap Test -// ================================================================================ -/// -/// - -// Imports -// -------------------------------------------------------------------------------- import * as React from 'react'; import { Component, CSSProperties } from 'react'; import { Button } from 'react-bootstrap'; import { LinkContainer, IndexLinkContainer } from 'react-router-bootstrap' - export class ReactRouterBootstrapTest extends Component { callback() { alert('Callback: ' + JSON.stringify(arguments)); @@ -20,7 +12,7 @@ export class ReactRouterBootstrapTest extends Component { let style: CSSProperties = { padding: '50px' }; return (
              - +
              diff --git a/react-router-redux/index.d.ts b/react-router-redux/index.d.ts index 0736359b21..9f8044a7c0 100644 --- a/react-router-redux/index.d.ts +++ b/react-router-redux/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for react-router-redux 4.0 // Project: https://github.com/rackt/react-router-redux -// Definitions by: Isman Usoh , Noah Shipley , Dimitri Rosenberg , Karol Janyst +// Definitions by: Isman Usoh , Noah Shipley , Dimitri Rosenberg , Karol Janyst , Dovydas Navickas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -51,7 +51,7 @@ export interface SyncHistoryWithStoreOptions { } export interface HistoryUnsubscribe { - unsubscribe(): undefined; + unsubscribe(): void; } export function routerReducer(state?: RouterState, action?: Action): RouterState; diff --git a/react-router-redux/v3/index.d.ts b/react-router-redux/v3/index.d.ts index fdea00bbc6..be706bdcc8 100644 --- a/react-router-redux/v3/index.d.ts +++ b/react-router-redux/v3/index.d.ts @@ -34,8 +34,8 @@ export interface RouteActions { } export interface HistoryMiddleware extends Redux.Middleware { - listenForReplays(store: Redux.Store, selectLocationState?: Function): undefined; - unsubscribe(): undefined; + listenForReplays(store: Redux.Store, selectLocationState?: Function): void; + unsubscribe(): void; } export function routeReducer(state?: any, options?: any): Redux.Reducer; diff --git a/react-router/index.d.ts b/react-router/index.d.ts index be48438489..05fe9b3371 100644 --- a/react-router/index.d.ts +++ b/react-router/index.d.ts @@ -8,6 +8,7 @@ // Kostya Esmukov // John Reilly // Karol Janyst +// Dovydas Navickas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 diff --git a/react-router/lib/IndexRoute.d.ts b/react-router/lib/IndexRoute.d.ts index 84b70d7874..44b8c82919 100644 --- a/react-router/lib/IndexRoute.d.ts +++ b/react-router/lib/IndexRoute.d.ts @@ -15,8 +15,8 @@ type ComponentsCallback = (err: any, components: RouteComponents) => any; export interface IndexRouteProps { component?: RouteComponent; components?: RouteComponents; - getComponent?(nextState: RouterState, callback: ComponentCallback): undefined; - getComponents?(nextState: RouterState, callback: ComponentsCallback): undefined; + getComponent?: (nextState: RouterState, callback: ComponentCallback) => void; + getComponents?: (nextState: RouterState, callback: ComponentsCallback) => void; onEnter?: EnterHook; onChange?: ChangeHook; onLeave?: LeaveHook; diff --git a/react-router/lib/Route.d.ts b/react-router/lib/Route.d.ts index 1c0969da51..9063ac8b45 100644 --- a/react-router/lib/Route.d.ts +++ b/react-router/lib/Route.d.ts @@ -20,12 +20,12 @@ declare const Route: Route; export default Route; -type RouteCallback = (err: any, route: PlainRoute) => any; -type RoutesCallback = (err: any, routesArray: PlainRoute[]) => any; +type RouteCallback = (err: any, route: PlainRoute) => void; +type RoutesCallback = (err: any, routesArray: PlainRoute[]) => void; export interface PlainRoute extends RouteProps { childRoutes?: PlainRoute[]; - getChildRoutes?(partialNextState: LocationState, callback: RoutesCallback): undefined; + getChildRoutes?: (partialNextState: LocationState, callback: RoutesCallback) => void; indexRoute?: PlainRoute; - getIndexRoute?(partialNextState: LocationState, callback: RouteCallback): undefined; + getIndexRoute?: (partialNextState: LocationState, callback: RouteCallback) => void; } diff --git a/react-router/lib/Router.d.ts b/react-router/lib/Router.d.ts index daae78411a..02550026b9 100644 --- a/react-router/lib/Router.d.ts +++ b/react-router/lib/Router.d.ts @@ -36,8 +36,8 @@ export type ChangeHook = (prevState: RouterState, nextState: RouterState, replac export type RouteHook = (nextLocation?: Location) => any; export interface RedirectFunction { - (location: LocationDescriptor): undefined; - (state: LocationState, pathname: Pathname | Path, query?: Query): undefined; + (location: LocationDescriptor): void; + (state: LocationState, pathname: Pathname | Path, query?: Query): void; } export interface RouterState { @@ -47,11 +47,11 @@ export interface RouterState { components: RouteComponent[]; } -type LocationFunction = (location: LocationDescriptor) => any; -type GoFunction = (n: number) => any; -type NavigateFunction = () => any; +type LocationFunction = (location: LocationDescriptor) => void; +type GoFunction = (n: number) => void; +type NavigateFunction = () => void; type ActiveFunction = (location: LocationDescriptor, indexOnly?: boolean) => boolean; -type LeaveHookFunction = (route: any, callback: RouteHook) => any; +type LeaveHookFunction = (route: any, callback: RouteHook) => void; type CreatePartFunction = (path: Path, query?: any) => Part; export interface InjectedRouter { diff --git a/react-router/lib/match.d.ts b/react-router/lib/match.d.ts index a99561e6ba..82c19e83f6 100644 --- a/react-router/lib/match.d.ts +++ b/react-router/lib/match.d.ts @@ -18,6 +18,6 @@ interface MatchHistoryArgs extends MatchArgs { history: History; } -export type MatchCallback = (error: any, redirectLocation: Location, renderProps: any) => any; +export type MatchCallback = (error: any, redirectLocation: Location, renderProps: any) => void; -export default function match(args: MatchLocationArgs | MatchHistoryArgs, cb: MatchCallback): undefined; +export default function match(args: MatchLocationArgs | MatchHistoryArgs, cb: MatchCallback): void; diff --git a/react-router/lib/withRouter.d.ts b/react-router/lib/withRouter.d.ts index 25f9d357c7..209c01f913 100644 --- a/react-router/lib/withRouter.d.ts +++ b/react-router/lib/withRouter.d.ts @@ -6,4 +6,7 @@ interface Options { type ComponentConstructor

              = ComponentClass

              | StatelessComponent

              ; -export default function withRouter

              (component: ComponentConstructor

              , options?: Options): ComponentClass

              ; +declare function withRouter(component: ComponentConstructor

              & S, options?: Options): ComponentClass

              & S; +declare function withRouter

              (component: ComponentConstructor

              , options?: Options): ComponentClass

              ; + +export default withRouter; diff --git a/react-router/react-router-tests.tsx b/react-router/react-router-tests.tsx index f8be6c3326..314c78c6ce 100644 --- a/react-router/react-router-tests.tsx +++ b/react-router/react-router-tests.tsx @@ -27,7 +27,7 @@ import { createHistory, History } from "history"; const routerHistory = useRouterHistory(createHistory)({ basename: "/test" }); interface CustomHistory { - test(): undefined; + test(): void; } type CombinedHistory = History & CustomHistory; @@ -81,6 +81,7 @@ interface DashboardProps { } class Dashboard extends React.Component { + static staticMethodToBeHoisted(): void {} navigate() { var router = this.props.router; @@ -102,6 +103,8 @@ class Dashboard extends React.Component { const DashboardWithRouter = withRouter(Dashboard); +DashboardWithRouter.staticMethodToBeHoisted(); + class NotFound extends React.Component<{}, {}> { render() { diff --git a/react-scroll/react-scroll-tests.tsx b/react-scroll/react-scroll-tests.tsx index b5d2fb2245..63db573722 100644 --- a/react-scroll/react-scroll-tests.tsx +++ b/react-scroll/react-scroll-tests.tsx @@ -1,5 +1,3 @@ -/// - import * as React from 'react'; import { Link, Element, scroller } from 'react-scroll'; diff --git a/react-select/index.d.ts b/react-select/index.d.ts index 5393888f3b..789512661f 100644 --- a/react-select/index.d.ts +++ b/react-select/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-select v1.0.0 +// Type definitions for react-select 1.0 // Project: https://github.com/JedWatson/react-select // Definitions by: ESQUIBET Hugo , Gilad Gray , Izaak Baker , Tadas Dailyda , Mark Vujevits , Mike Deverell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -23,7 +23,7 @@ declare namespace ReactSelectClass { /** Text for rendering */ label?: string; /** Value for searching */ - value?: string | number; + value?: string | number | boolean; /** * Allow this option to be cleared * @default true @@ -238,7 +238,7 @@ declare namespace ReactSelectClass { /** * onChange handler: function (newValue) {} */ - onChange?: (newValue: Option | Option[]) => void; + onChange?: (newValue: Option | Option[] | null) => void; /** * fires when the menu is closed */ @@ -397,6 +397,11 @@ declare namespace ReactSelectClass { export interface ReactAsyncSelectProps extends ReactSelectProps { + /** + * Whether to auto-load the default async options set. + */ + autoload?: boolean; + /** * object to use to cache results; can be null to disable cache */ diff --git a/react-sortable-hoc/index.d.ts b/react-sortable-hoc/index.d.ts index 64a17f4800..a9ef36379c 100644 --- a/react-sortable-hoc/index.d.ts +++ b/react-sortable-hoc/index.d.ts @@ -7,7 +7,7 @@ declare module 'react-sortable-hoc' { import React = require('react'); - export type Axis = 'x' | 'y'; + export type Axis = 'x' | 'y' | 'xy'; export type Offset = number | string; diff --git a/react-sortable-hoc/react-sortable-hoc-tests.tsx b/react-sortable-hoc/react-sortable-hoc-tests.tsx index 0e90f9aa0a..8f10b69a17 100644 --- a/react-sortable-hoc/react-sortable-hoc-tests.tsx +++ b/react-sortable-hoc/react-sortable-hoc-tests.tsx @@ -8,6 +8,7 @@ interface SortableItemProps { interface SortableListProps { items: Array; + axis: 'x' | 'y' | 'xy' } type SortableComponentState = SortableListProps; @@ -40,12 +41,15 @@ class SortableComponent extends React.Component { public constructor() { super(); - this.state = { items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6'] }; + this.state = { + items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6'], + axis: 'x' + }; this._onSortEnd = this._handleSotEnd.bind(this); } public render(): JSX.Element { - return ; + return ; } } diff --git a/react-spinkit/index.d.ts b/react-spinkit/index.d.ts index 05955e3f53..24de75a032 100644 --- a/react-spinkit/index.d.ts +++ b/react-spinkit/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for react-spinkit 1.1.4 // Project: https://github.com/KyleAMathews/react-spinkit -// Definitions by: Qubo , Mleko +// Definitions by: Qubo , Mleko , Tom Crockett // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -8,7 +8,22 @@ declare namespace spinner { export interface SpinnerProps { - spinnerName?: string; + /** + * Specify spinner to use. + */ + spinnerName?: 'three-bounce' | 'double-bounce' | 'rotating-plane' | 'folding-cube' | 'wave' | 'wandering-cubes' | 'pulse' | 'chasing-dots' | 'circle' | 'cube-grid' | 'wordpress'; + /** + * Disable the initial fade-in of the spinner. + */ + noFadeIn?: boolean; + /** + * Change the default "spinner" className. + */ + overrideSpinnerClassName?: string; + /** + * Component className. + */ + className?: string; } export interface Spinner extends React.ComponentClass { diff --git a/react-spinkit/react-spinkit-tests.tsx b/react-spinkit/react-spinkit-tests.tsx index a163400601..6742096ebe 100644 --- a/react-spinkit/react-spinkit-tests.tsx +++ b/react-spinkit/react-spinkit-tests.tsx @@ -1,7 +1,23 @@ - -/// - import * as Spinner from 'react-spinkit'; import * as React from 'react'; -let spinner = ; +// Examples taken from http://kyleamathews.github.io/react-spinkit/ +const spinners = [ + // Basic spinners + , + , + , + , + , + , + , + , + , + , + , + + // Spinner options + , + , + , +]; diff --git a/react-syntax-highlighter/index.d.ts b/react-syntax-highlighter/index.d.ts index 57d81c9d6d..94cf519204 100644 --- a/react-syntax-highlighter/index.d.ts +++ b/react-syntax-highlighter/index.d.ts @@ -12,6 +12,8 @@ declare module 'react-syntax-highlighter' { declare module 'react-syntax-highlighter/dist/light' { import * as React from 'react'; + export function registerLanguage(name: string, func: any): void; + interface SyntaxHighlighterProps { language?: string; style?: any; @@ -498,4 +500,4 @@ declare module 'react-syntax-highlighter/dist/styles/xt256' { declare module 'react-syntax-highlighter/dist/styles/zenburn' { const style: any; export default style; -} \ No newline at end of file +} diff --git a/react-tabs/react-tabs-tests.ts b/react-tabs/react-tabs-tests.ts index b067987518..9998bcafbd 100644 --- a/react-tabs/react-tabs-tests.ts +++ b/react-tabs/react-tabs-tests.ts @@ -1,7 +1,3 @@ - -/// -/// - import React = require("react"); import ReactDOM = require("react-dom"); import { Tabs, TabList, Tab, TabPanel } from "react-tabs"; diff --git a/react-tagcloud/react-tagcloud-tests.tsx b/react-tagcloud/react-tagcloud-tests.tsx index d0594314bc..552cc20e2d 100644 --- a/react-tagcloud/react-tagcloud-tests.tsx +++ b/react-tagcloud/react-tagcloud-tests.tsx @@ -1,8 +1,3 @@ -/// -/// - - - // simple cloud import * as React from "react"; import * as ReactDOM from "react-dom"; diff --git a/react-tether/index.d.ts b/react-tether/index.d.ts new file mode 100644 index 0000000000..14344c5476 --- /dev/null +++ b/react-tether/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for react-tether 0.5 +// Project: https://github.com/souporserious/react-tether +// Definitions by: Ryan Price +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export default TetherComponent; +export as namespace ReactTether; + +import * as React from 'react'; +import * as Tether from 'tether'; + +declare class TetherComponent extends React.Component { } + +declare namespace ReactTether { + export interface TetherComponentProps extends React.Props, Tether.ITetherOptions { + renderElementTag?: string; + renderElementTo?: string | {appendChild: (element: HTMLElement) => void}; + id?: string; + className?: string; + style?: React.CSSProperties; + onUpdate?: () => void; + onRepositioned?: () => void; + } +} diff --git a/react-tether/react-tether-tests.tsx b/react-tether/react-tether-tests.tsx new file mode 100644 index 0000000000..666329621e --- /dev/null +++ b/react-tether/react-tether-tests.tsx @@ -0,0 +1,16 @@ +import TetherComponent from "react-tether"; +import * as React from "react"; + +const ReactTetherAllOptions: JSX.Element = + {}} + onRepositioned={() => {}} + renderElementTag="div" + renderElementTo=".container" + />; + +const ReactTetherRequiredOptions: JSX.Element = + ; \ No newline at end of file diff --git a/react-tether/tsconfig.json b/react-tether/tsconfig.json new file mode 100644 index 0000000000..f2138b25c9 --- /dev/null +++ b/react-tether/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "jsx": "react", + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-tether-tests.tsx" + ] +} + diff --git a/react-tether/tslint.json b/react-tether/tslint.json new file mode 100644 index 0000000000..ccdb64abf2 --- /dev/null +++ b/react-tether/tslint.json @@ -0,0 +1,2 @@ +{ "extends": "../tslint.json" } + diff --git a/react-virtualized/index.d.ts b/react-virtualized/index.d.ts index 963af32a27..1994466f8c 100644 --- a/react-virtualized/index.d.ts +++ b/react-virtualized/index.d.ts @@ -1,224 +1,522 @@ -// Type definitions for react-virtualized 8.9.0 +// Type definitions for react-virtualized 9.2.1 // Project: https://github.com/bvaughn/react-virtualized -// Definitions by: Andrew de Waal +// Definitions by: Kalle Ott // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -/// +import * as React from "react"; -declare module "react-virtualized" { - import * as React from "react"; - - /* - * Components - */ - - interface VirtualScrollProps { - className?: string; - autoHeight?: boolean; - estimatedRowSize?: number; - height: number; - noRowsRenderer?: Function; - onRowsRendered?: (info: { overscanStartIndex: number, overscanStopIndex: number, startIndex: number, stopIndex: number }) => void; - onScroll?: (info: { clientHeight: number, scrollHeight: number, scrollTop: number }) => void; - overscanRowCount?: number; - rowHeight: number | ((info: { index: number }) => number); - rowRenderer: (info: { index: number, isScrolling: boolean }) => React.ReactNode; - rowClassName?: string | ((info: { index: number }) => string); - rowCount: number; - rowStyle?: React.CSSProperties | ((info: { index: number }) => React.CSSProperties); - scrollToAlignment?: string; - scrollToIndex?: number; - scrollTop?: number; - style?: React.CSSProperties; - tabIndex?: number; - width: number; - } - export class VirtualScroll extends React.Component { } - - type CollectionProps = any; - export class Collection extends React.Component { } - - type FlexTableProps = any; - export class FlexTable extends React.Component { } - - type FlexColumnProps = any; - export class FlexColumn extends React.Component { } - - type SortDirectionProps = any; - export class SortDirection extends React.Component { } - - type GridProps = any; - export class Grid extends React.Component { } - - interface ListProps { - className?: string; - autoHeight?: boolean; - estimatedRowSize?: number; - height: number; - noRowsRenderer?: Function; - onRowsRendered?: (info: { overscanStartIndex: number, overscanStopIndex: number, startIndex: number, stopIndex: number }) => void; - onScroll?: (info: { clientHeight: number, scrollHeight: number, scrollTop: number }) => void; - overscanRowCount?: number; - rowHeight: number | ((info: { index: number }) => number); - rowRenderer: (info: { index: number, isScrolling: boolean }) => React.ReactNode; - rowCount: number; - scrollToAlignment?: string; - scrollToIndex?: number; - scrollTop?: number; - style?: React.CSSProperties; - tabIndex?: number; - width: number; - } - export class List extends React.Component { } - - // https://github.com/bvaughn/react-virtualized/blob/master/docs/Column.md - interface ColumnProps { - cellDataGetter?: (info: { columnData: any, dataKey: string, rowData: any }) => any; - cellRenderer?: (info: { cellData: any, columnData: any, dataKey: string, isScrolling: boolean, rowData: any, rowIndex: number }) => any; - className?: string; - columnData?: any; - dataKey: any; - disableSort?: boolean; - flexGrow?: number; - flexShrink?: number; - headerClassName?: string; - headerRenderer?: (info: { columnData: any, dataKey: string, disableSort: boolean, label: string, sortBy: string, sortDirection: string }) => any; - label?: string; - maxWidth?: number; - minWidth?: number; - style?: React.CSSProperties; - width: number; - } - - export class Column extends React.Component { } - - // ref: https://github.com/bvaughn/react-virtualized/blob/master/docs/Table.md - interface TableProps { - autoHeight?: boolean; - children?: React.ReactNode; - className?: string; - disableHeader?: boolean; - estimatedRowSize?: number; - gridClassName?: string; - gridStyle?: any; - headerClassName?: string; - headerHeight: number; - headerStyle?: any; - height: number; - id?: string; - noRowsRender?: () => void; - onHeaderClick?: (dataKey: string, columnData: any) => void; - onRowClick?: (info: { index: number }) => void; - onRowDoubleClick?: (info: { index: number }) => void; - onRowMouseOut?: (info: { index: number }) => void; - onRowMouseOver?: (info: { index: number }) => void; - onRowsRendered?: (info: { index: number }) => void; - overscanRowCount?: number; - onScroll?: (info: { clientHeight: number, scrollHeight: number, scrollTop: number }) => void; - rowClassName?: string | ((info: { index: number }) => string); - rowCount: number; - rowGetter?: (info: { index: number }) => any; - rowHeight: number | ((info: { index: number }) => number); - rowRenderer?: (info: { index: number, isScrolling: boolean }) => React.ReactNode; - rowStyle?: React.CSSProperties | ((info: { index: number }) => React.CSSProperties); - scrollToAlignment?: string; - scrollToIndex?: number; - scrollTop?: number; - sort?: (info: { sortBy: string, sortDirection: 'ASC' | 'DESC' }) => void; - sortBy?: string; - sortDirection?: 'ASC' | 'DESC'; - style?: React.CSSProperties; - tabIndex?: number; - width: number; - } - - export class Table extends React.Component { } - - /* - * Higher-Order Components - */ - - interface AutoSizerProps { - disableHeight?: boolean; - disableWidth?: boolean; - onResize?: (info: { height: number, width: number }) => any; - } - export class AutoSizer extends React.Component { } - - interface ArrowKeyStepperProps { - children?: React.StatelessComponent<{ - onSectionRendered: Function, - scrollToColumn: number, - scrollToRow: number - }>; - className?: string; - columnCount: number; - rowCount: number; - } - export class ArrowKeyStepper extends React.Component { } - - interface CellMeasurerProps { - cellRenderer: (info: { columnIndex: number, rowIndex: number }) => React.ReactNode; - cellSizeCache?: { - clearAllColumnWidths(): void; - clearAllRowHeights(): void; - clearColumnWidth(index: number): void; - clearRowHeight(index: number): void; - getColumnWidth(index: number): number; - getRowHeight(index: number): number; - hasColumnWidth(index: number): boolean; - hasRowHeight(index: number): boolean; - setColumnWidth(index: number, width: number): void; - setRowHeight(index: number, height: number): void; - }; - children?: React.StatelessComponent<{ - getColumnWidth: () => number, - getRowHeight: () => number, - resetMeasurements: () => any, - resetMeasurementsForColumn: (index: number) => any, - resetMeasurementsForRow: (index: number) => any, - }>; - columnCount: number; - container?: React.ReactType; - height?: number; - rowCount: number; - width?: number; - } - export class CellMeasurer extends React.Component { } - - interface ColumnSizerProps { - children?: React.StatelessComponent<{ adjustedWidth: number, getColumnWidth: () => number, registerChild: any }>; - columnMaxWidth?: number; - columnMinWidth?: number; - columnCount?: number; - width: number; - } - export class ColumnSizer extends React.Component { } - - type InfiniteLoaderProps = any; - export class InfiniteLoader extends React.Component { } - - type ScrollSyncProps = any; - export class ScrollSync extends React.Component { } - - export module WindowScroller { - export type OnResizeArg = { - height: number; - } - export type OnScrollArg = { - scrollTop: number; - } - export type RenderCallbackArg = { - height: number; - scrollTop: number; - isScrolling: boolean; - } - export type Props = { - onScroll?: (arg: OnScrollArg) => void; - onResize?: (arg: OnResizeArg) => void; - // TODO `children` should be typed here - }; - } - export class WindowScroller extends React.Component { } +export interface ArrowKeyStepperProps { + children?: React.StatelessComponent<{ + onSectionRendered: Function, + scrollToColumn: number, + scrollToRow: number + }>; + className?: string; + columnCount: number; + rowCount: number; } +export class ArrowKeyStepper extends React.PureComponent { } + +export interface AutoSizerProps { + disableHeight?: boolean; + disableWidth?: boolean; + onResize?: (info: { height: number, width: number }) => any; +} +export class AutoSizer extends React.PureComponent { } + +export interface CellMeasurerProps { + cellRenderer: (info: { columnIndex: number, rowIndex: number }) => React.ReactNode; + cellSizeCache?: { + clearAllColumnWidths(): void; + clearAllRowHeights(): void; + clearColumnWidth(index: number): void; + clearRowHeight(index: number): void; + getColumnWidth(index: number): number; + getRowHeight(index: number): number; + hasColumnWidth(index: number): boolean; + hasRowHeight(index: number): boolean; + setColumnWidth(index: number, width: number): void; + setRowHeight(index: number, height: number): void; + }; + children?: React.StatelessComponent<{ + getColumnWidth: () => number, + getRowHeight: () => number, + resetMeasurements: () => any, + resetMeasurementsForColumn: (index: number) => any, + resetMeasurementsForRow: (index: number) => any, + }>; + columnCount: number; + container?: React.ReactType; + height?: number; + rowCount: number; + width?: number; +} +export class CellMeasurer extends React.PureComponent { } + +export type KeyMapper = ( + rowIndex: number, + columnIndex: number +) => any; +export type Map = { [key: string]: T }; +export type Cache = Map; +export type IndexParam = { + index: number +}; + +export type CellMeasurerCacheParams = { + defaultHeight?: number, + defaultWidth?: number, + fixedHeight?: boolean, + fixedWidth?: boolean, + minHeight?: number, + minWidth?: number, + keyMapper?: KeyMapper +} +export class CellMeasurerCache { + _cellHeightCache: Cache; + _cellWidthCache: Cache; + _columnWidthCache: Cache; + _defaultHeight?: number; + _defaultWidth?: number; + _minHeight?: number; + _minWidth?: number; + _keyMapper: KeyMapper; + _rowHeightCache: Cache; + _hasFixedHeight: boolean; + _hasFixedWidth: boolean; + constructor(params: CellMeasurerCacheParams); + clear( + rowIndex: number, + columnIndex: number + ): void; + clearAll(): void; + columnWidth: (params: IndexParam) => number | undefined; + hasFixedHeight(): boolean; + hasFixedWidth(): boolean; + getHeight( + rowIndex: number, + columnIndex: number + ): number | undefined; + getWidth( + rowIndex: number, + columnIndex: number + ): number | undefined; + has( + rowIndex: number, + columnIndex: number + ): boolean; + rowHeight: (params: IndexParam) => number | undefined; + set( + rowIndex: number, + columnIndex: number, + width: number, + height: number + ): void; + _updateCachedColumnAndRowSizes( + rowIndex: number, + columnIndex: number + ): void; +} + +export type CollectionCellSizeAndPosition = { height: number, width: number, x: number, y: number }; +export type CollectionCellSizeAndPositionGetter = (params: IndexParam) => CollectionCellSizeAndPosition; + +export type CollectionCellGroupRendererParams = { + cellSizeAndPositionGetter: CollectionCellSizeAndPositionGetter, + indices: number[], + cellRenderer: CollectionCellRenderer +} +export type CollectionCellGroupRenderer = (params: CollectionCellGroupRendererParams) => React.ReactNode[]; +export type CollectionCellRendererParams = { + index: number, + key: string, + style?: React.CSSProperties +} +export type CollectionCellRenderer = (params: CollectionCellRendererParams) => React.ReactNode; +export type CollectionProps = { + 'aria-label'?: string; + cellCount: number; + cellGroupRenderer?: CollectionCellGroupRenderer, + cellRenderer: CollectionCellRenderer, + cellSizeAndPositionGetter: CollectionCellSizeAndPositionGetter, + sectionSize?: number; +}; +export class Collection extends React.PureComponent { } + +export interface ColumnSizerProps { + children?: React.StatelessComponent<{ adjustedWidth: number, getColumnWidth: () => number, registerChild: any }>; + columnMaxWidth?: number; + columnMinWidth?: number; + columnCount?: number; + width: number; +} +export class ColumnSizer extends React.PureComponent { } + +export type CellDataGetterParams = { + columnData?: any, + dataKey: string, + rowData: any +}; +export type CellRendererParams = { + cellData?: any, + columnData?: any, + dataKey: string, + rowData: any, + rowIndex: number +}; +export type HeaderRendererParams = { + columnData?: any, + dataKey: string, + disableSort?: boolean, + label?: string, + sortBy?: string, + sortDirection?: SortDirectionType +}; +export type HeaderRowRendererParams = { + className: string, + columns: React.ReactNode[], + style: React.CSSProperties, + scrollbarWidth: number, + height: number, + width: number +}; +export type RowRendererParams = { + className: string, + columns: Array, + index: number, + isScrolling: boolean, + onRowClick?: Function, + onRowDoubleClick?: Function, + onRowMouseOver?: Function, + onRowMouseOut?: Function, + rowData: any, + style: any +}; + +export type TableCellDataGetter = (params: CellDataGetterParams) => any; +export type TableCellRenderer = (params: CellRendererParams) => React.ReactNode; +export type TableHeaderRenderer = (params: HeaderRendererParams) => React.ReactNode; +export type TableHeaderRowRenderer = (params: HeaderRowRendererParams) => React.ReactNode; +export type TableRowRenderer = (params: RowRendererParams) => React.ReactNode; + +// https://github.com/bvaughn/react-virtualized/blob/master/docs/Column.md +export interface ColumnProps { + cellDataGetter?: TableCellDataGetter; + cellRenderer?: TableCellRenderer; + className?: string; + columnData?: any; + dataKey: any; + disableSort?: boolean; + flexGrow?: number; + flexShrink?: number; + headerClassName?: string; + headerRenderer?: TableHeaderRenderer; + label?: string; + maxWidth?: number; + minWidth?: number; + style?: React.CSSProperties; + width: number; +} +export class Column extends React.Component { } + +// ref: https://github.com/bvaughn/react-virtualized/blob/master/docs/Table.md +export interface TableProps { + autoHeight?: boolean; + children?: React.ReactChildren; + className?: string; + disableHeader?: boolean; + estimatedRowSize?: number; + gridClassName?: string; + gridStyle?: any; + headerClassName?: string; + headerHeight: number; + headerStyle?: any; + height: number; + id?: string; + noRowsRender?: () => void; + onHeaderClick?: (dataKey: string, columnData: any) => void; + onRowClick?: (info: IndexParam) => void; + onRowDoubleClick?: (info: IndexParam) => void; + onRowMouseOut?: (info: IndexParam) => void; + onRowMouseOver?: (info: IndexParam) => void; + onRowsRendered?: (info: IndexParam) => void; + overscanRowCount?: number; + onScroll?: (info: { clientHeight: number, scrollHeight: number, scrollTop: number }) => void; + rowClassName?: string | ((info: IndexParam) => string); + rowCount: number; + rowGetter?: (info: IndexParam) => any; + rowHeight: number | ((info: IndexParam) => number); + rowRenderer?: TableRowRenderer; + headerRowRenderer?: TableHeaderRowRenderer; + rowStyle?: React.CSSProperties | ((info: IndexParam) => React.CSSProperties); + scrollToAlignment?: string; + scrollToIndex?: number; + scrollTop?: number; + sort?: (info: { sortBy: string, sortDirection: SortDirectionType }) => void; + sortBy?: string; + sortDirection?: SortDirectionType; + style?: React.CSSProperties; + tabIndex?: number; + width: number; +} +export class Table extends React.PureComponent { } + +export const defaultTableCellDataGetter: TableCellDataGetter; +export const defaultTableCellRenderer: TableCellRenderer; +export const defaultTableHeaderRenderer: () => React.ReactElement[]; +export const defaultTableHeaderRowRenderer: TableHeaderRowRenderer; +export const defaultTableRowRenderer: TableRowRenderer; + +interface ISortDirection { + /** + * Sort items in ascending order. + * This means arranging from the lowest value to the highest (e.g. a-z, 0-9). + */ + ASC: 'ASC', + + /** + * Sort items in descending order. + * This means arranging from the highest value to the lowest (e.g. z-a, 9-0). + */ + DESC: 'DESC' +} + +export const SortDirection: ISortDirection + +export type SortDirectionType = 'ASC' | 'DESC' + +export const SortIndicator: React.StatelessComponent<{ sortDirection: SortDirectionType }> + + +export type DefaultCellRangeRendererParams = { + cellCache: Object, + cellRenderer: Function, + columnSizeAndPositionManager: Object, + columnStartIndex: number, + columnStopIndex: number, + horizontalOffsetAdjustment: number, + isScrolling: boolean, + rowSizeAndPositionManager: Object, + rowStartIndex: number, + rowStopIndex: number, + scrollLeft: number, + scrollTop: number, + styleCache: Object, + verticalOffsetAdjustment: number, + visibleColumnIndices: Object, + visibleRowIndices: Object +}; +export function defaultCellRangeRenderer(params: DefaultCellRangeRendererParams): React.ReactElement; + + +export type GridCellRendererParams = { + columnIndex: number; + isScrolling: boolean; + isVisible: boolean; + key: string; + parent: Grid | List | Table; + rowIndex: number; + style: React.CSSProperties; +}; +export type GridCellRenderer = (params: GridCellRendererParams) => React.ReactNode; + +export type ConfigureParams = { + cellCount: number, + estimatedCellSize: number +}; +export type ContainerSizeAndOffset = { + containerSize: number, + offset: number +}; +export type SizeAndPositionData = { + offset: number, + size: number +}; +export type GetVisibleCellRangeParams = { + containerSize: number, + offset: number +}; +export type VisibleCellRange = { + start: number; + stop: number; +} + +export type CellSizeAndPositionManager = { + areOffsetsAdjusted(): boolean; + configure({ + cellCount, + estimatedCellSize + }: ConfigureParams): void; + getCellCount(): number; + getEstimatedCellSize(): number; + getLastMeasuredIndex(): number; + getOffsetAdjustment({ + containerSize, + offset // safe + }: ContainerSizeAndOffset): number; + /** + * This method returns the size and position for the cell at the specified index. + * It just-in-time calculates (or used cached values) for cells leading up to the index. + */ + getSizeAndPositionOfCell(index: number): SizeAndPositionData; + getSizeAndPositionOfLastMeasuredCell(): SizeAndPositionData; + /** + * Total size of all cells being measured. + * This value will be completedly estimated initially. + * As cells as measured the estimate will be updated. + */ + getTotalSize(): number; + /** + * Determines a new offset that ensures a certain cell is visible, given the current offset. + * If the cell is already visible then the current offset will be returned. + * If the current offset is too great or small, it will be adjusted just enough to ensure the specified index is visible. + * + * @param align Desired alignment within container; one of "auto" (default), "start", or "end" + * @param containerSize Size (width or height) of the container viewport + * @param currentOffset Container's current (x or y) offset + * @param totalSize Total size (width or height) of all cells + * @return Offset to use to ensure the specified cell is visible + */ + getUpdatedOffsetForIndex(params: { + align: string, + containerSize: number, + currentOffset: number, + targetIndex: number + }): number; + getVisibleCellRange(params: GetVisibleCellRangeParams): VisibleCellRange; + /** + * Clear all cached values for cells after the specified index. + * This method should be called for any cell that has changed its size. + * It will not immediately perform any calculations; they'll be performed the next time getSizeAndPositionOfCell() is called. + */ + resetCell(index: number): void +} + +export type GridCellRangeRendererParams = { + cellCache: Map, + cellRenderer: GridCellRenderer, + columnSizeAndPositionManager: CellSizeAndPositionManager, + columnStartIndex: number, + columnStopIndex: number, + isScrolling: boolean, + rowSizeAndPositionManager: CellSizeAndPositionManager, + rowStartIndex: number, + rowStopIndex: number, + scrollLeft: number, + scrollTop: number +} +export type GridCellRangeRenderer = (params: GridCellRangeRendererParams) => React.ReactNode[]; +// TODO add proper typing +export type GridProps = { + 'aria-label'?: string; + autoContainerWidth?: boolean; + autoHeight?: boolean; + cellRenderer: GridCellRenderer; + cellRangeRenderer?: GridCellRangeRenderer; + className?: string; + columnCount: number; + columnWidth: number | ((params: IndexParam) => number); + containerStyle?: React.CSSProperties; + deferredMeasurementCache?: Object; + estimatedColumnSize?: number; + estimatedRowSize?: number; + getScrollbarSize?: () => number; + height: number; + id?: string; + noContentRenderer?: () => React.ReactNode; + onScroll?: (params: { clientHeight: number, clientWidth: number, scrollHeight: number, scrollLeft: number, scrollTop: number, scrollWidth: number }) => any; + onSectionRendered?: (params: { columnStartIndex: number, columnStopIndex: number, rowStartIndex: number, rowStopIndex: number }) => any; + overscanColumnCount?: number; + overscanIndicesGetter?: (params: { + cellCount: number, + overscanCellsCount: number, + scrollDirection: number, + startIndex: number, + stopIndex: number + }) => { overscanStartIndex: number, overscanStopIndex: number }; + overscanRowCount?: number; + rowHeight: number | ((params: IndexParam) => number); + rowCount: number; + scrollingResetTimeInterval?: number; + scrollLeft?: number; + scrollToAlignment?: 'auto' | 'end' | 'start' | 'center'; + scrollToColumn?: number; + scrollTop?: number; + scrollToRow?: number; + style?: React.CSSProperties; + tabIndex?: number; + width: number; +}; +export class Grid extends React.PureComponent { } + +export type InfiniteLoaderProps = { + children?: React.StatelessComponent<{ + onRowsRendered: (params: { startIndex: number, stopIndex: number }) => void, + registerChild: (registeredChild: any) => void + }>; + isRowLoaded: (params: IndexParam) => boolean; + loadMoreRows: (params: { startIndex: number, stopIndex: number }) => Promise; + minimumBatchSize?: number; + rowCount?: number; + threshold?: number; +}; +export class InfiniteLoader extends React.PureComponent { } +export type ListRowRenderer = (params: GridCellRendererParams & { index: number, style: React.CSSProperties }) => React.ReactNode; +export interface ListProps { + className?: string; + autoHeight?: boolean; + estimatedRowSize?: number; + height: number; + noRowsRenderer?: Function; + onRowsRendered?: (info: { overscanStartIndex: number, overscanStopIndex: number, startIndex: number, stopIndex: number }) => void; + onScroll?: (info: { clientHeight: number, scrollHeight: number, scrollTop: number }) => void; + overscanRowCount?: number; + rowHeight: number | ((info: IndexParam) => number); + rowRenderer: ListRowRenderer; + rowCount: number; + scrollToAlignment?: string; + scrollToIndex?: number; + scrollTop?: number; + style?: React.CSSProperties; + tabIndex?: number; + width: number; +} +export class List extends React.PureComponent { } + +export interface MultiGridProps { + fixedColumnCount: number; + fixedRowCount: number; + style: React.CSSProperties; + styleBottomLeftGrid: React.CSSProperties; + styleBottomRightGrid: React.CSSProperties; + styleTopLeftGrid: React.CSSProperties; + styleTopRightGrid: React.CSSProperties; +} +export class MultiGrid extends React.PureComponent { } + +export type ScrollSyncProps = { + children?: React.StatelessComponent<{ + clientHeight: number, + clientWidth: number, + onScroll: (params: { clientHeight: number, clientWidth: number, scrollHeight: number, scrollLeft: number, scrollTop: number, scrollWidth: number }) => void, + scrollHeight: number, + scrollLeft: number, + scrollTop: number, + scrollWidth: number + }>; +}; +export class ScrollSync extends React.PureComponent { } +export type WindowScrollerRenderCallBackParams = { + height: number, + isScrolling: boolean, + scrollTop: number +}; + +export type WindowScrollerProps = { + children?: React.StatelessComponent; + onResize?: (prams: { height: number }) => void; + onScroll?: (params: { scrollTop: number }) => void; + scrollElement?: HTMLElement; +} +export class WindowScroller extends React.PureComponent { } diff --git a/react-virtualized/react-virtualized-tests.tsx b/react-virtualized/react-virtualized-tests.tsx index 7da7e26c88..1ab6654c18 100644 --- a/react-virtualized/react-virtualized-tests.tsx +++ b/react-virtualized/react-virtualized-tests.tsx @@ -1,17 +1,10 @@ -/// -/// -/// - import * as React from "react"; import * as ReactDOM from "react-dom"; import { Collection, - FlexTable, - FlexColumn, SortDirection, Grid, - VirtualScroll, ArrowKeyStepper, AutoSizer, CellMeasurer, @@ -19,6 +12,7 @@ import { InfiniteLoader, ScrollSync, WindowScroller, + WindowScrollerRenderCallBackParams, List, Column, Table, @@ -46,44 +40,8 @@ function CollectionTest() { x: datum.x, y: datum.y }; - } } - height={300} - width={300} - />, - document.getElementById("example") - ); -} - - -function FlexTableTest() { - const list = [ - { name: 'Brian Vaughn', description: 'Software engineer' } - // And so on... - ]; - - // Render your table - ReactDOM.render( - list[index] - } - > - - - , + }} + />, document.getElementById("example") ); } @@ -105,7 +63,7 @@ function GridTest() { columnCount={list[0].length} rowCount={list.length} cellRenderer={({ columnIndex, isScrolling, rowIndex }) => list[rowIndex][columnIndex]} - />, + />, document.getElementById('example') ); } @@ -113,7 +71,7 @@ function GridTest() { function ListTest() { // List data const list = [ - {name: 'Brian Vaughn', occupation: 'Software Engineer', location: 'San Jose, CA, 95125' /* ... */} + { name: 'Brian Vaughn', occupation: 'Software Engineer', location: 'San Jose, CA, 95125' /* ... */ } // And so on... ]; @@ -125,7 +83,7 @@ function ListTest() { rowHeight={30} rowCount={list.length} rowRenderer={({ index, isScrolling }) => list[index]} - />, + />, document.getElementById('example') ); } @@ -159,26 +117,6 @@ function TableTest() { ); } -function VirtualScrollTest() { - // List data as an array of strings - const list = [ - 'Brian Vaughn' - // And so on... - ]; - - // Render your list - ReactDOM.render( - list[index]} - />, - document.getElementById('example') - ); -} - function ArrowKeyStepperTest() { const columnCount = 12; const rowCount = 3; @@ -187,13 +125,18 @@ function ArrowKeyStepperTest() { {({ onSectionRendered, scrollToColumn, scrollToRow }) => ( null} columnCount={columnCount} onSectionRendered={onSectionRendered} rowCount={rowCount} scrollToColumn={scrollToColumn} scrollToRow={scrollToRow} - /> - ) } + /> + )} , document.getElementById('example') ); @@ -205,21 +148,46 @@ function AutoSizerTest() { 'Brian Vaughn' // And so on... ]; + const _rowRenderer = ({ index, key, style }) => { + + const row = list[index]; + + return ( +

              + {row} +
              + ) + } // Render your list ReactDOM.render( - {({ height, width }) => ( - ( + list[index] // Could also be a DOM element - } - /> - ) } + rowHeight={30} + rowRenderer={({ index, key, style }) => { + const row = list[index]; + + return ( +
              + {row} +
              + ) + }} + width={width} + /> + )}
              , document.getElementById('example') ); @@ -239,7 +207,7 @@ function CellMeasurerTest() { columnCount={columnCount} height={fixedRowHeight} rowCount={rowCount} - > + > {({ getColumnWidth }) => ( - ) } + /> + )} , document.getElementById('example') ); @@ -263,7 +231,7 @@ function ColumnSizerTest() { columnMinWidth={50} columnCount={12} width={120} - > + > {({ adjustedWidth, getColumnWidth, registerChild }) => ( - ) } + /> + )} , document.getElementById('example') ); @@ -288,75 +256,273 @@ function InfiniteLoaderTest() { return !!list[index]; } - function loadMoreRows({ startIndex, stopIndex }) { - return list.push('test'); + function loadMoreRows({ startIndex, stopIndex }: { startIndex: number, stopIndex: number }) { + return new Promise(resolve => resolve(list.push('test'))); } + function rowRenderer({ index, key, style }) { + const content = list[index]; + + return ( +
              + {content} +
              + ) + } + + // Render your list ReactDOM.render( + > {({ onRowsRendered, registerChild }) => ( - list[index] // Could also be a DOM element - } - /> - ) } + + {({ width }) => ( + + )} + + )} , document.getElementById('example') ); } function ScrollSyncTest() { + function hexToRgb(hex) { + const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex) + return result ? { + r: parseInt(result[1], 16), + g: parseInt(result[2], 16), + b: parseInt(result[3], 16) + } : null + } + + const LEFT_COLOR_FROM = hexToRgb('#471061') + const LEFT_COLOR_TO = hexToRgb('#BC3959') + const TOP_COLOR_FROM = hexToRgb('#000000') + const TOP_COLOR_TO = hexToRgb('#333333') + const columnWidth = 20; + const rowHeight = 10; + const overscanColumnCount = 10; + const overscanRowCount = 10; + const height = 10; + const rowCount = 100; + const columnCount = 100; + + + function mixColors(color1, color2, amount) { + const weight1 = amount + const weight2 = 1 - amount + + const r = Math.round(weight1 * color1.r + weight2 * color2.r) + const g = Math.round(weight1 * color1.g + weight2 * color2.g) + const b = Math.round(weight1 * color1.b + weight2 * color2.b) + + return { r, g, b } + }; + + function renderLeftHeaderCell({ columnIndex, key, rowIndex, style }) { + return ( +
              + {`C${columnIndex}`} +
              + ) + }; + function renderLeftSideCell({ columnIndex, key, rowIndex, style }) { + const rowClass = rowIndex % 2 === 0 + ? columnIndex % 2 === 0 ? 'styles.evenRow' : 'styles.oddRow' + : columnIndex % 2 !== 0 ? 'styles.evenRow' : 'styles.oddRow' + const classNames = [rowClass, 'styles.cell'].join(' ') + + return ( +
              + {`R${rowIndex}, C${columnIndex}`} +
              + ) + }; + + function renderHeaderCell({ columnIndex, key, rowIndex, style }) { + if (columnIndex < 1) { + return + } + + return renderLeftHeaderCell({ columnIndex, key, rowIndex, style }) + }; + + function renderBodyCell({ columnIndex, key, rowIndex, style }) { + if (columnIndex < 1) { + return + } + + return renderLeftSideCell({ columnIndex, key, rowIndex, style }) + } + return ( - {({ clientHeight, clientWidth, onScroll, scrollHeight, scrollLeft, scrollTop, scrollWidth }) => ( -
              -
              - "test"} - rowCount={42} - height={12} - width={12} - rowHeight={120} - scrollTop={scrollTop}/> - /> + {({ clientHeight, clientWidth, onScroll, scrollHeight, scrollLeft, scrollTop, scrollWidth }) => { + const x = scrollLeft / (scrollWidth - clientWidth) + const y = scrollTop / (scrollHeight - clientHeight) + + const leftBackgroundColor = mixColors(LEFT_COLOR_FROM, LEFT_COLOR_TO, y) + const leftColor = '#ffffff' + const topBackgroundColor = mixColors(TOP_COLOR_FROM, TOP_COLOR_TO, x) + const topColor = '#ffffff' + const middleBackgroundColor = mixColors(leftBackgroundColor, topBackgroundColor, 0.5) + const middleColor = '#ffffff' + + return ( +
              +
              + +
              +
              + +
              +
              + + {({ width }) => ( +
              +
              + +
              +
              + +
              +
              + )} +
              +
              -
              - -
              -
              - ) } + ) + }} ); } function WindowScrollerTest() { - const onScroll = function({scrollTop}: WindowScroller.OnScrollArg) {}; - const onResize = function({height}: WindowScroller.OnResizeArg) {}; + const onScroll = function ({scrollTop}: { scrollTop: number }) { }; + const onResize = function ({height}: { height: number }) { }; + const list = [ + { name: 'Brian Vaughn', description: 'Software engineer' } + // And so on... + ]; ReactDOM.render( - {({ height, isScrolling, scrollTop }: WindowScroller.RenderCallbackArg) => ( - 'test'} - scrollTop={scrollTop} - width={120}/> - ) } + {({ height, isScrolling, scrollTop }) => ( + + {({ width }) => ( + list[index].name} + scrollTop={scrollTop} + width={width} + /> + )} + + )} , document.getElementById('example') ); diff --git a/react-widgets/react-widgets-tests.tsx b/react-widgets/react-widgets-tests.tsx index a108d8e513..0f66458c36 100644 --- a/react-widgets/react-widgets-tests.tsx +++ b/react-widgets/react-widgets-tests.tsx @@ -1,8 +1,3 @@ - -/// -/// - - import * as React from "react" import * as ReactDOM from "react-dom" @@ -45,10 +40,10 @@ class Test extends React.Component, {}> { itemComponent={itemComponent} />
              diff --git a/react/index.d.ts b/react/index.d.ts index 234e3ec4f7..3bd624521e 100644 --- a/react/index.d.ts +++ b/react/index.d.ts @@ -242,10 +242,10 @@ declare namespace React { interface ComponentLifecycle { componentWillMount?(): void; componentDidMount?(): void; - componentWillReceiveProps?(nextProps: P, nextContext: any): void; - shouldComponentUpdate?(nextProps: P, nextState: S, nextContext: any): boolean; - componentWillUpdate?(nextProps: P, nextState: S, nextContext: any): void; - componentDidUpdate?(prevProps: P, prevState: S, prevContext: any): void; + componentWillReceiveProps?(nextProps: Readonly

              , nextContext: any): void; + shouldComponentUpdate?(nextProps: Readonly

              , nextState: Readonly, nextContext: any): boolean; + componentWillUpdate?(nextProps: Readonly

              , nextState: Readonly, nextContext: any): void; + componentDidUpdate?(prevProps: Readonly

              , prevState: Readonly, prevContext: any): void; componentWillUnmount?(): void; } @@ -942,6 +942,12 @@ declare namespace React { */ boxFlexGroup?: CSSWideKeyword | number; + /** + * Cast a drop shadow from the frame of almost any element. + * MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow + */ + boxShadow?: CSSWideKeyword | any; + /** * The CSS break-after property allows you to force a break on multi-column layouts. More specifically, it allows you to force a break after an element. It allows you to determine if a break should occur, and what type of break it should be. The break-after CSS property describes how the page, column or region break behaves after the generated box. If there is no generated box, the property is ignored. */ @@ -2042,6 +2048,7 @@ declare namespace React { // React-specific Attributes defaultChecked?: boolean; defaultValue?: string | string[]; + suppressContentEditableWarning?: boolean; // Standard HTML Attributes accept?: string; diff --git a/react/test/cssProperties.tsx b/react/test/cssProperties.tsx index 293f0b5374..1221a0effc 100644 --- a/react/test/cssProperties.tsx +++ b/react/test/cssProperties.tsx @@ -24,6 +24,8 @@ const fontWeightStyleTest =

              ; const justifyContentStyle: React.CSSProperties = { justifyContent: 'space-evenly' }; const justifyContentStyleTest =
              ; +const boxShadowStyle: React.CSSProperties = { boxShadow: '2px 2px 2px 1px rgba(0, 0, 0, 0.2)' }; +const boxShadowStyleTest =
              ; // SVG specific style attribute declarations diff --git a/react/test/tsx.tsx b/react/test/tsx.tsx index 540c712596..1d6b683bcf 100644 --- a/react/test/tsx.tsx +++ b/react/test/tsx.tsx @@ -33,3 +33,13 @@ StatelessComponent2.defaultProps = {
              Hello again!
              ; + +// React-specific Attributes +
              + foo +
              diff --git a/readdir-stream/readdir-stream-tests.ts b/readdir-stream/readdir-stream-tests.ts index f0a2dba78b..d808bc5b6d 100644 --- a/readdir-stream/readdir-stream-tests.ts +++ b/readdir-stream/readdir-stream-tests.ts @@ -1,6 +1,3 @@ - -/// - import readdir = require('readdir-stream'); var rs: NodeJS.ReadableStream; diff --git a/reduce-reducers/index.d.ts b/reduce-reducers/index.d.ts new file mode 100644 index 0000000000..2b630766fc --- /dev/null +++ b/reduce-reducers/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for reduce-reducers 0.1 +// Project: https://github.com/acdlite/reduce-reducers +// Definitions by: Huy Nguyen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import {Reducer} from 'redux'; +export default function reduceReducer(...reducers: Array>): Reducer; diff --git a/reduce-reducers/package.json b/reduce-reducers/package.json new file mode 100644 index 0000000000..36ce503807 --- /dev/null +++ b/reduce-reducers/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "redux": "^3.6.0" + } +} diff --git a/reduce-reducers/reduce-reducers-tests.ts b/reduce-reducers/reduce-reducers-tests.ts new file mode 100644 index 0000000000..d5eeb02633 --- /dev/null +++ b/reduce-reducers/reduce-reducers-tests.ts @@ -0,0 +1,13 @@ +import { + Reducer, + Action, +} from 'redux'; +import reduceReducers from 'reduce-reducers'; + +interface TestStore { + a: number, + b: string +} +let firstReducer: (state: TestStore, action: Action) => TestStore = (a, b) => a; +let secondReducer: (state: TestStore, action: Action) => TestStore = (a, b) => a +let finalReducer: (state: TestStore, action: Action) => TestStore = reduceReducers(firstReducer, secondReducer); diff --git a/reduce-reducers/tsconfig.json b/reduce-reducers/tsconfig.json new file mode 100644 index 0000000000..d7ca486716 --- /dev/null +++ b/reduce-reducers/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "reduce-reducers-tests.ts" + ] +} diff --git a/reduce-reducers/tslint.json b/reduce-reducers/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/reduce-reducers/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/redux-debounced/redux-debounced-tests.ts b/redux-debounced/redux-debounced-tests.ts index f33050e394..ad83e40bc5 100644 --- a/redux-debounced/redux-debounced-tests.ts +++ b/redux-debounced/redux-debounced-tests.ts @@ -1,5 +1,3 @@ -/// - import { applyMiddleware } from 'redux'; import createDebounce from 'redux-debounced'; diff --git a/redux-devtools-dock-monitor/redux-devtools-dock-monitor-tests.tsx b/redux-devtools-dock-monitor/redux-devtools-dock-monitor-tests.tsx index 5a99ba665a..7e33588a41 100644 --- a/redux-devtools-dock-monitor/redux-devtools-dock-monitor-tests.tsx +++ b/redux-devtools-dock-monitor/redux-devtools-dock-monitor-tests.tsx @@ -1,5 +1,3 @@ -/// - import * as React from 'react' import DockMonitor from 'redux-devtools-dock-monitor' diff --git a/redux-devtools-log-monitor/redux-devtools-log-monitor-tests.tsx b/redux-devtools-log-monitor/redux-devtools-log-monitor-tests.tsx index 48a655bea2..477f4bbc55 100644 --- a/redux-devtools-log-monitor/redux-devtools-log-monitor-tests.tsx +++ b/redux-devtools-log-monitor/redux-devtools-log-monitor-tests.tsx @@ -1,5 +1,3 @@ -/// - import * as React from 'react' import LogMonitor from 'redux-devtools-log-monitor' diff --git a/redux-devtools/redux-devtools-tests.tsx b/redux-devtools/redux-devtools-tests.tsx index 10e20b7e87..695fbe60ff 100644 --- a/redux-devtools/redux-devtools-tests.tsx +++ b/redux-devtools/redux-devtools-tests.tsx @@ -1,6 +1,3 @@ -/// -/// - import * as React from 'react' import { compose, createStore, Reducer, Store, StoreEnhancerStoreCreator } from 'redux' import { Provider } from 'react-redux' diff --git a/redux-form/index.d.ts b/redux-form/index.d.ts index 590fe3a633..f36162d684 100644 --- a/redux-form/index.d.ts +++ b/redux-form/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for redux-form v6.3.1 +// Type definitions for redux-form v6.3.3 // Project: https://github.com/erikras/redux-form -// Definitions by: Carson Full , Daniel Lytkin +// Definitions by: Carson Full // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 diff --git a/redux-form/lib/reduxForm.d.ts b/redux-form/lib/reduxForm.d.ts index 512797a39c..100a708032 100644 --- a/redux-form/lib/reduxForm.d.ts +++ b/redux-form/lib/reduxForm.d.ts @@ -1,5 +1,6 @@ import { Component, + StatelessComponent, ReactElement, SyntheticEvent, ReactEventHandler, @@ -20,7 +21,8 @@ export function reduxForm( ): FormDecorator; export interface FormDecorator { - (component: T): T & Form; + )>(component: T): + T & Form; } export interface Config { @@ -28,7 +30,7 @@ export interface Config { * the name of your form and the key to where your form's state will be * mounted under the redux-form reducer */ - form: string; + form?: string; /** * An adapter function that will render a component based on a string component @@ -48,14 +50,14 @@ export interface Config { asyncBlurFields?: string[]; /** - * a function that takes all the form values, the dispatch function, and - * the props given to your component, and returns a Promise that will - * resolve if the validation is passed, or will reject with an object of - * validation errors in the form { field1: , field2: }. + * a function that takes all the form values, the dispatch function, + * the props given to your component and the current blurred field, + * and returns a Promise that will resolve if the validation is passed, + * or will reject with an object of validation errors in the form { field1: , field2: }. * * See Asynchronous Blur Validation Example for more details. */ - asyncValidate?(values: FormData, dispatch: Dispatch, props: P): Promise; + asyncValidate?(values: FormData, dispatch: Dispatch, props: P, blurredField: string): Promise; /** * Whether or not to automatically destroy your form's state in the Redux @@ -63,6 +65,12 @@ export interface Config { */ destroyOnUnmount?: boolean; + /** + * Whether or not to force unregistration of fields -- use in conjunction + * with destroyOnUnmount. + */ + forceUnregisterOnUnmount?: boolean; + /** * A function that takes the entire Redux state and returns the state slice * which corresponds to where the redux-form reducer was mounted. This diff --git a/redux-form/redux-form-tests.tsx b/redux-form/redux-form-tests.tsx index 244ab11382..396ca8df85 100644 --- a/redux-form/redux-form-tests.tsx +++ b/redux-form/redux-form-tests.tsx @@ -50,3 +50,29 @@ class MyForm extends Component<{}, {}> { ); } } + +const MyStatelessFunctionalComponent: React.SFC = () =>
              ; + +reduxForm({ + form: 'mySFCForm' +})(MyStatelessFunctionalComponent); + +@reduxForm({}) +class MyDynamicForm extends Component { + render() { + return ( +
              + +
              + ); + } +} + +reduxForm({ + form: 'forceUnregisterOnMountForm', + forceUnregisterOnUnmount: true +}); diff --git a/redux-ui/index.d.ts b/redux-ui/index.d.ts index 3b1f8f4a58..1c3468233d 100644 --- a/redux-ui/index.d.ts +++ b/redux-ui/index.d.ts @@ -2,7 +2,9 @@ // Project: https://github.com/tonyhb/redux-ui // Definitions by: Andy Shu Xin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 +/// import * as Redux from 'redux'; export interface uiParams { diff --git a/reflux/reflux-tests.ts b/reflux/reflux-tests.ts index 7a392282fa..150e40db03 100644 --- a/reflux/reflux-tests.ts +++ b/reflux/reflux-tests.ts @@ -1,5 +1,4 @@ import Reflux = require("reflux"); -import React = require("react"); var syncActions = Reflux.createActions([ "statusUpdate", diff --git a/request/index.d.ts b/request/index.d.ts index d576c82e3b..e65c8308d6 100644 --- a/request/index.d.ts +++ b/request/index.d.ts @@ -145,6 +145,7 @@ declare namespace request { export interface RequestResponse extends http.IncomingMessage { request: Options; + body: any; } export interface HttpArchiveRequest { diff --git a/resolve/resolve-tests.ts b/resolve/resolve-tests.ts index 3cac830c58..1f9f50b5ee 100644 --- a/resolve/resolve-tests.ts +++ b/resolve/resolve-tests.ts @@ -1,5 +1,3 @@ -/// - import * as fs from 'fs'; import * as resolve from 'resolve'; diff --git a/revalidate/index.d.ts b/revalidate/index.d.ts new file mode 100644 index 0000000000..a764e41e15 --- /dev/null +++ b/revalidate/index.d.ts @@ -0,0 +1,67 @@ +// Type definitions for revalidate 1.1 +// Project: https://github.com/jfairbank/revalidate +// Definitions by: alex3165 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// This project is licensed under the MIT license. +// Copyrights are respective of each contributor listed at the beginning of each definition file. + +// 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. + +export interface CombineValidatorsOptions { + serializeValues?: (values: any) => any; +} + +export interface Config { + field?: any; + message?: string; +} + +interface Multiple { + multiple?: boolean; +} + +export type ComposeConfig = Config & Multiple; + +export interface ParsedField { + isArray: boolean; + baseName: string; + fullName: string; +} + +export type MessageCreator = ((field: any) => any) | string; +export type ValidatorImpl = (message: any) => (value: any, allValues?: any) => any; +export type Comparer = (a: any, b: any) => boolean; + +export type ConfiguredValidator = (value?: any, allValues?: any) => any; +export type UnconfiguredValidator = (config?: string | Config, value?: any, allValues?: any) => any; +export type ConfiguredCombinedValidator = (value?: any, allValues?: any) => any; + +export type CurryableValidator = (config?: string | Config) => ConfiguredValidator; +export type ComposedCurryableValidator = (config?: string | ComposeConfig) => ConfiguredValidator; + +export type ConfigurableValidator = UnconfiguredValidator & CurryableValidator; + +export type Validator = ConfiguredValidator & UnconfiguredValidator; + +export function createValidator(curriedDefinition: ValidatorImpl, defaultMessageCreator?: MessageCreator): ConfigurableValidator; +export function composeValidators(firstValidator: Validator | any, ...validators: Validator[]): ComposedCurryableValidator; +export function combineValidators(validators: any, options?: CombineValidatorsOptions): ConfiguredCombinedValidator; + +export function hasLengthBetween(min: number, max: number): ConfigurableValidator; +export function hasLengthGreaterThan(min: number): ConfigurableValidator; +export function hasLengthLessThan(max: number): ConfigurableValidator; + +export function isAlphabetic(config?: string | Config, value?: any, allValues?: any): ConfiguredValidator | any; +export function isAlphaNumeric(config?: string | Config, value?: any, allValues?: any): ConfiguredValidator | any; +export function isNumeric(config?: string | Config, value?: any, allValues?: any): ConfiguredValidator | any; +export function isOneOf(config?: string | Config, value?: any, allValues?: any): ConfiguredValidator | any; +export function isRequired(config?: string | Config, value?: any, allValues?: any): ConfiguredValidator | any; +export function isRequiredIf(config?: string | Config, value?: any, allValues?: any): ConfiguredValidator | any; + +export function matchesField(otherField: string, otherFieldLabel: string): ConfigurableValidator; +export function matchesPattern(regex: RegExp): ConfigurableValidator; diff --git a/revalidate/revalidate-tests.ts b/revalidate/revalidate-tests.ts new file mode 100644 index 0000000000..798089d6a0 --- /dev/null +++ b/revalidate/revalidate-tests.ts @@ -0,0 +1,53 @@ +import r = require("revalidate"); + +const isValidEmail = r.createValidator( + message => value => { + if (value && !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)) { + return message + } + }, + 'Invalid email address' +); + +const isGreaterThan = (n: any) => r.createValidator( + message => value => { + if (value && Number(value) <= n) { + return message + } + }, + field => `${field} must be greater than ${n}` +); + +const customIsRequired = r.isRequired({ message: 'Required' }); + +const lessThan = r.hasLengthLessThan(16)({ message: 'Must be 15 characters or less' }); + +const username = r.composeValidators( + customIsRequired, + lessThan +)(); + +const email = r.composeValidators( + customIsRequired, + isValidEmail +)(); + +const isNumber = r.isNumeric({ + message: 'Must be a number' +}); + +const isGreater = isGreaterThan(17)({ + message: 'Sorry, you must be at least 18 years old' +}); + +const age = r.composeValidators( + customIsRequired, + isNumber, + isGreater +)(); + +const validate = r.combineValidators({ + username, + email, + age +}); diff --git a/revalidate/tsconfig.json b/revalidate/tsconfig.json new file mode 100644 index 0000000000..3c031968d3 --- /dev/null +++ b/revalidate/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "revalidate-tests.ts" + ] +} diff --git a/revalidate/tslint.json b/revalidate/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/revalidate/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/rvo2/index.d.ts b/rvo2/index.d.ts new file mode 100644 index 0000000000..88ee40cd96 --- /dev/null +++ b/rvo2/index.d.ts @@ -0,0 +1,581 @@ +// Type definitions for rvo2 +// Project: https://github.com/TNOCS/rvo2 +// Definitions by: Erik Vullings +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace rvo2 { + + class Line { + /** + * A point on the directed line. + */ + point: Vector2; + + /** + * The direction of the directed line. + */ + direction: Vector2; + } + + /** + * The Agent class has no public members or methods. + * + * @class Agent + */ + class Agent { } + + /** + * The KdTree class has no public members or methods. + * + * @class KdTree + */ + class KdTree { } + + /** + * The Obstacle class has no public members or methods. + * + * @class Obstacle + */ + class Obstacle { } + + /** + * A simple two dimensional vector with an x and y position. + * + * @class Vector2 + */ + class Vector2 { + /** + * Creates an instance of Vector2. + * + * @param {number} x + * @param {number} y + * + * @memberOf Vector2 + */ + constructor(x: number, y: number); + + /** + * Returns the x position. + * + * @returns {number} + * + * @memberOf Vector2 + */ + x(): number; + /** + * Returns the y position. + * + * @returns {number} + * + * @memberOf Vector2 + */ + y(): number; + /** + * Add two vectors. + * + * @param {Vector2} v + * @returns {Vector2} + * + * @memberOf Vector2 + */ + add(v: Vector2): Vector2; + /** + * Subtract two vectors. + * + * @param {Vector2} v + * @returns {Vector2} + * + * @memberOf Vector2 + */ + sub(v: Vector2): Vector2; + /** + * Multiplies the vector by a scalar. + * + * @param {number} s + * @returns {Vector2} + * + * @memberOf Vector2 + */ + mul(s: number): Vector2; + } + + /** + * An array of Vector2 vectors. + * + * @class vectorvector + */ + class vectorvector { + constructor(size?: number); + + [index: number]: Vector2; + } + + /** + * Simulation engine. + * + * @class sim + */ + class RVOSimulator { + constructor(); + + /** + * Constructs a simulator instance and sets the default + * properties for any new agent that is added. + * + * @param {number} timeStep The time step of the simulation. + * Must be positive. + * @param {number} neighborDist The default maximum distance (center point + * to center point) to other agents a new agent + * takes into account in the navigation. The + * larger this number, the longer he running + * time of the simulation. If the number is too + * low, the simulation will not be safe. Must be + * non-negative. + * @param {number} maxNeighbors The default maximum number of other agents a + * new agent takes into account in the + * navigation. The larger this number, the + * longer the running time of the simulation. + * If the number is too low, the simulation + * will not be safe. + * @param {number} timeHorizon The default minimal amount of time for which + * a new agent's velocities that are computed + * by the simulation are safe with respect to + * other agents. The larger this number, the + * sooner an agent will respond to the presence + * of other agents, but the less freedom the + * agent has in choosing its velocities. + * Must be positive. + * @param {number} timeHorizonObst The default minimal amount of time for which + * a new agent's velocities that are computed + * by the simulation are safe with respect to + * obstacles. The larger this number, the + * sooner an agent will respond to the presence + * of obstacles, but the less freedom the agent + * has in choosing its velocities. + * Must be positive. + * @param {number} radius The default radius of a new agent. + * Must be non-negative. + * @param {number} maxSpeed The default maximum speed of a new agent. + * Must be non-negative. + * @param {Vector2} velocity The default initial two-dimensional linear + * velocity of a new agent (optional). + */ + constructor(timeStep: number, neighborDist: number, maxNeighbors: number, + timeHorizon: number, timeHorizonObst: number, radius: number, + maxSpeed: number, velocity?: Vector2); + + /** + * Sets the time step of the simulation. + * + * @param {number} timeStep The time step of the simulation. + * Must be positive. + * + * @memberOf sim + */ + setTimeStep(timeStep: number): void; + + /** + * Lets the simulator perform a simulation step and updates the + * two-dimensional position and two-dimensional velocity of each agent. + * + * @memberOf RVOSimulator + */ + doStep(): void; + + /** + * Sets the default properties for any new agent that is added. + * @param {number} neighborDist The default maximum distance (center point + * to center point) to other agents a new agent + * takes into account in the navigation. The + * larger this number, the longer he running + * time of the simulation. If the number is too + * low, the simulation will not be safe. + * Must be non-negative. + * @param {number} maxNeighbors The default maximum number of other agents a + * new agent takes into account in the + * navigation. The larger this number, the + * longer the running time of the simulation. + * If the number is too low, the simulation + * will not be safe. + * @param {number} timeHorizon The default minimal amount of time for which + * a new agent's velocities that are computed + * by the simulation are safe with respect to + * other agents. The larger this number, the + * sooner an agent will respond to the presence + * of other agents, but the less freedom the + * agent has in choosing its velocities. + * Must be positive. + * @param {number} timeHorizonObst The default minimal amount of time for which + * a new agent's velocities that are computed + * by the simulation are safe with respect to + * obstacles. The larger this number, the + * sooner an agent will respond to the presence + * of obstacles, but the less freedom the agent + * has in choosing its velocities. + * Must be positive. + * @param {number} radius The default radius of a new agent. + * Must be non-negative. + * @param {number} maxSpeed The default maximum speed of a new agent. + * Must be non-negative. + * @param {Vector2} velocity The default initial two-dimensional linear + * velocity of a new agent (optional). + */ + setAgentDefaults(neighborDist: number, maxNeighbors: number, timeHorizon: number, timeHorizonObst: number, radius: number, maxSpeed: number, velocity?: Vector2): void; + /** + * Adds a new agent with default properties to the simulation. + * + * @param {Vector2} position The two-dimensional starting position of this agent. + + * @returns {number} The number of the agent, or RVO::RVO_ERROR when the * agent defaults have not been set. + * + * @membeim + */ + addAgent(position: Vector2): number; + + /** + * Adds a new agent to the simulation. + * + * @param {Vector2} position The two-dimensional starting position of + * this agent. + * @param {number} neighborDist The maximum distance (center point to + * center point) to other agents this agent + * takes into account in the navigation. The + * larger this number, the longer the running + * of the simulation. If the number is too + * low, the simulation will not be safe. + * Must be non-negative. + * @param {number} maxNeighbors The maximum number of other agents this + * agent takes into account in the navigation. + * The larger this number, the longer the + * running time of the simulation. If the + * number is too low, the simulation will not + * safe. + * @param {number} timeHorizon The minimal amount of time for which this + * agent's velocities that are computed by the + * simulation are safe with respect to other + * agents. The larger this number, the sooner + * this agent will respond to the presence of + * other agents, but the less freedom this + * agent has in choosing its velocities. + * be positive. + * @param {number} timeHorizonObst The minimal amount of time for which this + * agevelocities that are computed by the + * simulation are safe with respect to + * obst. The larger this number, the + * sooner this agent will respond to the + * presence of obstacles, but the less freedom + * this agent has in choosing its velocities. + * Must be positive. + * @param {number} radius The radius of this agent. + * Must be non-negative. + * @param {number} maxSpeed The maximum speed of this agent. + * Must be non-negative. + * @param {number} velocity The initial two-dimensional linear velocity + * of this agent (optional). + * @returns {number} The number of the agent. + */ + addAgent(position: Vector2, neighborDist: number, maxNeighbors: number, + timeHorizon: number, timeHorizonObst: number, radius: number, + maxSpeed: number, velocity: Vector2): number; + + /** + * Adds a new obstacle to the simulation. + * + * To add a "negative" obstacle, e.g. a bounding polygon around + * the environment, the vertices should be listed in clockwise order. + * + * @param {vectorvector} vertices List of the vertices of the polygonal + * obstacle in counterclockwise order. + * @returns {number} The number of the first vertex of the obstacle, + * or RVO::RVO_ERROR when the number of vertices is less than two. + */ + addObstacle(vertices: vectorvector): number; + + /** + * Returns the position of agent at the specified index. + * + * @param {number} index Index of the agent. Must be >= 0. + * @returns {Vector2} Position of the agent. + * + * @memberOf sim + */ + getAgentPosition(index: number): Vector2; + + /** + * Sets the two-dimensional preferred velocity of a specified agent. + * @param {number} agentNo The number of the agent whose two-dimensional + * preferred velocity is to be modified. + * @param {Vector2} prefVelocity The replacement of the two-dimensional + * preferred velocity. + */ + setAgentPrefVelocity(agentNo: number, prefVelocity: Vector2): void; + + /** + * Returns the specified agent neighbor of the specified agent. + * + * @param {number} agentNo The number of the agent whose agent + * neighbor is to be retrieved. + * @param {number} neighborNo The number of the agent neighbor to be + * retrieved. + * @returns The number of the neighboring agent. + */ + getAgentAgentNeighbor(agentNo: number, neighborNo: number): number; + + /** + * Returns the maximum neighbor count of a specified agent. + * + * @param {number} agentNo The number of the agent whose maximum neighbor count is + * to be retrieved. + * @return {number} The present maximum neighbor count of the agent. + */ + getAgentMaxNeighbors(agentNo: number): number; + + /** + * Returns the maximum speed of a specified agent. + * + * @param {number} agentNo The number of the agent whose maximum speed is to be retrieved. + * @return {number} The present maximum speed of the agent. + */ + getAgentMaxSpeed(agentNo: number): number; + + /** + * Returns the maximum neighbor distance of a specified agent. + * @param {number} agentNo The number of the agent whose maximum + * neighbor distance is to be retrieved. + * @return The present maximum neighbor distance of the agent. + */ + getAgentNeighborDist(agentNo: number): number; + + /** + * Returns the count of agent neighbors taken into account to + * compute the current velocity for the specified agent. + * + * @param {number} agentNo The number of the agent whose count of agent + * neighbors is to be retrieved. + * @return {number} The count of agent neighbors taken into account to compute + * the current velocity for the specified agent. + */ + getAgentNumAgentNeighbors(agentNo: number): number; + + /** + * Returns the count of obstacle neighbors taken into account + * to compute the current velocity for the specified agent. + * + * @param {number} agentNo The number of the agent whose count of + * obstacle neighbors is to be retrieved. + * @return {number} The count of obstacle neighbors taken into account to + * compute the current velocity for the specified agent. + */ + getAgentNumObstacleNeighbors(agentNo: number): number; + + + /** + * Returns the count of ORCAconstraints used to compute + * + * the current velocity for the specified agent. + * + * @param {number} agentNo The number of the agent whose count of ORCA + * constraints is to be retrieved. + * + * @return {number} The count of ORCAconstraints used to compute the current + * + * velocity for the specified agent. + */ + getAgentNumORCALines(agentNo: number): number; + + /** + * Returns the specified obstacle neighbor of the specified agent. + * + * @param {number} agentNo The number of the agent whose obstacle + * neighbor is to be retrieved. + * @param {number} neighborNo The number of the obstacle neighbor to be + * retrieved. + * @return {number} The number of the first vertex of the neighboring obstacle edge. + */ + getAgentObstacleNeighbor(agentNo: number, neighborNo: number): number; + + /** + * Returns the specified ORCA constraint of the specified agent. + * + * The halfplane to the left of the line is the region of + * permissible velocities with respect to the specified + * ORCAconstraint. + * + * @param {number} agentNo The number of the agent whose ORCA constraint is to be retrieved. + * + * @param {number} lineNo The number of the ORCAconstraint to be retrieved. + * @return {number} A line representing the specified ORCAconstraint. + * + * + */ + getAgentORCALine(agentNo: number, lineNo: number): Line; + + /** + * Returns the two-dimensional position of a specified + * agent. + * @param {number} agentNo The number of the agent whose two-dimensional position + * is to be retrieved. + * @return {number} The present two-dimensional position of the (center of the) agent. + */ + getAgentPosition(agentNo: number): Vector2; + + /** + * Returns the two-dimensional preferred velocity of a + * specified agent. + * @param {number} agentNo The number of the agent whose two-dimensional + * preferred velocity is to be retrieved. + * @return {number} The present two-dimensional preferred velocity of the agent. + */ + getAgentPrefVelocity(agentNo: number): Vector2; + + /** + * Returns the radius of a specified agent. + * @param {number} agentNo The number of the agent whose radius is to be retrieved. + * @return {number} The present radius of the agent. + */ + getAgentRadius(agentNo: number): number; + + /** + * Returns the time horizon of a specified agent. + * @param {number} agentNo The number of the agent whose time horizon is to be retrieved. + * @return {number} The present time horizon of the agent. + */ + getAgentTimeHorizon(agentNo: number): number; + + /** + * Returns the time horizon with respect to obstacles of a specified agent. + * + * @param {number} agentNo The number of the agent whose time horizon + * with respect to obstacles is to be retrieved. + * @return {number} The present time horizon with respect to obstacles of the + * agent. + */ + getAgentTimeHorizonObst(agentNo: number): number; + + /** + * Returns the two-dimensional linear velocity of a + * specified agent. + * @param {number} agentNo The number of the agent whose two-dimensional linear + * velocity is to be retrieved. + * @return {Vector2} The present two-dimensional linear velocity of the agent. + */ + getAgentVelocity(agentNo: number): Vector2; + + /** + * Returns the global time of the simulation. + * + * @return {number} The present global time of the simulation (zero initially). + */ + getGlobalTime(): number; + + /** + * Returns the count of agents in the simulation. + * + * @return {number} The count of agents in the simulation. + */ + getNumAgents(): number; + + /** + * Returns the count of obstacle vertices in the simulation. + * + * @return {number} The count of obstacle vertices in the simulation. + */ + getNumObstacleVertices(): number; + + /** + * Returns the two-dimensional position of a specified obstacle vertex. + * @param {number} vertexNo The number of the obstacle vertex to be retrieved. + * @return {Vector2} The two-dimensional position of the specified obstacle vertex. + */ + getObstacleVertex(vertexNo: number): Vector2; + + /** + * Returns the number of the obstacle vertex succeeding the specified obstacle vertex in its polygon. + * + * @param {number} vertexNo The number of the obstacle vertex whose + * successor is to be retrieved. + * @return {number} The number of the obstacle vertex succeeding the specified + * obstacle vertex in its polygon. + */ + getNextObstacleVertexNo(vertexNo: number): number; + + /** + * Returns the number of the obstacle vertex preceding the specified obstacle + * vertex in its polygon. + * + * @param {number} vertexNo The number of the obstacle vertex whose + * predecessor is to be retrieved. + * @return {number} The number of the obstacle vertex preceding the specified + * obstacle vertex in its polygon. + */ + getPrevObstacleVertexNo(vertexNo: number): number; + + /** + * Returns the time step of the simulation. + * + * @return {number} The present time step of the simulation. + */ + getTimeStep(): number; + + /** + * Processes the obstacles that have been added so that they are accounted for in + * the simulation. + * + * Obstacles added to the simulation after this function has + * been called are not accounted for in the simulation. + */ + processObstacles(): void; + + /** + * Performs a visibility query between the two specified points with respect to + * the obstacles + * + * @param {number} point1 The first point of the query. + * @param {number} point2 The second point of the query. + * @param {number} radius The minimal distance between the line + * connecting the two points and the obstacles + * in order for the points to be mutually + * visible (optional). Must be non-negative. + * @return {number} A boolean specifying whether the two points are mutually + * visible. Returns true when the obstacles have not been processed. + */ + queryVisibility(point1: Vector2, point2: Vector2, radius?: number): number; + } + + /** + * Computes the length of a specified two-dimensional vector. + * + * @param {Vector2} v The two-dimensional vector whose length is to be computed. + * @returns {number} The length of the two-dimensional vector. + * + * @memberOf sim + */ + function abs(v: Vector2): number; + + /** + * Computes the squared length of a specified two-dimensional vector. + * @param {Vector2} v The two-dimensional vector whose squared length is to be computed. + * @returns {number} The squared length of the two-dimensional vector. + */ + function absSq(v: Vector2): number; + + /** + * Computes the determinant of a two-dimensional square matrix with + * rows consisting of the specified two-dimensional vectors. + * @param {Vector2} v1 The top row of the two-dimensional square matrix. + * @param {Vector2} v2 The bottom row of the two-dimensional square matrix. + * @returns {number} The determinant of the two-dimensional square matrix. + */ + function det(v1: Vector2, v2: Vector2): number; + + /** + * Computes the normalization of the specified two-dimensional vector. + * @param {Vector2} vector The two-dimensional vector whose normalization + * is to be computed. + * returns {Vector2} The normalization of the two-dimensional vector. + */ + function normalize(vector: Vector2): Vector2 + +} + +export = rvo2; \ No newline at end of file diff --git a/rvo2/rvo2-tests.ts b/rvo2/rvo2-tests.ts new file mode 100644 index 0000000000..80906011e9 --- /dev/null +++ b/rvo2/rvo2-tests.ts @@ -0,0 +1,137 @@ +import { Vector2, vectorvector, RVOSimulator, absSq, normalize } from './index'; + +// Some examples of vector functions. +const v1 = new Vector2(-1, 2); +const v2 = new Vector2(1, 2); +const v3 = v1.mul(3); // -3, 6 +const v4 = v1.sub(v2); // -2, 0 +const v5 = v1.add(v2); // 0, 4 + +function setupScenario(sim: RVOSimulator, goals: vectorvector) { + sim.setTimeStep(0.25); + /* Specify the default parameters for agents that are subsequently added. */ + sim.setAgentDefaults(15, 10, 5, 5, 2, 2); + + /* + * Add agents, specifying their start position, and store their goals on the + * opposite side of the environment. + */ + for (var i = 0; i < 5; ++i) { + for (var j = 0; j < 5; ++j) { + var index = sim.addAgent(new Vector2(55 + i * 10, 55 + j * 10)); + goals[index] = new Vector2(-75, -75); + + index = sim.addAgent(new Vector2(-55 - i * 10, 55 + j * 10)); + goals[index] = new Vector2(75, -75); + + index = sim.addAgent(new Vector2(55 + i * 10, -55 - j * 10)); + goals[index] = new Vector2(-75, 75); + + index = sim.addAgent(new Vector2(-55 - i * 10, -55 - j * 10)); + goals[index] = new Vector2(75, 75); + } + } + + /* + * Add (polygonal) obstacles, specifying their vertices in counterclockwise + * order. + */ + const obstacle1 = new vectorvector(4) + , obstacle2 = new vectorvector(4) + , obstacle3 = new vectorvector(4) + , obstacle4 = new vectorvector(4); + + obstacle1[0] = new Vector2(-10, 40); + obstacle1[1] = new Vector2(-40, 40); + obstacle1[2] = new Vector2(-40, 10); + obstacle1[3] = new Vector2(-10, 10); + + obstacle2[0] = new Vector2(10, 40); + obstacle2[1] = new Vector2(10, 10); + obstacle2[2] = new Vector2(40, 10); + obstacle2[3] = new Vector2(40, 40); + + obstacle3[0] = new Vector2(10, -40); + obstacle3[1] = new Vector2(40, -40); + obstacle3[2] = new Vector2(40, -10); + obstacle3[3] = new Vector2(10, -10); + + obstacle4[0] = new Vector2(-10, -40); + obstacle4[1] = new Vector2(-10, -10); + obstacle4[2] = new Vector2(-40, -10); + obstacle4[3] = new Vector2(-40, -40); + + sim.addObstacle(obstacle1); + sim.addObstacle(obstacle2); + sim.addObstacle(obstacle3); + sim.addObstacle(obstacle4); + + /* Process the obstacles so that they are accounted for in the simulation. */ + sim.processObstacles(); +} + +function updateVisualization(sim: RVOSimulator) +{ + /* Output the current global time. */ + const time = sim.getGlobalTime(); + // console.log(`Time: ${time}`); + /* Output the current position of all the agents. */ + for (let i = 0; i < sim.getNumAgents(); ++i) { + const p = sim.getAgentPosition(i); + // console.log(`#${i}) x: ${p.x()}, y: ${p.y()}`); + } +} + +function setPreferredVelocity(sim: RVOSimulator, goals: vectorvector) { + for (var i = 0; i < sim.getNumAgents(); i++) { + const delta = goals[i].sub(sim.getAgentPosition(i)); + + /* + * Perturb a little to avoid deadlocks due to perfect symmetry. + */ + const angle = Math.random() * 2.0 * Math.PI; + const dist = Math.random() * 0.0001; + + var goalVector = new Vector2(delta.x() + dist * Math.cos(angle), delta.y() + dist * Math.sin(angle)); + + if (absSq(goalVector) > 1.0) { + goalVector = normalize(goalVector); + } + + sim.setAgentPrefVelocity(i, goalVector); + } +} + +function reachedGoal(sim: RVOSimulator, goals: vectorvector) { + /* Check if all agents have reached their goals. */ + for (var i = 0; i < sim.getNumAgents(); ++i) { + const dist = sim.getAgentPosition(i).sub(goals[i]); + if (absSq(dist) > 400) { // 400 <= 20 x 20 + return false; + } + } + return true; +} + +function main(debug = false) { + const nbrAgents = 100; + const sim = new RVOSimulator(); + const goals = new vectorvector(nbrAgents); + + setupScenario(sim, goals); + + // sim.addObstacle(vv); + var i = 0; + do { + if (++i % 10 === 0) { + // console.log('TIME: ' + i); + } + setPreferredVelocity(sim, goals); + if (debug) { updateVisualization(sim); } + sim.doStep(); + } while (!reachedGoal(sim, goals)); + + // console.log('Done'); +} + +main(); diff --git a/jsonschema/tsconfig.json b/rvo2/tsconfig.json similarity index 93% rename from jsonschema/tsconfig.json rename to rvo2/tsconfig.json index d2f3e4dcab..bf6778173d 100644 --- a/jsonschema/tsconfig.json +++ b/rvo2/tsconfig.json @@ -17,6 +17,6 @@ }, "files": [ "index.d.ts", - "jsonschema-tests.ts" + "rvo2-tests.ts" ] -} \ No newline at end of file +} diff --git a/rx.wamp/rx.wamp-tests.ts b/rx.wamp/rx.wamp-tests.ts index 2b6d4c95bc..3bd6ddbffb 100644 --- a/rx.wamp/rx.wamp-tests.ts +++ b/rx.wamp/rx.wamp-tests.ts @@ -1,6 +1,3 @@ - -/// - import * as autobahn from "autobahn"; import {IWampEvent} from "rx.wamp"; diff --git a/s3-upload-stream/s3-upload-stream-tests.ts b/s3-upload-stream/s3-upload-stream-tests.ts index ef03000ad2..0f02beb63f 100644 --- a/s3-upload-stream/s3-upload-stream-tests.ts +++ b/s3-upload-stream/s3-upload-stream-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as fs from 'fs'; import * as S3Stream from 's3-upload-stream'; import * as AWS from 'aws-sdk'; diff --git a/samchon-framework/index.d.ts b/samchon-framework/index.d.ts index 558efd674a..fa540e033d 100644 --- a/samchon-framework/index.d.ts +++ b/samchon-framework/index.d.ts @@ -1,10811 +1,13 @@ -// Type definitions for Samchon Framework 2.0 +// Type definitions for Samchon Framework v2.0.x // Project: https://github.com/samchon/framework // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// +// Samchon-Framework is renamed to Samchon declare module "samchon-framework" { + import samchon = require("samchon"); export = samchon; -} - -/** - * # Samchon-Framework - * - *
              - * - * - * Samchon, a OON (Object-Oriented Network) framework. - * - * With Samchon Framework, you can implement distributed processing system within framework of OOD like handling S/W - * objects (classes). You can realize cloud and distributed system very easily with provided system templates and even - * integration with C++ is possible. - * - * The goal, ultimate utilization model of Samchon Framework is, building cloud system with NodeJS and taking heavy works - * to C++ distributed systems with provided modules (those are system templates). - * - * @git https://github.com/samchon/framework - * @author Jeongho Nam - */ -declare namespace samchon { - /** - * Running on Node. - * - * Test whether the JavaScript is running on Node. - * - * @references http://stackoverflow.com/questions/17575790/environment-detection-node-js-or-browser - */ - function is_node(): boolean; -} -declare namespace samchon.collections { - /** - * A {@link Vector} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link CollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link push} - * - {@link push_back} - * - {@link unshift} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - {@link pop_back} - * - {@link shift} - * - {@link pop} - * - {@link splice} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link Vector} - * {@link Vector Vectors}s are sequence containers representing arrays that can change in size. - * - * Just like arrays, {@link Vector}s use contiguous storage locations for their elements, which means that their - * elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in - * arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically - * by the container. - * - * Internally, {@link Vector}s use a dynamically allocated array to store their elements. This array may need to - * be reallocated in order to grow in size when new elements are inserted, which implies allocating a new array - * and moving all elements to it. This is a relatively expensive task in terms of processing time, and thus, - * {@link Vector}s do not reallocate each time an element is added to the container. - * - * Instead, {@link Vector} containers may allocate some extra storage to accommodate for possible growth, and - * thus the container may have an actual {@link capacity} greater than the storage strictly needed to contain its - * elements (i.e., its {@link size}). Libraries can implement different strategies for growth to balance between - * memory usage and reallocations, but in any case, reallocations should only happen at logarithmically growing - * intervals of {@link size} so that the insertion of individual elements at the end of the {@link Vector} can be - * provided with amortized constant time complexity (see {@link push_back push_back()}). - * - * Therefore, compared to arrays, {@link Vector}s consume more memory in exchange for the ability to manage - * storage and grow dynamically in an efficient way. - * - * Compared to the other dynamic sequence containers ({@link Deque}s, {@link List}s), {@link Vector Vectors} are - * very efficient accessing its elements (just like arrays) and relatively efficient adding or removing elements - * from its end. For operations that involve inserting or removing elements at positions other than the end, they - * perform worse than the others, and have less consistent iterators and references than {@link List}s. - * - * - * - * - * - *

              Container properties

              - *
              - *
              Sequence
              - *
              - * Elements in sequence containers are ordered in a strict linear sequence. Individual elements are - * accessed by their position in this sequence. - *
              - * - *
              Dynamic array
              - *
              - * Allows direct access to any element in the sequence, even through pointer arithmetics, and provides - * relatively fast addition/removal of elements at the end of the sequence. - *
              - *
              - * - * @param Type of the elements. - * - * @reference http://www.cplusplus.com/reference/vector/vector - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class ArrayCollection extends std.Vector implements ICollection { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - push(...items: T[]): number; - /** - * @inheritdoc - */ - push_back(val: T): void; - /** - * @hidden - */ - protected _Insert_by_repeating_val(position: std.VectorIterator, n: number, val: T): std.VectorIterator; - /** - * @hidden - */ - protected _Insert_by_range>(position: std.VectorIterator, begin: InputIterator, end: InputIterator): std.VectorIterator; - /** - * @hidden - */ - protected _Erase_by_range(first: std.VectorIterator, last: std.VectorIterator): std.VectorIterator; - /** - * @hidden - */ - private notify_insert(first, last); - /** - * @hidden - */ - private notify_erase(first, last); - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.VectorIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.VectorIterator, last: std.VectorIterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener): void; - addEventListener(type: "erase", listener: CollectionEventListener): void; - addEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener): void; - removeEventListener(type: "erase", listener: CollectionEventListener): void; - removeEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - unshift(...items: U[]): number; - /** - * @inheritdoc - */ - pop(): T; - /** - * @inheritdoc - */ - splice(start: number): T[]; - /** - * @inheritdoc - */ - splice(start: number, deleteCount: number, ...items: T[]): T[]; - } -} -declare namespace samchon.library { - /** - * A basic event class of Samchon Framework. - * - * @reference https://developer.mozilla.org/en-US/docs/Web/API/Event - * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-EventDispatcher - * @author Jeongho Nam - */ - class BasicEvent { - protected type_: string; - protected target_: IEventDispatcher; - private currentTarget_; - protected trusted_: boolean; - protected bubbles_: boolean; - protected cancelable_: boolean; - protected defaultPrevented_: boolean; - protected cancelBubble_: boolean; - private timeStamp_; - constructor(type: string, bubbles?: boolean, cancelable?: boolean); - /** - * @inheritdoc - */ - initEvent(type: string, bubbles: boolean, cancelable: boolean): void; - /** - * @inheritdoc - */ - /** - * @inheritdoc - */ - stopImmediatePropagation(): void; - /** - * @inheritdoc - */ - stopPropagation(): void; - /** - * @inheritdoc - */ - readonly type: string; - /** - * @inheritdoc - */ - target: IEventDispatcher; - /** - * @inheritdoc - */ - readonly currentTarget: IEventDispatcher; - /** - * @inheritdoc - */ - readonly isTrusted: boolean; - /** - * @inheritdoc - */ - readonly bubbles: boolean; - /** - * @inheritdoc - */ - readonly cancelable: boolean; - /** - * @inheritdoc - */ - readonly eventPhase: number; - /** - * @inheritdoc - */ - readonly defaultPrevented: boolean; - /** - * @inheritdoc - */ - readonly srcElement: Element; - /** - * @inheritdoc - */ - readonly cancelBubble: boolean; - /** - * @inheritdoc - */ - readonly timeStamp: number; - /** - * Don't know what it is. - */ - readonly returnValue: boolean; - } -} -declare namespace samchon.collections { - /** - * Type of function pointer for listener of {@link CollectionEvent CollectionEvents}. - */ - type CollectionEventListener = (event: CollectionEvent) => void; -} -declare namespace samchon.collections { - /** - * An event occured in a {@link ICollection collection} object. - * - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class CollectionEvent extends library.BasicEvent { - /** - * @hidden - */ - private first_; - /** - * @hidden - */ - private last_; - /** - * @hidden - */ - private temporary_container_; - /** - * @hidden - */ - private origin_first_; - /** - * Initialization Constructor. - * - * @param type Type of collection event. - * @param first An {@link Iterator} to the initial position in this {@link CollectionEvent}. - * @param last An {@link Iterator} to the final position in this {@link CollectionEvent}. - */ - constructor(type: string, first: std.Iterator, last: std.Iterator); - constructor(type: "insert", first: std.Iterator, last: std.Iterator); - constructor(type: "erase", first: std.Iterator, last: std.Iterator); - constructor(type: "refresh", first: std.Iterator, last: std.Iterator); - /** - * Associative target, the {@link ICollection collection}. - */ - readonly target: ICollection; - /** - * An {@link Iterator} to the initial position in this {@link CollectionEvent}. - */ - readonly first: std.Iterator; - /** - * An {@link Iterator} to the final position in this {@link CollectionEvent}. - */ - readonly last: std.Iterator; - /** - * @inheritdoc - */ - preventDefault(): void; - } -} -declare namespace samchon.collections.CollectionEvent { - const INSERT: "insert"; - const ERASE: "erase"; - const REFRESH: "refresh"; -} -declare namespace samchon.collections { - /** - * A {@link Deque} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link CollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link push} - * - {@link push_front} - * - {@link push_back} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - {@link pop_front} - * - {@link pop_back} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link Deque} - * {@link Deque} (usually pronounced like "*deck*") is an irregular acronym of **d**ouble-**e**nded **q**ueue. - * Double-ended queues are sequence containers with dynamic sizes that can be expanded or contracted on both ends - * (either its front or its back). - * - * Specific libraries may implement deques in different ways, generally as some form of dynamic array. But in any - * case, they allow for the individual elements to be accessed directly through random access iterators, with - * storage handled automatically by expanding and contracting the container as needed. - * - * Therefore, they provide a functionality similar to vectors, but with efficient insertion and deletion of - * elements also at the beginning of the sequence, and not only at its end. But, unlike {@link Vector Vectors}, - * {@link Deque Deques} are not guaranteed to store all its elements in contiguous storage locations: accessing - * elements in a deque by offsetting a pointer to another element causes undefined behavior. - * - * Both {@link Vector}s and {@link Deque}s provide a very similar interface and can be used for similar purposes, - * but internally both work in quite different ways: While {@link Vector}s use a single array that needs to be - * occasionally reallocated for growth, the elements of a {@link Deque} can be scattered in different chunks of - * storage, with the container keeping the necessary information internally to provide direct access to any of its - * elements in constant time and with a uniform sequential interface (through iterators). Therefore, - * {@link Deque Deques} are a little more complex internally than {@link Vector}s, but this allows them to grow - * more efficiently under certain circumstances, especially with very long sequences, where reallocations become - * more expensive. - * - * For operations that involve frequent insertion or removals of elements at positions other than the beginning or - * the end, {@link Deque Deques} perform worse and have less consistent iterators and references than - * {@link List Lists}. - * - * - * - * - * - *

              Container properties

              - *
              - *
              Sequence
              - *
              Elements in sequence containers are ordered in a strict linear sequence. Individual elements - * are accessed by their position in this sequence.
              - * - *
              Dynamic array
              - *
              Generally implemented as a dynamic array, it allows direct access to any element in the - * sequence and provides relatively fast addition/removal of elements at the beginning or the end - * of the sequence.
              - *
              - * - * @param Type of the elements. - * - * @reference http://www.cplusplus.com/reference/deque/deque/ - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class DequeCollection extends std.Deque implements ICollection { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - push(...items: T[]): number; - /** - * @inheritdoc - */ - push_back(val: T): void; - /** - * @hidden - */ - protected _Insert_by_repeating_val(position: std.DequeIterator, n: number, val: T): std.DequeIterator; - /** - * @hidden - */ - protected _Insert_by_range>(position: std.DequeIterator, begin: InputIterator, end: InputIterator): std.DequeIterator; - /** - * @inheritdoc - */ - pop_back(): void; - /** - * @hidden - */ - protected _Erase_by_range(first: std.DequeIterator, last: std.DequeIterator): std.DequeIterator; - /** - * @hidden - */ - private notify_insert(first, last); - /** - * @hidden - */ - private notify_erase(first, last); - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.DequeIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.DequeIterator, last: std.DequeIterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener): void; - addEventListener(type: "erase", listener: CollectionEventListener): void; - addEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener): void; - removeEventListener(type: "erase", listener: CollectionEventListener): void; - removeEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - } -} -declare namespace samchon.collections { - /** - * A {@link HashMap} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link MapCollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link insert_or_assign} - * - {@link emplace} - * - {@link set} - * - {@link push} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - {@link extract} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link HashMap} - * {@link HashMap HashMaps} are associative containers that store elements formed by the combination of a - * *key value* and a *mapped value*, and which allows for fast retrieval of individual elements based on their - * *keys*. - * - * In an {@link HashMap}, the *key value* is generally used to uniquely identify the element, while the - * *mapped value* is an object with the content associated to this *key*. Types of *key* and *mapped value* may - * differ. - * - * Internally, the elements in the {@link HashMap} are not sorted in any particular order with respect to either - * their *key* or *mapped values*, but organized into *buckets* depending on their hash values to allow for fast - * access to individual elements directly by their *key values* (with a constant average time complexity on - * average). - * - * {@link HashMap} containers are faster than {@link TreeMap} containers to access individual elements by their - * *key*, although they are generally less efficient for range iteration through a subset of their elements. - * - * - * - * - * - *

              Container properties

              - *
              - *
              Associative
              - *
              Elements in associative containers are referenced by their *key* and not by their absolute - * position in the container.
              - * - *
              Hashed
              - *
              Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their *key*.
              - * - *
              Map
              - *
              Each element associates a *key* to a *mapped value*: - * *Keys* are meant to identify the elements whose main content is the *mapped value*.
              - * - *
              Unique keys
              - *
              No two elements in the container can have equivalent keys.
              - *
              - * - * @param Type of the key values. - * Each element in an {@link HashMap} is uniquely identified by its key value. - * @param Type of the mapped value. - * Each element in an {@link HashMap} is used to store some data as its mapped value. - * - * @reference http://www.cplusplus.com/reference/unordered_map/unordered_map - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class HashMapCollection extends std.HashMap implements ICollection> { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.MapIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: MapCollectionEventListener): void; - addEventListener(type: "erase", listener: MapCollectionEventListener): void; - addEventListener(type: "refresh", listener: MapCollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: MapCollectionEventListener): void; - removeEventListener(type: "erase", listener: MapCollectionEventListener): void; - removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; - } -} -declare namespace samchon.collections { - /** - * A {@link HashMultiMap} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link MapCollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link emplace} - * - {@link push} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link HashMultiMap} - * {@link HashMultiMap HashMultiMap}s are associative containers that store elements formed by the combination of - * a *key value* and a *mapped value*, much like {@link HashMultiMap} containers, but allowing different elements - * to have equivalent *keys*. - * - * In an {@link HashMultiMap}, the *key value* is generally used to uniquely identify the element, while the - * *mapped value* is an object with the content associated to this *key*. Types of *key* and *mapped value* may - * differ. - * - * Internally, the elements in the {@link HashMultiMap} are not sorted in any particular order with respect to - * either their *key* or *mapped values*, but organized into *buckets* depending on their hash values to allow for - * fast access to individual elements directly by their *key values* (with a constant average time complexity on - * average). - * - * Elements with equivalent *keys* are grouped together in the same bucket and in such a way that an iterator can - * iterate through all of them. Iterators in the container are doubly linked iterators. - * - * - * - * - * - *

              Container properties

              - *
              - *
              Associative
              - *
              Elements in associative containers are referenced by their *key* and not by their absolute - * position in the container.
              - * - *
              Hashed
              - *
              Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their *key*.
              - * - *
              Map
              - *
              Each element associates a *key* to a *mapped value*: - * *Keys* are meant to identify the elements whose main content is the *mapped value*.
              - * - *
              Multiple equivalent keys
              - *
              The container can hold multiple elements with equivalent *keys*.
              - *
              - * - * @param Type of the key values. - * Each element in an {@link HashMultiMap} is identified by a key value. - * @param Type of the mapped value. - * Each element in an {@link HashMultiMap} is used to store some data as its mapped value. - * - * @reference http://www.cplusplus.com/reference/unordered_map/unordered_multimap - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class HashMultiMapCollection extends std.HashMap implements ICollection> { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.MapIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: MapCollectionEventListener): void; - addEventListener(type: "erase", listener: MapCollectionEventListener): void; - addEventListener(type: "refresh", listener: MapCollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: MapCollectionEventListener): void; - removeEventListener(type: "erase", listener: MapCollectionEventListener): void; - removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; - } -} -declare namespace samchon.collections { - /** - * A {@link HashMultiSet} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link CollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link push} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link HashMultiSet} - * {@link HashMultiSet HashMultiSets} are containers that store elements in no particular order, allowing fast - * retrieval of individual elements based on their value, much like {@link HashMultiSet} containers, but allowing - * different elements to have equivalent values. - * - * In an {@link HashMultiSet}, the value of an element is at the same time its *key*, used to identify it. *Keys* - * are immutable, therefore, the elements in an {@link HashMultiSet} cannot be modified once in the container - - * they can be inserted and removed, though. - * - * Internally, the elements in the {@link HashMultiSet} are not sorted in any particular, but organized into - * *buckets* depending on their hash values to allow for fast access to individual elements directly by their - * *values* (with a constant average time complexity on average). - * - * Elements with equivalent values are grouped together in the same bucket and in such a way that an iterator can - * iterate through all of them. Iterators in the container are doubly linked iterators. - * - * - * - * - * - *

              Container properties

              - *
              - *
              Associative
              - *
              Elements in associative containers are referenced by their *key* and not by their absolute - * position in the container.
              - * - *
              Hashed
              - *
              Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their *key*.
              - * - *
              Set
              - *
              The value of an element is also the *key* used to identify it.
              - * - *
              Multiple equivalent keys
              - *
              The container can hold multiple elements with equivalent *keys*.
              - *
              - * - * @param Type of the elements. - * Each element in an {@link UnorderedMultiSet} is also identified by this value.. - * - * @reference http://www.cplusplus.com/reference/unordered_set/unordered_multiset - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class HashMultiSetCollection extends std.HashMultiSet implements ICollection { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.SetIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener): void; - addEventListener(type: "erase", listener: CollectionEventListener): void; - addEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener): void; - removeEventListener(type: "erase", listener: CollectionEventListener): void; - removeEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - } -} -declare namespace samchon.collections { - /** - * A {@link HashSet} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link CollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link push} - * - {@link insert_or_assign} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - {@link extract} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link HashSet} - * {@link HashSet HashSets} are containers that store unique elements in no particular order, and which allow for - * fast retrieval of individual elements based on their value. - * - * In an {@link HashSet}, the value of an element is at the same time its *key*, that identifies it uniquely. - * Keys are immutable, therefore, the elements in an {@link HashSet} cannot be modified once in the container - - * they can be inserted and removed, though. - * - * Internally, the elements in the {@link HashSet} are not sorted in any particular order, but organized into - * buckets depending on their hash values to allow for fast access to individual elements directly by their - * *values* (with a constant average time complexity on average). - * - * {@link HashSet} containers are faster than {@link TreeSet} containers to access individual elements by their - * *key*, although they are generally less efficient for range iteration through a subset of their elements. - * - * - * - * - * - *

              Container properties

              - *
              - *
              Associative
              - *
              Elements in associative containers are referenced by their *key* and not by their absolute - * position in the container.
              - * - *
              Hashed
              - *
              Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their *key*.
              - * - *
              Set
              - *
              The value of an element is also the *key* used to identify it.
              - * - *
              Unique keys
              - *
              No two elements in the container can have equivalent *keys*.
              - *
              - * - * @param Type of the elements. - * Each element in an {@link HashSet} is also uniquely identified by this value. - * - * @reference http://www.cplusplus.com/reference/unordered_set/unordered_set - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class HashSetCollection extends std.HashSet implements ICollection { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.SetIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener): void; - addEventListener(type: "erase", listener: CollectionEventListener): void; - addEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener): void; - removeEventListener(type: "erase", listener: CollectionEventListener): void; - removeEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - } -} -/** - * Collections, elements I/O detectable STL containers. - * - * STL Containers | Collections - * ---------------------|------------------- - * {@link Vector} | {@link ArrayCollection} - * {@link List} | {@link ListCollection} - * {@link Deque} | {@link DequeCollection} - * | - * {@link TreeSet} | {@link TreeSetCollection} - * {@link HashSet} | {@link HashSetCollection} - * {@link TreeMultiSet} | {@link TreeMultiSetCollection} - * {@link HashMultiSet} | {@link HashMultiSetCollection} - * | - * {@link TreeMap} | {@link TreeMapCollection} - * {@link HashMap} | {@link HashMapCollection} - * {@link TreeMultiMap} | {@link TreeMultiMapCollection} - * {@link HashMultiMap} | {@link HashMultiMapCollection} - * - * @author Jeongho Nam - */ -declare namespace samchon.collections { - /** - * An interface for {@link IContainer containers} who can detect element I/O events. - * - * Below are list of methods who are dispatching {@link CollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link push} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - *refresh* typed events: - * - {@link refresh} - * - * @author Jeongho Nam - */ - interface ICollection extends std.base.IContainer, library.IEventDispatcher { - /** - * Dispatch a {@link CollectionEvent} with *refresh* typed. - * - * {@link ICollection} dispatches {@link CollectionEvent} typed *insert* or *erase* whenever elements I/O has - * occured. However, unlike those elements I/O events, content change in element level can't be detected. - * There's no way to detect those events automatically by {@link IContainer}. - * - * If you want to dispatch those typed events (notifying change on contents in element level), you've to - * dispatch *refresh* typed event manually, by yourself. Call {@link refresh refresh()} with specified - * iterators who're pointing the elements whose content have changed. Then a {@link CollectionEvent} with - * *refresh* typed will be dispatched. - * - * If you don't specify any iterator, then the range of the *refresh* event will be all elements in this - * {@link ICollection collection}; {@link begin begin()} to {@link end end()}. - */ - refresh(): void; - /** - * Dispatch a {@link CollectionEvent} with *refresh* typed. - * - * {@link ICollection} dispatches {@link CollectionEvent} typed *insert* or *erase* whenever elements I/O has - * occured. However, unlike those elements I/O events, content change in element level can't be detected. - * There's no way to detect those events automatically by {@link IContainer}. - * - * If you want to dispatch those typed events (notifying change on contents in element level), you've to - * dispatch *refresh* typed event manually, by yourself. Call {@link refresh refresh()} with specified - * iterators who're pointing the elements whose content have changed. Then a {@link CollectionEvent} with - * *refresh* typed will be dispatched. - * - * @param it An iterator targeting the content changed element. - */ - refresh(it: std.Iterator): void; - /** - * Dispatch a {@link CollectionEvent} with *refresh* typed. - * - * {@link ICollection} dispatches {@link CollectionEvent} typed *insert* or *erase* whenever elements I/O has - * occured. However, unlike those elements I/O events, content change in element level can't be detected. - * There's no way to detect those events automatically by {@link IContainer}. - * - * If you want to dispatch those typed events (notifying change on contents in element level), you've to - * dispatch *refresh* typed event manually, by yourself. Call {@link refresh refresh()} with specified - * iterators who're pointing the elements whose content have changed. Then a {@link CollectionEvent} with - * *refresh* typed will be dispatched. - * - * @param first An Iterator to the initial position in a sequence of the content changed elmeents. - * @param last An {@link Iterator} to the final position in a sequence of the content changed elements. The range - * used is [*first*, *last*), which contains all the elements between *first* and - * *last*, including the element pointed by *first* but not the element pointed by - * *last*. - */ - refresh(first: std.Iterator, last: std.Iterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener): void; - addEventListener(type: "erase", listener: CollectionEventListener): void; - addEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener): void; - removeEventListener(type: "erase", listener: CollectionEventListener): void; - removeEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - } - /** - * @hidden - */ - namespace ICollection { - /** - * @hidden - */ - function _Dispatch_CollectionEvent(collection: ICollection, type: string, first: std.Iterator, last: std.Iterator): void; - /** - * @hidden - */ - function _Dispatch_MapCollectionEvent(collection: ICollection>, type: string, first: std.MapIterator, last: std.MapIterator): void; - } -} -declare namespace samchon.collections { - /** - * A {@link List} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link CollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link push} - * - {@link push_front} - * - {@link push_back} - * - {@link merge} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - {@link pop_front} - * - {@link pop_back} - * - {@link unique} - * - {@link remove} - * - {@link remove_if} - * - {@link splice} - * - *refresh* typed events: - * - {@link refresh} - * - {@link sort} - * - * #### [Inherited] {@link List} - * {@link List Lists} are sequence containers that allow constant time insert and erase operations anywhere within - * the sequence, and iteration in both directions. - * - * List containers are implemented as doubly-linked lists; Doubly linked lists can store each of the elements they - * contain in different and unrelated storage locations. The ordering is kept internally by the association to - * each element of a link to the element preceding it and a link to the element following it. - * - * They are very similar to forward_list: The main difference being that forward_list objects are single-linked - * lists, and thus they can only be iterated forwards, in exchange for being somewhat smaller and more efficient. - * - * Compared to other base standard sequence containers (array, vector and deque), lists perform generally better - * in inserting, extracting and moving elements in any position within the container for which an iterator has - * already been obtained, and therefore also in algorithms that make intensive use of these, like sorting - * algorithms. - * - * The main drawback of lists and forward_lists compared to these other sequence containers is that they lack - * direct access to the elements by their position; For example, to access the sixth element in a list, one has to - * iterate from a known position (like the beginning or the end) to that position, which takes linear time in the - * distance between these. They also consume some extra memory to keep the linking information associated to each - * element (which may be an important factor for large lists of small-sized elements). - * - * - * - * - * - *

              Container properties

              - *
              - *
              Sequence
              - *
              Elements in sequence containers are ordered in a strict linear sequence. Individual elements are accessed by - * their position in this sequence.
              - * - *
              Doubly-linked list
              - *
              Each element keeps information on how to locate the next and the previous elements, allowing constant time - * insert and erase operations before or after a specific element (even of entire ranges), but no direct random - * access.
              - *
              - * - * @param Type of the elements. - * - * @reference http://www.cplusplus.com/reference/list/list/ - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class ListCollection extends std.List implements ICollection { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - push(...items: T[]): number; - /** - * @inheritdoc - */ - push_front(val: T): void; - /** - * @inheritdoc - */ - push_back(val: T): void; - /** - * @hidden - */ - protected _Insert_by_repeating_val(position: std.ListIterator, n: number, val: T): std.ListIterator; - /** - * @hidden - */ - protected _Insert_by_range>(position: std.ListIterator, begin: InputIterator, end: InputIterator): std.ListIterator; - /** - * @inheritdoc - */ - pop_front(): void; - /** - * @inheritdoc - */ - pop_back(): void; - /** - * @hidden - */ - protected _Erase_by_range(first: std.ListIterator, last: std.ListIterator): std.ListIterator; - /** - * @hidden - */ - private notify_insert(first, last); - /** - * @hidden - */ - private notify_erase(first, last); - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.ListIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.ListIterator, last: std.ListIterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener): void; - addEventListener(type: "erase", listener: CollectionEventListener): void; - addEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener): void; - removeEventListener(type: "erase", listener: CollectionEventListener): void; - removeEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - } -} -declare namespace samchon.collections { - type MapCollectionEventListener = (event: MapCollectionEvent) => void; - /** - * An event occured in a {@link MapContainer map container} object. - * - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class MapCollectionEvent extends CollectionEvent> { - /** - * @inheritdoc - */ - readonly first: std.MapIterator; - /** - * @inheritdoc - */ - readonly last: std.MapIterator; - } -} -declare namespace samchon.collections { - /** - * A {@link TreeMap} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link MapCollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link insert_or_assign} - * - {@link emplace} - * - {@link set} - * - {@link push} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - {@link extract} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link TreeMap} - * {@link TreeMap TreeMaps} are associative containers that store elements formed by a combination of a - * *key value* (*Key*) and a *mapped value* (*T*), following order. - * - * In a {@link TreeMap}, the *key values* are generally used to sort and uniquely identify the elements, while the - * *mapped values* store the content associated to this key. The types of *key* and *mapped value* may differ, and - * are grouped together in member type *value_type*, which is a {@link Pair} type combining both: - * - * ```typedef Pair value_type;``` - * - * Internally, the elements in a {@link TreeMap} are always sorted by its *key* following a *strict weak ordering* - * criterion indicated by its internal comparison method {@link less}. - * - * {@link TreeMap} containers are generally slower than {@link HashMap HashMap} containers to access individual - * elements by their *key*, but they allow the direct iteration on subsets based on their order. - * - * {@link TreeMap}s are typically implemented as binary search trees. - * - * - * - * - * - *

              Container properties

              - *
              - *
              Associative
              - *
              Elements in associative containers are referenced by their *key* and not by their absolute - * position in the container.
              - * - *
              Ordered
              - *
              The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order.
              - * - *
              Map
              - *
              Each element associates a *key* to a *mapped value*: - * *Keys* are meant to identify the elements whose main content is the *mapped value*.
              - * - *
              Unique keys
              - *
              No two elements in the container can have equivalent *keys*.
              - *
              - * - * @param Type of the keys. Each element in a map is uniquely identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. - * - * @reference http://www.cplusplus.com/reference/map/map - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class TreeMapCollection extends std.TreeMap implements ICollection> { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.MapIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: MapCollectionEventListener): void; - addEventListener(type: "erase", listener: MapCollectionEventListener): void; - addEventListener(type: "refresh", listener: MapCollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: MapCollectionEventListener): void; - removeEventListener(type: "erase", listener: MapCollectionEventListener): void; - removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; - } -} -declare namespace samchon.collections { - /** - * A {@link TreeMultiMap} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link MapCollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link emplace} - * - {@link push} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link TreeMultiMap} - * {@link TreeMultiMap TreeMultiMaps} are associative containers that store elements formed by a combination of a - * *key value* and a *mapped value*, following a specific order, and where multiple elements can have equivalent - * keys. - * - * In a {@link TreeMultiMap}, the *key values* are generally used to sort and uniquely identify the elements, - * while the *mapped values* store the content associated to this *key*. The types of *key* and *mapped value* may - * differ, and are grouped together in member type ```value_type```, which is a {@link Pair} type combining both: - * - * ```typedef Pair value_type;``` - * - * Internally, the elements in a {@link TreeMultiMap}are always sorted by its key following a strict weak ordering - * criterion indicated by its internal comparison method (of {@link less}). - * - * {@link TreeMultiMap}containers are generally slower than {@link HashMap} containers to access individual - * elements by their *key*, but they allow the direct iteration on subsets based on their order. - * - * {@link TreeMultiMap TreeMultiMaps} are typically implemented as binary search trees. - * - * < - * img src="http://samchon.github.io/typescript-stl/images/design/class_diagram/map_containers.png" style="max-width: 100%" /> - * - * - *

              Container properties

              - *
              - *
              Associative
              - *
              - * Elements in associative containers are referenced by their *key* and not by their absolute - * position in the container. - *
              - * - *
              Ordered
              - *
              - * The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order. - *
              - * - *
              Map
              - *
              - * Each element associates a *key* to a *mapped value*: - * *Keys* are meant to identify the elements whose main content is the *mapped value*. - *
              - * - *
              Multiple equivalent keys
              - *
              Multiple elements in the container can have equivalent *keys*.
              - *
              - * - * @param Type of the keys. Each element in a map is uniquely identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. - * - * @reference http://www.cplusplus.com/reference/map/multimap - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class TreeMultiMapCollection extends std.TreeMultiMap implements ICollection> { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.MapIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: MapCollectionEventListener): void; - addEventListener(type: "erase", listener: MapCollectionEventListener): void; - addEventListener(type: "refresh", listener: MapCollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: MapCollectionEventListener): void; - removeEventListener(type: "erase", listener: MapCollectionEventListener): void; - removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; - } -} -declare namespace samchon.collections { - /** - * A {@link TreeMultiSet} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link CollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link push} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link TreeMultiSet} - * {@link TreeMultiSet TreeMultiSets} are containers that store elements following a specific order, and where - * multiple elements can have equivalent values. - * - * In a {@link TreeMultiSet}, the value of an element also identifies it (the value is itself the *key*, of type - * *T*). The value of the elements in a {@link TreeMultiSet} cannot be modified once in the container (the - * elements are always const), but they can be inserted or removed from the container. - * - * Internally, the elements in a {@link TreeMultiSet TreeMultiSets} are always sorted following a strict weak - * ordering criterion indicated by its internal comparison method (of {@link IComparable.less less}). - * - * {@link TreeMultiSet} containers are generally slower than {@link HashMultiSet} containers to access individual - * elements by their *key*, but they allow the direct iteration on subsets based on their order. - * - *

              {@link TreeMultiSet TreeMultiSets} are typically implemented as binary search trees.

              - * - *

              - *

              - * - *

              Container properties

              - *
              - *
              Associative
              - *
              - * Elements in associative containers are referenced by their *key* and not by their absolute - * position in the container. - *
              - * - *
              Ordered
              - *
              - * The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order. - *
              - * - *
              Set
              - *
              The value of an element is also the *key* used to identify it.
              - * - *
              Multiple equivalent keys
              - *
              Multiple elements in the container can have equivalent *keys*.
              - *
              - * - * @param Type of the elements. Each element in a {@link TreeMultiSet} container is also identified - * by this value (each value is itself also the element's *key*). - * - * @reference http://www.cplusplus.com/reference/set/multiset - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class TreeMultiSetCollection extends std.TreeMultiSet implements ICollection { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.SetIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener): void; - addEventListener(type: "erase", listener: CollectionEventListener): void; - addEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener): void; - removeEventListener(type: "erase", listener: CollectionEventListener): void; - removeEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - } -} -declare namespace samchon.collections { - /** - * A {@link TreeMap} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link CollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link insert_or_assign} - * - {@link push} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - {@link extract} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link TreeSet} - * {@link TreeSet TreeSets} are containers that store unique elements following a specific order. - * - * In a {@link TreeSet}, the value of an element also identifies it (the value is itself the *key*, of type *T*), - * and each value must be unique. The value of the elements in a {@link TreeSet} cannot be modified once in the - * container (the elements are always const), but they can be inserted or removed from the container. - * - * Internally, the elements in a {@link TreeSet} are always sorted following a specific strict weak ordering - * criterion indicated by its internal comparison method (of {@link less}). - * - * {@link TreeSet} containers are generally slower than {@link HashSet} containers to access individual elements - * by their *key*, but they allow the direct iteration on subsets based on their order. - * - * {@link TreeSet}s are typically implemented as binary search trees. - * - * - * - * - * - *

              Container properties

              - *
              - *
              Associative
              - *
              - * Elements in associative containers are referenced by their *key* and not by their absolute - * position in the container. - *
              - * - *
              Ordered
              - *
              - * The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order. - *
              - * - *
              Set
              - *
              The value of an element is also the *key* used to identify it.
              - * - *
              Unique keys
              - *
              No two elements in the container can have equivalent *keys*.
              - *
              - * - * @param Type of the elements. - * Each element in an {@link TreeSet} is also uniquely identified by this value. - * - * @reference http://www.cplusplus.com/reference/set/set - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class TreeSetCollection extends std.TreeSet implements ICollection { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.SetIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener): void; - addEventListener(type: "erase", listener: CollectionEventListener): void; - addEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener): void; - removeEventListener(type: "erase", listener: CollectionEventListener): void; - removeEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - } -} -declare namespace samchon.library { - /** - * Case generator. - * - * {@link CaseGenerator} is an abstract case generator being used like a matrix. - *
                - *
              • n��r(n^r) -> {@link CombinedPermutationGenerator}
              • - *
              • nPr -> {@link PermutationGenerator}
              • - *
              • n! -> {@link FactorialGenerator}
              • - *
              - * - * @author Jeongho Nam - */ - abstract class CaseGenerator { - /** - * Size, the number of all cases. - */ - protected size_: number; - /** - * N, size of the candidates. - */ - protected n_: number; - /** - * R, size of elements of each case. - */ - protected r_: number; - /** - * Construct from size of N and R. - * - * @param n Size of candidates. - * @param r Size of elements of each case. - */ - constructor(n: number, r: number); - /** - * Get size of all cases. - * - * @return Get a number of the all cases. - */ - size(): number; - /** - * Get size of the N. - */ - n(): number; - /** - * Get size of the R. - */ - r(): number; - /** - * Get index'th case. - * - * @param index Index number - * @return The row of the index'th in combined permuation case - */ - abstract at(index: number): number[]; - } - /** - * A combined-permutation case generator. - * - * n��r - * - * @author Jeongho Nam - */ - class CombinedPermutationGenerator extends CaseGenerator { - /** - * An array using for dividing each element index. - */ - private divider_array; - /** - * Construct from size of N and R. - * - * @param n Size of candidates. - * @param r Size of elements of each case. - */ - constructor(n: number, r: number); - at(index: number): number[]; - } - /** - * A permutation case generator. - * - * nPr - * - * @author Jeongho Nam - */ - class PermuationGenerator extends CaseGenerator { - /** - * Construct from size of N and R. - * - * @param n Size of candidates. - * @param r Size of elements of each case. - */ - constructor(n: number, r: number); - /** - * @inheritdoc - */ - at(index: number): number[]; - } - /** - * Factorial case generator. - * - * n! = nPn - * - * @author Jeongho Nam - */ - class FactorialGenerator extends PermuationGenerator { - /** - * Construct from factorial size N. - * - * @param n Factoria size N. - */ - constructor(n: number); - } -} -declare namespace samchon.library { - type BasicEventListener = (event: BasicEvent) => void; - /** - * The IEventDispatcher interface defines methods for adding or removing event listeners, checks whether specific - * types of event listeners are registered, and dispatches events. - * - * The event target serves as the local point for how events flow through the display list hierarchy. When an - * event such as a mouse click or a key press occurs, an event object is dispatched into the event flow from the - * root of the display list. The event object makes a round-trip journey to the event target, which is - * conceptually divided into three phases: the capture phase includes the journey from the root to the last node - * before the event target's node; the target phase includes only the event target node; and the bubbling phase - * includes any subsequent nodes encountered on the return trip to the root of the display list. - * - * In general, the easiest way for a user-defined class to gain event dispatching capabilities is to extend - * {@link EventDispatcher}. If this is impossible (that is, if the class is already extending another class), you - * can instead implement the {@link IEventDispatcher} interface, create an {@link EventDispatcher} member, and - * write simple hooks to route calls into the aggregated {@link EventDispatcher}. - * - * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/IEventDispatcher.html - * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-EventDispatcher - * @author Migrated by Jeongho Nam - */ - interface IEventDispatcher { - /** - * Checks whether the {@link EventDispatcher} object has any listeners registered for a specific type of event. - * This allows you to determine where an {@link EventDispatcher} object has altered handling of an event type - * in the event flow hierarchy. To determine whether a specific event type actually triggers an event listener, - * use {@link willTrigger willTrigger()}. - * - * The difference between {@link hasEventListener hasEventListener()} and {@link willTrigger willTrigger()} is - * that {@link hasEventListener} examines only the object to which it belongs, whereas {@link willTrigger} - * examines the entire event flow for the event specified by the type parameter. - * - * @param type The type of event. - */ - hasEventListener(type: string): boolean; - /** - * Dispatches an event into the event flow. - * - * The event target is the {@link EventDispatcher} object upon which the {@link dispatchEvent dispatchEvent()} - * method is called. - * - * @param event The {@link BasicEvent} object that is dispatched into the event flow. If the event is being - * redispatched, a clone of the event is created automatically. After an event is dispatched, its - * target property cannot be changed, so you must create a new copy - * of the event for redispatching to work. - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * Registers an event listener object with an {@link EventDispatcher} object so that the listener receives - * notification of an event. You can register event listeners on all nodes in the display list for a specific - * type of event, phase, and priority. - * - * After you successfully register an event listener, you cannot change its priority through additional calls - * to {@link addEventListener addEventListener()|} To change a listener's priority, you must first call - * {@link removeEventListener removeEventListener()}. Then you can register the listener again with the new - * priority level. - * - * Keep in mind that after the listener is registered, subsequent calls to {@link addEventListener} with a - * different type or useCapture value result in the creation of a separate listener registration. For example, - * if you first register a listener with useCapture set to true, it listens only during the capture phase. If - * you call {@link addEventListener} again using the same listener object, but with useCapture set to false, - * you have two separate listeners: one that listens during the capture phase and another that listens during - * the target and bubbling phases. - * - * You cannot register an event listener for only the target phase or the bubbling phase. Those phases are - * coupled during registration because bubbling applies only to the ancestors of the target node. - * - * If you no longer need an event listener, remove it by calling {@link removeEventListener}, or memory - * problems could result. Event listeners are not automatically removed from memory because the garbage - * collector does not remove the listener as long as the dispatching object exists (unless the - * useWeakReference parameter is set to true). - * - * Copying an {@link EventDispatcher} instance does not copy the event listeners attached to it. (If your n - * ewly created node needs an event listener, you must attach the listener after creating the node.) However, - * if you move an {@link EventDispatcher} instance, the event listeners attached to it move along with it. - * - * If the event listener is being registered on a node while an event is also being processed on this node, - * the event listener is not triggered during the current phase but may be triggered during a later phase in - * the event flow, such as the bubbling phase. - * - * If an event listener is removed from a node while an event is being processed on the node, it is still - * triggered by the current actions. After it is removed, the event listener is never invoked again (unless it - * is registered again for future processing). - * - * @param event The type of event. - * @param listener The listener function that processes the event. - * This function must accept an Event object as its only parameter and must return - * nothing. - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - /** - * Registers an event listener object with an {@link EventDispatcher} object so that the listener receives - * notification of an event. You can register event listeners on all nodes in the display list for a specific - * type of event, phase, and priority. - * - * After you successfully register an event listener, you cannot change its priority through additional calls - * to {@link addEventListener addEventListener()|} To change a listener's priority, you must first call - * {@link removeEventListener removeEventListener()}. Then you can register the listener again with the new - * priority level. - * - * Keep in mind that after the listener is registered, subsequent calls to {@link addEventListener} with a - * different type or useCapture value result in the creation of a separate listener registration. For example, - * if you first register a listener with useCapture set to true, it listens only during the capture phase. If - * you call {@link addEventListener} again using the same listener object, but with useCapture set to false, - * you have two separate listeners: one that listens during the capture phase and another that listens during - * the target and bubbling phases. - * - * You cannot register an event listener for only the target phase or the bubbling phase. Those phases are - * coupled during registration because bubbling applies only to the ancestors of the target node. - * - * If you no longer need an event listener, remove it by calling {@link removeEventListener}, or memory - * problems could result. Event listeners are not automatically removed from memory because the garbage - * collector does not remove the listener as long as the dispatching object exists (unless the - * useWeakReference parameter is set to true). - * - * Copying an {@link EventDispatcher} instance does not copy the event listeners attached to it. (If your n - * ewly created node needs an event listener, you must attach the listener after creating the node.) However, - * if you move an {@link EventDispatcher} instance, the event listeners attached to it move along with it. - * - * If the event listener is being registered on a node while an event is also being processed on this node, - * the event listener is not triggered during the current phase but may be triggered during a later phase in - * the event flow, such as the bubbling phase. - * - * If an event listener is removed from a node while an event is being processed on the node, it is still - * triggered by the current actions. After it is removed, the event listener is never invoked again (unless it - * is registered again for future processing). - * - * @param event The type of event. - * @param listener The listener function that processes the event. - * This function must accept an Event object as its only parameter and must return - * nothing. - * @param thisArg The object to be used as the **this** object. - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - /** - * Removes a listener from the {@link EventDispatcher} object. If there is no matching listener registered - * with the {@link EventDispatcher} object, a call to this method has no effect. - * - * @param type The type of event. - * @param listener The listener object to remove. - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - /** - * Removes a listener from the {@link EventDispatcher} object. If there is no matching listener registered - * with the {@link EventDispatcher} object, a call to this method has no effect. - * - * @param type The type of event. - * @param listener The listener object to remove. - * @param thisArg The object to be used as the **this** object. - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - } - /** - * The {@link EventDispatcher} class is the base class for all classes that dispatch events. The - * {@link EventDispatcher} class implements the {@link IEventDispatcher} interface and is the base class for the - * {@link DisplayObject} class. The {@link EventDispatcher} class allows any object on the display list to be an - * event target and as such, to use the methods of the {@link IEventDispatcher} interface. - * - * The event target serves as the local point for how events flow through the display list hierarchy. When an - * event such as a mouse click or a key press occurs, an event object is dispatched into the event flow from the - * root of the display list. The event object makes a round-trip journey to the event target, which is - * conceptually divided into three phases: the capture phase includes the journey from the root to the last node - * before the event target's node; the target phase includes only the event target node; and the bubbling phase - * includes any subsequent nodes encountered on the return trip to the root of the display list. - * - * In general, the easiest way for a user-defined class to gain event dispatching capabilities is to extend - * {@link EventDispatcher}. If this is impossible (that is, if the class is already extending another class), you - * can instead implement the {@link IEventDispatcher} interface, create an {@link EventDispatcher} member, and - * write simple hooks to route calls into the aggregated {@link EventDispatcher}. - * - * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/EventDispatcher.html - * @author Migrated by Jeongho Nam - */ - class EventDispatcher implements IEventDispatcher { - /** - * @hidden - */ - private event_dispatcher_; - /** - * @hidden - */ - private event_listeners_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from the origin event dispatcher. - * - * @param dispatcher The origin object who issuing events. - */ - constructor(dispatcher: IEventDispatcher); - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - } -} -declare namespace samchon.library { - /** - * The {@link FileReference} class provides a means to load and save files in browser level. - * - * The {@link FileReference} class provides a means to {@link load} and {@link save} files in browser level. A - * browser-system dialog box prompts the user to select a file to {@link load} or a location for {@link svae}. Each - * {@link FileReference} object refers to a single file on the user's disk and has properties that contain - * information about the file's size, type, name, creation date, modification date, and creator type (Macintosh only). - * - * - * FileReference instances are created in the following ways: - *
                - *
              • - * When you use the new operator with the {@link FileReference} constructor: - * let myFileReference: FileReference = new FileReference(); - *
              • - *
              • - * When you call the {@link FileReferenceList.browse} method, which creates an array of {@link FileReference} - * objects. - *
              • - *
              - * - * During a load operation, all the properties of a {@link FileReference} object are populated by calls to the - * {@link FileReference.browse} or {@link FileReferenceList.browse} methods. During a save operation, the name - * property is populated when the select event is dispatched; all other properties are populated when the complete - * event is dispatched. - * - * The {@link browse browse()} method opens an browser-system dialog box that prompts the user to select a file - * for {@link load}. The {@link FileReference.browse} method lets the user select a single file; the - * {@link FileReferenceList.browse} method lets the user select multiple files. After a successful call to the - * {@link browse browse()} method, call the {@link FileReference.load} method to load one file at a time. The - * {@link FileReference.save} method prompts the user for a location to save the file and initiates downloading from - * a binary or string data. - * - * The {@link FileReference} and {@link FileReferenceList} classes do not let you set the default file location - * for the dialog box that the {@link browse} or {@link save} methods generate. The default location shown in the - * dialog box is the most recently browsed folder, if that location can be determined, or the desktop. The classes do - * not allow you to read from or write to the transferred file. They do not allow the browser that initiated the - * {@link load} or {@link save} to access the loaded or saved file or the file's location on the user's disk. - * - * @references http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference.html - * @author Jeongho Nam - */ - class FileReference extends EventDispatcher { - /** - * @hidden - */ - private file_; - /** - * @hidden - */ - private data_; - /** - * Default Constructor. - */ - constructor(); - /** - * The data from the loaded file after a successful call to the {@link load load()} method. - * - * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), - * an {@link LogicError exception} will be thrown when you try to get the value of this property. - * - * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. - * - */ - readonly data: any; - /** - * The name of the file on the local disk. - * - * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), - * an {@link LogicError exception} will be thrown when you try to get the value of this property. - * - * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. - * - */ - readonly name: string; - /** - * The filename extension. - * - * A file's extension is the part of the name following (and not including) the final dot ("."). If - * there is no dot in the filename, the extension is null. - * - * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), - * an {@link LogicError exception} will be thrown when you try to get the value of this property. - * - * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. - * - */ - readonly extension: string; - /** - * The file type, metadata of the {@link extension}. - * - * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), - * an {@link LogicError exception} will be thrown when you try to get the value of this property. - * - * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. - * - */ - readonly type: string; - /** - * The size of the file on the local disk in bytes. - * - * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), - * an {@link LogicError exception} will be thrown when you try to get the value of this property. - * - * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. - * - */ - readonly size: number; - /** - * The date that the file on the local disk was last modified. - * - * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), - * an {@link LogicError exception} will be thrown when you try to get the value of this property. - * - * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. - * - */ - readonly modificationDate: Date; - /** - * Displays a file-browsing dialog box that lets the user select a file to upload. The dialog box is native - * to the user's browser system. The user can select a file on the local computer or from other systems, for - * example, through a UNC path on Windows. - * - * When you call this method and the user successfully selects a file, the properties of this - * {@link FileReference} object are populated with the properties of that file. Each subsequent time that the - * {@link FileReference.browse} method is called, the {@link FileReference} object's properties are reset to - * the file that the user selects in the dialog box. Only one {@link browse browse()} can be performed at a time - * (because only one dialog box can be invoked at a time). - * - * Using the *typeFilter parameter*, you can determine which files the dialog box displays. - * - * @param typeFilter An array of filter strings used to filter the files that are displayed in the dialog box. - * If you omit this parameter, all files are displayed. - */ - browse(...typeFilter: string[]): void; - /** - * Starts the load of a local file selected by a user. - * - * You must call the {@link FileReference.browse} or {@link FileReferenceList.browse} method before you call - * the {@link load load()} method. - * - * Listeners receive events to indicate the progress, success, or failure of the load. Although you can use - * the {@link FileReferenceList} object to let users select multiple files to load, you must {@link load} the - * {@link FileReferenceList files} one by one. To {@link load} the files one by one, iterate through the - * {@link FileReferenceList.fileList} array of {@link FileReference} objects. - * - * If the file finishes loading successfully, its contents are stored in the {@link data} property. - */ - load(): void; - /** - * Save a file to local filesystem. - * - * {@link FileReference.save} implemented the save function by downloading a file from a hidden anchor tag. - * However, the plan, future's {@link FileReference} will follow such rule: - * - * Opens a dialog box that lets the user save a file to the local filesystem. - * - * The {@link save save()} method first opens an browser-system dialog box that asks the user to enter a - * filename and select a location on the local computer to save the file. When the user selects a location and - * confirms the save operation (for example, by clicking Save), the save process begins. Listeners receive events - * to indicate the progress, success, or failure of the save operation. To ascertain the status of the dialog box - * and the save operation after calling {@link save save()}, your code must listen for events such as cancel, - * open, progress, and complete. - * - * When the file is saved successfully, the properties of the {@link FileReference} object are populated with - * the properties of the local file. The complete event is dispatched if the save is successful. - * - * Only one {@link browse browse()} or {@link save()} session can be performed at a time (because only one - * dialog box can be invoked at a time). - * - * @param data The data to be saved. The data can be in one of several formats, and will be treated appropriately. - * @param fileName File name to be saved. - */ - save(data: string, fileName: string): void; - /** - * Save a file to local filesystem. - * - * {@link FileReference.save} implemented the save function by downloading a file from a hidden anchor tag. - * However, the plan, future's {@link FileReference} will follow such rule: - * - * Opens a dialog box that lets the user save a file to the local filesystem. - * - * The {@link save save()} method first opens an browser-system dialog box that asks the user to enter a - * filename and select a location on the local computer to save the file. When the user selects a location and - * confirms the save operation (for example, by clicking Save), the save process begins. Listeners receive events - * to indicate the progress, success, or failure of the save operation. To ascertain the status of the dialog box - * and the save operation after calling {@link save save()}, your code must listen for events such as cancel, - * open, progress, and complete. - * - * When the file is saved successfully, the properties of the {@link FileReference} object are populated with - * the properties of the local file. The complete event is dispatched if the save is successful. - * - * Only one {@link browse browse()} or {@link save()} session can be performed at a time (because only one - * dialog box can be invoked at a time). - * - * @param data The data to be saved. The data can be in one of several formats, and will be treated appropriately. - * @param fileName File name to be saved. - */ - static save(data: string, fileName: string): void; - } - /** - * The {@link FileReferenceList} class provides a means to let users select one or more files for - * {@link FileReference.load loading}. A {@link FileReferenceList} object represents a group of one or more local - * files on the user's disk as an array of {@link FileReference} objects. For detailed information and important - * considerations about {@link FileReference} objects and the FileReference class, which you use with - * {@link FileReferenceList}, see the {@link FileReference} class. - * - * To work with the {@link FileReferenceList} class: - *
                - *
              • Instantiate the class: var myFileRef = new FileReferenceList();
              • - *
              • - * Call the {@link FileReferenceList.browse} method, which opens a dialog box that lets the user select one or - * more files for upload: myFileRef.browse(); - *
              • - *
              • - * After the {@link browse browse()} method is called successfully, the {@link fileList} property of the - * {@link FileReferenceList} object is populated with an array of {@link FileReference} objects. - *
              • - *
              • Call {@link FileReference.load} on each element in the {@link fileList} array.
              • - *
              - * - * The {@link FileReferenceList} class includes a {@link browse browse()} method and a {@link fileList} property - * for working with multiple files. - * - * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReferenceList.html - * @author Jeongho Nam - */ - class FileReferenceList extends EventDispatcher { - /** - * @hidden - */ - file_list: std.Vector; - /** - * Default Constructor. - */ - constructor(); - /** - * An array of {@link FileReference} objects. - * - * When the {@link FileReferenceList.browse} method is called and the user has selected one or more files - * from the dialog box that the {@link browse browse()} method opens, this property is populated with an array of - * {@link FileReference} objects, each of which represents the files the user selected. - * - * The {@link fileList} property is populated anew each time {@link browse browse()} is called on that - * {@link FileReferenceList} object. - */ - readonly fileList: std.Vector; - /** - * Displays a file-browsing dialog box that lets the user select one or more local files to upload. The - * dialog box is native to the user's browser system. - * - * When you call this method and the user successfully selects files, the {@link fileList} property of this - * {@link FileReferenceList} object is populated with an array of {@link FileReference} objects, one for each - * file that the user selects. Each subsequent time that the {@link FileReferenceList.browse} method is called, - * the {@link FileReferenceList.fileList} property is reset to the file(s) that the user selects in the dialog - * box. - * - * Using the *typeFilter* parameter, you can determine which files the dialog box displays. - * - * Only one {@link FileReference.browse}, {@link FileReference.load}, or {@link FileReferenceList.browse} - * session can be performed at a time on a {@link FileReferenceList} object (because only one dialog box can be - * opened at a time). - * - * @param typeFilter An array of filter strings used to filter the files that are displayed in the dialog box. - * If you omit this parameter, all files are displayed. - */ - browse(...typeFilter: string[]): void; - } -} -declare namespace samchon.library { - /** - * A genetic algorithm class. - * - * In the field of artificial intelligence, a genetic algorithm (GA) is a search heuristic that mimics the - * process of natural selection. This heuristic (also sometimes called a metaheuristic) is routinely used to generate - * useful solutions to optimization and search problems. - * - * Genetic algorithms belong to the larger class of evolutionary algorithms (EA), which generate solutions to - * optimization problems using techniques inspired by natural evolution, such as inheritance, {@link mutate mutation}, - * {@link selection}, and {@link crossover}. - * - * @reference https://en.wikipedia.org/wiki/Genetic_algorithm - * @author Jeongho Nam - */ - class GeneticAlgorithm { - /** - * Whether each element (Gene) is unique in their GeneArray. - */ - private unique_; - /** - * Rate of mutation. - * - * The {@link mutation_rate} determines the percentage of occurence of mutation in GeneArray. - * - *
                - *
              • When {@link mutation_rate} is too high, it is hard to ancitipate studying on genetic algorithm.
              • - *
              • - * When {@link mutation_rate} is too low and initial set of genes (GeneArray) is far away from optimal, the - * evolution tends to wandering outside of he optimal. - *
              • - *
              - */ - private mutation_rate_; - /** - * Number of tournaments in selection. - */ - private tournament_; - /** - * Initialization Constructor. - * - * @param unique Whether each Gene is unique in their GeneArray. - * @param mutation_rate Rate of mutation. - * @param tournament Number of tournaments in selection. - */ - constructor(unique?: boolean, mutation_rate?: number, tournament?: number); - /** - * Evolove *GeneArray*. - * - * Convenient method accessing to {@link evolvePopulation evolvePopulation()}. - * - * @param individual An initial set of genes; sequence listing. - * @param population Size of population in a generation. - * @param generation Size of generation in evolution. - * @param compare A comparison function returns whether left gene is more optimal. - * - * @return An evolved *GeneArray*, optimally. - * - * @see {@link GAPopulation.compare} - */ - evolveGeneArray>(individual: GeneArray, population: number, generation: number, compare?: (left: T, right: T) => boolean): GeneArray; - /** - * Evolve *population*, a mass of *GeneArraies*. - * - * @param population An initial population. - * @param compare A comparison function returns whether left gene is more optimal. - * - * @return An evolved population. - * - * @see {@link GAPopulation.compare} - */ - evolvePopulation>(population: GAPopulation, compare?: (left: T, right: T) => boolean): GAPopulation; - /** - * Select the best GeneArray in *population* from tournament. - * - * {@link selection Selection} is the stage of a genetic algorithm in which individual genomes are chosen - * from a population for later breeding (using {@linlk crossover} operator). A generic {@link selection} - * procedure may be implemented as follows: - * - *
                - *
              1. - * The fitness function is evaluated for each individual, providing fitness values, which are then - * normalized. ization means dividing the fitness value of each individual by the sum of all fitness - * values, so that the sum of all resulting fitness values equals 1. - *
              2. - *
              3. The population is sorted by descending fitness values.
              4. - *
              5. - * Accumulated normalized fitness values are computed (the accumulated fitness value of an individual is the - * sum of its own fitness value plus the fitness values of all the previous individuals). The accumulated - * fitness of the last individual should be 1 (otherwise something went wrong in the normalization step). - *
              6. - *
              7. A random number R between 0 and 1 is chosen.
              8. - *
              9. The selected individual is the first one whose accumulated normalized value is greater than R.
              10. - *
              - * - * @param population The target of tournament. - * @return The best genes derived by the tournament. - * - * @reference https://en.wikipedia.org/wiki/Selection_(genetic_algorithm) - */ - private selection(population); - /** - * Create a new GeneArray by crossing over two *GeneArray*(s). - * - * {@link crossover} is a genetic operator used to vary the programming of a chromosome or chromosomes from - * one generation to the next. It is analogous to reproduction and biological crossover, upon which genetic - * algorithms are based. - * - * {@link crossover Cross over} is a process of taking more than one parent solutions and producing a child - * solution from them. There are methods for selection of the chromosomes. - * - * @param parent1 A parent sequence listing - * @param parent2 A parent sequence listing - * - * @reference https://en.wikipedia.org/wiki/Crossover_(genetic_algorithm) - */ - private crossover(parent1, parent2); - /** - * Cause a mutation on the *GeneArray*. - * - * {@link mutate Mutation} is a genetic operator used to maintain genetic diversity from one generation of a - * population of genetic algorithm chromosomes to the next. It is analogous to biological mutation. - * - * {@link mutate Mutation} alters one or more gene values in a chromosome from its initial state. In - * {@link mutate mutation}, the solution may change entirely from the previous solution. Hence GA can come to - * better solution by using {@link mutate mutation}. - * - * {@link mutate Mutation} occurs during evolution according to a user-definable mutation probability. This - * probability should be set low. If it is set too high, the search will turn into a primitive random search. - * - *

              Note

              - * Muttion is pursuing diversity. Mutation is useful for avoiding the following problem. - * - * When initial set of genes(GeneArray) is far away from optimail, without mutation (only with selection and - * crossover), the genetic algorithm has a tend to wandering outside of the optimal. - * - * Genes in the GeneArray will be swapped following percentage of the {@link mutation_rate}. - * - * @param individual A container of genes to mutate - * - * @reference https://en.wikipedia.org/wiki/Mutation_(genetic_algorithm) - * @see {@link mutation_rate} - */ - private mutate(individual); - } - /** - * A population in a generation. - * - * {@link GAPopulation} is a class representing population of candidate genes (sequence listing) having an array - * of GeneArray as a member. {@link GAPopulation} also manages initial set of genes and handles fitting test direclty - * by the method {@link fitTest fitTest()}. - * - * The success of evolution of genetic algorithm is depend on the {@link GAPopulation}'s initial set and fitting - * test. (*GeneArray* and {@link compare}.) - * - *

              Warning

              - * Be careful for the mistakes of direction or position of the {@link compare}. - * Most of logical errors failed to access optimal solution are occured from those mistakes. - * - * @param Type of gene elements. - * @param An array containing genes as elments; sequnce listing. - * - * @author Jeongho Nam - */ - class GAPopulation> { - /** - * Genes representing the population. - */ - private children_; - /** - * A comparison function returns whether left gene is more optimal, greater. - * - * Default value of this {@link compare} is {@link std.greater}. It means to compare two array - * (GeneArray must be a type of {@link std.base.IArrayContainer}). Thus, you've to keep follwing rule. - * - *
                - *
              • GeneArray is implemented from {@link std.base.IArrayContainer}.
              • - *
                  - *
                • {@link std.Vector}
                • - *
                • {@link std.Deque}
                • - *
                - *
              • GeneArray has custom public less(obj: T): boolean; function.
              • - *
              - * - * If you don't want to follow the rule or want a custom comparison function, you have to realize a - * comparison function. - */ - private compare_; - /** - * Private constructor with population. - * - * Private constructor of GAPopulation does not create {@link children}. (candidate genes) but only assigns - * *null* repeatedly following the *population size*. - * - * This private constructor is designed only for {@link GeneticAlgorithm}. Don't create {@link GAPopulation} - * with this constructor, by yourself. - * - * @param size Size of the population. - */ - constructor(size: number); - /** - * Construct from a {@link GeneArray} and *size of the population*. - * - * This public constructor creates *GeneArray(s)* as population (size) having shuffled genes which are - * came from the initial set of genes (*geneArray*). It uses {@link std.greater} as default comparison function. - * - * - * @param geneArray An initial sequence listing. - * @param size The size of population to have as children. - */ - constructor(geneArray: GeneArray, size: number); - /** - * Constructor from a GeneArray, size of the poluation and custom comparison function. - * - * This public constructor creates *GeneArray(s)* as population (size) having shuffled genes which are - * came from the initial set of genes (*geneArray*). The *compare* is used for comparison function. - * - * - * @param geneArray An initial sequence listing. - * @param size The size of population to have as children. - * @param compare A comparison function returns whether left gene is more optimal. - */ - constructor(geneArray: GeneArray, size: number, compare: (left: GeneArray, right: GeneArray) => boolean); - children(): std.Vector; - /** - * Test fitness of each *GeneArray* in the {@link population}. - * - * @return The best *GeneArray* in the {@link population}. - */ - fitTest(): GeneArray; - /** - * @hidden - */ - private clone(obj); - } -} -declare namespace samchon.library { - /** - * A utility class supporting static methods of string. - * - * The {@link StringUtil} utility class is an all-static class with methods for working with string objects. - * You do not create instances of {@link StringUtil}; instead you call methods such as the - * ```StringUtil.substitute()``` method. - * - * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/utils/StringUtil.html - * @author Jeongho Nam - */ - class StringUtil { - /** - * Generate a substring. - * - * Extracts a substring consisting of the characters from specified start to end. - * It's same with str.substring( ? = (str.find(start) + start.size()), str.find(end, ?) ) - * - * ```typescript - * let str: string = StringUtil.between("ABCD(EFGH)IJK", "(", ")"); - * console.log(str); // PRINTS "EFGH" - * ``` - * - * - If start is not specified, extracts from begin of the string to end. - * - If end is not specified, extracts from start to end of the string. - * - If start and end are all omitted, returns str, itself. - * - * @param str Target string to be applied between. - * @param start A string for separating substring at the front. - * @param end A string for separating substring at the end. - * - * @return substring by specified terms. - */ - static between(str: string, start?: string, end?: string): string; - /** - * Fetch substrings. - * - * Splits a string into an array of substrings dividing by specified delimeters of start and end. - * It's the array of substrings adjusted the between. - * - *
                - *
              • If startStr is omitted, it's same with the split by endStr not having last item.
              • - *
              • If endStr is omitted, it's same with the split by startStr not having first item.
              • - *
              • If startStr and endStar are all omitted, returns *str*.
              • - *
              - * - * @param str Target string to split by between. - * @param start A string for separating substring at the front. - * If omitted, it's same with split(end) not having last item. - * @param end A string for separating substring at the end. - * If omitted, it's same with split(start) not having first item. - * @return An array of substrings. - */ - static betweens(str: string, start?: string, end?: string): Array; - /** - * An array containing whitespaces. - */ - private static SPACE_ARRAY; - /** - * Remove all designated characters from the beginning and end of the specified string. - * - * @param str The string whose designated characters should be trimmed. - * @param args Designated character(s). - * - * @return Updated string where designated characters was removed from the beginning and end. - */ - static trim(str: string, ...args: string[]): string; - /** - * Remove all designated characters from the beginning of the specified string. - * - * @param str The string should be trimmed. - * @param delims Designated character(s). - * - * @return Updated string where designated characters was removed from the beginning - */ - static ltrim(str: string, ...args: string[]): string; - /** - * Remove all designated characters from the end of the specified string. - * - * @param str The string should be trimmed. - * @param delims Designated character(s). - * - * @return Updated string where designated characters was removed from the end. - */ - static rtrim(str: string, ...args: string[]): string; - /** - * Substitute {n} tokens within the specified string. - * - * @param format The string to make substitutions in. This string can contain special tokens of the form - * {n}, where n is a zero based index, that will be replaced with the - * additional parameters found at that index if specified. - * @param args Additional parameters that can be substituted in the *format* parameter at each - * {n} location, where n is an integer (zero based) index value into - * the array of values specified. - * - * @return New string with all of the {n} tokens replaced with the respective arguments specified. - */ - static substitute(format: string, ...args: any[]): string; - /** - * Returns a string specified word is replaced. - * - * @param str Target string to replace - * @param before Specific word you want to be replaced - * @param after Specific word you want to replace - * - * @return A string specified word is replaced - */ - static replaceAll(str: string, before: string, after: string): string; - /** - * Returns a string specified words are replaced. - * - * @param str Target string to replace - * @param pairs A specific word's pairs you want to replace and to be replaced - * - * @return A string specified words are replaced - */ - static replaceAll(str: string, ...pairs: std.Pair[]): string; - /** - * Replace all HTML spaces to a literal space. - * - * @param str Target string to replace. - */ - static removeHTMLSpaces(str: string): string; - /** - * Repeat a string. - * - * Returns a string consisting of a specified string concatenated with itself a specified number of times. - * - * @param str The string to be repeated. - * @param n The repeat count. - * - * @return The repeated string. - */ - static repeat(str: string, n: number): string; - /** - * Number to formatted string with "," sign. - * - * Returns a string converted from the number rounded off from specified precision with "," symbols. - * - * @param val A number wants to convert to string. - * @param precision Target precision of round off. - * - * @return A string who represents the number with roundoff and "," symbols. - */ - static numberFormat(val: number, precision?: number): string; - static percentFormat(val: number, precision?: number): string; - } -} -declare namespace samchon.library { - /** - * URLVariables class is for representing variables of HTTP. - * - * {@link URLVariables} class allows you to transfer variables between an application and server. - * - * When transfering, {@link URLVariables} will be converted to a *URI* string. - * - URI: Uniform Resource Identifier - * - * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLVariables.html - * @author Migrated by Jeongho Nam - */ - class URLVariables extends std.HashMap { - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from a URL-encoded string. - * - * The {@link decode decode()} method is automatically called to convert the string to properties of the {@link URLVariables} object. - * - * @param str A URL-encoded string containing name/value pairs. - */ - constructor(str: string); - /** - * Converts the variable string to properties of the specified URLVariables object. - * - * @param str A URL-encoded query string containing name/value pairs. - */ - decode(str: string): void; - /** - * Returns a string containing all enumerable variables, in the MIME content encoding application/x-www-form-urlencoded. - */ - toString(): string; - } -} -declare namespace samchon.library { - /** - * A tree-structured XML object. - * - * The {@link XML| class contains methods and properties for working with XML objects. The {@link XML} class (along - * with the {@link XMLList}) implements the powerful XML-handling standards defined in ECMAScript for XML (E4X) - * specification (ECMA-357 edition 2). - * - * An XML object, it is composed with three members; {@link getTag tag}, {@link getProperty properties} and - * {@link getValue value}. As you know, XML is a tree structured data expression method. The tree-stucture; - * {@link XML} class realizes it by extending ```std.HashMap```. Child {@link XML} objects are - * contained in the matched {@link XMLList} object being grouped by their {@link getTag tag name}. The - * {@link XMLList} objects, they're stored in the {@link std.HashMap} ({@link XML} itself) with its **key**; common - * {@link getTag tag name} of children {@link XML} objects. - * - * ```typescript - * class XML extends std.HashMap - * { - * private tag_: string; - * private properties_: std.HashMap; - * private value_: string; - * } - * ``` - * - * ```xml - * - * - * - * {value} - * {value} - * {value} - * - * - * - * - * ``` - * - * Use the {@link toString toString()} method to return a string representation of the {@link XML} object regardless - * of whether the {@link XML} object has simple content or complex content. - * - * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/XML.html - * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-XML - * @author Jeongho Nam - */ - class XML extends std.HashMap { - /** - * @hidden - */ - private tag_; - /** - * @hidden - */ - private value_; - /** - * @hidden - */ - private property_map_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from string. - * - * Creates {@link XML} object by parsing a string who represents xml structure. - * - * @param str A string represents XML structure. - */ - constructor(str: string); - /** - * @hidden - */ - private parse(str); - /** - * @hidden - */ - private parse_tag(str); - /** - * @hidden - */ - private parse_properties(str); - /** - * @hidden - */ - private parse_value(str); - /** - * @hidden - */ - private parse_children(str); - /** - * Get tag. - * - * ```xml - * {value} - * ``` - * - * @return tag. - */ - getTag(): string; - /** - * Get value. - * - * ```xml - * {VALUE} - * ``` - * - * @return value. - */ - getValue(): string; - /** - * Get iterator to property element. - * - * Searches the {@link getPropertyMap properties} for an element with a identifier equivalent to key - * and returns an iterator to it if found, otherwise it returns an iterator to {@link HashMap.end end()}. - * - *

              Two keys are considered equivalent if the properties' comparison object returns false reflexively - * (i.e., no matter the order in which the elements are passed as arguments).

              - * - * Another member function, {@link hasProperty hasProperty()} can be used to just check whether a particular - * key exists. - * - * ```xml - * {value} - * ``` - * - * @param key Key to be searched for - * @return An iterator to the element, if an element with specified key is found, or - * {@link end HashMap.end()} otherwise. - */ - findProperty(key: string): std.MapIterator; - /** - * Test whether a property exists. - * - * ```xml - * {value} - * ``` - * - * @return Whether a property has the *key* exists or not. - */ - hasProperty(key: string): boolean; - /** - * Get property. - * - * Get property by its *key*, property name. If the matched *key* does not exist, then exception - * {@link std.OutOfRange} is thrown. Thus, it would better to test whether the *key* exits or not by calling the - * {@link hasProperty hasProperty()} method before calling this {@link getProperty getProperty()}. - * - * This method can be substituted by {@link getPropertyMap getPropertyMap()} such below: - * - ```getPropertyMap().get(key, value);``` - * - ```getPropertyMap().find(key).second;``` - * - * ```xml - * {value} - * ``` - * - * @return Value of the matched property. - */ - getProperty(key: string): string; - /** - * Get property map. - * - * ```xml - * {value} - * ``` - * - * @return {@link HashMap} containing properties' keys and values. - */ - getPropertyMap(): std.HashMap; - /** - * Set tag. - * - * Set tag name, identifier of this {@link XML} object. - * - * If this {@link XML} object is belonged to, a child of, an {@link XMLList} and its related {@link XML} objects, - * then calling this {@link setTag setTag()} method direclty is not recommended. Erase this {@link XML} object - * from parent objects and insert this object again. - * - * ```xml - * {value} - * ``` - * - * @param val To be new {@link getTag tag}. - */ - setTag(val: string): void; - /** - * Set value. - * - * ```xml - * {VALUE} - * ``` - * - * @param val To be new {@link getValue value}. - */ - setValue(val: string): void; - /** - * Set property. - * - * Set a property *value* with its *key*. If the *key* already exists, then the *value* will be overwritten to - * the property. Otherwise the *key* is not exist yet, then insert the *key* and *value* {@link Pair pair} to - * {@link getPropertyMao property map}. - * - * This method can be substituted by {@link getPropertyMap getPropertyMap()} such below: - * - ```getPropertyMap().set(key, value);``` - * - ```getPropertyMap().emplace(key, value);``` - * - ```getPropertyMap().insert([key, value]);``` - * - ```getPropertyMap().insert(std.make_pair(key, value));``` - * - * ```xml - * {value} - * ``` - * - * @param key Key, identifier of property to be newly inserted. - * @param value Value of new property to be newly inserted. - */ - setProperty(key: string, value: string): void; - /** - * Erase property. - * - * Erases a property by its *key*, property name. If the matched *key* does not exist, then exception - * {@link std.OutOfRange} is thrown. Thus, it would better to test whether the *key* exits or not by calling the - * {@link hasProperty hasProperty()} method before calling this {@link eraseProperty eraseProperty()}. - * - * This method can be substituted by ``getPropertyMap().erase(key)````. - * - * ```xml - * {value} - * ``` - * - * @param key Key of the property to erase - * @throw {@link std.OutOfRange} - */ - eraseProperty(key: string): void; - /** - * @hidden - */ - push(...args: std.Pair[]): number; - /** - * @hidden - */ - push(...args: [string, XMLList][]): number; - push(...xmls: XML[]): number; - push(...xmlLists: XMLList[]): number; - /** - * Add all properties from other {@link XML} object. - * - * All the properties in the *obj* are copied to this {@link XML} object. If this {@link XML} object has same - * property key in the *obj*, then value of the property will be replaced to *obj*'s own. If you don't want to - * overwrite properties with same key, then use {@link getPropertyMap getPropertyMap()} method. - * - * ```typescript - * let x: library.XML; - * let y: library.XML; - * - * x.addAllProperties(y); // duplicated key exists, then overwrites - * x.getPropertyMap().insert(y.getPropertyMap().begin(), y.getPropertyMap().end()); - * // ducpliated key, then ignores. only non-duplicateds are copied. - * ``` - * - * ```xml - * {value} - * ``` - * - * @param obj Target {@link XML} object to copy properties. - */ - insertAllProperties(obj: XML): void; - /** - * Clear properties. - * - * Remove all properties. It's same with calling ```getPropertyMap().clear()```. - * - * ```xml - * {value} - * ``` - */ - clearProperties(): void; - /** - * @hidden - */ - private compute_min_index(...args); - /** - * @hidden - */ - private decode_value(str); - /** - * @hidden - */ - private encode_value(str); - /** - * @hidden - */ - private decode_property(str); - /** - * @hidden - */ - private encode_property(str); - /** - * {@link XML} object to xml string. - * - * Returns a string representation of the {@link XML} object. - * - * @param tab Number of tabs to spacing. - * @return The string representation of the {@link XML} object. - */ - toString(tab?: number): string; - } -} -declare namespace samchon.library { - /** - * List of {@link XML} objects with same tag. - * - * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/XMLList.html - * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-XML - * @author Jeongho Nam - */ - class XMLList extends std.Deque { - /** - * Get tag. - */ - getTag(): string; - /** - * {@link XMLList XML objects} to string. - * - * Returns a string representation of the {@link XMLList XML objects}. - * - * @param tab Number of tabs to spacing. - * @return The string representation of the {@link XMLList XML objects}. - */ - toString(level?: number): string; - } -} -declare namespace samchon.protocol { - /** - * An interface of entity. - * - * Entity is a class for standardization of expression method using on network I/O by XML. If - * Invoke is a standard message protocol of Samchon Framework which must be kept, Entity is a - * recommended semi-protocol of message for expressing a data class. Following the semi-protocol - * Entity is not imposed but encouraged. - * - * As we could get advantages from standardization of message for network I/O with Invoke, - * we can get additional advantage from standardizing expression method of data class with Entity. - * We do not need to know a part of network communication. Thus, with the Entity, we can only - * concentrate on entity's own logics and relationships between another entities. Entity does not - * need to how network communications are being done. - * - * I say repeatedly. Expression method of Entity is recommended, but not imposed. It's a semi - * protocol for network I/O but not a essential protocol must be kept. The expression method of - * Entity, using on network I/O, is expressed by XML string. - * - * If your own network system has a critical performance issue on communication data class, - * it would be better to using binary communication (with ByteArray). - * Don't worry about the problem! Invoke also provides methods for binary data (ByteArray). - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) - * - * @author Jeongho Nam - */ - interface IEntity { - /** - * Construct data of the Entity from a XML object. - * - * Overrides the construct() method and fetch data of member variables from the XML. - * - * By recommended guidance, data representing member variables are contained in properties - * of the put XML object. - * - * @param xml An xml used to contruct data of entity. - */ - construct(xml: library.XML): void; - /** - * Get a key that can identify the Entity uniquely. - * - * If identifier of the Entity is not atomic value, returns a paired or tuple object - * that can represents the composite identifier. - * - * - * class Point extends Entity - * { - * private x: number; - * private y: number; - * - * public key(): std.Pair - * { - * return std.make_pair(this.x, this.y); - * } - * } - * - */ - key(): any; - /** - * A tag name when represented by XML. - * - * - */ - TAG(): string; - /** - * Get a XML object represents the Entity. - * - * A member variable (not object, but atomic value like number, string or date) is categorized - * as a property within the framework of entity side. Thus, when overriding a toXML() method and - * archiving member variables to an XML object to return, puts each variable to be a property - * belongs to only a XML object. - * - * Don't archive the member variable of atomic value to XML::value causing enormouse creation - * of XML objects to number of member variables. An Entity must be represented by only a XML - * instance (tag). - * - *

              Standard Usage.

              - * - * - * - * - * - * - * - *

              Non-standard usage abusing value.

              - * - * - * jhnam88 - * Jeongho Nam - * 1988-03-11 - * - * - * master - * Administartor - * 2011-07-28 - * - * - * - * @return An XML object representing the Entity. - */ - toXML(): library.XML; - } - /** - * @hidden - */ - namespace IEntity { - function construct(entity: IEntity, xml: library.XML, ...prohibited_names: string[]): void; - function toXML(entity: IEntity, ...prohibited_names: string[]): library.XML; - } - /** - * An entity, a standard data class. - * - * Entity is a class for standardization of expression method using on network I/O by XML. If - * Invoke is a standard message protocol of Samchon Framework which must be kept, Entity is a - * recommended semi-protocol of message for expressing a data class. Following the semi-protocol - * Entity is not imposed but encouraged. - * - * As we could get advantages from standardization of message for network I/O with Invoke, - * we can get additional advantage from standardizing expression method of data class with Entity. - * We do not need to know a part of network communication. Thus, with the Entity, we can only - * concentrate on entity's own logics and relationships between another entities. Entity does not - * need to how network communications are being done. - * - * I say repeatedly. Expression method of Entity is recommended, but not imposed. It's a semi - * protocol for network I/O but not a essential protocol must be kept. The expression method of - * Entity, using on network I/O, is expressed by XML string. - * - * If your own network system has a critical performance issue on communication data class, - * it would be better to using binary communication (with ByteArray). - * Don't worry about the problem! Invoke also provides methods for binary data (ByteArray). - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) - * - * @author Jeongho Nam - */ - abstract class Entity implements IEntity { - /** - * Default Constructor. - */ - constructor(); - construct(xml: library.XML): void; - /** - * @inheritdoc - */ - key(): any; - /** - * @inheritdoc - */ - abstract TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.protocol { - /** - * @inheritdoc - */ - interface IEntityCollection extends IEntityGroup, collections.ICollection { - } -} -declare namespace samchon.protocol { - /** - * @inheritdoc - */ - abstract class EntityArrayCollection extends collections.ArrayCollection implements IEntityCollection { - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * @inheritdoc - */ - abstract createChild(xml: library.XML): T; - /** - * @inheritdoc - */ - key(): any; - /** - * @inheritdoc - */ - has(key: any): boolean; - /** - * @inheritdoc - */ - count(key: any): number; - /** - * @inheritdoc - */ - get(key: any): T; - /** - * @inheritdoc - */ - abstract TAG(): string; - /** - * @inheritdoc - */ - abstract CHILD_TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.protocol { - /** - * @inheritdoc - */ - abstract class EntityListCollection extends collections.ListCollection implements IEntityCollection { - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * @inheritdoc - */ - abstract createChild(xml: library.XML): T; - /** - * @inheritdoc - */ - key(): any; - /** - * @inheritdoc - */ - has(key: any): boolean; - /** - * @inheritdoc - */ - count(key: any): number; - /** - * @inheritdoc - */ - get(key: any): T; - /** - * @inheritdoc - */ - abstract TAG(): string; - /** - * @inheritdoc - */ - abstract CHILD_TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.protocol { - /** - * @inheritdoc - */ - abstract class EntityDequeCollection extends collections.DequeCollection implements IEntityCollection { - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * @inheritdoc - */ - abstract createChild(xml: library.XML): T; - /** - * @inheritdoc - */ - key(): any; - /** - * @inheritdoc - */ - has(key: any): boolean; - /** - * @inheritdoc - */ - count(key: any): number; - /** - * @inheritdoc - */ - get(key: any): T; - /** - * @inheritdoc - */ - abstract TAG(): string; - /** - * @inheritdoc - */ - abstract CHILD_TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -/** - * A template for External Systems Manager. - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ -declare namespace samchon.templates.external { - /** - * An array and manager of {@link ExternalSystem external system drivers}. - * - * The {@link ExternalSystemArray} is an abstract class containing and managing external system drivers, - * {@link ExternalSystem} objects. Within framewokr of network, {@link ExternalSystemArray} represents your system - * and children {@link ExternalSystem} objects represent remote, external systems connected with your system. - * With this {@link ExternalSystemArray}, you can manage multiple external systems as a group. - * - * You can specify this {@link ExternalSystemArray} class to be *a server accepting external clients* or - * *a client connecting to external servers*. Even both of them is also possible. - * - * - {@link ExternalClientArray}: A server accepting {@link ExternalSystem external clients}. - * - {@link ExternalServerArray}: A client connecting to {@link ExternalServer external servers}. - * - {@link ExternalServerClientArray}: Both of them. Accepts {@link ExternalSystem external clients} and connects to - * {@link ExternalServer external servers} at the same time. - * - * - * - * - * - * #### Proxy Pattern - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - abstract class ExternalSystemArray extends protocol.EntityDequeCollection implements protocol.IProtocol { - /** - * Default Constructor. - */ - constructor(); - /** - * @hidden - */ - private handle_system_erase(event); - /** - * Test whether the role exists. - * - * @param name Name, identifier of target {@link ExternalSystemRole role}. - * - * @return Whether the role has or not. - */ - hasRole(name: string): boolean; - /** - * Get a role. - * - * @param name Name, identifier of target {@link ExternalSystemRole role}. - * - * @return The specified role. - */ - getRole(name: string): ExternalSystemRole; - /** - * Send an {@link Invoke} message. - * - * @param invoke An {@link Invoke} message to send. - */ - sendData(invoke: protocol.Invoke): void; - /** - * Handle an {@Invoke} message have received. - * - * @param invoke An {@link Invoke} message have received. - */ - replyData(invoke: protocol.Invoke): void; - /** - * Tag name of the {@link ExternalSytemArray} in {@link XML}. - * - * @return *systemArray*. - */ - TAG(): string; - /** - * Tag name of {@link ExternalSystem children elements} belonged to the {@link ExternalSytemArray} in {@link XML}. - * - * @return *system*. - */ - CHILD_TAG(): string; - } -} -/** - * A template for Parallel Processing System. - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ -declare namespace samchon.templates.parallel { - /** - * Master of Parallel Processing System. - * - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to **slave** systems and the - * children {@link ParallelSystem} objects represent the remote **slave** systems, who is being requested the - * *parallel processes*. - * - * You can specify this {@link ParallelSystemArray} class to be *a server accepting parallel clients* or - * *a client connecting to parallel servers*. Even both of them is possible. Extends one of them below and overrides - * abstract factory method(s) creating the child {@link ParallelSystem} object. - * - * - {@link ParallelClientArray}: A server accepting {@link ParallelSystem parallel clients}. - * - {@link ParallelServerArray}: A client connecting to {@link ParallelServer parallel servers}. - * - {@link ParallelServerClientArray}: Both of them. Accepts {@link ParallelSystem parallel clients} and connects to - * {@link ParallelServer parallel servers} at the same time. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelSystemArray extends external.ExternalSystemArray { - /** - * @hidden - */ - private history_sequence_; - /** - * Default Constructor. - */ - constructor(); - /** - * Send an {@link Invoke} message with segment size. - * - * Sends an {@link Invoke} message requesting a **parallel process** with its *segment size*. The {@link Invoke} - * message will be delivered to children {@link ParallelSystem} objects with the *piece size*, which is divided - * from the *segment size*, basis on their {@link ParallelSystem.getPerformance performance indices}. - * - * - If segment size is 100, - * - The segment will be allocated such below: - * - * Name | Performance index | Number of pieces to be allocated | Formula - * --------|-------------------|----------------------------------|-------------- - * Snail | 1 | 10 | 100 / 10 * 1 - * Cheetah | 4 | 40 | 100 / 10 * 4 - * Rabbit | 3 | 30 | 100 / 10 * 3 - * Turtle | 2 | 20 | 100 / 10 * 2 - * - * When the **parallel process** has completed, then this {@link ParallelSystemArraY} will estimate - * {@link ParallelSystem.getPerformance performance indices} of {@link ParallelSystem} objects basis on their - * execution time. - * - * @param invoke An {@link Invoke} message requesting parallel process. - * @param size Number of pieces to segment. - * - * @return Number of {@link ParallelSystem slave systems} participating in the *Parallel Process*. - * - * @see {@link sendPieceData}, {@link ParallelSystem.getPerformacen} - */ - sendSegmentData(invoke: protocol.Invoke, size: number): number; - /** - * Send an {@link Invoke} message with range of pieces. - * - * Sends an {@link Invoke} message requesting a **parallel process** with its *range of pieces [first, last)*. - * The {@link Invoke} will be delivered to children {@link ParallelSystem} objects with the newly computed - * *range of sub-pieces*, which is divided from the *range of pieces (first to last)*, basis on their - * {@link ParallelSystem.getPerformance performance indices}. - * - * - If indices of pieces are 0 to 50, - * - The sub-pieces will be allocated such below: - * - * Name | Performance index | Range of sub-pieces to be allocated | Formula - * --------|-------------------|-------------------------------------|------------------------ - * Snail | 1 | ( 0, 5] | (50 - 0) / 10 * 1 - * Cheetah | 4 | ( 5, 25] | (50 - 0) / 10 * 4 + 5 - * Rabbit | 3 | (25, 40] | (50 - 0) / 10 * 3 + 25 - * Turtle | 2 | (40, 50] | (50 - 0) / 10 * 2 + 40 - * - * When the **parallel process** has completed, then this {@link ParallelSystemArraY} will estimate - * {@link ParallelSystem.getPerformance performance indices} of {@link ParallelSystem} objects basis on their - * execution time. - * - * @param invoke An {@link Invoke} message requesting parallel process. - * @param first Initial piece's index in a section. - * @param last Final piece's index in a section. The range used is [*first*, *last*), which contains - * all the pieces' indices between *first* and *last*, including the piece pointed by index - * *first*, but not the piece pointed by the index *last*. - * - * @return Number of {@link ParallelSystem slave systems} participating in the *Parallel Process*. - * - * @see {@link sendSegmentData}, {@link ParallelSystem.getPerformacen} - */ - sendPieceData(invoke: protocol.Invoke, first: number, last: number): number; - /** - * @hidden - */ - protected _Complete_history(history: protocol.InvokeHistory): boolean; - /** - * @hidden - */ - protected _Normalize_performance(): void; - } -} -/** - * A template for Distributed Processing System. - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ -declare namespace samchon.templates.distributed { - /** - * Master of Distributed Processing System. - * - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * You can specify this {@link DistributedSystemArray} class to be *a server accepting distributed clients* or - * *a client connecting to distributed servers*. Even both of them is possible. Extends one of them below and overrides - * abstract factory method(s) creating the child {@link DistributedSystem} object. - * - * - {@link DistributedClientArray}: A server accepting {@link DistributedSystem distributed clients}. - * - {@link DistributedServerArray}: A client connecting to {@link DistributedServer distributed servers}. - * - {@link DistributedServerClientArray}: Both of them. Accepts {@link DistributedSystem distributed clients} and - * connects to {@link DistributedServer distributed servers} at the same time. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedSystemArray extends parallel.ParallelSystemArray { - /** - * @hidden - */ - private process_map_; - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * Factory method creating a child {@link DistributedProcess process} object. - * - * @param xml {@link XML} represents the {@link DistributedProcess child} object. - * @return A new {@link DistributedProcess} object. - */ - protected abstract createProcess(xml: library.XML): DistributedProcess; - /** - * Get process map. - * - * Gets an {@link HashMap} containing {@link DistributedProcess} objects with their *key*. - * - * @return An {@link HasmMap> containing pairs of string and {@link DistributedProcess} object. - */ - getProcessMap(): std.HashMap; - /** - * Test whether the process exists. - * - * @param name Name, identifier of target {@link DistributedProcess process}. - * - * @return Whether the process has or not. - */ - hasProcess(name: string): boolean; - /** - * Get a process. - * - * @param name Name, identifier of target {@link DistributedProcess process}. - * - * @return The specified process. - */ - getProcess(name: string): DistributedProcess; - /** - * Insert a process. - * - * @param process A process to be inserted. - * @return Success flag. - */ - insertProcess(process: DistributedProcess): boolean; - /** - * Erase a process. - * - * @param name Name, identifier of target {@link DistributedProcess process}. - */ - eraseProcess(name: string): boolean; - /** - * @hidden - */ - protected _Complete_history(history: protocol.InvokeHistory): boolean; - /** - * @hidden - */ - private estimate_process_resource(history); - /** - * @hidden - */ - private estimate_system_performance(history); - /** - * @hidden - */ - protected _Normalize_performance(): void; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.templates.distributed { - /** - * Mediator of Distributed Processing System. - * - * The {@link DistributedSystemArrayMediator} class be a master for its slave systems, and be a slave to its master - * system at the same time. This {@link DistributedSystemArrayMediator} be a master system, containing and managing - * {@link DistributedSystem} objects, which represent distributed slave systems, by extending - * {@link DistributedSystemArray} class. Also, be a slave system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a master, you can specify this {@link DistributedSystemArrayMediator} class to be a master server accepting - * slave clients or a master client to connecting slave servers. Even both of them is possible. Extends one - * of them below and overrides abstract factory method(s) creating the child {@link DistributedSystem} object. - * - * - {@link DistributedClientArrayMediator}: A server accepting {@link DistributedSystem distributed clients}. - * - {@link DistributedServerArrayMediator}: A client connecting to {@link DistributedServer distributed servers}. - * - {@link DistributedServerClientArrayMediator}: Both of them. Accepts {@link DistributedSystem distributed clients} and - * connects to {@link DistributedServer distributed servers} at the same time. - * - * As a slave, you can specify this {@link DistributedSystemArrayMediator} to be a client slave connecting to master - * server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link DistributedSystemArray} - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedSystemArrayMediator extends DistributedSystemArray { - /** - * @hidden - */ - private mediator_; - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method creating a {@link MediatorSystem} object. - * - * The {@link createMediator createMediator()} is an abstract method creating the {@link MediatorSystem} object. - * - * You know what? this {@link DistributedSystemArrayMediator} class be a master for its slave systems, and be a - * slave to its master system at the same time. The {@link MediatorSystem} object makes it possible; be a slave - * system. This {@link createMediator} determines specific type of the {@link MediatorSystem}. - * - * Overrides the {@link createMediator createMediator()} method to create and return one of them following which - * protocol and which type of remote connection (server or client) will be used: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * @return A newly created {@link MediatorSystem} object. - */ - protected abstract createMediator(): parallel.MediatorSystem; - /** - * Start mediator. - * - * If the {@link getMediator mediator} is a type of server, then opens the server accepting master client. - * Otherwise, the {@link getMediator mediator} is a type of client, then connects the master server. - */ - protected startMediator(): void; - /** - * Get {@link MediatorSystem} object. - * - * When you need to send an {@link Invoke} message to the master system of this - * {@link DistributedSystemArrayMediator}, then send to the {@link MediatorSystem} through this - * {@link getMediator}. - * - * ```typescript - * this.getMediator().sendData(...); - * ``` - * - * @return The {@link MediatorSystem} object. - */ - getMediator(): parallel.MediatorSystem; - /** - * @hidden - */ - protected _Complete_history(history: parallel.PRInvokeHistory): boolean; - } -} -declare namespace samchon.protocol { - /** - * An interface taking full charge of network communication. - * - * {@link ICommunicator} is an interface for communicator classes who take full charge of network communication with - * remote system, without reference to whether the remote system is a server or a client. Type of the - * {@link ICommunicator} is specified to {@link IServerConnector} and {@link IClientDriver} whether the remote system - * is a server (that I've to connect) or a client (a client connected to my server). - * - * Whenever a replied message comes from the remote system, the message will be converted to an {@link Invoke} class - * and the {@link Invoke} object will be shifted to the {@link IProtocol listener}'s - * {@link IProtocol.replyData IProtocol.replyData()} method. - * - * - * - * - * - * @see {@link IClientDriver}, {@link IServerConnector}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#icommunicator) - * @author Jeongho Nam - */ - interface ICommunicator extends IProtocol { - /** - * Callback function for connection closed. - */ - onClose: Function; - /** - * Close connection. - */ - close(): void; - /** - * Test connection. - * - * Test whether this {@link ICommunicator communicator} object is connected with the remote system. If the - * connection is alive, then returns ```true```. Otherwise, the connection is not alive or this - * {@link ICommunicator communicator has not connected with the remote system yet, then returns ```false```. - * - * @return true if connected, otherwise false. - */ - isConnected(): boolean; - /** - * Send message. - * - * Send {@link Invoke} message to remote system. - * - * @param invoke An {@link Invoke} message to send. - */ - sendData(invoke: protocol.Invoke): void; - /** - * Handle replied message. - * - * Handles replied {@link Invoke} message recived from remove system. The {@link Invoke} message will be shifted - * to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} by this method. - * - * @param invoke An {@link Invoke} message received from remote system. - */ - replyData(invoke: protocol.Invoke): void; - } -} -declare namespace samchon.protocol { - /** - * An abstract, basic class for communicators. - * - * {@link CommunicatorBase} is an abstract class implemented from the {@link ICommunicator}. Mechanism of converting - * raw data to {@link Invoke} messag has realized in this abstract class. Type of this {@link CommunicatorBase} class - * is specified to as below following which protocol is used. - * - * - {@link Communicator}: Samchon Framework's own protocool. - * - {@link WebCommunicator}: Web-socket protocol - * - {@link SharedWorkerCommunicator}: SharedWorker's message protocol. - * - * #### [Inherited] {@link ICommunicator} - * {@link ICommunicator} is an interface for communicator classes who take full charge of network communication with - * remote system, without reference to whether the remote system is a server or a client. Type of the - * {@link ICommunicator} is specified to {@link IServerConnector} and {@link IClientDriver} whether the remote system - * is a server (that I've to connect) or a client (a client connected to my server). - * - * Whenever a replied message comes from the remote system, the message will be converted to an {@link Invoke} class - * and the {@link Invoke} object will be shifted to the {@link IProtocol listener}'s - * {@link IProtocol.replyData IProtocol.replyData()} method. - * - * - * - * - * - * @see {@link IClientDriver}, {@link IServerConnector}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#icommunicator) - * @author Jeongho Nam - */ - abstract class CommunicatorBase implements ICommunicator { - /** - * @hidden - */ - protected listener_: IProtocol; - /** - * @inheritdoc - */ - onClose: Function; - /** - * @hidden - */ - protected connected_: boolean; - /** - * @hidden - */ - private binary_invoke_; - /** - * @hidden - */ - private binary_parameters_; - /** - * @hidden - */ - private unhandled_invokes; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from *listener*. - * - * @param listener An {@link IProtocol} object to listen {@link Invoke} messages. - */ - constructor(listener: IProtocol); - /** - * @inheritdoc - */ - abstract close(): void; - /** - * @inheritdoc - */ - isConnected(): boolean; - /** - * @hidden - */ - protected is_binary_invoke(): boolean; - /** - * @inheritdoc - */ - abstract sendData(invoke: Invoke): void; - /** - * @inheritdoc - */ - replyData(invoke: Invoke): void; - /** - * @hidden - */ - protected handle_string(str: string): void; - /** - * @hidden - */ - protected handle_binary(binary: Uint8Array): void; - } -} -declare namespace samchon.protocol { - /** - * A communicator following Samchon Framework's own protocol. - * - * {@link Communicator} is an abstract class following Samchon Framework's own protocol. This {@link Communicator} - * class is specified to {@link ServerConnector} and {@link ClientDriver} whether the remote system is a server (that - * my system is connecting to) or a client (a client conneting to to my server). - * - * Note that, if one of this or remote system is web-browser based, then you don't have to use this - * {@link Communicator} class who follows Samchon Framework's own protocol. Web-browser supports only Web-socket - * protocol. Thus in that case, you have to use {@link WebCommunicator} instead. - * - * #### [Inherited] {@link ICommunicator} - * {@link ICommunicator} is an interface for communicator classes who take full charge of network communication with - * remote system, without reference to whether the remote system is a server or a client. Type of the - * {@link ICommunicator} is specified to {@link IServerConnector} and {@link IClientDriver} whether the remote system - * is a server (that I've to connect) or a client (a client connected to my server). - * - * Whenever a replied message comes from the remote system, the message will be converted to an {@link Invoke} class - * and the {@link Invoke} object will be shifted to the {@link IProtocol listener}'s - * {@link IProtocol.replyData IProtocol.replyData()} method. - * - * - * - * - * - * @see {@link ClientDriver}, {@link ServerConnector}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#icommunicator) - * @author Jeongho Nam - */ - abstract class Communicator extends CommunicatorBase { - /** - * @hidden - */ - protected socket_: socket.socket; - /** - * @hidden - */ - private header_bytes_; - /** - * @hidden - */ - private data_; - /** - * @hidden - */ - private data_index_; - /** - * @hidden - */ - private listening_; - /** - * @inheritdoc - */ - close(): void; - /** - * @hidden - */ - protected start_listen(): void; - /** - * @hidden - */ - private handle_error(); - /** - * @hidden - */ - private handle_close(); - /** - * @inheritdoc - */ - sendData(invoke: Invoke): void; - /** - * @hidden - */ - private listen_piece(piece); - /** - * @hidden - */ - private listen_header(piece, piece_index); - /** - * @hidden - */ - private listen_data(piece, piece_index); - } -} -declare namespace samchon.protocol { - /** - * A communicator following Web-socket protocol. - * - * {@link WebCommunicator} is an abstract class following Web-socket protocol. This {@link WebCommunicator} class is - * specified to {@link WebServerConnector} and {@link WebClientDriver} whether the remote system is a server (that my - * system is connecting to) or a client (a client conneting to to my server). - * - * Note that, one of this or remote system is web-browser based, then there's not any alternative choice. Web browser - * supports only Web-socket protocol. In that case, you've use this {@link WebCommunicator} class. - * - * #### [Inherited] {@link ICommunicator} - * {@link ICommunicator} is an interface for communicator classes who take full charge of network communication with - * remote system, without reference to whether the remote system is a server or a client. Type of the - * {@link ICommunicator} is specified to {@link IServerConnector} and {@link IClientDriver} whether the remote system - * is a server (that I've to connect) or a client (a client connected to my server). - * - * Whenever a replied message comes from the remote system, the message will be converted to an {@link Invoke} class - * and the {@link Invoke} object will be shifted to the {@link IProtocol listener}'s - * {@link IProtocol.replyData IProtocol.replyData()} method. - * - * - * - * - * - * @see {@link WebClientDriver}, {@link WebServerConnector}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#icommunicator) - * @author Jeongho Nam - */ - abstract class WebCommunicator extends CommunicatorBase { - /** - * @hidden - */ - protected connection_: websocket.connection; - /** - * @inheritdoc - */ - close(): void; - /** - * @inheritdoc - */ - sendData(invoke: Invoke): void; - /** - * @hidden - */ - protected handle_message(message: websocket.IMessage): void; - /** - * @hidden - */ - protected handle_close(): void; - } -} -declare namespace samchon.protocol { - /** - * A communicator for shared worker. - * - * {@link DedicatedWorkerCommunicator} is an abstract class for communication between DedicatedWorker and Web-browser. - * This {@link DedicatedWorkerCommunicator} is specified to {@link DedicatedWorkerServerConnector} and - * {@link DedicatedWorkerClientDriver} whether the remote system is a server (that my system is connecting to) or a - * client (a client conneting to to my server). - * - * #### Why DedicatedWorker be a server? - * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the - * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the - * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network - * communication? Furthermore, there's not any difference between the worker communication and network communication. - * It's the reason why Samchon Framework considers the **Worker** as a network node. - * - * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a - * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the - * server and clients with this {@link DedicatedWorkerCommunicator}. - * - * #### [Inherited] {@link ICommunicator} - * {@link ICommunicator} is an interface for communicator classes who take full charge of network communication with - * remote system, without reference to whether the remote system is a server or a client. Type of the - * {@link ICommunicator} is specified to {@link IServerConnector} and {@link IClientDriver} whether the remote system - * is a server (that I've to connect) or a client (a client connected to my server). - * - * Whenever a replied message comes from the remote system, the message will be converted to an {@link Invoke} class - * and the {@link Invoke} object will be shifted to the {@link IProtocol listener}'s - * {@link IProtocol.replyData IProtocol.replyData()} method. - * - * - * - * - * - * @see {@link DedicatedWorkerClientDriver}, {@link DedicatedWorkerServerConnector}, {@link IProtocol} - * @reference https://developer.mozilla.org/en-US/docs/Web/API/DedicatedWorker - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#icommunicator) - * @author Jeongho Nam - */ - abstract class DedicatedWorkerCommunicator extends CommunicatorBase { - /** - * @hidden - */ - protected handle_message(event: MessageEvent): void; - } -} -declare namespace samchon.protocol { - /** - * A communicator for shared worker. - * - * {@link SharedWorkerCommunicator} is an abstract class for communication between SharedWorker and Web-browser. This - * {@link SharedWorkerCommunicator} is specified to {@link SharedWorkerServerConnector} and - * {@link SharedWorkerClientDriver} whether the remote system is a server (that my system is connecting to) or a client - * (a client conneting to to my server). - * - * Note that, SharedWorker is a conception only existed in web-browser. This {@link SharedWorkerCommunicator} is not - * supported in NodeJS. Only web-browser environment can utilize this {@link SharedWorkerCommunicator}. - * - * #### Why SharedWorker be a server? - * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser - * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship - * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as - * clients. - * - * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a - * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the - * server and clients with this {@link SharedWorkerCommunicator}. - * - * #### [Inherited] {@link ICommunicator} - * {@link ICommunicator} is an interface for communicator classes who take full charge of network communication with - * remote system, without reference to whether the remote system is a server or a client. Type of the - * {@link ICommunicator} is specified to {@link IServerConnector} and {@link IClientDriver} whether the remote system - * is a server (that I've to connect) or a client (a client connected to my server). - * - * Whenever a replied message comes from the remote system, the message will be converted to an {@link Invoke} class - * and the {@link Invoke} object will be shifted to the {@link IProtocol listener}'s - * {@link IProtocol.replyData IProtocol.replyData()} method. - * - * - * - * - * - * @see {@link SharedWorkerClientDriver}, {@link SharedWorkerServerConnector}, {@link IProtocol} - * @reference https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#icommunicator) - * @author Jeongho Nam - */ - abstract class SharedWorkerCommunicator extends CommunicatorBase { - /** - * @hidden - */ - protected port_: MessagePort; - /** - * @inheritdoc - */ - close(): void; - /** - * @inheritdoc - */ - sendData(invoke: Invoke): void; - /** - * @hidden - */ - protected handle_message(event: MessageEvent): void; - } -} -declare namespace samchon.protocol { - /** - * An interface for communicator with remote client. - * - * {@link IClientDriver} is a type of {@link ICommunicator}, specified for communication with remote client who has - * connected in a {@link IServer server}. It takes full charge of network communication with the remote client. - * - * The {@link IClientDriver} object is created and delivered from {@link IServer} and - * {@link IServer.addClient IServer.addClient()}. Those are derived types from this {@link IClientDriver}, being - * created by the matched {@link IServer} object. - * - * Protocol | Derived Type | Created By - * ------------------------|-------------------------------------|---------------------------- - * Samchon Framework's own | {@link ClientDriver} | {@link Server} - * Web-socket protocol | {@link WebClientDriver} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerClinetDriver} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerClientDriver} | {@link SharedWorkerServer} - * - * When you've got an {@link IClientDriver} object from the {@link IServer.addClient IServer.addClient()}, then - * specify {@link IProtocol listener} with {@link IClient.listen IClient.listen()}. Whenever a replied message comes - * from the remote system, the message will be converted to an {@link Invoke} class and the {@link Invoke} object - * will be shifted to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * Below code is an example specifying and managing the {@link IProtocol listener} objects. - * - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - * - * - * - * - * @see {@link IServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iclientdriver) - * @author Jeongho Nam - */ - interface IClientDriver extends ICommunicator { - /** - * Listen message from the newly connected client. - * - * Starts listening message from the newly connected client. Replied message from the connected client will be - * converted to {@link Invoke} classes and shifted to the *listener*'s {@link IProtocol.replyData replyData()} - * method. - * - * @param listener A listener object to listen replied message from newly connected client in - * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. - */ - listen(listener: IProtocol): void; - } -} -declare namespace samchon.protocol { - /** - * Communicator with remote client. - * - * {@link ClientDriver} is a class taking full charge of network communication with remote client who follows Samchon - * Framework's own protocol. This {@link ClientDriver} object is always created by {@link Server} class. When you got - * this {@link ClientDriver} object from the {@link Server.addClient Server.addClient()}, then specify - * {@link IProtocol listener} with the {@link ClientDriver.listen ClientDriver.listen()} method. - * - * #### [Inherited] {@link IClientDriver} - * {@link IClientDriver} is a type of {@link ICommunicator}, specified for communication with remote client who has - * connected in a {@link IServer server}. It takes full charge of network communication with the remote client. - * - * The {@link IClientDriver} object is created and delivered from {@link IServer} and - * {@link IServer.addClient IServer.addClient()}. Those are derived types from this {@link IClientDriver}, being - * created by the matched {@link IServer} object. - * - * Protocol | Derived Type | Created By - * ------------------------|-------------------------------------|---------------------------- - * Samchon Framework's own | {@link ClientDriver} | {@link Server} - * Web-socket protocol | {@link WebClientDriver} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerClinetDriver} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerClientDriver} | {@link SharedWorkerServer} - * - * When you've got an {@link IClientDriver} object from the {@link IServer.addClient IServer.addClient()}, then - * specify {@link IProtocol listener} with {@link IClient.listen IClient.listen()}. Whenever a replied message comes - * from the remote system, the message will be converted to an {@link Invoke} class and the {@link Invoke} object - * will be shifted to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * Below code is an example specifying and managing the {@link IProtocol listener} objects. - * - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - * - * - * - * - * @see {@link Server}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iclientdriver) - * @author Jeongho Nam - */ - class ClientDriver extends Communicator implements IClientDriver { - /** - * Construct from a socket. - */ - constructor(socket: socket.socket); - /** - * @inheritdoc - */ - listen(listener: IProtocol): void; - } -} -declare namespace samchon.protocol { - /** - * Communicator with remote web-client. - * - * {@link WebClientDriver} is a class taking full charge of network communication with remote client who follows - * Web-socket protocol. This {@link WebClientDriver} object is always created by {@link WebServer} class. When you - * got this {@link WebClientDriver} object from the {@link WebServer.addClient WebServer.addClient()}, then specify - * {@link IProtocol listener} with the {@link WebClientDriver.listen WebClientDriver.listen()} method. - * - * Unlike other protocol, Web-socket protocol's clients notify two parameters on their connection; - * {@link getSessionID session-id} and {@link getPath path}. The {@link getSessionID session-id} can be used to - * identify *user* of each client, and the {@link getPath path} can be used which type of *service* that client wants. - * In {@link service} module, you can see the best utilization case of them. - * - {@link service.User}: utlization of the {@link getSessionID session-id}. - * - {@link service.Service}: utilization of the {@link getPath path}. - * - * #### [Inherited] {@link IClientDriver} - * {@link IClientDriver} is a type of {@link ICommunicator}, specified for communication with remote client who has - * connected in a {@link IServer server}. It takes full charge of network communication with the remote client. - * - * The {@link IClientDriver} object is created and delivered from {@link IServer} and - * {@link IServer.addClient IServer.addClient()}. Those are derived types from this {@link IClientDriver}, being - * created by the matched {@link IServer} object. - * - * Protocol | Derived Type | Created By - * ------------------------|-------------------------------------|---------------------------- - * Samchon Framework's own | {@link ClientDriver} | {@link Server} - * Web-socket protocol | {@link WebClientDriver} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerClinetDriver} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerClientDriver} | {@link SharedWorkerServer} - * - * When you've got an {@link IClientDriver} object from the {@link IServer.addClient IServer.addClient()}, then - * specify {@link IProtocol listener} with {@link IClient.listen IClient.listen()}. Whenever a replied message comes - * from the remote system, the message will be converted to an {@link Invoke} class and the {@link Invoke} object - * will be shifted to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * Below code is an example specifying and managing the {@link IProtocol listener} objects. - * - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - * - * - * - * - * @see {@link WebServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iclientdriver) - * @author Jeongho Nam - */ - class WebClientDriver extends WebCommunicator implements IClientDriver { - /** - * @hidden - */ - private path_; - /** - * @hidden - */ - private session_id_; - /** - * @hidden - */ - private listening_; - /** - * Initialization Constructor. - * - * @param connection Connection driver, a socket for web-socket. - * @param path Requested path. - * @param session_id Session ID, an identifier of the remote client. - */ - constructor(connection: websocket.connection, path: string, session_id: string); - /** - * @inheritdoc - */ - listen(listener: IProtocol): void; - /** - * Get requested path. - */ - getPath(): string; - /** - * Get session ID, an identifier of the remote client. - */ - getSessionID(): string; - } -} -declare namespace samchon.protocol { - /** - * Communicator with master web-browser. - * - * {@link DedicatedWorkerClientDriver} is a class taking full charge of network communication with web browsers. This - * {@link DedicatedWorkerClientDriver} object is always created by {@link DedicatedWorkerServer} class. When you got - * this {@link DedicatedWorkerClientDriver} object from - * {@link DedicatedWorkerServer.addClient DedicatedWorkerServer.addClient()}, then specify {@link IProtocol listener} - * with the {@link DedicatedWorkerClientDriver.listen DedicatedWorkerClientDriver.listen()} method. - * - * #### Why DedicatedWorker be a server? - * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the - * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the - * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network - * communication? Furthermore, there's not any difference between the worker communication and network communication. - * It's the reason why Samchon Framework considers the **Worker** as a network node. - * - * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a - * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the - * server and clients with this {@link DedicatedWorkerCommunicator}. - * - * #### [Inherited] {@link IClientDriver} - * {@link IClientDriver} is a type of {@link ICommunicator}, specified for communication with remote client who has - * connected in a {@link IServer server}. It takes full charge of network communication with the remote client. - * - * The {@link IClientDriver} object is created and delivered from {@link IServer} and - * {@link IServer.addClient IServer.addClient()}. Those are derived types from this {@link IClientDriver}, being - * created by the matched {@link IServer} object. - * - * Protocol | Derived Type | Created By - * ------------------------|-------------------------------------|---------------------------- - * Samchon Framework's own | {@link ClientDriver} | {@link Server} - * Web-socket protocol | {@link WebClientDriver} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerClinetDriver} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerClientDriver} | {@link SharedWorkerServer} - * - * When you've got an {@link IClientDriver} object from the {@link IServer.addClient IServer.addClient()}, then - * specify {@link IProtocol listener} with {@link IClient.listen IClient.listen()}. Whenever a replied message comes - * from the remote system, the message will be converted to an {@link Invoke} class and the {@link Invoke} object - * will be shifted to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * Below code is an example specifying and managing the {@link IProtocol listener} objects. - * - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - * - * - * - * - * @see {@link DedicatedWorkerServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iclientdriver) - * @author Jeongho Nam - */ - class DedicatedWorkerClientDriver extends DedicatedWorkerCommunicator implements IClientDriver { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - listen(listener: IProtocol): void; - /** - * @inheritdoc - */ - close(): void; - /** - * @inheritdoc - */ - sendData(invoke: Invoke): void; - } -} -declare namespace samchon.protocol { - /** - * Communicator with remote web-browser. - * - * {@link SharedWorkerClientDriver} is a class taking full charge of network communication with web browsers. This - * {@link SharedWorkerClientDriver} object is always created by {@link SharedWorkerServer} class. When you got this - * {@link SharedWorkerClientDriver} object from {@link SharedWorkerServer.addClient SharedWorkerServer.addClient()}, - * then specify {@link IProtocol listener} with the - * {@link SharedWorkerClientDriver.listen SharedWorkerClientDriver.listen()} method. - * - * #### Why SharedWorker be a server? - * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser - * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship - * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as - * clients. - * - * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a - * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the - * server and clients with this {@link SharedWorkerCommunicator}. - * - * #### [Inherited] {@link IClientDriver} - * {@link IClientDriver} is a type of {@link ICommunicator}, specified for communication with remote client who has - * connected in a {@link IServer server}. It takes full charge of network communication with the remote client. - * - * The {@link IClientDriver} object is created and delivered from {@link IServer} and - * {@link IServer.addClient IServer.addClient()}. Those are derived types from this {@link IClientDriver}, being - * created by the matched {@link IServer} object. - * - * Protocol | Derived Type | Created By - * ------------------------|-------------------------------------|---------------------------- - * Samchon Framework's own | {@link ClientDriver} | {@link Server} - * Web-socket protocol | {@link WebClientDriver} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerClinetDriver} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerClientDriver} | {@link SharedWorkerServer} - * - * When you've got an {@link IClientDriver} object from the {@link IServer.addClient IServer.addClient()}, then - * specify {@link IProtocol listener} with {@link IClient.listen IClient.listen()}. Whenever a replied message comes - * from the remote system, the message will be converted to an {@link Invoke} class and the {@link Invoke} object - * will be shifted to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * Below code is an example specifying and managing the {@link IProtocol listener} objects. - * - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - * - * - * - * - * @see {@link SharedWorkerServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iclientdriver) - * @author Jeongho Nam - */ - class SharedWorkerClientDriver extends SharedWorkerCommunicator implements IClientDriver { - private listening_; - /** - * Construct from a MessagePort object. - */ - constructor(port: MessagePort); - /** - * @inheritdoc - */ - listen(listener: IProtocol): void; - } -} -declare namespace samchon.protocol { - /** - * A container of entity, and it's a type of entity, too. - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) - * - * @handbook [Protocol - Standard Message](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Standard_Message) - * @author Jeongho Nam - */ - interface IEntityGroup extends IEntity, std.base.IContainer { - /** - * Construct data of the Entity from an XML object. - * - * Constructs the EntityArray's own member variables only from the input XML object. - * - * Do not consider about constructing children Entity objects' data in EntityArray::construct(). - * Those children Entity objects' data will constructed by their own construct() method. Even insertion - * of XML objects representing children are done by abstract method of EntityArray::toXML(). - * - * Constructs only data of EntityArray's own. - */ - construct(xml: library.XML): void; - /** - * Factory method of a child Entity. - * - * EntityArray::createChild() is a factory method creating a new child Entity which is belonged - * to the EntityArray. This method is called by EntityArray::construct(). The children construction - * methods Entity::construct() will be called by abstract method of the EntityArray::construct(). - * - * @return A new child Entity belongs to EntityArray. - */ - createChild(xml: library.XML): T; - /** - * Get iterator to element. - * - * Searches the container for an element with a identifier equivalent to *key* and returns an - * iterator to it if found, otherwise it returns an iterator to {@link end end()}. - * - * Two keys are considered equivalent if the container's comparison object returns false reflexively - * (i.e., no matter the order in which the elements are passed as arguments). - * - * Another member functions, {@link has has()} and {@link count count()}, can be used to just check - * whether a particular *key* exists. - * - * @param key Key to be searched for - * @return An iterator to the element, if an element with specified *key* is found, or - * {@link end end()} otherwise. - */ - /** - * Whether have the item or not. - * - * Indicates whether a map has an item having the specified identifier. - * - * @param key Key value of the element whose mapped value is accessed. - * - * @return Whether the map has an item having the specified identifier. - */ - has(key: any): boolean; - /** - * Count elements with a specific key. - * - * Searches the container for elements whose key is *key* and returns the number of elements found. - * - * @param key Key value to be searched for. - * - * @return The number of elements in the container with a *key*. - */ - count(key: any): number; - /** - * Get an element - * - * Returns a reference to the mapped value of the element identified with *key*. - * - * @param key Key value of the element whose mapped value is accessed. - * - * @throw exception out of range - * - * @return A reference object of the mapped value (_Ty) - */ - get(key: any): T; - /** - * A tag name of children objects. - */ - CHILD_TAG(): string; - /** - * Get an XML object represents the EntityArray. - * - * Archives the EntityArray's own member variables only to the returned XML object. - * - * Do not consider about archiving children Entity objects' data in EntityArray::toXML(). - * Those children Entity objects will converted to XML object by their own toXML() method. The - * insertion of XML objects representing children are done by abstract method of - * EntityArray::toXML(). - * - * Archives only data of EntityArray's own. - */ - toXML(): library.XML; - } - /** - * @hidden - */ - namespace IEntityGroup { - /** - * @hidden - */ - function construct(entityGroup: IEntityGroup, xml: library.XML, ...prohibited_names: string[]): void; - /** - * @hidden - */ - function toXML(entityGroup: IEntityGroup, ...prohibited_names: string[]): library.XML; - function has(entityGroup: IEntityGroup, key: any): boolean; - function count(entityGroup: IEntityGroup, key: any): number; - function get(entityGroup: IEntityGroup, key: any): T; - } -} -declare namespace samchon.protocol { - /** - * @inheritdoc - */ - abstract class EntityArray extends std.Vector implements IEntityGroup { - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * @inheritdoc - */ - abstract createChild(xml: library.XML): T; - /** - * @inheritdoc - */ - key(): any; - /** - * @inheritdoc - */ - has(key: any): boolean; - /** - * @inheritdoc - */ - count(key: any): number; - /** - * @inheritdoc - */ - get(key: any): T; - /** - * @inheritdoc - */ - abstract TAG(): string; - /** - * @inheritdoc - */ - abstract CHILD_TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.protocol { - /** - * @inheritdoc - */ - abstract class EntityList extends std.List implements IEntityGroup { - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * @inheritdoc - */ - abstract createChild(xml: library.XML): T; - /** - * @inheritdoc - */ - key(): any; - /** - * @inheritdoc - */ - has(key: any): boolean; - /** - * @inheritdoc - */ - count(key: any): number; - /** - * @inheritdoc - */ - get(key: any): T; - /** - * @inheritdoc - */ - abstract TAG(): string; - /** - * @inheritdoc - */ - abstract CHILD_TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.protocol { - /** - * @inheritdoc - */ - abstract class EntityDeque extends std.Deque implements IEntityGroup { - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * @inheritdoc - */ - abstract createChild(xml: library.XML): T; - /** - * @inheritdoc - */ - key(): any; - /** - * @inheritdoc - */ - has(key: any): boolean; - /** - * @inheritdoc - */ - count(key: any): number; - /** - * @inheritdoc - */ - get(key: any): T; - /** - * @inheritdoc - */ - abstract TAG(): string; - /** - * @inheritdoc - */ - abstract CHILD_TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.protocol { - /** - * Standard message of network I/O. - * - * {@link Invoke} is a class used in network I/O in protocol package of Samchon Framework. - * - * The Invoke message has an XML structure like the result screen of provided example in below. - * We can enjoy lots of benefits by the normalized and standardized message structure used in - * network I/O. - * - * The greatest advantage is that we can make any type of network system, even how the system - * is enourmously complicated. As network communication message is standardized, we only need to - * concentrate on logical relationships between network systems. We can handle each network system - * like a object (class) in OOD. And those relationships can be easily designed by using design - * pattern. - * - * In Samchon Framework, you can make any type of network system with basic componenets - * (IProtocol, IServer and ICommunicator) by implemens or inherits them, like designing - * classes of S/W architecture. - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) - * - * @see {@link IProtocol} - * @author Jeongho Nam - */ - class Invoke extends EntityArray { - /** - * Listener, represent function's name. - */ - private listener; - /** - * Default Constructor. - */ - constructor(); - constructor(listener: string); - /** - * Copy Constructor. - * - * @param invoke - */ - constructor(invoke: Invoke); - /** - * Construct from listener and parametric values. - * - * @param listener - * @param parameters - */ - constructor(listener: string, ...parameters: Array); - /** - * @inheritdoc - */ - createChild(xml: library.XML): InvokeParameter; - /** - * Get listener. - */ - getListener(): string; - /** - * Get arguments for Function.apply(). - * - * @return An array containing values of the contained parameters. - */ - getArguments(): Array; - /** - * Apply to a matched function. - * - * @param obj Target {@link IProtocol} object to find matched function. - * @return Whether succeded to find matched function. - */ - apply(obj: IProtocol): boolean; - /** - * Apply to a function. - * - * @param thisArg Owner of the function. - * @param func Function to call. - */ - apply(thisArg: IProtocol, func: Function): void; - /** - * @inheritdoc - */ - TAG(): string; - /** - * @inheritdoc - */ - CHILD_TAG(): string; - } -} -declare namespace samchon.protocol { - /** - * A parameter belongs to an Invoke. - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) - * - * @author Jeongho Nam - */ - class InvokeParameter extends Entity { - /** - * Name of the parameter. - * - * @details Optional property, can be omitted. - */ - protected name: string; - /** - * Type of the parameter. - */ - protected type: string; - /** - * Value of the parameter. - */ - protected value: string | number | library.XML | Uint8Array; - /** - * Default Constructor. - */ - constructor(); - constructor(val: number); - constructor(val: string); - constructor(val: library.XML); - constructor(val: Uint8Array); - /** - * Construct from variable name and number value. - * - * @param name - * @param val - */ - constructor(name: string, val: number); - constructor(name: string, val: string); - constructor(name: string, val: library.XML); - constructor(name: string, val: Uint8Array); - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - setValue(value: number): void; - setValue(value: string): void; - setValue(value: library.XML): void; - setValue(value: Uint8Array): void; - /** - * @inheritdoc - */ - key(): any; - /** - * Get name. - */ - getName(): string; - /** - * Get type. - */ - getType(): string; - /** - * Get value. - */ - getValue(): any; - /** - * @inheritdoc - */ - TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.protocol { - /** - * History of an {@link Invoke} message. - * - * The {@link InvokeHistory} is a class archiving history log of an {@link Invoke} message with elapsed time. This - * {@link InvokeHistory} class is used to report elapsed time of handling a requested process from **slave** to - * **master** system. - * - * The **master** system utilizes derived {@link InvokeHistory} objects to compute performance indices. - * - {@link ParallelSytem.getPerformance} - * - {@link DistributedProcess.getResource} - * - * @author Jeongho Nam - */ - class InvokeHistory extends protocol.Entity { - /** - * @hidden - */ - private uid; - /** - * @hidden - */ - private listener; - /** - * @hidden - */ - private start_time_; - /** - * @hidden - */ - private end_time_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from an {@link Invoke} message. - * - * @param invoke An {@link Invoke} message requesting a *parallel or distributed process*. - */ - constructor(invoke: protocol.Invoke); - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * Complete the history. - * - * Completes the history and determines the {@link getEndTime end time}. - */ - complete(): void; - key(): number; - /** - * Get unique ID. - */ - getUID(): number; - /** - * Get {@link Invoke.getListener listener} of the {@link Invoke} message. - */ - getListener(): string; - /** - * Get start time. - */ - getStartTime(): Date; - /** - * Get end time. - */ - getEndTime(): Date; - /** - * Compute elapsed time. - * - * @return nanoseconds. - */ - computeElapsedTime(): number; - /** - * @inheritdoc - */ - TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - /** - * Convert to an {@link Invoke} message. - * - * Creates and returns an {@link Invoke} message that is used to reporting to the **master**. - */ - toInvoke(): protocol.Invoke; - } -} -declare namespace samchon.protocol { - /** - * An interface for {@link Invoke} message chain. - * - * {@link IProtocol} is an interface for {@link Invoke} message, which is standard message of network I/O in - * *Samchon Framework*, chain. The {@link IProtocol} interface is used to network drivers and some classes which are - * in a relationship of *Chain of Responsibility Pattern* with those network drivers. - * - * Implements {@link IProtocol} if the class sends and handles {@link Invoke} messages. Looking around source codes of - * the *Samchon Framework*, especially *Templates*, you can find out that all the classes and modules handling - * {@link Invoke} messages are always implementing this {@link IProtocol}. - * - * - * - * - * - * @see {@link Invoke} - * @handbook https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iprotocol - * @author Jeongho Nam - */ - interface IProtocol { - /** - * Sending message. - * - * Sends message to related system or shifts the responsibility to chain. - * - * @param invoke Invoke message to send - */ - replyData(invoke: Invoke): void; - /** - * Handling replied message. - * - * Handles replied message or shifts the responsibility to chain. - * - * @param invoke An {@link Invoke} message has received. - */ - sendData(invoke: Invoke): void; - } -} -declare namespace samchon.protocol { - /** - * An interface for a server. - * - * {@link IServer} is an interfaec for server classes who are providing methods for {@link open opening a server} and - * {@link IClientDriver accepting clients}. - * - * To open a server, extends one of derived class under below considedring which protocol to follow first. At next, - * overrides {@link addClient addClient()} method who accepts a newly connected client as an {@link IClientDriver} - * object. Then at last, call {@link open open()} method with specified port number. - * - * Protocol | Derived Type | Related {@link IClientDriver} - * ------------------------|-------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerClientDriver} - * - * Below codes and classes will be good examples for comprehending how to open a server and handle remote clients. - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - https://github.com/samchon/framework/blob/master/ts/examples/chat-server/server.ts - * - {@link service.Server} - * - {@link external.ExternalClientArray} - * - {@link slave.SlaveServer} - * - * If you're embarrased because your class already extended another one, then use {@link IServerBase}. - * - * - * - * - * - * @see {@link IClientDriver}, {@link IServerBase} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserver) - * @author Jeongho Nam - */ - interface IServer { - /** - * Open server. - * - * @param port Port number to open. - */ - open(port: number): void; - /** - * Close server. - * - * Close opened server. All remote clients, have connected with this server, are also closed and their call back - * functions, for closed connection, {@link IClientDriver.onClose} are also called. - */ - close(): void; - /** - * Add a newly connected remote client. - * - * The {@link addClient addClient()} is an abstract method being called when a remote client is newly connected - * with {@link IClientDriver} object who communicates with the remote system. Overrides this method and defines - * what to do with the *driver*, a newly connected remote client. - * - * Below methods and example codes may be good for comprehending how to utilize this {@link addClient} method. - * - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - https://github.com/samchon/framework/blob/master/ts/examples/chat-server/server.ts - * - {@link service.Server.addClient} - * - {@link external.ExternalClientArray.addClient} - * - {@link slave.SlaveServer.addClient} - * - * @param driver A {@link ICommunicator communicator} with (newly connected) remote client. - */ - addClient(driver: IClientDriver): void; - } -} -declare namespace samchon.protocol { - /** - * A server. - * - * The {@link Server} is an abstract class designed to open a server and accept clients who are following Samchon - * Framework's own protocol. Extends this {@link Server} class and overrides {@link addClient addClient()} method to - * define what to do with newly connected {@link ClientDriver remote clients}. - * - * #### [Inherited] {@link IServer} - * {@link IServer} is an interfaec for server classes who are providing methods for {@link open opening a server} and - * {@link IClientDriver accepting clients}. - * - * To open a server, extends one of derived class under below considedring which protocol to follow first. At next, - * overrides {@link addClient addClient()} method who accepts a newly connected client as an {@link IClientDriver} - * object. Then at last, call {@link open open()} method with specified port number. - * - * Protocol | Derived Type | Related {@link IClientDriver} - * ------------------------|-------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerClientDriver} - * - * Below codes and classes will be good examples for comprehending how to open a server and handle remote clients. - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - https://github.com/samchon/framework/blob/master/ts/examples/chat-server/server.ts - * - {@link service.Server} - * - {@link external.ExternalClientArray} - * - {@link slave.SlaveServer} - * - * If you're embarrased because your class already extended another one, then use {@link IServerBase}. - * - * - * - * - * - * @see {@link ClientDriver}, {@link ServerBase} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserver) - * @author Jeongho Nam - */ - abstract class Server implements IServer { - /** - * @hidden - */ - private server; - /** - * @inheritdoc - */ - abstract addClient(driver: ClientDriver): void; - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - /** - * @hidden - */ - private handle_connect(socket); - } -} -declare namespace samchon.protocol { - /** - * A web server. - * - * The {@link WebServer} is an abstract class designed to open a server and accept clients who are following - * web-socket protocol. Extends this {@link WebServer} class and overrides {@link addClient addClient()} method to - * define what to do with newly connected {@link WebClientDriver remote clients}. - * - * #### [Inherited] {@link IServer} - * {@link IServer} is an interfaec for server classes who are providing methods for {@link open opening a server} and - * {@link IClientDriver accepting clients}. - * - * To open a server, extends one of derived class under below considedring which protocol to follow first. At next, - * overrides {@link addClient addClient()} method who accepts a newly connected client as an {@link IClientDriver} - * object. Then at last, call {@link open open()} method with specified port number. - * - * Protocol | Derived Type | Related {@link IClientDriver} - * ------------------------|-------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerClientDriver} - * - * Below codes and classes will be good examples for comprehending how to open a server and handle remote clients. - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - https://github.com/samchon/framework/blob/master/ts/examples/chat-server/server.ts - * - {@link service.Server} - * - {@link external.ExternalClientArray} - * - {@link slave.SlaveServer} - * - * If you're embarrased because your class already extended another one, then use {@link IServerBase}. - * - * - * - * - * - * @see {@link WebClientDriver}, {@link WebServerBase} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserver) - * @author Jeongho Nam - */ - abstract class WebServer implements IServer { - /** - * @hidden - */ - private http_server_; - /** - * @hidden - */ - private sequence_; - /** - * @hidden - */ - private my_port_; - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - /** - * @inheritdoc - */ - abstract addClient(driver: WebClientDriver): void; - /** - * @hidden - */ - private handle_request(request); - /** - * @hidden - */ - private get_session_id(cookies); - /** - * @hidden - */ - private issue_session_id(); - } -} -declare namespace samchon.protocol { - /** - * A SharedWorker server. - * - * The {@link DedicatedWorkerServer} is an abstract class is realized to open a DedicatedWorker server and accept - * web-browser client (master). Extends this {@link DedicatedWorkerServer} class and overrides - * {@link addClient addClient()} method to define what to do with a newly connected - * {@link DedicatedWorkerClientDriver remote client}. - * - * #### Why DedicatedWorker be a server? - * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the - * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the - * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network - * communication? Furthermore, there's not any difference between the worker communication and network communication. - * It's the reason why Samchon Framework considers the **Worker** as a network node. - * - * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a - * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the - * server and clients with this {@link DedicatedWorkerCommunicator}. - * - * #### [Inherited] {@link IServer} - * {@link IServer} is an interfaec for server classes who are providing methods for {@link open opening a server} and - * {@link IClientDriver accepting clients}. - * - * To open a server, extends one of derived class under below considedring which protocol to follow first. At next, - * overrides {@link addClient addClient()} method who accepts a newly connected client as an {@link IClientDriver} - * object. Then at last, call {@link open open()} method with specified port number. - * - * Protocol | Derived Type | Related {@link IClientDriver} - * ------------------------|-------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerClientDriver} - * - * Below codes and classes will be good examples for comprehending how to open a server and handle remote clients. - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - https://github.com/samchon/framework/blob/master/ts/examples/chat-server/server.ts - * - {@link service.Server} - * - {@link external.ExternalClientArray} - * - {@link slave.SlaveServer} - * - * If you're embarrased because your class already extended another one, then use {@link IServerBase}. - * - * - * - * - * - * @see {@link DedicatedWorkerClientDriver}, {@link DedicatedWorkerServerBase} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserver) - * @author Jeongho Nam - */ - abstract class DedicatedWorkerServer implements IServer { - /** - * @inheritdoc - */ - open(): void; - /** - * @inheritdoc - */ - close(): void; - /** - * @inheritdoc - */ - abstract addClient(driver: DedicatedWorkerClientDriver): void; - } -} -declare namespace samchon.protocol { - /** - * A SharedWorker server. - * - * The {@link SharedWorker} is an abstract class is realized to open a SharedWorker server and accept web-browser - * clients. Extends this {@link SharedWorkerServer} class and overrides {@link addClient addClient()} method to - * define what to do with newly connected {@link SharedWorkerClientDriver remote clients}. - * - * #### Why SharedWorker be a server? - * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser - * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship - * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as - * clients. - * - * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a - * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the - * server and clients with this {@link SharedWorkerCommunicator}. - * - * #### [Inherited] {@link IServer} - * {@link IServer} is an interfaec for server classes who are providing methods for {@link open opening a server} and - * {@link IClientDriver accepting clients}. - * - * To open a server, extends one of derived class under below considedring which protocol to follow first. At next, - * overrides {@link addClient addClient()} method who accepts a newly connected client as an {@link IClientDriver} - * object. Then at last, call {@link open open()} method with specified port number. - * - * Protocol | Derived Type | Related {@link IClientDriver} - * ------------------------|-------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerClientDriver} - * - * Below codes and classes will be good examples for comprehending how to open a server and handle remote clients. - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - https://github.com/samchon/framework/blob/master/ts/examples/chat-server/server.ts - * - {@link service.Server} - * - {@link external.ExternalClientArray} - * - {@link slave.SlaveServer} - * - * If you're embarrased because your class already extended another one, then use {@link IServerBase}. - * - * - * - * - * - * @see {@link SharedWorkerClientDriver}, {@link SharedWorkerServerBase} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserver) - * @author Jeongho Nam - */ - abstract class SharedWorkerServer implements IServer { - /** - * @inheritdoc - */ - abstract addClient(driver: SharedWorkerClientDriver): void; - /** - * @inheritdoc - */ - open(): void; - /** - * @inheritdoc - */ - close(): void; - /** - * @hidden - */ - private handle_connect(event); - } -} -declare namespace samchon.protocol { - /** - * An interface for substitute server classes. - * - * {@link IServerBase} is an interface for substitue server classes who subrogate server's role. - * - * The easiest way to defining a server class is to extending one of them below, who implemented the {@link IServer}. - * However, it is impossible (that is, if the class is already extending another class), you can instead implement - * the {@link IServer} interface, create an {@link IServerBase} member, and write simple hooks to route calls into - * the aggregated {@link IServerBase}. - * - * Protocol | {@link IServer} | {@link IServerBase} | {@link IClientDriver} - * ------------------------|-------------------------------|-----------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ServerBase} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebServerBase} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerServerBase} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerServerBase} | {@link SharedWorkerClientDriver} - * - * After the hooking to aggregated {@link IServerBase} object, overrides {@link addClient addClient()} method who - * accepts a newly connected client as an {@link IClientDriver} object. At last, call {@link open open()} method with - * specified port number. - * - * ```typescript - * class MyServer extends Something implements IServer - * { - * private server_base_: IServerBase = new WebServerBase(this); - * - * public addClient(driver: IClientDriver): void - * { - * // WHAT TO DO WHEN A CLIENT HAS CONNECTED - * } - * - * public open(port: number): void - * { - * this.server_base_.open(); - * } - * public close(): void - * { - * this.server_base_.close(); - * } - * } - * ``` - * - * - * - * - * - * @see {@link IServer}, {@link IClientDriver} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverbase) - * @author Jeongho Nam - */ - interface IServerBase extends IServer { - } -} -declare namespace samchon.protocol { - /** - * A substitute {@link Server}. - * - * The {@link ServerBase} is a substitute class who subrogates {@link Server}'s responsibility. - * - * #### [Inherited] {@link IServerBase} - * {@link IServerBase} is an interface for substitue server classes who subrogate server's role. - * - * The easiest way to defining a server class is to extending one of them below, who implemented the {@link IServer}. - * However, it is impossible (that is, if the class is already extending another class), you can instead implement - * the {@link IServer} interface, create an {@link IServerBase} member, and write simple hooks to route calls into - * the aggregated {@link IServerBase}. - * - * Protocol | {@link IServer} | {@link IServerBase} | {@link IClientDriver} - * ------------------------|-------------------------------|-----------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ServerBase} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebServerBase} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerServerBase} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerServerBase} | {@link SharedWorkerClientDriver} - * - * After the hooking to aggregated {@link IServerBase} object, overrides {@link addClient addClient()} method who - * accepts a newly connected client as an {@link IClientDriver} object. At last, call {@link open open()} method with - * specified port number. - * - * ```typescript - * class MyServer extends Something implements IServer - * { - * private server_base_: IServerBase = new WebServerBase(this); - * - * public addClient(driver: IClientDriver): void - * { - * // WHAT TO DO WHEN A CLIENT HAS CONNECTED - * } - * - * public open(port: number): void - * { - * this.server_base_.open(); - * } - * public close(): void - * { - * this.server_base_.close(); - * } - * } - * ``` - * - * - * - * - * - * - * @see {@link Server}, {@link ClientDriver} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverbase) - * @author Jeongho Nam - */ - class ServerBase extends Server implements IServerBase { - /** - * @hidden - */ - private hooker_; - /** - * Construct from a *hooker*. - * - * @param hooker A hooker throwing responsibility of server's role. - */ - constructor(hooker: IServer); - /** - * @inheritdoc - */ - addClient(driver: IClientDriver): void; - } -} -declare namespace samchon.protocol { - /** - * A substitute {@link WebServer}. - * - * The {@link WebServerBase} is a substitute class who subrogates {@link WebServer}'s responsibility. - * - * #### [Inherited] {@link IServerBase} - * {@link IServerBase} is an interface for substitue server classes who subrogate server's role. - * - * The easiest way to defining a server class is to extending one of them below, who implemented the {@link IServer}. - * However, it is impossible (that is, if the class is already extending another class), you can instead implement - * the {@link IServer} interface, create an {@link IServerBase} member, and write simple hooks to route calls into - * the aggregated {@link IServerBase}. - * - * Protocol | {@link IServer} | {@link IServerBase} | {@link IClientDriver} - * ------------------------|-------------------------------|-----------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ServerBase} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebServerBase} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerServerBase} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerServerBase} | {@link SharedWorkerClientDriver} - * - * After the hooking to aggregated {@link IServerBase} object, overrides {@link addClient addClient()} method who - * accepts a newly connected client as an {@link IClientDriver} object. At last, call {@link open open()} method with - * specified port number. - * - * ```typescript - * class MyServer extends Something implements IServer - * { - * private server_base_: IServerBase = new WebServerBase(this); - * - * public addClient(driver: IClientDriver): void - * { - * // WHAT TO DO WHEN A CLIENT HAS CONNECTED - * } - * - * public open(port: number): void - * { - * this.server_base_.open(); - * } - * public close(): void - * { - * this.server_base_.close(); - * } - * } - * ``` - * - * - * - * - * - * @see {@link WebServer}, {@link WebClientDriver} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverbase) - * @author Jeongho Nam - */ - class WebServerBase extends WebServer implements IServerBase { - /** - * @hidden - */ - private hooker_; - /** - * Construct from a *hooker*. - * - * @param hooker A hooker throwing responsibility of server's role. - */ - constructor(hooker: IServer); - /** - * @inheritdoc - */ - addClient(driver: IClientDriver): void; - } -} -declare namespace samchon.protocol { - /** - * A substitute {@link DedicatedWorkerServer}. - * - * The {@link DedicatedWorkerServerBase} is a substitute class who subrogates {@link DedicatedWorkerServer}'s - * responsibility. - * - * #### [Inherited] {@link IServerBase} - * {@link IServerBase} is an interface for substitue server classes who subrogate server's role. - * - * The easiest way to defining a server class is to extending one of them below, who implemented the {@link IServer}. - * However, it is impossible (that is, if the class is already extending another class), you can instead implement - * the {@link IServer} interface, create an {@link IServerBase} member, and write simple hooks to route calls into - * the aggregated {@link IServerBase}. - * - * Protocol | {@link IServer} | {@link IServerBase} | {@link IClientDriver} - * ------------------------|-------------------------------|-----------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ServerBase} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebServerBase} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerServerBase} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerServerBase} | {@link SharedWorkerClientDriver} - * - * After the hooking to aggregated {@link IServerBase} object, overrides {@link addClient addClient()} method who - * accepts a newly connected client as an {@link IClientDriver} object. At last, call {@link open open()} method with - * specified port number. - * - * ```typescript - * class MyServer extends Something implements IServer - * { - * private server_base_: IServerBase = new WebServerBase(this); - * - * public addClient(driver: IClientDriver): void - * { - * // WHAT TO DO WHEN A CLIENT HAS CONNECTED - * } - * - * public open(port: number): void - * { - * this.server_base_.open(); - * } - * public close(): void - * { - * this.server_base_.close(); - * } - * } - * ``` - * - * - * - * - * - * @see {@link DedicatedWorkerServer}, {@link DedicatedWorkerClientDriver} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverbase) - * @author Jeongho Nam - */ - class DedicatedWorkerServerBase extends DedicatedWorkerServer implements IServerBase { - /** - * @hidden - */ - private hooker_; - /** - * Construct from a *hooker*. - * - * @param hooker A hooker throwing responsibility of server's role. - */ - constructor(hooker: IServer); - /** - * @inheritdoc - */ - addClient(driver: IClientDriver): void; - } -} -declare namespace samchon.protocol { - /** - * A substitute {@link SharedWorkerServer}. - * - * The {@link SharedWorkerServerBase} is a substitute class who subrogates {@link SharedWorkerServer}'s - * responsibility. - * - * #### [Inherited] {@link IServerBase} - * {@link IServerBase} is an interface for substitue server classes who subrogate server's role. - * - * The easiest way to defining a server class is to extending one of them below, who implemented the {@link IServer}. - * However, it is impossible (that is, if the class is already extending another class), you can instead implement - * the {@link IServer} interface, create an {@link IServerBase} member, and write simple hooks to route calls into - * the aggregated {@link IServerBase}. - * - * Protocol | {@link IServer} | {@link IServerBase} | {@link IClientDriver} - * ------------------------|-------------------------------|-----------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ServerBase} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebServerBase} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerServerBase} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerServerBase} | {@link SharedWorkerClientDriver} - * - * After the hooking to aggregated {@link IServerBase} object, overrides {@link addClient addClient()} method who - * accepts a newly connected client as an {@link IClientDriver} object. At last, call {@link open open()} method with - * specified port number. - * - * ```typescript - * class MyServer extends Something implements IServer - * { - * private server_base_: IServerBase = new WebServerBase(this); - * - * public addClient(driver: IClientDriver): void - * { - * // WHAT TO DO WHEN A CLIENT HAS CONNECTED - * } - * - * public open(port: number): void - * { - * this.server_base_.open(); - * } - * public close(): void - * { - * this.server_base_.close(); - * } - * } - * ``` - * - * - * - * - * - * @see {@link SharedWorkerServer}, {@link SharedWorkerClientDriver} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverbase) - * @author Jeongho Nam - */ - class SharedWorkerServerBase extends SharedWorkerServer implements IServerBase { - /** - * @hidden - */ - private hooker_; - /** - * Construct from a *hooker*. - * - * @param hooker A hooker throwing responsibility of server's role. - */ - constructor(hooker: IServer); - /** - * @inheritdoc - */ - addClient(driver: IClientDriver): void; - } -} -declare namespace samchon.protocol { - /** - * An interface for server connector. - * - * {@link IServerConnector} is a type of {@link ICommunicator}, specified for server connector classes who connect to - * the remote server as a client. {@link IServerConnector} provides {@link connect connection method} and takes full - * charge of network communication with the remote server. - * - * Declare specific type of {@link IServerConnector} from {@link IProtocol listener} and call the - * {@link connect connect()} method. Then whenever a replied message comes from the remote system, the message will - * be converted to an {@link Invoke} object and the {@link Invoke} object will be shifted to the - * {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. Below code is an example - * connecting to remote server and interacting with it. - * - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-application.ts - * - * Note that, protocol of this client and remote server must be matched. Thus, before determining specific type of - * this {@link IServerConnector}, you've to consider which protocol and type the remote server follows. - * - * Protocol | Derived Type | Connect to - * ------------------------|----------------------------------------|------------------------------- - * Samchon Framework's own | {@link ServerConnector} | {@link Server} - * Web-socket protocol | {@link WebServerConnector} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerServerConnector} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerServerConnector} | {@link SharedWorkerServer} - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_basic_components.png) - * - * @see {@link IServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverconnector) - * @author Jeongho Nam - */ - interface IServerConnector extends ICommunicator { - /** - * Callback function for connection completed. - * - * When you call {@link connect connect()} and the connection has completed, then this call back function - * {@link onConnect} will be called. Note that, if the listener of this {@link onConnect} is a member method of - * some class, then you've use the ```bind```. - */ - onConnect: Function; - /** - * Connect to a server. - * - * Connects to a server with specified *host* address and *port* number. After the connection has - * succeeded, callback function {@link onConnect} is called. Listening data from the connected server also begins. - * Replied messages from the connected server will be converted to {@link Invoke} classes and will be shifted to - * the {@link WebCommunicator.listener listener}'s {@link IProtocol.replyData replyData()} method. - * - * If the connection fails immediately, either an event is dispatched or an exception is thrown: an error - * event is dispatched if a host was specified, and an exception is thrown if no host was specified. Otherwise, - * the status of the connection is reported by an event. If the socket is already connected, the existing - * connection is closed first. - * - * @param ip The name or IP address of the host to connect to. - * If no host is specified, the host that is contacted is the host where the calling file resides. - * If you do not specify a host, use an event listener to determine whether the connection was - * successful. - * @param port The port number to connect to. - */ - connect(ip: string, port: number): void; - } -} -declare namespace samchon.protocol { - /** - * Server connnector. - * - * {@link ServerConnector} is a class connecting to remote server who follows Samchon Framework's own protocol and - * taking full charge of network communication with the remote server. Create a {@link ServerConnector} instance from - * the {@IProtocol listener} and call the {@link connect connect()} method. - * - * #### [Inherited] {@link IServerConnector} - * {@link IServerConnector} is a type of {@link ICommunicator}, specified for server connector classes who connect to - * the remote server as a client. {@link IServerConnector} provides {@link connect connection method} and takes full - * charge of network communication with the remote server. - * - * Declare specific type of {@link IServerConnector} from {@link IProtocol listener} and call the - * {@link connect connect()} method. Then whenever a replied message comes from the remote system, the message will - * be converted to an {@link Invoke} object and the {@link Invoke} object will be shifted to the - * {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * - * Note that, protocol of this client and remote server must be matched. Thus, before determining specific type of - * this {@link IServerConnector}, you've to consider which protocol and type the remote server follows. - * - * Protocol | Derived Type | Connect to - * ------------------------|----------------------------------------|------------------------------- - * Samchon Framework's own | {@link ServerConnector} | {@link Server} - * Web-socket protocol | {@link WebServerConnector} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerServerConnector} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerServerConnector} | {@link SharedWorkerServer} - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_basic_components.png) - * - * @see {@link Server}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverconnector) - * @author Jeongho Nam - */ - class ServerConnector extends Communicator implements IServerConnector { - /** - * @inheritdoc - */ - onConnect: Function; - /** - * Construct from *listener*. - * - * @param listener A listener object to listen replied message from newly connected client in - * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. - */ - constructor(listener: IProtocol); - /** - * @inheritdoc - */ - connect(ip: string, port: number): void; - /** - * @hidden - */ - private handle_connect(...arg); - } -} -declare namespace samchon.protocol { - /** - * A server connector for web-socket protocol. - * - * {@link WebServerConnector} is a class connecting to remote server who follows Web-socket protocol and taking full - * charge of network communication with the remote server. Create an {@link WebServerConnector} instance from the - * {@IProtocol listener} and call the {@link connect connect()} method. - * - * #### [Inherited] {@link IServerConnector} - * {@link IServerConnector} is a type of {@link ICommunicator}, specified for server connector classes who connect to - * the remote server as a client. {@link IServerConnector} provides {@link connect connection method} and takes full - * charge of network communication with the remote server. - * - * Declare specific type of {@link IServerConnector} from {@link IProtocol listener} and call the - * {@link connect connect()} method. Then whenever a replied message comes from the remote system, the message will - * be converted to an {@link Invoke} class and the {@link Invoke} object will be shifted to the - * {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * - * Note that, protocol of this client and remote server must be matched. Thus, before determining specific type of - * this {@link IServerConnector}, you've to consider which protocol and type the remote server follows. - * - * Protocol | Derived Type | Connect to - * ------------------------|----------------------------------------|------------------------------- - * Samchon Framework's own | {@link ServerConnector} | {@link Server} - * Web-socket protocol | {@link WebServerConnector} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerServerConnector} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerServerConnector} | {@link SharedWorkerServer} - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_basic_components.png) - * - * @see {@link WebServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverconnector) - * @author Jeongho Nam - */ - class WebServerConnector extends WebCommunicator implements IServerConnector { - /** - * @hidden - */ - private browser_socket_; - /** - * @hidden - */ - private node_client_; - /** - * @inheritdoc - */ - onConnect: Function; - /** - * Construct from *listener*. - * - * @param listener A listener object to listen replied message from newly connected client in - * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. - */ - constructor(listener: IProtocol); - /** - * Connect to a web server. - * - * Connects to a server with specified *host* address, *port* number and *path*. After the connection has - * succeeded, callback function {@link onConnect} is called. Listening data from the connected server also begins. - * Replied messages from the connected server will be converted to {@link Invoke} classes and will be shifted to - * the {@link WebCommunicator.listener listener}'s {@link IProtocol.replyData replyData()} method. - * - * If the connection fails immediately, either an event is dispatched or an exception is thrown: an error - * event is dispatched if a host was specified, and an exception is thrown if no host was specified. Otherwise, - * the status of the connection is reported by an event. If the socket is already connected, the existing - * connection is closed first. - * - * @param ip The name or IP address of the host to connect to. - * If no host is specified, the host that is contacted is the host where the calling file resides. - * If you do not specify a host, use an event listener to determine whether the connection was - * successful. - * @param port The port number to connect to. - * @param path Path of service which you want. - */ - connect(ip: string, port: number, path?: string): void; - /** - * @inheritdoc - */ - close(): void; - /** - * @inheritdoc - */ - sendData(invoke: Invoke): void; - /** - * @hidden - */ - private handle_browser_connect(event); - /** - * @hidden - */ - private handle_browser_message(event); - /** - * @hidden - */ - private handle_node_connect(connection); - } -} -declare namespace samchon.protocol { - /** - * A server connector for DedicatedWorker. - * - * {@link DedicatedWorkerServerConnector} is a class connecting to SharedWorker and taking full charge of network - * communication with the SharedWorker. Create an {@link DedicatedWorkerServer} instance from the - * {@IProtocol listener} and call the {@link connect connect()} method. - * - * #### Why DedicatedWorker be a server? - * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the - * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the - * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network - * communication? Furthermore, there's not any difference between the worker communication and network communication. - * It's the reason why Samchon Framework considers the **Worker** as a network node. - * - * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a - * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the - * server and clients with this {@link DedicatedWorkerCommunicator}. - * - * #### [Inherited] {@link IServerConnector} - * {@link IServerConnector} is a type of {@link ICommunicator}, specified for server connector classes who connect to - * the remote server as a client. {@link IServerConnector} provides {@link connect connection method} and takes full - * charge of network communication with the remote server. - * - * Declare specific type of {@link IServerConnector} from {@link IProtocol listener} and call the - * {@link connect connect()} method. Then whenever a replied message comes from the remote system, the message will - * be converted to an {@link Invoke} class and the {@link Invoke} object will be shifted to the - * {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * - * Note that, protocol of this client and remote server must be matched. Thus, before determining specific type of - * this {@link IServerConnector}, you've to consider which protocol and type the remote server follows. - * - * Protocol | Derived Type | Connect to - * ------------------------|----------------------------------------|------------------------------- - * Samchon Framework's own | {@link ServerConnector} | {@link Server} - * Web-socket protocol | {@link WebServerConnector} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerServerConnector} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerServerConnector} | {@link SharedWorkerServer} - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_basic_components.png) - * - * @see {@link DedicatedWorkerServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverconnector) - * @author Jeongho Nam - */ - class DedicatedWorkerServerConnector extends DedicatedWorkerCommunicator implements IServerConnector { - /** - * @hidden - */ - private worker; - /** - * @inheritdoc - */ - onConnect: Function; - /** - * Construct from *listener*. - * - * @param listener A listener object to listen replied message from newly connected client in - * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. - */ - constructor(listener: IProtocol); - /** - * @inheritdoc - */ - connect(jsFile: string): void; - /** - * @inheritdoc - */ - close(): void; - /** - * @inheritdoc - */ - sendData(invoke: Invoke): void; - } -} -declare namespace samchon.protocol { - /** - * A server connector for SharedWorker. - * - * {@link SharedWorkerServerConnector} is a class connecting to SharedWorker and taking full charge of network - * communication with the SharedWorker. Create an {@link SharedWorkerServerConnector} instance from the - * {@IProtocol listener} and call the {@link connect connect()} method. - * - * #### Why SharedWorker be a server? - * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser - * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship - * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as - * clients. - * - * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a - * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the - * server and clients with this {@link SharedWorkerCommunicator}. - * - * #### [Inherited] {@link IServerConnector} - * {@link IServerConnector} is a type of {@link ICommunicator}, specified for server connector classes who connect to - * the remote server as a client. {@link IServerConnector} provides {@link connect connection method} and takes full - * charge of network communication with the remote server. - * - * Declare specific type of {@link IServerConnector} from {@link IProtocol listener} and call the - * {@link connect connect()} method. Then whenever a replied message comes from the remote system, the message will - * be converted to an {@link Invoke} class and the {@link Invoke} object will be shifted to the - * {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * - * Note that, protocol of this client and remote server must be matched. Thus, before determining specific type of - * this {@link IServerConnector}, you've to consider which protocol and type the remote server follows. - * - * Protocol | Derived Type | Connect to - * ------------------------|----------------------------------------|------------------------------- - * Samchon Framework's own | {@link ServerConnector} | {@link Server} - * Web-socket protocol | {@link WebServerConnector} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerServerConnector} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerServerConnector} | {@link SharedWorkerServer} - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_basic_components.png) - * - * @see {@link SharedWorkerServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverconnector) - * @author Jeongho Nam - */ - class SharedWorkerServerConnector extends SharedWorkerCommunicator implements IServerConnector { - /** - * @inheritdoc - */ - onConnect: Function; - /** - * Construct from *listener*. - * - * @param listener A listener object to listen replied message from newly connected client in - * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. - */ - constructor(listener: IProtocol); - /** - * Connect to a SharedWorker. - * - * Connects to a server with specified *jstFile* path. If a SharedWorker instance of the *jsFile* is not - * constructed yet, then the SharedWorker will be newly constructed. Otherwise the SharedWorker already exists, - * then connect to the SharedWorker. After those processes, callback function {@link onConnect} is called. - * Listening data from the connected server also begins. Replied messages from the connected server will be - * converted to {@link Invoke} classes and will be shifted to the {@link WebCommunicator.listener listener}'s - * {@link IProtocol.replyData replyData()} method. - * - * If the connection fails immediately, either an event is dispatched or an exception is thrown: an error - * event is dispatched if a host was specified, and an exception is thrown if no host was specified. Otherwise, - * the status of the connection is reported by an event. If the socket is already connected, the existing - * connection is closed first. - * - * @param jsFile Path of JavaScript file to execute who defines SharedWorker. - */ - connect(jsFile: string): void; - } -} -declare namespace samchon.protocol { - /** - * @hidden - */ - namespace socket { - type socket = any; - type server = any; - type http_server = any; - } - /** - * @hidden - */ - namespace websocket { - type connection = any; - type request = any; - type IMessage = any; - type ICookie = any; - type client = any; - } -} -declare namespace samchon.templates.distributed { - /** - * Master of Distributed Processing System, a server accepting slave clients. - * - * The {@link DistributedClientArray} is an abstract class, derived from the {@link DistributedSystemArray} class, - * opening a server accepting {@link DistributedSystem distributed clients}. - * - * Extends this {@link DistributedClientArray}, overrides {@link createServerBase createServerBase()} to determine - * which protocol to follow and {@link createExternalClient createExternalClient()} creating child - * {@link DistributedSystem} object. After the extending and overridings, open this server using the - * {@link open open()} method. - * - * #### [Inherited] {@link DistributedSystemArray} - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedClientArray extends DistributedSystemArray implements external.IExternalClientArray { - /** - * @hidden - */ - private server_base_; - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method creating {@link IServerBase} object. - * - * This method {@link createServerBase createServerBase()} determines which protocol is used in this server, - * {@link ExternalClientArray}. If the protocol is determined, then {@link ExternalSystem external clients} who - * may connect to {@link ExternalClientArray this server} must follow the specified protocol. - * - * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: - * - * - {@link ServerBase} - * - {@link WebServerBase} - * - {@link SharedWorkerServerBase} - * - * @return A new {@link IServerBase} object. - */ - protected abstract createServerBase(): protocol.IServerBase; - /** - * Add a newly connected remote client. - * - * When a {@link IClientDriver remote client} connects to this *master server of parallel processing system*, - * then this {@link ParallelClientArray} creates a child {@link ParallelSystem parallel client} object through - * the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. - * - * @param driver A communicator for external client. - */ - addClient(driver: protocol.IClientDriver): void; - /** - * (Deprecated) Factory method creating child object. - * - * The method {@link createChild createChild()} is deprecated. Don't use and override this. - * - * Note that, the {@link ParallelClientArray} is a server accepting {@link ParallelSystem parallel clients}. - * There's no way to creating the {@link ParallelSystem parallel clients} in advance before opening the server. - * - * @param xml An {@link XML} object represents the child {@link ParallelSystem} object. - * @return ```null``` - */ - createChild(xml: library.XML): System; - /** - * Factory method creating {@link DistributedSystem} object. - * - * The method {@link createExternalClient createExternalClient()} is a factory method creating a child - * {@link ParallelSystem} object, that is called whenever a parallel client has connected, by - * {@link addClient addClient()}. - * - * Overrides this {@link createExternalClient} method and creates a type of {@link DistributedSystem} object with - * the *driver* that communicates with the parallel client. After the creation, returns the object. Then whenever - * a parallel client has connected, matched {@link DistributedSystem} object will be constructed and - * {@link insert inserted} into this {@link DistributedSystemArray} object. - * - * @param driver A communicator with the parallel client. - * @return A newly created {@link ParallelSystem} object. - */ - protected abstract createExternalClient(driver: protocol.IClientDriver): System; - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - } -} -declare namespace samchon.templates.distributed { - /** - * Mediator of Distributed Processing System, a server accepting slave clients. - * - * The {@link DistributedClientArrayMediator} is an abstract class, derived from {@link DistributedSystemArrayMediator} - * class, opening a server accepting {@link DistributedSystem distributed clients} as a **master**. - * - * Extends this {@link DistributedClientArrayMediator}, overrides {@link createServerBase createServerBase()} to - * determine which protocol to follow and {@link createExternalClient createExternalClient()} creating child - * {@link DistributedSystem} object. After the extending and overridings, open this server using the - * {@link open open()} method. - * - * #### [Inherited] {@link DistributedSystemArrayMediator} - * The {@link DistributedSystemArrayMediator} class be a master for its slave systems, and be a slave to its master - * system at the same time. This {@link DistributedSystemArrayMediator} be a master system, containing and managing - * {@link DistributedSystem} objects, which represent distributed slave systems, by extending - * {@link DistributedSystemArray} class. Also, be a slave system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a slave, you can specify this {@link DistributedSystemArrayMediator} to be a client slave connecting to master - * server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link DistributedSystemArray} - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedClientArrayMediator extends DistributedSystemArrayMediator implements external.IExternalClientArray { - /** - * A subrogator of {@link IServer server}'s role instead of this {@link ExternalClientArray}. - */ - private server_base_; - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method creating {@link IServerBase} object. - * - * This method {@link createServerBase createServerBase()} determines which protocol is used in this - * {@link DistributedClientArrayMediator} object as a **master**. If the protocol is determined, then - * {@link DistributedSystem distributed clients} who may connect to {@link DistributedClientArrayMediator this - * server} must follow the specified protocol. - * - * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: - * - * - {@link ServerBase} - * - {@link WebServerBase} - * - {@link SharedWorkerServerBase} - * - * @return A new {@link IServerBase} object. - */ - protected abstract createServerBase(): protocol.IServerBase; - /** - * Add a newly connected remote client. - * - * When a {@link IClientDriver remote client} connects to this *master server of distributed processing system*, - * then this {@link DistributedClientArrayMediator} creates a child {@link Distributed distributed client} object - * through the {@link createExternalClient createExternalClient()} method. - * - * @param driver A communicator for external client. - */ - addClient(driver: protocol.IClientDriver): void; - /** - * (Deprecated) Factory method creating child object. - * - * The method {@link createChild createChild()} is deprecated. Don't use and override this. - * - * Note that, the {@link DistributedClientArrayMediator} is a server accepting {@link DistributedSystem distributed - * clients} as a master. There's no way to creating the {@link DistributedSystem distributed clients} in advance - * before opening the server. - * - * @param xml An {@link XML} object represents the child {@link DistributedSystem} object. - * @return null - */ - createChild(xml: library.XML): System; - /** - * Factory method creating {@link DistributedSystem} object. - * - * The method {@link createExternalClient createExternalClient()} is a factory method creating a child - * {@link DistributedSystem} object, that is called whenever a distributed client has connected, by - * {@link addClient addClient()}. - * - * Overrides this {@link createExternalClient} method and creates a type of {@link DistributedSystem} object with - * the *driver* that communicates with the distributed client. After the creation, returns the object. Then whenever - * a distributed client has connected, matched {@link DistributedSystem} object will be constructed and - * {@link insert inserted} into this {@link DistributedClientArrayMediator} object. - * - * @param driver A communicator with the distributed client. - * @return A newly created {@link DistributedSystem} object. - */ - protected abstract createExternalClient(driver: protocol.IClientDriver): System; - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - } -} -declare namespace samchon.templates.distributed { - /** - * A process of Distributed Processing System. - * - * The {@link DistributedProcess} is an abstract class who represents a **process**, *SOMETHING TO DISTRIBUTE* in a Distributed - * Processing System. Overrides the {@link DistributedProcess} and defines the *SOMETHING TO DISTRIBUTE*. - * - * Relationship between {@link DistributedSystem} and {@link DistributedProcess} objects are **M: N Associative**. - * Unlike {@link ExternalSystemRole}, the {@link DistributedProcess} objects are not belonged to a specific - * {@link DistributedSystem} object. The {@link DistributedProcess} objects are belonged to the - * {@link DistributedSystemArrayMediator} directly. - * - * When you need the **distributed process**, then call {@link sendData sendData()}. The {@link sendData} will find - * the most idle {@link DistributedSystem slave system} considering not only number of processes on progress, but also - * {@link DistributedSystem.getPerformance performance index} of each {@link DistributedSystem} object and - * {@link getResource resource index} of this {@link DistributedProcess} object. The {@link Invoke} message - * requesting the **distributed process** will be sent to the most idle {@link DistributedSystem slave system}. - * - * Those {@link DistributedSystem.getPerformance performance index} and {@link getResource resource index} are - * revaluated whenever the **distributed process** has completed basis on the execution time. - * - * - * - * - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedProcess extends protocol.Entity implements protocol.IProtocol { - /** - * @hidden - */ - private system_array_; - /** - * A name, represents and identifies this {@link DistributedProcess process}. - * - * This {@link name} is an identifier represents this {@link DistributedProcess process}. This {@link name} is - * used in {@link DistributedSystemArray.getProcess} and {@link DistributedSystemArray.getProcess}, as a key elements. - * Thus, this {@link name} should be unique in its parent {@link DistributedSystemArray} object. - */ - protected name: string; - /** - * @hidden - */ - private progress_list_; - /** - * @hidden - */ - private history_list_; - /** - * @hidden - */ - private resource; - /** - * @hidden - */ - private enforced_; - /** - * Constrct from parent {@link DistributedSystemArray} object. - * - * @param systemArray The parent {@link DistributedSystemArray} object. - */ - constructor(systemArray: DistributedSystemArray); - /** - * Identifier of {@link ParallelProcess} is its {@link name}. - */ - key(): string; - /** - * Get parent {@link DistributedSystemArray} object. - * - * @return The parent {@link DistributedSystemArray} object. - */ - getSystemArray(): DistributedSystemArray; - /** - * Get parent {@link DistributedSystemArray} object. - * - * @return The parent {@link DistributedSystemArray} object. - */ - getSystemArray>(): SystemArray; - /** - * Get name, who represents and identifies this process. - */ - getName(): string; - /** - * Get resource index. - * - * Get *resource index* that indicates how much this {@link DistributedProcess process} is heavy. - * - * If this {@link DistributedProcess process} does not have any {@link Invoke} message had handled, then the - * *resource index* will be ```1.0```, which means default and average value between all - * {@link DistributedProcess} instances (that are belonged to a same {@link DistributedSystemArray} object). - * - * You can specify the *resource index* by yourself, but notice that, if the *resource index* is higher than - * other {@link DistributedProcess} objects, then this {@link DistributedProcess process} will be ordered to - * handle less processes than other {@link DistributedProcess} objects. Otherwise, the *resource index* is - * lower than others, of course, much processes will be requested. - * - * - {@link setResource setResource()} - * - {@link enforceResource enforceResource()} - * - * Unless {@link enforceResource enforceResource()} is called, This *resource index* is **revaluated** whenever - * {@link sendData sendData()} is called. - * - * @return Resource index. - */ - getResource(): number; - /** - * Set resource index. - * - * Set *resource index* that indicates how much this {@link DistributedProcess process} is heavy. This - * *resource index* can be **revaulated**. - * - * Note that, initial and average *resource index* of {@link DistributedProcess} objects are ```1.0```. If the - * *resource index* is higher than other {@link DistributedProcess} objects, then this - * {@link DistributedProcess} will be ordered to handle more processes than other {@link DistributedProcess} - * objects. Otherwise, the *resource index* is lower than others, of course, less processes will be requested. - * - * Unlike {@link enforceResource}, configuring *resource index* by this {@link setResource} allows the - * **revaluation**. This **revaluation** prevents wrong valuation from user. For example, you *mis-valuated* the - * *resource index*. The {@link DistributedProcess process} is much heavier than any other, but you estimated it - * to the lightest one. It looks like a terrible case that causes - * {@link DistributedSystemArray entire distributed processing system} to be slower, however, don't mind. The - * {@link DistributedProcess process} will the direct to the *propriate resource index* eventually with the - * **revaluation**. - * - * - The **revaluation** is caused by the {@link sendData sendData()} method. - * - * @param val New resource index, but can be revaluated. - */ - setResource(val: number): void; - /** - * Enforce resource index. - * - * Enforce *resource index* that indicates how much heavy the {@link DistributedProcess process is}. The - * *resource index* will be fixed, never be **revaluated**. - * - * Note that, initial and average *resource index* of {@link DistributedProcess} objects are ```1.0```. If the - * *resource index* is higher than other {@link DistributedProcess} objects, then this - * {@link DistributedProcess} will be ordered to handle more processes than other {@link DistributedProcess} - * objects. Otherwise, the *resource index* is lower than others, of course, less processes will be requested. - * - * The difference between {@link setResource} and this {@link enforceResource} is allowing **revaluation** or not. - * This {@link enforceResource} does not allow the **revaluation**. The *resource index* is clearly fixed and - * never be changed by the **revaluation**. But you've to keep in mind that, you can't avoid the **mis-valuation** - * with this {@link enforceResource}. - * - * For example, there's a {@link DistributedProcess process} much heavier than any other, but you - * **mis-estimated** it to the lightest. In that case, there's no way. The - * {@link DistributedSystemArray entire distributed processing system} will be slower by the **mis-valuation**. - * By the reason, using {@link enforceResource}, it's recommended only when you can clearly certain the - * *resource index*. If you can't certain the *resource index* but want to recommend, then use {@link setResource} - * instead. - * - * @param val New resource index to be fixed. - */ - enforceResource(val: number): void; - /** - * @hidden - */ - private compute_average_elapsed_time(); - /** - * @inheritdoc - */ - abstract replyData(invoke: protocol.Invoke): void; - /** - * Send an {@link Invoke} message. - * - * Sends an {@link Invoke} message requesting a **distributed process**. The {@link Invoke} message will be sent - * to the most idle {@link DistributedSystem} object, which represents a slave system, and the most idle - * {@link DistributedSystem} object will be returned. - * - * When the **distributed process** has completed, then the {@link DistributedSystemArray} object will revaluate - * {@link getResource resource index} and {@link DistributedSystem.getPerformance performance index} of this - * {@link DistributedSystem} and the most idle {@link DistributedSystem} objects basis on the execution time. - * - * @param invoke An {@link Invoke} message requesting distributed process. - * @return The most idle {@link DistributedSystem} object who may send the {@link Invoke} message. - */ - sendData(invoke: protocol.Invoke): DistributedSystem; - /** - * Send an {@link Invoke} message. - * - * Sends an {@link Invoke} message requesting a **distributed process**. The {@link Invoke} message will be sent - * to the most idle {@link DistributedSystem} object, which represents a slave system, and the most idle - * {@link DistributedSystem} object will be returned. - * - * When the **distributed process** has completed, then the {@link DistributedSystemArray} object will revaluate - * {@link getResource resource index} and {@link DistributedSystem.getPerformance performance index} of this - * {@link DistributedSystem} and the most idle {@link DistributedSystem} objects basis on the execution time. - * - * @param invoke An {@link Invoke} message requesting distributed process. - * @param weight Weight of resource which indicates how heavy this {@link Invoke} message is. Default is 1. - * - * @return The most idle {@link DistributedSystem} object who may send the {@link Invoke} message. - */ - sendData(invoke: protocol.Invoke, weight: number): DistributedSystem; - /** - * @hidden - */ - private complete_history(history); - /** - * @inheritdoc - */ - TAG(): string; - } -} -declare namespace samchon.templates.external { - /** - * An external system driver. - * - * The {@link ExternalSystem} class represents an external system, connected and interact with this system. - * {@link ExternalSystem} takes full charge of network communication with the remote, external system have connected. - * Replied {@link Invoke} messages from the external system is shifted to and processed in, children elements of this - * class, {@link ExternalSystemRole} objects. - * - * - * - * - * - * #### Bridge & Proxy Pattern - * The {@link ExternalSystem} class can be a *bridge* for *logical proxy*. In framework within user, - * which {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Bridge Pattern* and *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - abstract class ExternalSystem extends protocol.EntityDequeCollection implements protocol.IProtocol { - /** - * The name represents external system have connected. - */ - protected name: string; - /** - * @hidden - */ - private system_array_; - /** - * @hidden - */ - private communicator_; - /** - * Construct from parent {@link ExternalSystemArray}. - * - * @param systemArray The parent {@link ExternalSystemArray} object. - */ - constructor(systemArray: ExternalSystemArray); - /** - * Constrct from parent {@link ExternalSystemArray} and communicator. - * - * @param systemArray The parent {@link ExternalSystemArray} object. - * @param communicator Communicator with the remote, external system. - */ - constructor(systemArray: ExternalSystemArray, communicator: protocol.IClientDriver); - /** - * Default Destructor. - * - * This {@link destructor destructor()} method is called when the {@link ExternalSystem} object is destructed and - * the {@link ExternalSystem} object is destructed when connection with the remote system is closed or this - * {@link ExternalSystem} object is {@link ExternalSystemArray.erase erased} from its parent - * {@link ExternalSystemArray} object. - * - * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically - * by those *destruction* cases. Also, if your derived {@link ExternalSystem} class has something to do on the - * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. - * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. - * - * ```typescript - * class SomeSystem extends templates.external.ExternalSystem - * { - * protected destructor(): void - * { - * // DO SOMETHING - * this.do_something(); - * - * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS - * super.destructor(); - * } - * } - * ``` - */ - protected destructor(): void; - /** - * @hidden - */ - private handle_close(); - /** - * Get parent {@link ExternalSystemArray} object. - */ - getSystemArray(): ExternalSystemArray; - /** - * Get parent {@link ExternalSystemArray} object. - */ - getSystemArray>(): SystemArray; - /** - * Identifier of {@link ExternalSystem} is its {@link name}. - * - * @return name. - */ - key(): string; - /** - * Get {@link name}. - */ - getName(): string; - /** - * @hidden - */ - /** - * @hidden - */ - protected communicator: protocol.ICommunicator; - /** - * Close connection. - */ - close(): void; - /** - * Send {@link Invoke} message to external system. - * - * @param invoke An {@link Invoke} message to send. - */ - sendData(invoke: protocol.Invoke): void; - /** - * Handle an {@Invoke} message has received. - * - * @param invoke An {@link Invoke} message have received. - */ - replyData(invoke: protocol.Invoke): void; - /** - * Tag name of the {@link ExternalSystem} in {@link XML}. - * - * @return *system*. - */ - TAG(): string; - /** - * Tag name of {@link ExternalSystemRole children elements} belonged to the {@link ExternalSystem} in {@link XML}. - * - * @return *role*. - */ - CHILD_TAG(): string; - } -} -declare namespace samchon.templates.parallel { - /** - * A driver for a parallel slave system. - * - * The {@link ParallelSystem} is an abstract class represents a **slave** system in *Parallel Processing System*, - * connected with this **master** system. This {@link ParallelSystem} takes full charge of network communication with - * the remote, parallel **slave** system has connected. - * - * When a *parallel process* is requested (by {@link ParallelSystemArray.sendSegmentData} or - * {@link ParallelSystemArray.sendPieceData}), the number of pieces to be allocated to a {@link ParallelSystem} is - * turn on its {@link getPerformance performance index}. Higher {@link getPerformance performance index}, then - * more pieces are requested. The {@link getPerformance performance index} is revaluated whenever a *parallel process* - * has completed, basic on the execution time and number of pieces. You can sugguest or enforce the - * {@link getPerformance performance index} with {@link setPerformance} or {@link enforcePerformance}. - * - * - * - * - * - * #### Bridge & Proxy Pattern - * This class {@link ParallelSystem} is derived from the {@link ExternalSystem} class. Thus, you can take advantage - * of the *Bridge & Proxy Pattern* in this {@link ParallelSystem} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Bridge & Proxy Pattern*: - * - * The {@link ExternalSystem} class can be a *bridge* for *logical proxy*. In framework within user, - * which {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Bridge Pattern* and *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelSystem extends external.ExternalSystem { - /** - * @hidden - */ - private progress_list_; - /** - * @hidden - */ - private history_list_; - /** - * @hidden - */ - private exclude_; - /** - * @hidden - */ - private performance; - /** - * @hidden - */ - private enforced_; - /** - * Construct from parent {@link ParallelSystemArray}. - * - * @param systemArray The parent {@link ParallelSystemArray} object. - */ - constructor(systemArray: ParallelSystemArray); - /** - * Construct from parent {@link ParallelSystemArray} and communicator. - * - * @param systemArray The parent {@link ParallelSystemArray} object. - * @param communicator A communicator communicates with remote, the external system. - */ - constructor(systemArray: ParallelSystemArray, communicator: protocol.IClientDriver); - /** - * Default Destructor. - * - * This {@link destructor destructor()} method is called when the {@link ParallelSystem} object is destructed and - * the {@link ParallelSystem} object is destructed when connection with the remote system is closed or this - * {@link ParallelSystem} object is {@link ParallelSystemArray.erase erased} from its parent - * {@link ParallelSystemArray} object. - * - * You may think if there're some *parallel processes* have requested but not completed yet, then it would be a - * critical problem because the *parallel processes* will not complete forever. Do not worry. The critical problem - * does not happen. After the destruction, the remained *parallel processes* will be shifted to and proceeded in - * other {@link ParallelSystem} objects. - * - * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically - * by those *destruction* cases. Also, if your derived {@link ParallelSystem} class has something to do on the - * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. - * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. - * - * ```typescript - * class SomeSystem extends protocol.external.ExternalSystem - * { - * protected destructor(): void - * { - * // DO SOMETHING - * this.do_something(); - * - * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS - * super.destructor(); - * } - * } - * ``` - */ - protected destructor(): void; - /** - * Get manager of this object. - * - * @return The parent {@link ParallelSystemArray} object. - */ - getSystemArray(): ParallelSystemArray; - /** - * Get manager of this object. - * - * @return The parent {@link ParallelSystemArray} object. - */ - getSystemArray>(): SystemArray; - /** - * Get performance index. - * - * Get *performance index* that indicates how much fast the remote system is. - * - * If this {@link ParallelSystem parallel system} does not have any {@link Invoke} message had handled, then the - * *performance index* will be ```1.0```, which means default and average value between all {@link ParallelSystem} - * instances (that are belonged to a same {@link ParallelSystemArray} object). - * - * You can specify this *performance index* by yourself but notice that, if the *performance index* is higher - * than other {@link ParallelSystem} objects, then this {@link ParallelSystem parallel system} will be ordered to - * handle more processes than other {@link ParallelSystem} objects. Otherwise, the *performance index* is lower - * than others, of course, less processes will be delivered. - * - * - {@link setPerformance setPerformance()} - * - {@link enforcePerformance enforcePerformance()} - * - * Unless {@link enforcePerformance enforcePerformance()} is called, This *performance index* is **revaluated** - * whenever user calls one of them below. - * - * - {@link ParallelSystemArray.sendSegmentData ParallelSystemArray.sendSegmentData()} - * - {@link ParallelSystemArray.sendPieceData ParallelSystemArray.sendPieceData()} - * - {@link DistributedProcess.sendData DistributedProcess.sendData()}. - * - * @return Performance index. - */ - getPerformance(): number; - /** - * Set performance index. - * - * Set *performance index* that indicates how much fast the remote system is. This *performance index* can be - * **revaulated**. - * - * Note that, initial and average *performance index* of {@link ParallelSystem} objects are ```1.0```. If the - * *performance index* is higher than other {@link ParallelSystem} objects, then this {@link ParallelSystem} will - * be ordered to handle more processes than other {@link ParallelSystem} objects. Otherwise, the - * *performance index* is lower than others, of course, less processes will be delivered. - * - * Unlike {@link enforcePerformance}, configuring *performance index* by this {@link setPerformance} allows - * **revaluation**. This **revaluation** prevents wrong valuation from user. For example, you *mis-valuated* the - * *performance index*. The remote system is much faster than any other, but you estimated it to the slowest one. - * It looks like a terrible case that causes {@link ParallelSystemArray entire parallel systems} to be slower, - * however, don't mind. The system will direct to the *propriate performance index* eventually with the - * **revaluation** by following methods. - * - * - {@link ParallelSystemArray.sendSegmentData ParallelSystemArray.sendSegmentData()} - * - {@link ParallelSystemArray.sendPieceData ParallelSystemArray.sendPieceData()} - * - {@link DistributedProcess.sendData DistributedProcess.sendData()}. - * - * @param val New performance index, but can be revaluated. - */ - setPerformance(val: number): void; - /** - * Enforce performance index. - * - * Enforce *performance index* that indicates how much fast the remote system is. The *performance index* will be - * fixed, never be **revaluated**. - * - * Note that, initial and average *performance index* of {@link ParallelSystem} objects are ```1.0```. If the - * *performance index* is higher than other {@link ParallelSystem} objects, then this {@link ParallelSystem} will - * be ordered to handle more processes than other {@link ParallelSystem} objects. Otherwise, the - * *performance index* is lower than others, of course, less processes will be delivered. - * - * The difference between {@link setPerformance} and this {@link enforcePerformance} is allowing **revaluation** - * or not. This {@link enforcePerformance} does not allow the **revaluation**. The *performance index* is clearly - * fixed and never be changed by the **revaluation**. But you've to keep in mind that, you can't avoid the - * **mis-valuation** with this {@link enforcePerformance}. - * - * For example, there's a remote system much faster than any other, but you **mis-estimated** it to the slowest. - * In that case, there's no way. The {@link ParallelSystemArray entire parallel systems} will be slower by the - * **mis-valuation**. By the reason, using {@link enforcePerformance}, it's recommended only when you can clearly - * certain the *performance index*. If you can't certain the *performance index* but want to recommend, then use - * {@link setPerformance} instead. - * - * @param val New performance index to be fixed. - */ - enforcePerformance(val: number): void; - /** - * @hidden - */ - private send_piece_data(invoke, first, last); - /** - * @hidden - */ - private _replyData(invoke); - /** - * @hidden - */ - protected _Report_history(xml: library.XML): void; - /** - * @hidden - */ - protected _Send_back_history(invoke: protocol.Invoke, history: protocol.InvokeHistory): void; - } -} -declare namespace samchon.templates.distributed { - /** - * A driver for a distributed slave system. - * - * The {@link DistributedSystem} is an abstract class represents a **slave** system in *Distributed Processing System*, - * connected with this **master** system. This {@link DistributedSystem} takes full charge of network communication - * with the remote, distributed **slave** system has connected. - * - * This {@link DistributedSystem} has a {@link getPerformance performance index} that indicates how much the **slave** - * system is fast. The {@link getPerformance performance index} is referenced and revaluated whenever those methods - * are called: - * - * - Requesting a *parallel process* - * - {@link DistributedSystemArray.sendSegmentData} - * - {@link DistributedSystemArray.sendPieceData} - * - Requesting a *distributed process*: {@link DistributedProcess.sendData} - * - * Note that, this {@link DistributedSystem} class derived from the {@link ExternalSystem} class. Thus, this - * {@link DistributedSystem} can also have children {@link ExternalSystemRole} objects exclusively. However, the - * children {@link ExternalSystemRole roles} objects are different with the {@link DistributedProcess}. The - * domestic {@link ExternalSystemRole roles} are belonged to only a specific {@link DistributedSystem} object. - * Otherwise, the {@link DistributedProcess} objects are belonged to a {@link DistributedSystemArray} object. - * Furthermore, the relationship between this {@link DistributedSystem} and {@link DistributedProcess} classes are - * **M: N Associative**. - * - * Articles | {@link DistributedProcess} | {@link ExternalSystemRole} - * -------------|--------------------------------|---------------------------- - * Belonged to | {@link DistributedSystemArray} | {@link DistributedSystem} - * Relationship | M: N Associative | 1: N Composite - * Ownership | References | Exclusive possession - * - * - * - * - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedSystem extends parallel.ParallelSystem { - /** - * Construct from parent {@link DistributedSystemArray}. - * - * @param systemArray The parent {@link DistributedSystemArray} object. - */ - constructor(systemArray: DistributedSystemArray); - /** - * Constrct from parent {@link DistributedSystemArray} and communicator. - * - * @param systemArray The parent {@link DistributedSystemArray} object. - * @param communicator A communicator communicates with remote, the external system. - */ - constructor(systemArray: DistributedSystemArray, communicator: protocol.IClientDriver); - /** - * Factory method creating a {@link ExternalSystemRole child} object. - * - * In {@link distributed} module, the process class {@link DistributedProcess} is not belonged to a specific - * {@link DistributedSystem} object. It only belongs to a {@link DistributedSystemArray} object and has a - * **M: N Associative Relationship** between this {@link DistributedSystem} class. - * - * By that reason, it's the normal case that the {@link DistributedSystem} object does not have any children - * {@link ExternalSystemRole} object. Thus, default {@link createChild} returns ```null```. - * - * However, if you want a {@link DistributedSystem} to have its own domestic {@link ExternalSystemRole} objects - * without reference to the {@link DistributedProcess} objects, it is possible. Creates and returns the - * domestic {@link ExternalSystemRole} object. - * - * @param xml {@link XML} represents the {@link ExternalSystemRole child} object. - * @return A newly created {@link ExternalSystemRole} object or ```null```. - */ - createChild(xml: library.XML): external.ExternalSystemRole; - /** - * Get manager of this object. - * - * @return The parent {@link DistributedSystemArray} object. - */ - getSystemArray(): DistributedSystemArray; - /** - * Get manager of this object. - * - * @return The parent {@link DistributedSystemArray} object. - */ - getSystemArray>(): SystemArray; - /** - * @hidden - */ - private compute_average_elapsed_time(); - /** - * @inheritdoc - */ - replyData(invoke: protocol.Invoke): void; - /** - * @hidden - */ - protected _Report_history(xml: library.XML): void; - /** - * @hidden - */ - protected _Send_back_history(invoke: protocol.Invoke, history: protocol.InvokeHistory): void; - } -} -declare namespace samchon.templates.distributed { - /** - * An interface for a distributed slave server driver. - * - * The easiest way to defining a driver for distributed **slave** server is extending {@link DistributedServer} class. - * However, if you've to interact with a prallel **slave** system who can be both server and client, them make a class - * (let's name it **BaseSystem**) extending the {@link DistributedServer} class. At next, make a new class (now, I name - * it **BaseServer**) extending the **BaseSystem** and implements this interface {@link IParallelServer}. Define the - * **BaseServer** following those codes on below: - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - interface IDistributedServer extends DistributedSystem { - /** - * Connect to external server. - */ - connect(): void; - } - /** - * A driver for distributed slave server. - * - * The {@link DistributedServer} is an abstract class, derived from the {@link DistributedSystem} class, connecting to - * remote, distributed **slave** server. Extends this {@link DistributedServer} class and overrides the - * {@link createServerConnector createServerConnector()} method following which protocol the **slave** server uses. - * - * #### [Inheritdoc] {@link DistributedSystem} - * The {@link DistributedSystem} is an abstract class represents a **slave** system in *Distributed Processing System*, - * connected with this **master** system. This {@link DistributedSystem} takes full charge of network communication - * with the remote, distributed **slave** system has connected. - * - * This {@link DistributedSystem} has a {@link getPerformance performance index} that indicates how much the **slave** - * system is fast. The {@link getPerformance performance index} is referenced and revaluated whenever those methods - * are called: - * - * - Requesting a *parallel process* - * - {@link DistributedSystemArray.sendSegmentData} - * - {@link DistributedSystemArray.sendPieceData} - * - Requesting a *distributed process*: {@link DistributedProcess.sendData} - * - * Note that, this {@link DistributedSystem} class derived from the {@link ExternalSystem} class. Thus, this - * {@link DistributedSystem} can also have children {@link ExternalSystemRole} objects exclusively. However, the - * children {@link ExternalSystemRole roles} objects are different with the {@link DistributedProcess}. The - * domestic {@link ExternalSystemRole roles} are belonged to only a specific {@link DistributedSystem} object. - * Otherwise, the {@link DistributedProcess} objects are belonged to a {@link DistributedSystemArray} object. - * Furthermore, the relationship between this {@link DistributedSystem} and {@link DistributedProcess} classes are - * **M: N Associative**. - * - * Articles | {@link DistributedProcess} | {@link ExternalSystemRole} - * -------------|--------------------------------|---------------------------- - * Belonged to | {@link DistributedSystemArray} | {@link DistributedSystem} - * Relationship | M: N Associative | 1: N Composite - * Ownership | References | Exclusive possession - * - * - * - * - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedServer extends DistributedSystem implements external.IExternalServer { - /** - * IP address of target external system to connect. - */ - protected ip: string; - /** - * Port number of target external system to connect. - */ - protected port: number; - /** - * Construct from parent {@link DistributedSystemArray}. - * - * @param systemArray The parent {@link DistributedSystemArray} object. - */ - constructor(systemArray: DistributedSystemArray); - /** - * Factory method creating {@link IServerConnector} object. - * - * The {@link createServerConnector createServerConnector()} is an abstract method creating - * {@link IServerConnector} object. Overrides and returns one of them, considering which protocol the slave server - * follows: - * - * - {@link ServerConnector} - * - {@link WebServerConnector} - * - {@link DedicatedWorkerServerConnector} - * - {@link SharedWorkerServerConnector} - * - * @return A newly created {@link IServerConnector} object. - */ - protected abstract createServerConnector(): protocol.IServerConnector; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.distributed { - /** - * Master of Distributed Processing System, a client connecting to slave servers. - * - * The {@link DistributedServerArray} is an abstract class, derived from the {@link DistributedSystemArray} class, - * connecting to {@link IDistributedServer distributed servers}. - * - * Extends this {@link DistributedServerArray} and overrides {@link createChild createChild()} method creating child - * {@link IDistributedServer} object. After the extending and overriding, construct children {@link IDistributedServer} - * objects and call the {@link connect connect()} method. - * - * #### [Inherited] {@link DistributedSystemArray} - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedServerArray extends DistributedSystemArray implements external.IExternalServerArray { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.distributed { - /** - * Mediator of Distributed Processing System, a client connecting to slave servers. - * - * The {@link DistributedServerArrayMediator} is an abstract class, derived from {@link DistributedSystemArrayMediator} - * class, connecting to {@link IDistributedServer distributed servers}. - * - * Extends this {@link DistributedServerArrayMediator} and overrides {@link createChild createChild()} method creating - * child {@link IDistributedServer} object. After the extending and overriding, construct children - * {@link IDistributedServer} objects and call the {@link connect connect()} method. - * - * #### [Inherited] {@link DistributedSystemArrayMediator} - * The {@link DistributedSystemArrayMediator} class be a master for its slave systems, and be a slave to its master - * system at the same time. This {@link DistributedSystemArrayMediator} be a master system, containing and managing - * {@link DistributedSystem} objects, which represent distributed slave systems, by extending - * {@link DistributedSystemArray} class. Also, be a slave system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a slave, you can specify this {@link DistributedSystemArrayMediator} to be a client slave connecting to master - * server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link DistributedSystemArray} - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedServerArrayMediator extends DistributedSystemArrayMediator implements external.IExternalServerArray { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.distributed { - /** - * Master of Distributed Processing System, be a server and client at the same time. - * - * The {@link DistributedServerClientArray} is an abstract class, derived from the {@link DistributedSystemArray} - * class, opening a server accepting {@link Distributed distributed clients} and being a client connecting to - * {@link IDistributedServer distributed servers} at the same time. - * - * Extends this {@link DistributedServerClientArray} and overrides below methods. After the overridings, open server - * with {@link open open()} method and connect to {@link IDistributedServer distributed servers} through the - * {@link connect connect()} method. - * - * - {@link createServerBase createServerBase()} - * - {@link createExternalClient createExternalClient()} - * - {@link createExternalServer createExternalServer()} - * - * #### [Inherited] {@link DistributedSystemArray} - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedServerClientArray extends DistributedClientArray implements external.IExternalServerClientArray { - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method of a child Entity. - * - * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. - * - * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. - * @return A new child Entity via {@link createExternalServer createExternalServer()}. - */ - createChild(xml: library.XML): System; - /** - * Factory method creating an {@link IDistributedServer} object. - * - * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. - * @return A newly created {@link IDistributedServer} object. - */ - protected abstract createExternalServer(xml: library.XML): System; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.distributed { - /** - * Mediator of Distributed Processing System, be a server and client at the same time as a **master**. - * - * The {@link DistributedServerClientArrayMediator} is an abstract class, derived from the - * {@link DistributedSystemArrayMediator} class, opening a server accepting {@link DistributedSystem distributed - * clients} and being a client connecting to {@link IDistributedServer distributed servers} at the same time. - * - * Extends this {@link DistributedServerClientArrayMediator} and overrides below methods. After the overridings, open - * server with {@link open open()} method and connect to {@link IDistributedServer distributed servers} through the - * {@link connect connect()} method. - * - * - {@link createServerBase createServerBase()} - * - {@link createExternalClient createExternalClient()} - * - {@link createExternalServer createExternalServer()} - * - * #### [Inherited] {@link DistributedSystemArrayMediator} - * The {@link DistributedSystemArrayMediator} class be a master for its slave systems, and be a slave to its master - * system at the same time. This {@link DistributedSystemArrayMediator} be a master system, containing and managing - * {@link DistributedSystem} objects, which represent distributed slave systems, by extending - * {@link DistributedSystemArray} class. Also, be a slave system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a slave, you can specify this {@link DistributedSystemArrayMediator} to be a client slave connecting to master - * server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link DistributedSystemArray} - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedServerClientArrayMediator extends DistributedClientArrayMediator implements external.IExternalServerClientArray { - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method of a child Entity. - * - * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. - * - * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. - * @return A new child Entity via {@link createExternalServer createExternalServer()}. - */ - createChild(xml: library.XML): System; - /** - * Factory method creating an {@link IDistributedServer} object. - * - * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. - * @return A newly created {@link IDistributedServer} object. - */ - protected abstract createExternalServer(xml: library.XML): System; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.distributed { - /** - * History of an {@link Invoke} message. - * - * The {@link PRInvokeHistory} is a class archiving history log of an {@link Invoke} message which requests the - * *distributed process*, created whenever {@link DistributedProcess.sendData} is called. - * - * When the *distributed process* has completed, then {@link complete complete()} is called and the *elapsed time* is - * determined. The elapsed time is utilized for computation of {@link DistributedSystem.getPerformance performance index} - * and {@link DistributedProcess.getResource resource index} of related objects. - * - * - * - * - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class DSInvokeHistory extends protocol.InvokeHistory { - /** - * @hidden - */ - private system_; - /** - * @hidden - */ - private process_; - /** - * @hidden - */ - private weight_; - /** - * Construct from a DistributedSystem. - * - * @param system The {@link DistributedSystem} object who sent the {@link Invoke} message. - */ - constructor(system: DistributedSystem); - /** - * Initilizer Constructor. - * - * @param system The {@link DistributedSystem} object who sent the {@link Invoke} message. - * @param process The {@link DistributedProcess} object who sent the {@link Invoke} message. - * @param invoke An {@link Invoke} message requesting the *distributed process*. - * @param weight Weight of resource which indicates how heavy this {@link Invoke} message is. - */ - constructor(system: DistributedSystem, process: DistributedProcess, invoke: protocol.Invoke, weight: number); - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * Get the related {@link DistributedSystem} object. - */ - getSystem(): DistributedSystem; - /** - * Get the related {@link DistributedProcess} object. - */ - getProcess(): DistributedProcess; - /** - * Get weight. - * - * Gets weight of resource which indicates how heavy this {@link Invoke} message is. Default is 1. - */ - getWeight(): number; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.templates.external { - /** - * An interface for an {@link ExternalSystemArray} accepts {@link ExternalSystem external clients} as a - * {@link IServer server}. - * - * The easiest way to defining an {@link ExternalSystemArray} who opens server and accepts - * {@link ExternalSystem external clients} is to extending one of below, who are derived from this interface - * {@link IExternalClientArray}. However, if you can't specify an {@link ExternalSystemArray} to be whether server or - * client, then make a class (let's name it as **BaseSystemArray**) extending {@link ExternalSystemArray} and make - * a new class (now, I name it **BaseClientArray**) extending **BaseSystemArray** and implementing this - * interface {@link IExternalClientArray}. Define the **BaseClientArray** following those codes on below: - * - * - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - interface IExternalClientArray extends ExternalSystemArray, protocol.IServer { - } - /** - * An array and manager of {@link ExternalSystem external clients} as a server. - * - * The {@link ExternalClientArray} is an abstract class, derived from the {@link ExternalSystemArray} class, opening - * a server accepting {@link ExternalSystem external clients}. - * - * Extends this {@link ExternalClientArray}, overrides {@link createServerBase createServerBase()} to determine which - * protocol to follow and {@link createExternalClient createExternalClient()} creating child {@link ExternalSystem} - * object. After the extending and overridings, open this server using the {@link open open()} method. - * - * #### [Inherited] {@link ExternalSystemArray} - * The {@link ExternalSystemArray} is an abstract class containing and managing external system drivers, - * {@link ExternalSystem} objects. Within framewokr of network, {@link ExternalSystemArray} represents your system - * and children {@link ExternalSystem} objects represent remote, external systems connected with your system. - * With this {@link ExternalSystemArray}, you can manage multiple external systems as a group. - * - * - * - * - * - * #### Proxy Pattern - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - abstract class ExternalClientArray extends ExternalSystemArray implements IExternalClientArray { - /** - * @hidden - */ - private server_base_; - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method creating {@link IServerBase} object. - * - * This method {@link createServerBase createServerBase()} determines which templates is used in this server, - * {@link ExternalClientArray}. If the templates is determined, then {@link ExternalSystem external clients} who - * may connect to {@link ExternalClientArray this server} must follow the specified templates. - * - * Creates and returns one of them: - * - * - {@link ServerBase} - * - {@link WebServerBase} - * - {@link SharedWorkerServerBase} - * - * @return A new {@link IServerBase} object. - */ - protected abstract createServerBase(): protocol.IServerBase; - /** - * Add a newly connected remote client. - * - * When a {@link IClientDriver remote client} connects to this *server* {@link ExternalClientArray} object, - * then this {@link ExternalClientArray} creates a child {@link ExternalSystem external client} object through - * the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. - * - * @param driver A communicator for external client. - */ - addClient(driver: protocol.IClientDriver): void; - /** - * (Deprecated) Factory method creating child object. - * - * The method {@link createChild createChild()} is deprecated. Don't use and override this. - * - * Note that, the {@link ExternalClientArray} is a server accepting {@link ExternalSystem external clients}. - * There's no way to creating the {@link ExternalSystem external clients} in advance before opening the server. - * - * @param xml An {@link XML} object represents the child {@link ExternalSystem} object. - * @return null - */ - createChild(xml: library.XML): T; - /** - * Factory method creating a child {@link ExternalSystem} object. - * - * @param driver A communicator with connected client. - * @return A newly created {@link ExternalSystem} object. - */ - protected abstract createExternalClient(driver: protocol.IClientDriver): T; - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - } -} -declare namespace samchon.templates.external { - /** - * An interface for an external server driver. - * - * The easiest way to defining an external server driver is to extending one of below, who are derived from this - * interface {@link IExternalServer}. However, if you've to interact with an external system who can be both server - * and client, then make a class (let's name it as **BaseSystem**) extending {@link ExternalSystem} and make a - * new class (now, I name it **BaseServer**) extending **BaseSystem** and implementing this interface - * {@link IExternalServer}. Define the **BaseServer** following those codes on below: - * - * - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - interface IExternalServer extends ExternalSystem { - /** - * Connect to external server. - */ - connect(): void; - } - /** - * An external server driver. - * - * The {@link ExternalServer} is an abstract class, derived from the {@link ExternalSystem} class, connecting to - * remote, external server. Extends this {@link ExternalServer} class and overrides the - * {@link createServerConnector createServerConnector()} method following which protocol the external server uses. - * - * #### [Inherited] {@link ExternalSystem} - * The {@link ExternalSystem} class represents an external system, connected and interact with this system. - * {@link ExternalSystem} takes full charge of network communication with the remote, external system have connected. - * Replied {@link Invoke} messages from the external system is shifted to and processed in, children elements of this - * class, {@link ExternalSystemRole} objects. - * - * - * - * - * - * #### Bridge & Proxy Pattern - * The {@link ExternalSystem} class can be a *bridge* for *logical proxy*. In framework within user, - * which {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Bridge Pattern* and *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - abstract class ExternalServer extends ExternalSystem implements IExternalServer { - /** - * IP address of target external system to connect. - */ - protected ip: string; - /** - * Port number of target external system to connect. - */ - protected port: number; - /** - * Construct from parent {@link ExternalSystemArray}. - * - * @param systemArray The parent {@link ExternalSystemArray} object. - */ - constructor(systemArray: ExternalSystemArray); - /** - * Factory method creating {@link IServerConnector} object. - * - * The {@link createServerConnector createServerConnector()} is an abstract method creating - * {@link IServerConnector} object. Overrides and returns one of them, considering which templates the external - * system follows: - * - * - {@link ServerConnector} - * - {@link WebServerConnector} - * - {@link DedicatedWorkerServerConnector} - * - {@link SharedWorkerServerConnector} - * - * @return A newly created {@link IServerConnector} object. - */ - protected abstract createServerConnector(): protocol.IServerConnector; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.external { - /** - * An interface for an {@link ExternalSystemArray} connects to {@link IExternalServer external servers} as a - * **client**. - * - * The easiest way to defining an {@link ExternalSystemArray} who connects to - * {@link IExternalServer external servers} is to extending one of below, who are derived from this interface - * {@link IExternalServerArray}. However, if you can't specify an {@link ExternalSystemArray} to be whether server or - * client, then make a class (let's name it as **BaseSystemArray**) extending {@link ExternalSystemArray} and make - * a new class (now, I name it **BaseServerArray**) extending **BaseSystemArray** and implementing this - * interface {@link IExternalServerArray}. Define the **BaseServerArray** following those codes on below: - * - * - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - interface IExternalServerArray extends ExternalSystemArray { - /** - * Connect to {@link IExternalServer external servers}. - * - * This method calls children elements' method {@link IExternalServer.connect} gradually. - */ - connect(): void; - } - /** - * An array and manager of {@link IExternalServer external servers}. - * - * The {@link ExternalServerArray} is an abstract class, derived from the {@link ExternalSystemArray} class, - * connecting to {@link IExternalServer external servers}. - * - * Extends this {@link ExternalServerArray} and overrides {@link createChild createChild()} method creating child - * {@link IExternalServer} object. After the extending and overriding, construct children {@link IExternalServer} - * objects and call the {@link connect connect()} method. - * - * #### [Inherited] {@link ExternalSystemArray} - * The {@link ExternalSystemArray} is an abstract class containing and managing external system drivers, - * {@link ExternalSystem} objects. Within framewokr of network, {@link ExternalSystemArray} represents your system - * and children {@link ExternalSystem} objects represent remote, external systems connected with your system. - * With this {@link ExternalSystemArray}, you can manage multiple external systems as a group. - * - * - * - * - * - * #### Proxy Pattern - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - abstract class ExternalServerArray extends ExternalSystemArray implements IExternalServerArray { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.external { - /** - * An interface for an {@link ExternalSystemArray} accepts {@link ExternalSystem external clients} as a - * {@link IServer server} and connects to {@link IExternalServer} as **client**, at the same time. - * - * The easiest way to defining an {@link IExternalServerClientArray} who opens server, accepts - * {@link ExternalSystem external clients} and connects to {@link IExternalServer external servers} is to extending - * one of below, who are derived from this interface {@link IExternalServerClientArray}. However, if you can't - * specify an {@link ExternalSystemArray} to be whether server or client or even can both them, then make a class - * (let's name it as **BaseSystemArray**) extending {@link ExternalSystemArray} and make a new class (now, I name - * it **BaseServerClientArray**) extending **BaseSystemArray** and implementing this interface - * {@link IExternalServerClientArray}. Define the **BaseServerClientArray** following those codes on below: - * - * - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - interface IExternalServerClientArray extends IExternalClientArray { - /** - * Connect to {@link IExternalServer external servers}. - * - * This method calls children elements' method {@link IExternalServer.connect} gradually. - */ - connect(): void; - } - /** - * An array and manager of {@link IExternalServer external servers} and {@link ExternalSystem external clients}. - * - * The {@link ExternalServerClientArray} is an abstract class, derived from the {@link ExternalSystemArray} class, - * opening a server accepting {@link ExternalSystem external clients} and being a client connecting to - * {@link IExternalServer external servers} at the same time. - * - * Extends this {@link ExternalServerClientArray} and overrides below methods. After the overridings, open server - * with {@link open open()} method and connect to {@link IExternalServer external servers} through the - * {@link connect connect()} method. - * - * - {@link createServerBase createServerBase()} - * - {@link createExternalClient createExternalClient()} - * - {@link createExternalServer createExternalServer()} - * - * #### [Inherited] {@link ExternalSystemArray} - * The {@link ExternalSystemArray} is an abstract class containing and managing external system drivers, - * {@link ExternalSystem} objects. Within framewokr of network, {@link ExternalSystemArray} represents your system - * and children {@link ExternalSystem} objects represent remote, external systems connected with your system. - * With this {@link ExternalSystemArray}, you can manage multiple external systems as a group. - * - * - * - * - * - * #### Proxy Pattern - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - abstract class ExternalServerClientArray extends ExternalClientArray implements IExternalServerClientArray { - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method of a child Entity. - * - * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. - * - * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. - * @return A new child Entity via {@link createExternalServer createExternalServer()}. - */ - createChild(xml: library.XML): T; - /** - * Factory method creating an {@link IExternalServer} object. - * - * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. - * @return A newly created {@link IExternalServer} object. - */ - protected abstract createExternalServer(xml: library.XML): T; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.external { - /** - * A role of an external system. - * - * The {@link ExternalSystemRole} class represents a role, *WHAT TO DO*. Extends the {@link ExternalSystemRole} class - * and overrides {@link replyData replyData()} to define the *WHAT TO DO*. And assign this {@link ExternalSystemRole} - * object to related {@link ExternalSystem} object. - * - * - * - * - * - * #### Proxy Pattern - * The {@link ExternalSystemRole} class can be an *logical proxy*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem} object, via {@link ExternalSystemArray.getRole ExternalSystemArray.getRole()}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - abstract class ExternalSystemRole extends protocol.Entity implements protocol.IProtocol { - /** - * @hidden - */ - private system; - /** - * A name, represents and identifies this {@link ExternalSystemRole role}. - * - * This {@link name} is an identifier represents this {@link ExternalSystemRole role}. This {@link name} is - * used in {@link ExternalSystemArray.getRole} and {@link ExternalSystem.get}, as a key elements. Thus, this - * {@link name} should be unique in an {@link ExternalSystemArray}. - */ - protected name: string; - /** - * Constructor from a system. - * - * @param system An external system containing this role. - */ - constructor(system: ExternalSystem); - /** - * Identifier of {@link ExternalSystemRole} is its {@link name}. - */ - key(): string; - /** - * Get grandparent {@link ExternalSystemArray}. - * - * Get the grandparent {@link ExternalSystemArray} object through this parent {@link ExternalSystem}, - * {@link ExternalSystem.getSystemArray ExternalSystem.getSystemArray()}. - * - * @return The grandparent {@link ExternalSystemArray} object. - */ - getSystemArray(): ExternalSystemArray; - /** - * Get parent {@link ExternalSystemRole} object. - */ - getSystem(): ExternalSystem; - /** - * Get name, who represents and identifies this role. - */ - getName(): string; - /** - * Send an {@link Invoke} message. - * - * Sends an {@link Invoke} message to remote system through the parent {@link ExternalSystem} object. - * - * @param invoke An {@link Invoke} message to send to the external system. - */ - sendData(invoke: protocol.Invoke): void; - /** - * Handle replied {@link Invoke} message. - * - * {@link ExternalSystemRole.replyData ExternalSystemRole.replyData()} is an abstract method handling a replied - * {@link Invoke message} gotten from remote system via parent {@link ExternalSystem} object. Overrides this - * method and defines the *WHAT TO DO* with the {@link Invoke message}. - * - * @param invoke An {@link Invoke} message received from the {@link ExternalSystem external system}. - */ - abstract replyData(invoke: protocol.Invoke): void; - /** - * Tag name of the {@link ExternalSytemRole} in {@link XML}. - * - * @return *role*. - */ - TAG(): string; - } -} -declare namespace samchon.templates.slave { - abstract class SlaveSystem implements protocol.IProtocol { - /** - * @hidden - */ - protected communicator_: protocol.ICommunicator; - /** - * Default Constructor. - */ - constructor(); - sendData(invoke: protocol.Invoke): void; - /** - * @hidden - */ - protected _replyData(invoke: protocol.Invoke): void; - replyData(invoke: protocol.Invoke): void; - } -} -declare namespace samchon.templates.parallel { - /** - * A mediator, the master driver. - * - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class MediatorSystem extends slave.SlaveSystem { - /** - * @hidden - */ - private system_array_; - /** - * @hidden - */ - private progress_list_; - /** - * Construct from parent {@link ParallelSystemArrayMediator} object. - * - * @param systemArray The parent {@link ParallelSystemArrayMediator} object. - */ - constructor(systemArray: ParallelSystemArrayMediator); - /** - * Construct from parent {@link DistributedSystemArrayMediator} object. - * - * @param systemArray The parent {@link DistributedSystemArrayMediator} object. - */ - constructor(systemArray: distributed.DistributedSystemArrayMediator); - /** - * Start interaction. - * - * The {@link start start()} is an abstract method starting interaction with the **master** system. If the - * **master** is a server, then connects to the **master**. Otherwise, the **master** is client, then this - * {@link MediatorSystem} object wil open a server accepting the **master**. - */ - abstract start(): void; - /** - * Get parent {@link ParallelSystemArrayMediator} or {@link DistributedSystemArrayMediator} object. - */ - getSystemArray(): ParallelSystemArrayMediator | distributed.DistributedSystemArrayMediator; - /** - * Get parent {@link ParallelSystemArrayMediator} object. - */ - getSystemArray>(): SystemArray; - /** - * Get parent {@link DistributedSystemArrayMediator} object. - */ - getSystemArray>(): SystemArray; - /** - * @hidden - */ - private complete_history(uid); - /** - * @hidden - */ - protected _replyData(invoke: protocol.Invoke): void; - /** - * @inheritdoc - */ - replyData(invoke: protocol.Invoke): void; - } -} -declare namespace samchon.templates.parallel { - /** - * A mediator server, driver for the master client. - * - * The {@link MediatorServer} is a class opening a server accepting the **master** client, following the protocol of - * Samchon Framework's own. - * - * #### [Inherited] {@link MediatorSystem} - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class MediatorServer extends MediatorSystem implements slave.ISlaveServer { - /** - * @hidden - */ - private server_base_; - /** - * @hidden - */ - private port; - /** - * Initializer Constructor. - * - * @param systemArray The parent {@link ParallelSystemArrayMediator} object. - * @param port Port number of server to open. - */ - constructor(systemArray: ParallelSystemArrayMediator, port: number); - /** - * Initializer Constructor. - * - * @param systemArray The parent {@link DistributedSystemArrayMediator} object. - * @param port Port number of server to open. - */ - constructor(systemArray: distributed.DistributedSystemArrayMediator, port: number); - /** - * Factory method creating {@link IServerBase} object. - * - * This method {@link createServerBase createServerBase()} determines which protocol is used in this server, - * {@link MediatorServer}. Note that, **slave** (this {@link MediatorServer} object) must follow the **master**'s - * protocol. - * - * Overrides and return one of them considering the which protocol to follow: - * - * - {@link ServerBase} - * - {@link WebServerBase} - * - {@link SharedWorkerServerBase} - */ - protected createServerBase(): protocol.IServerBase; - /** - * Add a newly connected remote client. - * - * {@link MediatorServer} represents a **slave** dedicating to its **master**. In that reason, the - * {@link MediatorServer} does not accept multiple **master** clients. It accepts only one. Thus, *listener* of - * the *communicator* is {@link MediatorSystem} object, itself. - * - * @param driver A communicator with remote client. - */ - addClient(driver: protocol.IClientDriver): void; - /** - * @inheritdoc - */ - start(): void; - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - } - /** - * A mediator server, driver for the master client. - * - * The {@link MediatorWebServer} is a class opening a server accepting the **master** client, following the - * web-socket protocol. - * - * #### [Inherited] {@link MediatorSystem} - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class MediatorWebServer extends MediatorServer { - /** - * @inheritdoc - */ - protected createServerBase(): protocol.IServerBase; - } - /** - * A mediator server, driver for the master client. - * - * The {@link MediatorDedicatedWorkerServer} is a class opening a server accepting the **master** client, following - * the DedicatedWorker's protocol. - * - * #### [Inherited] {@link MediatorSystem} - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class MediatorDedicatedWorkerServer extends MediatorServer { - /** - * @inheritdoc - */ - protected createServerBase(): protocol.IServerBase; - } - /** - * A mediator server, driver for the master client. - * - * The {@link MediatorSharedWorkerServer} is a class opening a server accepting the **master** client, following the - * SharedWorker's protocol. - * - * #### [Inherited] {@link MediatorSystem} - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class MediatorSharedWorkerServer extends MediatorServer { - /** - * @inheritdoc - */ - protected createServerBase(): protocol.IServerBase; - } -} -declare namespace samchon.templates.parallel { - /** - * A mediator client, driver for the master server. - * - * The {@link MediatorServer} is a class being a client connecting to the **master** server, following the protocol - * of Samchon Framework's own. - * - * #### [Inherited] {@link MediatorSystem} - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class MediatorClient extends MediatorSystem implements slave.ISlaveClient { - /** - * @hidden - */ - private ip; - /** - * @hidden - */ - private port; - /** - * Initializer Constructor. - * - * @param systemArray The parent {@link ParallelSystemArrayMediator} object. - * @param ip IP address to connect. - * @param port Port number to connect. - */ - constructor(systemArray: ParallelSystemArrayMediator, ip: string, port: number); - /** - * Initializer Constructor. - * - * @param systemArray The parent {@link DistributedSystemArrayMediator} object. - * @param ip IP address to connect. - * @param port Port number to connect. - */ - constructor(systemArray: distributed.DistributedSystemArrayMediator, ip: string, port: number); - /** - * Factory method creating {@link IServerConnector} object. - * - * The {@link createServerConnector createServerConnector()} is an abstract method creating - * {@link IServerConnector} object. Overrides and returns one of them, considering which protocol the **master** - * server follows: - * - * - {@link ServerConnector} - * - {@link WebServerConnector} - * - {@link SharedWorkerServerConnector} - * - * @return A newly created {@link IServerConnector} object. - */ - protected createServerConnector(): protocol.IServerConnector; - /** - * @inheritdoc - */ - start(): void; - /** - * @inheritdoc - */ - connect(): void; - } - /** - * A mediator client, driver for the master server. - * - * The {@link MediatorWebClient} is a class being a client connecting to the **master** server, following the - * web-socket protocol. - * - * #### [Inherited] {@link MediatorSystem} - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class MediatorWebClient extends MediatorClient { - /** - * @inheritdoc - */ - protected createServerConnector(): protocol.IServerConnector; - } - /** - * A mediator client, driver for the master server. - * - * The {@link MediatorSharedWorkerClient} is a class being a client connecting to the **master** server, following - * the SharedWorker's protocol. - * - * #### [Inherited] {@link MediatorSystem} - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class MediatorSharedWorkerClient extends MediatorClient { - /** - * @inheritdoc - */ - protected createServerConnector(): protocol.IServerConnector; - } -} -declare namespace samchon.templates.parallel { - /** - * Master of Parallel Processing System, a server accepting slave clients. - * - * The {@link ParallelClientArray} is an abstract class, derived from the {@link ParallelSystemArray} class, opening - * a server accepting {@link ParallelSystem parallel clients}. - * - * Extends this {@link ParallelClientArray}, overrides {@link createServerBase createServerBase()} to determine which - * protocol to follow and {@link createExternalClient createExternalClient()} creating child {@link ParallelSystem} - * object. After the extending and overridings, open this server using the {@link open open()} method. - * - * #### [Inherited] {@link ParallelSystemArray} - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to slave systems and the - * children {@link ParallelSystem} objects represent the remote slave systems, who is being requested the - * *parallel processes*. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelClientArray extends ParallelSystemArray implements external.IExternalClientArray { - /** - * @hidden - */ - private server_base_; - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method creating {@link IServerBase} object. - * - * This method {@link createServerBase createServerBase()} determines which protocol is used in this server, - * {@link ExternalClientArray}. If the protocol is determined, then {@link ExternalSystem external clients} who - * may connect to {@link ExternalClientArray this server} must follow the specified protocol. - * - * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: - * - * - {@link ServerBase} - * - {@link WebServerBase} - * - {@link SharedWorkerServerBase} - * - * @return A new {@link IServerBase} object. - */ - protected abstract createServerBase(): protocol.IServerBase; - /** - * Add a newly connected remote client. - * - * When a {@link IClientDriver remote client} connects to this *master server of parallel processing system*, - * then this {@link ParallelClientArray} creates a child {@link ParallelSystem parallel client} object through - * the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. - * - * @param driver A communicator for external client. - */ - addClient(driver: protocol.IClientDriver): void; - /** - * (Deprecated) Factory method creating child object. - * - * The method {@link createChild createChild()} is deprecated. Don't use and override this. - * - * Note that, the {@link ParallelClientArray} is a server accepting {@link ParallelSystem parallel clients}. - * There's no way to creating the {@link ParallelSystem parallel clients} in advance before opening the server. - * - * @param xml An {@link XML} object represents the child {@link ParallelSystem} object. - * @return ```null``` - */ - createChild(xml: library.XML): System; - /** - * Factory method creating {@link ParallelSystem} object. - * - * The method {@link createExternalClient createExternalClient()} is a factory method creating a child - * {@link ParallelSystem} object, that is called whenever a parallel client has connected, by - * {@link addClient addClient()}. - * - * Overrides this {@link createExternalClient} method and creates a type of {@link ParallelSystem} object with - * the *driver* that communicates with the parallel client. After the creation, returns the {@link ParallelSystem} - * object. Then whenever a parallel client has connected, matched {@link ParallelSystem} object will be - * constructed and {@link insert inserted} into this {@link ParallelClientArray} object. - * - * @param driver A communicator with the parallel client. - * @return A newly created {@link ParallelSystem} object. - */ - protected abstract createExternalClient(driver: protocol.IClientDriver): System; - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - } -} -declare namespace samchon.templates.parallel { - /** - * Mediator of Parallel Processing System. - * - * The {@link ParallelSystemArrayMediator} class be a **master** for its slave systems, and be a **slave** to its - * master system at the same time. This {@link ParallelSystemArrayMediator} be a **master **system, containing and - * managing {@link ParallelSystem} objects, which represent parallel slave systems, by extending - * {@link ParallelSystemArray} class. Also, be a **slave** system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a **master**, you can specify this {@link ParallelSystemArrayMediator} class to be a master server accepting - * slave clients or a master client to connecting slave servers. Even both of them is possible. Extends one - * of them below and overrides abstract factory method(s) creating the child {@link ParallelSystem} object. - * - * - {@link ParallelClientArrayMediator}: A server accepting {@link ParallelSystem parallel clients}. - * - {@link ParallelServerArrayMediator}: A client connecting to {@link ParallelServer parallel servers}. - * - {@link ParallelServerClientArrayMediator}: Both of them. Accepts {@link ParallelSystem parallel clients} and - * connects to {@link ParallelServer parallel servers} at the same time. - * - * As a **slave**, you can specify this {@link ParallelSystemArrayMediator} to be a client slave connecting to - * master server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link ParallelSystemArray} - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to slave systems and the - * children {@link ParallelSystem} objects represent the remote slave systems, who is being requested the - * *parallel processes*. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelSystemArrayMediator extends ParallelSystemArray { - /** - * @hidden - */ - private mediator_; - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method creating a {@link MediatorSystem} object. - * - * The {@link createMediator createMediator()} is an abstract method creating the {@link MediatorSystem} object. - * - * You know what? this {@link ParallelSystemArrayMediator} class be a **master** for its slave systems, and be a - * **slave** to its master system at the same time. The {@link MediatorSystem} object makes it possible; be a - * **slave** system. This {@link createMediator} determines specific type of the {@link MediatorSystem}. - * - * Overrides the {@link createMediator createMediator()} method to create and return one of them following which - * protocol and which type of remote connection (server or client) will be used: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * @return A newly created {@link MediatorSystem} object. - */ - protected abstract createMediator(): MediatorSystem; - /** - * Start mediator. - * - * If the {@link getMediator mediator} is a type of server, then opens the server accepting master client. - * Otherwise, the {@link getMediator mediator} is a type of client, then connects the master server. - */ - protected startMediator(): void; - /** - * Get {@link MediatorSystem} object. - * - * When you need to send an {@link Invoke} message to the master system of this - * {@link ParallelSystemArrayMediator}, then send to the {@link MediatorSystem} through this {@link getMediator}. - * - * ```typescript - * this.getMediator().sendData(...); - * ``` - * - * @return The {@link MediatorSystem} object. - */ - getMediator(): MediatorSystem; - /** - * @hidden - */ - protected _Complete_history(history: PRInvokeHistory): boolean; - } -} -declare namespace samchon.templates.parallel { - /** - * Mediator of Parallel Processing System, a server accepting slave clients. - * - * The {@link ParallelClientArrayMediator} is an abstract class, derived from the {@link ParallelSystemArrayMediator} - * class, opening a server accepting {@link ParallelSystem parallel clients} as a **master**. - * - * Extends this {@link ParallelClientArrayMediator}, overrides {@link createServerBase createServerBase()} to - * determine which protocol to follow and {@link createExternalClient createExternalClient()} creating child - * {@link ParallelSystem} object. After the extending and overridings, open this server using the - * {@link open open()} method. - * - * #### [Inherited] {@link ParallelSystemArrayMediator} - * The {@link ParallelSystemArrayMediator} class be a **master** for its slave systems, and be a **slave** to its - * master system at the same time. This {@link ParallelSystemArrayMediator} be a **master **system, containing and - * managing {@link ParallelSystem} objects, which represent parallel slave systems, by extending - * {@link ParallelSystemArray} class. Also, be a **slave** system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a **slave**, you can specify this {@link ParallelSystemArrayMediator} to be a client slave connecting to - * master server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link ParallelSystemArray} - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to slave systems and the - * children {@link ParallelSystem} objects represent the remote slave systems, who is being requested the - * *parallel processes*. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelClientArrayMediator extends ParallelSystemArrayMediator implements external.IExternalClientArray { - /** - * @hidden - */ - private server_base_; - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method creating {@link IServerBase} object. - * - * This method {@link createServerBase createServerBase()} determines which protocol is used in this server, - * {@link ParallelClientArrayMediator}. If the protocol is determined, then - * {@link ParallelSystem parallel clients} who may connect to {@link ParallelClientArrayMediator this server} - * must follow the specified protocol. - * - * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: - * - * - {@link ServerBase} - * - {@link WebServerBase} - * - {@link SharedWorkerServerBase} - * - * @return A new {@link IServerBase} object. - */ - protected abstract createServerBase(): protocol.IServerBase; - /** - * Add a newly connected remote client. - * - * When a {@link IClientDriver remote client} connects to this *master server of parallel processing system*, - * then this {@link ParallelClientArrayMediator} creates a child {@link ParallelSystem parallel client} object - * through the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. - * - * @param driver A communicator for parallel client. - */ - addClient(driver: protocol.IClientDriver): void; - /** - * (Deprecated) Factory method creating child object. - * - * The method {@link createChild createChild()} is deprecated. Don't use and override this. - * - * Note that, the {@link ParallelClientArrayMediator} is a server accepting {@link ParallelSystem parallel - * clients} as a master. There's no way to creating the {@link ParallelSystem parallel clients} in advance before - * opening the server. - * - * @param xml An {@link XML} object represents the child {@link ParallelSystem} object. - * @return null - */ - createChild(xml: library.XML): System; - /** - * Factory method creating {@link ParallelSystem} object. - * - * The method {@link createExternalClient createExternalClient()} is a factory method creating a child - * {@link ParallelSystem} object, that is called whenever a parallel client has connected, by - * {@link addClient addClient()}. - * - * Overrides this {@link createExternalClient} method and creates a type of {@link ParallelSystem} object with - * the *driver* that communicates with the parallel client. After the creation, returns the {@link ParallelSystem} - * object. Then whenever a parallel client has connected, matched {@link ParallelSystem} object will be - * constructed and {@link insert inserted} into this {@link ParallelClientArrayMediator} object. - * - * @param driver A communicator with the parallel client. - * @return A newly created {@link ParallelSystem} object. - */ - protected abstract createExternalClient(driver: protocol.IClientDriver): System; - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - } -} -declare namespace samchon.templates.parallel { - /** - * An interface for a parallel slave server driver. - * - * The easiest way to defining a driver for parallel **slave** server is extending {@link ParallelServer} class. - * However, if you've to interact with a prallel **slave** system who can be both server and client, them make a class - * (let's name it **BaseSystem**) extending the {@link ParallelSystem} class. At next, make a new class (now, I name it - * **BaseServer**) extending the **BaseSystem** and implements this interface {@link IParallelServer}. Define the - * **BaseServer** following those codes on below: - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - interface IParallelServer extends ParallelSystem { - /** - * Connect to slave server. - */ - connect(): void; - } - /** - * A driver for parallel slave server. - * - * The {@link ParallelServer} is an abstract class, derived from the {@link ParallelSystem} class, connecting to - * remote, parallel **slave** server. Extends this {@link ParallelServer} class and overrides the - * {@link createServerConnector createServerConnector()} method following which protocol the **slave** server uses. - * - * #### [Inherited] {@link ParallelSystem} - * The {@link ParallelSystem} is an abstract class represents a **slave** system in *Parallel Processing System*, - * connected with this **master** system. This {@link ParallelSystem} takes full charge of network communication with - * the remote, parallel **slave** system has connected. - * - * When a *parallel process* is requested (by {@link ParallelSystemArray.sendSegmentData} or - * {@link ParallelSystemArray.sendPieceData}), the number of pieces to be allocated to a {@link ParallelSystem} is - * turn on its {@link getPerformance performance index}. Higher {@link getPerformance performance index}, then - * more pieces are requested. The {@link getPerformance performance index} is revaluated whenever a *parallel process* - * has completed, basic on the execution time and number of pieces. You can sugguest or enforce the - * {@link getPerformance performance index} with {@link setPerformance} or {@link enforcePerformance}. - * - * - * - * - * - * #### Bridge & Proxy Pattern - * This class {@link ParallelSystem} is derived from the {@link ExternalSystem} class. Thus, you can take advantage - * of the *Bridge & Proxy Pattern* in this {@link ParallelSystem} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Bridge & Proxy Pattern*: - * - * The {@link ExternalSystem} class can be a *bridge* for *logical proxy*. In framework within user, - * which {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Bridge Pattern* and *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelServer extends ParallelSystem implements IParallelServer { - /** - * IP address of target external system to connect. - */ - protected ip: string; - /** - * Port number of target external system to connect. - */ - protected port: number; - /** - * Construct from parent {@link ParallelSystemArray}. - * - * @param systemArray The parent {@link ParallelSystemArray} object. - */ - constructor(systemArray: ParallelSystemArray); - /** - * Factory method creating {@link IServerConnector} object. - * - * The {@link createServerConnector createServerConnector()} is an abstract method creating - * {@link IServerConnector} object. Overrides and returns one of them, considering which protocol the slave server - * follows: - * - * - {@link ServerConnector} - * - {@link WebServerConnector} - * - {@link DedicatedWorkerServerConnector} - * - {@link SharedWorkerServerConnector} - * - * @return A newly created {@link IServerConnector} object. - */ - protected abstract createServerConnector(): protocol.IServerConnector; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.parallel { - /** - * Master of Parallel Processing System, a client connecting to slave servers. - * - * The {@link ParallelServerArray} is an abstract class, derived from the {@link ParallelSystemArray} class, - * connecting to {@link IParallelServer parallel servers}. - * - * Extends this {@link ParallelServerArray} and overrides {@link createChild createChild()} method creating child - * {@link IParallelServer} object. After the extending and overriding, construct children {@link IParallelServer} - * objects and call the {@link connect connect()} method. - * - * #### [Inherited] {@link ParallelSystemArray} - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to slave systems and the - * children {@link ParallelSystem} objects represent the remote slave systems, who is being requested the - * *parallel processes*. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelServerArray extends ParallelSystemArray implements external.IExternalServerArray { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.parallel { - /** - * Mediator of Parallel Processing System, a client connecting to slave servers. - * - * The {@link ParallelServerArrayMediator} is an abstract class, derived from the {@link ParallelSystemArrayMediator} - * class, connecting to {@link IParallelServer parallel servers}. - * - * Extends this {@link ParallelServerArrayMediator} and overrides {@link createChild createChild()} method creating - * child {@link IParallelServer} object. After the extending and overriding, construct children - * {@link IParallelServer} objects and call the {@link connect connect()} method. - * - * #### [Inherited] {@link ParallelSystemArrayMediator} - * The {@link ParallelSystemArrayMediator} class be a **master** for its slave systems, and be a **slave** to its - * master system at the same time. This {@link ParallelSystemArrayMediator} be a **master **system, containing and - * managing {@link ParallelSystem} objects, which represent parallel slave systems, by extending - * {@link ParallelSystemArray} class. Also, be a **slave** system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a **master**, you can specify this {@link ParallelSystemArrayMediator} class to be a master server accepting - * slave clients or a master client to connecting slave servers. Even both of them is possible. Extends one - * of them below and overrides abstract factory method(s) creating the child {@link ParallelSystem} object. - * - * - {@link ParallelClientArrayMediator}: A server accepting {@link ParallelSystem parallel clients}. - * - {@link ParallelServerArrayMediator}: A client connecting to {@link ParallelServer parallel servers}. - * - {@link ParallelServerClientArrayMediator}: Both of them. Accepts {@link ParallelSystem parallel clients} and - * connects to {@link ParallelServer parallel servers} at the same time. - * - * As a **slave**, you can specify this {@link ParallelSystemArrayMediator} to be a client slave connecting to - * master server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link ParallelSystemArray} - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to slave systems and the - * children {@link ParallelSystem} objects represent the remote slave systems, who is being requested the - * *parallel processes*. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelServerArrayMediator extends ParallelSystemArrayMediator implements external.IExternalServerArray { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.parallel { - /** - * Master of Parallel Processing System, be a server and client at the same time. - * - * The {@link ParallelServerClientArray} is an abstract class, derived from the {@link ParallelSystemArray} class, - * opening a server accepting {@link ParallelSystem parallel clients} and being a client connecting to - * {@link IParallelServer parallel servers} at the same time. - * - * Extends this {@link ParallelServerClientArray} and overrides below methods. After the overridings, open server - * with {@link open open()} method and connect to {@link IParallelServer parallel servers} through the - * {@link connect connect()} method. - * - * - {@link createServerBase createServerBase()} - * - {@link createExternalClient createExternalClient()} - * - {@link createExternalServer createExternalServer()} - * - * #### [Inherited] {@link ParallelSystemArray} - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to slave systems and the - * children {@link ParallelSystem} objects represent the remote slave systems, who is being requested the - * *parallel processes*. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelServerClientArray extends ParallelClientArray implements external.IExternalServerClientArray { - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method of a child Entity. - * - * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. - * - * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. - * @return A new child Entity via {@link createExternalServer createExternalServer()}. - */ - createChild(xml: library.XML): System; - /** - * Factory method creating an {@link IParallelServer} object. - * - * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. - * @return A newly created {@link IParallelServer} object. - */ - protected abstract createExternalServer(xml: library.XML): System; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.parallel { - /** - * Mediator of Parallel Processing System, be a server and client at the same time as a **master**. - * - * The {@link ParallelServerClientArrayMediator} is an abstract class, derived from the - * {@link ParallelSystemArrayMediator} class, opening a server accepting {@link ParallelSystem parallel clients} and - * being a client connecting to {@link IParallelServer parallel servers} at the same time. - * - * Extends this {@link ParallelServerClientArrayMediator} and overrides below methods. After the overridings, open - * server with {@link open open()} method and connect to {@link IParallelServer parallel servers} through the - * {@link connect connect()} method. - * - * - {@link createServerBase createServerBase()} - * - {@link createExternalClient createExternalClient()} - * - {@link createExternalServer createExternalServer()} - * - * #### [Inherited] {@link ParallelSystemArrayMediator} - * The {@link ParallelSystemArrayMediator} class be a **master** for its slave systems, and be a **slave** to its - * master system at the same time. This {@link ParallelSystemArrayMediator} be a **master **system, containing and - * managing {@link ParallelSystem} objects, which represent parallel slave systems, by extending - * {@link ParallelSystemArray} class. Also, be a **slave** system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a **master**, you can specify this {@link ParallelSystemArrayMediator} class to be a master server accepting - * slave clients or a master client to connecting slave servers. Even both of them is possible. Extends one - * of them below and overrides abstract factory method(s) creating the child {@link ParallelSystem} object. - * - * - {@link ParallelClientArrayMediator}: A server accepting {@link ParallelSystem parallel clients}. - * - {@link ParallelServerArrayMediator}: A client connecting to {@link ParallelServer parallel servers}. - * - {@link ParallelServerClientArrayMediator}: Both of them. Accepts {@link ParallelSystem parallel clients} and - * connects to {@link ParallelServer parallel servers} at the same time. - * - * As a **slave**, you can specify this {@link ParallelSystemArrayMediator} to be a client slave connecting to - * master server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link ParallelSystemArray} - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to slave systems and the - * children {@link ParallelSystem} objects represent the remote slave systems, who is being requested the - * *parallel processes*. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
                - *
              • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
              • - *
              • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
              • - *
              • Those strategy is called *Proxy Pattern*.
              • - *
              - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelServerClientArrayMediator extends ParallelClientArrayMediator implements external.IExternalServerClientArray { - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method of a child Entity. - * - * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. - * - * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. - * @return A new child Entity via {@link createExternalServer createExternalServer()}. - */ - createChild(xml: library.XML): System; - /** - * Factory method creating an {@link IParallelServer} object. - * - * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. - * @return A newly created {@link IParallelServer} object. - */ - protected abstract createExternalServer(xml: library.XML): System; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.parallel { - /** - * History of an {@link Invoke} message. - * - * The {@link PRInvokeHistory} is a class archiving history log of an {@link Invoke} message which requests the - * *parallel process*, created whenever {@link ParallelSystemArray.sendSegmentData} or - * {@link ParallelSystemArray.sendSegmentData} is called. - * - * When the *parallel process* has completed, then {@link complete complete()} is called and the *elapsed time* is - * determined. The elapsed time is utilized for computation of {@link ParallelSystem.getPerformance performance index} - * of each {@link ParallelSystem parallel slave system}. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - class PRInvokeHistory extends protocol.InvokeHistory { - /** - * @hidden - */ - private first; - /** - * @hidden - */ - private last; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from an {@link Invoke} message. - * - * @param invoke An {@link Invoke} message requesting a *parallel process*. - */ - constructor(invoke: protocol.Invoke); - /** - * Get initial piece's index. - * - * Returns initial piece's index in the section of requested *parallel process*. - * - * @return The initial index. - */ - getFirst(): number; - /** - * Get final piece's index. - * - * Returns initial piece's index in the section of requested *parallel process*. The range used is - * [*first*, *last*), which contains all the pieces' indices between *first* and *last*, including the piece - * pointed by index *first*, but not the piece pointed by the index *last*. - * - * @return The final index. - */ - getLast(): number; - /** - * Compute number of allocated pieces. - */ - computeSize(): number; - } -} -declare namespace samchon.templates.service { - /** - * A driver of remote client. - * - * The {@link Client} is an abstract class representing and interacting with a remote client. It deals the network - * communication with the remote client and shifts {@link Invoke} message to related {@link User} and {@link Service} - * objects. - * - * Extends this {@link Client} class and override the {@link createService} method, a factory method creating a child - * {@link Service} object. Note that, {@link Client} represents a remote client, not *an user*, a specific *web page* - * or *service*. Do not define logics about user or account information. It must be declared in the parent - * {@link User} class. Also, don't define processes of a specific a web page or service. Defines them in the child - * {@link Service} class. - * - * - * - * - * - * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) - * @author Jeongho Nam - */ - abstract class Client implements protocol.IProtocol { - /** - * @hidden - */ - private user_; - /** - * @hidden - */ - private no_; - /** - * @hidden - */ - private communicator_; - /** - * @hidden - */ - private service_; - /** - * Construct from parent {@link User} and communicator. - * - * @param user Parent {@link User} object. - * @param driver Communicator with remote client. - */ - constructor(user: User, driver: protocol.WebClientDriver); - /** - * Default Destructor. - * - * This {@link destructor destructor()} method is called when the {@link Client} object is destructed and this - * {@link Client} object is destructed when connection with the remote client is closed or this {@link Client} - * object is {@link User.erase erased} from its parent {@link User} object. - * - * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically - * by those *destruction* cases. Also, if your derived {@link Client} class has something to do on the - * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. - * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. - * - * ```typescript - * class MyUser extends protocol.service.Client - * { - * protected destructor(): void - * { - * // DO SOMETHING - * this.do_something(); - * - * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS - * super.destructor(); - * } - * } - * ``` - */ - protected destructor(): void; - /** - * Factory method creating {@link Service} object. - * - * @param path Requested path. - * @return A newly created {@link Service} object or ```null```. - */ - protected abstract createService(path: string): Service; - /** - * Close connection. - */ - close(): void; - /** - * Get parent {@link User} object. - * - * Get the parent {@link User} object, who is groupping {@link Client} objects with same session id. - * - * @return The parent {@link User} object. - */ - getUser(): User; - /** - * Get child {@link Service} object. - * - * @return The child {@link Service} object. - */ - getService(): Service; - /** - * Get sequence number. - * - * Get sequence number of this {@link Client} object in the parent {@link User} object. This sequence number also - * be a *key* in the parent {@link User} object, who extended the ```std.HashMap```. - * - * @return Sequence number. - */ - getNo(): number; - /** - * Change related {@link Service} object. - * - * @param path Requested, identifier path. - */ - protected changeService(path: string): void; - /** - * Change {@link Service} to another. - * - * @param service {@link service} object to newly assigned. - */ - protected changeService(service: Service): void; - /** - * Send an {@link Invoke} message. - * - * Sends an {@link Invoke} message to remote client. - * - * @param invoke An {@link Invoke} messgae to send to remote client. - */ - sendData(invoke: protocol.Invoke): void; - /** - * Handle a replied {@link Invoke} message. - * - * The default {@link Client.replyData Client.replyData()} shifts chain to its parent {@link User} and belonged - * {@link Service} objects, by calling the the {@link User.replyData User.replyData()} and - * {@link Service.replyData Service.replyData()} methods. - * - * Note that, {@link Client} represents a remote client, not *an user*, a specific *web page* or *service*. Do not - * define logics about user or account information. It must be declared in the parent {@link User} class. Also, - * don't define processes of a specific a web page or service. Defines them in the child {@link Service} class. - * - * ```typescript - * class protocol.service.Client - * { - * public replyData(invoke: protocol.Invoke): void - * { - * // SHIFT TO PARENT USER - * // THE PARENT USER ALSO MAY SHIFT TO ITS PARENT SERVER - * this.getUser().replyData(invoke); - * - * // SHIFT TO BELOGED SERVICE - * if (this.getService() != null) - * this.getService().replyData(invoke); - * } - * } - * - * class MyClient extends protocol.service.Client - * { - * public replyData(invoke: protocol.Invoke): void - * { - * if (invoke.getListener() == "do_something_in_client_level") - * this.do_something_in_client_level(); - * else - * super.replyData(invoke); - * } - * } - * ``` - * - * @param invoke An {@link Invoke invoke} message to be handled in {@link Client} level. - */ - replyData(invoke: protocol.Invoke): void; - } -} -/** - * A system template for Cloud Service. - * - * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) - * @author Jeongho Nam - */ -declare namespace samchon.templates.service { - /** - * A cloud server. - * - * The {@link Server} is an abstract server class, who can build a real-time cloud server, that is following the - * web-socket protocol. Extends this {@link Server} and related classes and overrides abstract methods under below. - * After the overridings, open this {@link Server cloud server} using the {@link open open()} method. - * - * - Objects in composite relationship and their factory methods - * - {@link User}: {@link Server.createUser Server.createUser()} - * - {@link Client}: {@link User.createClient User.createClient()} - * - {@link Service}: {@link Client.createService Client.createService()} - * - {@link Invoke} message chains; {@link IProtocol.replyData replyData} - * - {@link Server.replyData} - * - {@link User.replyData} - * - {@link Client.replyData} - * - {@link Service.replyData} - * - * - * - * - * - * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) - * @author Jeongho Nam - */ - abstract class Server extends protocol.WebServer implements protocol.IProtocol { - /** - * @hidden - */ - private session_map_; - /** - * @hidden - */ - private account_map_; - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method creating {@link User} object. - * - * @return A newly created {@link User} object. - */ - protected abstract createUser(): User; - /** - * Test wheter an {@link User} exists with the *accountID*. - * - * @param accountID Account id of {@link User} to find. - * @return Exists or not. - */ - has(accountID: string): boolean; - /** - * Get an {@link User} object by its *accountID*. - * - * @param accountID Account id of {@link User} to get. - * @return An {@link User} object. - */ - get(accountID: string): User; - /** - * Send an {@link Invoke} message. - * - * Sends an {@link Invoke} message to all remote clients through the belonged {@link User} and {@link Client} - * objects. Sending the {@link Invoke} message to all remote clients, it's came true by passing through - * {@link User.sendData User.sendData()}. And the {@link User.sendData} also pass through the - * {@link Client.sendData Client.sendData()}. - * - * ```typescript - * class protocol.service.Server - * { - * public sendData(invoke: Invoke): void - * { - * for (user: User in this) - * for (client: Client in user) - * client.sendData(invoke); - * } - * } - * ``` - * - * @param invoke {@link Invoke} message to send to all remote clients. - */ - sendData(invoke: protocol.Invoke): void; - /** - * Handle a replied {@link Invoke} message. - * - * The {@link Server.replyData Server.replyData()} is an abstract method that handling {@link Invoke} message - * that should be handled in the {@link Server} level. Overrides this {@link replyData replyData()} method and - * defines what to do with the {@link Invoke} message in this {@link Server} level. - * - * @param invoke An {@link Invoke invoke} message to be handled in {@link Server} level. - */ - abstract replyData(invoke: protocol.Invoke): void; - /** - * Add a newly connected remote client. - * - * When a {@link WebClientDriver remote client} connects to this cloud server, then {@link Server} queries the - * {WebClientDriver.getSessionID session id} of the {@link WebClientDriver remote client}. If the - * {WebClientDriver.getSessionID session id} is new one, then creates a new {@link User} object. - * - * At next, creates a {@link Client} object who represents the newly connected remote client and insert the - * {@link Client} object to the matched {@link User} object which is new or ordinary one following the - * {WebClientDriver.getSessionID session id}. At last, a {@link Service} object can be created with referencing - * the {@link WebClientDriver.getPath path}. - * - * List of objects can be created by this method. - * - {@link User} by {@link createUser createUser()}. - * - {@link Client} by {@link User.createClient User.createClient()}. - * - {@link Service} by {@link Client.createService Client.createService()}. - * - * @param driver A web communicator for remote client. - */ - addClient(driver: protocol.WebClientDriver): void; - /** - * @hidden - */ - private erase_user(user); - } -} -declare namespace samchon.templates.service { - /** - * A service. - * - * The {@link Service} is an abstract class who represents a service, that is providing functions a specific page. - * - * Extends the {@link Service} class and defines its own service, which to be provided for the specific weg page, - * by overriding the {@link replyData replyData()} method. Note that, the service, functions for the specific page - * should be defined in this {@link Service} class, not its parent {@link Client} class who represents a remote client - * and takes communication responsibility. - * - * - * - * - * - * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) - * @author Jeongho Nam - */ - abstract class Service implements protocol.IProtocol { - /** - * @hidden - */ - private client_; - /** - * @hidden - */ - private path_; - /** - * Construct from parent {@link Client} and requested path. - * - * @param client Driver of remote client. - * @param path Requested path that identifies this {@link Service}. - */ - constructor(client: Client, path: string); - /** - * Default Destructor. - * - * This {@link destructor destructor()} method is call when the {@link Service} object is destructed and the - * {@link Service} object is destructed when its parent {@link Client} object has - * {@link Client.destructor destructed} or the {@link Client} object {@link Client.changeService changed} its - * child {@link Service service} object to another one. - * - * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically - * by those *destruction* cases. Also, if your derived {@link Service} class has something to do on the - * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. - */ - protected destructor(): void; - /** - * Get client. - */ - getClient(): Client; - /** - * Get requested path. - */ - getPath(): string; - /** - * Send an {@link Invoke} message. - * - * Sends an {@link Invoke} message to remote system through parent {@link Client} object ({@link Client.sendData}). - * - * @param invoke An {@link Invoke} message to send to the remte system. - */ - sendData(invoke: protocol.Invoke): void; - /** - * @inheritdoc - */ - abstract replyData(invoke: protocol.Invoke): void; - } -} -declare namespace samchon.templates.service { - /** - * An user. - * - * The {@link User} is an abstract class groupping {@link Client} objects, who communicates with remote client, with - * same *session id*. This {@link User} represents a *remote user* literally. Within framework of remote system, - * an {@link User} corresponds to a web-browser and a {@link Client} represents a window in the web-browser. - * - * Extends this {@link User} class and override the {@link createClient} method, a factory method creating a child - * {@link Client} object. I repeat, the {@link User} class represents a *remote user*, groupping {@link Client} - * objects with same *session id*. If your cloud server has some processes to be handled in the **user level**, then - * defines method in this {@link User} class. Methods managing **account** under below are some of them: - * - * - {@link setAccount setAccount()} - * - {@link getAccountID getAccountID()} - * - {@link getAuthority getAuthority()} - * - * The children {@link Client} objects, they're contained with their key, the {@link Client.getNo sequence number}. - * If you {@link User.erase erase} the children {@link Client} object by yourself, then their connection with the - * remote clients will be {@link Client.close closed} and their {@link Client.destructor destruction method} will be - * called. If you remove {@link clear all children}, then this {@link User} object will be also - * {@link destructor destructed} and erased from the parent {@link Server} object. - * - * - * - * - * - * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) - * @author Jeongho Nam - */ - abstract class User extends collections.HashMapCollection implements protocol.IProtocol { - /** - * @hidden - */ - private server_; - /** - * @hidden - */ - private session_id_; - /** - * @hidden - */ - private sequence_; - /** - * @hidden - */ - private account_id_; - /** - * @hidden - */ - private authority_; - /** - * Construct from its parent {@link Server}. - * - * @param server The parent {@link Server} object. - */ - constructor(server: Server); - /** - * Default Destructor. - * - * This {@link destructor destructor()} method is called when the {@link User} object is destructed. The - * {@link User} object is destructed when connections with the remote clients are all closed, that is all the - * children {@link Client} objects are all removed, and 30 seconds has left. If some remote client connects - * within the 30 seconds, then the {@link User} object doesn't be destructed. - * - * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically - * by those *destruction* cases. Also, if your derived {@link User} class has something to do on the - * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. - * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. - * - * ```typescript - * class MyUser extends protocol.service.User - * { - * protected destructor(): void - * { - * // DO SOMETHING - * this.do_something(); - * - * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS - * super.destructor(); - * } - * } - * ``` - */ - protected destructor(): void; - /** - * Factory method creating a {@link Client} object. - * - * @param driver A web communicator for remote client. - * @return A newly created {@link Client} object. - */ - protected abstract createClient(driver: protocol.WebClientDriver): Client; - /** - * @hidden - */ - private handle_erase_client(event); - /** - * Get parent {@lin Server} object. - * - * @return Parent {@link Server} object. - */ - getServer(): Server; - /** - * Get account id. - * - * @return Account ID. - */ - getAccountID(): string; - /** - * Get authority. - * - * @return Authority - */ - getAuthority(): number; - /** - * Set *account id* and *authority*. - * - * The {@link setAccount setAccount()} is a method configuring *account id* and *authority* of this {@link User}. - * - * After the configuring, the {@link getAccountID account id} is enrolled into the parent {@link Server} as a - * **key** for this {@link User} object. You can test existence and access this {@link User} object from - * {@link Server.has Server.has()} and {@link Server.get Server.get()} with the {@link getAccountID account id}. - * Of course, if ordinary {@link getAccountID account id} had existed, then the ordinary **key** will be - * replaced. - * - * As you suggest, this {@link setAccount setAccount()} is something like a **log-in** function. If what you want - * is not **logging-in**, but **logging-out**, then configure the *account id* to empty string ``""```` or call - * the {@link lgout logout()} method. - * - * @param id To be account id. - * @param authority To be authority. - */ - setAccount(id: string, authority: number): void; - /** - * Log-out. - * - * This {@link logout logout()} method configures {@link getAccountID account id} to empty string and - * {@link getAuthority authority} to zero. - * - * The ordinary {@link getAccountID account id} will be also erased from the parent {@link Server} object. You - * can't access this {@link User} object from {@link Server.has Server.has()} and {@link Server.get Server.get()} - * with the ordinary {@link getAccountID account id} more. - */ - logout(): void; - /** - * Send an {@link Invoke} message. - * - * Sends an {@link Invoke} message to all remote clients through the belonged {@link Client} objects. Sending the - * {@link Invoke} message to all remote clients, it's came true by passing through the - * {@link Client.sendData Client.sendData()} methods. - * - * ```typescript - * class protocol.service.User - * { - * public sendData(invoke: Invoke): void - * { - * for (let it = this.begin(); !it.equal_to(this.end()); it = it.next()) - * it.second.sendData(invoke); - * } - * } - * ``` - * - * @param invoke {@link Invoke} message to send to all remote clients. - */ - sendData(invoke: protocol.Invoke): void; - /** - * Handle a replied {@link Invoke} message. - * - * The default {@link User.replyData User.replyData()} shifts chain to its parent {@link Server} object, by - * calling the {@link Server.replyData Server.replyData()} method. If there're some {@link Invoke} message to be - * handled in this {@link User} level, then override this method and defines what to do with the {@link Invoke} - * message in this {@link User} level. - * - * ```typescript - * class protocol.service.User - * { - * public replyData(invoke: protocol.Invoke): void - * { - * this.getServer().replyData(invoke); - * } - * } - * - * class MyUser extends protocol.service.User - * { - * public replyData(invoke: protocol.Invoke): void - * { - * if (invoke.apply(this) == false) // IS TARGET TO BE HANDLED IN THIS USER LEVEL - * super.replyData(invoke); // SHIFT TO SERVER - * } - * } - * ``` - * - * @param invoke An {@link Invoke invoke} message to be handled in {@link User} level. - */ - replyData(invoke: protocol.Invoke): void; - } -} -declare namespace samchon.templates.slave { - interface ISlaveClient extends SlaveSystem { - connect(ip: string, port: number): void; - } - abstract class SlaveClient extends SlaveSystem implements ISlaveClient { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - protected abstract createServerConnector(): protocol.IServerConnector; - /** - * @inheritdoc - */ - connect(ip: string, port: number): void; - } -} -declare namespace samchon.templates.slave { - interface ISlaveServer extends SlaveSystem, protocol.IServer { - } - abstract class SlaveServer extends SlaveSystem implements ISlaveServer { - private server_base_; - constructor(); - protected abstract createServerBase(): protocol.IServerBase; - open(port: number): void; - close(): void; - addClient(driver: protocol.IClientDriver): void; - } -} +} \ No newline at end of file diff --git a/samchon/index.d.ts b/samchon/index.d.ts new file mode 100644 index 0000000000..6f2bc17b43 --- /dev/null +++ b/samchon/index.d.ts @@ -0,0 +1,8403 @@ +// Type definitions for Samchon Framework v2.0.7 +// Project: https://github.com/samchon/framework +// Definitions by: Jeongho Nam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "samchon" +{ + export = samchon; +} + +/** + * # Samchon Framework + * + * + * + * + * Samchon, a OON (Object-Oriented Network) framework. + * + * With Samchon Framework, you can implement distributed processing system within framework of OOD like handling S/W + * objects (classes). You can realize cloud and distributed system very easily with provided system templates and even + * integration with C++ is possible. + * + * The goal, ultimate utilization model of Samchon Framework is, building cloud system with NodeJS and taking heavy works + * to C++ distributed systems with provided modules (those are system templates). + * + * @git https://github.com/samchon/framework + * @author Jeongho Nam + */ +declare namespace samchon { +} +declare namespace samchon.collections { + /** + * A {@link Vector} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link CollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link push} + * - {@link push_back} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - {@link pop_back} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link Vector} + * @copydoc Vector + */ + class ArrayCollection extends std.Vector implements ICollection { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @inheritdoc + */ + push(...items: T[]): number; + /** + * @inheritdoc + */ + push_back(val: T): void; + /** + * @hidden + */ + protected _Insert_by_range>(position: std.VectorIterator, begin: InputIterator, end: InputIterator): std.VectorIterator; + /** + * @hidden + */ + protected _Erase_by_range(first: std.VectorIterator, last: std.VectorIterator): std.VectorIterator; + /** + * @hidden + */ + private _Notify_insert(first, last); + /** + * @hidden + */ + private _Notify_erase(first, last); + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.VectorIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.VectorIterator, last: std.VectorIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.library { + /** + * A basic event class of Samchon Framework. + * + * @reference https://developer.mozilla.org/en-US/docs/Web/API/Event + * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-EventDispatcher + * @author Jeongho Nam + */ + class BasicEvent { + protected type_: string; + protected target_: IEventDispatcher; + private currentTarget_; + protected trusted_: boolean; + protected bubbles_: boolean; + protected cancelable_: boolean; + protected defaultPrevented_: boolean; + protected cancelBubble_: boolean; + private timeStamp_; + constructor(type: string, bubbles?: boolean, cancelable?: boolean); + /** + * @inheritdoc + */ + initEvent(type: string, bubbles: boolean, cancelable: boolean): void; + /** + * @inheritdoc + */ + /** + * @inheritdoc + */ + stopImmediatePropagation(): void; + /** + * @inheritdoc + */ + stopPropagation(): void; + /** + * @inheritdoc + */ + readonly type: string; + /** + * @inheritdoc + */ + target: IEventDispatcher; + /** + * @inheritdoc + */ + readonly currentTarget: IEventDispatcher; + /** + * @inheritdoc + */ + readonly bubbles: boolean; + /** + * @inheritdoc + */ + readonly cancelable: boolean; + /** + * @inheritdoc + */ + readonly eventPhase: number; + /** + * @inheritdoc + */ + readonly defaultPrevented: boolean; + /** + * @inheritdoc + */ + readonly srcElement: Element; + /** + * @inheritdoc + */ + readonly cancelBubble: boolean; + /** + * @inheritdoc + */ + readonly timeStamp: number; + /** + * Don't know what it is. + */ + readonly returnValue: boolean; + } +} +declare namespace samchon.collections { + /** + * Type of function pointer for listener of {@link CollectionEvent CollectionEvents}. + */ + type CollectionEventListener = (event: CollectionEvent) => void; +} +declare namespace samchon.collections { + /** + * An event occured in a {@link ICollection collection} object. + * + * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) + * @author Jeongho Nam + */ + class CollectionEvent extends library.BasicEvent { + /** + * @hidden + */ + private first_; + /** + * @hidden + */ + private last_; + /** + * @hidden + */ + private temporary_container_; + /** + * @hidden + */ + private origin_first_; + /** + * Initialization Constructor. + * + * @param type Type of collection event. + * @param first An {@link Iterator} to the initial position in this {@link CollectionEvent}. + * @param last An {@link Iterator} to the final position in this {@link CollectionEvent}. + */ + constructor(type: string, first: std.Iterator, last: std.Iterator); + constructor(type: "insert", first: std.Iterator, last: std.Iterator); + constructor(type: "erase", first: std.Iterator, last: std.Iterator); + constructor(type: "refresh", first: std.Iterator, last: std.Iterator); + /** + * Associative target, the {@link ICollection collection}. + */ + readonly target: ICollection; + /** + * An {@link Iterator} to the initial position in this {@link CollectionEvent}. + */ + readonly first: std.Iterator; + /** + * An {@link Iterator} to the final position in this {@link CollectionEvent}. + */ + readonly last: std.Iterator; + /** + * @inheritdoc + */ + preventDefault(): void; + } +} +declare namespace samchon.collections.CollectionEvent { + const INSERT: "insert"; + const ERASE: "erase"; + const REFRESH: "refresh"; +} +declare namespace samchon.collections { + /** + * A {@link Deque} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link CollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link push} + * - {@link push_front} + * - {@link push_back} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - {@link pop_front} + * - {@link pop_back} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link Deque} + * @copydoc Deque + */ + class DequeCollection extends std.Deque implements ICollection { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @inheritdoc + */ + push_front(val: T): void; + /** + * @inheritdoc + */ + push_back(val: T): void; + /** + * @hidden + */ + protected _Insert_by_range>(position: std.DequeIterator, begin: InputIterator, end: InputIterator): std.DequeIterator; + /** + * @inheritdoc + */ + pop_front(): void; + /** + * @inheritdoc + */ + pop_back(): void; + /** + * @hidden + */ + protected _Erase_by_range(first: std.DequeIterator, last: std.DequeIterator): std.DequeIterator; + /** + * @hidden + */ + private _Notify_insert(first, last); + /** + * @hidden + */ + private _Notify_erase(first, last); + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.DequeIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.DequeIterator, last: std.DequeIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.collections { + /** + * A {@link HashMap} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link MapCollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link insert_or_assign} + * - {@link emplace} + * - {@link set} + * - {@link push} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - {@link extract} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link HashMap} + * @copydoc HashMap + */ + class HashMapCollection extends std.HashMap implements ICollection> { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.MapIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: MapCollectionEventListener): void; + addEventListener(type: "erase", listener: MapCollectionEventListener): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.collections { + /** + * A {@link HashMultiMap} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link MapCollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link emplace} + * - {@link push} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link HashMultiMap} + * @copydoc HashMultiMap + */ + class HashMultiMapCollection extends std.HashMultiMap implements ICollection> { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.MapIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: MapCollectionEventListener): void; + addEventListener(type: "erase", listener: MapCollectionEventListener): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.collections { + /** + * A {@link HashMultiSet} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link CollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link push} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link HashMultiSet} + * @copydoc HashMultiSet + */ + class HashMultiSetCollection extends std.HashMultiSet implements ICollection { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.SetIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.collections { + /** + * A {@link HashSet} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link CollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link push} + * - {@link insert_or_assign} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - {@link extract} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link HashSet} + * @copydoc HashSet + */ + class HashSetCollection extends std.HashSet implements ICollection { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.SetIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + } +} +/** + * Collections, elements I/O detectable STL containers. + * + * STL Containers | Collections + * ---------------------|------------------- + * {@link Vector} | {@link ArrayCollection} + * {@link List} | {@link ListCollection} + * {@link Deque} | {@link DequeCollection} + * | + * {@link TreeSet} | {@link TreeSetCollection} + * {@link HashSet} | {@link HashSetCollection} + * {@link TreeMultiSet} | {@link TreeMultiSetCollection} + * {@link HashMultiSet} | {@link HashMultiSetCollection} + * | + * {@link TreeMap} | {@link TreeMapCollection} + * {@link HashMap} | {@link HashMapCollection} + * {@link TreeMultiMap} | {@link TreeMultiMapCollection} + * {@link HashMultiMap} | {@link HashMultiMapCollection} + * + * @author Jeongho Nam + */ +declare namespace samchon.collections { + /** + * An interface for {@link IContainer containers} who can detect element I/O events. + * + * Below are list of methods who are dispatching {@link CollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link push} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - *refresh* typed events: + * - {@link refresh} + * + * @author Jeongho Nam + */ + interface ICollection extends std.base.Container, library.IEventDispatcher { + /** + * Dispatch a {@link CollectionEvent} with *refresh* typed. + * + * {@link ICollection} dispatches {@link CollectionEvent} typed *insert* or *erase* whenever elements I/O has + * occured. However, unlike those elements I/O events, content change in element level can't be detected. + * There's no way to detect those events automatically by {@link IContainer}. + * + * If you want to dispatch those typed events (notifying change on contents in element level), you've to + * dispatch *refresh* typed event manually, by yourself. Call {@link refresh refresh()} with specified + * iterators who're pointing the elements whose content have changed. Then a {@link CollectionEvent} with + * *refresh* typed will be dispatched. + * + * If you don't specify any iterator, then the range of the *refresh* event will be all elements in this + * {@link ICollection collection}; {@link begin begin()} to {@link end end()}. + */ + refresh(): void; + /** + * Dispatch a {@link CollectionEvent} with *refresh* typed. + * + * {@link ICollection} dispatches {@link CollectionEvent} typed *insert* or *erase* whenever elements I/O has + * occured. However, unlike those elements I/O events, content change in element level can't be detected. + * There's no way to detect those events automatically by {@link IContainer}. + * + * If you want to dispatch those typed events (notifying change on contents in element level), you've to + * dispatch *refresh* typed event manually, by yourself. Call {@link refresh refresh()} with specified + * iterators who're pointing the elements whose content have changed. Then a {@link CollectionEvent} with + * *refresh* typed will be dispatched. + * + * @param it An iterator targeting the content changed element. + */ + refresh(it: std.Iterator): void; + /** + * Dispatch a {@link CollectionEvent} with *refresh* typed. + * + * {@link ICollection} dispatches {@link CollectionEvent} typed *insert* or *erase* whenever elements I/O has + * occured. However, unlike those elements I/O events, content change in element level can't be detected. + * There's no way to detect those events automatically by {@link IContainer}. + * + * If you want to dispatch those typed events (notifying change on contents in element level), you've to + * dispatch *refresh* typed event manually, by yourself. Call {@link refresh refresh()} with specified + * iterators who're pointing the elements whose content have changed. Then a {@link CollectionEvent} with + * *refresh* typed will be dispatched. + * + * @param first An Iterator to the initial position in a sequence of the content changed elmeents. + * @param last An {@link Iterator} to the final position in a sequence of the content changed elements. The range + * used is [*first*, *last*), which contains all the elements between *first* and + * *last*, including the element pointed by *first* but not the element pointed by + * *last*. + */ + refresh(first: std.Iterator, last: std.Iterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + } + /** + * @hidden + */ + namespace ICollection { + /** + * @hidden + */ + function _Dispatch_CollectionEvent(collection: ICollection, type: string, first: std.Iterator, last: std.Iterator): void; + /** + * @hidden + */ + function _Dispatch_MapCollectionEvent(collection: ICollection>, type: string, first: std.MapIterator, last: std.MapIterator): void; + } +} +declare namespace samchon.collections { + /** + * A {@link List} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link CollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link push} + * - {@link push_front} + * - {@link push_back} + * - {@link merge} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - {@link pop_front} + * - {@link pop_back} + * - {@link unique} + * - {@link remove} + * - {@link remove_if} + * - {@link splice} + * - *refresh* typed events: + * - {@link refresh} + * - {@link sort} + * + * #### [Inherited] {@link List} + * @copydoc List + */ + class ListCollection extends std.List implements ICollection { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Insert_by_range>(position: std.ListIterator, begin: InputIterator, end: InputIterator): std.ListIterator; + /** + * @hidden + */ + protected _Erase_by_range(first: std.ListIterator, last: std.ListIterator): std.ListIterator; + /** + * @hidden + */ + private _Notify_insert(first, last); + /** + * @hidden + */ + private _Notify_erase(first, last); + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.ListIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.ListIterator, last: std.ListIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.collections { + type MapCollectionEventListener = (event: MapCollectionEvent) => void; + /** + * An event occured in a {@link MapContainer map container} object. + * + * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) + * @author Jeongho Nam + */ + class MapCollectionEvent extends CollectionEvent> { + /** + * @inheritdoc + */ + readonly first: std.MapIterator; + /** + * @inheritdoc + */ + readonly last: std.MapIterator; + } +} +declare namespace samchon.collections { + /** + * A {@link TreeMap} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link MapCollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link insert_or_assign} + * - {@link emplace} + * - {@link set} + * - {@link push} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - {@link extract} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link TreeMap} + * @copydoc TreeMap + */ + class TreeMapCollection extends std.TreeMap implements ICollection> { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.MapIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: MapCollectionEventListener): void; + addEventListener(type: "erase", listener: MapCollectionEventListener): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.collections { + /** + * A {@link TreeMultiMap} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link MapCollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link emplace} + * - {@link push} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link TreeMultiMap} + * @copydoc TreeMultiMap + */ + class TreeMultiMapCollection extends std.TreeMultiMap implements ICollection> { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.MapIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: MapCollectionEventListener): void; + addEventListener(type: "erase", listener: MapCollectionEventListener): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.collections { + /** + * A {@link TreeMultiSet} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link CollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link push} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link TreeMultiSet} + * @copydoc TreeMultiSet + */ + class TreeMultiSetCollection extends std.TreeMultiSet implements ICollection { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.SetIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.collections { + /** + * A {@link TreeMap} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link CollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link insert_or_assign} + * - {@link push} + * - *erase* typed events: + * - {@link assign} + * - {@link clear}7 + * - {@link erase} + * - {@link extract} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link TreeSet} + * @copydoc TreeSet + */ + class TreeSetCollection extends std.TreeSet implements ICollection { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.SetIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.library { + /** + * Case generator. + * + * {@link CaseGenerator} is an abstract case generator being used like a matrix. + *
                + *
              • n��r(n^r) -> {@link CombinedPermutationGenerator}
              • + *
              • nPr -> {@link PermutationGenerator}
              • + *
              • n! -> {@link FactorialGenerator}
              • + *
              + * + * @author Jeongho Nam + */ + abstract class CaseGenerator { + /** + * Size, the number of all cases. + */ + protected size_: number; + /** + * N, size of the candidates. + */ + protected n_: number; + /** + * R, size of elements of each case. + */ + protected r_: number; + /** + * Construct from size of N and R. + * + * @param n Size of candidates. + * @param r Size of elements of each case. + */ + constructor(n: number, r: number); + /** + * Get size of all cases. + * + * @return Get a number of the all cases. + */ + size(): number; + /** + * Get size of the N. + */ + n(): number; + /** + * Get size of the R. + */ + r(): number; + /** + * Get index'th case. + * + * @param index Index number + * @return The row of the index'th in combined permuation case + */ + abstract at(index: number): number[]; + } + /** + * A combined-permutation case generator. + * + * n��r + * + * @author Jeongho Nam + */ + class CombinedPermutationGenerator extends CaseGenerator { + /** + * An array using for dividing each element index. + */ + private divider_array; + /** + * Construct from size of N and R. + * + * @param n Size of candidates. + * @param r Size of elements of each case. + */ + constructor(n: number, r: number); + at(index: number): number[]; + } + /** + * A permutation case generator. + * + * nPr + * + * @author Jeongho Nam + */ + class PermuationGenerator extends CaseGenerator { + /** + * Construct from size of N and R. + * + * @param n Size of candidates. + * @param r Size of elements of each case. + */ + constructor(n: number, r: number); + /** + * @inheritdoc + */ + at(index: number): number[]; + } + /** + * Factorial case generator. + * + * n! = nPn + * + * @author Jeongho Nam + */ + class FactorialGenerator extends PermuationGenerator { + /** + * Construct from factorial size N. + * + * @param n Factoria size N. + */ + constructor(n: number); + } +} +declare namespace samchon.library { + type BasicEventListener = (event: BasicEvent) => void; + /** + * The IEventDispatcher interface defines methods for adding or removing event listeners, checks whether specific + * types of event listeners are registered, and dispatches events. + * + * The event target serves as the local point for how events flow through the display list hierarchy. When an + * event such as a mouse click or a key press occurs, an event object is dispatched into the event flow from the + * root of the display list. The event object makes a round-trip journey to the event target, which is + * conceptually divided into three phases: the capture phase includes the journey from the root to the last node + * before the event target's node; the target phase includes only the event target node; and the bubbling phase + * includes any subsequent nodes encountered on the return trip to the root of the display list. + * + * In general, the easiest way for a user-defined class to gain event dispatching capabilities is to extend + * {@link EventDispatcher}. If this is impossible (that is, if the class is already extending another class), you + * can instead implement the {@link IEventDispatcher} interface, create an {@link EventDispatcher} member, and + * write simple hooks to route calls into the aggregated {@link EventDispatcher}. + * + * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/IEventDispatcher.html + * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-EventDispatcher + * @author Migrated by Jeongho Nam + */ + interface IEventDispatcher { + /** + * Checks whether the {@link EventDispatcher} object has any listeners registered for a specific type of event. + * This allows you to determine where an {@link EventDispatcher} object has altered handling of an event type + * in the event flow hierarchy. To determine whether a specific event type actually triggers an event listener, + * use {@link willTrigger willTrigger()}. + * + * The difference between {@link hasEventListener hasEventListener()} and {@link willTrigger willTrigger()} is + * that {@link hasEventListener} examines only the object to which it belongs, whereas {@link willTrigger} + * examines the entire event flow for the event specified by the type parameter. + * + * @param type The type of event. + */ + hasEventListener(type: string): boolean; + /** + * Dispatches an event into the event flow. + * + * The event target is the {@link EventDispatcher} object upon which the {@link dispatchEvent dispatchEvent()} + * method is called. + * + * @param event The {@link BasicEvent} object that is dispatched into the event flow. If the event is being + * redispatched, a clone of the event is created automatically. After an event is dispatched, its + * target property cannot be changed, so you must create a new copy + * of the event for redispatching to work. + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * Registers an event listener object with an {@link EventDispatcher} object so that the listener receives + * notification of an event. You can register event listeners on all nodes in the display list for a specific + * type of event, phase, and priority. + * + * After you successfully register an event listener, you cannot change its priority through additional calls + * to {@link addEventListener addEventListener()|} To change a listener's priority, you must first call + * {@link removeEventListener removeEventListener()}. Then you can register the listener again with the new + * priority level. + * + * Keep in mind that after the listener is registered, subsequent calls to {@link addEventListener} with a + * different type or useCapture value result in the creation of a separate listener registration. For example, + * if you first register a listener with useCapture set to true, it listens only during the capture phase. If + * you call {@link addEventListener} again using the same listener object, but with useCapture set to false, + * you have two separate listeners: one that listens during the capture phase and another that listens during + * the target and bubbling phases. + * + * You cannot register an event listener for only the target phase or the bubbling phase. Those phases are + * coupled during registration because bubbling applies only to the ancestors of the target node. + * + * If you no longer need an event listener, remove it by calling {@link removeEventListener}, or memory + * problems could result. Event listeners are not automatically removed from memory because the garbage + * collector does not remove the listener as long as the dispatching object exists (unless the + * useWeakReference parameter is set to true). + * + * Copying an {@link EventDispatcher} instance does not copy the event listeners attached to it. (If your n + * ewly created node needs an event listener, you must attach the listener after creating the node.) However, + * if you move an {@link EventDispatcher} instance, the event listeners attached to it move along with it. + * + * If the event listener is being registered on a node while an event is also being processed on this node, + * the event listener is not triggered during the current phase but may be triggered during a later phase in + * the event flow, such as the bubbling phase. + * + * If an event listener is removed from a node while an event is being processed on the node, it is still + * triggered by the current actions. After it is removed, the event listener is never invoked again (unless it + * is registered again for future processing). + * + * @param event The type of event. + * @param listener The listener function that processes the event. + * This function must accept an Event object as its only parameter and must return + * nothing. + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + /** + * Registers an event listener object with an {@link EventDispatcher} object so that the listener receives + * notification of an event. You can register event listeners on all nodes in the display list for a specific + * type of event, phase, and priority. + * + * After you successfully register an event listener, you cannot change its priority through additional calls + * to {@link addEventListener addEventListener()|} To change a listener's priority, you must first call + * {@link removeEventListener removeEventListener()}. Then you can register the listener again with the new + * priority level. + * + * Keep in mind that after the listener is registered, subsequent calls to {@link addEventListener} with a + * different type or useCapture value result in the creation of a separate listener registration. For example, + * if you first register a listener with useCapture set to true, it listens only during the capture phase. If + * you call {@link addEventListener} again using the same listener object, but with useCapture set to false, + * you have two separate listeners: one that listens during the capture phase and another that listens during + * the target and bubbling phases. + * + * You cannot register an event listener for only the target phase or the bubbling phase. Those phases are + * coupled during registration because bubbling applies only to the ancestors of the target node. + * + * If you no longer need an event listener, remove it by calling {@link removeEventListener}, or memory + * problems could result. Event listeners are not automatically removed from memory because the garbage + * collector does not remove the listener as long as the dispatching object exists (unless the + * useWeakReference parameter is set to true). + * + * Copying an {@link EventDispatcher} instance does not copy the event listeners attached to it. (If your n + * ewly created node needs an event listener, you must attach the listener after creating the node.) However, + * if you move an {@link EventDispatcher} instance, the event listeners attached to it move along with it. + * + * If the event listener is being registered on a node while an event is also being processed on this node, + * the event listener is not triggered during the current phase but may be triggered during a later phase in + * the event flow, such as the bubbling phase. + * + * If an event listener is removed from a node while an event is being processed on the node, it is still + * triggered by the current actions. After it is removed, the event listener is never invoked again (unless it + * is registered again for future processing). + * + * @param event The type of event. + * @param listener The listener function that processes the event. + * This function must accept an Event object as its only parameter and must return + * nothing. + * @param thisArg The object to be used as the **this** object. + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + /** + * Removes a listener from the {@link EventDispatcher} object. If there is no matching listener registered + * with the {@link EventDispatcher} object, a call to this method has no effect. + * + * @param type The type of event. + * @param listener The listener object to remove. + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + /** + * Removes a listener from the {@link EventDispatcher} object. If there is no matching listener registered + * with the {@link EventDispatcher} object, a call to this method has no effect. + * + * @param type The type of event. + * @param listener The listener object to remove. + * @param thisArg The object to be used as the **this** object. + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + } + /** + * The {@link EventDispatcher} class is the base class for all classes that dispatch events. The + * {@link EventDispatcher} class implements the {@link IEventDispatcher} interface and is the base class for the + * {@link DisplayObject} class. The {@link EventDispatcher} class allows any object on the display list to be an + * event target and as such, to use the methods of the {@link IEventDispatcher} interface. + * + * The event target serves as the local point for how events flow through the display list hierarchy. When an + * event such as a mouse click or a key press occurs, an event object is dispatched into the event flow from the + * root of the display list. The event object makes a round-trip journey to the event target, which is + * conceptually divided into three phases: the capture phase includes the journey from the root to the last node + * before the event target's node; the target phase includes only the event target node; and the bubbling phase + * includes any subsequent nodes encountered on the return trip to the root of the display list. + * + * In general, the easiest way for a user-defined class to gain event dispatching capabilities is to extend + * {@link EventDispatcher}. If this is impossible (that is, if the class is already extending another class), you + * can instead implement the {@link IEventDispatcher} interface, create an {@link EventDispatcher} member, and + * write simple hooks to route calls into the aggregated {@link EventDispatcher}. + * + * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/EventDispatcher.html + * @author Migrated by Jeongho Nam + */ + class EventDispatcher implements IEventDispatcher { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + private event_listeners_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from the origin event dispatcher. + * + * @param dispatcher The origin object who issuing events. + */ + constructor(dispatcher: IEventDispatcher); + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + } +} +declare namespace samchon.library { + /** + * The {@link FileReference} class provides a means to load and save files in browser level. + * + * The {@link FileReference} class provides a means to {@link load} and {@link save} files in browser level. A + * browser-system dialog box prompts the user to select a file to {@link load} or a location for {@link svae}. Each + * {@link FileReference} object refers to a single file on the user's disk and has properties that contain + * information about the file's size, type, name, creation date, modification date, and creator type (Macintosh only). + * + * + * FileReference instances are created in the following ways: + *
                + *
              • + * When you use the new operator with the {@link FileReference} constructor: + * let myFileReference: FileReference = new FileReference(); + *
              • + *
              • + * When you call the {@link FileReferenceList.browse} method, which creates an array of {@link FileReference} + * objects. + *
              • + *
              + * + * During a load operation, all the properties of a {@link FileReference} object are populated by calls to the + * {@link FileReference.browse} or {@link FileReferenceList.browse} methods. During a save operation, the name + * property is populated when the select event is dispatched; all other properties are populated when the complete + * event is dispatched. + * + * The {@link browse browse()} method opens an browser-system dialog box that prompts the user to select a file + * for {@link load}. The {@link FileReference.browse} method lets the user select a single file; the + * {@link FileReferenceList.browse} method lets the user select multiple files. After a successful call to the + * {@link browse browse()} method, call the {@link FileReference.load} method to load one file at a time. The + * {@link FileReference.save} method prompts the user for a location to save the file and initiates downloading from + * a binary or string data. + * + * The {@link FileReference} and {@link FileReferenceList} classes do not let you set the default file location + * for the dialog box that the {@link browse} or {@link save} methods generate. The default location shown in the + * dialog box is the most recently browsed folder, if that location can be determined, or the desktop. The classes do + * not allow you to read from or write to the transferred file. They do not allow the browser that initiated the + * {@link load} or {@link save} to access the loaded or saved file or the file's location on the user's disk. + * + * @references http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference.html + * @author Jeongho Nam + */ + class FileReference extends EventDispatcher { + /** + * @hidden + */ + private file_; + /** + * @hidden + */ + private data_; + /** + * Default Constructor. + */ + constructor(); + /** + * The data from the loaded file after a successful call to the {@link load load()} method. + * + * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), + * an {@link LogicError exception} will be thrown when you try to get the value of this property. + * + * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. + * + */ + readonly data: any; + /** + * The name of the file on the local disk. + * + * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), + * an {@link LogicError exception} will be thrown when you try to get the value of this property. + * + * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. + * + */ + readonly name: string; + /** + * The filename extension. + * + * A file's extension is the part of the name following (and not including) the final dot ("."). If + * there is no dot in the filename, the extension is null. + * + * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), + * an {@link LogicError exception} will be thrown when you try to get the value of this property. + * + * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. + * + */ + readonly extension: string; + /** + * The file type, metadata of the {@link extension}. + * + * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), + * an {@link LogicError exception} will be thrown when you try to get the value of this property. + * + * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. + * + */ + readonly type: string; + /** + * The size of the file on the local disk in bytes. + * + * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), + * an {@link LogicError exception} will be thrown when you try to get the value of this property. + * + * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. + * + */ + readonly size: number; + /** + * The date that the file on the local disk was last modified. + * + * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), + * an {@link LogicError exception} will be thrown when you try to get the value of this property. + * + * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. + * + */ + readonly modificationDate: Date; + /** + * Displays a file-browsing dialog box that lets the user select a file to upload. The dialog box is native + * to the user's browser system. The user can select a file on the local computer or from other systems, for + * example, through a UNC path on Windows. + * + * When you call this method and the user successfully selects a file, the properties of this + * {@link FileReference} object are populated with the properties of that file. Each subsequent time that the + * {@link FileReference.browse} method is called, the {@link FileReference} object's properties are reset to + * the file that the user selects in the dialog box. Only one {@link browse browse()} can be performed at a time + * (because only one dialog box can be invoked at a time). + * + * Using the *typeFilter parameter*, you can determine which files the dialog box displays. + * + * @param typeFilter An array of filter strings used to filter the files that are displayed in the dialog box. + * If you omit this parameter, all files are displayed. + */ + browse(...typeFilter: string[]): void; + /** + * Starts the load of a local file selected by a user. + * + * You must call the {@link FileReference.browse} or {@link FileReferenceList.browse} method before you call + * the {@link load load()} method. + * + * Listeners receive events to indicate the progress, success, or failure of the load. Although you can use + * the {@link FileReferenceList} object to let users select multiple files to load, you must {@link load} the + * {@link FileReferenceList files} one by one. To {@link load} the files one by one, iterate through the + * {@link FileReferenceList.fileList} array of {@link FileReference} objects. + * + * If the file finishes loading successfully, its contents are stored in the {@link data} property. + */ + load(): void; + /** + * Save a file to local filesystem. + * + * {@link FileReference.save} implemented the save function by downloading a file from a hidden anchor tag. + * However, the plan, future's {@link FileReference} will follow such rule: + * + * Opens a dialog box that lets the user save a file to the local filesystem. + * + * The {@link save save()} method first opens an browser-system dialog box that asks the user to enter a + * filename and select a location on the local computer to save the file. When the user selects a location and + * confirms the save operation (for example, by clicking Save), the save process begins. Listeners receive events + * to indicate the progress, success, or failure of the save operation. To ascertain the status of the dialog box + * and the save operation after calling {@link save save()}, your code must listen for events such as cancel, + * open, progress, and complete. + * + * When the file is saved successfully, the properties of the {@link FileReference} object are populated with + * the properties of the local file. The complete event is dispatched if the save is successful. + * + * Only one {@link browse browse()} or {@link save()} session can be performed at a time (because only one + * dialog box can be invoked at a time). + * + * @param data The data to be saved. The data can be in one of several formats, and will be treated appropriately. + * @param fileName File name to be saved. + */ + save(data: string, fileName: string): void; + /** + * Save a file to local filesystem. + * + * {@link FileReference.save} implemented the save function by downloading a file from a hidden anchor tag. + * However, the plan, future's {@link FileReference} will follow such rule: + * + * Opens a dialog box that lets the user save a file to the local filesystem. + * + * The {@link save save()} method first opens an browser-system dialog box that asks the user to enter a + * filename and select a location on the local computer to save the file. When the user selects a location and + * confirms the save operation (for example, by clicking Save), the save process begins. Listeners receive events + * to indicate the progress, success, or failure of the save operation. To ascertain the status of the dialog box + * and the save operation after calling {@link save save()}, your code must listen for events such as cancel, + * open, progress, and complete. + * + * When the file is saved successfully, the properties of the {@link FileReference} object are populated with + * the properties of the local file. The complete event is dispatched if the save is successful. + * + * Only one {@link browse browse()} or {@link save()} session can be performed at a time (because only one + * dialog box can be invoked at a time). + * + * @param data The data to be saved. The data can be in one of several formats, and will be treated appropriately. + * @param fileName File name to be saved. + */ + static save(data: string, fileName: string): void; + } + /** + * The {@link FileReferenceList} class provides a means to let users select one or more files for + * {@link FileReference.load loading}. A {@link FileReferenceList} object represents a group of one or more local + * files on the user's disk as an array of {@link FileReference} objects. For detailed information and important + * considerations about {@link FileReference} objects and the FileReference class, which you use with + * {@link FileReferenceList}, see the {@link FileReference} class. + * + * To work with the {@link FileReferenceList} class: + *
                + *
              • Instantiate the class: var myFileRef = new FileReferenceList();
              • + *
              • + * Call the {@link FileReferenceList.browse} method, which opens a dialog box that lets the user select one or + * more files for upload: myFileRef.browse(); + *
              • + *
              • + * After the {@link browse browse()} method is called successfully, the {@link fileList} property of the + * {@link FileReferenceList} object is populated with an array of {@link FileReference} objects. + *
              • + *
              • Call {@link FileReference.load} on each element in the {@link fileList} array.
              • + *
              + * + * The {@link FileReferenceList} class includes a {@link browse browse()} method and a {@link fileList} property + * for working with multiple files. + * + * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReferenceList.html + * @author Jeongho Nam + */ + class FileReferenceList extends EventDispatcher { + /** + * @hidden + */ + file_list: std.Vector; + /** + * Default Constructor. + */ + constructor(); + /** + * An array of {@link FileReference} objects. + * + * When the {@link FileReferenceList.browse} method is called and the user has selected one or more files + * from the dialog box that the {@link browse browse()} method opens, this property is populated with an array of + * {@link FileReference} objects, each of which represents the files the user selected. + * + * The {@link fileList} property is populated anew each time {@link browse browse()} is called on that + * {@link FileReferenceList} object. + */ + readonly fileList: std.Vector; + /** + * Displays a file-browsing dialog box that lets the user select one or more local files to upload. The + * dialog box is native to the user's browser system. + * + * When you call this method and the user successfully selects files, the {@link fileList} property of this + * {@link FileReferenceList} object is populated with an array of {@link FileReference} objects, one for each + * file that the user selects. Each subsequent time that the {@link FileReferenceList.browse} method is called, + * the {@link FileReferenceList.fileList} property is reset to the file(s) that the user selects in the dialog + * box. + * + * Using the *typeFilter* parameter, you can determine which files the dialog box displays. + * + * Only one {@link FileReference.browse}, {@link FileReference.load}, or {@link FileReferenceList.browse} + * session can be performed at a time on a {@link FileReferenceList} object (because only one dialog box can be + * opened at a time). + * + * @param typeFilter An array of filter strings used to filter the files that are displayed in the dialog box. + * If you omit this parameter, all files are displayed. + */ + browse(...typeFilter: string[]): void; + } +} +declare namespace samchon.library { + /** + * A genetic algorithm class. + * + * In the field of artificial intelligence, a genetic algorithm (GA) is a search heuristic that mimics the + * process of natural selection. This heuristic (also sometimes called a metaheuristic) is routinely used to generate + * useful solutions to optimization and search problems. + * + * Genetic algorithms belong to the larger class of evolutionary algorithms (EA), which generate solutions to + * optimization problems using techniques inspired by natural evolution, such as inheritance, {@link mutate mutation}, + * {@link selection}, and {@link crossover}. + * + * @reference https://en.wikipedia.org/wiki/Genetic_algorithm + * @author Jeongho Nam + */ + class GeneticAlgorithm { + /** + * Whether each element (Gene) is unique in their GeneArray. + */ + private unique_; + /** + * Rate of mutation. + * + * The {@link mutation_rate} determines the percentage of occurence of mutation in GeneArray. + * + *
                + *
              • When {@link mutation_rate} is too high, it is hard to ancitipate studying on genetic algorithm.
              • + *
              • + * When {@link mutation_rate} is too low and initial set of genes (GeneArray) is far away from optimal, the + * evolution tends to wandering outside of he optimal. + *
              • + *
              + */ + private mutation_rate_; + /** + * Number of tournaments in selection. + */ + private tournament_; + /** + * Initialization Constructor. + * + * @param unique Whether each Gene is unique in their GeneArray. + * @param mutation_rate Rate of mutation. + * @param tournament Number of tournaments in selection. + */ + constructor(unique?: boolean, mutation_rate?: number, tournament?: number); + /** + * Evolove *GeneArray*. + * + * Convenient method accessing to {@link evolvePopulation evolvePopulation()}. + * + * @param individual An initial set of genes; sequence listing. + * @param population Size of population in a generation. + * @param generation Size of generation in evolution. + * @param compare A comparison function returns whether left gene is more optimal. + * + * @return An evolved *GeneArray*, optimally. + * + * @see {@link GAPopulation.compare} + */ + evolveGeneArray>(individual: GeneArray, population: number, generation: number, compare?: (left: T, right: T) => boolean): GeneArray; + /** + * Evolve *population*, a mass of *GeneArraies*. + * + * @param population An initial population. + * @param compare A comparison function returns whether left gene is more optimal. + * + * @return An evolved population. + * + * @see {@link GAPopulation.compare} + */ + evolvePopulation>(population: GAPopulation, compare?: (left: T, right: T) => boolean): GAPopulation; + /** + * Select the best GeneArray in *population* from tournament. + * + * {@link selection Selection} is the stage of a genetic algorithm in which individual genomes are chosen + * from a population for later breeding (using {@linlk crossover} operator). A generic {@link selection} + * procedure may be implemented as follows: + * + *
                + *
              1. + * The fitness function is evaluated for each individual, providing fitness values, which are then + * normalized. ization means dividing the fitness value of each individual by the sum of all fitness + * values, so that the sum of all resulting fitness values equals 1. + *
              2. + *
              3. The population is sorted by descending fitness values.
              4. + *
              5. + * Accumulated normalized fitness values are computed (the accumulated fitness value of an individual is the + * sum of its own fitness value plus the fitness values of all the previous individuals). The accumulated + * fitness of the last individual should be 1 (otherwise something went wrong in the normalization step). + *
              6. + *
              7. A random number R between 0 and 1 is chosen.
              8. + *
              9. The selected individual is the first one whose accumulated normalized value is greater than R.
              10. + *
              + * + * @param population The target of tournament. + * @return The best genes derived by the tournament. + * + * @reference https://en.wikipedia.org/wiki/Selection_(genetic_algorithm) + */ + private selection(population); + /** + * Create a new GeneArray by crossing over two *GeneArray*(s). + * + * {@link crossover} is a genetic operator used to vary the programming of a chromosome or chromosomes from + * one generation to the next. It is analogous to reproduction and biological crossover, upon which genetic + * algorithms are based. + * + * {@link crossover Cross over} is a process of taking more than one parent solutions and producing a child + * solution from them. There are methods for selection of the chromosomes. + * + * @param parent1 A parent sequence listing + * @param parent2 A parent sequence listing + * + * @reference https://en.wikipedia.org/wiki/Crossover_(genetic_algorithm) + */ + private crossover(parent1, parent2); + /** + * Cause a mutation on the *GeneArray*. + * + * {@link mutate Mutation} is a genetic operator used to maintain genetic diversity from one generation of a + * population of genetic algorithm chromosomes to the next. It is analogous to biological mutation. + * + * {@link mutate Mutation} alters one or more gene values in a chromosome from its initial state. In + * {@link mutate mutation}, the solution may change entirely from the previous solution. Hence GA can come to + * better solution by using {@link mutate mutation}. + * + * {@link mutate Mutation} occurs during evolution according to a user-definable mutation probability. This + * probability should be set low. If it is set too high, the search will turn into a primitive random search. + * + *

              Note

              + * Muttion is pursuing diversity. Mutation is useful for avoiding the following problem. + * + * When initial set of genes(GeneArray) is far away from optimail, without mutation (only with selection and + * crossover), the genetic algorithm has a tend to wandering outside of the optimal. + * + * Genes in the GeneArray will be swapped following percentage of the {@link mutation_rate}. + * + * @param individual A container of genes to mutate + * + * @reference https://en.wikipedia.org/wiki/Mutation_(genetic_algorithm) + * @see {@link mutation_rate} + */ + private mutate(individual); + } + /** + * A population in a generation. + * + * {@link GAPopulation} is a class representing population of candidate genes (sequence listing) having an array + * of GeneArray as a member. {@link GAPopulation} also manages initial set of genes and handles fitting test direclty + * by the method {@link fitTest fitTest()}. + * + * The success of evolution of genetic algorithm is depend on the {@link GAPopulation}'s initial set and fitting + * test. (*GeneArray* and {@link compare}.) + * + *

              Warning

              + * Be careful for the mistakes of direction or position of the {@link compare}. + * Most of logical errors failed to access optimal solution are occured from those mistakes. + * + * @param Type of gene elements. + * @param An array containing genes as elments; sequnce listing. + * + * @author Jeongho Nam + */ + class GAPopulation> { + /** + * Genes representing the population. + */ + private children_; + /** + * A comparison function returns whether left gene is more optimal, greater. + * + * Default value of this {@link compare} is {@link std.greater}. It means to compare two array + * (GeneArray must be a type of {@link std.base.IArrayContainer}). Thus, you've to keep follwing rule. + * + *
                + *
              • GeneArray is implemented from {@link std.base.IArrayContainer}.
              • + *
                  + *
                • {@link std.Vector}
                • + *
                • {@link std.Deque}
                • + *
                + *
              • GeneArray has custom public less(obj: T): boolean; function.
              • + *
              + * + * If you don't want to follow the rule or want a custom comparison function, you have to realize a + * comparison function. + */ + private compare_; + /** + * Private constructor with population. + * + * Private constructor of GAPopulation does not create {@link children}. (candidate genes) but only assigns + * *null* repeatedly following the *population size*. + * + * This private constructor is designed only for {@link GeneticAlgorithm}. Don't create {@link GAPopulation} + * with this constructor, by yourself. + * + * @param size Size of the population. + */ + constructor(size: number); + /** + * Construct from a {@link GeneArray} and *size of the population*. + * + * This public constructor creates *GeneArray(s)* as population (size) having shuffled genes which are + * came from the initial set of genes (*geneArray*). It uses {@link std.greater} as default comparison function. + * + * + * @param geneArray An initial sequence listing. + * @param size The size of population to have as children. + */ + constructor(geneArray: GeneArray, size: number); + /** + * Constructor from a GeneArray, size of the poluation and custom comparison function. + * + * This public constructor creates *GeneArray(s)* as population (size) having shuffled genes which are + * came from the initial set of genes (*geneArray*). The *compare* is used for comparison function. + * + * + * @param geneArray An initial sequence listing. + * @param size The size of population to have as children. + * @param compare A comparison function returns whether left gene is more optimal. + */ + constructor(geneArray: GeneArray, size: number, compare: (left: GeneArray, right: GeneArray) => boolean); + children(): std.Vector; + /** + * Test fitness of each *GeneArray* in the {@link population}. + * + * @return The best *GeneArray* in the {@link population}. + */ + fitTest(): GeneArray; + /** + * @hidden + */ + private clone(obj); + } +} +declare namespace samchon.library { + /** + * A utility class supporting static methods of string. + * + * The {@link StringUtil} utility class is an all-static class with methods for working with string objects. + * You do not create instances of {@link StringUtil}; instead you call methods such as the + * ```StringUtil.substitute()``` method. + * + * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/utils/StringUtil.html + * @author Jeongho Nam + */ + class StringUtil { + /** + * Generate a substring. + * + * Extracts a substring consisting of the characters from specified start to end. + * It's same with str.substring( ? = (str.find(start) + start.size()), str.find(end, ?) ) + * + * ```typescript + * let str: string = StringUtil.between("ABCD(EFGH)IJK", "(", ")"); + * console.log(str); // PRINTS "EFGH" + * ``` + * + * - If start is not specified, extracts from begin of the string to end. + * - If end is not specified, extracts from start to end of the string. + * - If start and end are all omitted, returns str, itself. + * + * @param str Target string to be applied between. + * @param start A string for separating substring at the front. + * @param end A string for separating substring at the end. + * + * @return substring by specified terms. + */ + static between(str: string, start?: string, end?: string): string; + /** + * Fetch substrings. + * + * Splits a string into an array of substrings dividing by specified delimeters of start and end. + * It's the array of substrings adjusted the between. + * + *
                + *
              • If startStr is omitted, it's same with the split by endStr not having last item.
              • + *
              • If endStr is omitted, it's same with the split by startStr not having first item.
              • + *
              • If startStr and endStar are all omitted, returns *str*.
              • + *
              + * + * @param str Target string to split by between. + * @param start A string for separating substring at the front. + * If omitted, it's same with split(end) not having last item. + * @param end A string for separating substring at the end. + * If omitted, it's same with split(start) not having first item. + * @return An array of substrings. + */ + static betweens(str: string, start?: string, end?: string): Array; + /** + * An array containing whitespaces. + */ + private static SPACE_ARRAY; + /** + * Remove all designated characters from the beginning and end of the specified string. + * + * @param str The string whose designated characters should be trimmed. + * @param args Designated character(s). + * + * @return Updated string where designated characters was removed from the beginning and end. + */ + static trim(str: string, ...args: string[]): string; + /** + * Remove all designated characters from the beginning of the specified string. + * + * @param str The string should be trimmed. + * @param delims Designated character(s). + * + * @return Updated string where designated characters was removed from the beginning + */ + static ltrim(str: string, ...args: string[]): string; + /** + * Remove all designated characters from the end of the specified string. + * + * @param str The string should be trimmed. + * @param delims Designated character(s). + * + * @return Updated string where designated characters was removed from the end. + */ + static rtrim(str: string, ...args: string[]): string; + /** + * Substitute `{n}` tokens within the specified string. + * + * @param format The string to make substitutions in. This string can contain special tokens of the form + * `{n}`, where *n* is a zero based index, that will be replaced with the additional parameters + * found at that index if specified. + * @param args Additional parameters that can be substituted in the *format* parameter at each + * `{n}` location, where *n* is an integer (zero based) index value into the array of values + * specified. + * + * @return New string with all of the `{n}` tokens replaced with the respective arguments specified. + */ + static substitute(format: string, ...args: any[]): string; + /** + * Substitute `{n}` tokens within the specified SQL-string. + * + * @param format The string to make substitutions in. This string can contain special tokens of the form + * `{n}`, where *n* is a zero based index, that will be replaced with the additional parameters + * found at that index if specified. + * @param args Additional parameters that can be substituted in the *format* parameter at each + * `{n}` location, where *n* is an integer (zero based) index value into the array of values + * specified. + * + * @return New SQL-string with all of the `{n}` tokens replaced with the respective arguments specified. + */ + static substituteSQL(format: string, ...args: any[]): string; + /** + * @hidden + */ + private static _Fetch_substitute_index(format); + /** + * Returns a string specified word is replaced. + * + * @param str Target string to replace + * @param before Specific word you want to be replaced + * @param after Specific word you want to replace + * + * @return A string specified word is replaced + */ + static replaceAll(str: string, before: string, after: string): string; + /** + * Returns a string specified words are replaced. + * + * @param str Target string to replace + * @param pairs A specific word's pairs you want to replace and to be replaced + * + * @return A string specified words are replaced + */ + static replaceAll(str: string, ...pairs: std.Pair[]): string; + /** + * Replace all HTML spaces to a literal space. + * + * @param str Target string to replace. + */ + static removeHTMLSpaces(str: string): string; + /** + * Repeat a string. + * + * Returns a string consisting of a specified string concatenated with itself a specified number of times. + * + * @param str The string to be repeated. + * @param n The repeat count. + * + * @return The repeated string. + */ + static repeat(str: string, n: number): string; + /** + * Number to formatted string with "," sign. + * + * Returns a string converted from the number rounded off from specified precision with "," symbols. + * + * @param val A number wants to convert to string. + * @param precision Target precision of round off. + * + * @return A string who represents the number with roundoff and "," symbols. + */ + static numberFormat(val: number, precision?: number): string; + static percentFormat(val: number, precision?: number): string; + } +} +declare namespace samchon.library { + /** + * URLVariables class is for representing variables of HTTP. + * + * {@link URLVariables} class allows you to transfer variables between an application and server. + * + * When transfering, {@link URLVariables} will be converted to a *URI* string. + * - URI: Uniform Resource Identifier + * + * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLVariables.html + * @author Migrated by Jeongho Nam + */ + class URLVariables extends std.HashMap { + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from a URL-encoded string. + * + * The {@link decode decode()} method is automatically called to convert the string to properties of the {@link URLVariables} object. + * + * @param str A URL-encoded string containing name/value pairs. + */ + constructor(str: string); + /** + * Converts the variable string to properties of the specified URLVariables object. + * + * @param str A URL-encoded query string containing name/value pairs. + */ + decode(str: string): void; + /** + * Returns a string containing all enumerable variables, in the MIME content encoding application/x-www-form-urlencoded. + */ + toString(): string; + } +} +declare namespace samchon.library { + /** + * A tree-structured XML object. + * + * The {@link XML| class contains methods and properties for working with XML objects. The {@link XML} class (along + * with the {@link XMLList}) implements the powerful XML-handling standards defined in ECMAScript for XML (E4X) + * specification (ECMA-357 edition 2). + * + * An XML object, it is composed with three members; {@link getTag tag}, {@link getProperty properties} and + * {@link getValue value}. As you know, XML is a tree structured data expression method. The tree-stucture; + * {@link XML} class realizes it by extending ```std.HashMap```. Child {@link XML} objects are + * contained in the matched {@link XMLList} object being grouped by their {@link getTag tag name}. The + * {@link XMLList} objects, they're stored in the {@link std.HashMap} ({@link XML} itself) with its **key**; common + * {@link getTag tag name} of children {@link XML} objects. + * + * ```typescript + * class XML extends std.HashMap + * { + * private tag_: string; + * private properties_: std.HashMap; + * private value_: string; + * } + * ``` + * + * ```xml + * + * + * + * {value} + * {value} + * {value} + * + * + * + * + * ``` + * + * Use the {@link toString toString()} method to return a string representation of the {@link XML} object regardless + * of whether the {@link XML} object has simple content or complex content. + * + * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/XML.html + * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-XML + * @author Jeongho Nam + */ + class XML extends std.HashMap { + /** + * @hidden + */ + private tag_; + /** + * @hidden + */ + private value_; + /** + * @hidden + */ + private property_map_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from string. + * + * Creates {@link XML} object by parsing a string who represents xml structure. + * + * @param str A string represents XML structure. + */ + constructor(str: string); + /** + * @hidden + */ + private _Parse(str); + /** + * @hidden + */ + private _Parse_tag(str); + /** + * @hidden + */ + private _Parse_properties(str); + /** + * @hidden + */ + private _Parse_value(str); + /** + * @hidden + */ + private _Parse_children(str); + /** + * Get tag. + * + * ```xml + * {value} + * ``` + * + * @return tag. + */ + getTag(): string; + /** + * Get value. + * + * ```xml + * {VALUE} + * ``` + * + * @return value. + */ + getValue(): string; + /** + * Get iterator to property element. + * + * Searches the {@link getPropertyMap properties} for an element with a identifier equivalent to key + * and returns an iterator to it if found, otherwise it returns an iterator to {@link HashMap.end end()}. + * + *

              Two keys are considered equivalent if the properties' comparison object returns false reflexively + * (i.e., no matter the order in which the elements are passed as arguments).

              + * + * Another member function, {@link hasProperty hasProperty()} can be used to just check whether a particular + * key exists. + * + * ```xml + * {value} + * ``` + * + * @param key Key to be searched for + * @return An iterator to the element, if an element with specified key is found, or + * {@link end HashMap.end()} otherwise. + */ + findProperty(key: string): std.MapIterator; + /** + * Test whether a property exists. + * + * ```xml + * {value} + * ``` + * + * @return Whether a property has the *key* exists or not. + */ + hasProperty(key: string): boolean; + /** + * Get property. + * + * Get property by its *key*, property name. If the matched *key* does not exist, then exception + * {@link std.OutOfRange} is thrown. Thus, it would better to test whether the *key* exits or not by calling the + * {@link hasProperty hasProperty()} method before calling this {@link getProperty getProperty()}. + * + * This method can be substituted by {@link getPropertyMap getPropertyMap()} such below: + * - ```getPropertyMap().get(key, value);``` + * - ```getPropertyMap().find(key).second;``` + * + * ```xml + * {value} + * ``` + * + * @return Value of the matched property. + */ + getProperty(key: string): string; + /** + * Get property map. + * + * ```xml + * {value} + * ``` + * + * @return {@link HashMap} containing properties' keys and values. + */ + getPropertyMap(): std.HashMap; + /** + * Set tag. + * + * Set tag name, identifier of this {@link XML} object. + * + * If this {@link XML} object is belonged to, a child of, an {@link XMLList} and its related {@link XML} objects, + * then calling this {@link setTag setTag()} method direclty is not recommended. Erase this {@link XML} object + * from parent objects and insert this object again. + * + * ```xml + * {value} + * ``` + * + * @param val To be new {@link getTag tag}. + */ + setTag(val: string): void; + /** + * Set value. + * + * ```xml + * {VALUE} + * ``` + * + * @param val To be new {@link getValue value}. + */ + setValue(val: string): void; + /** + * Set property. + * + * Set a property *value* with its *key*. If the *key* already exists, then the *value* will be overwritten to + * the property. Otherwise the *key* is not exist yet, then insert the *key* and *value* {@link Pair pair} to + * {@link getPropertyMao property map}. + * + * This method can be substituted by {@link getPropertyMap getPropertyMap()} such below: + * - ```getPropertyMap().set(key, value);``` + * - ```getPropertyMap().emplace(key, value);``` + * - ```getPropertyMap().insert([key, value]);``` + * - ```getPropertyMap().insert(std.make_pair(key, value));``` + * + * ```xml + * {value} + * ``` + * + * @param key Key, identifier of property to be newly inserted. + * @param value Value of new property to be newly inserted. + */ + setProperty(key: string, value: string): void; + /** + * Erase property. + * + * Erases a property by its *key*, property name. If the matched *key* does not exist, then exception + * {@link std.OutOfRange} is thrown. Thus, it would better to test whether the *key* exits or not by calling the + * {@link hasProperty hasProperty()} method before calling this {@link eraseProperty eraseProperty()}. + * + * This method can be substituted by ``getPropertyMap().erase(key)````. + * + * ```xml + * {value} + * ``` + * + * @param key Key of the property to erase + * @throw {@link std.OutOfRange} + */ + eraseProperty(key: string): void; + /** + * @hidden + */ + push(...args: std.Pair[]): number; + /** + * @hidden + */ + push(...args: [string, XMLList][]): number; + push(...xmls: XML[]): number; + push(...xmlLists: XMLList[]): number; + /** + * Add all properties from other {@link XML} object. + * + * All the properties in the *obj* are copied to this {@link XML} object. If this {@link XML} object has same + * property key in the *obj*, then value of the property will be replaced to *obj*'s own. If you don't want to + * overwrite properties with same key, then use {@link getPropertyMap getPropertyMap()} method. + * + * ```typescript + * let x: library.XML; + * let y: library.XML; + * + * x.addAllProperties(y); // duplicated key exists, then overwrites + * x.getPropertyMap().insert(y.getPropertyMap().begin(), y.getPropertyMap().end()); + * // ducpliated key, then ignores. only non-duplicateds are copied. + * ``` + * + * ```xml + * {value} + * ``` + * + * @param obj Target {@link XML} object to copy properties. + */ + insertAllProperties(obj: XML): void; + /** + * Clear properties. + * + * Remove all properties. It's same with calling ```getPropertyMap().clear()```. + * + * ```xml + * {value} + * ``` + */ + clearProperties(): void; + /** + * @hidden + */ + private _Compute_min_index(...args); + /** + * @hidden + */ + private _Decode_value(str); + /** + * @hidden + */ + private _Encode_value(str); + /** + * @hidden + */ + private _Decode_property(str); + /** + * @hidden + */ + private _Encode_property(str); + /** + * {@link XML} object to xml string. + * + * Returns a string representation of the {@link XML} object. + * + * @param tab Number of tabs to spacing. + * @return The string representation of the {@link XML} object. + */ + toString(tab?: number): string; + } +} +declare namespace samchon.library { + /** + * List of {@link XML} objects with same tag. + * + * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/XMLList.html + * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-XML + * @author Jeongho Nam + */ + class XMLList extends std.Deque { + /** + * Get tag. + */ + getTag(): string; + /** + * {@link XMLList XML objects} to string. + * + * Returns a string representation of the {@link XMLList XML objects}. + * + * @param tab Number of tabs to spacing. + * @return The string representation of the {@link XMLList XML objects}. + */ + toString(level?: number): string; + } +} +declare namespace samchon.protocol { + /** + * An interface of entity. + * + * Entity is a class for standardization of expression method using on network I/O by XML. If + * Invoke is a standard message protocol of Samchon Framework which must be kept, Entity is a + * recommended semi-protocol of message for expressing a data class. Following the semi-protocol + * Entity is not imposed but encouraged. + * + * As we could get advantages from standardization of message for network I/O with Invoke, + * we can get additional advantage from standardizing expression method of data class with Entity. + * We do not need to know a part of network communication. Thus, with the Entity, we can only + * concentrate on entity's own logics and relationships between another entities. Entity does not + * need to how network communications are being done. + * + * I say repeatedly. Expression method of Entity is recommended, but not imposed. It's a semi + * protocol for network I/O but not a essential protocol must be kept. The expression method of + * Entity, using on network I/O, is expressed by XML string. + * + * If your own network system has a critical performance issue on communication data class, + * it would be better to using binary communication (with ByteArray). + * Don't worry about the problem! Invoke also provides methods for binary data (ByteArray). + * + * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) + * + * @author Jeongho Nam + */ + interface IEntity { + /** + * Construct data of the Entity from a XML object. + * + * Overrides the construct() method and fetch data of member variables from the XML. + * + * By recommended guidance, data representing member variables are contained in properties + * of the put XML object. + * + * @param xml An xml used to contruct data of entity. + */ + construct(xml: library.XML): void; + /** + * Get a key that can identify the Entity uniquely. + * + * If identifier of the Entity is not atomic value, returns a paired or tuple object + * that can represents the composite identifier. + * + * + * class Point extends Entity + * { + * private x: number; + * private y: number; + * + * public key(): std.Pair + * { + * return std.make_pair(this.x, this.y); + * } + * } + * + */ + key(): any; + /** + * A tag name when represented by XML. + * + * + */ + TAG(): string; + /** + * Get a XML object represents the Entity. + * + * A member variable (not object, but atomic value like number, string or date) is categorized + * as a property within the framework of entity side. Thus, when overriding a toXML() method and + * archiving member variables to an XML object to return, puts each variable to be a property + * belongs to only a XML object. + * + * Don't archive the member variable of atomic value to XML::value causing enormouse creation + * of XML objects to number of member variables. An Entity must be represented by only a XML + * instance (tag). + * + *

              Standard Usage.

              + * + * + * + * + * + * + * + *

              Non-standard usage abusing value.

              + * + * + * jhnam88 + * Jeongho Nam + * 1988-03-11 + * + * + * master + * Administartor + * 2011-07-28 + * + * + * + * @return An XML object representing the Entity. + */ + toXML(): library.XML; + } + /** + * @hidden + */ + namespace IEntity { + function construct(entity: IEntity, xml: library.XML, ...prohibited_names: string[]): void; + function toXML(entity: IEntity, ...prohibited_names: string[]): library.XML; + } + /** + * An entity, a standard data class. + * + * Entity is a class for standardization of expression method using on network I/O by XML. If + * Invoke is a standard message protocol of Samchon Framework which must be kept, Entity is a + * recommended semi-protocol of message for expressing a data class. Following the semi-protocol + * Entity is not imposed but encouraged. + * + * As we could get advantages from standardization of message for network I/O with Invoke, + * we can get additional advantage from standardizing expression method of data class with Entity. + * We do not need to know a part of network communication. Thus, with the Entity, we can only + * concentrate on entity's own logics and relationships between another entities. Entity does not + * need to how network communications are being done. + * + * I say repeatedly. Expression method of Entity is recommended, but not imposed. It's a semi + * protocol for network I/O but not a essential protocol must be kept. The expression method of + * Entity, using on network I/O, is expressed by XML string. + * + * If your own network system has a critical performance issue on communication data class, + * it would be better to using binary communication (with ByteArray). + * Don't worry about the problem! Invoke also provides methods for binary data (ByteArray). + * + * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) + * + * @author Jeongho Nam + */ + abstract class Entity implements IEntity { + /** + * Default Constructor. + */ + constructor(); + construct(xml: library.XML): void; + /** + * @inheritdoc + */ + key(): any; + /** + * @inheritdoc + */ + abstract TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + * @inheritdoc + */ + interface IEntityCollection extends IEntityGroup, collections.ICollection { + } +} +declare namespace samchon.protocol { + /** + * @inheritdoc + */ + abstract class EntityArrayCollection extends collections.ArrayCollection implements IEntityCollection { + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * @inheritdoc + */ + abstract createChild(xml: library.XML): T; + /** + * @inheritdoc + */ + key(): any; + /** + * @inheritdoc + */ + has(key: any): boolean; + /** + * @inheritdoc + */ + count(key: any): number; + /** + * @inheritdoc + */ + get(key: any): T; + /** + * @inheritdoc + */ + abstract TAG(): string; + /** + * @inheritdoc + */ + abstract CHILD_TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + * @inheritdoc + */ + abstract class EntityListCollection extends collections.ListCollection implements IEntityCollection { + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * @inheritdoc + */ + abstract createChild(xml: library.XML): T; + /** + * @inheritdoc + */ + key(): any; + /** + * @inheritdoc + */ + has(key: any): boolean; + /** + * @inheritdoc + */ + count(key: any): number; + /** + * @inheritdoc + */ + get(key: any): T; + /** + * @inheritdoc + */ + abstract TAG(): string; + /** + * @inheritdoc + */ + abstract CHILD_TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + * @inheritdoc + */ + abstract class EntityDequeCollection extends collections.DequeCollection implements IEntityCollection { + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * @inheritdoc + */ + abstract createChild(xml: library.XML): T; + /** + * @inheritdoc + */ + key(): any; + /** + * @inheritdoc + */ + has(key: any): boolean; + /** + * @inheritdoc + */ + count(key: any): number; + /** + * @inheritdoc + */ + get(key: any): T; + /** + * @inheritdoc + */ + abstract TAG(): string; + /** + * @inheritdoc + */ + abstract CHILD_TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +/** + * A template for External Systems Manager. + * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @author Jeongho Nam + */ +declare namespace samchon.templates.external { + /** + * An array and manager of {@link ExternalSystem external system drivers}. + * + * The {@link ExternalSystemArray} is an abstract class containing and managing external system drivers, + * {@link ExternalSystem} objects. Within framewokr of network, {@link ExternalSystemArray} represents your system + * and children {@link ExternalSystem} objects represent remote, external systems connected with your system. + * With this {@link ExternalSystemArray}, you can manage multiple external systems as a group. + * + * You can specify this {@link ExternalSystemArray} class to be *a server accepting external clients* or + * *a client connecting to external servers*. Even both of them is also possible. + * + * - {@link ExternalClientArray}: A server accepting {@link ExternalSystem external clients}. + * - {@link ExternalServerArray}: A client connecting to {@link ExternalServer external servers}. + * - {@link ExternalServerClientArray}: Both of them. Accepts {@link ExternalSystem external clients} and connects to + * {@link ExternalServer external servers} at the same time. + * + * + * + * + * + * #### Proxy Pattern + * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which + * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not + * important. Only interested in user's perspective is *which can be done*. + * + * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. + * + *
                + *
              • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
              • + *
              • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
              • + *
              • Those strategy is called *Proxy Pattern*.
              • + *
              + * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @author Jeongho Nam + */ + abstract class ExternalSystemArray extends protocol.EntityDequeCollection implements protocol.IProtocol { + /** + * Default Constructor. + */ + constructor(); + /** + * @hidden + */ + private _Handle_system_erase(event); + /** + * Test whether the role exists. + * + * @param name Name, identifier of target {@link ExternalSystemRole role}. + * + * @return Whether the role has or not. + */ + hasRole(name: string): boolean; + /** + * Get a role. + * + * @param name Name, identifier of target {@link ExternalSystemRole role}. + * + * @return The specified role. + */ + getRole(name: string): ExternalSystemRole; + /** + * Send an {@link Invoke} message. + * + * @param invoke An {@link Invoke} message to send. + */ + sendData(invoke: protocol.Invoke): void; + /** + * Handle an {@Invoke} message have received. + * + * @param invoke An {@link Invoke} message have received. + */ + abstract replyData(invoke: protocol.Invoke): void; + /** + * Tag name of the {@link ExternalSytemArray} in {@link XML}. + * + * @return *systemArray*. + */ + TAG(): string; + /** + * Tag name of {@link ExternalSystem children elements} belonged to the {@link ExternalSytemArray} in {@link XML}. + * + * @return *system*. + */ + CHILD_TAG(): string; + } +} +/** + * A template for Parallel Processing System. + * + * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) + * @author Jeongho Nam + */ +declare namespace samchon.templates.parallel { + /** + * Master of Parallel Processing System. + * + * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system + * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your + * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to **slave** systems and the + * children {@link ParallelSystem} objects represent the remote **slave** systems, who is being requested the + * *parallel processes*. + * + * You can specify this {@link ParallelSystemArray} class to be *a server accepting parallel clients* or + * *a client connecting to parallel servers*. Even both of them is possible. Extends one of them below and overrides + * abstract factory method(s) creating the child {@link ParallelSystem} object. + * + * - {@link ParallelClientArray}: A server accepting {@link ParallelSystem parallel clients}. + * - {@link ParallelServerArray}: A client connecting to {@link ParallelServer parallel servers}. + * - {@link ParallelServerClientArray}: Both of them. Accepts {@link ParallelSystem parallel clients} and connects to + * {@link ParallelServer parallel servers} at the same time. + * + * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. + * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s + * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices + * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. + * + * + * + * + * + * #### Proxy Pattern + * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take + * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the + * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it + * may better to utilizing the *Proxy Pattern*: + * + * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which + * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not + * important. Only interested in user's perspective is *which can be done*. + * + * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. + * + *
                + *
              • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
              • + *
              • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
              • + *
              • Those strategy is called *Proxy Pattern*.
              • + *
              + * + * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) + * @author Jeongho Nam + */ + abstract class ParallelSystemArray extends external.ExternalSystemArray { + /** + * @hidden + */ + private history_sequence_; + /** + * Default Constructor. + */ + constructor(); + /** + * Send an {@link Invoke} message with segment size. + * + * Sends an {@link Invoke} message requesting a **parallel process** with its *segment size*. The {@link Invoke} + * message will be delivered to children {@link ParallelSystem} objects with the *piece size*, which is divided + * from the *segment size*, basis on their {@link ParallelSystem.getPerformance performance indices}. + * + * - If segment size is 100, + * - The segment will be allocated such below: + * + * Name | Performance index | Number of pieces to be allocated | Formula + * --------|-------------------|----------------------------------|-------------- + * Snail | 1 | 10 | 100 / 10 * 1 + * Cheetah | 4 | 40 | 100 / 10 * 4 + * Rabbit | 3 | 30 | 100 / 10 * 3 + * Turtle | 2 | 20 | 100 / 10 * 2 + * + * When the **parallel process** has completed, then this {@link ParallelSystemArraY} will estimate + * {@link ParallelSystem.getPerformance performance indices} of {@link ParallelSystem} objects basis on their + * execution time. + * + * @param invoke An {@link Invoke} message requesting parallel process. + * @param size Number of pieces to segment. + * + * @return Number of {@link ParallelSystem slave systems} participating in the *Parallel Process*. + * + * @see {@link sendPieceData}, {@link ParallelSystem.getPerformacen} + */ + sendSegmentData(invoke: protocol.Invoke, size: number): number; + /** + * Send an {@link Invoke} message with range of pieces. + * + * Sends an {@link Invoke} message requesting a **parallel process** with its *range of pieces [first, last)*. + * The {@link Invoke} will be delivered to children {@link ParallelSystem} objects with the newly computed + * *range of sub-pieces*, which is divided from the *range of pieces (first to last)*, basis on their + * {@link ParallelSystem.getPerformance performance indices}. + * + * - If indices of pieces are 0 to 50, + * - The sub-pieces will be allocated such below: + * + * Name | Performance index | Range of sub-pieces to be allocated | Formula + * --------|-------------------|-------------------------------------|------------------------ + * Snail | 1 | ( 0, 5] | (50 - 0) / 10 * 1 + * Cheetah | 4 | ( 5, 25] | (50 - 0) / 10 * 4 + 5 + * Rabbit | 3 | (25, 40] | (50 - 0) / 10 * 3 + 25 + * Turtle | 2 | (40, 50] | (50 - 0) / 10 * 2 + 40 + * + * When the **parallel process** has completed, then this {@link ParallelSystemArraY} will estimate + * {@link ParallelSystem.getPerformance performance indices} of {@link ParallelSystem} objects basis on their + * execution time. + * + * @param invoke An {@link Invoke} message requesting parallel process. + * @param first Initial piece's index in a section. + * @param last Final piece's index in a section. The range used is [*first*, *last*), which contains + * all the pieces' indices between *first* and *last*, including the piece pointed by index + * *first*, but not the piece pointed by the index *last*. + * + * @return Number of {@link ParallelSystem slave systems} participating in the *Parallel Process*. + * + * @see {@link sendSegmentData}, {@link ParallelSystem.getPerformacen} + */ + sendPieceData(invoke: protocol.Invoke, first: number, last: number): number; + /** + * @hidden + */ + protected _Complete_history(history: slave.InvokeHistory): boolean; + /** + * @hidden + */ + protected _Normalize_performance(): void; + } +} +/** + * A template for Distributed Processing System. + * + * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) + * @author Jeongho Nam + */ +declare namespace samchon.templates.distributed { + /** + * Master of Distributed Processing System. + * + * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system + * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents + * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** + * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being + * requested the *distributed processes*. + * + * You can specify this {@link DistributedSystemArray} class to be *a server accepting distributed clients* or + * *a client connecting to distributed servers*. Even both of them is possible. Extends one of them below and overrides + * abstract factory method(s) creating the child {@link DistributedSystem} object. + * + * - {@link DistributedClientArray}: A server accepting {@link DistributedSystem distributed clients}. + * - {@link DistributedServerArray}: A client connecting to {@link DistributedServer distributed servers}. + * - {@link DistributedServerClientArray}: Both of them. Accepts {@link DistributedSystem distributed clients} and + * connects to {@link DistributedServer distributed servers} at the same time. + * + * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a + * **distributed process** through the {@link DistributedProcess} object. You can access the + * {@link DistributedProcess} object(s) with those methods: + * + * - {@link hasProcess} + * - {@link getProcess} + * - {@link insertProcess} + * - {@link eraseProcess} + * - {@link getProcessMap} + * + * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the + * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed + * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When + * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and + * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. + * + * + * + * + * + * #### Parallel Process + * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request + * a **parallel process**, too. + * + * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. + * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s + * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will + * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. + * + * #### Proxy Pattern + * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take + * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the + * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it + * may better to utilizing the *Proxy Pattern*: + * + * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which + * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not + * important. Only interested in user's perspective is *which can be done*. + * + * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. + * + *
                + *
              • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
              • + *
              • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
              • + *
              • Those strategy is called *Proxy Pattern*.
              • + *
              + * + * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) + * @author Jeongho Nam + */ + abstract class DistributedSystemArray extends parallel.ParallelSystemArray { + /** + * @hidden + */ + private process_map_; + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * Factory method creating a child {@link DistributedProcess process} object. + * + * @param xml {@link XML} represents the {@link DistributedProcess child} object. + * @return A new {@link DistributedProcess} object. + */ + protected abstract createProcess(xml: library.XML): DistributedProcess; + /** + * Get process map. + * + * Gets an {@link HashMap} containing {@link DistributedProcess} objects with their *key*. + * + * @return An {@link HasmMap> containing pairs of string and {@link DistributedProcess} object. + */ + getProcessMap(): std.HashMap; + /** + * Test whether the process exists. + * + * @param name Name, identifier of target {@link DistributedProcess process}. + * + * @return Whether the process has or not. + */ + hasProcess(name: string): boolean; + /** + * Get a process. + * + * @param name Name, identifier of target {@link DistributedProcess process}. + * + * @return The specified process. + */ + getProcess(name: string): DistributedProcess; + /** + * Insert a process. + * + * @param process A process to be inserted. + * @return Success flag. + */ + insertProcess(process: DistributedProcess): boolean; + /** + * Erase a process. + * + * @param name Name, identifier of target {@link DistributedProcess process}. + */ + eraseProcess(name: string): boolean; + /** + * @hidden + */ + protected _Complete_history(history: slave.InvokeHistory): boolean; + /** + * @hidden + */ + private estimate_process_resource(history); + /** + * @hidden + */ + private estimate_system_performance(history); + /** + * @hidden + */ + protected _Normalize_performance(): void; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.templates.distributed { + /** + * Mediator of Distributed Processing System. + * + * The {@link DistributedSystemArrayMediator} class be a master for its slave systems, and be a slave to its master + * system at the same time. This {@link DistributedSystemArrayMediator} be a master system, containing and managing + * {@link DistributedSystem} objects, which represent distributed slave systems, by extending + * {@link DistributedSystemArray} class. Also, be a slave system through {@link getMediator mediator} object, which is + * derived from the {@link SlaveSystem} class. + * + * As a master, you can specify this {@link DistributedSystemArrayMediator} class to be a master server accepting + * slave clients or a master client to connecting slave servers. Even both of them is possible. Extends one + * of them below and overrides abstract factory method(s) creating the child {@link DistributedSystem} object. + * + * - {@link DistributedClientArrayMediator}: A server accepting {@link DistributedSystem distributed clients}. + * - {@link DistributedServerArrayMediator}: A client connecting to {@link DistributedServer distributed servers}. + * - {@link DistributedServerClientArrayMediator}: Both of them. Accepts {@link DistributedSystem distributed clients} and + * connects to {@link DistributedServer distributed servers} at the same time. + * + * As a slave, you can specify this {@link DistributedSystemArrayMediator} to be a client slave connecting to master + * server or a server slave accepting master client by overriding the {@link createMediator} method. + * Overrides the {@link createMediator createMediator()} method and return one of them: + * + * - A client slave connecting to master server: + * - {@link MediatorClient} + * - {@link MediatorWebClient} + * - {@link MediatorSharedWorkerClient} + * - A server slave accepting master client: + * - {@link MediatorServer} + * - {@link MediatorWebServer} + * - {@link MediatorDedicatedWorkerServer} + * - {@link MediatorSharedWorkerServer} + * + * #### [Inherited] {@link DistributedSystemArray} + * @copydoc DistributedSystemArray + */ + abstract class DistributedSystemArrayMediator extends DistributedSystemArray { + /** + * @hidden + */ + private mediator_; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating a {@link MediatorSystem} object. + * + * The {@link createMediator createMediator()} is an abstract method creating the {@link MediatorSystem} object. + * + * You know what? this {@link DistributedSystemArrayMediator} class be a master for its slave systems, and be a + * slave to its master system at the same time. The {@link MediatorSystem} object makes it possible; be a slave + * system. This {@link createMediator} determines specific type of the {@link MediatorSystem}. + * + * Overrides the {@link createMediator createMediator()} method to create and return one of them following which + * protocol and which type of remote connection (server or client) will be used: + * + * - A client slave connecting to master server: + * - {@link MediatorClient} + * - {@link MediatorWebClient} + * - {@link MediatorSharedWorkerClient} + * - A server slave accepting master client: + * - {@link MediatorServer} + * - {@link MediatorWebServer} + * - {@link MediatorDedicatedWorkerServer} + * - {@link MediatorSharedWorkerServer} + * + * @return A newly created {@link MediatorSystem} object. + */ + protected abstract createMediator(): parallel.MediatorSystem; + /** + * Start mediator. + * + * If the {@link getMediator mediator} is a type of server, then opens the server accepting master client. + * Otherwise, the {@link getMediator mediator} is a type of client, then connects the master server. + */ + protected startMediator(): void; + /** + * Get {@link MediatorSystem} object. + * + * When you need to send an {@link Invoke} message to the master system of this + * {@link DistributedSystemArrayMediator}, then send to the {@link MediatorSystem} through this + * {@link getMediator}. + * + * ```typescript + * this.getMediator().sendData(...); + * ``` + * + * @return The {@link MediatorSystem} object. + */ + getMediator(): parallel.MediatorSystem; + /** + * @hidden + */ + protected _Complete_history(history: slave.InvokeHistory): boolean; + } +} +declare namespace samchon.protocol { + /** + * @hidden + */ + namespace socket { + type socket = any; + type server = any; + type http_server = any; + } + /** + * @hidden + */ + namespace websocket { + type connection = any; + type request = any; + type IMessage = any; + type ICookie = any; + type client = any; + } +} +declare namespace samchon.protocol { + /** + * @hidden + */ + abstract class _CommunicatorBase implements ICommunicator { + /** + * @hidden + */ + protected listener_: IProtocol; + /** + * @inheritdoc + */ + onClose: Function; + /** + * @hidden + */ + protected connected_: boolean; + /** + * @hidden + */ + private binary_invoke_; + /** + * @hidden + */ + private binary_parameters_; + /** + * @hidden + */ + private unhandled_invokes_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from *listener*. + * + * @param listener An {@link IProtocol} object to listen {@link Invoke} messages. + */ + constructor(listener: IProtocol); + /** + * @inheritdoc + */ + abstract close(): void; + /** + * @inheritdoc + */ + isConnected(): boolean; + /** + * @hidden + */ + protected _Is_binary_invoke(): boolean; + /** + * @inheritdoc + */ + abstract sendData(invoke: Invoke): void; + /** + * @inheritdoc + */ + replyData(invoke: Invoke): void; + /** + * @hidden + */ + protected _Handle_string(str: string): void; + /** + * @hidden + */ + protected _Handle_binary(binary: Uint8Array): void; + } +} +declare namespace samchon.protocol { + /** + * A communicator following Samchon Framework's own protocol. + * + * {@link Communicator} is an abstract class following Samchon Framework's own protocol. This {@link Communicator} + * class is specified to {@link ServerConnector} and {@link ClientDriver} whether the remote system is a server (that + * my system is connecting to) or a client (a client conneting to to my server). + * + * Note that, if one of this or remote system is web-browser based, then you don't have to use this + * {@link Communicator} class who follows Samchon Framework's own protocol. Web-browser supports only Web-socket + * protocol. Thus in that case, you have to use {@link WebCommunicator} instead. + * + * #### [Inherited] {@link ICommunicator} + * @copydoc ICommunicator + */ + abstract class Communicator extends _CommunicatorBase { + /** + * @hidden + */ + protected socket_: socket.socket; + /** + * @hidden + */ + private header_bytes_; + /** + * @hidden + */ + private data_; + /** + * @hidden + */ + private data_index_; + /** + * @hidden + */ + private listening_; + /** + * @inheritdoc + */ + close(): void; + /** + * @hidden + */ + protected _Start_listen(): void; + /** + * @hidden + */ + private _Handle_error(); + /** + * @hidden + */ + private _Handle_close(); + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + /** + * @hidden + */ + private _Listen_piece(piece); + /** + * @hidden + */ + private _Listen_header(piece, piece_index); + /** + * @hidden + */ + private _Listen_data(piece, piece_index); + } +} +declare namespace samchon.protocol { + /** + * Communicator with remote client. + * + * {@link ClientDriver} is a class taking full charge of network communication with remote client who follows Samchon + * Framework's own protocol. This {@link ClientDriver} object is always created by {@link Server} class. When you got + * this {@link ClientDriver} object from the {@link Server.addClient Server.addClient()}, then specify + * {@link IProtocol listener} with the {@link ClientDriver.listen ClientDriver.listen()} method. + * + * #### [Inherited] {@link IClientDriver} + * @copydoc IClientDriver + */ + class ClientDriver extends Communicator implements IClientDriver { + /** + * Construct from a socket. + */ + constructor(socket: socket.socket); + /** + * @inheritdoc + */ + listen(listener: IProtocol): void; + } +} +declare namespace samchon.protocol { + /** + * A communicator for shared worker. + * + * {@link DedicatedWorkerCommunicator} is an abstract class for communication between DedicatedWorker and Web-browser. + * This {@link DedicatedWorkerCommunicator} is specified to {@link DedicatedWorkerServerConnector} and + * {@link DedicatedWorkerClientDriver} whether the remote system is a server (that my system is connecting to) or a + * client (a client conneting to to my server). + * + * #### Why DedicatedWorker be a server? + * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the + * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the + * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network + * communication? Furthermore, there's not any difference between the worker communication and network communication. + * It's the reason why Samchon Framework considers the **Worker** as a network node. + * + * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a + * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the + * server and clients with this {@link DedicatedWorkerCommunicator}. + * + * #### [Inherited] {@link ICommunicator} + * @copydoc ICommunicator + */ + abstract class DedicatedWorkerCommunicator extends _CommunicatorBase { + /** + * @hidden + */ + protected _Handle_message(event: MessageEvent): void; + } +} +declare namespace samchon.protocol { + /** + * Communicator with master web-browser. + * + * {@link DedicatedWorkerClientDriver} is a class taking full charge of network communication with web browsers. This + * {@link DedicatedWorkerClientDriver} object is always created by {@link DedicatedWorkerServer} class. When you got + * this {@link DedicatedWorkerClientDriver} object from + * {@link DedicatedWorkerServer.addClient DedicatedWorkerServer.addClient()}, then specify {@link IProtocol listener} + * with the {@link DedicatedWorkerClientDriver.listen DedicatedWorkerClientDriver.listen()} method. + * + * #### Why DedicatedWorker be a server? + * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the + * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the + * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network + * communication? Furthermore, there's not any difference between the worker communication and network communication. + * It's the reason why Samchon Framework considers the **Worker** as a network node. + * + * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a + * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the + * server and clients with this {@link DedicatedWorkerCommunicator}. + * + * #### [Inherited] {@link IClientDriver} + * @copydoc IClientDriver + */ + class DedicatedWorkerClientDriver extends DedicatedWorkerCommunicator implements IClientDriver { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + listen(listener: IProtocol): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + } +} +declare namespace samchon.protocol { + /** + * A communicator for shared worker. + * + * {@link SharedWorkerCommunicator} is an abstract class for communication between SharedWorker and Web-browser. This + * {@link SharedWorkerCommunicator} is specified to {@link SharedWorkerServerConnector} and + * {@link SharedWorkerClientDriver} whether the remote system is a server (that my system is connecting to) or a client + * (a client conneting to to my server). + * + * Note that, SharedWorker is a conception only existed in web-browser. This {@link SharedWorkerCommunicator} is not + * supported in NodeJS. Only web-browser environment can utilize this {@link SharedWorkerCommunicator}. + * + * #### Why SharedWorker be a server? + * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser + * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship + * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as + * clients. + * + * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a + * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the + * server and clients with this {@link SharedWorkerCommunicator}. + * + * #### [Inherited] {@link ICommunicator} + * @copydoc ICommunicator + */ + abstract class SharedWorkerCommunicator extends _CommunicatorBase { + /** + * @hidden + */ + protected port_: MessagePort; + /** + * @inheritdoc + */ + close(): void; + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + /** + * @hidden + */ + protected _Handle_message(event: MessageEvent): void; + } +} +declare namespace samchon.protocol { + /** + * Communicator with remote web-browser. + * + * {@link SharedWorkerClientDriver} is a class taking full charge of network communication with web browsers. This + * {@link SharedWorkerClientDriver} object is always created by {@link SharedWorkerServer} class. When you got this + * {@link SharedWorkerClientDriver} object from {@link SharedWorkerServer.addClient SharedWorkerServer.addClient()}, + * then specify {@link IProtocol listener} with the + * {@link SharedWorkerClientDriver.listen SharedWorkerClientDriver.listen()} method. + * + * #### Why SharedWorker be a server? + * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser + * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship + * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as + * clients. + * + * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a + * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the + * server and clients with this {@link SharedWorkerCommunicator}. + * + * #### [Inherited] {@link IClientDriver} + * @copydoc IClientDriver + */ + class SharedWorkerClientDriver extends SharedWorkerCommunicator implements IClientDriver { + /** + * @hidden + */ + private listening_; + /** + * Construct from a MessagePort object. + */ + constructor(port: MessagePort); + /** + * @inheritdoc + */ + listen(listener: IProtocol): void; + } +} +declare namespace samchon.protocol { + /** + * A communicator following Web-socket protocol. + * + * {@link WebCommunicator} is an abstract class following Web-socket protocol. This {@link WebCommunicator} class is + * specified to {@link WebServerConnector} and {@link WebClientDriver} whether the remote system is a server (that my + * system is connecting to) or a client (a client conneting to to my server). + * + * Note that, one of this or remote system is web-browser based, then there's not any alternative choice. Web browser + * supports only Web-socket protocol. In that case, you've use this {@link WebCommunicator} class. + * + * #### [Inherited] {@link ICommunicator} + * @copydoc ICommunicator + */ + abstract class WebCommunicator extends _CommunicatorBase { + /** + * @hidden + */ + protected connection_: websocket.connection; + /** + * @inheritdoc + */ + close(): void; + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + /** + * @hidden + */ + protected _Handle_message(message: websocket.IMessage): void; + /** + * @hidden + */ + protected _Handle_close(): void; + } +} +declare namespace samchon.protocol { + /** + * Communicator with remote web-client. + * + * {@link WebClientDriver} is a class taking full charge of network communication with remote client who follows + * Web-socket protocol. This {@link WebClientDriver} object is always created by {@link WebServer} class. When you + * got this {@link WebClientDriver} object from the {@link WebServer.addClient WebServer.addClient()}, then specify + * {@link IProtocol listener} with the {@link WebClientDriver.listen WebClientDriver.listen()} method. + * + * Unlike other protocol, Web-socket protocol's clients notify two parameters on their connection; + * {@link getSessionID session-id} and {@link getPath path}. The {@link getSessionID session-id} can be used to + * identify *user* of each client, and the {@link getPath path} can be used which type of *service* that client wants. + * In {@link service} module, you can see the best utilization case of them. + * - {@link service.User}: utlization of the {@link getSessionID session-id}. + * - {@link service.Service}: utilization of the {@link getPath path}. + * + * #### [Inherited] {@link IClientDriver} + * @copydoc IClientDriver + */ + class WebClientDriver extends WebCommunicator implements IClientDriver { + /** + * @hidden + */ + private path_; + /** + * @hidden + */ + private session_id_; + /** + * @hidden + */ + private listening_; + /** + * Initialization Constructor. + * + * @param connection Connection driver, a socket for web-socket. + * @param path Requested path. + * @param session_id Session ID, an identifier of the remote client. + */ + constructor(connection: websocket.connection, path: string, session_id: string); + /** + * @inheritdoc + */ + listen(listener: IProtocol): void; + /** + * Get requested path. + */ + getPath(): string; + /** + * Get session ID, an identifier of the remote client. + */ + getSessionID(): string; + } +} +declare namespace samchon.protocol { + /** + * An interface for communicator with remote client. + * + * {@link IClientDriver} is a type of {@link ICommunicator}, specified for communication with remote client who has + * connected in a {@link IServer server}. It takes full charge of network communication with the remote client. + * + * The {@link IClientDriver} object is created and delivered from {@link IServer} and + * {@link IServer.addClient IServer.addClient()}. Those are derived types from this {@link IClientDriver}, being + * created by the matched {@link IServer} object. + * + * Protocol | Derived Type | Created By + * ------------------------|-------------------------------------|---------------------------- + * Samchon Framework's own | {@link ClientDriver} | {@link Server} + * Web-socket protocol | {@link WebClientDriver} | {@link WebServer} + * DedicatedWorker | {@link DedicatedWorkerClinetDriver} | {@link DedicatedWorkerServer} + * SharedWorker | {@link SharedWorkerClientDriver} | {@link SharedWorkerServer} + * + * When you've got an {@link IClientDriver} object from the {@link IServer.addClient IServer.addClient()}, then + * specify {@link IProtocol listener} with {@link IClient.listen IClient.listen()}. Whenever a replied message comes + * from the remote system, the message will be converted to an {@link Invoke} class and the {@link Invoke} object + * will be shifted to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. + * Below code is an example specifying and managing the {@link IProtocol listener} objects. + * + * - https://github.com/samchon/framework-examples/blob/master/calculator/calculator-server.ts + * + * + * + * + * + * @see {@link IServer}, {@link IProtocol} + * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iclientdriver) + * @author Jeongho Nam + */ + interface IClientDriver extends ICommunicator { + /** + * Listen message from the newly connected client. + * + * Starts listening message from the newly connected client. Replied message from the connected client will be + * converted to {@link Invoke} classes and shifted to the *listener*'s {@link IProtocol.replyData replyData()} + * method. + * + * @param listener A listener object to listen replied message from newly connected client in + * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. + */ + listen(listener: IProtocol): void; + } +} +declare namespace samchon.protocol { + /** + * An interface taking full charge of network communication. + * + * {@link ICommunicator} is an interface for communicator classes who take full charge of network communication with + * remote system, without reference to whether the remote system is a server or a client. Type of the + * {@link ICommunicator} is specified to {@link IServerConnector} and {@link IClientDriver} whether the remote system + * is a server (that I've to connect) or a client (a client connected to my server). + * + * Whenever a replied message comes from the remote system, the message will be converted to an {@link Invoke} class + * and the {@link Invoke} object will be shifted to the {@link IProtocol listener}'s + * {@link IProtocol.replyData IProtocol.replyData()} method. + * + * + * + * + * + * @see {@link IClientDriver}, {@link IServerConnector}, {@link IProtocol} + * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#icommunicator) + * @author Jeongho Nam + */ + interface ICommunicator extends IProtocol { + /** + * Callback function for connection closed. + */ + onClose: Function; + /** + * Close connection. + */ + close(): void; + /** + * Test connection. + * + * Test whether this {@link ICommunicator communicator} object is connected with the remote system. If the + * connection is alive, then returns ```true```. Otherwise, the connection is not alive or this + * {@link ICommunicator communicator has not connected with the remote system yet, then returns ```false```. + * + * @return true if connected, otherwise false. + */ + isConnected(): boolean; + /** + * Send message. + * + * Send {@link Invoke} message to remote system. + * + * @param invoke An {@link Invoke} message to send. + */ + sendData(invoke: protocol.Invoke): void; + /** + * Handle replied message. + * + * Handles replied {@link Invoke} message recived from remove system. The {@link Invoke} message will be shifted + * to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} by this method. + * + * @param invoke An {@link Invoke} message received from remote system. + */ + replyData(invoke: protocol.Invoke): void; + } +} +declare namespace samchon.protocol { + /** + * An interface for server connector. + * + * {@link IServerConnector} is a type of {@link ICommunicator}, specified for server connector classes who connect to + * the remote server as a client. {@link IServerConnector} provides {@link connect connection method} and takes full + * charge of network communication with the remote server. + * + * Declare specific type of {@link IServerConnector} from {@link IProtocol listener} and call the + * {@link connect connect()} method. Then whenever a replied message comes from the remote system, the message will + * be converted to an {@link Invoke} object and the {@link Invoke} object will be shifted to the + * {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. Below code is an example + * connecting to remote server and interacting with it. + * + * - https://github.com/samchon/framework-examples/blob/master/calculator/calculator-application.ts + * + * Note that, protocol of this client and remote server must be matched. Thus, before determining specific type of + * this {@link IServerConnector}, you've to consider which protocol and type the remote server follows. + * + * Protocol | Derived Type | Connect to + * ------------------------|----------------------------------------|------------------------------- + * Samchon Framework's own | {@link ServerConnector} | {@link Server} + * Web-socket protocol | {@link WebServerConnector} | {@link WebServer} + * DedicatedWorker | {@link DedicatedWorkerServerConnector} | {@link DedicatedWorkerServer} + * SharedWorker | {@link SharedWorkerServerConnector} | {@link SharedWorkerServer} + * + * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_basic_components.png) + * + * @see {@link IServer}, {@link IProtocol} + * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverconnector) + * @author Jeongho Nam + */ + interface IServerConnector extends ICommunicator { + /** + * Callback function for connection completed. + * + * When you call {@link connect connect()} and the connection has completed, then this call back function + * {@link onConnect} will be called. Note that, if the listener of this {@link onConnect} is a member method of + * some class, then you've use the ```bind```. + */ + onConnect: Function; + /** + * Connect to a server. + * + * Connects to a server with specified *host* address and *port* number. After the connection has + * succeeded, callback function {@link onConnect} is called. Listening data from the connected server also begins. + * Replied messages from the connected server will be converted to {@link Invoke} classes and will be shifted to + * the {@link WebCommunicator.listener listener}'s {@link IProtocol.replyData replyData()} method. + * + * If the connection fails immediately, either an event is dispatched or an exception is thrown: an error + * event is dispatched if a host was specified, and an exception is thrown if no host was specified. Otherwise, + * the status of the connection is reported by an event. If the socket is already connected, the existing + * connection is closed first. + * + * @param ip The name or IP address of the host to connect to. + * If no host is specified, the host that is contacted is the host where the calling file resides. + * If you do not specify a host, use an event listener to determine whether the connection was + * successful. + * @param port The port number to connect to. + */ + connect(ip: string, port: number): void; + } +} +declare namespace samchon.protocol { + /** + * A server connector for DedicatedWorker. + * + * {@link DedicatedWorkerServerConnector} is a class connecting to SharedWorker and taking full charge of network + * communication with the SharedWorker. Create an {@link DedicatedWorkerServer} instance from the + * {@IProtocol listener} and call the {@link connect connect()} method. + * + * #### Why DedicatedWorker be a server? + * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the + * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the + * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network + * communication? Furthermore, there's not any difference between the worker communication and network communication. + * It's the reason why Samchon Framework considers the **Worker** as a network node. + * + * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a + * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the + * server and clients with this {@link DedicatedWorkerCommunicator}. + * + * #### [Inherited] {@link IServerConnector} + * @copydoc IServerConnector + */ + class DedicatedWorkerServerConnector extends DedicatedWorkerCommunicator implements IServerConnector { + /** + * @hidden + */ + private worker_; + /** + * @inheritdoc + */ + onConnect: Function; + /** + * Construct from *listener*. + * + * @param listener A listener object to listen replied message from newly connected client in + * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. + */ + constructor(listener: IProtocol); + /** + * @inheritdoc + */ + connect(jsFile: string): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + } +} +declare namespace samchon.protocol { + /** + * Server connnector. + * + * {@link ServerConnector} is a class connecting to remote server who follows Samchon Framework's own protocol and + * taking full charge of network communication with the remote server. Create a {@link ServerConnector} instance from + * the {@IProtocol listener} and call the {@link connect connect()} method. + * + * #### [Inherited] {@link IServerConnector} + * @copydoc IServerConnector + */ + class ServerConnector extends Communicator implements IServerConnector { + /** + * @inheritdoc + */ + onConnect: Function; + /** + * Construct from *listener*. + * + * @param listener A listener object to listen replied message from newly connected client in + * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. + */ + constructor(listener: IProtocol); + /** + * @inheritdoc + */ + connect(ip: string, port: number): void; + /** + * @hidden + */ + private _Handle_connect(...arg); + /** + * @hidden + */ + private _Send_dummy_packet_repeatedly(); + } +} +declare namespace samchon.protocol { + /** + * A server connector for SharedWorker. + * + * {@link SharedWorkerServerConnector} is a class connecting to SharedWorker and taking full charge of network + * communication with the SharedWorker. Create an {@link SharedWorkerServerConnector} instance from the + * {@IProtocol listener} and call the {@link connect connect()} method. + * + * #### Why SharedWorker be a server? + * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser + * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship + * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as + * clients. + * + * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a + * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the + * server and clients with this {@link SharedWorkerCommunicator}. + * + * #### [Inherited] {@link IServerConnector} + * @copydoc IServerConnector + */ + class SharedWorkerServerConnector extends SharedWorkerCommunicator implements IServerConnector { + /** + * @inheritdoc + */ + onConnect: Function; + /** + * Construct from *listener*. + * + * @param listener A listener object to listen replied message from newly connected client in + * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. + */ + constructor(listener: IProtocol); + /** + * Connect to a SharedWorker. + * + * Connects to a server with specified *jstFile* path. If a SharedWorker instance of the *jsFile* is not + * constructed yet, then the SharedWorker will be newly constructed. Otherwise the SharedWorker already exists, + * then connect to the SharedWorker. After those processes, callback function {@link onConnect} is called. + * Listening data from the connected server also begins. Replied messages from the connected server will be + * converted to {@link Invoke} classes and will be shifted to the {@link WebCommunicator.listener listener}'s + * {@link IProtocol.replyData replyData()} method. + * + * If the connection fails immediately, either an event is dispatched or an exception is thrown: an error + * event is dispatched if a host was specified, and an exception is thrown if no host was specified. Otherwise, + * the status of the connection is reported by an event. If the socket is already connected, the existing + * connection is closed first. + * + * @param jsFile Path of JavaScript file to execute who defines SharedWorker. + */ + connect(jsFile: string): void; + } +} +declare namespace samchon.protocol { + /** + * A server connector for web-socket protocol. + * + * {@link WebServerConnector} is a class connecting to remote server who follows Web-socket protocol and taking full + * charge of network communication with the remote server. Create an {@link WebServerConnector} instance from the + * {@IProtocol listener} and call the {@link connect connect()} method. + * + * #### [Inherited] {@link IServerConnector} + * @copydoc IServerConnector + */ + class WebServerConnector extends WebCommunicator implements IServerConnector { + /** + * @hidden + */ + private browser_socket_; + /** + * @hidden + */ + private node_client_; + /** + * @inheritdoc + */ + onConnect: Function; + /** + * Construct from *listener*. + * + * @param listener A listener object to listen replied message from newly connected client in + * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. + */ + constructor(listener: IProtocol); + /** + * Connect to a web server. + * + * Connects to a server with specified *host* address, *port* number and *path*. After the connection has + * succeeded, callback function {@link onConnect} is called. Listening data from the connected server also begins. + * Replied messages from the connected server will be converted to {@link Invoke} classes and will be shifted to + * the {@link WebCommunicator.listener listener}'s {@link IProtocol.replyData replyData()} method. + * + * If the connection fails immediately, either an event is dispatched or an exception is thrown: an error + * event is dispatched if a host was specified, and an exception is thrown if no host was specified. Otherwise, + * the status of the connection is reported by an event. If the socket is already connected, the existing + * connection is closed first. + * + * @param ip The name or IP address of the host to connect to. + * If no host is specified, the host that is contacted is the host where the calling file resides. + * If you do not specify a host, use an event listener to determine whether the connection was + * successful. + * @param port The port number to connect to. + * @param path Path of service which you want. + */ + connect(ip: string, port: number, path?: string): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + /** + * @hidden + */ + private _Handle_browser_connect(event); + /** + * @hidden + */ + private _Handle_browser_message(event); + /** + * @hidden + */ + private _Handle_node_connect(connection); + } +} +declare namespace samchon.protocol { + /** + * A container of entity, and it's a type of entity, too. + * + * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) + * + * @handbook [Protocol - Standard Message](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Standard_Message) + * @author Jeongho Nam + */ + interface IEntityGroup extends IEntity, std.base.Container { + /** + * Construct data of the Entity from an XML object. + * + * Constructs the EntityArray's own member variables only from the input XML object. + * + * Do not consider about constructing children Entity objects' data in EntityArray::construct(). + * Those children Entity objects' data will constructed by their own construct() method. Even insertion + * of XML objects representing children are done by abstract method of EntityArray::toXML(). + * + * Constructs only data of EntityArray's own. + */ + construct(xml: library.XML): void; + /** + * Factory method of a child Entity. + * + * EntityArray::createChild() is a factory method creating a new child Entity which is belonged + * to the EntityArray. This method is called by EntityArray::construct(). The children construction + * methods Entity::construct() will be called by abstract method of the EntityArray::construct(). + * + * @return A new child Entity belongs to EntityArray. + */ + createChild(xml: library.XML): T; + /** + * Get iterator to element. + * + * Searches the container for an element with a identifier equivalent to *key* and returns an + * iterator to it if found, otherwise it returns an iterator to {@link end end()}. + * + * Two keys are considered equivalent if the container's comparison object returns false reflexively + * (i.e., no matter the order in which the elements are passed as arguments). + * + * Another member functions, {@link has has()} and {@link count count()}, can be used to just check + * whether a particular *key* exists. + * + * @param key Key to be searched for + * @return An iterator to the element, if an element with specified *key* is found, or + * {@link end end()} otherwise. + */ + /** + * Whether have the item or not. + * + * Indicates whether a map has an item having the specified identifier. + * + * @param key Key value of the element whose mapped value is accessed. + * + * @return Whether the map has an item having the specified identifier. + */ + has(key: any): boolean; + /** + * Count elements with a specific key. + * + * Searches the container for elements whose key is *key* and returns the number of elements found. + * + * @param key Key value to be searched for. + * + * @return The number of elements in the container with a *key*. + */ + count(key: any): number; + /** + * Get an element + * + * Returns a reference to the mapped value of the element identified with *key*. + * + * @param key Key value of the element whose mapped value is accessed. + * + * @throw exception out of range + * + * @return A reference object of the mapped value (_Ty) + */ + get(key: any): T; + /** + * A tag name of children objects. + */ + CHILD_TAG(): string; + /** + * Get an XML object represents the EntityArray. + * + * Archives the EntityArray's own member variables only to the returned XML object. + * + * Do not consider about archiving children Entity objects' data in EntityArray::toXML(). + * Those children Entity objects will converted to XML object by their own toXML() method. The + * insertion of XML objects representing children are done by abstract method of + * EntityArray::toXML(). + * + * Archives only data of EntityArray's own. + */ + toXML(): library.XML; + } + /** + * @hidden + */ + namespace IEntityGroup { + /** + * @hidden + */ + function construct(entityGroup: IEntityGroup, xml: library.XML, ...prohibited_names: string[]): void; + /** + * @hidden + */ + function toXML(group: IEntityGroup, ...prohibited_names: string[]): library.XML; + function has(entityGroup: IEntityGroup, key: any): boolean; + function count(entityGroup: IEntityGroup, key: any): number; + function get(entityGroup: IEntityGroup, key: any): T; + } +} +declare namespace samchon.protocol { + /** + * @inheritdoc + */ + abstract class EntityArray extends std.Vector implements IEntityGroup { + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * @inheritdoc + */ + abstract createChild(xml: library.XML): T; + /** + * @inheritdoc + */ + key(): any; + /** + * @inheritdoc + */ + has(key: any): boolean; + /** + * @inheritdoc + */ + count(key: any): number; + /** + * @inheritdoc + */ + get(key: any): T; + /** + * @inheritdoc + */ + abstract TAG(): string; + /** + * @inheritdoc + */ + abstract CHILD_TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + * @inheritdoc + */ + abstract class EntityList extends std.List implements IEntityGroup { + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * @inheritdoc + */ + abstract createChild(xml: library.XML): T; + /** + * @inheritdoc + */ + key(): any; + /** + * @inheritdoc + */ + has(key: any): boolean; + /** + * @inheritdoc + */ + count(key: any): number; + /** + * @inheritdoc + */ + get(key: any): T; + /** + * @inheritdoc + */ + abstract TAG(): string; + /** + * @inheritdoc + */ + abstract CHILD_TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + * @inheritdoc + */ + abstract class EntityDeque extends std.Deque implements IEntityGroup { + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * @inheritdoc + */ + abstract createChild(xml: library.XML): T; + /** + * @inheritdoc + */ + key(): any; + /** + * @inheritdoc + */ + has(key: any): boolean; + /** + * @inheritdoc + */ + count(key: any): number; + /** + * @inheritdoc + */ + get(key: any): T; + /** + * @inheritdoc + */ + abstract TAG(): string; + /** + * @inheritdoc + */ + abstract CHILD_TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + * Standard message of network I/O. + * + * {@link Invoke} is a class used in network I/O in protocol package of Samchon Framework. + * + * The Invoke message has an XML structure like the result screen of provided example in below. + * We can enjoy lots of benefits by the normalized and standardized message structure used in + * network I/O. + * + * The greatest advantage is that we can make any type of network system, even how the system + * is enourmously complicated. As network communication message is standardized, we only need to + * concentrate on logical relationships between network systems. We can handle each network system + * like a object (class) in OOD. And those relationships can be easily designed by using design + * pattern. + * + * In Samchon Framework, you can make any type of network system with basic componenets + * (IProtocol, IServer and ICommunicator) by implemens or inherits them, like designing + * classes of S/W architecture. + * + * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) + * + * @see {@link IProtocol} + * @author Jeongho Nam + */ + class Invoke extends EntityArray { + /** + * Listener, represent function's name. + */ + private listener; + /** + * Default Constructor. + */ + constructor(); + constructor(listener: string); + /** + * Copy Constructor. + * + * @param invoke + */ + constructor(invoke: Invoke); + /** + * Construct from listener and parametric values. + * + * @param listener + * @param parameters + */ + constructor(listener: string, ...parameters: Array); + /** + * @inheritdoc + */ + createChild(xml: library.XML): InvokeParameter; + /** + * Get listener. + */ + getListener(): string; + /** + * Get arguments for Function.apply(). + * + * @return An array containing values of the contained parameters. + */ + getArguments(): Array; + /** + * Apply to a matched function. + * + * @param obj Target object to find matched function. + * @return Whether succeded to find matched function. + */ + apply(obj: Object): boolean; + /** + * Apply to a function. + * + * @param thisArg Owner of the function. + * @param func Function to call. + */ + apply(thisArg: Object, func: Function): void; + /** + * @inheritdoc + */ + TAG(): string; + /** + * @inheritdoc + */ + CHILD_TAG(): string; + } +} +declare namespace samchon.protocol { + /** + * A parameter belongs to an Invoke. + * + * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) + * + * @author Jeongho Nam + */ + class InvokeParameter extends Entity { + /** + * Name of the parameter. + * + * @details Optional property, can be omitted. + */ + protected name: string; + /** + * Type of the parameter. + */ + protected type: string; + /** + * Value of the parameter. + */ + protected value: boolean | number | string | library.XML | Uint8Array; + /** + * Default Constructor. + */ + constructor(); + constructor(val: boolean); + constructor(val: number); + constructor(val: string); + constructor(val: library.XML); + constructor(val: Uint8Array); + /** + * Construct from variable name and number value. + * + * @param name + * @param val + */ + constructor(name: string, val: boolean); + constructor(name: string, val: number); + constructor(name: string, val: string); + constructor(name: string, val: library.XML); + constructor(name: string, val: Uint8Array); + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + setValue(value: boolean): void; + setValue(value: number): void; + setValue(value: string): void; + setValue(value: library.XML): void; + setValue(value: Uint8Array): void; + /** + * @inheritdoc + */ + key(): any; + /** + * Get name. + */ + getName(): string; + /** + * Get type. + */ + getType(): string; + /** + * Get value. + */ + getValue(): any; + /** + * @inheritdoc + */ + TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + * An interface for {@link Invoke} message chain. + * + * {@link IProtocol} is an interface for {@link Invoke} message, which is standard message of network I/O in + * *Samchon Framework*, chain. The {@link IProtocol} interface is used to network drivers and some classes which are + * in a relationship of *Chain of Responsibility Pattern* with those network drivers. + * + * Implements {@link IProtocol} if the class sends and handles {@link Invoke} messages. Looking around source codes of + * the *Samchon Framework*, especially *Templates*, you can find out that all the classes and modules handling + * {@link Invoke} messages are always implementing this {@link IProtocol}. + * + * + * + * + * + * @see {@link Invoke} + * @handbook https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iprotocol + * @author Jeongho Nam + */ + interface IProtocol { + /** + * Sending message. + * + * Sends message to related system or shifts the responsibility to chain. + * + * @param invoke Invoke message to send + */ + replyData(invoke: Invoke): void; + /** + * Handling replied message. + * + * Handles replied message or shifts the responsibility to chain. + * + * @param invoke An {@link Invoke} message has received. + */ + sendData(invoke: Invoke): void; + } +} +declare namespace samchon.protocol { + /** + * A DeidcatedWorker server. + * + * The {@link DedicatedWorkerServer} is an abstract class is realized to open a DedicatedWorker server and accept + * web-browser client (master). Extends this {@link DedicatedWorkerServer} class and overrides + * {@link addClient addClient()} method to define what to do with a newly connected + * {@link DedicatedWorkerClientDriver remote client}. + * + * #### Why DedicatedWorker be a server? + * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the + * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the + * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network + * communication? Furthermore, there's not any difference between the worker communication and network communication. + * It's the reason why Samchon Framework considers the **Worker** as a network node. + * + * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a + * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the + * server and clients with this {@link DedicatedWorkerCommunicator}. + * + * #### [Inherited] {@link IServer} + * @copydoc IServer + */ + abstract class DedicatedWorkerServer implements IServer { + /** + * @inheritdoc + */ + abstract addClient(driver: DedicatedWorkerClientDriver): void; + /** + * @inheritdoc + */ + open(): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.protocol { + /** + * A substitute {@link DedicatedWorkerServer}. + * + * The {@link DedicatedWorkerServerBase} is a substitute class who subrogates {@link DedicatedWorkerServer}'s + * responsibility. + * + * #### [Inherited] {@link IServerBase} + * @copydoc IServerBase + */ + class DedicatedWorkerServerBase extends DedicatedWorkerServer implements IServerBase { + /** + * @hidden + */ + private hooker_; + /** + * Construct from a *hooker*. + * + * @param hooker A hooker throwing responsibility of server's role. + */ + constructor(hooker: IServer); + /** + * @inheritdoc + */ + addClient(driver: IClientDriver): void; + } +} +declare namespace samchon.protocol { + /** + * An interface for substitute server classes. + * + * {@link IServerBase} is an interface for substitue server classes who subrogate server's role. + * + * The easiest way to defining a server class is to extending one of them below, who implemented the {@link IServer}. + * However, it is impossible (that is, if the class is already extending another class), you can instead implement + * the {@link IServer} interface, create an {@link IServerBase} member, and write simple hooks to route calls into + * the aggregated {@link IServerBase}. + * + * Protocol | {@link IServer} | {@link IServerBase} | {@link IClientDriver} + * ------------------------|-------------------------------|-----------------------------------|------------------------------------- + * Samchon Framework's own | {@link Server} | {@link ServerBase} | {@link ClientDriver} + * Web-socket protocol | {@link WebServer} | {@link WebServerBase} | {@link WebClientDriver} + * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerServerBase} | {@link DedicatedWorkerClientDriver} + * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerServerBase} | {@link SharedWorkerClientDriver} + * + * After the hooking to aggregated {@link IServerBase} object, overrides {@link addClient addClient()} method who + * accepts a newly connected client as an {@link IClientDriver} object. At last, call {@link open open()} method with + * specified port number. + * + * ```typescript + * class MyServer extends Something implements IServer + * { + * private server_base_: IServerBase = new WebServerBase(this); + * + * public addClient(driver: IClientDriver): void + * { + * // WHAT TO DO WHEN A CLIENT HAS CONNECTED + * } + * + * public open(port: number): void + * { + * this.server_base_.open(); + * } + * public close(): void + * { + * this.server_base_.close(); + * } + * } + * ``` + * + * + * + * + * + * @see {@link IServer}, {@link IClientDriver} + * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverbase) + * @author Jeongho Nam + */ + interface IServerBase extends IServer { + } +} +declare namespace samchon.protocol { + /** + * A server. + * + * The {@link Server} is an abstract class designed to open a server and accept clients who are following Samchon + * Framework's own protocol. Extends this {@link Server} class and overrides {@link addClient addClient()} method to + * define what to do with newly connected {@link ClientDriver remote clients}. + * + * #### [Inherited] {@link IServer} + * @copydoc Server + */ + abstract class Server implements IServer { + /** + * @hidden + */ + private net_driver_; + /** + * @inheritdoc + */ + abstract addClient(driver: ClientDriver): void; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @hidden + */ + private _Handle_connect(socket); + } +} +declare namespace samchon.protocol { + /** + * A substitute {@link Server}. + * + * The {@link ServerBase} is a substitute class who subrogates {@link Server}'s responsibility. + * + * #### [Inherited] {@link IServerBase} + * @copydoc IServerBase + */ + class ServerBase extends Server implements IServerBase { + /** + * @hidden + */ + private hooker_; + /** + * Construct from a *hooker*. + * + * @param hooker A hooker throwing responsibility of server's role. + */ + constructor(hooker: IServer); + /** + * @inheritdoc + */ + addClient(driver: IClientDriver): void; + } +} +declare namespace samchon.protocol { + /** + * A SharedWorker server. + * + * The {@link SharedWorker} is an abstract class is realized to open a SharedWorker server and accept web-browser + * clients. Extends this {@link SharedWorkerServer} class and overrides {@link addClient addClient()} method to + * define what to do with newly connected {@link SharedWorkerClientDriver remote clients}. + * + * #### Why SharedWorker be a server? + * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser + * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship + * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as + * clients. + * + * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a + * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the + * server and clients with this {@link SharedWorkerCommunicator}. + * + * #### [Inherited] {@link IServer} + * @copydoc IServer + */ + abstract class SharedWorkerServer implements IServer { + /** + * @inheritdoc + */ + abstract addClient(driver: SharedWorkerClientDriver): void; + /** + * @inheritdoc + */ + open(): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @hidden + */ + private _Handle_connect(event); + } +} +declare namespace samchon.protocol { + /** + * A substitute {@link SharedWorkerServer}. + * + * The {@link SharedWorkerServerBase} is a substitute class who subrogates {@link SharedWorkerServer}'s + * responsibility. + * + * #### [Inherited] {@link IServerBase} + * @copydoc IServerBase + */ + class SharedWorkerServerBase extends SharedWorkerServer implements IServerBase { + /** + * @hidden + */ + private hooker_; + /** + * Construct from a *hooker*. + * + * @param hooker A hooker throwing responsibility of server's role. + */ + constructor(hooker: IServer); + /** + * @inheritdoc + */ + addClient(driver: IClientDriver): void; + } +} +declare namespace samchon.protocol { + /** + * A web server. + * + * The {@link WebServer} is an abstract class designed to open a server and accept clients who are following + * web-socket protocol. Extends this {@link WebServer} class and overrides {@link addClient addClient()} method to + * define what to do with newly connected {@link WebClientDriver remote clients}. + * + * #### [Inherited] {@link IServer} + * @copydoc IServer + */ + abstract class WebServer implements IServer { + /** + * @hidden + */ + private http_server_; + /** + * @hidden + */ + private sequence_; + /** + * @hidden + */ + private my_port_; + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + abstract addClient(driver: WebClientDriver): void; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @hidden + */ + private _Handle_request(request); + /** + * @hidden + */ + private _Fetch_session_id(cookies); + /** + * @hidden + */ + private _Issue_session_id(); + } +} +declare namespace samchon.protocol { + /** + * A substitute {@link WebServer}. + * + * The {@link WebServerBase} is a substitute class who subrogates {@link WebServer}'s responsibility. + * + * #### [Inherited] {@link IServerBase} + * @copydoc IServerBase + */ + class WebServerBase extends WebServer implements IServerBase { + /** + * @hidden + */ + private hooker_; + /** + * Construct from a *hooker*. + * + * @param hooker A hooker throwing responsibility of server's role. + */ + constructor(hooker: IServer); + /** + * @inheritdoc + */ + addClient(driver: IClientDriver): void; + } +} +declare namespace samchon.protocol { + /** + * An interface for a server. + * + * {@link IServer} is an interfaec for server classes who are providing methods for {@link open opening a server} and + * {@link IClientDriver accepting clients}. + * + * To open a server, extends one of derived class under below considedring which protocol to follow first. At next, + * overrides {@link addClient addClient()} method who accepts a newly connected client as an {@link IClientDriver} + * object. Then at last, call {@link open open()} method with specified port number. + * + * Protocol | Derived Type | Related {@link IClientDriver} + * ------------------------|-------------------------------|------------------------------------- + * Samchon Framework's own | {@link Server} | {@link ClientDriver} + * Web-socket protocol | {@link WebServer} | {@link WebClientDriver} + * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerClientDriver} + * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerClientDriver} + * + * Below codes and classes will be good examples for comprehending how to open a server and handle remote clients. + * - https://github.com/samchon/framework-examples/blob/master/calculator/calculator-server.ts + * - https://github.com/samchon/framework-examples/blob/master/chat-server/server.ts + * - {@link service.Server} + * - {@link external.ExternalClientArray} + * - {@link slave.SlaveServer} + * + * If you're embarrased because your class already extended another one, then use {@link IServerBase}. + * + * + * + * + * + * @see {@link IClientDriver}, {@link IServerBase} + * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserver) + * @author Jeongho Nam + */ + interface IServer { + /** + * Open server. + * + * @param port Port number to open. + */ + open(port: number): void; + /** + * Close server. + * + * Close opened server. All remote clients, have connected with this server, are also closed and their call back + * functions, for closed connection, {@link IClientDriver.onClose} are also called. + */ + close(): void; + /** + * Add a newly connected remote client. + * + * The {@link addClient addClient()} is an abstract method being called when a remote client is newly connected + * with {@link IClientDriver} object who communicates with the remote system. Overrides this method and defines + * what to do with the *driver*, a newly connected remote client. + * + * Below methods and example codes may be good for comprehending how to utilize this {@link addClient} method. + * + * - https://github.com/samchon/framework-examples/blob/master/calculator/calculator-server.ts + * - https://github.com/samchon/framework-examples/blob/master/chat-server/server.ts + * - {@link service.Server.addClient} + * - {@link external.ExternalClientArray.addClient} + * - {@link slave.SlaveServer.addClient} + * + * @param driver A {@link ICommunicator communicator} with (newly connected) remote client. + */ + addClient(driver: IClientDriver): void; + } +} +declare namespace samchon.templates.distributed { + /** + * Master of Distributed Processing System, a server accepting slave clients. + * + * The {@link DistributedClientArray} is an abstract class, derived from the {@link DistributedSystemArray} class, + * opening a server accepting {@link DistributedSystem distributed clients}. + * + * Extends this {@link DistributedClientArray}, overrides {@link createServerBase createServerBase()} to determine + * which protocol to follow and {@link createExternalClient createExternalClient()} creating child + * {@link DistributedSystem} object. After the extending and overridings, open this server using the + * {@link open open()} method. + * + * #### [Inherited] {@link DistributedSystemArray} + * @copydoc DistributedSystemArray + */ + abstract class DistributedClientArray extends DistributedSystemArray implements external.IExternalClientArray { + /** + * @hidden + */ + private server_base_; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating {@link IServerBase} object. + * + * This method {@link createServerBase createServerBase()} determines which protocol is used in this server, + * {@link ExternalClientArray}. If the protocol is determined, then {@link ExternalSystem external clients} who + * may connect to {@link ExternalClientArray this server} must follow the specified protocol. + * + * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: + * + * - {@link ServerBase} + * - {@link WebServerBase} + * - {@link SharedWorkerServerBase} + * + * @return A new {@link IServerBase} object. + */ + protected abstract createServerBase(): protocol.IServerBase; + /** + * Add a newly connected remote client. + * + * When a {@link IClientDriver remote client} connects to this *master server of parallel processing system*, + * then this {@link ParallelClientArray} creates a child {@link ParallelSystem parallel client} object through + * the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. + * + * @param driver A communicator for external client. + */ + addClient(driver: protocol.IClientDriver): void; + /** + * (Deprecated) Factory method creating child object. + * + * The method {@link createChild createChild()} is deprecated. Don't use and override this. + * + * Note that, the {@link ParallelClientArray} is a server accepting {@link ParallelSystem parallel clients}. + * There's no way to creating the {@link ParallelSystem parallel clients} in advance before opening the server. + * + * @param xml An {@link XML} object represents the child {@link ParallelSystem} object. + * @return ```null``` + */ + createChild(xml: library.XML): System; + /** + * Factory method creating {@link DistributedSystem} object. + * + * The method {@link createExternalClient createExternalClient()} is a factory method creating a child + * {@link ParallelSystem} object, that is called whenever a parallel client has connected, by + * {@link addClient addClient()}. + * + * Overrides this {@link createExternalClient} method and creates a type of {@link DistributedSystem} object with + * the *driver* that communicates with the parallel client. After the creation, returns the object. Then whenever + * a parallel client has connected, matched {@link DistributedSystem} object will be constructed and + * {@link insert inserted} into this {@link DistributedSystemArray} object. + * + * @param driver A communicator with the parallel client. + * @return A newly created {@link ParallelSystem} object. + */ + protected abstract createExternalClient(driver: protocol.IClientDriver): System; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.templates.distributed { + /** + * Mediator of Distributed Processing System, a server accepting slave clients. + * + * The {@link DistributedClientArrayMediator} is an abstract class, derived from {@link DistributedSystemArrayMediator} + * class, opening a server accepting {@link DistributedSystem distributed clients} as a **master**. + * + * Extends this {@link DistributedClientArrayMediator}, overrides {@link createServerBase createServerBase()} to + * determine which protocol to follow and {@link createExternalClient createExternalClient()} creating child + * {@link DistributedSystem} object. After the extending and overridings, open this server using the + * {@link open open()} method. + * + * #### [Inherited] {@link DistributedSystemArrayMediator} + * @copydoc DistributedSystemArrayMediator + */ + abstract class DistributedClientArrayMediator extends DistributedSystemArrayMediator implements external.IExternalClientArray { + /** + * A subrogator of {@link IServer server}'s role instead of this {@link ExternalClientArray}. + */ + private server_base_; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating {@link IServerBase} object. + * + * This method {@link createServerBase createServerBase()} determines which protocol is used in this + * {@link DistributedClientArrayMediator} object as a **master**. If the protocol is determined, then + * {@link DistributedSystem distributed clients} who may connect to {@link DistributedClientArrayMediator this + * server} must follow the specified protocol. + * + * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: + * + * - {@link ServerBase} + * - {@link WebServerBase} + * - {@link SharedWorkerServerBase} + * + * @return A new {@link IServerBase} object. + */ + protected abstract createServerBase(): protocol.IServerBase; + /** + * Add a newly connected remote client. + * + * When a {@link IClientDriver remote client} connects to this *master server of distributed processing system*, + * then this {@link DistributedClientArrayMediator} creates a child {@link Distributed distributed client} object + * through the {@link createExternalClient createExternalClient()} method. + * + * @param driver A communicator for external client. + */ + addClient(driver: protocol.IClientDriver): void; + /** + * (Deprecated) Factory method creating child object. + * + * The method {@link createChild createChild()} is deprecated. Don't use and override this. + * + * Note that, the {@link DistributedClientArrayMediator} is a server accepting {@link DistributedSystem distributed + * clients} as a master. There's no way to creating the {@link DistributedSystem distributed clients} in advance + * before opening the server. + * + * @param xml An {@link XML} object represents the child {@link DistributedSystem} object. + * @return null + */ + createChild(xml: library.XML): System; + /** + * Factory method creating {@link DistributedSystem} object. + * + * The method {@link createExternalClient createExternalClient()} is a factory method creating a child + * {@link DistributedSystem} object, that is called whenever a distributed client has connected, by + * {@link addClient addClient()}. + * + * Overrides this {@link createExternalClient} method and creates a type of {@link DistributedSystem} object with + * the *driver* that communicates with the distributed client. After the creation, returns the object. Then whenever + * a distributed client has connected, matched {@link DistributedSystem} object will be constructed and + * {@link insert inserted} into this {@link DistributedClientArrayMediator} object. + * + * @param driver A communicator with the distributed client. + * @return A newly created {@link DistributedSystem} object. + */ + protected abstract createExternalClient(driver: protocol.IClientDriver): System; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.templates.external { + /** + * An external system driver. + * + * The {@link ExternalSystem} class represents an external system, connected and interact with this system. + * {@link ExternalSystem} takes full charge of network communication with the remote, external system have connected. + * Replied {@link Invoke} messages from the external system is shifted to and processed in, children elements of this + * class, {@link ExternalSystemRole} objects. + * + * + * + * + * + * #### Bridge & Proxy Pattern + * The {@link ExternalSystem} class can be a *bridge* for *logical proxy*. In framework within user, + * which {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not + * important. Only interested in user's perspective is *which can be done*. + * + * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. + * + *
                + *
              • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
              • + *
              • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
              • + *
              • Those strategy is called *Bridge Pattern* and *Proxy Pattern*.
              • + *
              + * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @author Jeongho Nam + */ + abstract class ExternalSystem extends protocol.EntityDequeCollection implements protocol.IProtocol { + /** + * The name represents external system have connected. + */ + protected name: string; + /** + * @hidden + */ + private system_array_; + /** + * @hidden + */ + private communicator_; + /** + * Construct from parent {@link ExternalSystemArray}. + * + * @param systemArray The parent {@link ExternalSystemArray} object. + */ + constructor(systemArray: ExternalSystemArray); + /** + * Constrct from parent {@link ExternalSystemArray} and communicator. + * + * @param systemArray The parent {@link ExternalSystemArray} object. + * @param communicator Communicator with the remote, external system. + */ + constructor(systemArray: ExternalSystemArray, communicator: protocol.IClientDriver); + /** + * Default Destructor. + * + * This {@link destructor destructor()} method is called when the {@link ExternalSystem} object is destructed and + * the {@link ExternalSystem} object is destructed when connection with the remote system is closed or this + * {@link ExternalSystem} object is {@link ExternalSystemArray.erase erased} from its parent + * {@link ExternalSystemArray} object. + * + * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically + * by those *destruction* cases. Also, if your derived {@link ExternalSystem} class has something to do on the + * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. + * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. + * + * ```typescript + * class SomeSystem extends templates.external.ExternalSystem + * { + * protected destructor(): void + * { + * // DO SOMETHING + * this.do_something(); + * + * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS + * super.destructor(); + * } + * } + * ``` + */ + protected destructor(): void; + /** + * @hidden + */ + private _Handle_close(); + /** + * Get parent {@link ExternalSystemArray} object. + */ + getSystemArray(): ExternalSystemArray; + /** + * Get parent {@link ExternalSystemArray} object. + */ + getSystemArray>(): SystemArray; + /** + * Identifier of {@link ExternalSystem} is its {@link name}. + * + * @return name. + */ + key(): string; + /** + * Get {@link name}. + */ + getName(): string; + /** + * @hidden + */ + /** + * @hidden + */ + protected communicator: protocol.ICommunicator; + /** + * Close connection. + */ + close(): void; + /** + * Send {@link Invoke} message to external system. + * + * @param invoke An {@link Invoke} message to send. + */ + sendData(invoke: protocol.Invoke): void; + /** + * Handle an {@Invoke} message has received. + * + * @param invoke An {@link Invoke} message have received. + */ + replyData(invoke: protocol.Invoke): void; + /** + * Tag name of the {@link ExternalSystem} in {@link XML}. + * + * @return *system*. + */ + TAG(): string; + /** + * Tag name of {@link ExternalSystemRole children elements} belonged to the {@link ExternalSystem} in {@link XML}. + * + * @return *role*. + */ + CHILD_TAG(): string; + } +} +declare namespace samchon.templates.parallel { + /** + * A driver for a parallel slave system. + * + * The {@link ParallelSystem} is an abstract class represents a **slave** system in *Parallel Processing System*, + * connected with this **master** system. This {@link ParallelSystem} takes full charge of network communication with + * the remote, parallel **slave** system has connected. + * + * When a *parallel process* is requested (by {@link ParallelSystemArray.sendSegmentData} or + * {@link ParallelSystemArray.sendPieceData}), the number of pieces to be allocated to a {@link ParallelSystem} is + * turn on its {@link getPerformance performance index}. Higher {@link getPerformance performance index}, then + * more pieces are requested. The {@link getPerformance performance index} is revaluated whenever a *parallel process* + * has completed, basic on the execution time and number of pieces. You can sugguest or enforce the + * {@link getPerformance performance index} with {@link setPerformance} or {@link enforcePerformance}. + * + * + * + * + * + * #### Bridge & Proxy Pattern + * This class {@link ParallelSystem} is derived from the {@link ExternalSystem} class. Thus, you can take advantage + * of the *Bridge & Proxy Pattern* in this {@link ParallelSystem} class. If a process to request is not the + * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it + * may better to utilizing the *Bridge & Proxy Pattern*: + * + * The {@link ExternalSystem} class can be a *bridge* for *logical proxy*. In framework within user, + * which {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not + * important. Only interested in user's perspective is *which can be done*. + * + * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. + * + *
                + *
              • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
              • + *
              • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
              • + *
              • Those strategy is called *Bridge Pattern* and *Proxy Pattern*.
              • + *
              + * + * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) + * @author Jeongho Nam + */ + abstract class ParallelSystem extends external.ExternalSystem { + /** + * @hidden + */ + private progress_list_; + /** + * @hidden + */ + private history_list_; + /** + * @hidden + */ + private exclude_; + /** + * @hidden + */ + private performance; + /** + * @hidden + */ + private enforced_; + /** + * Construct from parent {@link ParallelSystemArray}. + * + * @param systemArray The parent {@link ParallelSystemArray} object. + */ + constructor(systemArray: ParallelSystemArray); + /** + * Construct from parent {@link ParallelSystemArray} and communicator. + * + * @param systemArray The parent {@link ParallelSystemArray} object. + * @param communicator A communicator communicates with remote, the external system. + */ + constructor(systemArray: ParallelSystemArray, communicator: protocol.IClientDriver); + /** + * Default Destructor. + * + * This {@link destructor destructor()} method is called when the {@link ParallelSystem} object is destructed and + * the {@link ParallelSystem} object is destructed when connection with the remote system is closed or this + * {@link ParallelSystem} object is {@link ParallelSystemArray.erase erased} from its parent + * {@link ParallelSystemArray} object. + * + * You may think if there're some *parallel processes* have requested but not completed yet, then it would be a + * critical problem because the *parallel processes* will not complete forever. Do not worry. The critical problem + * does not happen. After the destruction, the remained *parallel processes* will be shifted to and proceeded in + * other {@link ParallelSystem} objects. + * + * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically + * by those *destruction* cases. Also, if your derived {@link ParallelSystem} class has something to do on the + * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. + * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. + * + * ```typescript + * class SomeSystem extends protocol.external.ExternalSystem + * { + * protected destructor(): void + * { + * // DO SOMETHING + * this.do_something(); + * + * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS + * super.destructor(); + * } + * } + * ``` + */ + protected destructor(): void; + /** + * Get manager of this object. + * + * @return The parent {@link ParallelSystemArray} object. + */ + getSystemArray(): ParallelSystemArray; + /** + * Get manager of this object. + * + * @return The parent {@link ParallelSystemArray} object. + */ + getSystemArray>(): SystemArray; + /** + * Get performance index. + * + * Get *performance index* that indicates how much fast the remote system is. + * + * If this {@link ParallelSystem parallel system} does not have any {@link Invoke} message had handled, then the + * *performance index* will be ```1.0```, which means default and average value between all {@link ParallelSystem} + * instances (that are belonged to a same {@link ParallelSystemArray} object). + * + * You can specify this *performance index* by yourself but notice that, if the *performance index* is higher + * than other {@link ParallelSystem} objects, then this {@link ParallelSystem parallel system} will be ordered to + * handle more processes than other {@link ParallelSystem} objects. Otherwise, the *performance index* is lower + * than others, of course, less processes will be delivered. + * + * - {@link setPerformance setPerformance()} + * - {@link enforcePerformance enforcePerformance()} + * + * Unless {@link enforcePerformance enforcePerformance()} is called, This *performance index* is **revaluated** + * whenever user calls one of them below. + * + * - {@link ParallelSystemArray.sendSegmentData ParallelSystemArray.sendSegmentData()} + * - {@link ParallelSystemArray.sendPieceData ParallelSystemArray.sendPieceData()} + * - {@link DistributedProcess.sendData DistributedProcess.sendData()}. + * + * @return Performance index. + */ + getPerformance(): number; + /** + * Set performance index. + * + * Set *performance index* that indicates how much fast the remote system is. This *performance index* can be + * **revaulated**. + * + * Note that, initial and average *performance index* of {@link ParallelSystem} objects are ```1.0```. If the + * *performance index* is higher than other {@link ParallelSystem} objects, then this {@link ParallelSystem} will + * be ordered to handle more processes than other {@link ParallelSystem} objects. Otherwise, the + * *performance index* is lower than others, of course, less processes will be delivered. + * + * Unlike {@link enforcePerformance}, configuring *performance index* by this {@link setPerformance} allows + * **revaluation**. This **revaluation** prevents wrong valuation from user. For example, you *mis-valuated* the + * *performance index*. The remote system is much faster than any other, but you estimated it to the slowest one. + * It looks like a terrible case that causes {@link ParallelSystemArray entire parallel systems} to be slower, + * however, don't mind. The system will direct to the *propriate performance index* eventually with the + * **revaluation** by following methods. + * + * - {@link ParallelSystemArray.sendSegmentData ParallelSystemArray.sendSegmentData()} + * - {@link ParallelSystemArray.sendPieceData ParallelSystemArray.sendPieceData()} + * - {@link DistributedProcess.sendData DistributedProcess.sendData()}. + * + * @param val New performance index, but can be revaluated. + */ + setPerformance(val: number): void; + /** + * Enforce performance index. + * + * Enforce *performance index* that indicates how much fast the remote system is. The *performance index* will be + * fixed, never be **revaluated**. + * + * Note that, initial and average *performance index* of {@link ParallelSystem} objects are ```1.0```. If the + * *performance index* is higher than other {@link ParallelSystem} objects, then this {@link ParallelSystem} will + * be ordered to handle more processes than other {@link ParallelSystem} objects. Otherwise, the + * *performance index* is lower than others, of course, less processes will be delivered. + * + * The difference between {@link setPerformance} and this {@link enforcePerformance} is allowing **revaluation** + * or not. This {@link enforcePerformance} does not allow the **revaluation**. The *performance index* is clearly + * fixed and never be changed by the **revaluation**. But you've to keep in mind that, you can't avoid the + * **mis-valuation** with this {@link enforcePerformance}. + * + * For example, there's a remote system much faster than any other, but you **mis-estimated** it to the slowest. + * In that case, there's no way. The {@link ParallelSystemArray entire parallel systems} will be slower by the + * **mis-valuation**. By the reason, using {@link enforcePerformance}, it's recommended only when you can clearly + * certain the *performance index*. If you can't certain the *performance index* but want to recommend, then use + * {@link setPerformance} instead. + * + * @param val New performance index to be fixed. + */ + enforcePerformance(val: number): void; + /** + * @hidden + */ + private _Send_piece_data(invoke, first, last); + /** + * @hidden + */ + private _Reply_data(invoke); + /** + * @hidden + */ + protected _Report_history(xml: library.XML): void; + /** + * @hidden + */ + protected _Send_back_history(invoke: protocol.Invoke, history: slave.InvokeHistory): void; + } +} +declare namespace samchon.templates.distributed { + /** + * A driver for a distributed slave system. + * + * The {@link DistributedSystem} is an abstract class represents a **slave** system in *Distributed Processing System*, + * connected with this **master** system. This {@link DistributedSystem} takes full charge of network communication + * with the remote, distributed **slave** system has connected. + * + * This {@link DistributedSystem} has a {@link getPerformance performance index} that indicates how much the **slave** + * system is fast. The {@link getPerformance performance index} is referenced and revaluated whenever those methods + * are called: + * + * - Requesting a *parallel process* + * - {@link DistributedSystemArray.sendSegmentData} + * - {@link DistributedSystemArray.sendPieceData} + * - Requesting a *distributed process*: {@link DistributedProcess.sendData} + * + * Note that, this {@link DistributedSystem} class derived from the {@link ExternalSystem} class. Thus, this + * {@link DistributedSystem} can also have children {@link ExternalSystemRole} objects exclusively. However, the + * children {@link ExternalSystemRole roles} objects are different with the {@link DistributedProcess}. The + * domestic {@link ExternalSystemRole roles} are belonged to only a specific {@link DistributedSystem} object. + * Otherwise, the {@link DistributedProcess} objects are belonged to a {@link DistributedSystemArray} object. + * Furthermore, the relationship between this {@link DistributedSystem} and {@link DistributedProcess} classes are + * **M: N Associative**. + * + * Articles | {@link DistributedProcess} | {@link ExternalSystemRole} + * -------------|--------------------------------|---------------------------- + * Belonged to | {@link DistributedSystemArray} | {@link DistributedSystem} + * Relationship | M: N Associative | 1: N Composite + * Ownership | References | Exclusive possession + * + * + * + * + * + * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) + * @author Jeongho Nam + */ + abstract class DistributedSystem extends parallel.ParallelSystem { + /** + * Construct from parent {@link DistributedSystemArray}. + * + * @param systemArray The parent {@link DistributedSystemArray} object. + */ + constructor(systemArray: DistributedSystemArray); + /** + * Constrct from parent {@link DistributedSystemArray} and communicator. + * + * @param systemArray The parent {@link DistributedSystemArray} object. + * @param communicator A communicator communicates with remote, the external system. + */ + constructor(systemArray: DistributedSystemArray, communicator: protocol.IClientDriver); + /** + * Factory method creating a {@link ExternalSystemRole child} object. + * + * In {@link distributed} module, the process class {@link DistributedProcess} is not belonged to a specific + * {@link DistributedSystem} object. It only belongs to a {@link DistributedSystemArray} object and has a + * **M: N Associative Relationship** between this {@link DistributedSystem} class. + * + * By that reason, it's the normal case that the {@link DistributedSystem} object does not have any children + * {@link ExternalSystemRole} object. Thus, default {@link createChild} returns ```null```. + * + * However, if you want a {@link DistributedSystem} to have its own domestic {@link ExternalSystemRole} objects + * without reference to the {@link DistributedProcess} objects, it is possible. Creates and returns the + * domestic {@link ExternalSystemRole} object. + * + * @param xml {@link XML} represents the {@link ExternalSystemRole child} object. + * @return A newly created {@link ExternalSystemRole} object or ```null```. + */ + createChild(xml: library.XML): external.ExternalSystemRole; + /** + * Get manager of this object. + * + * @return The parent {@link DistributedSystemArray} object. + */ + getSystemArray(): DistributedSystemArray; + /** + * Get manager of this object. + * + * @return The parent {@link DistributedSystemArray} object. + */ + getSystemArray>(): SystemArray; + /** + * @hidden + */ + private _Compute_average_elapsed_time(); + /** + * @inheritdoc + */ + replyData(invoke: protocol.Invoke): void; + /** + * @hidden + */ + protected _Report_history(xml: library.XML): void; + /** + * @hidden + */ + protected _Send_back_history(invoke: protocol.Invoke, history: slave.InvokeHistory): void; + } +} +declare namespace samchon.templates.distributed { + /** + * A driver for distributed slave server. + * + * The {@link DistributedServer} is an abstract class, derived from the {@link DistributedSystem} class, connecting to + * remote, distributed **slave** server. Extends this {@link DistributedServer} class and overrides the + * {@link createServerConnector createServerConnector()} method following which protocol the **slave** server uses. + * + * #### [Inheritdoc] {@link DistributedSystem} + * @copydoc DistributedSystem + */ + abstract class DistributedServer extends DistributedSystem implements external.IExternalServer { + /** + * IP address of target external system to connect. + */ + protected ip: string; + /** + * Port number of target external system to connect. + */ + protected port: number; + /** + * Construct from parent {@link DistributedSystemArray}. + * + * @param systemArray The parent {@link DistributedSystemArray} object. + */ + constructor(systemArray: DistributedSystemArray); + /** + * Factory method creating {@link IServerConnector} object. + * + * The {@link createServerConnector createServerConnector()} is an abstract method creating + * {@link IServerConnector} object. Overrides and returns one of them, considering which protocol the slave server + * follows: + * + * - {@link ServerConnector} + * - {@link WebServerConnector} + * - {@link DedicatedWorkerServerConnector} + * - {@link SharedWorkerServerConnector} + * + * @return A newly created {@link IServerConnector} object. + */ + protected abstract createServerConnector(): protocol.IServerConnector; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.distributed { + /** + * Master of Distributed Processing System, a client connecting to slave servers. + * + * The {@link DistributedServerArray} is an abstract class, derived from the {@link DistributedSystemArray} class, + * connecting to {@link IDistributedServer distributed servers}. + * + * Extends this {@link DistributedServerArray} and overrides {@link createChild createChild()} method creating child + * {@link IDistributedServer} object. After the extending and overriding, construct children {@link IDistributedServer} + * objects and call the {@link connect connect()} method. + * + * #### [Inherited] {@link DistributedSystemArray} + * @copydoc DistributedSystemArray + */ + abstract class DistributedServerArray extends DistributedSystemArray implements external.IExternalServerArray { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.distributed { + /** + * Mediator of Distributed Processing System, a client connecting to slave servers. + * + * The {@link DistributedServerArrayMediator} is an abstract class, derived from {@link DistributedSystemArrayMediator} + * class, connecting to {@link IDistributedServer distributed servers}. + * + * Extends this {@link DistributedServerArrayMediator} and overrides {@link createChild createChild()} method creating + * child {@link IDistributedServer} object. After the extending and overriding, construct children + * {@link IDistributedServer} objects and call the {@link connect connect()} method. + * + * #### [Inherited] {@link DistributedSystemArrayMediator} + * @copydoc DistributedSystemArrayMediator + */ + abstract class DistributedServerArrayMediator extends DistributedSystemArrayMediator implements external.IExternalServerArray { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.distributed { + /** + * Master of Distributed Processing System, be a server and client at the same time. + * + * The {@link DistributedServerClientArray} is an abstract class, derived from the {@link DistributedSystemArray} + * class, opening a server accepting {@link Distributed distributed clients} and being a client connecting to + * {@link IDistributedServer distributed servers} at the same time. + * + * Extends this {@link DistributedServerClientArray} and overrides below methods. After the overridings, open server + * with {@link open open()} method and connect to {@link IDistributedServer distributed servers} through the + * {@link connect connect()} method. + * + * - {@link createServerBase createServerBase()} + * - {@link createExternalClient createExternalClient()} + * - {@link createExternalServer createExternalServer()} + * + * #### [Inherited] {@link DistributedSystemArray} + * @copydoc DistributedSystemArray + */ + abstract class DistributedServerClientArray extends DistributedClientArray implements external.IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method of a child Entity. + * + * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * @return A new child Entity via {@link createExternalServer createExternalServer()}. + */ + createChild(xml: library.XML): System; + /** + * Factory method creating an {@link IDistributedServer} object. + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * @return A newly created {@link IDistributedServer} object. + */ + protected abstract createExternalServer(xml: library.XML): System; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.distributed { + /** + * Mediator of Distributed Processing System, be a server and client at the same time as a **master**. + * + * The {@link DistributedServerClientArrayMediator} is an abstract class, derived from the + * {@link DistributedSystemArrayMediator} class, opening a server accepting {@link DistributedSystem distributed + * clients} and being a client connecting to {@link IDistributedServer distributed servers} at the same time. + * + * Extends this {@link DistributedServerClientArrayMediator} and overrides below methods. After the overridings, open + * server with {@link open open()} method and connect to {@link IDistributedServer distributed servers} through the + * {@link connect connect()} method. + * + * - {@link createServerBase createServerBase()} + * - {@link createExternalClient createExternalClient()} + * - {@link createExternalServer createExternalServer()} + * + * #### [Inherited] {@link DistributedSystemArrayMediator} + * @copydoc DistributedSystemArrayMediator + */ + abstract class DistributedServerClientArrayMediator extends DistributedClientArrayMediator implements external.IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method of a child Entity. + * + * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * @return A new child Entity via {@link createExternalServer createExternalServer()}. + */ + createChild(xml: library.XML): System; + /** + * Factory method creating an {@link IDistributedServer} object. + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * @return A newly created {@link IDistributedServer} object. + */ + protected abstract createExternalServer(xml: library.XML): System; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.distributed { + /** + * A process of Distributed Processing System. + * + * The {@link DistributedProcess} is an abstract class who represents a **process**, *SOMETHING TO DISTRIBUTE* in a Distributed + * Processing System. Overrides the {@link DistributedProcess} and defines the *SOMETHING TO DISTRIBUTE*. + * + * Relationship between {@link DistributedSystem} and {@link DistributedProcess} objects are **M: N Associative**. + * Unlike {@link ExternalSystemRole}, the {@link DistributedProcess} objects are not belonged to a specific + * {@link DistributedSystem} object. The {@link DistributedProcess} objects are belonged to the + * {@link DistributedSystemArrayMediator} directly. + * + * When you need the **distributed process**, then call {@link sendData sendData()}. The {@link sendData} will find + * the most idle {@link DistributedSystem slave system} considering not only number of processes on progress, but also + * {@link DistributedSystem.getPerformance performance index} of each {@link DistributedSystem} object and + * {@link getResource resource index} of this {@link DistributedProcess} object. The {@link Invoke} message + * requesting the **distributed process** will be sent to the most idle {@link DistributedSystem slave system}. + * + * Those {@link DistributedSystem.getPerformance performance index} and {@link getResource resource index} are + * revaluated whenever the **distributed process** has completed basis on the execution time. + * + * + * + * + * + * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) + * @author Jeongho Nam + */ + abstract class DistributedProcess extends protocol.Entity implements protocol.IProtocol { + /** + * @hidden + */ + private system_array_; + /** + * A name, represents and identifies this {@link DistributedProcess process}. + * + * This {@link name} is an identifier represents this {@link DistributedProcess process}. This {@link name} is + * used in {@link DistributedSystemArray.getProcess} and {@link DistributedSystemArray.getProcess}, as a key elements. + * Thus, this {@link name} should be unique in its parent {@link DistributedSystemArray} object. + */ + protected name: string; + /** + * @hidden + */ + private progress_list_; + /** + * @hidden + */ + private history_list_; + /** + * @hidden + */ + private resource; + /** + * @hidden + */ + private enforced_; + /** + * Constrct from parent {@link DistributedSystemArray} object. + * + * @param systemArray The parent {@link DistributedSystemArray} object. + */ + constructor(systemArray: DistributedSystemArray); + /** + * Identifier of {@link ParallelProcess} is its {@link name}. + */ + key(): string; + /** + * Get parent {@link DistributedSystemArray} object. + * + * @return The parent {@link DistributedSystemArray} object. + */ + getSystemArray(): DistributedSystemArray; + /** + * Get parent {@link DistributedSystemArray} object. + * + * @return The parent {@link DistributedSystemArray} object. + */ + getSystemArray>(): SystemArray; + /** + * Get name, who represents and identifies this process. + */ + getName(): string; + /** + * Get resource index. + * + * Get *resource index* that indicates how much this {@link DistributedProcess process} is heavy. + * + * If this {@link DistributedProcess process} does not have any {@link Invoke} message had handled, then the + * *resource index* will be ```1.0```, which means default and average value between all + * {@link DistributedProcess} instances (that are belonged to a same {@link DistributedSystemArray} object). + * + * You can specify the *resource index* by yourself, but notice that, if the *resource index* is higher than + * other {@link DistributedProcess} objects, then this {@link DistributedProcess process} will be ordered to + * handle less processes than other {@link DistributedProcess} objects. Otherwise, the *resource index* is + * lower than others, of course, much processes will be requested. + * + * - {@link setResource setResource()} + * - {@link enforceResource enforceResource()} + * + * Unless {@link enforceResource enforceResource()} is called, This *resource index* is **revaluated** whenever + * {@link sendData sendData()} is called. + * + * @return Resource index. + */ + getResource(): number; + /** + * Set resource index. + * + * Set *resource index* that indicates how much this {@link DistributedProcess process} is heavy. This + * *resource index* can be **revaulated**. + * + * Note that, initial and average *resource index* of {@link DistributedProcess} objects are ```1.0```. If the + * *resource index* is higher than other {@link DistributedProcess} objects, then this + * {@link DistributedProcess} will be ordered to handle more processes than other {@link DistributedProcess} + * objects. Otherwise, the *resource index* is lower than others, of course, less processes will be requested. + * + * Unlike {@link enforceResource}, configuring *resource index* by this {@link setResource} allows the + * **revaluation**. This **revaluation** prevents wrong valuation from user. For example, you *mis-valuated* the + * *resource index*. The {@link DistributedProcess process} is much heavier than any other, but you estimated it + * to the lightest one. It looks like a terrible case that causes + * {@link DistributedSystemArray entire distributed processing system} to be slower, however, don't mind. The + * {@link DistributedProcess process} will the direct to the *propriate resource index* eventually with the + * **revaluation**. + * + * - The **revaluation** is caused by the {@link sendData sendData()} method. + * + * @param val New resource index, but can be revaluated. + */ + setResource(val: number): void; + /** + * Enforce resource index. + * + * Enforce *resource index* that indicates how much heavy the {@link DistributedProcess process is}. The + * *resource index* will be fixed, never be **revaluated**. + * + * Note that, initial and average *resource index* of {@link DistributedProcess} objects are ```1.0```. If the + * *resource index* is higher than other {@link DistributedProcess} objects, then this + * {@link DistributedProcess} will be ordered to handle more processes than other {@link DistributedProcess} + * objects. Otherwise, the *resource index* is lower than others, of course, less processes will be requested. + * + * The difference between {@link setResource} and this {@link enforceResource} is allowing **revaluation** or not. + * This {@link enforceResource} does not allow the **revaluation**. The *resource index* is clearly fixed and + * never be changed by the **revaluation**. But you've to keep in mind that, you can't avoid the **mis-valuation** + * with this {@link enforceResource}. + * + * For example, there's a {@link DistributedProcess process} much heavier than any other, but you + * **mis-estimated** it to the lightest. In that case, there's no way. The + * {@link DistributedSystemArray entire distributed processing system} will be slower by the **mis-valuation**. + * By the reason, using {@link enforceResource}, it's recommended only when you can clearly certain the + * *resource index*. If you can't certain the *resource index* but want to recommend, then use {@link setResource} + * instead. + * + * @param val New resource index to be fixed. + */ + enforceResource(val: number): void; + /** + * @hidden + */ + private _Compute_average_elapsed_time(); + /** + * @inheritdoc + */ + abstract replyData(invoke: protocol.Invoke): void; + /** + * Send an {@link Invoke} message. + * + * Sends an {@link Invoke} message requesting a **distributed process**. The {@link Invoke} message will be sent + * to the most idle {@link DistributedSystem} object, which represents a slave system, and the most idle + * {@link DistributedSystem} object will be returned. + * + * When the **distributed process** has completed, then the {@link DistributedSystemArray} object will revaluate + * {@link getResource resource index} and {@link DistributedSystem.getPerformance performance index} of this + * {@link DistributedSystem} and the most idle {@link DistributedSystem} objects basis on the execution time. + * + * @param invoke An {@link Invoke} message requesting distributed process. + * @return The most idle {@link DistributedSystem} object who may send the {@link Invoke} message. + */ + sendData(invoke: protocol.Invoke): DistributedSystem; + /** + * Send an {@link Invoke} message. + * + * Sends an {@link Invoke} message requesting a **distributed process**. The {@link Invoke} message will be sent + * to the most idle {@link DistributedSystem} object, which represents a slave system, and the most idle + * {@link DistributedSystem} object will be returned. + * + * When the **distributed process** has completed, then the {@link DistributedSystemArray} object will revaluate + * {@link getResource resource index} and {@link DistributedSystem.getPerformance performance index} of this + * {@link DistributedSystem} and the most idle {@link DistributedSystem} objects basis on the execution time. + * + * @param invoke An {@link Invoke} message requesting distributed process. + * @param weight Weight of resource which indicates how heavy this {@link Invoke} message is. Default is 1. + * + * @return The most idle {@link DistributedSystem} object who may send the {@link Invoke} message. + */ + sendData(invoke: protocol.Invoke, weight: number): DistributedSystem; + /** + * @hidden + */ + private _Complete_history(history); + /** + * @inheritdoc + */ + TAG(): string; + } +} +declare namespace samchon.templates.slave { + /** + * History of an {@link Invoke} message. + * + * The {@link InvokeHistory} is a class archiving history log of an {@link Invoke} message with elapsed time. This + * {@link InvokeHistory} class is used to report elapsed time of handling a requested process from **slave** to + * **master** system. + * + * The **master** system utilizes derived {@link InvokeHistory} objects to compute performance indices. + * - {@link ParallelSytem.getPerformance} + * - {@link DistributedProcess.getResource} + * + * @author Jeongho Nam + */ + class InvokeHistory extends protocol.Entity { + /** + * @hidden + */ + private uid; + /** + * @hidden + */ + private listener; + /** + * @hidden + */ + private start_time_; + /** + * @hidden + */ + private end_time_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from an {@link Invoke} message. + * + * @param invoke An {@link Invoke} message requesting a *parallel or distributed process*. + */ + constructor(invoke: protocol.Invoke); + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * Complete the history. + * + * Completes the history and determines the {@link getEndTime end time}. + */ + complete(): void; + key(): number; + /** + * Get unique ID. + */ + getUID(): number; + /** + * Get {@link Invoke.getListener listener} of the {@link Invoke} message. + */ + getListener(): string; + /** + * Get start time. + */ + getStartTime(): Date; + /** + * Get end time. + */ + getEndTime(): Date; + /** + * Compute elapsed time. + * + * @return nanoseconds. + */ + computeElapsedTime(): number; + /** + * @inheritdoc + */ + TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + /** + * Convert to an {@link Invoke} message. + * + * Creates and returns an {@link Invoke} message that is used to reporting to the **master**. + */ + toInvoke(): protocol.Invoke; + } +} +declare namespace samchon.templates.distributed { + /** + * History of an {@link Invoke} message. + * + * The {@link PRInvokeHistory} is a class archiving history log of an {@link Invoke} message which requests the + * *distributed process*, created whenever {@link DistributedProcess.sendData} is called. + * + * When the *distributed process* has completed, then {@link complete complete()} is called and the *elapsed time* is + * determined. The elapsed time is utilized for computation of {@link DistributedSystem.getPerformance performance index} + * and {@link DistributedProcess.getResource resource index} of related objects. + * + * + * + * + * + * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) + * @author Jeongho Nam + */ + class DSInvokeHistory extends slave.InvokeHistory { + /** + * @hidden + */ + private system_; + /** + * @hidden + */ + private process_; + /** + * @hidden + */ + private weight_; + /** + * Construct from a DistributedSystem. + * + * @param system The {@link DistributedSystem} object who sent the {@link Invoke} message. + */ + constructor(system: DistributedSystem); + /** + * Initilizer Constructor. + * + * @param system The {@link DistributedSystem} object who sent the {@link Invoke} message. + * @param process The {@link DistributedProcess} object who sent the {@link Invoke} message. + * @param invoke An {@link Invoke} message requesting the *distributed process*. + * @param weight Weight of resource which indicates how heavy this {@link Invoke} message is. + */ + constructor(system: DistributedSystem, process: DistributedProcess, invoke: protocol.Invoke, weight: number); + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * Get the related {@link DistributedSystem} object. + */ + getSystem(): DistributedSystem; + /** + * Get the related {@link DistributedProcess} object. + */ + getProcess(): DistributedProcess; + /** + * Get weight. + * + * Gets weight of resource which indicates how heavy this {@link Invoke} message is. Default is 1. + */ + getWeight(): number; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.templates.distributed { + /** + * An interface for a distributed slave server driver. + * + * The easiest way to defining a driver for distributed **slave** server is extending {@link DistributedServer} class. + * However, if you've to interact with a prallel **slave** system who can be both server and client, them make a class + * (let's name it **BaseSystem**) extending the {@link DistributedServer} class. At next, make a new class (now, I name + * it **BaseServer**) extending the **BaseSystem** and implements this interface {@link IParallelServer}. Define the + * **BaseServer** following those codes on below: + * + * + * + * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) + * @author Jeongho Nam + */ + interface IDistributedServer extends DistributedSystem { + /** + * Connect to external server. + */ + connect(): void; + } +} +declare namespace samchon.templates.external { + /** + * An array and manager of {@link ExternalSystem external clients} as a server. + * + * The {@link ExternalClientArray} is an abstract class, derived from the {@link ExternalSystemArray} class, opening + * a server accepting {@link ExternalSystem external clients}. + * + * Extends this {@link ExternalClientArray}, overrides {@link createServerBase createServerBase()} to determine which + * protocol to follow and {@link createExternalClient createExternalClient()} creating child {@link ExternalSystem} + * object. After the extending and overridings, open this server using the {@link open open()} method. + * + * #### [Inherited] {@link ExternalSystemArray} + * @copydoc ExternalSystemArray + */ + abstract class ExternalClientArray extends ExternalSystemArray implements IExternalClientArray { + /** + * @hidden + */ + private server_base_; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating {@link IServerBase} object. + * + * This method {@link createServerBase createServerBase()} determines which templates is used in this server, + * {@link ExternalClientArray}. If the templates is determined, then {@link ExternalSystem external clients} who + * may connect to {@link ExternalClientArray this server} must follow the specified templates. + * + * Creates and returns one of them: + * + * - {@link ServerBase} + * - {@link WebServerBase} + * - {@link SharedWorkerServerBase} + * + * @return A new {@link IServerBase} object. + */ + protected abstract createServerBase(): protocol.IServerBase; + /** + * Add a newly connected remote client. + * + * When a {@link IClientDriver remote client} connects to this *server* {@link ExternalClientArray} object, + * then this {@link ExternalClientArray} creates a child {@link ExternalSystem external client} object through + * the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. + * + * @param driver A communicator for external client. + */ + addClient(driver: protocol.IClientDriver): void; + /** + * (Deprecated) Factory method creating child object. + * + * The method {@link createChild createChild()} is deprecated. Don't use and override this. + * + * Note that, the {@link ExternalClientArray} is a server accepting {@link ExternalSystem external clients}. + * There's no way to creating the {@link ExternalSystem external clients} in advance before opening the server. + * + * @param xml An {@link XML} object represents the child {@link ExternalSystem} object. + * @return null + */ + createChild(xml: library.XML): T; + /** + * Factory method creating a child {@link ExternalSystem} object. + * + * @param driver A communicator with connected client. + * @return A newly created {@link ExternalSystem} object. + */ + protected abstract createExternalClient(driver: protocol.IClientDriver): T; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.templates.external { + /** + * An external server driver. + * + * The {@link ExternalServer} is an abstract class, derived from the {@link ExternalSystem} class, connecting to + * remote, external server. Extends this {@link ExternalServer} class and overrides the + * {@link createServerConnector createServerConnector()} method following which protocol the external server uses. + * + * #### [Inherited] {@link ExternalSystem} + * @copydoc ExternalSystem + */ + abstract class ExternalServer extends ExternalSystem implements IExternalServer { + /** + * IP address of target external system to connect. + */ + protected ip: string; + /** + * Port number of target external system to connect. + */ + protected port: number; + /** + * Construct from parent {@link ExternalSystemArray}. + * + * @param systemArray The parent {@link ExternalSystemArray} object. + */ + constructor(systemArray: ExternalSystemArray); + /** + * Factory method creating {@link IServerConnector} object. + * + * The {@link createServerConnector createServerConnector()} is an abstract method creating + * {@link IServerConnector} object. Overrides and returns one of them, considering which templates the external + * system follows: + * + * - {@link ServerConnector} + * - {@link WebServerConnector} + * - {@link DedicatedWorkerServerConnector} + * - {@link SharedWorkerServerConnector} + * + * @return A newly created {@link IServerConnector} object. + */ + protected abstract createServerConnector(): protocol.IServerConnector; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.external { + /** + * An array and manager of {@link IExternalServer external servers}. + * + * The {@link ExternalServerArray} is an abstract class, derived from the {@link ExternalSystemArray} class, + * connecting to {@link IExternalServer external servers}. + * + * Extends this {@link ExternalServerArray} and overrides {@link createChild createChild()} method creating child + * {@link IExternalServer} object. After the extending and overriding, construct children {@link IExternalServer} + * objects and call the {@link connect connect()} method. + * + * #### [Inherited] {@link ExternalSystemArray} + * @copydoc ExternalSystemArray + */ + abstract class ExternalServerArray extends ExternalSystemArray implements IExternalServerArray { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.external { + /** + * An array and manager of {@link IExternalServer external servers} and {@link ExternalSystem external clients}. + * + * The {@link ExternalServerClientArray} is an abstract class, derived from the {@link ExternalSystemArray} class, + * opening a server accepting {@link ExternalSystem external clients} and being a client connecting to + * {@link IExternalServer external servers} at the same time. + * + * Extends this {@link ExternalServerClientArray} and overrides below methods. After the overridings, open server + * with {@link open open()} method and connect to {@link IExternalServer external servers} through the + * {@link connect connect()} method. + * + * - {@link createServerBase createServerBase()} + * - {@link createExternalClient createExternalClient()} + * - {@link createExternalServer createExternalServer()} + * + * #### [Inherited] {@link ExternalSystemArray} + * @copydoc ExternalSystemArray + */ + abstract class ExternalServerClientArray extends ExternalClientArray implements IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method of a child Entity. + * + * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * @return A new child Entity via {@link createExternalServer createExternalServer()}. + */ + createChild(xml: library.XML): T; + /** + * Factory method creating an {@link IExternalServer} object. + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * @return A newly created {@link IExternalServer} object. + */ + protected abstract createExternalServer(xml: library.XML): T; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.external { + /** + * A role of an external system. + * + * The {@link ExternalSystemRole} class represents a role, *WHAT TO DO*. Extends the {@link ExternalSystemRole} class + * and overrides {@link replyData replyData()} to define the *WHAT TO DO*. And assign this {@link ExternalSystemRole} + * object to related {@link ExternalSystem} object. + * + * + * + * + * + * #### Proxy Pattern + * The {@link ExternalSystemRole} class can be an *logical proxy*. In framework within user, which + * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not + * important. Only interested in user's perspective is *which can be done*. + * + * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. + * + *
                + *
              • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem} object, via {@link ExternalSystemArray.getRole ExternalSystemArray.getRole()}. + *
              • + *
              • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
              • + *
              • Those strategy is called *Proxy Pattern*.
              • + *
              + * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @author Jeongho Nam + */ + abstract class ExternalSystemRole extends protocol.Entity implements protocol.IProtocol { + /** + * @hidden + */ + private system; + /** + * A name, represents and identifies this {@link ExternalSystemRole role}. + * + * This {@link name} is an identifier represents this {@link ExternalSystemRole role}. This {@link name} is + * used in {@link ExternalSystemArray.getRole} and {@link ExternalSystem.get}, as a key elements. Thus, this + * {@link name} should be unique in an {@link ExternalSystemArray}. + */ + protected name: string; + /** + * Constructor from a system. + * + * @param system An external system containing this role. + */ + constructor(system: ExternalSystem); + /** + * Identifier of {@link ExternalSystemRole} is its {@link name}. + */ + key(): string; + /** + * Get grandparent {@link ExternalSystemArray}. + * + * Get the grandparent {@link ExternalSystemArray} object through this parent {@link ExternalSystem}, + * {@link ExternalSystem.getSystemArray ExternalSystem.getSystemArray()}. + * + * @return The grandparent {@link ExternalSystemArray} object. + */ + getSystemArray(): ExternalSystemArray; + /** + * Get parent {@link ExternalSystemRole} object. + */ + getSystem(): ExternalSystem; + /** + * Get name, who represents and identifies this role. + */ + getName(): string; + /** + * Send an {@link Invoke} message. + * + * Sends an {@link Invoke} message to remote system through the parent {@link ExternalSystem} object. + * + * @param invoke An {@link Invoke} message to send to the external system. + */ + sendData(invoke: protocol.Invoke): void; + /** + * Handle replied {@link Invoke} message. + * + * {@link ExternalSystemRole.replyData ExternalSystemRole.replyData()} is an abstract method handling a replied + * {@link Invoke message} gotten from remote system via parent {@link ExternalSystem} object. Overrides this + * method and defines the *WHAT TO DO* with the {@link Invoke message}. + * + * @param invoke An {@link Invoke} message received from the {@link ExternalSystem external system}. + */ + abstract replyData(invoke: protocol.Invoke): void; + /** + * Tag name of the {@link ExternalSytemRole} in {@link XML}. + * + * @return *role*. + */ + TAG(): string; + } +} +declare namespace samchon.templates.external { + /** + * An interface for an {@link ExternalSystemArray} accepts {@link ExternalSystem external clients} as a + * {@link IServer server}. + * + * The easiest way to defining an {@link ExternalSystemArray} who opens server and accepts + * {@link ExternalSystem external clients} is to extending one of below, who are derived from this interface + * {@link IExternalClientArray}. However, if you can't specify an {@link ExternalSystemArray} to be whether server or + * client, then make a class (let's name it as **BaseSystemArray**) extending {@link ExternalSystemArray} and make + * a new class (now, I name it **BaseClientArray**) extending **BaseSystemArray** and implementing this + * interface {@link IExternalClientArray}. Define the **BaseClientArray** following those codes on below: + * + * + * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @author Jeongho Nam + */ + interface IExternalClientArray extends ExternalSystemArray, protocol.IServer { + } +} +declare namespace samchon.templates.external { + /** + * An interface for an external server driver. + * + * The easiest way to defining an external server driver is to extending one of below, who are derived from this + * interface {@link IExternalServer}. However, if you've to interact with an external system who can be both server + * and client, then make a class (let's name it as **BaseSystem**) extending {@link ExternalSystem} and make a + * new class (now, I name it **BaseServer**) extending **BaseSystem** and implementing this interface + * {@link IExternalServer}. Define the **BaseServer** following those codes on below: + * + * + * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @author Jeongho Nam + */ + interface IExternalServer extends ExternalSystem { + /** + * Connect to the external server. + */ + connect(): void; + } +} +declare namespace samchon.templates.external { + /** + * An interface for an {@link ExternalSystemArray} connects to {@link IExternalServer external servers} as a + * **client**. + * + * The easiest way to defining an {@link ExternalSystemArray} who connects to + * {@link IExternalServer external servers} is to extending one of below, who are derived from this interface + * {@link IExternalServerArray}. However, if you can't specify an {@link ExternalSystemArray} to be whether server or + * client, then make a class (let's name it as **BaseSystemArray**) extending {@link ExternalSystemArray} and make + * a new class (now, I name it **BaseServerArray**) extending **BaseSystemArray** and implementing this + * interface {@link IExternalServerArray}. Define the **BaseServerArray** following those codes on below: + * + * + * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @author Jeongho Nam + */ + interface IExternalServerArray extends ExternalSystemArray { + /** + * Connect to {@link IExternalServer external servers}. + * + * This method calls children elements' method {@link IExternalServer.connect} gradually. + */ + connect(): void; + } +} +declare namespace samchon.templates.external { + /** + * An interface for an {@link ExternalSystemArray} accepts {@link ExternalSystem external clients} as a + * {@link IServer server} and connects to {@link IExternalServer} as **client**, at the same time. + * + * The easiest way to defining an {@link IExternalServerClientArray} who opens server, accepts + * {@link ExternalSystem external clients} and connects to {@link IExternalServer external servers} is to extending + * one of below, who are derived from this interface {@link IExternalServerClientArray}. However, if you can't + * specify an {@link ExternalSystemArray} to be whether server or client or even can both them, then make a class + * (let's name it as **BaseSystemArray**) extending {@link ExternalSystemArray} and make a new class (now, I name + * it **BaseServerClientArray**) extending **BaseSystemArray** and implementing this interface + * {@link IExternalServerClientArray}. Define the **BaseServerClientArray** following those codes on below: + * + * + * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @author Jeongho Nam + */ + interface IExternalServerClientArray extends IExternalClientArray { + /** + * Connect to {@link IExternalServer external servers}. + * + * This method calls children elements' method {@link IExternalServer.connect} gradually. + */ + connect(): void; + } +} +declare namespace samchon.templates.slave { + /** + * A slave system. + * + * @author Jeongho Nam + */ + abstract class SlaveSystem implements protocol.IProtocol { + /** + * @hidden + */ + protected communicator_: protocol.ICommunicator; + /** + * Default Constructor. + */ + constructor(); + sendData(invoke: protocol.Invoke): void; + abstract replyData(invoke: protocol.Invoke): void; + /** + * @hidden + */ + protected _Reply_data(invoke: protocol.Invoke): void; + } +} +declare namespace samchon.templates.parallel { + /** + * A mediator, the master driver. + * + * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** + * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. + * + * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the + * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which + * type and protocol the **master** system follows: + * + * - A client slave connecting to master server: + * - {@link MediatorClient} + * - {@link MediatorWebClient} + * - {@link MediatorSharedWorkerClient} + * - A server slave accepting master client: + * - {@link MediatorServer} + * - {@link MediatorWebServer} + * - {@link MediatorDedicatedWorkerServer} + * - {@link MediatorSharedWorkerServer} + * + * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the + * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The + * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, + * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the + * result to its **master**. + * + * + * + * + * + * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), + * [Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) + * @author Jeongho Nam + */ + abstract class MediatorSystem extends slave.SlaveSystem { + /** + * @hidden + */ + private system_array_; + /** + * @hidden + */ + private progress_list_; + /** + * Construct from parent {@link ParallelSystemArrayMediator} object. + * + * @param systemArray The parent {@link ParallelSystemArrayMediator} object. + */ + constructor(systemArray: ParallelSystemArrayMediator); + /** + * Construct from parent {@link DistributedSystemArrayMediator} object. + * + * @param systemArray The parent {@link DistributedSystemArrayMediator} object. + */ + constructor(systemArray: distributed.DistributedSystemArrayMediator); + /** + * Start interaction. + * + * The {@link start start()} is an abstract method starting interaction with the **master** system. If the + * **master** is a server, then connects to the **master**. Otherwise, the **master** is client, then this + * {@link MediatorSystem} object wil open a server accepting the **master**. + */ + abstract start(): void; + /** + * Get parent {@link ParallelSystemArrayMediator} or {@link DistributedSystemArrayMediator} object. + */ + getSystemArray(): ParallelSystemArrayMediator | distributed.DistributedSystemArrayMediator; + /** + * Get parent {@link ParallelSystemArrayMediator} object. + */ + getSystemArray>(): SystemArray; + /** + * Get parent {@link DistributedSystemArrayMediator} object. + */ + getSystemArray>(): SystemArray; + /** + * @hidden + */ + private _Complete_history(uid); + /** + * @hidden + */ + protected _Reply_data(invoke: protocol.Invoke): void; + /** + * @inheritdoc + */ + replyData(invoke: protocol.Invoke): void; + } +} +declare namespace samchon.templates.parallel { + /** + * A mediator client, driver for the master server. + * + * The {@link MediatorServer} is a class being a client connecting to the **master** server, following the protocol + * of Samchon Framework's own. + * + * #### [Inherited] {@link MediatorSystem} + * @copydoc MediatorSystem + */ + class MediatorClient extends MediatorSystem implements slave.ISlaveClient { + /** + * @hidden + */ + private ip; + /** + * @hidden + */ + private port; + /** + * Initializer Constructor. + * + * @param systemArray The parent {@link ParallelSystemArrayMediator} object. + * @param ip IP address to connect. + * @param port Port number to connect. + */ + constructor(systemArray: ParallelSystemArrayMediator, ip: string, port: number); + /** + * Initializer Constructor. + * + * @param systemArray The parent {@link DistributedSystemArrayMediator} object. + * @param ip IP address to connect. + * @param port Port number to connect. + */ + constructor(systemArray: distributed.DistributedSystemArrayMediator, ip: string, port: number); + /** + * Factory method creating {@link IServerConnector} object. + * + * The {@link createServerConnector createServerConnector()} is an abstract method creating + * {@link IServerConnector} object. Overrides and returns one of them, considering which protocol the **master** + * server follows: + * + * - {@link ServerConnector} + * - {@link WebServerConnector} + * - {@link SharedWorkerServerConnector} + * + * @return A newly created {@link IServerConnector} object. + */ + protected createServerConnector(): protocol.IServerConnector; + /** + * @inheritdoc + */ + start(): void; + /** + * @inheritdoc + */ + connect(): void; + } + /** + * A mediator client, driver for the master server. + * + * The {@link MediatorWebClient} is a class being a client connecting to the **master** server, following the + * web-socket protocol. + * + * #### [Inherited] {@link MediatorSystem} + * @copydoc MediatorSystem + */ + class MediatorWebClient extends MediatorClient { + /** + * @inheritdoc + */ + protected createServerConnector(): protocol.IServerConnector; + } + /** + * A mediator client, driver for the master server. + * + * The {@link MediatorSharedWorkerClient} is a class being a client connecting to the **master** server, following + * the SharedWorker's protocol. + * + * #### [Inherited] {@link MediatorSystem} + * @copydoc MediatorSystem + */ + class MediatorSharedWorkerClient extends MediatorClient { + /** + * @inheritdoc + */ + protected createServerConnector(): protocol.IServerConnector; + } +} +declare namespace samchon.templates.parallel { + /** + * A mediator server, driver for the master client. + * + * The {@link MediatorServer} is a class opening a server accepting the **master** client, following the protocol of + * Samchon Framework's own. + * + * #### [Inherited] {@link MediatorSystem} + * @copydoc MediatorSystem + */ + class MediatorServer extends MediatorSystem implements slave.ISlaveServer { + /** + * @hidden + */ + private server_base_; + /** + * @hidden + */ + private port; + /** + * Initializer Constructor. + * + * @param systemArray The parent {@link ParallelSystemArrayMediator} object. + * @param port Port number of server to open. + */ + constructor(systemArray: ParallelSystemArrayMediator, port: number); + /** + * Initializer Constructor. + * + * @param systemArray The parent {@link DistributedSystemArrayMediator} object. + * @param port Port number of server to open. + */ + constructor(systemArray: distributed.DistributedSystemArrayMediator, port: number); + /** + * Factory method creating {@link IServerBase} object. + * + * This method {@link createServerBase createServerBase()} determines which protocol is used in this server, + * {@link MediatorServer}. Note that, **slave** (this {@link MediatorServer} object) must follow the **master**'s + * protocol. + * + * Overrides and return one of them considering the which protocol to follow: + * + * - {@link ServerBase} + * - {@link WebServerBase} + * - {@link SharedWorkerServerBase} + */ + protected createServerBase(): protocol.IServerBase; + /** + * Add a newly connected remote client. + * + * {@link MediatorServer} represents a **slave** dedicating to its **master**. In that reason, the + * {@link MediatorServer} does not accept multiple **master** clients. It accepts only one. Thus, *listener* of + * the *communicator* is {@link MediatorSystem} object, itself. + * + * @param driver A communicator with remote client. + */ + addClient(driver: protocol.IClientDriver): void; + /** + * @inheritdoc + */ + start(): void; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } + /** + * A mediator server, driver for the master client. + * + * The {@link MediatorWebServer} is a class opening a server accepting the **master** client, following the + * web-socket protocol. + * + * #### [Inherited] {@link MediatorSystem} + * @copydoc MediatorSystem + */ + class MediatorWebServer extends MediatorServer { + /** + * @inheritdoc + */ + protected createServerBase(): protocol.IServerBase; + } + /** + * A mediator server, driver for the master client. + * + * The {@link MediatorDedicatedWorkerServer} is a class opening a server accepting the **master** client, following + * the DedicatedWorker's protocol. + * + * #### [Inherited] {@link MediatorSystem} + * @copydoc MediatorSystem + */ + class MediatorDedicatedWorkerServer extends MediatorServer { + /** + * @inheritdoc + */ + protected createServerBase(): protocol.IServerBase; + } + /** + * A mediator server, driver for the master client. + * + * The {@link MediatorSharedWorkerServer} is a class opening a server accepting the **master** client, following the + * SharedWorker's protocol. + * + * #### [Inherited] {@link MediatorSystem} + * @copydoc MediatorSystem + */ + class MediatorSharedWorkerServer extends MediatorServer { + /** + * @inheritdoc + */ + protected createServerBase(): protocol.IServerBase; + } +} +declare namespace samchon.templates.parallel { + /** + * Master of Parallel Processing System, a server accepting slave clients. + * + * The {@link ParallelClientArray} is an abstract class, derived from the {@link ParallelSystemArray} class, opening + * a server accepting {@link ParallelSystem parallel clients}. + * + * Extends this {@link ParallelClientArray}, overrides {@link createServerBase createServerBase()} to determine which + * protocol to follow and {@link createExternalClient createExternalClient()} creating child {@link ParallelSystem} + * object. After the extending and overridings, open this server using the {@link open open()} method. + * + * #### [Inherited] {@link ParallelSystemArray} + * @copydoc ParallelSystemArray + */ + abstract class ParallelClientArray extends ParallelSystemArray implements external.IExternalClientArray { + /** + * @hidden + */ + private server_base_; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating {@link IServerBase} object. + * + * This method {@link createServerBase createServerBase()} determines which protocol is used in this server, + * {@link ExternalClientArray}. If the protocol is determined, then {@link ExternalSystem external clients} who + * may connect to {@link ExternalClientArray this server} must follow the specified protocol. + * + * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: + * + * - {@link ServerBase} + * - {@link WebServerBase} + * - {@link SharedWorkerServerBase} + * + * @return A new {@link IServerBase} object. + */ + protected abstract createServerBase(): protocol.IServerBase; + /** + * Add a newly connected remote client. + * + * When a {@link IClientDriver remote client} connects to this *master server of parallel processing system*, + * then this {@link ParallelClientArray} creates a child {@link ParallelSystem parallel client} object through + * the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. + * + * @param driver A communicator for external client. + */ + addClient(driver: protocol.IClientDriver): void; + /** + * (Deprecated) Factory method creating child object. + * + * The method {@link createChild createChild()} is deprecated. Don't use and override this. + * + * Note that, the {@link ParallelClientArray} is a server accepting {@link ParallelSystem parallel clients}. + * There's no way to creating the {@link ParallelSystem parallel clients} in advance before opening the server. + * + * @param xml An {@link XML} object represents the child {@link ParallelSystem} object. + * @return ```null``` + */ + createChild(xml: library.XML): System; + /** + * Factory method creating {@link ParallelSystem} object. + * + * The method {@link createExternalClient createExternalClient()} is a factory method creating a child + * {@link ParallelSystem} object, that is called whenever a parallel client has connected, by + * {@link addClient addClient()}. + * + * Overrides this {@link createExternalClient} method and creates a type of {@link ParallelSystem} object with + * the *driver* that communicates with the parallel client. After the creation, returns the {@link ParallelSystem} + * object. Then whenever a parallel client has connected, matched {@link ParallelSystem} object will be + * constructed and {@link insert inserted} into this {@link ParallelClientArray} object. + * + * @param driver A communicator with the parallel client. + * @return A newly created {@link ParallelSystem} object. + */ + protected abstract createExternalClient(driver: protocol.IClientDriver): System; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * Mediator of Parallel Processing System. + * + * The {@link ParallelSystemArrayMediator} class be a **master** for its slave systems, and be a **slave** to its + * master system at the same time. This {@link ParallelSystemArrayMediator} be a **master **system, containing and + * managing {@link ParallelSystem} objects, which represent parallel slave systems, by extending + * {@link ParallelSystemArray} class. Also, be a **slave** system through {@link getMediator mediator} object, which is + * derived from the {@link SlaveSystem} class. + * + * As a **master**, you can specify this {@link ParallelSystemArrayMediator} class to be a master server accepting + * slave clients or a master client to connecting slave servers. Even both of them is possible. Extends one + * of them below and overrides abstract factory method(s) creating the child {@link ParallelSystem} object. + * + * - {@link ParallelClientArrayMediator}: A server accepting {@link ParallelSystem parallel clients}. + * - {@link ParallelServerArrayMediator}: A client connecting to {@link ParallelServer parallel servers}. + * - {@link ParallelServerClientArrayMediator}: Both of them. Accepts {@link ParallelSystem parallel clients} and + * connects to {@link ParallelServer parallel servers} at the same time. + * + * As a **slave**, you can specify this {@link ParallelSystemArrayMediator} to be a client slave connecting to + * master server or a server slave accepting master client by overriding the {@link createMediator} method. + * Overrides the {@link createMediator createMediator()} method and return one of them: + * + * - A client slave connecting to master server: + * - {@link MediatorClient} + * - {@link MediatorWebClient} + * - {@link MediatorSharedWorkerClient} + * - A server slave accepting master client: + * - {@link MediatorServer} + * - {@link MediatorWebServer} + * - {@link MediatorDedicatedWorkerServer} + * - {@link MediatorSharedWorkerServer} + * + * #### [Inherited] {@link ParallelSystemArray} + * @copydoc ParallelSystemArray + */ + abstract class ParallelSystemArrayMediator extends ParallelSystemArray { + /** + * @hidden + */ + private mediator_; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating a {@link MediatorSystem} object. + * + * The {@link createMediator createMediator()} is an abstract method creating the {@link MediatorSystem} object. + * + * You know what? this {@link ParallelSystemArrayMediator} class be a **master** for its slave systems, and be a + * **slave** to its master system at the same time. The {@link MediatorSystem} object makes it possible; be a + * **slave** system. This {@link createMediator} determines specific type of the {@link MediatorSystem}. + * + * Overrides the {@link createMediator createMediator()} method to create and return one of them following which + * protocol and which type of remote connection (server or client) will be used: + * + * - A client slave connecting to master server: + * - {@link MediatorClient} + * - {@link MediatorWebClient} + * - {@link MediatorSharedWorkerClient} + * - A server slave accepting master client: + * - {@link MediatorServer} + * - {@link MediatorWebServer} + * - {@link MediatorDedicatedWorkerServer} + * - {@link MediatorSharedWorkerServer} + * + * @return A newly created {@link MediatorSystem} object. + */ + protected abstract createMediator(): MediatorSystem; + /** + * Start mediator. + * + * If the {@link getMediator mediator} is a type of server, then opens the server accepting master client. + * Otherwise, the {@link getMediator mediator} is a type of client, then connects the master server. + */ + protected startMediator(): void; + /** + * Get {@link MediatorSystem} object. + * + * When you need to send an {@link Invoke} message to the master system of this + * {@link ParallelSystemArrayMediator}, then send to the {@link MediatorSystem} through this {@link getMediator}. + * + * ```typescript + * this.getMediator().sendData(...); + * ``` + * + * @return The {@link MediatorSystem} object. + */ + getMediator(): MediatorSystem; + /** + * @hidden + */ + protected _Complete_history(history: slave.InvokeHistory): boolean; + } +} +declare namespace samchon.templates.parallel { + /** + * Mediator of Parallel Processing System, a server accepting slave clients. + * + * The {@link ParallelClientArrayMediator} is an abstract class, derived from the {@link ParallelSystemArrayMediator} + * class, opening a server accepting {@link ParallelSystem parallel clients} as a **master**. + * + * Extends this {@link ParallelClientArrayMediator}, overrides {@link createServerBase createServerBase()} to + * determine which protocol to follow and {@link createExternalClient createExternalClient()} creating child + * {@link ParallelSystem} object. After the extending and overridings, open this server using the + * {@link open open()} method. + * + * #### [Inherited] {@link ParallelSystemArrayMediator} + * @copydoc ParallelSystemArrayMediator + */ + abstract class ParallelClientArrayMediator extends ParallelSystemArrayMediator implements external.IExternalClientArray { + /** + * @hidden + */ + private server_base_; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating {@link IServerBase} object. + * + * This method {@link createServerBase createServerBase()} determines which protocol is used in this server, + * {@link ParallelClientArrayMediator}. If the protocol is determined, then + * {@link ParallelSystem parallel clients} who may connect to {@link ParallelClientArrayMediator this server} + * must follow the specified protocol. + * + * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: + * + * - {@link ServerBase} + * - {@link WebServerBase} + * - {@link SharedWorkerServerBase} + * + * @return A new {@link IServerBase} object. + */ + protected abstract createServerBase(): protocol.IServerBase; + /** + * Add a newly connected remote client. + * + * When a {@link IClientDriver remote client} connects to this *master server of parallel processing system*, + * then this {@link ParallelClientArrayMediator} creates a child {@link ParallelSystem parallel client} object + * through the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. + * + * @param driver A communicator for parallel client. + */ + addClient(driver: protocol.IClientDriver): void; + /** + * (Deprecated) Factory method creating child object. + * + * The method {@link createChild createChild()} is deprecated. Don't use and override this. + * + * Note that, the {@link ParallelClientArrayMediator} is a server accepting {@link ParallelSystem parallel + * clients} as a master. There's no way to creating the {@link ParallelSystem parallel clients} in advance before + * opening the server. + * + * @param xml An {@link XML} object represents the child {@link ParallelSystem} object. + * @return null + */ + createChild(xml: library.XML): System; + /** + * Factory method creating {@link ParallelSystem} object. + * + * The method {@link createExternalClient createExternalClient()} is a factory method creating a child + * {@link ParallelSystem} object, that is called whenever a parallel client has connected, by + * {@link addClient addClient()}. + * + * Overrides this {@link createExternalClient} method and creates a type of {@link ParallelSystem} object with + * the *driver* that communicates with the parallel client. After the creation, returns the {@link ParallelSystem} + * object. Then whenever a parallel client has connected, matched {@link ParallelSystem} object will be + * constructed and {@link insert inserted} into this {@link ParallelClientArrayMediator} object. + * + * @param driver A communicator with the parallel client. + * @return A newly created {@link ParallelSystem} object. + */ + protected abstract createExternalClient(driver: protocol.IClientDriver): System; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * A driver for parallel slave server. + * + * The {@link ParallelServer} is an abstract class, derived from the {@link ParallelSystem} class, connecting to + * remote, parallel **slave** server. Extends this {@link ParallelServer} class and overrides the + * {@link createServerConnector createServerConnector()} method following which protocol the **slave** server uses. + * + * #### [Inherited] {@link ParallelSystem} + * @copydoc ParallelSystem + */ + abstract class ParallelServer extends ParallelSystem implements IParallelServer { + /** + * IP address of target external system to connect. + */ + protected ip: string; + /** + * Port number of target external system to connect. + */ + protected port: number; + /** + * Construct from parent {@link ParallelSystemArray}. + * + * @param systemArray The parent {@link ParallelSystemArray} object. + */ + constructor(systemArray: ParallelSystemArray); + /** + * Factory method creating {@link IServerConnector} object. + * + * The {@link createServerConnector createServerConnector()} is an abstract method creating + * {@link IServerConnector} object. Overrides and returns one of them, considering which protocol the slave server + * follows: + * + * - {@link ServerConnector} + * - {@link WebServerConnector} + * - {@link DedicatedWorkerServerConnector} + * - {@link SharedWorkerServerConnector} + * + * @return A newly created {@link IServerConnector} object. + */ + protected abstract createServerConnector(): protocol.IServerConnector; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * Master of Parallel Processing System, a client connecting to slave servers. + * + * The {@link ParallelServerArray} is an abstract class, derived from the {@link ParallelSystemArray} class, + * connecting to {@link IParallelServer parallel servers}. + * + * Extends this {@link ParallelServerArray} and overrides {@link createChild createChild()} method creating child + * {@link IParallelServer} object. After the extending and overriding, construct children {@link IParallelServer} + * objects and call the {@link connect connect()} method. + * + * #### [Inherited] {@link ParallelSystemArray} + * @copydoc ParallelSystemArray + */ + abstract class ParallelServerArray extends ParallelSystemArray implements external.IExternalServerArray { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * Mediator of Parallel Processing System, a client connecting to slave servers. + * + * The {@link ParallelServerArrayMediator} is an abstract class, derived from the {@link ParallelSystemArrayMediator} + * class, connecting to {@link IParallelServer parallel servers}. + * + * Extends this {@link ParallelServerArrayMediator} and overrides {@link createChild createChild()} method creating + * child {@link IParallelServer} object. After the extending and overriding, construct children + * {@link IParallelServer} objects and call the {@link connect connect()} method. + * + * #### [Inherited] {@link ParallelSystemArrayMediator} + * @copydoc ParallelSystemArrayMediator + */ + abstract class ParallelServerArrayMediator extends ParallelSystemArrayMediator implements external.IExternalServerArray { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * Master of Parallel Processing System, be a server and client at the same time. + * + * The {@link ParallelServerClientArray} is an abstract class, derived from the {@link ParallelSystemArray} class, + * opening a server accepting {@link ParallelSystem parallel clients} and being a client connecting to + * {@link IParallelServer parallel servers} at the same time. + * + * Extends this {@link ParallelServerClientArray} and overrides below methods. After the overridings, open server + * with {@link open open()} method and connect to {@link IParallelServer parallel servers} through the + * {@link connect connect()} method. + * + * - {@link createServerBase createServerBase()} + * - {@link createExternalClient createExternalClient()} + * - {@link createExternalServer createExternalServer()} + * + * #### [Inherited] {@link ParallelSystemArray} + * @copydoc ParallelClientArray + */ + abstract class ParallelServerClientArray extends ParallelClientArray implements external.IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method of a child Entity. + * + * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * @return A new child Entity via {@link createExternalServer createExternalServer()}. + */ + createChild(xml: library.XML): System; + /** + * Factory method creating an {@link IParallelServer} object. + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * @return A newly created {@link IParallelServer} object. + */ + protected abstract createExternalServer(xml: library.XML): System; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * Mediator of Parallel Processing System, be a server and client at the same time as a **master**. + * + * The {@link ParallelServerClientArrayMediator} is an abstract class, derived from the + * {@link ParallelSystemArrayMediator} class, opening a server accepting {@link ParallelSystem parallel clients} and + * being a client connecting to {@link IParallelServer parallel servers} at the same time. + * + * Extends this {@link ParallelServerClientArrayMediator} and overrides below methods. After the overridings, open + * server with {@link open open()} method and connect to {@link IParallelServer parallel servers} through the + * {@link connect connect()} method. + * + * - {@link createServerBase createServerBase()} + * - {@link createExternalClient createExternalClient()} + * - {@link createExternalServer createExternalServer()} + * + * #### [Inherited] {@link ParallelSystemArrayMediator} + * @copydoc ParallelClientArrayMediator + */ + abstract class ParallelServerClientArrayMediator extends ParallelClientArrayMediator implements external.IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method of a child Entity. + * + * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * @return A new child Entity via {@link createExternalServer createExternalServer()}. + */ + createChild(xml: library.XML): System; + /** + * Factory method creating an {@link IParallelServer} object. + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * @return A newly created {@link IParallelServer} object. + */ + protected abstract createExternalServer(xml: library.XML): System; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * An interface for a parallel slave server driver. + * + * The easiest way to defining a driver for parallel **slave** server is extending {@link ParallelServer} class. + * However, if you've to interact with a prallel **slave** system who can be both server and client, them make a class + * (let's name it **BaseSystem**) extending the {@link ParallelSystem} class. At next, make a new class (now, I name it + * **BaseServer**) extending the **BaseSystem** and implements this interface {@link IParallelServer}. Define the + * **BaseServer** following those codes on below: + * + * + * + * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) + * @author Jeongho Nam + */ + interface IParallelServer extends ParallelSystem { + /** + * Connect to slave server. + */ + connect(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * History of an {@link Invoke} message. + * + * The {@link PRInvokeHistory} is a class archiving history log of an {@link Invoke} message which requests the + * *parallel process*, created whenever {@link ParallelSystemArray.sendSegmentData} or + * {@link ParallelSystemArray.sendSegmentData} is called. + * + * When the *parallel process* has completed, then {@link complete complete()} is called and the *elapsed time* is + * determined. The elapsed time is utilized for computation of {@link ParallelSystem.getPerformance performance index} + * of each {@link ParallelSystem parallel slave system}. + * + * + * + * + * + * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) + * @author Jeongho Nam + */ + class PRInvokeHistory extends slave.InvokeHistory { + /** + * @hidden + */ + private first; + /** + * @hidden + */ + private last; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from an {@link Invoke} message. + * + * @param invoke An {@link Invoke} message requesting a *parallel process*. + */ + constructor(invoke: protocol.Invoke); + /** + * Get initial piece's index. + * + * Returns initial piece's index in the section of requested *parallel process*. + * + * @return The initial index. + */ + getFirst(): number; + /** + * Get final piece's index. + * + * Returns initial piece's index in the section of requested *parallel process*. The range used is + * [*first*, *last*), which contains all the pieces' indices between *first* and *last*, including the piece + * pointed by index *first*, but not the piece pointed by the index *last*. + * + * @return The final index. + */ + getLast(): number; + /** + * Compute number of allocated pieces. + */ + computeSize(): number; + } +} +declare namespace samchon.templates.service { + /** + * A driver of remote client. + * + * The {@link Client} is an abstract class representing and interacting with a remote client. It deals the network + * communication with the remote client and shifts {@link Invoke} message to related {@link User} and {@link Service} + * objects. + * + * Extends this {@link Client} class and override the {@link createService} method, a factory method creating a child + * {@link Service} object. Note that, {@link Client} represents a remote client, not *an user*, a specific *web page* + * or *service*. Do not define logics about user or account information. It must be declared in the parent + * {@link User} class. Also, don't define processes of a specific a web page or service. Defines them in the child + * {@link Service} class. + * + * + * + * + * + * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) + * @author Jeongho Nam + */ + abstract class Client implements protocol.IProtocol { + /** + * @hidden + */ + private user_; + /** + * @hidden + */ + private no_; + /** + * @hidden + */ + private communicator_; + /** + * @hidden + */ + private service_; + /** + * Construct from parent {@link User} and communicator. + * + * @param user Parent {@link User} object. + * @param driver Communicator with remote client. + */ + constructor(user: User, driver: protocol.WebClientDriver); + /** + * Default Destructor. + * + * This {@link destructor destructor()} method is called when the {@link Client} object is destructed and this + * {@link Client} object is destructed when connection with the remote client is closed or this {@link Client} + * object is {@link User.erase erased} from its parent {@link User} object. + * + * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically + * by those *destruction* cases. Also, if your derived {@link Client} class has something to do on the + * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. + * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. + * + * ```typescript + * class MyUser extends protocol.service.Client + * { + * protected destructor(): void + * { + * // DO SOMETHING + * this.do_something(); + * + * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS + * super.destructor(); + * } + * } + * ``` + */ + protected destructor(): void; + /** + * Factory method creating {@link Service} object. + * + * @param path Requested path. + * @return A newly created {@link Service} object or ```null```. + */ + protected abstract createService(path: string): Service; + /** + * Close connection. + */ + close(): void; + /** + * Get parent {@link User} object. + * + * Get the parent {@link User} object, who is groupping {@link Client} objects with same session id. + * + * @return The parent {@link User} object. + */ + getUser(): User; + /** + * Get child {@link Service} object. + * + * @return The child {@link Service} object. + */ + getService(): Service; + /** + * Get sequence number. + * + * Get sequence number of this {@link Client} object in the parent {@link User} object. This sequence number also + * be a *key* in the parent {@link User} object, who extended the ```std.HashMap```. + * + * @return Sequence number. + */ + getNo(): number; + /** + * Change related {@link Service} object. + * + * @param path Requested, identifier path. + */ + protected changeService(path: string): void; + /** + * Change {@link Service} to another. + * + * @param service {@link service} object to newly assigned. + */ + protected changeService(service: Service): void; + /** + * Send an {@link Invoke} message. + * + * Sends an {@link Invoke} message to remote client. + * + * @param invoke An {@link Invoke} messgae to send to remote client. + */ + sendData(invoke: protocol.Invoke): void; + /** + * Handle a replied {@link Invoke} message. + * + * The default {@link Client.replyData Client.replyData()} shifts chain to its parent {@link User} and belonged + * {@link Service} objects, by calling the the {@link User.replyData User.replyData()} and + * {@link Service.replyData Service.replyData()} methods. + * + * Note that, {@link Client} represents a remote client, not *an user*, a specific *web page* or *service*. Do not + * define logics about user or account information. It must be declared in the parent {@link User} class. Also, + * don't define processes of a specific a web page or service. Defines them in the child {@link Service} class. + * + * ```typescript + * class protocol.service.Client + * { + * public replyData(invoke: protocol.Invoke): void + * { + * // SHIFT TO PARENT USER + * // THE PARENT USER ALSO MAY SHIFT TO ITS PARENT SERVER + * this.getUser().replyData(invoke); + * + * // SHIFT TO BELOGED SERVICE + * if (this.getService() != null) + * this.getService().replyData(invoke); + * } + * } + * + * class MyClient extends protocol.service.Client + * { + * public replyData(invoke: protocol.Invoke): void + * { + * if (invoke.getListener() == "do_something_in_client_level") + * this.do_something_in_client_level(); + * else + * super.replyData(invoke); + * } + * } + * ``` + * + * @param invoke An {@link Invoke invoke} message to be handled in {@link Client} level. + */ + replyData(invoke: protocol.Invoke): void; + } +} +/** + * A system template for Cloud Service. + * + * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) + * @author Jeongho Nam + */ +declare namespace samchon.templates.service { + /** + * A cloud server. + * + * The {@link Server} is an abstract server class, who can build a real-time cloud server, that is following the + * web-socket protocol. Extends this {@link Server} and related classes and overrides abstract methods under below. + * After the overridings, open this {@link Server cloud server} using the {@link open open()} method. + * + * - Objects in composite relationship and their factory methods + * - {@link User}: {@link Server.createUser Server.createUser()} + * - {@link Client}: {@link User.createClient User.createClient()} + * - {@link Service}: {@link Client.createService Client.createService()} + * - {@link Invoke} message chains; {@link IProtocol.replyData replyData} + * - {@link Server.replyData} + * - {@link User.replyData} + * - {@link Client.replyData} + * - {@link Service.replyData} + * + * + * + * + * + * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) + * @author Jeongho Nam + */ + abstract class Server extends protocol.WebServer implements protocol.IProtocol { + /** + * @hidden + */ + private session_map_; + /** + * @hidden + */ + private account_map_; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating {@link User} object. + * + * @return A newly created {@link User} object. + */ + protected abstract createUser(): User; + /** + * Test wheter an {@link User} exists with the *accountID*. + * + * @param accountID Account id of {@link User} to find. + * @return Exists or not. + */ + has(accountID: string): boolean; + /** + * Get an {@link User} object by its *accountID*. + * + * @param accountID Account id of {@link User} to get. + * @return An {@link User} object. + */ + get(accountID: string): User; + /** + * Send an {@link Invoke} message. + * + * Sends an {@link Invoke} message to all remote clients through the belonged {@link User} and {@link Client} + * objects. Sending the {@link Invoke} message to all remote clients, it's came true by passing through + * {@link User.sendData User.sendData()}. And the {@link User.sendData} also pass through the + * {@link Client.sendData Client.sendData()}. + * + * ```typescript + * class protocol.service.Server + * { + * public sendData(invoke: Invoke): void + * { + * for (user: User in this) + * for (client: Client in user) + * client.sendData(invoke); + * } + * } + * ``` + * + * @param invoke {@link Invoke} message to send to all remote clients. + */ + sendData(invoke: protocol.Invoke): void; + /** + * Handle a replied {@link Invoke} message. + * + * The {@link Server.replyData Server.replyData()} is an abstract method that handling {@link Invoke} message + * that should be handled in the {@link Server} level. Overrides this {@link replyData replyData()} method and + * defines what to do with the {@link Invoke} message in this {@link Server} level. + * + * @param invoke An {@link Invoke invoke} message to be handled in {@link Server} level. + */ + abstract replyData(invoke: protocol.Invoke): void; + /** + * Add a newly connected remote client. + * + * When a {@link WebClientDriver remote client} connects to this cloud server, then {@link Server} queries the + * {WebClientDriver.getSessionID session id} of the {@link WebClientDriver remote client}. If the + * {WebClientDriver.getSessionID session id} is new one, then creates a new {@link User} object. + * + * At next, creates a {@link Client} object who represents the newly connected remote client and insert the + * {@link Client} object to the matched {@link User} object which is new or ordinary one following the + * {WebClientDriver.getSessionID session id}. At last, a {@link Service} object can be created with referencing + * the {@link WebClientDriver.getPath path}. + * + * List of objects can be created by this method. + * - {@link User} by {@link createUser createUser()}. + * - {@link Client} by {@link User.createClient User.createClient()}. + * - {@link Service} by {@link Client.createService Client.createService()}. + * + * @param driver A web communicator for remote client. + */ + addClient(driver: protocol.WebClientDriver): void; + /** + * @hidden + */ + private _Erase_user(user); + } +} +declare namespace samchon.templates.service { + /** + * A service. + * + * The {@link Service} is an abstract class who represents a service, that is providing functions a specific page. + * + * Extends the {@link Service} class and defines its own service, which to be provided for the specific weg page, + * by overriding the {@link replyData replyData()} method. Note that, the service, functions for the specific page + * should be defined in this {@link Service} class, not its parent {@link Client} class who represents a remote client + * and takes communication responsibility. + * + * + * + * + * + * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) + * @author Jeongho Nam + */ + abstract class Service implements protocol.IProtocol { + /** + * @hidden + */ + private client_; + /** + * @hidden + */ + private path_; + /** + * Construct from parent {@link Client} and requested path. + * + * @param client Driver of remote client. + * @param path Requested path that identifies this {@link Service}. + */ + constructor(client: Client, path: string); + /** + * Default Destructor. + * + * This {@link destructor destructor()} method is call when the {@link Service} object is destructed and the + * {@link Service} object is destructed when its parent {@link Client} object has + * {@link Client.destructor destructed} or the {@link Client} object {@link Client.changeService changed} its + * child {@link Service service} object to another one. + * + * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically + * by those *destruction* cases. Also, if your derived {@link Service} class has something to do on the + * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. + */ + protected destructor(): void; + /** + * Get client. + */ + getClient(): Client; + /** + * Get requested path. + */ + getPath(): string; + /** + * Send an {@link Invoke} message. + * + * Sends an {@link Invoke} message to remote system through parent {@link Client} object ({@link Client.sendData}). + * + * @param invoke An {@link Invoke} message to send to the remte system. + */ + sendData(invoke: protocol.Invoke): void; + /** + * @inheritdoc + */ + abstract replyData(invoke: protocol.Invoke): void; + } +} +declare namespace samchon.templates.service { + /** + * An user. + * + * The {@link User} is an abstract class groupping {@link Client} objects, who communicates with remote client, with + * same *session id*. This {@link User} represents a *remote user* literally. Within framework of remote system, + * an {@link User} corresponds to a web-browser and a {@link Client} represents a window in the web-browser. + * + * Extends this {@link User} class and override the {@link createClient} method, a factory method creating a child + * {@link Client} object. I repeat, the {@link User} class represents a *remote user*, groupping {@link Client} + * objects with same *session id*. If your cloud server has some processes to be handled in the **user level**, then + * defines method in this {@link User} class. Methods managing **account** under below are some of them: + * + * - {@link setAccount setAccount()} + * - {@link getAccountID getAccountID()} + * - {@link getAuthority getAuthority()} + * + * The children {@link Client} objects, they're contained with their key, the {@link Client.getNo sequence number}. + * If you {@link User.erase erase} the children {@link Client} object by yourself, then their connection with the + * remote clients will be {@link Client.close closed} and their {@link Client.destructor destruction method} will be + * called. If you remove {@link clear all children}, then this {@link User} object will be also + * {@link destructor destructed} and erased from the parent {@link Server} object. + * + * + * + * + * + * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) + * @author Jeongho Nam + */ + abstract class User extends collections.HashMapCollection implements protocol.IProtocol { + /** + * @hidden + */ + private server_; + /** + * @hidden + */ + private session_id_; + /** + * @hidden + */ + private sequence_; + /** + * @hidden + */ + private account_id_; + /** + * @hidden + */ + private authority_; + /** + * Construct from its parent {@link Server}. + * + * @param server The parent {@link Server} object. + */ + constructor(server: Server); + /** + * Default Destructor. + * + * This {@link destructor destructor()} method is called when the {@link User} object is destructed. The + * {@link User} object is destructed when connections with the remote clients are all closed, that is all the + * children {@link Client} objects are all removed, and 30 seconds has left. If some remote client connects + * within the 30 seconds, then the {@link User} object doesn't be destructed. + * + * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically + * by those *destruction* cases. Also, if your derived {@link User} class has something to do on the + * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. + * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. + * + * ```typescript + * class MyUser extends protocol.service.User + * { + * protected destructor(): void + * { + * // DO SOMETHING + * this.do_something(); + * + * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS + * super.destructor(); + * } + * } + * ``` + */ + protected destructor(): void; + /** + * Factory method creating a {@link Client} object. + * + * @param driver A web communicator for remote client. + * @return A newly created {@link Client} object. + */ + protected abstract createClient(driver: protocol.WebClientDriver): Client; + /** + * @hidden + */ + private _Handle_erase_client(event); + /** + * Get parent {@lin Server} object. + * + * @return Parent {@link Server} object. + */ + getServer(): Server; + /** + * Get account id. + * + * @return Account ID. + */ + getAccountID(): string; + /** + * Get authority. + * + * @return Authority + */ + getAuthority(): number; + /** + * Set *account id* and *authority*. + * + * The {@link setAccount setAccount()} is a method configuring *account id* and *authority* of this {@link User}. + * + * After the configuring, the {@link getAccountID account id} is enrolled into the parent {@link Server} as a + * **key** for this {@link User} object. You can test existence and access this {@link User} object from + * {@link Server.has Server.has()} and {@link Server.get Server.get()} with the {@link getAccountID account id}. + * Of course, if ordinary {@link getAccountID account id} had existed, then the ordinary **key** will be + * replaced. + * + * As you suggest, this {@link setAccount setAccount()} is something like a **log-in** function. If what you want + * is not **logging-in**, but **logging-out**, then configure the *account id* to empty string ``""```` or call + * the {@link lgout logout()} method. + * + * @param id To be account id. + * @param authority To be authority. + */ + setAccount(id: string, authority: number): void; + /** + * Log-out. + * + * This {@link logout logout()} method configures {@link getAccountID account id} to empty string and + * {@link getAuthority authority} to zero. + * + * The ordinary {@link getAccountID account id} will be also erased from the parent {@link Server} object. You + * can't access this {@link User} object from {@link Server.has Server.has()} and {@link Server.get Server.get()} + * with the ordinary {@link getAccountID account id} more. + */ + logout(): void; + /** + * Send an {@link Invoke} message. + * + * Sends an {@link Invoke} message to all remote clients through the belonged {@link Client} objects. Sending the + * {@link Invoke} message to all remote clients, it's came true by passing through the + * {@link Client.sendData Client.sendData()} methods. + * + * ```typescript + * class protocol.service.User + * { + * public sendData(invoke: Invoke): void + * { + * for (let it = this.begin(); !it.equals(this.end()); it = it.next()) + * it.second.sendData(invoke); + * } + * } + * ``` + * + * @param invoke {@link Invoke} message to send to all remote clients. + */ + sendData(invoke: protocol.Invoke): void; + /** + * Handle a replied {@link Invoke} message. + * + * The default {@link User.replyData User.replyData()} shifts chain to its parent {@link Server} object, by + * calling the {@link Server.replyData Server.replyData()} method. If there're some {@link Invoke} message to be + * handled in this {@link User} level, then override this method and defines what to do with the {@link Invoke} + * message in this {@link User} level. + * + * ```typescript + * class protocol.service.User + * { + * public replyData(invoke: protocol.Invoke): void + * { + * this.getServer().replyData(invoke); + * } + * } + * + * class MyUser extends protocol.service.User + * { + * public replyData(invoke: protocol.Invoke): void + * { + * if (invoke.apply(this) == false) // IS TARGET TO BE HANDLED IN THIS USER LEVEL + * super.replyData(invoke); // SHIFT TO SERVER + * } + * } + * ``` + * + * @param invoke An {@link Invoke invoke} message to be handled in {@link User} level. + */ + replyData(invoke: protocol.Invoke): void; + } +} +declare namespace samchon.templates.slave { + /** + * An {@link Invoke} message which represents a **process**. + * + * + * + * #### [Inherited] {@link Invoke} + * @copydoc Invoke + */ + class PInvoke extends protocol.Invoke { + /** + * @hidden + */ + private history_; + /** + * @hidden + */ + private slave_system_; + /** + * @hidden + */ + private hold_; + /** + * Initializer Constructor. + * + * @param invoke Original {@link Invoke} message. + * @param history {@link InvokeHistory} object archiving execution time. + * @param slaveSystem Related {@link SlaveSystem} object who gets those processes from its master. + */ + constructor(invoke: protocol.Invoke, history: InvokeHistory, slaveSystem: SlaveSystem); + /** + * Get history object. + * + * Get {@link InvokeHistory} object who is archiving execution time of this process. + */ + getHistory(): InvokeHistory; + /** + * Is the reporting hold? + */ + isHold(): boolean; + /** + * Hold reporting completion to master. + */ + hold(): void; + /** + * Report completion. + */ + complete(): void; + } +} +declare namespace samchon.templates.slave { + interface ISlaveClient extends SlaveSystem { + connect(ip: string, port: number): void; + } + abstract class SlaveClient extends SlaveSystem implements ISlaveClient { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + protected abstract createServerConnector(): protocol.IServerConnector; + /** + * @inheritdoc + */ + connect(ip: string, port: number): void; + } +} +declare namespace samchon.templates.slave { + interface ISlaveServer extends SlaveSystem, protocol.IServer { + } + abstract class SlaveServer extends SlaveSystem implements ISlaveServer { + /** + * @hidden + */ + private server_base_; + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + protected abstract createServerBase(): protocol.IServerBase; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @inheritdoc + */ + addClient(driver: protocol.IClientDriver): void; + } +} diff --git a/samchon/samchon-tests.ts b/samchon/samchon-tests.ts new file mode 100644 index 0000000000..3c805025ac --- /dev/null +++ b/samchon/samchon-tests.ts @@ -0,0 +1,2 @@ +import samchon = require("samchon"); +console.log(samchon); \ No newline at end of file diff --git a/samchon/tsconfig.json b/samchon/tsconfig.json new file mode 100644 index 0000000000..ec6c511b01 --- /dev/null +++ b/samchon/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": false, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "samchon-tests.ts" + ] +} \ No newline at end of file diff --git a/sax/sax-tests.ts b/sax/sax-tests.ts index 4d9a90293d..5b11ab425e 100644 --- a/sax/sax-tests.ts +++ b/sax/sax-tests.ts @@ -1,5 +1,3 @@ -/// - import sax = require("sax"); import fs = require("fs"); diff --git a/seamless/seamless-tests.ts b/seamless/seamless-tests.ts index 4aa1ab3aba..40ba1868be 100644 --- a/seamless/seamless-tests.ts +++ b/seamless/seamless-tests.ts @@ -1,5 +1,3 @@ -/// - /* Create Parent Seamless IFrame */ $('#myiframe').seamless(); $('#myiframe').seamless({ diff --git a/select2/index.d.ts b/select2/index.d.ts index 2f6fea9063..719e6673f8 100644 --- a/select2/index.d.ts +++ b/select2/index.d.ts @@ -14,8 +14,7 @@ interface Select2QueryOptions { } interface AjaxFunction { - (settings: JQueryAjaxSettings): JQueryXHR; - (url: string, settings?: JQueryAjaxSettings): JQueryXHR; + (settings: JQueryAjaxSettings, success?: (data: any) => null, failure?: () => null): JQueryXHR; } interface Select2AjaxOptions { @@ -38,9 +37,12 @@ interface IdTextPair { } interface Select2Options { + amdBase?: string; + amdLanguageBase?: string; width?: string; dropdownAutoWidth?: boolean; minimumInputLength?: number; + maximumInputLength?: number; minimumResultsForSearch?: number; maximumSelectionSize?: number; placeholder?: string | IdTextPair; @@ -81,6 +83,9 @@ interface Select2Options { language?: string | string[] | {}; selectOnClose?: boolean; sorter?: (data: any[]) => any[]; + dropdownParent?: JQuery; + debug?: boolean; + dropdownAdapter?: any; } interface Select2JQueryEventObject extends JQueryEventObject { @@ -192,3 +197,18 @@ interface JQuery { select2(method: string, value: any, trigger?: boolean): any; select2(options: Select2Options): JQuery; } + +declare class Select2 { + constructor(element: JQuery, options: Select2Options); + focus(): void; + destroy(): void; + on(event: string, callback: Function): void; + selection: any; + dropdown: any; + results: any; + $container: JQuery; + $dropdown: JQuery; + $selection: JQuery; + $results: JQuery; + options: {options: Select2Options}; +} \ No newline at end of file diff --git a/select2/select2-tests.ts b/select2/select2-tests.ts index ade378ee71..c10b482cab 100644 --- a/select2/select2-tests.ts +++ b/select2/select2-tests.ts @@ -1,6 +1,3 @@ -/// - - $("#e9").select2(); $("#e2").select2({ placeholder: "Select a State", diff --git a/selectize/selectize-tests.ts b/selectize/selectize-tests.ts index b2ec9e0a29..10b12c91f2 100644 --- a/selectize/selectize-tests.ts +++ b/selectize/selectize-tests.ts @@ -1,6 +1,3 @@ -/// - - var $input = $(".test-input").selectize(); var testApi = $input[0].selectize; diff --git a/selenium-webdriver/chrome.d.ts b/selenium-webdriver/chrome.d.ts index ce26566f02..2604b99e89 100644 --- a/selenium-webdriver/chrome.d.ts +++ b/selenium-webdriver/chrome.d.ts @@ -1,5 +1,6 @@ import * as webdriver from './index'; import * as remote from './remote'; +import * as http from './http'; /** * Creates a new WebDriver client for Chrome. @@ -8,15 +9,19 @@ import * as remote from './remote'; */ export class Driver extends webdriver.WebDriver { /** - * @param {(webdriver.Capabilities|Options)=} opt_config The configuration - * options. - * @param {remote.DriverService=} opt_service The session to use; will use - * the {@link getDefaultService default service} by default. - * @param {webdriver.promise.ControlFlow=} opt_flow The control flow to use, or - * {@code null} to use the currently active flow. - * @constructor + * Creates a new session with the ChromeDriver. + * + * @param {(Capabilities|Options)=} opt_config The configuration options. + * @param {(remote.DriverService|http.Executor)=} opt_serviceExecutor Either + * a DriverService to use for the remote end, or a preconfigured executor + * for an externally managed endpoint. If neither is provided, the + * {@linkplain ##getDefaultService default service} will be used by + * default. + * @param {promise.ControlFlow=} opt_flow The control flow to use, or `null` + * to use the currently active flow. + * @return {!Driver} A new driver instance. */ - constructor(opt_config?: Options | webdriver.Capabilities, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + static createSession(opt_config?: Options | webdriver.CreateSessionCapabilities, opt_service?: remote.DriverService | http.Executor, opt_flow?: webdriver.promise.ControlFlow): Driver; } interface IOptionsValues { @@ -304,7 +309,7 @@ export class Options { * Creates {@link remote.DriverService} instances that manage a ChromeDriver * server. */ -export class ServiceBuilder { +export class ServiceBuilder extends remote.DriverService.Builder { /** * @param {string=} opt_exe Path to the server executable to use. If omitted, * the builder will attempt to locate the chromedriver on the current @@ -315,15 +320,6 @@ export class ServiceBuilder { */ constructor(opt_exe?: string); - /** - * Sets the port to start the ChromeDriver on. - * @param {number} port The port to use, or 0 for any free port. - * @return {!ServiceBuilder} A self reference. - * @throws {Error} If the port is invalid. - */ - usingPort(port: number): ServiceBuilder; - - /** * Sets which port adb is listening to. _The ChromeDriver will connect to adb * if an {@linkplain Options#androidPackage Android session} is requested, but @@ -332,7 +328,7 @@ export class ServiceBuilder { * @param {number} port Which port adb is running on. * @return {!ServiceBuilder} A self reference. */ - setAdbPort(port: number): ServiceBuilder; + setAdbPort(port: number): this; /** @@ -341,14 +337,14 @@ export class ServiceBuilder { * @param {string} path Path of the log file to use. * @return {!ServiceBuilder} A self reference. */ - loggingTo(path: string): ServiceBuilder; + loggingTo(path: string): this; /** * Enables verbose logging. * @return {!ServiceBuilder} A self reference. */ - enableVerboseLogging(): ServiceBuilder; + enableVerboseLogging(): this; /** @@ -357,45 +353,7 @@ export class ServiceBuilder { * @param {number} n The number of threads to use. * @return {!ServiceBuilder} A self reference. */ - setNumHttpThreads(n: number): ServiceBuilder; - - - /** - * Sets the base path for WebDriver REST commands (e.g. '/wd/hub'). - * By default, the driver will accept commands relative to '/'. - * @param {string} path The base path to use. - * @return {!ServiceBuilder} A self reference. - */ - setUrlBasePath(path: string): ServiceBuilder; - - - /** - * Defines the stdio configuration for the driver service. See - * {@code child_process.spawn} for more information. - * @param {(string|!Array.)} config The - * configuration to use. - * @return {!ServiceBuilder} A self reference. - */ - setStdio(config: string | Array): ServiceBuilder; - - - /** - * Defines the environment to start the server under. This settings will be - * inherited by every browser session started by the server. - * @param {!Object.} env The environment to use. - * @return {!ServiceBuilder} A self reference. - */ - withEnvironment(env: { [key: string]: string }): ServiceBuilder; - - - /** - * Creates a new DriverService using this instance's current configuration. - * @return {remote.DriverService} A new driver service using this instance's - * current configuration. - * @throws {Error} If the driver exectuable was not specified and a default - * could not be found on the current PATH. - */ - build(): remote.DriverService; + setNumHttpThreads(n: number): this; } /** diff --git a/selenium-webdriver/edge.d.ts b/selenium-webdriver/edge.d.ts index b18a959700..3fb3408b1f 100644 --- a/selenium-webdriver/edge.d.ts +++ b/selenium-webdriver/edge.d.ts @@ -3,14 +3,17 @@ import * as remote from './remote'; export class Driver extends webdriver.WebDriver { /** + * Creates a new browser session for Microsoft's Edge browser. + * * @param {(capabilities.Capabilities|Options)=} opt_config The configuration * options. * @param {remote.DriverService=} opt_service The session to use; will use * the {@linkplain #getDefaultService default service} by default. * @param {promise.ControlFlow=} opt_flow The control flow to use, or * {@code null} to use the currently active flow. + * @return {!Driver} A new driver instance. */ - constructor(opt_config?: webdriver.Capabilities | Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + static createSession(opt_config?: webdriver.CreateSessionCapabilities, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow): Driver; /** * This function is a no-op as file detectors are not supported by this @@ -56,14 +59,14 @@ export class Options { * merge these options into, if any. * @return {!capabilities.Capabilities} The capabilities. */ - toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; + toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; } /** * Creates {@link remote.DriverService} instances that manage a * MicrosoftEdgeDriver server in a child process. */ -export class ServiceBuilder { +export class ServiceBuilder extends remote.DriverService.Builder { /** * @param {string=} opt_exe Path to the server executable to use. If omitted, * the builder will attempt to locate the MicrosoftEdgeDriver on the current @@ -72,40 +75,6 @@ export class ServiceBuilder { * MicrosoftEdgeDriver cannot be found on the PATH. */ constructor(opt_exe?: string); - - /** - * Defines the stdio configuration for the driver service. See - * {@code child_process.spawn} for more information. - * @param {(string|!Array.)} - * config The configuration to use. - * @return {!ServiceBuilder} A self reference. - */ - setStdio(config: string | Array): ServiceBuilder; - - /** - * Sets the port to start the MicrosoftEdgeDriver on. - * @param {number} port The port to use, or 0 for any free port. - * @return {!ServiceBuilder} A self reference. - * @throws {Error} If the port is invalid. - */ - usingPort(port: number): ServiceBuilder; - - /** - * Defines the environment to start the server under. This settings will be - * inherited by every browser session started by the server. - * @param {!Object.} env The environment to use. - * @return {!ServiceBuilder} A self reference. - */ - withEnvironment(env: Object): ServiceBuilder; - - /** - * Creates a new DriverService using this instance's current configuration. - * @return {!remote.DriverService} A new driver service using this instance's - * current configuration. - * @throws {Error} If the driver exectuable was not specified and a default - * could not be found on the current PATH. - */ - build(): remote.DriverService; } /** diff --git a/selenium-webdriver/firefox.d.ts b/selenium-webdriver/firefox.d.ts index 7678c404ce..6746c3c683 100644 --- a/selenium-webdriver/firefox.d.ts +++ b/selenium-webdriver/firefox.d.ts @@ -1,5 +1,6 @@ import * as webdriver from './index'; import * as remote from './remote'; +import * as http from './http'; /** * Manages a Firefox subprocess configured for use with WebDriver. @@ -197,11 +198,13 @@ export class Options { setProxy(proxy: webdriver.ProxyConfig): Options; /** - * Sets whether to use Mozilla's Marionette to drive the browser. + * Sets whether to use Mozilla's geckodriver to drive the browser. This option + * is enabled by default and required for Firefox 47+. * - * @see https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver + * @param {boolean} enable Whether to enable the geckodriver. + * @see https://github.com/mozilla/geckodriver */ - useMarionette(marionette: any): Options; + useGeckoDriver(enable: boolean): Options; /** * Converts these options to a {@link capabilities.Capabilities} instance. @@ -235,14 +238,32 @@ export function prepareProfile(profile: string | any, port: number): any; */ export class Driver extends webdriver.WebDriver { /** + * Creates a new Firefox session. + * * @param {(Options|capabilities.Capabilities|Object)=} opt_config The * configuration options for this driver, specified as either an * {@link Options} or {@link capabilities.Capabilities}, or as a raw hash * object. + * @param {(http.Executor|remote.DriverService)=} opt_executor Either a + * pre-configured command executor to use for communicating with an + * externally managed remote end (which is assumed to already be running), + * or the `DriverService` to use to start the geckodriver in a child + * process. + * + * If an executor is provided, care should e taken not to use reuse it with + * other clients as its internal command mappings will be updated to support + * Firefox-specific commands. + * + * _This parameter may only be used with Mozilla's GeckoDriver._ + * * @param {promise.ControlFlow=} opt_flow The flow to * schedule commands through. Defaults to the active flow object. + * @throws {Error} If a custom command executor is provided and the driver is + * configured to use the legacy FirefoxDriver from the Selenium project. + * @return {!Driver} A new driver instance. */ - constructor(opt_config?: Options | webdriver.Capabilities | Object, opt_flow?: webdriver.promise.ControlFlow); + static createSession(opt_config?: Options | webdriver.Capabilities, opt_executor?: http.Executor | remote.DriverService, opt_flow?: webdriver.promise.ControlFlow): Driver; + /** * This function is a no-op as file detectors are not supported by this @@ -251,3 +272,37 @@ export class Driver extends webdriver.WebDriver { */ setFileDetector(): void; } + +/** + * Creates {@link selenium-webdriver/remote.DriverService} instances that manage + * a [geckodriver](https://github.com/mozilla/geckodriver) server in a child + * process. + */ +export class ServiceBuilder extends remote.DriverService.Builder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the geckodriver on the system PATH. + */ + constructor(opt_exe?: string); + + /** + * Enables verbose logging. + * + * @param {boolean=} opt_trace Whether to enable trace-level logging. By + * default, only debug logging is enabled. + * @return {!ServiceBuilder} A self reference. + */ + enableVerboseLogging(opt_trace?: boolean): this; + + /** + * Sets the path to the executable Firefox binary that the geckodriver should + * use. If this method is not called, this builder will attempt to locate + * Firefox in the default installation location for the current platform. + * + * @param {(string|!Binary)} binary Path to the executable Firefox binary to use. + * @return {!ServiceBuilder} A self reference. + * @see Binary#locate() + */ + setFirefoxBinary(binary: string | Binary): this; +} + diff --git a/selenium-webdriver/http.d.ts b/selenium-webdriver/http.d.ts index a0a25a7955..4fc12afb19 100644 --- a/selenium-webdriver/http.d.ts +++ b/selenium-webdriver/http.d.ts @@ -13,7 +13,7 @@ export function headersToString(headers: any): string; * responsibility to build the full URL for the final request. * @final */ -export class HttpRequest { +export class Request { /** * @param {string} method The HTTP method to use for the request. * @param {string} path The path on the server to send the request to. @@ -29,7 +29,7 @@ export class HttpRequest { * Represents a HTTP response message. * @final */ -export class HttpResponse { +export class Response { /** * @param {number} status The response code. * @param {!Object} headers The response headers. All header names @@ -70,7 +70,7 @@ export class HttpClient { * @return {!promise.Promise} A promise that will be fulfilled * with the server's response. */ - send(httpRequest: HttpRequest): webdriver.promise.Promise; + send(httpRequest: Request): webdriver.promise.Promise; } /** @@ -99,10 +99,11 @@ export function sendRequest(options: Object, onOk: any, onError: any, opt_data?: */ export class Executor { /** - * @param {!HttpClient} client The client to use for sending requests to the - * server. + * @param {!(HttpClient|IThenable)} client The client to use for sending + * requests to the server, or a promise-like object that will resolve to + * to the client. */ - constructor(client: HttpClient); + constructor(client: HttpClient | webdriver.promise.IThenable); /** * Defines a new command for use with this executor. When a command is sent, @@ -138,7 +139,7 @@ export function tryParse(str: string): any; * @return {{value: ?}} The parsed response. * @throws {WebDriverError} If the HTTP response is an error. */ -export function parseHttpResponse(httpResponse: HttpResponse, w3c: boolean): any; +export function parseHttpResponse(httpResponse: Response, w3c: boolean): any; /** * Builds a fully qualified path using the given set of command parameters. Each diff --git a/selenium-webdriver/ie.d.ts b/selenium-webdriver/ie.d.ts index 9e8cab2457..bf3932450e 100644 --- a/selenium-webdriver/ie.d.ts +++ b/selenium-webdriver/ie.d.ts @@ -5,12 +5,15 @@ import * as webdriver from './index'; */ export class Driver extends webdriver.WebDriver { /** + * Creates a new session for Microsoft's Internet Explorer. + * * @param {(capabilities.Capabilities|Options)=} opt_config The configuration * options. * @param {promise.ControlFlow=} opt_flow The control flow to use, * or {@code null} to use the currently active flow. + * @return {!Driver} A new driver instance. */ - constructor(opt_config?: webdriver.Capabilities | Options, opt_flow?: webdriver.promise.ControlFlow); + static createSession(opt_config?: webdriver.Capabilities | Options, opt_flow?: webdriver.promise.ControlFlow): Driver; /** * This function is a no-op as file detectors are not supported by this @@ -201,5 +204,5 @@ export class Options { * merge these options into, if any. * @return {!capabilities.Capabilities} The capabilities. */ - toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; + toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; } diff --git a/selenium-webdriver/index.d.ts b/selenium-webdriver/index.d.ts index 39d56d7d5b..bfd583302e 100644 --- a/selenium-webdriver/index.d.ts +++ b/selenium-webdriver/index.d.ts @@ -1,7 +1,11 @@ -// Type definitions for Selenium WebDriverJS 2.53 +// Type definitions for Selenium WebDriverJS 3.0 // Project: https://github.com/SeleniumHQ/selenium/tree/master/javascript/node/selenium-webdriver -// Definitions by: Bill Armstrong , Yuki Kokubun , Craig Nishina +// Definitions by: Bill Armstrong , +// Yuki Kokubun , +// Craig Nishina , +// Simon Gellis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as chrome from './chrome'; import * as edge from './edge'; @@ -13,8 +17,6 @@ import * as safari from './safari'; export namespace error { class IError extends Error { constructor(opt_error?: string); - - code(): number; } /** @@ -656,7 +658,8 @@ export namespace promise { /** * Creates a promise that has been resolved with the given value. * @param {T=} opt_value The resolved value. - * @return {!ManagedPromise} The resolved promise. + * @return {!Promise} The resolved promise. + * @deprecated Use {@link Promise#resolve Promise.resolve(value)}. * @template T */ function fulfilled(opt_value?: T): Promise; @@ -689,8 +692,8 @@ export namespace promise { * Creates a promise that has been rejected with the given reason. * @param {*=} opt_reason The rejection reason; may be any value, but is * usually an Error or a string. - * @return {!ManagedPromise} The rejected promise. - * @template T + * @return {!Promise} The rejected promise. + * @deprecated Use {@link Promise#reject Promise.Promise(reason)}. */ function rejected(opt_reason?: any): Promise; @@ -802,19 +805,6 @@ export namespace promise { } interface IThenable { - /** - * Cancels the computation of this promise's value, rejecting the promise in - * the process. This method is a no-op if the promise has already been - * resolved. - * - * @param {(string|Error)=} opt_reason The reason this promise is being - * cancelled. This value will be wrapped in a {@link CancellationError}. - */ - cancel(opt_reason?: string | Error): void; - - /** @return {boolean} Whether this promise's value is still being computed. */ - isPending(): boolean; - /** * Registers listeners for when this instance is resolved. * @@ -864,19 +854,6 @@ export namespace promise { * @template T */ class Thenable implements IThenable { - /** - * Cancels the computation of this promise's value, rejecting the promise in - * the process. This method is a no-op if the promise has already been - * resolved. - * - * @param {(string|Error)=} opt_reason The reason this promise is being - * cancelled. This value will be wrapped in a {@link CancellationError}. - */ - cancel(opt_reason?: string | Error): void; - - /** @return {boolean} Whether this promise's value is still being computed. */ - isPending(): boolean; - /** * Registers listeners for when this instance is resolved. * @@ -1007,60 +984,43 @@ export namespace promise { */ constructor(resolver: (resolve: IFulfilledCallback, reject: IRejectedCallback) => void, opt_flow?: ControlFlow); + //region Static Methods + + /** + * Creates a promise that is immediately resolved with the given value. + * + * @param {T=} opt_value The value to resolve. + * @return {!ManagedPromise} A promise resolved with the given value. + * @template T + */ + static resolve(opt_value?: T): Promise; + + /** + * Creates a promise that is immediately rejected with the given reason. + * + * @param {*=} opt_reason The rejection reason. + * @return {!ManagedPromise} A new rejected promise. + */ + static reject(opt_reason?: any): Promise; + + //endregion + // region Methods /** - * Cancels the computation of this promise's value, rejecting the promise in the - * process. - * @param {*} reason The reason this promise is being cancelled. If not an - * {@code Error}, one will be created using the value's string - * representation. - */ - cancel(opt_reason?: string | Error): void; - - /** @return {boolean} Whether this promise's value is still being computed. */ - isPending(): boolean; - - /** - * Registers listeners for when this instance is resolved. This function most - * overridden by subtypes. + * Registers listeners for when this instance is resolved. * - * @param opt_callback The function to call if this promise is - * successfully resolved. The function should expect a single argument: the - * promise's resolved value. - * @param opt_errback The function to call if this promise is - * rejected. The function should expect a single argument: the rejection - * reason. - * @return A new promise which will be resolved - * with the result of the invoked callback. - */ - then(opt_callback?: (value: T) => IThenable | R, opt_errback?: (error: any) => any): Promise; - - /** - * Registers a listener for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: - *
              
              -     *   // Synchronous API:
              -     *   try {
              -     *     doSynchronousWork();
              -     *   } catch (ex) {
              -     *     console.error(ex);
              -     *   }
              -     *
              -     *   // Asynchronous promise API:
              -     *   doAsynchronousWork().thenCatch(function(ex) {
              -     *     console.error(ex);
              -     *   });
              -     * 
              - * - * @param {function(*): (R|promise.Promise.)} errback The function - * to call if this promise is rejected. The function should expect a single - * argument: the rejection reason. - * @return {!promise.Promise.} A new promise which will be - * resolved with the result of the invoked callback. + * @param {?(function(T): (R|IThenable))=} opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param {?(function(*): (R|IThenable))=} opt_errback + * The function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!Thenable} A new promise which will be resolved with the result + * of the invoked callback. * @template R */ - thenCatch(errback: (error: any) => any): Promise; + then(opt_callback?: (value: T) => IThenable | R, opt_errback?: (error: any) => any): Promise; /** * Registers a listener for when this promise is rejected. This is synonymous @@ -1085,50 +1045,9 @@ export namespace promise { * resolved with the result of the invoked callback. * @template R */ - catch(errback: Function): Promise; + catch(errback: (err: any) => R | IThenable): Promise; - /** - * Registers a listener to invoke when this promise is resolved, regardless - * of whether the promise's value was successfully computed. This function - * is synonymous with the {@code finally} clause in a synchronous API: - *
              
              -     *   // Synchronous API:
              -     *   try {
              -     *     doSynchronousWork();
              -     *   } finally {
              -     *     cleanUp();
              -     *   }
              -     *
              -     *   // Asynchronous promise API:
              -     *   doAsynchronousWork().thenFinally(cleanUp);
              -     * 
              - * - * Note: similar to the {@code finally} clause, if the registered - * callback returns a rejected promise or throws an error, it will silently - * replace the rejection error (if any) from this promise: - *
              
              -     *   try {
              -     *     throw Error('one');
              -     *   } finally {
              -     *     throw Error('two');  // Hides Error: one
              -     *   }
              -     *
              -     *   promise.rejected(Error('one'))
              -     *       .thenFinally(function() {
              -     *         throw Error('two');  // Hides Error: one
              -     *       });
              -     * 
              - * - * - * @param {function(): (R|promise.Promise.)} callback The function - * to call when this promise is resolved. - * @return {!promise.Promise.} A promise that will be fulfilled - * with the callback result. - * @template R - */ - thenFinally(callback: Function): Promise; - // endregion } @@ -1143,13 +1062,8 @@ export namespace promise { * the next turn of the event loop, the rejection will be passed to the * {@link promise.ControlFlow} as an unhandled failure. * - *

              If this Deferred is cancelled, the cancellation reason will be forward to - * the Deferred's canceller function (if provided). The canceller may return a - * truth-y value to override the reason provided for rejection. - * - * @extends {promise.Promise} */ - class Deferred extends Promise { + class Deferred { // region Constructors /** @@ -1368,28 +1282,40 @@ export namespace promise { } } -export namespace until { +/** + * Defines a condition for use with WebDriver's WebDriver#wait wait command. + */ +export class Condition { /** - * Defines a condition to + * @param {string} message A descriptive error message. Should complete the + * sentence 'Waiting [...]' + * @param {function(!WebDriver): OUT} fn The condition function to + * evaluate on each iteration of the wait loop. + * @constructor */ - class Condition { + constructor(message: string, fn: (webdriver: WebDriver) => any); + + /** @return {string} A description of this condition. */ + description(): string; + + /** @type {function(!WebDriver): OUT} */ + fn(webdriver: WebDriver): any; +} + +/** + * Defines a condition that will result in a {@link WebElement}. + * + * @extends {Condition)>} + */ +export class WebElementCondition extends Condition { + // add an unused private member so the compiler treats this + // class distinct from other Conditions + private _nominal: undefined; +} + +export namespace until { + /** - * @param {string} message A descriptive error message. Should complete the - * sentence 'Waiting [...]' - * @param {function(!WebDriver): OUT} fn The condition function to - * evaluate on each iteration of the wait loop. - * @constructor - */ - constructor(message: string, fn: (webdriver: WebDriver) => any); - - /** @return {string} A description of this condition. */ - description(): string; - - /** @type {function(!WebDriver): OUT} */ - fn(webdriver: WebDriver): any; - } - - /** * Creates a condition that will wait until the input driver is able to switch * to the designated frame. The target frame may be specified as * @@ -1409,7 +1335,7 @@ export namespace until { * The frame identifier. * @return {!Condition} A new condition. */ - function ableToSwitchToFrame(frame: number | WebElement | By | ((webdriver: WebDriver) => WebElement)): Condition; + function ableToSwitchToFrame(frame: number | WebElement | By | ((webdriver: WebDriver) => WebElement) | ByHash): Condition; /** * Creates a condition that waits for an alert to be opened. Upon success, the @@ -1423,64 +1349,64 @@ export namespace until { * Creates a condition that will wait for the given element to be disabled. * * @param {!WebElement} element The element to test. - * @return {!until.Condition.} The new condition. + * @return {!WebElementCondition} The new condition. * @see WebDriver#isEnabled */ - function elementIsDisabled(element: WebElement): Condition; + function elementIsDisabled(element: WebElement): WebElementCondition; /** * Creates a condition that will wait for the given element to be enabled. * * @param {!WebElement} element The element to test. - * @return {!until.Condition.} The new condition. + * @return {!WebElementCondition} The new condition. * @see WebDriver#isEnabled */ - function elementIsEnabled(element: WebElement): Condition; + function elementIsEnabled(element: WebElement): WebElementCondition; /** * Creates a condition that will wait for the given element to be deselected. * * @param {!WebElement} element The element to test. - * @return {!until.Condition.} The new condition. + * @return {!WebElementCondition} The new condition. * @see WebDriver#isSelected */ - function elementIsNotSelected(element: WebElement): Condition; + function elementIsNotSelected(element: WebElement): WebElementCondition; /** * Creates a condition that will wait for the given element to be in the DOM, * yet not visible to the user. * * @param {!WebElement} element The element to test. - * @return {!until.Condition.} The new condition. + * @return {!WebElementCondition} The new condition. * @see WebDriver#isDisplayed */ - function elementIsNotVisible(element: WebElement): Condition; + function elementIsNotVisible(element: WebElement): WebElementCondition; /** * Creates a condition that will wait for the given element to be selected. * @param {!WebElement} element The element to test. - * @return {!until.Condition.} The new condition. + * @return {!WebElementCondition} The new condition. * @see WebDriver#isSelected */ - function elementIsSelected(element: WebElement): Condition; + function elementIsSelected(element: WebElement): WebElementCondition; /** * Creates a condition that will wait for the given element to become visible. * * @param {!WebElement} element The element to test. - * @return {!until.Condition.} The new condition. + * @return {!WebElementCondition} The new condition. * @see WebDriver#isDisplayed */ - function elementIsVisible(element: WebElement): Condition; + function elementIsVisible(element: WebElement): WebElementCondition; /** * Creates a condition that will loop until an element is * {@link ./WebDriver#findElement found} with the given locator. * * @param {!(By|Function)} locator The locator to use. - * @return {!until.Condition.} The new condition. + * @return {!WebElementCondition} The new condition. */ - function elementLocated(locator: By | Function): Condition; + function elementLocated(locator: Locator): WebElementCondition; /** * Creates a condition that will wait for the given element's @@ -1489,10 +1415,10 @@ export namespace until { * * @param {!WebElement} element The element to test. * @param {string} substr The substring to search for. - * @return {!until.Condition.} The new condition. + * @return {!WebElementCondition} The new condition. * @see WebDriver#getText */ - function elementTextContains(element: WebElement, substr: string): Condition; + function elementTextContains(element: WebElement, substr: string): WebElementCondition; /** * Creates a condition that will wait for the given element's @@ -1501,10 +1427,10 @@ export namespace until { * * @param {!WebElement} element The element to test. * @param {string} text The expected text. - * @return {!until.Condition.} The new condition. + * @return {!WebElementCondition} The new condition. * @see WebDriver#getText */ - function elementTextIs(element: WebElement, text: string): Condition; + function elementTextIs(element: WebElement, text: string): WebElementCondition; /** * Creates a condition that will wait for the given element's @@ -1513,10 +1439,10 @@ export namespace until { * * @param {!WebElement} element The element to test. * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition} The new condition. + * @return {!WebElementCondition} The new condition. * @see WebDriver#getText */ - function elementTextMatches(element: WebElement, regex: RegExp): Condition; + function elementTextMatches(element: WebElement, regex: RegExp): WebElementCondition; /** * Creates a condition that will loop until at least one element is @@ -1524,10 +1450,10 @@ export namespace until { * * @param {!(Locator|By.Hash|Function)} locator The locator * to use. - * @return {!until.Condition.>} The new + * @return {!Condition.>} The new * condition. */ - function elementsLocated(locator: By | Function): Condition; + function elementsLocated(locator: Locator): Condition; /** * Creates a condition that will wait for the given element to become stale. An @@ -1535,7 +1461,7 @@ export namespace until { * has loaded. * * @param {!WebElement} element The element that should become stale. - * @return {!until.Condition} The new condition. + * @return {!Condition} The new condition. */ function stalenessOf(element: WebElement): Condition; @@ -1545,7 +1471,7 @@ export namespace until { * * @param {string} substr The substring that should be present in the page * title. - * @return {!until.Condition.} The new condition. + * @return {!Condition.} The new condition. */ function titleContains(substr: string): Condition; @@ -1554,7 +1480,7 @@ export namespace until { * given value. * * @param {string} title The expected page title. - * @return {!until.Condition} The new condition. + * @return {!Condition} The new condition. */ function titleIs(title: string): Condition; @@ -1563,9 +1489,37 @@ export namespace until { * given regular expression. * * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition.} The new condition. + * @return {!Condition.} The new condition. */ function titleMatches(regex: RegExp): Condition; + + /** + * Creates a condition that will wait for the current page's url to contain + * the given substring. + * + * @param {string} substrUrl The substring that should be present in the current + * URL. + * @return {!Condition} The new condition. + */ + function urlContains(substrUrl: string): Condition; + + /** + * Creates a condition that will wait for the current page's url to match the + * given value. + * + * @param {string} url The expected page url. + * @return {!Condition} The new condition. + */ + function urlIs(url: string): Condition; + + /** + * Creates a condition that will wait for the current page's url to match the + * given regular expression. + * + * @param {!RegExp} regex The regular expression to test against. + * @return {!Condition} The new condition. + */ + function urlMatches(regex: RegExp): Condition; } interface ILocation { @@ -2093,18 +2047,6 @@ export class AlertPromise extends Alert implements promise.IThenable { // region Methods - /** - * Cancels the computation of this promise's value, rejecting the promise in the - * process. - * @param {*} reason The reason this promise is being cancelled. If not an - * {@code Error}, one will be created using the value's string - * representation. - */ - cancel(opt_reason?: string | Error): void; - - /** @return {boolean} Whether this promise's value is still being computed. */ - isPending(): boolean; - /** * Registers listeners for when this instance is resolved. This function most * overridden by subtypes. @@ -2120,32 +2062,6 @@ export class AlertPromise extends Alert implements promise.IThenable { */ then(opt_callback?: Function, opt_errback?: Function): promise.Promise; - /** - * Registers a listener for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: - *

              
              -   *   // Synchronous API:
              -   *   try {
              -   *     doSynchronousWork();
              -   *   } catch (ex) {
              -   *     console.error(ex);
              -   *   }
              -   *
              -   *   // Asynchronous promise API:
              -   *   doAsynchronousWork().thenCatch(function(ex) {
              -   *     console.error(ex);
              -   *   });
              -   * 
              - * - * @param {function(*): (R|promise.Promise.)} errback The function - * to call if this promise is rejected. The function should expect a single - * argument: the rejection reason. - * @return {!promise.Promise.} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - thenCatch(errback: (error: any) => any): promise.Promise; - /** * Registers a listener for when this promise is rejected. This is synonymous * with the {@code catch} clause in a synchronous API: @@ -2170,52 +2086,6 @@ export class AlertPromise extends Alert implements promise.IThenable { * @template R */ catch(errback: Function): promise.Promise; - - - /** - * Registers a listener to invoke when this promise is resolved, regardless - * of whether the promise's value was successfully computed. This function - * is synonymous with the {@code finally} clause in a synchronous API: - *
              
              -   *   // Synchronous API:
              -   *   try {
              -   *     doSynchronousWork();
              -   *   } finally {
              -   *     cleanUp();
              -   *   }
              -   *
              -   *   // Asynchronous promise API:
              -   *   doAsynchronousWork().thenFinally(cleanUp);
              -   * 
              - * - * Note: similar to the {@code finally} clause, if the registered - * callback returns a rejected promise or throws an error, it will silently - * replace the rejection error (if any) from this promise: - *
              
              -   *   try {
              -   *     throw Error('one');
              -   *   } finally {
              -   *     throw Error('two');  // Hides Error: one
              -   *   }
              -   *
              -   *   promise.rejected(Error('one'))
              -   *       .thenFinally(function() {
              -   *         throw Error('two');  // Hides Error: one
              -   *       });
              -   * 
              - * - * - * @param {function(): (R|promise.Promise.)} callback The function - * to call when this promise is resolved. - * @return {!promise.Promise.} A promise that will be fulfilled - * with the callback result. - * @template R - */ - thenFinally(callback: Function): promise.Promise; -} - -/** @deprecated Use {@link error.UnexpectedAlertOpenError} instead. */ -export class UnhandledAlertError extends error.UnexpectedAlertOpenError { } /** @@ -2246,6 +2116,9 @@ interface ProxyConfig { httpProxy?: string; sslProxy?: string; noProxy?: string; + socksProxy?: string, + socksUsername?: string, + socksPassword?: string } /** @@ -2312,32 +2185,16 @@ export class Builder { * Creates a new WebDriver client based on this builder's current * configuration. * - * While this method will immediately return a new WebDriver instance, any - * commands issued against it will be deferred until the associated browser - * has been fully initialized. Users may call {@link #buildAsync()} to obtain - * a promise that will not be fulfilled until the browser has been created - * (the difference is purely in style). + * This method will return a {@linkplain ThenableWebDriver} instance, allowing + * users to issue commands directly without calling `then()`. The returned + * thenable wraps a promise that will resolve to a concrete + * {@linkplain webdriver.WebDriver WebDriver} instance. The promise will be + * rejected if the remote end fails to create a new session. * - * @return {!WebDriver} A new WebDriver instance. + * @return {!ThenableWebDriver} A new WebDriver instance. * @throws {Error} If the current configuration is invalid. - * @see #buildAsync() */ - build(): WebDriver; - - /** - * Creates a new WebDriver client based on this builder's current - * configuration. This method returns a promise that will not be fulfilled - * until the new browser session has been fully initialized. - * - * __Note:__ this method is purely a convenience wrapper around - * {@link #build()}. - * - * @return {!promise.Promise} A promise that will be - * fulfilled with the newly created WebDriver instance once the browser - * has been fully initialized. - * @see #build() - */ - buildAsync(): promise.Promise; + build(): ThenableWebDriver; /** * Configures the target browser for clients created by this instance. @@ -2493,6 +2350,15 @@ export class Builder { */ setScrollBehavior(behavior: number): Builder; + /** + * Sets the http agent to use for each request. + * If this method is not called, the Builder will use http.globalAgent by default. + * + * @param {http.Agent} agent The agent to use for each request. + * @return {!Builder} A self reference. + */ + usingHttpAgent(agent: any): Builder; + /** * Sets the URL of a remote WebDriver server to use. Once a remote URL has been * specified, the builder direct all new clients to that server. If this method @@ -2666,6 +2532,8 @@ type ByHash = { className: string } | { tagName: string } | { xpath: string }; + export type Locator = By | Function | ByHash; + /** * Common webdriver capability keys. * @enum {string} @@ -3121,19 +2989,6 @@ export class Executor { execute(command: Command): promise.Promise } -/** - * Wraps a promised {@link Executor}, ensuring no commands are executed until - * the wrapped executor has been fully resolved. - * @implements {Executor} - */ -export class DeferredExecutor { - /** - * @param {!promise.Promise} delegate The promised delegate, which - * may be provided by any promise-like thenable object. - */ - constructor(delegate: promise.Promise); -} - /** * Describes an event listener registered on an {@linkplain EventEmitter}. */ @@ -3286,12 +3141,65 @@ export class Navigation { } interface IWebDriverOptionsCookie { + + /** + * The name of the cookie. + */ name: string; + + /** + * The cookie value. + */ value: string; + + /** + * The cookie path. Defaults to "/" when adding a cookie. + */ path?: string; + + /** + * The domain the cookie is visible to. Defaults to the current browsing + * context's document's URL when adding a cookie. + */ domain?: string; + + /** + * Whether the cookie is a secure cookie. Defaults to false when adding a new + * cookie. + */ secure?: boolean; - expiry?: number; + + /** + * Whether the cookie is an HTTP only cookie. Defaults to false when adding a + * new cookie. + */ + httpOnly?: boolean; + + /** + * When the cookie expires. + * + * When {@linkplain Options#addCookie() adding a cookie}, this may be specified + * in _seconds_ since Unix epoch (January 1, 1970). The expiry will default to + * 20 years in the future if omitted. + * + * The expiry is always returned in seconds since epoch when + * {@linkplain Options#getCookies() retrieving cookies} from the browser. + * + * @type {(!Date|number|undefined)} + */ + expiry?: number | Date; + } + + interface IWebDriverCookie extends IWebDriverOptionsCookie { + /** + * When the cookie expires. + * + * The expiry is always returned in seconds since epoch when + * {@linkplain Options#getCookies() retrieving cookies} from the browser. + * + * @type {(!number|undefined)} + */ + expiry?: number } /** @@ -3312,18 +3220,14 @@ export class Options { /** * Schedules a command to add a cookie. - * @param {string} name The cookie name. - * @param {string} value The cookie value. - * @param {string=} opt_path The cookie path. - * @param {string=} opt_domain The cookie domain. - * @param {boolean=} opt_isSecure Whether the cookie is secure. - * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified - * as a number, should be in milliseconds since midnight, - * January 1, 1970 UTC. + * @param {IWebDriverOptionsCookie} spec Defines the cookie to add. * @return {!promise.Promise} A promise that will be resolved * when the cookie has been added to the page. + * @throws {error.InvalidArgumentError} if any of the cookie parameters are + * invalid. + * @throws {TypeError} if `spec` is not a cookie object. */ - addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number | Date): promise.Promise; + addCookie(spec: IWebDriverOptionsCookie): promise.Promise; /** * Schedules a command to delete all cookies visible to the current page. @@ -3669,6 +3573,11 @@ export class FileDetector { handleFile(driver: WebDriver, path: string): promise.Promise; } + type CreateSessionCapabilities = Capabilities | { + desired?: Capabilities, + required?: Capabilities + } + /** * Creates a new WebDriver client, which provides control over a browser. * @@ -3719,17 +3628,63 @@ export class WebDriver { /** * Creates a new WebDriver session. + * + * By default, the requested session `capabilities` are merely "desired" and + * the remote end will still create a new session even if it cannot satisfy + * all of the requested capabilities. You can query which capabilities a + * session actually has using the + * {@linkplain #getCapabilities() getCapabilities()} method on the returned + * WebDriver instance. + * + * To define _required capabilities_, provide the `capabilities` as an object + * literal with `required` and `desired` keys. The `desired` key may be + * omitted if all capabilities are required, and vice versa. If the server + * cannot create a session with all of the required capabilities, it will + * return an {@linkplain error.SessionNotCreatedError}. + * + * let required = new Capabilities().set('browserName', 'firefox'); + * let desired = new Capabilities().set('version', '45'); + * let driver = WebDriver.createSession(executor, {required, desired}); + * + * This function will always return a WebDriver instance. If there is an error + * creating the session, such as the aforementioned SessionNotCreatedError, + * the driver will have a rejected {@linkplain #getSession session} promise. + * It is recommended that this promise is left _unhandled_ so it will + * propagate through the {@linkplain promise.ControlFlow control flow} and + * cause subsequent commands to fail. + * + * let required = Capabilities.firefox(); + * let driver = WebDriver.createSession(executor, {required}); + * + * // If the createSession operation failed, then this command will also + * // also fail, propagating the creation failure. + * driver.get('http://www.google.com').catch(e => console.log(e)); + * * @param {!command.Executor} executor The executor to create the new session * with. - * @param {!./capabilities.Capabilities} desiredCapabilities The desired + * @param {(!Capabilities| + * {desired: (Capabilities|undefined), + * required: (Capabilities|undefined)})} capabilities The desired * capabilities for the new session. * @param {promise.ControlFlow=} opt_flow The control flow all driver * commands should execute under, including the initial session creation. * Defaults to the {@link promise.controlFlow() currently active} * control flow. + * @param {(function(new: WebDriver, + * !IThenable, + * !command.Executor, + * promise.ControlFlow=))=} opt_ctor + * A reference to the constructor of the specific type of WebDriver client + * to instantiate. Will create a vanilla {@linkplain WebDriver} instance + * if a constructor is not provided. + * @param {(function(this: void): ?)=} opt_onQuit A callback to invoke when + * the newly created session is terminated. This should be used to clean + * up any resources associated with the session. * @return {!WebDriver} The driver for the newly created session. */ - static createSession(executor: Executor, desiredCapabilities: Capabilities, opt_flow?: promise.ControlFlow): WebDriver; + // This method's arguments are untyped so that its overloads can have correct types. + // Typescript doesn't allow static methods to be overridden with incompatible signatures. + static createSession(...var_args: any[]): WebDriver; // endregion @@ -3947,10 +3902,10 @@ export class WebDriver { /** * Schedules a command to wait for a condition to hold. The condition may be - * specified by a {@link until.Condition}, as a custom function, or + * specified by a {@link Condition}, as a custom function, or * as a {@link promise.Promise}. * - * For a {@link until.Condition} or function, the wait will repeatedly + * For a {@link Condition} or function, the wait will repeatedly * evaluate the condition until it returns a truthy value. If any errors occur * while evaluating the condition, they will be allowed to propagate. In the * event a condition returns a {@link promise.Promise promise}, the @@ -3958,6 +3913,10 @@ export class WebDriver { * whether the condition has been satisified. Note the resolution time for * a promise is factored into whether a wait has timed out. * + * Note, if the provided condition is a {@link WebElementCondition}, then + * the wait will return a {@link WebElementPromise} that will resolve to the + * element that satisified the condition. + * * *Example:* waiting up to 10 seconds for an element to be present and visible * on the page. * @@ -3978,8 +3937,58 @@ export class WebDriver { * driver.wait(started, 5 * 1000, 'Server should start within 5 seconds'); * driver.get(getServerUrl()); * + * @param {!WebElementCondition} condition The condition to + * wait on, defined as a promise, condition object, or a function to + * evaluate as a condition. + * @param {number=} opt_timeout How long to wait for the condition to be true. + * @param {string=} opt_message An optional message to use if the wait times + * out. + * @return {!WebElementPromise} A promise that will be fulfilled + * with the first truthy value returned by the condition function, or + * rejected if the condition times out. + * @template T + */ + wait(condition: WebElementCondition, opt_timeout?: number, opt_message?: string): WebElementPromise; + + /** + * Schedules a command to wait for a condition to hold. The condition may be + * specified by a {@link webdriver.Condition}, as a custom function, or + * as a {@link webdriver.promise.Promise}. + * + * For a {@link webdriver.Condition} or function, the wait will repeatedly + * evaluate the condition until it returns a truthy value. If any errors occur + * while evaluating the condition, they will be allowed to propagate. In the + * event a condition returns a {@link webdriver.promise.Promise promise}, the + * polling loop will wait for it to be resolved and use the resolved value for + * whether the condition has been satisified. Note the resolution time for + * a promise is factored into whether a wait has timed out. + * + * Note, if the provided condition is a {@link WebElementCondition}, then + * the wait will return a {@link WebElementPromise} that will resolve to the + * element that satisified the condition. + * + * *Example:* waiting up to 10 seconds for an element to be present and visible + * on the page. + * + * var button = driver.wait(until.elementLocated(By.id('foo'), 10000); + * button.click(); + * + * This function may also be used to block the command flow on the resolution + * of a {@link webdriver.promise.Promise promise}. When given a promise, the + * command will simply wait for its resolution before completing. A timeout may + * be provided to fail the command if the promise does not resolve before the + * timeout expires. + * + * *Example:* Suppose you have a function, `startTestServer`, that returns a + * promise for when a server is ready for requests. You can block a `WebDriver` + * client on this promise with: + * + * var started = startTestServer(); + * driver.wait(started, 5 * 1000, 'Server should start within 5 seconds'); + * driver.get(getServerUrl()); + * * @param {!(promise.Promise| - * until.Condition| + * Condition| * function(!WebDriver): T)} condition The condition to * wait on, defined as a promise, condition object, or a function to * evaluate as a condition. @@ -3991,7 +4000,7 @@ export class WebDriver { * rejected if the condition times out. * @template T */ - wait(condition: promise.Promise | until.Condition | ((driver: WebDriver) => T) | Function, timeout?: number, opt_message?: string): promise.Promise; + wait(condition: PromiseLike | Condition | ((driver: WebDriver) => T | PromiseLike) | Function, opt_timeout?: number, opt_message?: string): promise.Promise; /** * Schedules a command to make the driver sleep for the given amount of time. @@ -4060,7 +4069,7 @@ export class WebDriver { * by the driver. Unlike other commands, this error cannot be suppressed. In * other words, scheduling a command to find an element doubles as an assert * that the element is present on the page. To test whether an element is - * present on the page, use {@link #isElementPresent} instead. + * present on the page, use {@link #findElements}. * * The search criteria for an element may be defined using one of the * factories in the {@link By} namespace, or as a short-hand @@ -4090,25 +4099,7 @@ export class WebDriver { * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: By | Function): WebElementPromise; - - /** - * Schedules a command to test if an element is present on the page. - * - * If given a DOM element, this function will check if it belongs to the - * document the driver is currently focused on. Otherwise, the function will - * test if at least one element can be found with the given search criteria. - * - * @param {!(by.By|Function)} locator The locator to use. - * @return {!promise.Promise} A promise that will resolve - * with whether the element is present on the page. - * @deprecated This method will be removed in Selenium 3.0 for consistency - * with the other Selenium language bindings. This method is equivalent - * to - * - * driver.findElements(locator).then(e => !!e.length); - */ - isElementPresent(locatorOrElement: By | Function): promise.Promise; + findElement(locator: Locator): WebElementPromise; /** * Schedule a command to search for multiple elements on the page. @@ -4117,7 +4108,7 @@ export class WebDriver { * @return {!promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: By | Function): promise.Promise; + findElements(locator: Locator): promise.Promise; /** * Schedule a command to take a screenshot. The driver makes a best effort to @@ -4154,6 +4145,24 @@ export class WebDriver { // endregion } + /** + * A thenable wrapper around a {@linkplain webdriver.IWebDriver IWebDriver} + * instance that allows commands to be issued directly instead of having to + * repeatedly call `then`: + * + * let driver = new Builder().build(); + * driver.then(d => d.get(url)); // You can do this... + * driver.get(url); // ...or this + * + * If the driver instance fails to resolve (e.g. the session cannot be created), + * every issued command will fail. + * + * @extends {webdriver.IWebDriver} + * @extends {promise.IThenable} + * @interface + */ + interface ThenableWebDriver extends WebDriver, promise.IThenable { } + interface IWebElementId { [ELEMENT: string]: string; } @@ -4365,13 +4374,6 @@ interface IWebElement { */ isDisplayed(): promise.Promise; - /** - * Schedules a command to retrieve the outer HTML of this element. - * @return {!promise.Promise} A promise that will be resolved with - * the element's outer HTML. - */ - getOuterHtml(): promise.Promise; - /** * @return {!promise.Promise.} A promise * that resolves to this element's JSON representation as defined by the @@ -4380,13 +4382,6 @@ interface IWebElement { */ getId(): promise.Promise; - /** - * Schedules a command to retrieve the inner HTML of this element. - * @return {!promise.Promise} A promise that will be resolved with the - * element's inner HTML. - */ - getInnerHtml(): promise.Promise; - // endregion } @@ -4397,7 +4392,7 @@ interface IWebElementFinders { * be returned by the driver. Unlike other commands, this error cannot be * suppressed. In other words, scheduling a command to find an element doubles * as an assert that the element is present on the page. To test whether an - * element is present on the page, use {@code #isElementPresent} instead. + * element is present on the page, use {@code #findElements}. * *

              The search criteria for an element may be defined using one of the * factories in the {@link By} namespace, or as a short-hand @@ -4431,18 +4426,7 @@ interface IWebElementFinders { * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: By | Function): WebElementPromise; - - /** - * Schedules a command to test if there is at least one descendant of this - * element that matches the given search criteria. - * - * @param {!(Locator|By.Hash|Function)} locator The - * locator strategy to use when searching for the element. - * @return {!promise.Promise.} A promise that will be - * resolved with whether an element could be located on the page. - */ - isElementPresent(locator: By | Function): promise.Promise; + findElement(locator: Locator): WebElementPromise; /** * Schedules a command to find all of the descendants of this element that @@ -4453,7 +4437,7 @@ interface IWebElementFinders { * @return {!promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: By | Function): promise.Promise; + findElements(locator: Locator): promise.Promise; } /** @@ -4550,18 +4534,13 @@ export class WebElement implements Serializable { */ getId(): promise.Promise; - /** - * @deprecated Use {@link #getId()} instead. - */ - getRawId(): any; - /** * Schedule a command to find a descendant of this element. If the element * cannot be found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will * be returned by the driver. Unlike other commands, this error cannot be * suppressed. In other words, scheduling a command to find an element doubles * as an assert that the element is present on the page. To test whether an - * element is present on the page, use {@link #isElementPresent} instead. + * element is present on the page, use {@link #findElements}. * * The search criteria for an element may be defined using one of the * factories in the {@link By} namespace, or as a short-hand @@ -4593,23 +4572,7 @@ export class WebElement implements Serializable { * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: By | Function): WebElementPromise; - - /** - * Schedules a command to test if there is at least one descendant of this - * element that matches the given search criteria. - * - * @param {!(by.By|Function)} locator The locator strategy to use when - * searching for the element. - * @return {!promise.Promise} A promise that will be - * resolved with whether an element could be located on the page. - * @deprecated This method will be removed in Selenium 3.0 for consistency - * with the other Selenium language bindings. This method is equivalent - * to - * - * element.findElements(locator).then(e => !!e.length); - */ - isElementPresent(locator: By | Function): promise.Promise; + findElement(locator: Locator): WebElementPromise; /** * Schedules a command to find all of the descendants of this element that @@ -4620,7 +4583,7 @@ export class WebElement implements Serializable { * @return {!promise.Promise>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: By | Function): promise.Promise; + findElements(locator: Locator): promise.Promise; /** * Schedules a command to click on this element. @@ -4816,20 +4779,6 @@ export class WebElement implements Serializable { */ takeScreenshot(opt_scroll?: boolean): promise.Promise; - /** - * Schedules a command to retrieve the outer HTML of this element. - * @return {!promise.Promise.} A promise that will be - * resolved with the element's outer HTML. - */ - getOuterHtml(): promise.Promise; - - /** - * Schedules a command to retrieve the inner HTML of this element. - * @return {!promise.Promise} A promise that will be resolved with the - * element's inner HTML. - */ - getInnerHtml(): promise.Promise; - /** @override */ serialize(): promise.Promise; } @@ -4865,19 +4814,6 @@ export class WebElementPromise extends WebElement implements promise.IThenable); - /** - * Cancels the computation of this promise's value, rejecting the promise in the - * process. This method is a no-op if the promise has alreayd been resolved. - * - * @param {string=} opt_reason The reason this promise is being cancelled. - */ - cancel(opt_reason?: string): void; - - - /** @return {boolean} Whether this promise's value is still being computed. */ - isPending(): boolean; - - /** * Registers listeners for when this instance is resolved. * @@ -4907,74 +4843,6 @@ export class WebElementPromise extends WebElement implements promise.IThenable(opt_callback?: (value: WebElement) => R, opt_errback?: (error: any) => any): promise.Promise; - /** - * Registers a listener for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: - *

              
              -   *   // Synchronous API:
              -   *   try {
              -   *     doSynchronousWork();
              -   *   } catch (ex) {
              -   *     console.error(ex);
              -   *   }
              -   *
              -   *   // Asynchronous promise API:
              -   *   doAsynchronousWork().thenCatch(function(ex) {
              -   *     console.error(ex);
              -   *   });
              -   * 
              - * - * @param {function(*): (R|promise.Promise.)} errback The function - * to call if this promise is rejected. The function should expect a single - * argument: the rejection reason. - * @return {!promise.Promise.} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - thenCatch(errback: (error: any) => any): promise.Promise; - - - /** - * Registers a listener to invoke when this promise is resolved, regardless - * of whether the promise's value was successfully computed. This function - * is synonymous with the {@code finally} clause in a synchronous API: - *
              
              -   *   // Synchronous API:
              -   *   try {
              -   *     doSynchronousWork();
              -   *   } finally {
              -   *     cleanUp();
              -   *   }
              -   *
              -   *   // Asynchronous promise API:
              -   *   doAsynchronousWork().thenFinally(cleanUp);
              -   * 
              - * - * Note: similar to the {@code finally} clause, if the registered - * callback returns a rejected promise or throws an error, it will silently - * replace the rejection error (if any) from this promise: - *
              
              -   *   try {
              -   *     throw Error('one');
              -   *   } finally {
              -   *     throw Error('two');  // Hides Error: one
              -   *   }
              -   *
              -   *   promise.rejected(Error('one'))
              -   *       .thenFinally(function() {
              -   *         throw Error('two');  // Hides Error: one
              -   *       });
              -   * 
              - * - * - * @param {function(): (R|promise.Promise.)} callback The function - * to call when this promise is resolved. - * @return {!promise.Promise.} A promise that will be fulfilled - * with the callback result. - * @template R - */ - thenFinally(callback: () => any): promise.Promise; - /** * Registers a listener for when this promise is rejected. This is synonymous * with the {@code catch} clause in a synchronous API: diff --git a/selenium-webdriver/opera.d.ts b/selenium-webdriver/opera.d.ts index cd02889527..b4d118f6a7 100644 --- a/selenium-webdriver/opera.d.ts +++ b/selenium-webdriver/opera.d.ts @@ -155,14 +155,17 @@ export class Options { export class Driver extends webdriver.WebDriver { /** + * Creates a new session for Opera. + * * @param {(capabilities.Capabilities|Options)=} opt_config The configuration * options. * @param {remote.DriverService=} opt_service The session to use; will use * the {@link getDefaultService default service} by default. * @param {promise.ControlFlow=} opt_flow The control flow to use, * or {@code null} to use the currently active flow. + * @return {!Driver} A new driver instance. */ - constructor(opt_config?: webdriver.Capabilities | Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + static createSession(opt_config?: webdriver.Capabilities | Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow): Driver; /** * This function is a no-op as file detectors are not supported by this diff --git a/selenium-webdriver/remote.d.ts b/selenium-webdriver/remote.d.ts index ae4f156ba7..15303a6d7f 100644 --- a/selenium-webdriver/remote.d.ts +++ b/selenium-webdriver/remote.d.ts @@ -65,3 +65,135 @@ export class DriverService { */ stop(): webdriver.promise.Promise; } + +export module DriverService { + + /** + * Creates {@link DriverService} objects that manage a WebDriver server in a + * child process. + */ + export class Builder { + /** + * @param {string} exe Path to the executable to use. This executable must + * accept the `--port` flag for defining the port to start the server on. + * @throws {Error} If the provided executable path does not exist. + */ + constructor(exe: string); + + /** + * Define additional command line arguments to use when starting the server. + * + * @param {...CommandLineFlag} var_args The arguments to include. + * @return {!THIS} A self reference. + * @this {THIS} + * @template THIS + */ + addArguments(...var_args: string[]): this; + + + /** + * Sets the host name to access the server on. If specified, the + * {@linkplain #setLoopback() loopback} setting will be ignored. + * + * @param {string} hostname + * @return {!DriverService.Builder} A self reference. + */ + setHostname(hostname: string): this; + + /** + * Sets whether the service should be accessed at this host's loopback + * address. + * + * @param {boolean} loopback + * @return {!DriverService.Builder} A self reference. + */ + setLoopback(loopback: boolean): this; + + /** + * Sets the base path for WebDriver REST commands (e.g. "/wd/hub"). + * By default, the driver will accept commands relative to "/". + * + * @param {?string} basePath The base path to use, or `null` to use the + * default. + * @return {!DriverService.Builder} A self reference. + */ + setPath(basePath: string | null): this; + + + /** + * Sets the port to start the server on. + * + * @param {number} port The port to use, or 0 for any free port. + * @return {!DriverService.Builder} A self reference. + * @throws {Error} If an invalid port is specified. + */ + setPort(port: number): this; + + /** + * Defines the environment to start the server under. This setting will be + * inherited by every browser session started by the server. By default, the + * server will inherit the enviroment of the current process. + * + * @param {(Map|Object|null)} env The desired + * environment to use, or `null` if the server should inherit the + * current environment. + * @return {!DriverService.Builder} A self reference. + */ + setEnvironment(env: Map | {[name: string]: string} | null): this; + + /** + * IO configuration for the spawned server process. For more information, + * refer to the documentation of `child_process.spawn`. + * + * @param {StdIoOptions} config The desired IO configuration. + * @return {!DriverService.Builder} A self reference. + * @see https://nodejs.org/dist/latest-v4.x/docs/api/child_process.html#child_process_options_stdio + */ + setStdio(config: any): this; + + /** + * Creates a new DriverService using this instance's current configuration. + * + * @return {!DriverService} A new driver service. + */ + build(): DriverService; + } +} + +/** + * A {@link webdriver.FileDetector} that may be used when running + * against a remote + * [Selenium server](http://selenium-release.storage.googleapis.com/index.html). + * + * When a file path on the local machine running this script is entered with + * {@link webdriver.WebElement#sendKeys WebElement#sendKeys}, this file detector + * will transfer the specified file to the Selenium server's host; the sendKeys + * command will be updated to use the transfered file's path. + * + * __Note:__ This class depends on a non-standard command supported on the + * Java Selenium server. The file detector will fail if used with a server that + * only supports standard WebDriver commands (such as the ChromeDriver). + * + * @final + */ +export class FileDetector extends webdriver.FileDetector { + /** + * @constructor + **/ + constructor(); + + /** + * Prepares a `file` for use with the remote browser. If the provided path + * does not reference a normal file (i.e. it does not exist or is a + * directory), then the promise returned by this method will be resolved with + * the original file path. Otherwise, this method will upload the file to the + * remote server, which will return the file's path on the remote system so + * it may be referenced in subsequent commands. + * + * @param {!webdriver.WebDriver} driver The driver for the current browser. + * @param {string} file The path of the file to process. + * @return {!webdriver.promise.Promise} A promise for the processed + * file path. + */ + handleFile(driver: webdriver.WebDriver, file: string): webdriver.promise.Promise; +} diff --git a/selenium-webdriver/safari.d.ts b/selenium-webdriver/safari.d.ts index 7a6f1701c4..bbeb887410 100644 --- a/selenium-webdriver/safari.d.ts +++ b/selenium-webdriver/safari.d.ts @@ -65,7 +65,7 @@ export class Options { * merge these options into, if any. * @return {!Capabilities} The capabilities. */ - toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; + toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; } /** @@ -79,11 +79,13 @@ export class Options { */ export class Driver extends webdriver.WebDriver { /** + * Creates a new Safari session. + * * @param {(Options|Capabilities)=} opt_config The configuration * options for the new session. * @param {promise.ControlFlow=} opt_flow The control flow to create * the driver under. + * @return {!Driver} A new driver instance. */ - constructor(opt_config?: Options | webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); - + static createSession(opt_config?: Options | webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow): Driver; } diff --git a/selenium-webdriver/test/chrome.ts b/selenium-webdriver/test/chrome.ts index de358656bc..b26c43c2d6 100644 --- a/selenium-webdriver/test/chrome.ts +++ b/selenium-webdriver/test/chrome.ts @@ -3,9 +3,9 @@ import * as remote from 'selenium-webdriver/remote'; import * as webdriver from 'selenium-webdriver'; function TestChromeDriver() { - var driver: chrome.Driver = new chrome.Driver(); - driver = new chrome.Driver(webdriver.Capabilities.chrome()); - driver = new chrome.Driver(webdriver.Capabilities.chrome(), + var driver: chrome.Driver = chrome.Driver.createSession(); + driver = chrome.Driver.createSession(webdriver.Capabilities.chrome()); + driver = chrome.Driver.createSession(webdriver.Capabilities.chrome(), new remote.DriverService('executable', new chrome.Options()), new webdriver.promise.ControlFlow()); @@ -44,15 +44,15 @@ function TestServiceBuilder() { builder = new chrome.ServiceBuilder('exe'); var anything: any = builder.build(); - builder = builder.usingPort(8080); + builder = builder.setPort(8080); builder = builder.setAdbPort(5037); builder = builder.loggingTo('path'); builder = builder.enableVerboseLogging(); builder = builder.setNumHttpThreads(5); - builder = builder.setUrlBasePath('path'); + builder = builder.setPath('path'); builder = builder.setStdio('config'); builder = builder.setStdio(['A', 'B']); - builder = builder.withEnvironment({ A: 'a', B: 'b' }); + builder = builder.setEnvironment({ 'A': 'a', 'B': 'b' }); } function TestChromeModule() { diff --git a/selenium-webdriver/test/firefox.ts b/selenium-webdriver/test/firefox.ts index 8b329c8e73..38a3c3634e 100644 --- a/selenium-webdriver/test/firefox.ts +++ b/selenium-webdriver/test/firefox.ts @@ -1,6 +1,7 @@ import * as firefox from 'selenium-webdriver/firefox'; import * as remote from 'selenium-webdriver/remote'; import * as webdriver from 'selenium-webdriver'; +import * as http from 'selenium-webdriver/http'; function TestBinary() { var binary: firefox.Binary = new firefox.Binary(); @@ -12,9 +13,11 @@ function TestBinary() { } function TestFirefoxDriver() { - var driver: firefox.Driver = new firefox.Driver(); - driver = new firefox.Driver(webdriver.Capabilities.firefox()); - driver = new firefox.Driver(webdriver.Capabilities.firefox(), new webdriver.promise.ControlFlow()); + var driver: firefox.Driver = firefox.Driver.createSession(); + driver = firefox.Driver.createSession(webdriver.Capabilities.firefox()); + driver = firefox.Driver.createSession(webdriver.Capabilities.firefox(), new http.Executor(new http.HttpClient('http://someurl'))); + driver = firefox.Driver.createSession(webdriver.Capabilities.firefox(), new remote.DriverService('/dev/null', {})); + driver = firefox.Driver.createSession(webdriver.Capabilities.firefox(), new remote.DriverService('/dev/null', {}), new webdriver.promise.ControlFlow()); var baseDriver: webdriver.WebDriver = driver; } @@ -52,3 +55,20 @@ function TestFirefoxProfile() { var stringPromise: webdriver.promise.Promise = profile.writeToDisk(); stringPromise = profile.writeToDisk(true); } + + +function TestServiceBuilder() { + var builder: firefox.ServiceBuilder = new firefox.ServiceBuilder(); + builder = new firefox.ServiceBuilder('exe'); + + var anything: any = builder.build(); + builder = builder.setPort(8080); + builder = builder.enableVerboseLogging(); + builder = builder.enableVerboseLogging(true); + builder = builder.setFirefoxBinary('exe'); + builder = builder.setFirefoxBinary(new firefox.Binary()); + builder = builder.setPath('path'); + builder = builder.setStdio('config'); + builder = builder.setStdio(['A', 'B']); + builder = builder.setEnvironment({ 'A': 'a', 'B': 'b' }); +} diff --git a/selenium-webdriver/test/index.ts b/selenium-webdriver/test/index.ts index 5d32724b15..2556e7e2a8 100644 --- a/selenium-webdriver/test/index.ts +++ b/selenium-webdriver/test/index.ts @@ -1,16 +1,10 @@ import * as webdriver from 'selenium-webdriver'; import * as chrome from 'selenium-webdriver/chrome'; import * as firefox from 'selenium-webdriver/firefox'; +import * as http from 'selenium-webdriver/http'; import * as remote from 'selenium-webdriver/remote'; -import * as executors from 'selenium-webdriver/executors'; import * as testing from 'selenium-webdriver/testing'; -function TestExecutors() { - var exec: webdriver.Executor = executors.createExecutor('url'); - var promise: webdriver.promise.Promise; - exec = executors.createExecutor(promise); -} - function TestBuilder() { var builder: webdriver.Builder = new webdriver.Builder(); @@ -219,11 +213,6 @@ function TestCommand() { command = command.setParameters({ param: 123 }); } -function TestDeferredExecutor() { - var promise: webdriver.promise.Promise; - var executor: webdriver.DeferredExecutor = new webdriver.DeferredExecutor(promise); -} - function TestCommandName() { var command: string; @@ -469,14 +458,6 @@ function TestSession() { var data: string = session.toJSON(); } -function TestUnhandledAlertError() { - var someFunc = (error: webdriver.UnhandledAlertError) => { - var baseError: Error = error; - var str: string = error.getAlertText(); - str = error.toString(); - }; -} - function TestWebDriverFileDetector() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). @@ -519,18 +500,28 @@ function TestWebDriverOptions() { var options: webdriver.Options = new webdriver.Options(driver); var promise: webdriver.promise.Promise; + var name: string = 'name'; + var value: string = 'value'; + var path: string = 'path'; + var domain: string = 'domain'; + var secure: boolean = true; + var httpOnly: boolean = true; + // Add Cookie - promise = options.addCookie('name', 'value'); - promise = options.addCookie('name', 'value', 'path'); - promise = options.addCookie('name', 'value', 'path', 'domain'); - promise = options.addCookie('name', 'value', 'path', 'domain', true); - promise = options.addCookie('name', 'value', 'path', 'domain', true, 123); - promise = options.addCookie('name', 'value', 'path', 'domain', true, Date.now()); + promise = options.addCookie({ name, value }); + promise = options.addCookie({ name, value, path }); + promise = options.addCookie({ name, value, path, domain }); + promise = options.addCookie({ name, value, path, domain, secure }); + promise = options.addCookie({ name, value, path, domain, secure, httpOnly }); + promise = options.addCookie({ name, value, path, domain, secure, httpOnly, expiry: 123 }); + promise = options.addCookie({ name, value, path, domain, secure, httpOnly, expiry: Date.now() }); promise = options.deleteAllCookies(); promise = options.deleteCookie('name'); - options.getCookie('name').then((cookies: webdriver.IWebDriverOptionsCookie) => {}); - options.getCookies().then((cookies: webdriver.IWebDriverOptionsCookie[]) => {}); + options.getCookie('name').then((cookie: webdriver.IWebDriverCookie) => { + var expiry: number = cookie.expiry; + }); + options.getCookies().then((cookies: webdriver.IWebDriverCookie[]) => { }); var logs: webdriver.Logs = options.logs(); var timeouts: webdriver.Timeouts = options.timeouts(); @@ -585,7 +576,8 @@ function TestWebDriverWindow() { function TestWebDriver() { var session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android()); var sessionPromise: webdriver.promise.Promise; - var executor: webdriver.Executor = executors.createExecutor('http://someserver'); + var httpClient: http.HttpClient = new http.HttpClient('http://someserver'); + var executor: http.Executor = new http.Executor(httpClient); var flow: webdriver.promise.ControlFlow = new webdriver.promise.ControlFlow(); var driver: webdriver.WebDriver = new webdriver.WebDriver(session, executor); driver = new webdriver.WebDriver(session, executor, flow); @@ -595,6 +587,7 @@ function TestWebDriver() { var voidPromise: webdriver.promise.Promise; var stringPromise: webdriver.promise.Promise; var booleanPromise: webdriver.promise.Promise; + var webElementPromise: webdriver.WebElementPromise; var actions: webdriver.ActionSequence = driver.actions(); var touchActions: webdriver.TouchSequence = driver.touchActions(); @@ -638,9 +631,6 @@ function TestWebDriver() { stringPromise = driver.getTitle(); stringPromise = driver.getWindowHandle(); - booleanPromise = driver.isElementPresent(webdriver.By.className('ABC')); - booleanPromise = driver.isElementPresent(webdriver.By.js('function(){}')); - var options: webdriver.Options = driver.manage(); var navigation: webdriver.Navigation = driver.navigate(); var locator: webdriver.TargetLocator = driver.switchTo(); @@ -653,14 +643,17 @@ function TestWebDriver() { voidPromise = driver.sleep(123); stringPromise = driver.takeScreenshot(); - var booleanCondition: webdriver.until.Condition; + var booleanCondition: webdriver.Condition; booleanPromise = driver.wait(booleanPromise); booleanPromise = driver.wait(booleanCondition); booleanPromise = driver.wait((driver: webdriver.WebDriver) => true); - let conditionFunction: Function; // tslint:disable-line:prefer-const - booleanPromise = driver.wait(conditionFunction); + booleanPromise = driver.wait((driver: webdriver.WebDriver) => Promise.resolve(true)); + booleanPromise = driver.wait((driver: webdriver.WebDriver) => webdriver.promise.Promise.resolve(true)); booleanPromise = driver.wait(booleanPromise, 123); booleanPromise = driver.wait(booleanPromise, 123, 'Message'); + let webElementCondition: webdriver.WebElementCondition; + webElementPromise = driver.wait(webElementCondition); + voidPromise = driver.wait(webElementCondition).click(); driver = webdriver.WebDriver.attachToSession(executor, 'ABC'); driver = webdriver.WebDriver.createSession(executor, webdriver.Capabilities.android()); @@ -690,15 +683,13 @@ function TestWebElement() { voidPromise = element.click(); element = element.findElement(webdriver.By.id('ABC')); - element.findElements(webdriver.By.className('ABC')).then((elements: webdriver.WebElement[]) => {}); - booleanPromise = element.isElementPresent(webdriver.By.className('ABC')); + element = element.findElement({id: 'ABC'}); + element.findElements({className: 'ABC'}).then((elements: webdriver.WebElement[]) => { }); stringPromise = element.getAttribute('class'); stringPromise = element.getCssValue('display'); driver = element.getDriver(); - stringPromise = element.getInnerHtml(); element.getLocation().then((location: webdriver.ILocation) => {}); - stringPromise = element.getOuterHtml(); element.getSize().then((size: webdriver.ISize) => {}); stringPromise = element.getTagName(); stringPromise = element.getText(); @@ -712,7 +703,6 @@ function TestWebElement() { voidPromise = element.sendKeys('A', 1, webdriver.Key.BACK_SPACE, stringPromise); voidPromise = element.submit(); element.getId().then((id: string) => {}); - element.getRawId().then((id: string) => {}); element.serialize().then((id: webdriver.IWebElementId) => {}); booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, 'elementId')); @@ -725,19 +715,10 @@ function TestWebElementPromise() { var elementPromise: webdriver.WebElementPromise = driver.findElement(webdriver.By.id('id')); - elementPromise.cancel(); - elementPromise.cancel('reason'); - - var bool: boolean = elementPromise.isPending(); - elementPromise.then(); elementPromise.then((element: webdriver.WebElement) => {}); elementPromise.then((element: webdriver.WebElement) => {}, (error: any) => {}); elementPromise.then((element: webdriver.WebElement) => 'foo', (error: any) => {}).then((result: string) => {}); - - elementPromise.thenCatch((error: any) => {}).then((value: any) => {}); - - elementPromise.thenFinally(() => {}); } function TestLogging() { @@ -871,29 +852,32 @@ function TestUntilModule() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var conditionB: webdriver.until.Condition = new webdriver.until.Condition('message', (driver: webdriver.WebDriver) => true); - var conditionBBase: webdriver.until.Condition = conditionB; - var conditionWebElement: webdriver.until.Condition; - var conditionWebElements: webdriver.until.Condition; + var conditionB: webdriver.Condition = new webdriver.Condition('message', (driver: webdriver.WebDriver) => true); + var conditionBBase: webdriver.Condition = conditionB; + var conditionWebElement: webdriver.WebElementCondition; + var conditionWebElements: webdriver.Condition; conditionB = webdriver.until.ableToSwitchToFrame(5); - var conditionAlert: webdriver.until.Condition = webdriver.until.alertIsPresent(); + var conditionAlert: webdriver.Condition = webdriver.until.alertIsPresent(); var el: webdriver.WebElement = driver.findElement(webdriver.By.id('id')); - conditionB = webdriver.until.elementIsDisabled(el); - conditionB = webdriver.until.elementIsEnabled(el); - conditionB = webdriver.until.elementIsNotSelected(el); - conditionB = webdriver.until.elementIsNotVisible(el); - conditionB = webdriver.until.elementIsSelected(el); - conditionB = webdriver.until.elementIsVisible(el); - conditionB = webdriver.until.elementTextContains(el, 'text'); - conditionB = webdriver.until.elementTextIs(el, 'text'); - conditionB = webdriver.until.elementTextMatches(el, /text/); conditionB = webdriver.until.stalenessOf(el); conditionB = webdriver.until.titleContains('text'); conditionB = webdriver.until.titleIs('text'); conditionB = webdriver.until.titleMatches(/text/); + conditionB = webdriver.until.urlContains('text'); + conditionB = webdriver.until.urlIs('text'); + conditionB = webdriver.until.urlMatches(/text/); + conditionWebElement = webdriver.until.elementIsDisabled(el); + conditionWebElement = webdriver.until.elementIsEnabled(el); + conditionWebElement = webdriver.until.elementIsNotSelected(el); + conditionWebElement = webdriver.until.elementIsNotVisible(el); + conditionWebElement = webdriver.until.elementIsSelected(el); + conditionWebElement = webdriver.until.elementIsVisible(el); conditionWebElement = webdriver.until.elementLocated(webdriver.By.id('id')); + conditionWebElement = webdriver.until.elementTextContains(el, 'text'); + conditionWebElement = webdriver.until.elementTextIs(el, 'text'); + conditionWebElement = webdriver.until.elementTextMatches(el, /text/); conditionWebElements = webdriver.until.elementsLocated(webdriver.By.className('class')); } @@ -955,18 +939,10 @@ function TestPromiseClass() { promise = new webdriver.promise.Promise((resolve: (value: webdriver.promise.Promise) => void, reject: () => void) => {}); promise = new webdriver.promise.Promise((resolve: (value: string) => void, reject: () => void) => {}, controlFlow); - promise.cancel('Abort'); - - var isPending: boolean = promise.isPending(); - promise = promise.then(); promise = promise.then((a: string) => 'cde'); promise = promise.then((a: string) => 'cde', (e: any) => {}); promise = promise.then((a: string) => 'cde', (e: any) => 123); - - promise = promise.thenCatch((error: any) => {}); - - promise.thenFinally(() => {}); } function TestThenableClass() { @@ -974,46 +950,9 @@ function TestThenableClass() { resolve('a'); }); - thenable.cancel('Abort'); - - var isPending: boolean = thenable.isPending(); - thenable = thenable.then((a: string) => 'cde'); thenable = thenable.then((a: string) => 'cde', (e: any) => {}); thenable = thenable.then((a: string) => 'cde', (e: any) => 123); - - thenable = thenable.thenCatch((error: any) => {}); - - thenable.thenFinally(() => {}); -} - -function TestErrorCode() { - var errorCode: number; - - errorCode = new webdriver.error.ElementNotSelectableError().code(); - errorCode = new webdriver.error.ElementNotVisibleError().code(); - errorCode = new webdriver.error.InvalidArgumentError().code(); - errorCode = new webdriver.error.InvalidCookieDomainError().code(); - errorCode = new webdriver.error.InvalidElementCoordinatesError().code(); - errorCode = new webdriver.error.InvalidElementStateError().code(); - errorCode = new webdriver.error.InvalidSelectorError().code(); - errorCode = new webdriver.error.NoSuchSessionError().code(); - errorCode = new webdriver.error.JavascriptError().code(); - errorCode = new webdriver.error.MoveTargetOutOfBoundsError().code(); - errorCode = new webdriver.error.NoSuchAlertError().code(); - errorCode = new webdriver.error.NoSuchElementError().code(); - errorCode = new webdriver.error.NoSuchFrameError().code(); - errorCode = new webdriver.error.NoSuchWindowError().code(); - errorCode = new webdriver.error.ScriptTimeoutError().code(); - errorCode = new webdriver.error.SessionNotCreatedError().code(); - errorCode = new webdriver.error.StaleElementReferenceError().code(); - errorCode = new webdriver.error.TimeoutError().code(); - errorCode = new webdriver.error.UnableToSetCookieError().code(); - errorCode = new webdriver.error.UnableToCaptureScreenError().code(); - errorCode = new webdriver.error.UnexpectedAlertOpenError().code(); - errorCode = new webdriver.error.UnknownCommandError().code(); - errorCode = new webdriver.error.UnknownMethodError().code(); - errorCode = new webdriver.error.UnsupportedOperationError().code(); } async function TestAsyncAwaitable() { diff --git a/selenium-webdriver/test/remote.ts b/selenium-webdriver/test/remote.ts new file mode 100644 index 0000000000..a783101290 --- /dev/null +++ b/selenium-webdriver/test/remote.ts @@ -0,0 +1,11 @@ +import * as remote from "selenium-webdriver/remote"; +import * as webdriver from "selenium-webdriver"; + +function TestRemoteFileDetector() { + const driver: webdriver.WebDriver = new webdriver.Builder() + .withCapabilities(webdriver.Capabilities.chrome()) + .build(); + + const fileDetector: remote.FileDetector = new remote.FileDetector(); + fileDetector.handleFile(driver, 'path/to/file').then((path: string) => { /* empty */ }); +} diff --git a/selenium-webdriver/tsconfig.json b/selenium-webdriver/tsconfig.json index 50c76c7b28..a72458a455 100644 --- a/selenium-webdriver/tsconfig.json +++ b/selenium-webdriver/tsconfig.json @@ -20,7 +20,6 @@ "index.d.ts", "chrome.d.ts", "edge.d.ts", - "executors.d.ts", "firefox.d.ts", "http.d.ts", "ie.d.ts", @@ -30,6 +29,7 @@ "testing.d.ts", "test/index.ts", "test/chrome.ts", - "test/firefox.ts" + "test/firefox.ts", + "test/remote.ts" ] -} \ No newline at end of file +} diff --git a/selenium-webdriver/tslint.json b/selenium-webdriver/tslint.json index eb0befd093..93fffac84e 100644 --- a/selenium-webdriver/tslint.json +++ b/selenium-webdriver/tslint.json @@ -3,7 +3,7 @@ "rules": { "callable-types": false, "forbidden-types": false, - "interface-name": false, + "interface-name": [false], "no-empty-interface": false, "unified-signatures": false } diff --git a/selenium-webdriver/v2/chrome.d.ts b/selenium-webdriver/v2/chrome.d.ts new file mode 100644 index 0000000000..eb7b9f13c1 --- /dev/null +++ b/selenium-webdriver/v2/chrome.d.ts @@ -0,0 +1,415 @@ +/* tslint:disable */ +import * as webdriver from './index'; +import * as remote from './remote'; + +/** + * Creates a new WebDriver client for Chrome. + * + * @extends {webdriver.WebDriver} + */ +export class Driver extends webdriver.WebDriver { + /** + * @param {(webdriver.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@link getDefaultService default service} by default. + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow to use, or + * {@code null} to use the currently active flow. + * @constructor + */ + constructor(opt_config?: Options | webdriver.Capabilities, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); +} + +interface IOptionsValues { + args: string[]; + binary?: string; + detach: boolean; + extensions: string[]; + localState?: any; + logFile?: string; + prefs?: any; +} + +interface IPerfLoggingPrefs { + enableNetwork: boolean; + enablePage: boolean; + enableTimeline: boolean; + tracingCategories: string; + bufferUsageReportingInterval: number; +} + +/** + * Class for managing ChromeDriver specific options. + */ +export class Options { + /** + * @constructor + */ + constructor(); + + /** + * Extracts the ChromeDriver specific options from the given capabilities + * object. + * @param {!webdriver.Capabilities} capabilities The capabilities object. + * @return {!Options} The ChromeDriver options. + */ + static fromCapabilities(capabilities: webdriver.Capabilities): Options; + + + /** + * Add additional command line arguments to use when launching the Chrome + * browser. Each argument may be specified with or without the '--' prefix + * (e.g. '--foo' and 'foo'). Arguments with an associated value should be + * delimited by an '=': 'foo=bar'. + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: string[]): Options; + + + /** + * List of Chrome command line switches to exclude that ChromeDriver by default + * passes when starting Chrome. Do not prefix switches with '--'. + * + * @param {...(string|!Array)} var_args The switches to exclude. + * @return {!Options} A self reference. + */ + excludeSwitches(...var_args: string[]): Options; + + + /** + * Add additional extensions to install when launching Chrome. Each extension + * should be specified as the path to the packed CRX file, or a Buffer for an + * extension. + * @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The + * extensions to add. + * @return {!Options} A self reference. + */ + addExtensions(...var_args: any[]): Options; + + + /** + * Sets the path to the Chrome binary to use. On Mac OS X, this path should + * reference the actual Chrome executable, not just the application binary + * (e.g. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'). + * + * The binary path be absolute or relative to the chromedriver server + * executable, but it must exist on the machine that will launch Chrome. + * + * @param {string} path The path to the Chrome binary to use. + * @return {!Options} A self reference. + */ + setChromeBinaryPath(path: string): Options; + + + /** + * Sets whether to leave the started Chrome browser running if the controlling + * ChromeDriver service is killed before {@link webdriver.WebDriver#quit()} is + * called. + * @param {boolean} detach Whether to leave the browser running if the + * chromedriver service is killed before the session. + * @return {!Options} A self reference. + */ + detachDriver(detach: boolean): Options; + + + /** + * Sets the user preferences for Chrome's user profile. See the 'Preferences' + * file in Chrome's user data directory for examples. + * @param {!Object} prefs Dictionary of user preferences to use. + * @return {!Options} A self reference. + */ + setUserPreferences(prefs: any): Options; + + + /** + * Sets the logging preferences for the new session. + * @param {!webdriver.logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the performance logging preferences. Options include: + * + * - `enableNetwork`: Whether or not to collect events from Network domain. + * - `enablePage`: Whether or not to collect events from Page domain. + * - `enableTimeline`: Whether or not to collect events from Timeline domain. + * Note: when tracing is enabled, Timeline domain is implicitly disabled, + * unless `enableTimeline` is explicitly set to true. + * - `tracingCategories`: A comma-separated string of Chrome tracing categories + * for which trace events should be collected. An unspecified or empty + * string disables tracing. + * - `bufferUsageReportingInterval`: The requested number of milliseconds + * between DevTools trace buffer usage events. For example, if 1000, then + * once per second, DevTools will report how full the trace buffer is. If a + * report indicates the buffer usage is 100%, a warning will be issued. + * + * @param {{enableNetwork: boolean, + * enablePage: boolean, + * enableTimeline: boolean, + * tracingCategories: string, + * bufferUsageReportingInterval: number}} prefs The performance + * logging preferences. + * @return {!Options} A self reference. + */ + setPerfLoggingPrefs(prefs: IPerfLoggingPrefs): Options; + + + /** + * Sets preferences for the 'Local State' file in Chrome's user data + * directory. + * @param {!Object} state Dictionary of local state preferences. + * @return {!Options} A self reference. + */ + setLocalState(state: any): Options; + + + /** + * Sets the name of the activity hosting a Chrome-based Android WebView. This + * option must be set to connect to an [Android WebView]( + * https://sites.google.com/a/chromium.org/chromedriver/getting-started/getting-started---android) + * + * @param {string} name The activity name. + * @return {!Options} A self reference. + */ + androidActivity(name: string): Options; + + + /** + * Sets the device serial number to connect to via ADB. If not specified, the + * ChromeDriver will select an unused device at random. An error will be + * returned if all devices already have active sessions. + * + * @param {string} serial The device serial number to connect to. + * @return {!Options} A self reference. + */ + androidDeviceSerial(serial: string): Options; + + + /** + * Configures the ChromeDriver to launch Chrome on Android via adb. This + * function is shorthand for + * {@link #androidPackage options.androidPackage('com.android.chrome')}. + * @return {!Options} A self reference. + */ + androidChrome(): Options; + + + /** + * Sets the package name of the Chrome or WebView app. + * + * @param {?string} pkg The package to connect to, or `null` to disable Android + * and switch back to using desktop Chrome. + * @return {!Options} A self reference. + */ + androidPackage(pkg: string): Options; + + + /** + * Sets the process name of the Activity hosting the WebView (as given by `ps`). + * If not specified, the process name is assumed to be the same as + * {@link #androidPackage}. + * + * @param {string} processName The main activity name. + * @return {!Options} A self reference. + */ + androidProcess(processName: string): Options; + + + /** + * Sets whether to connect to an already-running instead of the specified + * {@linkplain #androidProcess app} instead of launching the app with a clean + * data directory. + * + * @param {boolean} useRunning Whether to connect to a running instance. + * @return {!Options} A self reference. + */ + androidUseRunningApp(useRunning: boolean): Options; + + + /** + * Sets the path to Chrome's log file. This path should exist on the machine + * that will launch Chrome. + * @param {string} path Path to the log file to use. + * @return {!Options} A self reference. + */ + setChromeLogFile(path: string): Options; + + + /** + * Sets the directory to store Chrome minidumps in. This option is only + * supported when ChromeDriver is running on Linux. + * @param {string} path The directory path. + * @return {!Options} A self reference. + */ + setChromeMinidumpPath(path: string): Options; + + + /** + * Configures Chrome to emulate a mobile device. For more information, refer + * to the ChromeDriver project page on [mobile emulation][em]. Configuration + * options include: + * + * - `deviceName`: The name of a pre-configured [emulated device][devem] + * - `width`: screen width, in pixels + * - `height`: screen height, in pixels + * - `pixelRatio`: screen pixel ratio + * + * __Example 1: Using a Pre-configured Device__ + * + * let options = new chrome.Options().setMobileEmulation( + * {deviceName: 'Google Nexus 5'}); + * + * let driver = new chrome.Driver(options); + * + * __Example 2: Using Custom Screen Configuration__ + * + * let options = new chrome.Options().setMobileEmulation({ + * width: 360, + * height: 640, + * pixelRatio: 3.0 + * }); + * + * let driver = new chrome.Driver(options); + * + * + * [em]: https://sites.google.com/a/chromium.org/chromedriver/mobile-emulation + * [devem]: https://developer.chrome.com/devtools/docs/device-mode + * + * @param {?({deviceName: string}| + * {width: number, height: number, pixelRatio: number})} config The + * mobile emulation configuration, or `null` to disable emulation. + * @return {!Options} A self reference. + */ + setMobileEmulation(config: any): Options; + + /** + * Sets the proxy settings for the new session. + * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + + /** + * Converts this options instance to a {@link webdriver.Capabilities} object. + * @param {webdriver.Capabilities=} opt_capabilities The capabilities to merge + * these options into, if any. + * @return {!webdriver.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; +} + +/** + * Creates {@link remote.DriverService} instances that manage a ChromeDriver + * server. + */ +export class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the chromedriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the chromedriver + * cannot be found on the PATH. + * @constructor + */ + constructor(opt_exe?: string); + + /** + * Sets the port to start the ChromeDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; + + + /** + * Sets which port adb is listening to. _The ChromeDriver will connect to adb + * if an {@linkplain Options#androidPackage Android session} is requested, but + * adb **must** be started beforehand._ + * + * @param {number} port Which port adb is running on. + * @return {!ServiceBuilder} A self reference. + */ + setAdbPort(port: number): ServiceBuilder; + + + /** + * Sets the path of the log file the driver should log to. If a log file is + * not specified, the driver will log to stderr. + * @param {string} path Path of the log file to use. + * @return {!ServiceBuilder} A self reference. + */ + loggingTo(path: string): ServiceBuilder; + + + /** + * Enables verbose logging. + * @return {!ServiceBuilder} A self reference. + */ + enableVerboseLogging(): ServiceBuilder; + + + /** + * Sets the number of threads the driver should use to manage HTTP requests. + * By default, the driver will use 4 threads. + * @param {number} n The number of threads to use. + * @return {!ServiceBuilder} A self reference. + */ + setNumHttpThreads(n: number): ServiceBuilder; + + + /** + * Sets the base path for WebDriver REST commands (e.g. '/wd/hub'). + * By default, the driver will accept commands relative to '/'. + * @param {string} path The base path to use. + * @return {!ServiceBuilder} A self reference. + */ + setUrlBasePath(path: string): ServiceBuilder; + + + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array.)} config The + * configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string | Array): ServiceBuilder; + + + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: { [key: string]: string }): ServiceBuilder; + + + /** + * Creates a new DriverService using this instance's current configuration. + * @return {remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; +} + +/** + * Returns the default ChromeDriver service. If such a service has not been + * configured, one will be constructed using the default configuration for + * a ChromeDriver executable found on the system PATH. + * @return {!remote.DriverService} The default ChromeDriver service. + */ +export function getDefaultService(): remote.DriverService; + +/** + * Sets the default service to use for new ChromeDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ +export function setDefaultService(service: remote.DriverService): void; diff --git a/selenium-webdriver/v2/edge.d.ts b/selenium-webdriver/v2/edge.d.ts new file mode 100644 index 0000000000..576dc01f94 --- /dev/null +++ b/selenium-webdriver/v2/edge.d.ts @@ -0,0 +1,125 @@ +/* tslint:disable */ +import * as webdriver from './index'; +import * as remote from './remote'; + +export class Driver extends webdriver.WebDriver { + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@linkplain #getDefaultService default service} by default. + * @param {promise.ControlFlow=} opt_flow The control flow to use, or + * {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities | Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; +} + +/** + * Class for managing MicrosoftEdgeDriver specific options. + */ +export class Options { + + /** + * Extracts the MicrosoftEdgeDriver specific options from the given + * capabilities object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The MicrosoftEdgeDriver options. + */ + static fromCapabilities(cap: webdriver.Capabilities): Options; + + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Sets the page load strategy for Edge. + * Supported values are 'normal', 'eager', and 'none'; + * + * @param {string} pageLoadStrategy The page load strategy to use. + * @return {!Options} A self reference. + */ + setPageLoadStrategy(pageLoadStrategy: string): Options; + + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; +} + +/** + * Creates {@link remote.DriverService} instances that manage a + * MicrosoftEdgeDriver server in a child process. + */ +export class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the MicrosoftEdgeDriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the + * MicrosoftEdgeDriver cannot be found on the PATH. + */ + constructor(opt_exe?: string); + + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array.)} + * config The configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string | Array): ServiceBuilder; + + /** + * Sets the port to start the MicrosoftEdgeDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; + + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: Object): ServiceBuilder; + + /** + * Creates a new DriverService using this instance's current configuration. + * @return {!remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; +} + +/** + * Returns the default MicrosoftEdgeDriver service. If such a service has + * not been configured, one will be constructed using the default configuration + * for an MicrosoftEdgeDriver executable found on the system PATH. + * @return {!remote.DriverService} The default MicrosoftEdgeDriver service. + */ +export function getDefaultService(): remote.DriverService; + +/** + * Sets the default service to use for new MicrosoftEdgeDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ +export function setDefaultService(service: remote.DriverService): void; diff --git a/selenium-webdriver/executors.d.ts b/selenium-webdriver/v2/executors.d.ts similarity index 96% rename from selenium-webdriver/executors.d.ts rename to selenium-webdriver/v2/executors.d.ts index c7bf15ef8d..ddb3e5b752 100644 --- a/selenium-webdriver/executors.d.ts +++ b/selenium-webdriver/v2/executors.d.ts @@ -1,3 +1,4 @@ +/* tslint:disable */ import * as webdriver from './index'; /** diff --git a/selenium-webdriver/v2/firefox.d.ts b/selenium-webdriver/v2/firefox.d.ts new file mode 100644 index 0000000000..9865896ba7 --- /dev/null +++ b/selenium-webdriver/v2/firefox.d.ts @@ -0,0 +1,254 @@ +/* tslint:disable */ +import * as webdriver from './index'; +import * as remote from './remote'; + +/** + * Manages a Firefox subprocess configured for use with WebDriver. + */ +export class Binary { + /** + * @param {string=} opt_exe Path to the Firefox binary to use. If not + * specified, will attempt to locate Firefox on the current system. + * @constructor + */ + constructor(opt_exe?: string); + + /** + * Add arguments to the command line used to start Firefox. + * @param {...(string|!Array.)} var_args Either the arguments to add as + * varargs, or the arguments as an array. + */ + addArguments(...var_args: string[]): void; + + + /** + * Launches Firefox and eturns a promise that will be fulfilled when the process + * terminates. + * @param {string} profile Path to the profile directory to use. + * @return {!promise.Promise.} A promise for the process result. + * @throws {Error} If this instance has already been started. + */ + launch(profile: string): webdriver.promise.Promise; + + + /** + * Kills the managed Firefox process. + * @return {!promise.Promise} A promise for when the process has terminated. + */ + kill(): webdriver.promise.Promise; +} + +/** + * Models a Firefox proifle directory for use with the FirefoxDriver. The + * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} + * is called. + */ +export class Profile { + /** + * @param {string=} opt_dir Path to an existing Firefox profile directory to + * use a template for this profile. If not specified, a blank profile will + * be used. + * @constructor + */ + constructor(opt_dir?: string); + + /** + * Registers an extension to be included with this profile. + * @param {string} extension Path to the extension to include, as either an + * unpacked extension directory or the path to a xpi file. + */ + addExtension(extension: string): void; + + + /** + * Sets a desired preference for this profile. + * @param {string} key The preference key. + * @param {(string|number|boolean)} value The preference value. + * @throws {Error} If attempting to set a frozen preference. + */ + setPreference(key: string, value: string): void; + setPreference(key: string, value: number): void; + setPreference(key: string, value: boolean): void; + + + /** + * Returns the currently configured value of a profile preference. This does + * not include any defaults defined in the profile's template directory user.js + * file (if a template were specified on construction). + * @param {string} key The desired preference. + * @return {(string|number|boolean|undefined)} The current value of the + * requested preference. + */ + getPreference(key: string): any; + + + /** + * @return {number} The port this profile is currently configured to use, or + * 0 if the port will be selected at random when the profile is written + * to disk. + */ + getPort(): number; + + + /** + * Sets the port to use for the WebDriver extension loaded by this profile. + * @param {number} port The desired port, or 0 to use any free port. + */ + setPort(port: number): void; + + + /** + * @return {boolean} Whether the FirefoxDriver is configured to automatically + * accept untrusted SSL certificates. + */ + acceptUntrustedCerts(): boolean; + + + /** + * Sets whether the FirefoxDriver should automatically accept untrusted SSL + * certificates. + * @param {boolean} value . + */ + setAcceptUntrustedCerts(value: boolean): void; + + + /** + * Sets whether to assume untrusted certificates come from untrusted issuers. + * @param {boolean} value . + */ + setAssumeUntrustedCertIssuer(value: boolean): void; + + + /** + * @return {boolean} Whether to assume untrusted certs come from untrusted + * issuers. + */ + assumeUntrustedCertIssuer(): boolean; + + + /** + * Sets whether to use native events with this profile. + * @param {boolean} enabled . + */ + setNativeEventsEnabled(enabled: boolean): void; + + + /** + * Returns whether native events are enabled in this profile. + * @return {boolean} . + */ + nativeEventsEnabled(): boolean; + + + /** + * Writes this profile to disk. + * @param {boolean=} opt_excludeWebDriverExt Whether to exclude the WebDriver + * extension from the generated profile. Used to reduce the size of an + * {@link #encode() encoded profile} since the server will always install + * the extension itself. + * @return {!promise.Promise.} A promise for the path to the new + * profile directory. + */ + writeToDisk(opt_excludeWebDriverExt?: boolean): webdriver.promise.Promise; + + + /** + * Encodes this profile as a zipped, base64 encoded directory. + * @return {!promise.Promise.} A promise for the encoded profile. + */ + encode(): webdriver.promise.Promise; +} + +/** + * Configuration options for the FirefoxDriver. + */ +export class Options { + /** + * Sets the profile to use. The profile may be specified as a + * {@link Profile} object or as the path to an existing Firefox profile to use + * as a template. + * + * @param {(string|!Profile)} profile The profile to use. + * @return {!Options} A self reference. + */ + setProfile(profile: string | any): Options; + + /** + * Sets the binary to use. The binary may be specified as the path to a Firefox + * executable, or as a {@link Binary} object. + * + * @param {(string|!Binary)} binary The binary to use. + * @return {!Options} A self reference. + */ + setBinary(binary: string | any): Options; + + /** + * Sets the logging preferences for the new session. + * @param {logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the proxy to use. + * + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Sets whether to use Mozilla's Marionette to drive the browser. + * + * @see https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver + */ + useMarionette(marionette: any): Options; + + /** + * Converts these options to a {@link capabilities.Capabilities} instance. + * + * @return {!capabilities.Capabilities} A new capabilities object. + */ + toCapabilities(): webdriver.Capabilities; +} + +/** + * @return {string} . + * @throws {Error} + */ +export function findWires(): string; + +/** + * @param {(string|!Binary)} binary . + * @return {!remote.DriverService} . + */ +export function createWiresService(binary: string | any): remote.DriverService; + +/** + * @param {(Profile|string)} profile The profile to prepare. + * @param {number} port The port the FirefoxDriver should listen on. + * @return {!Promise} a promise for the path to the profile directory. + */ +export function prepareProfile(profile: string | any, port: number): any; + +/** + * A WebDriver client for Firefox. + */ +export class Driver extends webdriver.WebDriver { + /** + * @param {(Options|capabilities.Capabilities|Object)=} opt_config The + * configuration options for this driver, specified as either an + * {@link Options} or {@link capabilities.Capabilities}, or as a raw hash + * object. + * @param {promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + */ + constructor(opt_config?: Options | webdriver.Capabilities | Object, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; +} diff --git a/selenium-webdriver/v2/http.d.ts b/selenium-webdriver/v2/http.d.ts new file mode 100644 index 0000000000..bdb2797406 --- /dev/null +++ b/selenium-webdriver/v2/http.d.ts @@ -0,0 +1,153 @@ +/* tslint:disable */ +import * as webdriver from './index'; + +/** + * Converts a headers map to a HTTP header block string. + * @param {!Map} headers The map to convert. + * @return {string} The headers as a string. + */ +export function headersToString(headers: any): string; + +/** + * Represents a HTTP request message. This class is a 'partial' request and only + * defines the path on the server to send a request to. It is each client's + * responsibility to build the full URL for the final request. + * @final + */ +export class HttpRequest { + /** + * @param {string} method The HTTP method to use for the request. + * @param {string} path The path on the server to send the request to. + * @param {Object=} opt_data This request's non-serialized JSON payload data. + */ + constructor(method: string, path: string, opt_data?: Object); + + /** @override */ + toString(): string; +} + +/** + * Represents a HTTP response message. + * @final + */ +export class HttpResponse { + /** + * @param {number} status The response code. + * @param {!Object} headers The response headers. All header names + * will be converted to lowercase strings for consistent lookups. + * @param {string} body The response body. + */ + constructor(status: number, headers: Object, body: string); + + /** @override */ + toString(): string; +} + + +export function post(path: string): any; +export function del(path: string): any; +export function get(path: string): any; +export function resource(method: string, path: string): any; + +/** + * A basic HTTP client used to send messages to a remote end. + */ +export class HttpClient { + /** + * @param {string} serverUrl URL for the WebDriver server to send commands to. + * @param {http.Agent=} opt_agent The agent to use for each request. + * Defaults to `http.globalAgent`. + * @param {?string=} opt_proxy The proxy to use for the connection to the + * server. Default is to use no proxy. + */ + constructor(serverUrl: string, opt_agent?: any, opt_proxy?: string); + + /** + * Sends a request to the server. The client will automatically follow any + * redirects returned by the server, fulfilling the returned promise with the + * final response. + * + * @param {!HttpRequest} httpRequest The request to send. + * @return {!promise.Promise} A promise that will be fulfilled + * with the server's response. + */ + send(httpRequest: HttpRequest): webdriver.promise.Promise; +} + +/** + * Sends a single HTTP request. + * @param {!Object} options The request options. + * @param {function(!HttpResponse)} onOk The function to call if the + * request succeeds. + * @param {function(!Error)} onError The function to call if the request fails. + * @param {?string=} opt_data The data to send with the request. + * @param {?string=} opt_proxy The proxy server to use for the request. + */ +export function sendRequest(options: Object, onOk: any, onError: any, opt_data?: string, opt_proxy?: string): any; + +/** + * A command executor that communicates with the server using HTTP + JSON. + * + * By default, each instance of this class will use the legacy wire protocol + * from [Selenium project][json]. The executor will automatically switch to the + * [W3C wire protocol][w3c] if the remote end returns a compliant response to + * a new session command. + * + * [json]: https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol + * [w3c]: https://w3c.github.io/webdriver/webdriver-spec.html + * + * @implements {cmd.Executor} + */ +export class Executor { + /** + * @param {!HttpClient} client The client to use for sending requests to the + * server. + */ + constructor(client: HttpClient); + + /** + * Defines a new command for use with this executor. When a command is sent, + * the {@code path} will be preprocessed using the command's parameters; any + * path segments prefixed with ':' will be replaced by the parameter of the + * same name. For example, given '/person/:name' and the parameters + * '{name: 'Bob'}', the final command path will be '/person/Bob'. + * + * @param {string} name The command name. + * @param {string} method The HTTP method to use when sending this command. + * @param {string} path The path to send the command to, relative to + * the WebDriver server's command root and of the form + * '/path/:variable/segment'. + */ + defineCommand(name: string, method: string, path: string): void; + + /** @override */ + execute(command: any): any; +} + +/** + * @param {string} str . + * @return {?} . + */ +export function tryParse(str: string): any; + +/** + * Callback used to parse {@link HttpResponse} objects from a + * {@link HttpClient}. + * @param {!HttpResponse} httpResponse The HTTP response to parse. + * @param {boolean} w3c Whether the response should be processed using the + * W3C wire protocol. + * @return {{value: ?}} The parsed response. + * @throws {WebDriverError} If the HTTP response is an error. + */ +export function parseHttpResponse(httpResponse: HttpResponse, w3c: boolean): any; + +/** + * Builds a fully qualified path using the given set of command parameters. Each + * path segment prefixed with ':' will be replaced by the value of the + * corresponding parameter. All parameters spliced into the path will be + * removed from the parameter map. + * @param {string} path The original resource path. + * @param {!Object<*>} parameters The parameters object to splice into the path. + * @return {string} The modified path. + */ +export function buildPath(path: string, parameters: Object): string; diff --git a/selenium-webdriver/v2/ie.d.ts b/selenium-webdriver/v2/ie.d.ts new file mode 100644 index 0000000000..a9ae4b2c4a --- /dev/null +++ b/selenium-webdriver/v2/ie.d.ts @@ -0,0 +1,206 @@ +/* tslint:disable */ +import * as webdriver from './index'; + +/** + * A WebDriver client for Microsoft's Internet Explorer. + */ +export class Driver extends webdriver.WebDriver { + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {promise.ControlFlow=} opt_flow The control flow to use, + * or {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities | Options, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; +} + +/** + * Class for managing IEDriver specific options. + */ +export class Options { + constructor(); + + /** + * Extracts the IEDriver specific options from the given capabilities + * object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The IEDriver options. + */ + static fromCapabilities(caps: webdriver.Capabilities): Options; + + /** + * Whether to disable the protected mode settings check when the session is + * created. Disbling this setting may lead to significant instability as the + * browser may become unresponsive/hang. Only 'best effort' support is provided + * when using this capability. + * + * For more information, refer to the IEDriver's + * [required system configuration](http://goo.gl/eH0Yi3). + * + * @param {boolean} ignoreSettings Whether to ignore protected mode settings. + * @return {!Options} A self reference. + */ + introduceFlakinessByIgnoringProtectedModeSettings(ignoreSettings: boolean): Options; + + /** + * Indicates whether to skip the check that the browser's zoom level is set to + * 100%. + * + * @param {boolean} ignore Whether to ignore the browser's zoom level settings. + * @return {!Options} A self reference. + */ + ignoreZoomSetting(ignore: boolean): Options; + + /** + * Sets the initial URL loaded when IE starts. This is intended to be used with + * {@link #ignoreProtectedModeSettings} to allow the user to initialize IE in + * the proper Protected Mode zone. Setting this option may cause browser + * instability or flaky and unresponsive code. Only 'best effort' support is + * provided when using this option. + * + * @param {string} url The initial browser URL. + * @return {!Options} A self reference. + */ + initialBrowserUrl(url: string): Options; + + /** + * Configures whether to enable persistent mouse hovering (true by default). + * Persistent hovering is achieved by continuously firing mouse over events at + * the last location the mouse cursor has been moved to. + * + * @param {boolean} enable Whether to enable persistent hovering. + * @return {!Options} A self reference. + */ + enablePersistentHover(enable: boolean): Options; + + /** + * Configures whether the driver should attempt to remove obsolete + * {@linkplain webdriver.WebElement WebElements} from its internal cache on + * page navigation (true by default). Disabling this option will cause the + * driver to run with a larger memory footprint. + * + * @param {boolean} enable Whether to enable element reference cleanup. + * @return {!Options} A self reference. + */ + enableElementCacheCleanup(enable: boolean): Options; + + /** + * Configures whether to require the IE window to have input focus before + * performing any user interactions (i.e. mouse or keyboard events). This + * option is disabled by default, but delivers much more accurate interaction + * events when enabled. + * + * @param {boolean} require Whether to require window focus. + * @return {!Options} A self reference. + */ + requireWindowFocus(require: boolean): Options; + + /** + * Configures the timeout, in milliseconds, that the driver will attempt to + * located and attach to a newly opened instance of Internet Explorer. The + * default is zero, which indicates waiting indefinitely. + * + * @param {number} timeout How long to wait for IE. + * @return {!Options} A self reference. + */ + browserAttachTimeout(timeout: number): Options; + + /** + * Configures whether to launch Internet Explorer using the CreateProcess API. + * If this option is not specified, IE is launched using IELaunchURL, if + * available. For IE 8 and above, this option requires the TabProcGrowth + * registry value to be set to 0. + * + * @param {boolean} force Whether to use the CreateProcess API. + * @return {!Options} A self reference. + */ + forceCreateProcessApi(force: boolean): Options; + + /** + * Specifies command-line switches to use when launching Internet Explorer. + * This is only valid when used with {@link #forceCreateProcessApi}. + * + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: string[]): Options; + + /** + * Configures whether proxies should be configured on a per-process basis. If + * not set, setting a {@linkplain #setProxy proxy} will configure the system + * proxy. The default behavior is to use the system proxy. + * + * @param {boolean} enable Whether to enable per-process proxy settings. + * @return {!Options} A self reference. + */ + usePerProcessProxy(enable: boolean): Options; + + /** + * Configures whether to clear the cache, cookies, history, and saved form data + * before starting the browser. _Using this capability will clear session data + * for all running instances of Internet Explorer, including those started + * manually._ + * + * @param {boolean} cleanSession Whether to clear all session data on startup. + * @return {!Options} A self reference. + */ + ensureCleanSession(cleanSession: boolean): Options; + + /** + * Sets the path to the log file the driver should log to. + * @param {string} file The log file path. + * @return {!Options} A self reference. + */ + setLogFile(file: string): Options; + + /** + * Sets the IEDriverServer's logging {@linkplain Level level}. + * @param {Level} level The logging level. + * @return {!Options} A self reference. + */ + setLogLevel(level: webdriver.logging.Level): Options; + + /** + * Sets the IP address of the driver's host adapter. + * @param {string} host The IP address to use. + * @return {!Options} A self reference. + */ + setHost(host: string): Options; + + /** + * Sets the path of the temporary data directory to use. + * @param {string} path The log file path. + * @return {!Options} A self reference. + */ + setExtractPath(path: string): Options; + + /** + * Sets whether the driver should start in silent mode. + * @param {boolean} silent Whether to run in silent mode. + * @return {!Options} A self reference. + */ + silent(silent: boolean): Options; + + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; +} diff --git a/selenium-webdriver/v2/index.d.ts b/selenium-webdriver/v2/index.d.ts new file mode 100644 index 0000000000..25e9e0f606 --- /dev/null +++ b/selenium-webdriver/v2/index.d.ts @@ -0,0 +1,5050 @@ +// Type definitions for Selenium WebDriverJS 2.53 +// Project: https://github.com/SeleniumHQ/selenium/tree/master/javascript/node/selenium-webdriver +// Definitions by: Bill Armstrong , Yuki Kokubun , Craig Nishina +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 +/* tslint:disable */ + +import * as chrome from './chrome'; +import * as edge from './edge'; +import * as firefox from './firefox'; +import * as ie from './ie'; +import * as opera from './opera'; +import * as safari from './safari'; + +export namespace error { + class IError extends Error { + constructor(opt_error?: string); + + code(): number; + } + + /** + * The base WebDriver error type. This error type is only used directly when a + * more appropriate category is not defined for the offending error. + */ + class WebDriverError extends IError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An attempt was made to select an element that cannot be selected. + */ + class ElementNotSelectableError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An element command could not be completed because the element is not visible + * on the page. + */ + class ElementNotVisibleError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The arguments passed to a command are either invalid or malformed. + */ + class InvalidArgumentError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An illegal attempt was made to set a cookie under a different domain than + * the current page. + */ + class InvalidCookieDomainError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The coordinates provided to an interactions operation are invalid. + */ + class InvalidElementCoordinatesError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An element command could not be completed because the element is in an + * invalid state, e.g. attempting to click an element that is no longer attached + * to the document. + */ + class InvalidElementStateError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * Argument was an invalid selector. + */ + class InvalidSelectorError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * Occurs when a command is directed to a session that does not exist. + */ + class NoSuchSessionError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An error occurred while executing JavaScript supplied by the user. + */ + class JavascriptError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The target for mouse interaction is not in the browser’s viewport and cannot + * be brought into that viewport. + */ + class MoveTargetOutOfBoundsError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An attempt was made to operate on a modal dialog when one was not open. + */ + class NoSuchAlertError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An element could not be located on the page using the given search + * parameters. + */ + class NoSuchElementError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A request to switch to a frame could not be satisfied because the frame + * could not be found. + */ + class NoSuchFrameError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A request to switch to a window could not be satisfied because the window + * could not be found. + */ + class NoSuchWindowError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A script did not complete before its timeout expired. + */ + class ScriptTimeoutError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A new session could not be created. + */ + class SessionNotCreatedError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An element command failed because the referenced element is no longer + * attached to the DOM. + */ + class StaleElementReferenceError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An operation did not completErrorCodee before its timeout expired. + */ + class TimeoutError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A request to set a cookie’s value could not be satisfied. + */ + class UnableToSetCookieError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A screen capture operation was not possible. + */ + class UnableToCaptureScreenError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A modal dialog was open, blocking this operation. + */ + class UnexpectedAlertOpenError extends WebDriverError { + /** + * @param {string=} opt_error the error message, if any. + * @param {string=} opt_text the text of the open dialog, if available. + */ + constructor(opt_error?: string, opt_text?: string); + + /** + * @return {(string|undefined)} The text displayed with the unhandled alert, + * if available. + */ + getAlertText(): string; + } + + /** + * A command could not be executed because the remote end is not aware of it. + */ + class UnknownCommandError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The requested command matched a known URL but did not match an method for + * that URL. + */ + class UnknownMethodError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * Reports an unsupport operation. + */ + class UnsupportedOperationError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } +} + +export namespace logging { + + /** + * A hash describing log preferences. + * @typedef {Object.} + */ + class Preferences { + setLevel(type: string, level: Level | string | number): void; + toJSON(): { [key: string]: string }; + } + + interface IType { + /** Logs originating from the browser. */ + BROWSER: string; + /** Logs from a WebDriver client. */ + CLIENT: string; + /** Logs from a WebDriver implementation. */ + DRIVER: string; + /** Logs related to performance. */ + PERFORMANCE: string; + /** Logs from the remote server. */ + SERVER: string; + } + + /** + * Common log types. + * @enum {string} + */ + var Type: IType; + + /** + * Defines a message level that may be used to control logging output. + * + * @final + */ + class Level { + name_: string; + value_: number; + /** + * @param {string} name the level's name. + * @param {number} level the level's numeric value. + */ + constructor(name: string, level: number); + + /** @override */ + toString(): string; + + /** This logger's name. */ + name: string; + + /** The numeric log level. */ + value: number; + + /** + * Indicates no log messages should be recorded. + * @const + */ + static OFF: Level; + /** + * Log messages with a level of `1000` or higher. + * @const + */ + static SEVERE: Level; + /** + * Log messages with a level of `900` or higher. + * @const + */ + static WARNING: Level; + /** + * Log messages with a level of `800` or higher. + * @const + */ + static INFO: Level; + /** + * Log messages with a level of `700` or higher. + * @const + */ + static DEBUG: Level; + /** + * Log messages with a level of `500` or higher. + * @const + */ + static FINE: Level; + /** + * Log messages with a level of `400` or higher. + * @const + */ + static FINER: Level; + /** + * Log messages with a level of `300` or higher. + * @const + */ + static FINEST: Level; + /** + * Indicates all log messages should be recorded. + * @const + */ + static ALL: Level; + } + + /** + * Converts a level name or value to a {@link logging.Level} value. + * If the name/value is not recognized, {@link logging.Level.ALL} + * will be returned. + * @param {(number|string)} nameOrValue The log level name, or value, to + * convert . + * @return {!logging.Level} The converted level. + */ + function getLevel(nameOrValue: string | number): Level; + + interface IEntryJSON { + level: string; + message: string; + timestamp: number; + type: string; + } + + /** + * A single log entry. + */ + class Entry { + /** + * @param {(!logging.Level|string)} level The entry level. + * @param {string} message The log message. + * @param {number=} opt_timestamp The time this entry was generated, in + * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the + * current time will be used. + * @param {string=} opt_type The log type, if known. + * @constructor + */ + constructor(level: Level | string | number, message: string, opt_timestamp?: number, opt_type?: string | IType); + + /** @type {!logging.Level} */ + level: Level; + + /** @type {string} */ + message: string; + + /** @type {number} */ + timestamp: number; + + /** @type {string} */ + type: string; + + /** + * @return {{level: string, message: string, timestamp: number, + * type: string}} The JSON representation of this entry. + */ + toJSON(): IEntryJSON; + } + + /** + * An object used to log debugging messages. Loggers use a hierarchical, + * dot-separated naming scheme. For instance, 'foo' is considered the parent of + * the 'foo.bar' and an ancestor of 'foo.bar.baz'. + * + * Each logger may be assigned a {@linkplain #setLevel log level}, which + * controls which level of messages will be reported to the + * {@linkplain #addHandler handlers} attached to this instance. If a log level + * is not explicitly set on a logger, it will inherit its parent. + * + * This class should never be directly instantiated. Instead, users should + * obtain logger references using the {@linkplain ./logging.getLogger() + * getLogger()} function. + * + * @final + */ + class Logger { + /** + * @param {string} name the name of this logger. + * @param {Level=} opt_level the initial level for this logger. + */ + constructor(name: string, opt_level?: Level); + + /** @private {string} */ + name_: string; + /** @private {Level} */ + level_: Level; + /** @private {Logger} */ + parent_: Logger; + /** @private {Set} */ + handlers_: any; + + /** @return {string} the name of this logger. */ + getName(): string; + + /** + * @param {Level} level the new level for this logger, or `null` if the logger + * should inherit its level from its parent logger. + */ + setLevel(level: Level): void; + + /** @return {Level} the log level for this logger. */ + getLevel(): Level; + + /** + * @return {!Level} the effective level for this logger. + */ + getEffectiveLevel(): Level; + + /** + * @param {!Level} level the level to check. + * @return {boolean} whether messages recorded at the given level are loggable + * by this instance. + */ + isLoggable(level: Level): boolean; + + /** + * Adds a handler to this logger. The handler will be invoked for each message + * logged with this instance, or any of its descendants. + * + * @param {function(!Entry)} handler the handler to add. + */ + addHandler(handler: any): void; + + /** + * Removes a handler from this logger. + * + * @param {function(!Entry)} handler the handler to remove. + * @return {boolean} whether a handler was successfully removed. + */ + removeHandler(handler: any): void; + + /** + * Logs a message at the given level. The message may be defined as a string + * or as a function that will return the message. If a function is provided, + * it will only be invoked if this logger's + * {@linkplain #getEffectiveLevel() effective log level} includes the given + * `level`. + * + * @param {!Level} level the level at which to log the message. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + log(level: Level, loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.SEVERE} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + severe(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.WARNING} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + warning(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.INFO} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + info(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.DEBUG} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + debug(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.FINE} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + fine(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.FINER} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + finer(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.FINEST} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + finest(loggable: string | Function): void; + } + + /** + * Maintains a collection of loggers. + * + * @final + */ + class LogManager { + /** + * Retrieves a named logger, creating it in the process. This function will + * implicitly create the requested logger, and any of its parents, if they + * do not yet exist. + * + * @param {string} name the logger's name. + * @return {!Logger} the requested logger. + */ + getLogger(name: string): Logger; + + /** + * Creates a new logger. + * + * @param {string} name the logger's name. + * @param {!Logger} parent the logger's parent. + * @return {!Logger} the new logger. + * @private + */ + createLogger_(name: string, parent: Logger): Logger; + } +} + +export namespace promise { + // region Functions + + /** + * Given an array of promises, will return a promise that will be fulfilled + * with the fulfillment values of the input array's values. If any of the + * input array's promises are rejected, the returned promise will be rejected + * with the same reason. + * + * @param {!Array<(T|!ManagedPromise)>} arr An array of + * promises to wait on. + * @return {!ManagedPromise} A promise that is + * fulfilled with an array containing the fulfilled values of the + * input array, or rejected with the same reason as the first + * rejected value. + * @template T + */ + function all(arr: Array>): Promise; + + /** + * Invokes the appropriate callback function as soon as a promised + * {@code value} is resolved. This function is similar to + * {@link promise.when}, except it does not return a new promise. + * @param {*} value The value to observe. + * @param {Function} callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + */ + function asap(value: any, callback: Function, opt_errback?: Function): void; + + /** + * @return {!promise.ControlFlow} The currently active control flow. + */ + function controlFlow(): ControlFlow; + + /** + * Creates a new control flow. The provided callback will be invoked as the + * first task within the new flow, with the flow as its sole argument. Returns + * a promise that resolves to the callback result. + * @param {function(!ControlFlow)} callback The entry point + * to the newly created flow. + * @return {!ManagedPromise} A promise that resolves to the callback + * result. + */ + function createFlow(callback: (flow: ControlFlow) => R): Promise; + + /** + * Determines whether a {@code value} should be treated as a promise. + * Any object whose 'then' property is a function will be considered a promise. + * + * @param {*} value The value to test. + * @return {boolean} Whether the value is a promise. + */ + function isPromise(value: any): boolean; + + /** + * Tests is a function is a generator. + * @param {!Function} fn The function to test. + * @return {boolean} Whether the function is a generator. + */ + function isGenerator(fn: Function): boolean; + + /** + * Creates a promise that will be resolved at a set time in the future. + * @param {number} ms The amount of time, in milliseconds, to wait before + * resolving the promise. + * @return {!ManagedPromise} The promise. + */ + function delayed(ms: number): Promise; + + /** + * Calls a function for each element in an array, and if the function returns + * true adds the element to a new array. + * + * If the return value of the filter function is a promise, this function + * will wait for it to be fulfilled before determining whether to insert the + * element into the new array. + * + * If the filter function throws or returns a rejected promise, the promise + * returned by this function will be rejected with the same reason. Only the + * first failure will be reported; all subsequent errors will be silently + * ignored. + * + * @param {!(Array|ManagedPromise>)} arr The + * array to iterator over, or a promise that will resolve to said array. + * @param {function(this: SELF, TYPE, number, !Array): ( + * boolean|ManagedPromise)} fn The function + * to call for each element in the array. + * @param {SELF=} opt_self The object to be used as the value of 'this' within + * {@code fn}. + * @template TYPE, SELF + */ + function filter(arr: T[] | Promise, fn: (element: T, type: any, index: number, array: T[]) => any, opt_self?: any): Promise; + + /** + * Creates a new deferred object. + * @return {!promise.Deferred} The new deferred object. + */ + function defer(): Deferred; + + /** + * Creates a promise that has been resolved with the given value. + * @param {T=} opt_value The resolved value. + * @return {!ManagedPromise} The resolved promise. + * @template T + */ + function fulfilled(opt_value?: T): Promise; + + /** + * Calls a function for each element in an array and inserts the result into a + * new array, which is used as the fulfillment value of the promise returned + * by this function. + * + * If the return value of the mapping function is a promise, this function + * will wait for it to be fulfilled before inserting it into the new array. + * + * If the mapping function throws or returns a rejected promise, the + * promise returned by this function will be rejected with the same reason. + * Only the first failure will be reported; all subsequent errors will be + * silently ignored. + * + * @param {!(Array|ManagedPromise>)} arr The + * array to iterator over, or a promise that will resolve to said array. + * @param {function(this: SELF, TYPE, number, !Array): ?} fn The + * function to call for each element in the array. This function should + * expect three arguments (the element, the index, and the array itself. + * @param {SELF=} opt_self The object to be used as the value of 'this' within + * {@code fn}. + * @template TYPE, SELF + */ + function map(arr: T[] | Promise, fn: (self: any, type: any, index: number, array: T[]) => any, opt_self?: any): Promise; + + /** + * Creates a promise that has been rejected with the given reason. + * @param {*=} opt_reason The rejection reason; may be any value, but is + * usually an Error or a string. + * @return {!ManagedPromise} The rejected promise. + * @template T + */ + function rejected(opt_reason?: any): Promise; + + /** + * Wraps a function that expects a node-style callback as its final + * argument. This callback expects two arguments: an error value (which will be + * null if the call succeeded), and the success value as the second argument. + * The callback will the resolve or reject the returned promise, based on its + * arguments. + * @param {!Function} fn The function to wrap. + * @param {...?} var_args The arguments to apply to the function, excluding the + * final callback. + * @return {!ManagedPromise} A promise that will be resolved with the + * result of the provided function's callback. + */ + function checkedNodeCall(fn: Function, ...var_args: any[]): Promise; + + /** + * Consumes a {@code GeneratorFunction}. Each time the generator yields a + * promise, this function will wait for it to be fulfilled before feeding the + * fulfilled value back into {@code next}. Likewise, if a yielded promise is + * rejected, the rejection error will be passed to {@code throw}. + * + * __Example 1:__ the Fibonacci Sequence. + * + * promise.consume(function* fibonacci() { + * var n1 = 1, n2 = 1; + * for (var i = 0; i < 4; ++i) { + * var tmp = yield n1 + n2; + * n1 = n2; + * n2 = tmp; + * } + * return n1 + n2; + * }).then(function(result) { + * console.log(result); // 13 + * }); + * + * __Example 2:__ a generator that throws. + * + * promise.consume(function* () { + * yield promise.delayed(250).then(function() { + * throw Error('boom'); + * }); + * }).catch(function(e) { + * console.log(e.toString()); // Error: boom + * }); + * + * @param {!Function} generatorFn The generator function to execute. + * @param {Object=} opt_self The object to use as 'this' when invoking the + * initial generator. + * @param {...*} var_args Any arguments to pass to the initial generator. + * @return {!ManagedPromise} A promise that will resolve to the + * generator's final result. + * @throws {TypeError} If the given function is not a generator. + */ + function consume(generatorFn: Function, opt_self?: any, ...var_args: any[]): Promise; + + /** + * Registers an observer on a promised {@code value}, returning a new promise + * that will be resolved when the value is. If {@code value} is not a promise, + * then the return promise will be immediately resolved. + * @param {*} value The value to observe. + * @param {Function=} opt_callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + * @return {!ManagedPromise} A new promise. + */ + function when(value: T | Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; + + /** + * Returns a promise that will be resolved with the input value in a + * fully-resolved state. If the value is an array, each element will be fully + * resolved. Likewise, if the value is an object, all keys will be fully + * resolved. In both cases, all nested arrays and objects will also be + * fully resolved. All fields are resolved in place; the returned promise will + * resolve on {@code value} and not a copy. + * + * Warning: This function makes no checks against objects that contain + * cyclical references: + * + * var value = {}; + * value['self'] = value; + * promise.fullyResolved(value); // Stack overflow. + * + * @param {*} value The value to fully resolve. + * @return {!ManagedPromise} A promise for a fully resolved version + * of the input value. + */ + function fullyResolved(value: any): Promise; + + /** + * Changes the default flow to use when no others are active. + * @param {!ControlFlow} flow The new default flow. + * @throws {Error} If the default flow is not currently active. + */ + function setDefaultFlow(flow: ControlFlow): void; + + // endregion + + /** + * Error used when the computation of a promise is cancelled. + */ + class CancellationError extends Error { + /** + * @param {string=} opt_msg The cancellation message. + */ + constructor(opt_msg?: string); + } + + interface IThenable { + /** + * Cancels the computation of this promise's value, rejecting the promise in + * the process. This method is a no-op if the promise has already been + * resolved. + * + * @param {(string|Error)=} opt_reason The reason this promise is being + * cancelled. This value will be wrapped in a {@link CancellationError}. + */ + cancel(opt_reason?: string | Error): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. + * + * @param {?(function(T): (R|IThenable))=} opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param {?(function(*): (R|IThenable))=} opt_errback + * The function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + then(opt_callback?: (value: T) => R | IThenable, opt_errback?: (error: any) => any): Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): Promise; + } + + /** + * Thenable is a promise-like object with a {@code then} method which may be + * used to schedule callbacks on a promised value. + * + * @interface + * @template T + */ + class Thenable implements IThenable { + /** + * Cancels the computation of this promise's value, rejecting the promise in + * the process. This method is a no-op if the promise has already been + * resolved. + * + * @param {(string|Error)=} opt_reason The reason this promise is being + * cancelled. This value will be wrapped in a {@link CancellationError}. + */ + cancel(opt_reason?: string | Error): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. + * + * @param {?(function(T): (R|IThenable))=} opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param {?(function(*): (R|IThenable))=} opt_errback + * The function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + then(opt_callback?: (value: T) => R | IThenable, opt_errback?: (error: any) => R | IThenable): Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): Promise; + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } finally { + * cleanUp(); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().finally(cleanUp); + * + * __Note:__ similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + * + * try { + * throw Error('one'); + * } finally { + * throw Error('two'); // Hides Error: one + * } + * + * promise.rejected(Error('one')) + * .finally(function() { + * throw Error('two'); // Hides Error: one + * }); + * + * @param {function(): (R|IThenable)} callback The function to call when + * this promise is resolved. + * @return {!ManagedPromise} A promise that will be fulfilled + * with the callback result. + * @template R + */ + finally(callback: Function): Promise; + + /** + * Adds a property to a class prototype to allow runtime checks of whether + * instances of that class implement the Thenable interface. This function + * will also ensure the prototype's {@code then} function is exported from + * compiled code. + * @param {function(new: Thenable, ...?)} ctor The + * constructor whose prototype to modify. + */ + static addImplementation(ctor: Function): void; + + /** + * Checks if an object has been tagged for implementing the Thenable + * interface as defined by {@link Thenable.addImplementation}. + * @param {*} object The object to test. + * @return {boolean} Whether the object is an implementation of the Thenable + * interface. + */ + static isImplementation(object: any): boolean; + } + + interface IFulfilledCallback { + (value: T | IThenable | Thenable | undefined): void; + } + + interface IRejectedCallback { + (reason: any): void; + } + + /** + * Represents the eventual value of a completed operation. Each promise may be + * in one of three states: pending, fulfilled, or rejected. Each promise starts + * in the pending state and may make a single transition to either a + * fulfilled or rejected state, at which point the promise is considered + * resolved. + * + * @implements {promise.Thenable} + * @template T + * @see http://promises-aplus.github.io/promises-spec/ + */ + class Promise implements IThenable { + /** + * @param {function( + * function((T|IThenable|Thenable)=), + * function(*=))} resolver + * Function that is invoked immediately to begin computation of this + * promise's value. The function should accept a pair of callback + * functions, one for fulfilling the promise and another for rejecting it. + * @param {ControlFlow=} opt_flow The control flow + * this instance was created under. Defaults to the currently active flow. + */ + constructor(resolver: (resolve: IFulfilledCallback, reject: IRejectedCallback) => void, opt_flow?: ControlFlow); + + // region Methods + + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. + * @param {*} reason The reason this promise is being cancelled. If not an + * {@code Error}, one will be created using the value's string + * representation. + */ + cancel(opt_reason?: string | Error): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. This function most + * overridden by subtypes. + * + * @param opt_callback The function to call if this promise is + * successfully resolved. The function should expect a single argument: the + * promise's resolved value. + * @param opt_errback The function to call if this promise is + * rejected. The function should expect a single argument: the rejection + * reason. + * @return A new promise which will be resolved + * with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => IThenable | R, opt_errback?: (error: any) => any): Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *
              
              +     *   // Synchronous API:
              +     *   try {
              +     *     doSynchronousWork();
              +     *   } catch (ex) {
              +     *     console.error(ex);
              +     *   }
              +     *
              +     *   // Asynchronous promise API:
              +     *   doAsynchronousWork().thenCatch(function(ex) {
              +     *     console.error(ex);
              +     *   });
              +     * 
              + * + * @param {function(*): (R|promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *
              
              +     *   // Synchronous API:
              +     *   try {
              +     *     doSynchronousWork();
              +     *   } finally {
              +     *     cleanUp();
              +     *   }
              +     *
              +     *   // Asynchronous promise API:
              +     *   doAsynchronousWork().thenFinally(cleanUp);
              +     * 
              + * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *
              
              +     *   try {
              +     *     throw Error('one');
              +     *   } finally {
              +     *     throw Error('two');  // Hides Error: one
              +     *   }
              +     *
              +     *   promise.rejected(Error('one'))
              +     *       .thenFinally(function() {
              +     *         throw Error('two');  // Hides Error: one
              +     *       });
              +     * 
              + * + * + * @param {function(): (R|promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: Function): Promise; + + // endregion + } + + /** + * Represents a value that will be resolved at some point in the future. This + * class represents the protected 'producer' half of a Promise - each Deferred + * has a {@code promise} property that may be returned to consumers for + * registering callbacks, reserving the ability to resolve the deferred to the + * producer. + * + *

              If this Deferred is rejected and there are no listeners registered before + * the next turn of the event loop, the rejection will be passed to the + * {@link promise.ControlFlow} as an unhandled failure. + * + *

              If this Deferred is cancelled, the cancellation reason will be forward to + * the Deferred's canceller function (if provided). The canceller may return a + * truth-y value to override the reason provided for rejection. + * + * @extends {promise.Promise} + */ + class Deferred extends Promise { + // region Constructors + + /** + * + * @param {promise.ControlFlow=} opt_flow The control flow + * this instance was created under. This should only be provided during + * unit tests. + * @constructor + */ + constructor(opt_flow?: ControlFlow); + + // endregion + + static State_: { + BLOCKED: number; + PENDING: number; + REJECTED: number; + RESOLVED: number; + }; + + // region Properties + + /** + * The consumer promise for this instance. Provides protected access to the + * callback registering functions. + * @type {!promise.Promise} + */ + promise: Promise; + + // endregion + + // region Methods + + /** + * Rejects this promise. If the error is itself a promise, this instance will + * be chained to it and be rejected with the error's resolved value. + * @param {*=} opt_error The rejection reason, typically either a + * {@code Error} or a {@code string}. + */ + reject(opt_error?: any): void; + errback(opt_error?: any): void; + + /** + * Resolves this promise with the given value. If the value is itself a + * promise and not a reference to this deferred, this instance will wait for + * it before resolving. + * @param {*=} opt_value The resolved value. + */ + fulfill(opt_value?: T): void; + + /** + * Removes all of the listeners previously registered on this deferred. + * @throws {Error} If this deferred has already been resolved. + */ + removeAll(): void; + + // endregion + } + + interface IControlFlowTimer { + clearInterval: (ms: number) => void; + clearTimeout: (ms: number) => void; + setInterval: (fn: Function, ms: number) => number; + setTimeout: (fn: Function, ms: number) => number; + } + + interface IEventType { + /** Emitted when all tasks have been successfully executed. */ + IDLE: string; + + /** Emitted when a ControlFlow has been reset. */ + RESET: string; + + /** Emitted whenever a new task has been scheduled. */ + SCHEDULE_TASK: string; + + /** + * Emitted whenever a control flow aborts due to an unhandled promise + * rejection. This event will be emitted along with the offending rejection + * reason. Upon emitting this event, the control flow will empty its task + * queue and revert to its initial state. + */ + UNCAUGHT_EXCEPTION: string; + } + + /** + * Handles the execution of scheduled tasks, each of which may be an + * asynchronous operation. The control flow will ensure tasks are executed in + * the ordered scheduled, starting each task only once those before it have + * completed. + * + * Each task scheduled within this flow may return a + * {@link promise.Promise} to indicate it is an asynchronous + * operation. The ControlFlow will wait for such promises to be resolved before + * marking the task as completed. + * + * Tasks and each callback registered on a {@link promise.Promise} + * will be run in their own ControlFlow frame. Any tasks scheduled within a + * frame will take priority over previously scheduled tasks. Furthermore, if any + * of the tasks in the frame fail, the remainder of the tasks in that frame will + * be discarded and the failure will be propagated to the user through the + * callback/task's promised result. + * + * Each time a ControlFlow empties its task queue, it will fire an + * {@link promise.ControlFlow.EventType.IDLE IDLE} event. Conversely, + * whenever the flow terminates due to an unhandled error, it will remove all + * remaining tasks in its queue and fire an + * {@link promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION + * UNCAUGHT_EXCEPTION} event. If there are no listeners registered with the + * flow, the error will be rethrown to the global error handler. + * + * @extends {EventEmitter} + * @final + */ + class ControlFlow extends EventEmitter { + /** + * @constructor + */ + constructor(); + + /** + * Events that may be emitted by an {@link promise.ControlFlow}. + * @enum {string} + */ + static EventType: IEventType; + + /** + * Returns a string representation of this control flow, which is its current + * {@link #getSchedule() schedule}, sans task stack traces. + * @return {string} The string representation of this contorl flow. + * @override + */ + toString(): string; + + /** + * Resets this instance, clearing its queue and removing all event listeners. + */ + reset(): void; + + /** + * Generates an annotated string describing the internal state of this control + * flow, including the currently executing as well as pending tasks. If + * {@code opt_includeStackTraces === true}, the string will include the + * stack trace from when each task was scheduled. + * @param {string=} opt_includeStackTraces Whether to include the stack traces + * from when each task was scheduled. Defaults to false. + * @return {string} String representation of this flow's internal state. + */ + getSchedule(opt_includeStackTraces?: boolean): string; + + /** + * Schedules a task for execution. If there is nothing currently in the + * queue, the task will be executed in the next turn of the event loop. If + * the task function is a generator, the task will be executed using + * {@link promise.consume}. + * + * @param {function(): (T|promise.Promise)} fn The function to + * call to start the task. If the function returns a + * {@link promise.Promise}, this instance will wait for it to be + * resolved before starting the next task. + * @param {string=} opt_description A description of the task. + * @return {!promise.Promise} A promise that will be resolved + * with the result of the action. + * @template T + */ + execute(fn: () => (T | Promise), opt_description?: string): Promise; + + /** + * Inserts a {@code setTimeout} into the command queue. This is equivalent to + * a thread sleep in a synchronous programming language. + * + * @param {number} ms The timeout delay, in milliseconds. + * @param {string=} opt_description A description to accompany the timeout. + * @return {!promise.Promise} A promise that will be resolved with + * the result of the action. + */ + timeout(ms: number, opt_description?: string): Promise; + + /** + * Schedules a task that shall wait for a condition to hold. Each condition + * function may return any value, but it will always be evaluated as a boolean. + * + * Condition functions may schedule sub-tasks with this instance, however, + * their execution time will be factored into whether a wait has timed out. + * + * In the event a condition returns a Promise, the polling loop will wait for + * it to be resolved before evaluating whether the condition has been satisfied. + * The resolution time for a promise is factored into whether a wait has timed + * out. + * + * If the condition function throws, or returns a rejected promise, the + * wait task will fail. + * + * If the condition is defined as a promise, the flow will wait for it to + * settle. If the timeout expires before the promise settles, the promise + * returned by this function will be rejected. + * + * If this function is invoked with `timeout === 0`, or the timeout is omitted, + * the flow will wait indefinitely for the condition to be satisfied. + * + * @param {(!promise.Promise|function())} condition The condition to poll, + * or a promise to wait on. + * @param {number=} opt_timeout How long to wait, in milliseconds, for the + * condition to hold before timing out. If omitted, the flow will wait + * indefinitely. + * @param {string=} opt_message An optional error message to include if the + * wait times out; defaults to the empty string. + * @return {!promise.Promise} A promise that will be fulfilled + * when the condition has been satisified. The promise shall be rejected if + * the wait times out waiting for the condition. + * @throws {TypeError} If condition is not a function or promise or if timeout + * is not a number >= 0. + * @template T + */ + wait(condition: Promise | Function, opt_timeout?: number, opt_message?: string): Promise; + } +} + +export namespace until { + /** + * Defines a condition to + */ + class Condition { + /** + * @param {string} message A descriptive error message. Should complete the + * sentence 'Waiting [...]' + * @param {function(!WebDriver): OUT} fn The condition function to + * evaluate on each iteration of the wait loop. + * @constructor + */ + constructor(message: string, fn: (webdriver: WebDriver) => any); + + /** @return {string} A description of this condition. */ + description(): string; + + /** @type {function(!WebDriver): OUT} */ + fn(webdriver: WebDriver): any; + } + + /** + * Creates a condition that will wait until the input driver is able to switch + * to the designated frame. The target frame may be specified as + * + * 1. a numeric index into + * [window.frames](https://developer.mozilla.org/en-US/docs/Web/API/Window.frames) + * for the currently selected frame. + * 2. a {@link ./WebElement}, which must reference a FRAME or IFRAME + * element on the current page. + * 3. a locator which may be used to first locate a FRAME or IFRAME on the + * current page before attempting to switch to it. + * + * Upon successful resolution of this condition, the driver will be left + * focused on the new frame. + * + * @param {!(number|./WebElement|By| + * function(!./WebDriver): !./WebElement)} frame + * The frame identifier. + * @return {!Condition} A new condition. + */ + function ableToSwitchToFrame(frame: number | WebElement | By | ((webdriver: WebDriver) => WebElement)): Condition; + + /** + * Creates a condition that waits for an alert to be opened. Upon success, the + * returned promise will be fulfilled with the handle for the opened alert. + * + * @return {!Condition} The new condition. + */ + function alertIsPresent(): Condition; + + /** + * Creates a condition that will wait for the given element to be disabled. + * + * @param {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see WebDriver#isEnabled + */ + function elementIsDisabled(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be enabled. + * + * @param {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see WebDriver#isEnabled + */ + function elementIsEnabled(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be deselected. + * + * @param {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see WebDriver#isSelected + */ + function elementIsNotSelected(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be in the DOM, + * yet not visible to the user. + * + * @param {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see WebDriver#isDisplayed + */ + function elementIsNotVisible(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be selected. + * @param {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see WebDriver#isSelected + */ + function elementIsSelected(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to become visible. + * + * @param {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see WebDriver#isDisplayed + */ + function elementIsVisible(element: WebElement): Condition; + + /** + * Creates a condition that will loop until an element is + * {@link ./WebDriver#findElement found} with the given locator. + * + * @param {!(By|Function)} locator The locator to use. + * @return {!until.Condition.} The new condition. + */ + function elementLocated(locator: By | Function): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link WebDriver#getText visible text} to contain the given + * substring. + * + * @param {!WebElement} element The element to test. + * @param {string} substr The substring to search for. + * @return {!until.Condition.} The new condition. + * @see WebDriver#getText + */ + function elementTextContains(element: WebElement, substr: string): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link WebDriver#getText visible text} to match the given + * {@code text} exactly. + * + * @param {!WebElement} element The element to test. + * @param {string} text The expected text. + * @return {!until.Condition.} The new condition. + * @see WebDriver#getText + */ + function elementTextIs(element: WebElement, text: string): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link WebDriver#getText visible text} to match a regular + * expression. + * + * @param {!WebElement} element The element to test. + * @param {!RegExp} regex The regular expression to test against. + * @return {!until.Condition} The new condition. + * @see WebDriver#getText + */ + function elementTextMatches(element: WebElement, regex: RegExp): Condition; + + /** + * Creates a condition that will loop until at least one element is + * {@link WebDriver#findElement found} with the given locator. + * + * @param {!(Locator|By.Hash|Function)} locator The locator + * to use. + * @return {!until.Condition.>} The new + * condition. + */ + function elementsLocated(locator: By | Function): Condition; + + /** + * Creates a condition that will wait for the given element to become stale. An + * element is considered stale once it is removed from the DOM, or a new page + * has loaded. + * + * @param {!WebElement} element The element that should become stale. + * @return {!until.Condition} The new condition. + */ + function stalenessOf(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the current page's title to contain + * the given substring. + * + * @param {string} substr The substring that should be present in the page + * title. + * @return {!until.Condition.} The new condition. + */ + function titleContains(substr: string): Condition; + + /** + * Creates a condition that will wait for the current page's title to match the + * given value. + * + * @param {string} title The expected page title. + * @return {!until.Condition} The new condition. + */ + function titleIs(title: string): Condition; + + /** + * Creates a condition that will wait for the current page's title to match the + * given regular expression. + * + * @param {!RegExp} regex The regular expression to test against. + * @return {!until.Condition.} The new condition. + */ + function titleMatches(regex: RegExp): Condition; +} + +interface ILocation { + x: number; + y: number; +} + +interface ISize { + width: number; + height: number; +} + +interface IButton { + LEFT: string; + MIDDLE: string; + RIGHT: string; +} + +/** + * Representations of pressable keys that aren't text. These are stored in + * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to + * http://www.google.com.au/search?&q=unicode+pua&btnG=Search + * + * @enum {string} + */ +export var Button: IButton; + +interface IKey { + NULL: string; + CANCEL: string; // ^break + HELP: string; + BACK_SPACE: string; + TAB: string; + CLEAR: string; + RETURN: string; + ENTER: string; + SHIFT: string; + CONTROL: string; + ALT: string; + PAUSE: string; + ESCAPE: string; + SPACE: string; + PAGE_UP: string; + PAGE_DOWN: string; + END: string; + HOME: string; + ARROW_LEFT: string; + LEFT: string; + ARROW_UP: string; + UP: string; + ARROW_RIGHT: string; + RIGHT: string; + ARROW_DOWN: string; + DOWN: string; + INSERT: string; + DELETE: string; + SEMICOLON: string; + EQUALS: string; + + NUMPAD0: string; // number pad keys + NUMPAD1: string; + NUMPAD2: string; + NUMPAD3: string; + NUMPAD4: string; + NUMPAD5: string; + NUMPAD6: string; + NUMPAD7: string; + NUMPAD8: string; + NUMPAD9: string; + MULTIPLY: string; + ADD: string; + SEPARATOR: string; + SUBTRACT: string; + DECIMAL: string; + DIVIDE: string; + + F1: string; // function keys + F2: string; + F3: string; + F4: string; + F5: string; + F6: string; + F7: string; + F8: string; + F9: string; + F10: string; + F11: string; + F12: string; + + COMMAND: string; // Apple command key + META: string; // alias for Windows key + + /** + * Simulate pressing many keys at once in a 'chord'. Takes a sequence of + * keys or strings, appends each of the values to a string, + * and adds the chord termination key ({@link Key.NULL}) and returns + * the resulting string. + * + * Note: when the low-level webdriver key handlers see Keys.NULL, active + * modifier keys (CTRL/ALT/SHIFT/etc) release via a keyup event. + * + * @param {...string} var_args The key sequence to concatenate. + * @return {string} The null-terminated key sequence. + */ + chord: (...var_args: Array) => string; +} + +/** + * Representations of pressable keys that aren't text. These are stored in + * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to + * http://www.google.com.au/search?&q=unicode+pua&btnG=Search + * + * @enum {string} + */ +export var Key: IKey; + +/** + * Class for defining sequences of complex user interactions. Each sequence + * will not be executed until {@link #perform} is called. + * + * Example: + * + * new ActionSequence(driver). + * keyDown(Key.SHIFT). + * click(element1). + * click(element2). + * dragAndDrop(element3, element4). + * keyUp(Key.SHIFT). + * perform(); + * + */ +export class ActionSequence { + + // region Constructors + + /** + * @param {!WebDriver} driver The driver instance to use. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Executes this action sequence. + * @return {!promise.Promise} A promise that will be resolved once + * this sequence has completed. + */ + perform(): promise.Promise; + + /** + * Moves the mouse. The location to move to may be specified in terms of the + * mouse's current location, an offset relative to the top-left corner of an + * element, or an element (in which case the middle of the element is used). + * + * @param {(!./WebElement|{x: number, y: number})} location The + * location to drag to, as either another WebElement or an offset in + * pixels. + * @param {{x: number, y: number}=} opt_offset If the target {@code location} + * is defined as a {@link ./WebElement}, this parameter defines + * an offset within that element. The offset should be specified in pixels + * relative to the top-left corner of the element's bounding box. If + * omitted, the element's center will be used as the target offset. + * @return {!ActionSequence} A self reference. + */ + mouseMove(location: WebElement | ILocation, opt_offset?: ILocation): ActionSequence; + + /** + * Presses a mouse button. The mouse button will not be released until + * {@link #mouseUp} is called, regardless of whether that call is made in this + * sequence or another. The behavior for out-of-order events (e.g. mouseDown, + * click) is undefined. + * + * If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + * + * sequence.mouseMove(element).mouseDown() + * + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./WebElement|input.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link input.Button.LEFT} if neither an element nor + * button is specified. + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!ActionSequence} A self reference. + */ + mouseDown(opt_elementOrButton?: WebElement | string, opt_button?: string): ActionSequence; + + /** + * Releases a mouse button. Behavior is undefined for calling this function + * without a previous call to {@link #mouseDown}. + * + * If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + * + * sequence.mouseMove(element).mouseUp() + * + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./WebElement|input.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link input.Button.LEFT} if neither an element nor + * button is specified. + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!ActionSequence} A self reference. + */ + mouseUp(opt_elementOrButton?: WebElement | string, opt_button?: string): ActionSequence; + + /** + * Convenience function for performing a 'drag and drop' manuever. The target + * element may be moved to the location of another element, or by an offset (in + * pixels). + * + * @param {!./WebElement} element The element to drag. + * @param {(!./WebElement|{x: number, y: number})} location The + * location to drag to, either as another WebElement or an offset in + * pixels. + * @return {!ActionSequence} A self reference. + */ + dragAndDrop(element: WebElement, location: WebElement | ILocation): ActionSequence; + + /** + * Clicks a mouse button. + * + * If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + * + * sequence.mouseMove(element).click() + * + * @param {(./WebElement|input.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link input.Button.LEFT} if neither an element nor + * button is specified. + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!ActionSequence} A self reference. + */ + click(opt_elementOrButton?: WebElement | string, opt_button?: string): ActionSequence; + + /** + * Double-clicks a mouse button. + * + * If an element is provided, the mouse will first be moved to the center of + * that element. This is equivalent to: + * + * sequence.mouseMove(element).doubleClick() + * + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./WebElement|input.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link input.Button.LEFT} if neither an element nor + * button is specified. + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!ActionSequence} A self reference. + */ + doubleClick(opt_elementOrButton?: WebElement | string, opt_button?: string): ActionSequence; + + /** + * Performs a modifier key press. The modifier key is not released + * until {@link #keyUp} or {@link #sendKeys} is called. The key press will be + * targetted at the currently focused element. + * @param {!Key} key The modifier key to push. Must be one of + * {ALT, CONTROL, SHIFT, COMMAND, META}. + * @return {!ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + keyDown(key: string): ActionSequence; + + /** + * Performs a modifier key release. The release is targetted at the currently + * focused element. + * @param {!Key} key The modifier key to release. Must be one of + * {ALT, CONTROL, SHIFT, COMMAND, META}. + * @return {!ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + keyUp(key: string): ActionSequence; + + /** + * Simulates typing multiple keys. Each modifier key encountered in the + * sequence will not be released until it is encountered again. All key events + * will be targeted at the currently focused element. + * + * @param {...(string|!input.Key|!Array<(string|!input.Key)>)} var_args + * The keys to type. + * @return {!ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + sendKeys(...var_args: Array>): ActionSequence; + + // endregion +} + + +/** + * Class for defining sequences of user touch interactions. Each sequence + * will not be executed until {@link #perform} is called. + * + * Example: + * + * new TouchSequence(driver). + * tapAndHold({x: 0, y: 0}). + * move({x: 3, y: 4}). + * release({x: 10, y: 10}). + * perform(); + */ +export class TouchSequence { + /* + * @param {!WebDriver} driver The driver instance to use. + * @constructor + */ + constructor(driver: WebDriver); + + + /** + * Executes this action sequence. + * @return {!promise.Promise} A promise that will be resolved once + * this sequence has completed. + */ + perform(): promise.Promise; + + + /** + * Taps an element. + * + * @param {!WebElement} elem The element to tap. + * @return {!TouchSequence} A self reference. + */ + tap(elem: WebElement): TouchSequence; + + + /** + * Double taps an element. + * + * @param {!WebElement} elem The element to double tap. + * @return {!TouchSequence} A self reference. + */ + doubleTap(elem: WebElement): TouchSequence; + + + /** + * Long press on an element. + * + * @param {!WebElement} elem The element to long press. + * @return {!TouchSequence} A self reference. + */ + longPress(elem: WebElement): TouchSequence; + + + /** + * Touch down at the given location. + * + * @param {{ x: number, y: number }} location The location to touch down at. + * @return {!TouchSequence} A self reference. + */ + tapAndHold(location: ILocation): TouchSequence; + + + /** + * Move a held {@linkplain #tapAndHold touch} to the specified location. + * + * @param {{x: number, y: number}} location The location to move to. + * @return {!TouchSequence} A self reference. + */ + move(location: ILocation): TouchSequence; + + + /** + * Release a held {@linkplain #tapAndHold touch} at the specified location. + * + * @param {{x: number, y: number}} location The location to release at. + * @return {!TouchSequence} A self reference. + */ + release(location: ILocation): TouchSequence; + + + /** + * Scrolls the touch screen by the given offset. + * + * @param {{x: number, y: number}} offset The offset to scroll to. + * @return {!TouchSequence} A self reference. + */ + scroll(offset: IOffset): TouchSequence; + + /** + * Scrolls the touch screen, starting on `elem` and moving by the specified + * offset. + * + * @param {!WebElement} elem The element where scroll starts. + * @param {{x: number, y: number}} offset The offset to scroll to. + * @return {!TouchSequence} A self reference. + */ + scrollFromElement(elem: WebElement, offset: IOffset): TouchSequence; + + /** + * Flick, starting anywhere on the screen, at speed xspeed and yspeed. + * + * @param {{xspeed: number, yspeed: number}} speed The speed to flick in each + direction, in pixels per second. + * @return {!TouchSequence} A self reference. + */ + flick(speed: ISpeed): TouchSequence; + + /** + * Flick starting at elem and moving by x and y at specified speed. + * + * @param {!WebElement} elem The element where flick starts. + * @param {{x: number, y: number}} offset The offset to flick to. + * @param {number} speed The speed to flick at in pixels per second. + * @return {!TouchSequence} A self reference. + */ + flickElement(elem: WebElement, offset: IOffset, speed: number): TouchSequence; +} + +interface IOffset { + x: number; + y: number; +} + +interface ISpeed { + xspeed: number; + yspeed: number; +} + +/** + * Represents a modal dialog such as {@code alert}, {@code confirm}, or + * {@code prompt}. Provides functions to retrieve the message displayed with + * the alert, accept or dismiss the alert, and set the response text (in the + * case of {@code prompt}). + */ +export class Alert { + /** + * @param {!WebDriver} driver The driver controlling the browser this alert + * is attached to. + * @param {string} text The message text displayed with this alert. + */ + constructor(driver: WebDriver, text: string); + + // region Methods + + /** + * Retrieves the message text displayed with this alert. For instance, if the + * alert were opened with alert('hello'), then this would return 'hello'. + * @return {!promise.Promise} A promise that will be resolved to the + * text displayed with this alert. + */ + getText(): promise.Promise; + + /** + * Sets the username and password in an alert prompting for credentials (such + * as a Basic HTTP Auth prompt). This method will implicitly + * {@linkplain #accept() submit} the dialog. + * + * @param {string} username The username to send. + * @param {string} password The password to send. + * @return {!promise.Promise} A promise that will be resolved when this + * command has completed. + */ + authenticateAs(username: string, password: string): promise.Promise; + + /** + * Accepts this alert. + * @return {!promise.Promise} A promise that will be resolved when + * this command has completed. + */ + accept(): promise.Promise; + + /** + * Dismisses this alert. + * @return {!promise.Promise} A promise that will be resolved when + * this command has completed. + */ + dismiss(): promise.Promise; + + /** + * Sets the response text on this alert. This command will return an error if + * the underlying alert does not support response text (e.g. window.alert and + * window.confirm). + * @param {string} text The text to set. + * @return {!promise.Promise} A promise that will be resolved when + * this command has completed. + */ + sendKeys(text: string): promise.Promise; + + // endregion + +} + +/** + * AlertPromise is a promise that will be fulfilled with an Alert. This promise + * serves as a forward proxy on an Alert, allowing calls to be scheduled + * directly on this instance before the underlying Alert has been fulfilled. In + * other words, the following two statements are equivalent: + * + * driver.switchTo().alert().dismiss(); + * driver.switchTo().alert().then(function(alert) { + * return alert.dismiss(); + * }); + * + * @implements {promise.Thenable.} + * @final + */ +export class AlertPromise extends Alert implements promise.IThenable { + /** + * @param {!WebDriver} driver The driver controlling the browser this + * alert is attached to. + * @param {!promise.Thenable} alert A thenable + * that will be fulfilled with the promised alert. + */ + constructor(driver: WebDriver, alert: promise.Promise); + + // region Methods + + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. + * @param {*} reason The reason this promise is being cancelled. If not an + * {@code Error}, one will be created using the value's string + * representation. + */ + cancel(opt_reason?: string | Error): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. This function most + * overridden by subtypes. + * + * @param opt_callback The function to call if this promise is + * successfully resolved. The function should expect a single argument: the + * promise's resolved value. + * @param opt_errback The function to call if this promise is + * rejected. The function should expect a single argument: the rejection + * reason. + * @return A new promise which will be resolved + * with the result of the invoked callback. + */ + then(opt_callback?: Function, opt_errback?: Function): promise.Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *

              
              +   *   // Synchronous API:
              +   *   try {
              +   *     doSynchronousWork();
              +   *   } catch (ex) {
              +   *     console.error(ex);
              +   *   }
              +   *
              +   *   // Asynchronous promise API:
              +   *   doAsynchronousWork().thenCatch(function(ex) {
              +   *     console.error(ex);
              +   *   });
              +   * 
              + * + * @param {function(*): (R|promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): promise.Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): promise.Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *
              
              +   *   // Synchronous API:
              +   *   try {
              +   *     doSynchronousWork();
              +   *   } finally {
              +   *     cleanUp();
              +   *   }
              +   *
              +   *   // Asynchronous promise API:
              +   *   doAsynchronousWork().thenFinally(cleanUp);
              +   * 
              + * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *
              
              +   *   try {
              +   *     throw Error('one');
              +   *   } finally {
              +   *     throw Error('two');  // Hides Error: one
              +   *   }
              +   *
              +   *   promise.rejected(Error('one'))
              +   *       .thenFinally(function() {
              +   *         throw Error('two');  // Hides Error: one
              +   *       });
              +   * 
              + * + * + * @param {function(): (R|promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: Function): promise.Promise; +} + +/** @deprecated Use {@link error.UnexpectedAlertOpenError} instead. */ +export class UnhandledAlertError extends error.UnexpectedAlertOpenError { +} + +/** + * Recognized browser names. + * @enum {string} + */ +interface IBrowser { + ANDROID: string; + CHROME: string; + EDGE: string; + FIREFOX: string; + IE: string; + INTERNET_EXPLORER: string; + IPAD: string; + IPHONE: string; + OPERA: string; + PHANTOM_JS: string; + SAFARI: string; + HTMLUNIT: string; +} + +export var Browser: IBrowser; + +interface ProxyConfig { + proxyType: string; + proxyAutoconfigUrl?: string; + ftpProxy?: string; + httpProxy?: string; + sslProxy?: string; + noProxy?: string; +} + +/** + * Creates new {@link WebDriver WebDriver} instances. The environment + * variables listed below may be used to override a builder's configuration, + * allowing quick runtime changes. + * + * - {@code SELENIUM_BROWSER}: defines the target browser in the form + * {@code browser[:version][:platform]}. + * + * - {@code SELENIUM_REMOTE_URL}: defines the remote URL for all builder + * instances. This environment variable should be set to a fully qualified + * URL for a WebDriver server (e.g. http://localhost:4444/wd/hub). This + * option always takes precedence over {@code SELENIUM_SERVER_JAR}. + * + * - {@code SELENIUM_SERVER_JAR}: defines the path to the + * + * standalone Selenium server jar to use. The server will be started the + * first time a WebDriver instance and be killed when the process exits. + * + * Suppose you had mytest.js that created WebDriver with + * + * var driver = new Builder() + * .forBrowser('chrome') + * .build(); + * + * This test could be made to use Firefox on the local machine by running with + * `SELENIUM_BROWSER=firefox node mytest.js`. Rather than change the code to + * target Google Chrome on a remote machine, you can simply set the + * `SELENIUM_BROWSER` and `SELENIUM_REMOTE_URL` environment variables: + * + * SELENIUM_BROWSER=chrome:36:LINUX \ + * SELENIUM_REMOTE_URL=http://www.example.com:4444/wd/hub \ + * node mytest.js + * + * You could also use a local copy of the standalone Selenium server: + * + * SELENIUM_BROWSER=chrome:36:LINUX \ + * SELENIUM_SERVER_JAR=/path/to/selenium-server-standalone.jar \ + * node mytest.js + */ +export class Builder { + + // region Constructors + + /** + * @constructor + */ + constructor(); + + // endregion + + // region Methods + + /** + * Configures this builder to ignore any environment variable overrides and to + * only use the configuration specified through this instance's API. + * + * @return {!Builder} A self reference. + */ + disableEnvironmentOverrides(): Builder; + + /** + * Creates a new WebDriver client based on this builder's current + * configuration. + * + * While this method will immediately return a new WebDriver instance, any + * commands issued against it will be deferred until the associated browser + * has been fully initialized. Users may call {@link #buildAsync()} to obtain + * a promise that will not be fulfilled until the browser has been created + * (the difference is purely in style). + * + * @return {!WebDriver} A new WebDriver instance. + * @throws {Error} If the current configuration is invalid. + * @see #buildAsync() + */ + build(): WebDriver; + + /** + * Creates a new WebDriver client based on this builder's current + * configuration. This method returns a promise that will not be fulfilled + * until the new browser session has been fully initialized. + * + * __Note:__ this method is purely a convenience wrapper around + * {@link #build()}. + * + * @return {!promise.Promise} A promise that will be + * fulfilled with the newly created WebDriver instance once the browser + * has been fully initialized. + * @see #build() + */ + buildAsync(): promise.Promise; + + /** + * Configures the target browser for clients created by this instance. + * Any calls to {@link #withCapabilities} after this function will + * overwrite these settings. + * + *

              You may also define the target browser using the {@code SELENIUM_BROWSER} + * environment variable. If set, this environment variable should be of the + * form {@code browser[:[version][:platform]]}. + * + * @param {(string|Browser)} name The name of the target browser; + * common defaults are available on the {@link Browser} enum. + * @param {string=} opt_version A desired version; may be omitted if any + * version should be used. + * @param {string=} opt_platform The desired platform; may be omitted if any + * version may be used. + * @return {!Builder} A self reference. + */ + forBrowser(name: string, opt_version?: string, opt_platform?: string): Builder; + + /** + * Returns the base set of capabilities this instance is currently configured + * to use. + * @return {!Capabilities} The current capabilities for this builder. + */ + getCapabilities(): Capabilities; + + /** + * @return {string} The URL of the WebDriver server this instance is configured + * to use. + */ + getServerUrl(): string; + + /** + * @return {?string} The URL of the proxy server to use for the WebDriver's + * HTTP connections, or `null` if not set. + */ + getWebDriverProxy(): string; + + /** + * Sets the default action to take with an unexpected alert before returning + * an error. + * @param {string} beahvior The desired behavior; should be 'accept', 'dismiss', + * or 'ignore'. Defaults to 'dismiss'. + * @return {!Builder} A self reference. + */ + setAlertBehavior(behavior: string): Builder; + + /** + * Sets Chrome-specific options for drivers created by this builder. Any + * logging or proxy settings defined on the given options will take precedence + * over those set through {@link #setLoggingPrefs} and {@link #setProxy}, + * respectively. + * + * @param {!chrome.Options} options The ChromeDriver options to use. + * @return {!Builder} A self reference. + */ + setChromeOptions(options: chrome.Options): Builder; + + /** + * Sets the control flow that created drivers should execute actions in. If + * the flow is never set, or is set to {@code null}, it will use the active + * flow at the time {@link #build()} is called. + * @param {promise.ControlFlow} flow The control flow to use, or + * {@code null} to + * @return {!Builder} A self reference. + */ + setControlFlow(flow: promise.ControlFlow): Builder; + + /** + * Set {@linkplain edge.Options options} specific to Microsoft's Edge browser + * for drivers created by this builder. Any proxy settings defined on the + * given options will take precedence over those set through + * {@link #setProxy}. + * + * @param {!edge.Options} options The MicrosoftEdgeDriver options to use. + * @return {!Builder} A self reference. + */ + setEdgeOptions(options: edge.Options): Builder; + + /** + * Sets whether native events should be used. + * @param {boolean} enabled Whether to enable native events. + * @return {!Builder} A self reference. + */ + setEnableNativeEvents(enabled: boolean): Builder; + + /** + * Sets Firefox-specific options for drivers created by this builder. Any + * logging or proxy settings defined on the given options will take precedence + * over those set through {@link #setLoggingPrefs} and {@link #setProxy}, + * respectively. + * + * @param {!firefox.Options} options The FirefoxDriver options to use. + * @return {!Builder} A self reference. + */ + setFirefoxOptions(options: firefox.Options): Builder; + + /** + * Set Internet Explorer specific {@linkplain ie.Options options} for drivers + * created by this builder. Any proxy settings defined on the given options + * will take precedence over those set through {@link #setProxy}. + * + * @param {!ie.Options} options The IEDriver options to use. + * @return {!Builder} A self reference. + */ + setIeOptions(options: ie.Options): Builder; + + /** + * Sets the logging preferences for the created session. Preferences may be + * changed by repeated calls, or by calling {@link #withCapabilities}. + * @param {!(logging.Preferences|Object.)} prefs The + * desired logging preferences. + * @return {!Builder} A self reference. + */ + setLoggingPrefs(prefs: logging.Preferences | Object): Builder; + + /** + * Sets Opera specific {@linkplain opera.Options options} for drivers created + * by this builder. Any logging or proxy settings defined on the given options + * will take precedence over those set through {@link #setLoggingPrefs} and + * {@link #setProxy}, respectively. + * + * @param {!opera.Options} options The OperaDriver options to use. + * @return {!Builder} A self reference. + */ + setOperaOptions(options: opera.Options): Builder; + + /** + * Sets the proxy configuration to use for WebDriver clients created by this + * builder. Any calls to {@link #withCapabilities} after this function will + * overwrite these settings. + * @param {!capabilities.ProxyConfig} config The configuration to use. + * @return {!Builder} A self reference. + */ + setProxy(config: ProxyConfig): Builder; + + /** + * Sets Safari specific {@linkplain safari.Options options} for drivers + * created by this builder. Any logging settings defined on the given options + * will take precedence over those set through {@link #setLoggingPrefs}. + * + * @param {!safari.Options} options The Safari options to use. + * @return {!Builder} A self reference. + */ + setSafari(options: safari.Options): Builder; + + /** + * Sets how elements should be scrolled into view for interaction. + * @param {number} behavior The desired scroll behavior: either 0 to align with + * the top of the viewport or 1 to align with the bottom. + * @return {!Builder} A self reference. + */ + setScrollBehavior(behavior: number): Builder; + + /** + * Sets the URL of a remote WebDriver server to use. Once a remote URL has been + * specified, the builder direct all new clients to that server. If this method + * is never called, the Builder will attempt to create all clients locally. + * + *

              As an alternative to this method, you may also set the + * {@code SELENIUM_REMOTE_URL} environment variable. + * + * @param {string} url The URL of a remote server to use. + * @return {!Builder} A self reference. + */ + usingServer(url: string): Builder; + + /** + * Sets the URL of the proxy to use for the WebDriver's HTTP connections. + * If this method is never called, the Builder will create a connection + * without a proxy. + * + * @param {string} proxy The URL of a proxy to use. + * @return {!Builder} A self reference. + */ + usingWebDriverProxy(proxy: string): Builder; + + /** + * Sets the desired capabilities when requesting a new session. This will + * overwrite any previously set capabilities. + * @param {!(Object|Capabilities)} capabilities The desired + * capabilities for a new session. + * @return {!Builder} A self reference. + */ + withCapabilities(capabilities: Object | Capabilities): Builder; + + // endregion +} + +/** + * Describes a mechanism for locating an element on the page. + * @final + */ +export class By { + + /** + * @param {string} using the name of the location strategy to use. + * @param {string} value the value to search for. + */ + constructor(using: string, value: string); + + /** + * Locates elements that have a specific class name. + * + * @param {string} name The class name to search for. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes + * @see http://www.w3.org/TR/CSS2/selector.html#class-html + */ + static className(name: string): By; + + /** + * Locates elements using a CSS selector. + * + * @param {string} selector The CSS selector to use. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/CSS2/selector.html + */ + static css(selector: string): By; + + /** + * Locates eleemnts by the ID attribute. This locator uses the CSS selector + * `*[id='$ID']`, _not_ `document.getElementById`. + * + * @param {string} id The ID to search for. + * @return {!By} The new locator. + */ + static id(id: string): By; + + /** + * Locates link elements whose + * {@linkplain WebElement#getText visible text} matches the given + * string. + * + * @param {string} text The link text to search for. + * @return {!By} The new locator. + */ + static linkText(text: string): By; + + /** + * Locates an elements by evaluating a + * {@linkplain WebDriver#executeScript JavaScript expression}. + * The result of this expression must be an element or list of elements. + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {function(!./WebDriver): !./promise.Promise} + * A new JavaScript-based locator function. + */ + static js(script: string | Function, ...var_args: any[]): (webdriver: WebDriver) => promise.Promise; + + /** + * Locates elements whose `name` attribute has the given value. + * + * @param {string} name The name attribute to search for. + * @return {!By} The new locator. + */ + static name(name: string): By; + + /** + * Locates link elements whose + * {@linkplain WebElement#getText visible text} contains the given + * substring. + * + * @param {string} text The substring to check for in a link's visible text. + * @return {!By} The new locator. + */ + static partialLinkText(text: string): By; + + /** + * Locates elements with a given tag name. + * + * @param {string} name The tag name to search for. + * @return {!By} The new locator. + * @deprecated Use {@link By.css() By.css(tagName)} instead. + */ + static tagName(name: string): By; + + /** + * Locates elements matching a XPath selector. Care should be taken when + * using an XPath selector with a {@link WebElement} as WebDriver + * will respect the context in the specified in the selector. For example, + * given the selector `//div`, WebDriver will search from the document root + * regardless of whether the locator was used with a WebElement. + * + * @param {string} xpath The XPath selector to use. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/xpath/ + */ + static xpath(xpath: string): By; + + /** @override */ + toString(): string; +} + +/** + * Short-hand expressions for the primary element locator strategies. + * For example the following two statements are equivalent: + * + * var e1 = driver.findElement(By.id('foo')); + * var e2 = driver.findElement({id: 'foo'}); + * + * Care should be taken when using JavaScript minifiers (such as the + * Closure compiler), as locator hashes will always be parsed using + * the un-obfuscated properties listed. + * + * @typedef {( + * {className: string}| + * {css: string}| + * {id: string}| + * {js: string}| + * {linkText: string}| + * {name: string}| + * {partialLinkText: string}| + * {tagName: string}| + * {xpath: string})} + */ +type ByHash = { className: string } | + { css: string } | + { id: string } | + { js: string } | + { linkText: string } | + { name: string } | + { partialLinkText: string } | + { tagName: string } | + { xpath: string }; + +/** + * Common webdriver capability keys. + * @enum {string} + */ +interface ICapability { + + /** + * Indicates whether a driver should accept all SSL certs by default. This + * capability only applies when requesting a new session. To query whether + * a driver can handle insecure SSL certs, see + * {@link Capability.SECURE_SSL}. + */ + ACCEPT_SSL_CERTS: string; + + + /** + * The browser name. Common browser names are defined in the + * {@link Browser} enum. + */ + BROWSER_NAME: string; + + /** + * Defines how elements should be scrolled into the viewport for interaction. + * This capability will be set to zero (0) if elements are aligned with the + * top of the viewport, or one (1) if aligned with the bottom. The default + * behavior is to align with the top of the viewport. + */ + ELEMENT_SCROLL_BEHAVIOR: string; + + /** + * Whether the driver is capable of handling modal alerts (e.g. alert, + * confirm, prompt). To define how a driver should handle alerts, + * use {@link Capability.UNEXPECTED_ALERT_BEHAVIOR}. + */ + HANDLES_ALERTS: string; + + /** + * Key for the logging driver logging preferences. + */ + LOGGING_PREFS: string; + + /** + * Whether this session generates native events when simulating user input. + */ + NATIVE_EVENTS: string; + + /** + * Describes the platform the browser is running on. Will be one of + * ANDROID, IOS, LINUX, MAC, UNIX, or WINDOWS. When requesting a + * session, ANY may be used to indicate no platform preference (this is + * semantically equivalent to omitting the platform capability). + */ + PLATFORM: string; + + /** + * Describes the proxy configuration to use for a new WebDriver session. + */ + PROXY: string; + + /** Whether the driver supports changing the brower's orientation. */ + ROTATABLE: string; + + /** + * Whether a driver is only capable of handling secure SSL certs. To request + * that a driver accept insecure SSL certs by default, use + * {@link Capability.ACCEPT_SSL_CERTS}. + */ + SECURE_SSL: string; + + /** Whether the driver supports manipulating the app cache. */ + SUPPORTS_APPLICATION_CACHE: string; + + /** Whether the driver supports locating elements with CSS selectors. */ + SUPPORTS_CSS_SELECTORS: string; + + /** Whether the browser supports JavaScript. */ + SUPPORTS_JAVASCRIPT: string; + + /** Whether the driver supports controlling the browser's location info. */ + SUPPORTS_LOCATION_CONTEXT: string; + + /** Whether the driver supports taking screenshots. */ + TAKES_SCREENSHOT: string; + + /** + * Defines how the driver should handle unexpected alerts. The value should + * be one of 'accept', 'dismiss', or 'ignore. + */ + UNEXPECTED_ALERT_BEHAVIOR: string; + + /** Defines the browser version. */ + VERSION: string; +} + +export var Capability: ICapability; + +export class Capabilities { + // region Constructors + + /** + * @param {(Capabilities|Object)=} opt_other Another set of + * capabilities to merge into this instance. + * @constructor + */ + constructor(opt_other?: Capabilities | Object); + + // endregion + + // region Methods + + /** @return {!Object} The JSON representation of this instance. */ + toJSON(): any; + + /** + * Merges another set of capabilities into this instance. Any duplicates in + * the provided set will override those already set on this instance. + * @param {!(Capabilities|Object)} other The capabilities to + * merge into this instance. + * @return {!Capabilities} A self reference. + */ + merge(other: Capabilities | Object): Capabilities; + + /** + * @param {string} key The capability to set. + * @param {*} value The capability value. Capability values must be JSON + * serializable. Pass {@code null} to unset the capability. + * @return {!Capabilities} A self reference. + */ + set(key: string, value: any): Capabilities; + + /** + * Sets the logging preferences. Preferences may be specified as a + * {@link logging.Preferences} instance, or a as a map of log-type to + * log-level. + * @param {!(logging.Preferences|Object.)} prefs The + * logging preferences. + * @return {!Capabilities} A self reference. + */ + setLoggingPrefs(prefs: logging.Preferences | Object): Capabilities; + + /** + * Sets the proxy configuration for this instance. + * @param {ProxyConfig} proxy The desired proxy configuration. + * @return {!Capabilities} A self reference. + */ + setProxy(proxy: ProxyConfig): Capabilities; + + + /** + * Sets whether native events should be used. + * @param {boolean} enabled Whether to enable native events. + * @return {!Capabilities} A self reference. + */ + setEnableNativeEvents(enabled: boolean): Capabilities; + + + /** + * Sets how elements should be scrolled into view for interaction. + * @param {number} behavior The desired scroll behavior: either 0 to align with + * the top of the viewport or 1 to align with the bottom. + * @return {!Capabilities} A self reference. + */ + setScrollBehavior(behavior: number): Capabilities; + + /** + * Sets the default action to take with an unexpected alert before returning + * an error. + * @param {string} behavior The desired behavior; should be 'accept', 'dismiss', + * or 'ignore'. Defaults to 'dismiss'. + * @return {!Capabilities} A self reference. + */ + setAlertBehavior(behavior: string): Capabilities; + + /** + * @param {string} key The capability to return. + * @return {*} The capability with the given key, or {@code null} if it has + * not been set. + */ + get(key: string): any; + + /** + * @param {string} key The capability to check. + * @return {boolean} Whether the specified capability is set. + */ + has(key: string): boolean; + + // endregion + + // region Static Methods + + /** + * @return {!Capabilities} A basic set of capabilities for Android. + */ + static android(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for Chrome. + */ + static chrome(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for Microsoft Edge. + */ + static edge(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for Firefox. + */ + static firefox(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for + * Internet Explorer. + */ + static ie(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for iPad. + */ + static ipad(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for iPhone. + */ + static iphone(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for Opera. + */ + static opera(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for + * PhantomJS. + */ + static phantomjs(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for Safari. + */ + static safari(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for HTMLUnit. + */ + static htmlunit(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for HTMLUnit + * with enabled Javascript. + */ + static htmlunitwithjs(): Capabilities; + + // endregion +} + +/** + * An enumeration of valid command string. + */ +interface ICommandName { + GET_SERVER_STATUS: string; + + NEW_SESSION: string; + GET_SESSIONS: string; + DESCRIBE_SESSION: string; + + CLOSE: string; + QUIT: string; + + GET_CURRENT_URL: string; + GET: string; + GO_BACK: string; + GO_FORWARD: string; + REFRESH: string; + + ADD_COOKIE: string; + GET_COOKIE: string; + GET_ALL_COOKIES: string; + DELETE_COOKIE: string; + DELETE_ALL_COOKIES: string; + + GET_ACTIVE_ELEMENT: string; + FIND_ELEMENT: string; + FIND_ELEMENTS: string; + FIND_CHILD_ELEMENT: string; + FIND_CHILD_ELEMENTS: string; + + CLEAR_ELEMENT: string; + CLICK_ELEMENT: string; + SEND_KEYS_TO_ELEMENT: string; + SUBMIT_ELEMENT: string; + + GET_CURRENT_WINDOW_HANDLE: string; + GET_WINDOW_HANDLES: string; + GET_WINDOW_POSITION: string; + SET_WINDOW_POSITION: string; + GET_WINDOW_SIZE: string; + SET_WINDOW_SIZE: string; + MAXIMIZE_WINDOW: string; + + SWITCH_TO_WINDOW: string; + SWITCH_TO_FRAME: string; + GET_PAGE_SOURCE: string; + GET_TITLE: string; + + EXECUTE_SCRIPT: string; + EXECUTE_ASYNC_SCRIPT: string; + + GET_ELEMENT_TEXT: string; + GET_ELEMENT_TAG_NAME: string; + IS_ELEMENT_SELECTED: string; + IS_ELEMENT_ENABLED: string; + IS_ELEMENT_DISPLAYED: string; + GET_ELEMENT_LOCATION: string; + GET_ELEMENT_LOCATION_IN_VIEW: string; + GET_ELEMENT_SIZE: string; + GET_ELEMENT_ATTRIBUTE: string; + GET_ELEMENT_VALUE_OF_CSS_PROPERTY: string; + ELEMENT_EQUALS: string; + + SCREENSHOT: string; + IMPLICITLY_WAIT: string; + SET_SCRIPT_TIMEOUT: string; + SET_TIMEOUT: string; + + ACCEPT_ALERT: string; + DISMISS_ALERT: string; + GET_ALERT_TEXT: string; + SET_ALERT_TEXT: string; + + EXECUTE_SQL: string; + GET_LOCATION: string; + SET_LOCATION: string; + GET_APP_CACHE: string; + GET_APP_CACHE_STATUS: string; + CLEAR_APP_CACHE: string; + IS_BROWSER_ONLINE: string; + SET_BROWSER_ONLINE: string; + + GET_LOCAL_STORAGE_ITEM: string; + GET_LOCAL_STORAGE_KEYS: string; + SET_LOCAL_STORAGE_ITEM: string; + REMOVE_LOCAL_STORAGE_ITEM: string; + CLEAR_LOCAL_STORAGE: string; + GET_LOCAL_STORAGE_SIZE: string; + + GET_SESSION_STORAGE_ITEM: string; + GET_SESSION_STORAGE_KEYS: string; + SET_SESSION_STORAGE_ITEM: string; + REMOVE_SESSION_STORAGE_ITEM: string; + CLEAR_SESSION_STORAGE: string; + GET_SESSION_STORAGE_SIZE: string; + + SET_SCREEN_ORIENTATION: string; + GET_SCREEN_ORIENTATION: string; + + // These belong to the Advanced user interactions - an element is + // optional for these commands. + CLICK: string; + DOUBLE_CLICK: string; + MOUSE_DOWN: string; + MOUSE_UP: string; + MOVE_TO: string; + SEND_KEYS_TO_ACTIVE_ELEMENT: string; + + // These belong to the Advanced Touch API + TOUCH_SINGLE_TAP: string; + TOUCH_DOWN: string; + TOUCH_UP: string; + TOUCH_MOVE: string; + TOUCH_SCROLL: string; + TOUCH_DOUBLE_TAP: string; + TOUCH_LONG_PRESS: string; + TOUCH_FLICK: string; + + GET_AVAILABLE_LOG_TYPES: string; + GET_LOG: string; + GET_SESSION_LOGS: string; + + UPLOAD_FILE: string; +} + +export var CommandName: ICommandName; + +/** + * Describes a command to be executed by the WebDriverJS framework. + * @param {!CommandName} name The name of this command. + * @constructor + */ +export class Command { + // region Constructors + + /** + * @param {!CommandName} name The name of this command. + * @constructor + */ + constructor(name: string); + + // endregion + + // region Methods + + /** + * @return {!CommandName} This command's name. + */ + getName(): string; + + /** + * Sets a parameter to send with this command. + * @param {string} name The parameter name. + * @param {*} value The parameter value. + * @return {!Command} A self reference. + */ + setParameter(name: string, value: any): Command; + + /** + * Sets the parameters for this command. + * @param {!Object.<*>} parameters The command parameters. + * @return {!Command} A self reference. + */ + setParameters(parameters: any): Command; + + /** + * Returns a named command parameter. + * @param {string} key The parameter key to look up. + * @return {*} The parameter value, or undefined if it has not been set. + */ + getParameter(key: string): any; + + /** + * @return {!Object.<*>} The parameters to send with this command. + */ + getParameters(): any; + + // endregion +} + +/** + * Handles the execution of WebDriver {@link Command commands}. + * @interface + */ +export class Executor { + /** + * Executes the given {@code command}. If there is an error executing the + * command, the provided callback will be invoked with the offending error. + * Otherwise, the callback will be invoked with a null Error and non-null + * response object. + * + * @param {!Command} command The command to execute. + * @return {!promise.Promise} A promise that will be fulfilled with + * the command result. + */ + execute(command: Command): promise.Promise +} + +/** + * Wraps a promised {@link Executor}, ensuring no commands are executed until + * the wrapped executor has been fully resolved. + * @implements {Executor} + */ +export class DeferredExecutor { + /** + * @param {!promise.Promise} delegate The promised delegate, which + * may be provided by any promise-like thenable object. + */ + constructor(delegate: promise.Promise); +} + +/** + * Describes an event listener registered on an {@linkplain EventEmitter}. + */ +export class Listener { + /** + * @param {!Function} fn The acutal listener function. + * @param {(Object|undefined)} scope The object in whose scope to invoke the + * listener. + * @param {boolean} oneshot Whether this listener should only be used once. + */ + constructor(fn: Function, scope: Object, oneshot: boolean); +} + +/** + * Object that can emit events for others to listen for. This is used instead + * of Closure's event system because it is much more light weight. The API is + * based on Node's EventEmitters. + */ +export class EventEmitter { + // region Constructors + + /** + * @constructor + */ + constructor(); + + // endregion + + // region Methods + + /** + * Fires an event and calls all listeners. + * @param {string} type The type of event to emit. + * @param {...*} var_args Any arguments to pass to each listener. + */ + emit(type: string, ...var_args: any[]): void; + + /** + * Returns a mutable list of listeners for a specific type of event. + * @param {string} type The type of event to retrieve the listeners for. + * @return {!Set} The registered listeners for the given event + * type. + */ + listeners(type: string): any; + + /** + * Registers a listener. + * @param {string} type The type of event to listen for. + * @param {!Function} fn The function to invoke when the event is fired. + * @param {Object=} opt_self The object in whose scope to invoke the listener. + * @param {boolean=} opt_oneshot Whether the listener should b (e removed after + * the first event is fired. + * @return {!EventEmitter} A self reference. + * @private + */ + addListener(type: string, fn: Function, opt_scope?: any, opt_oneshot?: boolean): EventEmitter; + + + /** + * Registers a one-time listener which will be called only the first time an + * event is emitted, after which it will be removed. + * @param {string} type The type of event to listen for. + * @param {!Function} fn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!EventEmitter} A self reference. + */ + once(type: string, fn: any, opt_scope?: any): EventEmitter; + + /** + * An alias for {@code #addListener()}. + * @param {string} type The type of event to listen for. + * @param {!Function} fn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!EventEmitter} A self reference. + */ + on(type: string, fn: Function, opt_scope?: any): EventEmitter; + + /** + * Removes a previously registered event listener. + * @param {string} type The type of event to unregister. + * @param {!Function} listenerFn The handler function to remove. + * @return {!EventEmitter} A self reference. + */ + removeListener(type: string, listenerFn: Function): EventEmitter; + + /** + * Removes all listeners for a specific type of event. If no event is + * specified, all listeners across all types will be removed. + * @param {string=} opt_type The type of event to remove listeners from. + * @return {!EventEmitter} A self reference. + */ + removeAllListeners(opt_type?: string): EventEmitter; + + // endregion +} + + +/** + * Interface for navigating back and forth in the browser history. + */ +export class Navigation { + // region Constructors + + /** + * Interface for navigating back and forth in the browser history. + * + * This class should never be instantiated directly. Insead, obtain an instance + * with + * + * navigate() + * + * @see WebDriver#navigate() + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Schedules a command to navigate to a new URL. + * @param {string} url The URL to navigate to. + * @return {!promise.Promise.} A promise that will be resolved + * when the URL has been loaded. + */ + to(url: string): promise.Promise; + + /** + * Schedules a command to move backwards in the browser history. + * @return {!promise.Promise.} A promise that will be resolved + * when the navigation event has completed. + */ + back(): promise.Promise; + + /** + * Schedules a command to move forwards in the browser history. + * @return {!promise.Promise.} A promise that will be resolved + * when the navigation event has completed. + */ + forward(): promise.Promise; + + /** + * Schedules a command to refresh the current page. + * @return {!promise.Promise.} A promise that will be resolved + * when the navigation event has completed. + */ + refresh(): promise.Promise; + + // endregion +} + +interface IWebDriverOptionsCookie { + name: string; + value: string; + path?: string; + domain?: string; + secure?: boolean; + expiry?: number; +} + +/** + * Provides methods for managing browser and driver state. + */ +export class Options { + // region Constructors + + /** + * @param {!WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Schedules a command to add a cookie. + * @param {string} name The cookie name. + * @param {string} value The cookie value. + * @param {string=} opt_path The cookie path. + * @param {string=} opt_domain The cookie domain. + * @param {boolean=} opt_isSecure Whether the cookie is secure. + * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified + * as a number, should be in milliseconds since midnight, + * January 1, 1970 UTC. + * @return {!promise.Promise} A promise that will be resolved + * when the cookie has been added to the page. + */ + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number | Date): promise.Promise; + + /** + * Schedules a command to delete all cookies visible to the current page. + * @return {!promise.Promise} A promise that will be resolved when all + * cookies have been deleted. + */ + deleteAllCookies(): promise.Promise; + + /** + * Schedules a command to delete the cookie with the given name. This command is + * a no-op if there is no cookie with the given name visible to the current + * page. + * @param {string} name The name of the cookie to delete. + * @return {!promise.Promise} A promise that will be resolved when the + * cookie has been deleted. + */ + deleteCookie(name: string): promise.Promise; + + /** + * Schedules a command to retrieve all cookies visible to the current page. + * Each cookie will be returned as a JSON object as described by the WebDriver + * wire protocol. + * @return {!promise.Promise} A promise that will be resolved with the + * cookies visible to the current page. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object + */ + getCookies(): promise.Promise; + + /** + * Schedules a command to retrieve the cookie with the given name. Returns null + * if there is no such cookie. The cookie will be returned as a JSON object as + * described by the WebDriver wire protocol. + * @param {string} name The name of the cookie to retrieve. + * @return {!promise.Promise} A promise that will be resolved with the + * named cookie, or {@code null} if there is no such cookie. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object + */ + getCookie(name: string): promise.Promise; + + /** + * @return {!Logs} The interface for managing driver + * logs. + */ + logs(): Logs; + + /** + * @return {!Timeouts} The interface for managing driver + * timeouts. + */ + timeouts(): Timeouts; + + /** + * @return {!Window} The interface for managing the + * current window. + */ + window(): Window; + + // endregion +} + +/** + * An interface for managing timeout behavior for WebDriver instances. + */ +export class Timeouts { + // region Constructors + + /** + * @param {!WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Specifies the amount of time the driver should wait when searching for an + * element if it is not immediately present. + *

              + * When searching for a single element, the driver should poll the page + * until the element has been found, or this timeout expires before failing + * with a {@code bot.ErrorCode.NO_SUCH_ELEMENT} error. When searching + * for multiple elements, the driver should poll the page until at least one + * element has been found or this timeout has expired. + *

              + * Setting the wait timeout to 0 (its default value), disables implicit + * waiting. + *

              + * Increasing the implicit wait timeout should be used judiciously as it + * will have an adverse effect on test run time, especially when used with + * slower location strategies like XPath. + * + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!promise.Promise} A promise that will be resolved when the + * implicit wait timeout has been set. + */ + implicitlyWait(ms: number): promise.Promise; + + /** + * Sets the amount of time to wait, in milliseconds, for an asynchronous script + * to finish execution before returning an error. If the timeout is less than or + * equal to 0, the script will be allowed to run indefinitely. + * + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!promise.Promise} A promise that will be resolved when the + * script timeout has been set. + */ + setScriptTimeout(ms: number): promise.Promise; + + /** + * Sets the amount of time to wait for a page load to complete before returning + * an error. If the timeout is negative, page loads may be indefinite. + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!promise.Promise} A promise that will be resolved when + * the timeout has been set. + */ + pageLoadTimeout(ms: number): promise.Promise; + + // endregion +} + +/** + * An interface for managing the current window. + */ +export class Window { + + // region Constructors + + /** + * @param {!WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Retrieves the window's current position, relative to the top left corner of + * the screen. + * @return {!promise.Promise} A promise that will be resolved with the + * window's position in the form of a {x:number, y:number} object literal. + */ + getPosition(): promise.Promise; + + /** + * Repositions the current window. + * @param {number} x The desired horizontal position, relative to the left side + * of the screen. + * @param {number} y The desired vertical position, relative to the top of the + * of the screen. + * @return {!promise.Promise} A promise that will be resolved when the + * command has completed. + */ + setPosition(x: number, y: number): promise.Promise; + + /** + * Retrieves the window's current size. + * @return {!promise.Promise} A promise that will be resolved with the + * window's size in the form of a {width:number, height:number} object + * literal. + */ + getSize(): promise.Promise; + + /** + * Resizes the current window. + * @param {number} width The desired window width. + * @param {number} height The desired window height. + * @return {!promise.Promise} A promise that will be resolved when the + * command has completed. + */ + setSize(width: number, height: number): promise.Promise; + + /** + * Maximizes the current window. + * @return {!promise.Promise} A promise that will be resolved when the + * command has completed. + */ + maximize(): promise.Promise; + + // endregion +} + +/** + * Interface for managing WebDriver log records. + */ +export class Logs { + + // region Constructors + + /** + * @param {!WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region + + /** + * Fetches available log entries for the given type. + * + *

              Note that log buffers are reset after each call, meaning that + * available log entries correspond to those entries not yet returned for a + * given log type. In practice, this means that this call will return the + * available log entries since the last call, or from the start of the + * session. + * + * @param {!logging.Type} type The desired log type. + * @return {!promise.Promise.>} A + * promise that will resolve to a list of log entries for the specified + * type. + */ + get(type: string): promise.Promise; + + /** + * Retrieves the log types available to this driver. + * @return {!promise.Promise.>} A + * promise that will resolve to a list of available log types. + */ + getAvailableLogTypes(): promise.Promise; + + // endregion +} + +/** + * An interface for changing the focus of the driver to another frame or window. + */ +export class TargetLocator { + + // region Constructors + + /** + * @param {!WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Schedules a command retrieve the {@code document.activeElement} element on + * the current document, or {@code document.body} if activeElement is not + * available. + * @return {!WebElement} The active element. + */ + activeElement(): WebElementPromise; + + /** + * Schedules a command to switch focus of all future commands to the first frame + * on the page. + * @return {!promise.Promise} A promise that will be resolved when the + * driver has changed focus to the default content. + */ + defaultContent(): promise.Promise; + + /** + * Schedules a command to switch the focus of all future commands to another + * frame on the page. The target frame may be specified as one of the + * following: + * + * - A number that specifies a (zero-based) index into [window.frames]( + * https://developer.mozilla.org/en-US/docs/Web/API/Window.frames). + * - A {@link WebElement} reference, which correspond to a `frame` or `iframe` + * DOM element. + * - The `null` value, to select the topmost frame on the page. Passing `null` + * is the same as calling {@link #defaultContent defaultContent()}. + * + * If the specified frame can not be found, the returned promise will be + * rejected with a {@linkplain error.NoSuchFrameError}. + * + * @param {(number|WebElement|null)} id The frame locator. + * @return {!promise.Promise} A promise that will be resolved + * when the driver has changed focus to the specified frame. + */ + frame(nameOrIndex: number | WebElement): promise.Promise; + + /** + * Schedules a command to switch the focus of all future commands to another + * window. Windows may be specified by their {@code window.name} attribute or + * by its handle (as returned by {@link WebDriver#getWindowHandles}). + * + * If the specified window cannot be found, the returned promise will be + * rejected with a {@linkplain error.NoSuchWindowError}. + * + * @param {string} nameOrHandle The name or window handle of the window to + * switch focus to. + * @return {!promise.Promise} A promise that will be resolved + * when the driver has changed focus to the specified window. + */ + window(nameOrHandle: string): promise.Promise; + + /** + * Schedules a command to change focus to the active modal dialog, such as + * those opened by `window.alert()`, `window.confirm()`, and + * `window.prompt()`. The returned promise will be rejected with a + * {@linkplain error.NoSuchAlertError} if there are no open alerts. + * + * @return {!AlertPromise} The open alert. + */ + alert(): AlertPromise; + + // endregion +} + +/** + * Used with {@link WebElement#sendKeys WebElement#sendKeys} on file + * input elements ({@code }) to detect when the entered key + * sequence defines the path to a file. + * + * By default, {@linkplain WebElement WebElement's} will enter all + * key sequences exactly as entered. You may set a + * {@linkplain WebDriver#setFileDetector file detector} on the parent + * WebDriver instance to define custom behavior for handling file elements. Of + * particular note is the {@link selenium-webdriver/remote.FileDetector}, which + * should be used when running against a remote + * [Selenium Server](http://docs.seleniumhq.org/download/). + */ +export class FileDetector { + /** @constructor */ + constructor(); + + /** + * Handles the file specified by the given path, preparing it for use with + * the current browser. If the path does not refer to a valid file, it will + * be returned unchanged, otherwisee a path suitable for use with the current + * browser will be returned. + * + * This default implementation is a no-op. Subtypes may override this + * function for custom tailored file handling. + * + * @param {!WebDriver} driver The driver for the current browser. + * @param {string} path The path to process. + * @return {!promise.Promise} A promise for the processed + * file path. + * @package + */ + handleFile(driver: WebDriver, path: string): promise.Promise; +} + +/** + * Creates a new WebDriver client, which provides control over a browser. + * + * Every WebDriver command returns a {@code promise.Promise} that + * represents the result of that command. Callbacks may be registered on this + * object to manipulate the command result or catch an expected error. Any + * commands scheduled with a callback are considered sub-commands and will + * execute before the next command in the current frame. For example: + * + * var message = []; + * driver.call(message.push, message, 'a').then(function() { + * driver.call(message.push, message, 'b'); + * }); + * driver.call(message.push, message, 'c'); + * driver.call(function() { + * alert('message is abc? ' + (message.join('') == 'abc')); + * }); + * + */ +export class WebDriver { + // region Constructors + + /** + * @param {!(Session|promise.Promise)} session Either a + * known session or a promise that will be resolved to a session. + * @param {!command.Executor} executor The executor to use when sending + * commands to the browser. + * @param {promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + */ + constructor(session: Session | promise.Promise, executor: Executor, opt_flow?: promise.ControlFlow); + + // endregion + + // region StaticMethods + + /** + * Creates a new WebDriver client for an existing session. + * @param {!command.Executor} executor Command executor to use when querying + * for session details. + * @param {string} sessionId ID of the session to attach to. + * @param {promise.ControlFlow=} opt_flow The control flow all + * driver commands should execute under. Defaults to the + * {@link promise.controlFlow() currently active} control flow. + * @return {!WebDriver} A new client for the specified session. + */ + static attachToSession(executor: Executor, sessionId: string, opt_flow?: promise.ControlFlow): WebDriver; + + /** + * Creates a new WebDriver session. + * @param {!command.Executor} executor The executor to create the new session + * with. + * @param {!./capabilities.Capabilities} desiredCapabilities The desired + * capabilities for the new session. + * @param {promise.ControlFlow=} opt_flow The control flow all driver + * commands should execute under, including the initial session creation. + * Defaults to the {@link promise.controlFlow() currently active} + * control flow. + * @return {!WebDriver} The driver for the newly created session. + */ + static createSession(executor: Executor, desiredCapabilities: Capabilities, opt_flow?: promise.ControlFlow): WebDriver; + + // endregion + + // region Methods + + /** + * @return {!promise.ControlFlow} The control flow used by this + * instance. + */ + controlFlow(): promise.ControlFlow; + + /** + * Schedules a {@link command.Command} to be executed by this driver's + * {@link command.Executor}. + * + * @param {!command.Command} command The command to schedule. + * @param {string} description A description of the command for debugging. + * @return {!promise.Promise} A promise that will be resolved + * with the command result. + * @template T + */ + schedule(command: Command, description: string): promise.Promise; + + + /** + * Sets the {@linkplain input.FileDetector file detector} that should be + * used with this instance. + * @param {input.FileDetector} detector The detector to use or {@code null}. + */ + setFileDetector(detector: FileDetector): void; + + + /** + * @return {!promise.Promise.} A promise for this + * client's session. + */ + getSession(): promise.Promise; + + + /** + * @return {!promise.Promise.} A promise + * that will resolve with the this instance's capabilities. + */ + getCapabilities(): promise.Promise; + + + /** + * Schedules a command to quit the current session. After calling quit, this + * instance will be invalidated and may no longer be used to issue commands + * against the browser. + * @return {!promise.Promise.} A promise that will be resolved + * when the command has completed. + */ + quit(): promise.Promise; + + /** + * Creates a new action sequence using this driver. The sequence will not be + * scheduled for execution until {@link actions.ActionSequence#perform} is + * called. Example: + * + * driver.actions(). + * mouseDown(element1). + * mouseMove(element2). + * mouseUp(). + * perform(); + * + * @return {!actions.ActionSequence} A new action sequence for this instance. + */ + actions(): ActionSequence; + + + /** + * Creates a new touch sequence using this driver. The sequence will not be + * scheduled for execution until {@link actions.TouchSequence#perform} is + * called. Example: + * + * driver.touchActions(). + * tap(element1). + * doubleTap(element2). + * perform(); + * + * @return {!actions.TouchSequence} A new touch sequence for this instance. + */ + touchActions(): TouchSequence; + + + /** + * Schedules a command to execute JavaScript in the context of the currently + * selected frame or window. The script fragment will be executed as the body + * of an anonymous function. If the script is provided as a function object, + * that function will be converted to a string for injection into the target + * window. + * + * Any arguments provided in addition to the script will be included as script + * arguments and may be referenced using the {@code arguments} object. + * Arguments may be a boolean, number, string, or {@code WebElement}. + * Arrays and objects may also be used as script arguments as long as each item + * adheres to the types previously mentioned. + * + * The script may refer to any variables accessible from the current window. + * Furthermore, the script will execute in the window's context, thus + * {@code document} may be used to refer to the current document. Any local + * variables will not be available once the script has finished executing, + * though global variables will persist. + * + * If the script has a return value (i.e. if the script contains a return + * statement), then the following steps will be taken for resolving this + * functions return value: + * + * - For a HTML element, the value will resolve to a + * {@link WebElement} + * - Null and undefined return values will resolve to null + * - Booleans, numbers, and strings will resolve as is + * - Functions will resolve to their string representation + * - For arrays and objects, each member item will be converted according to + * the rules above + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {!promise.Promise.} A promise that will resolve to the + * scripts return value. + * @template T + */ + executeScript(script: string | Function, ...var_args: any[]): promise.Promise; + + /** + * Schedules a command to execute asynchronous JavaScript in the context of the + * currently selected frame or window. The script fragment will be executed as + * the body of an anonymous function. If the script is provided as a function + * object, that function will be converted to a string for injection into the + * target window. + * + * Any arguments provided in addition to the script will be included as script + * arguments and may be referenced using the {@code arguments} object. + * Arguments may be a boolean, number, string, or {@code WebElement}. + * Arrays and objects may also be used as script arguments as long as each item + * adheres to the types previously mentioned. + * + * Unlike executing synchronous JavaScript with {@link #executeScript}, + * scripts executed with this function must explicitly signal they are finished + * by invoking the provided callback. This callback will always be injected + * into the executed function as the last argument, and thus may be referenced + * with {@code arguments[arguments.length - 1]}. The following steps will be + * taken for resolving this functions return value against the first argument + * to the script's callback function: + * + * - For a HTML element, the value will resolve to a + * {@link WebElement} + * - Null and undefined return values will resolve to null + * - Booleans, numbers, and strings will resolve as is + * - Functions will resolve to their string representation + * - For arrays and objects, each member item will be converted according to + * the rules above + * + * __Example #1:__ Performing a sleep that is synchronized with the currently + * selected window: + * + * var start = new Date().getTime(); + * driver.executeAsyncScript( + * 'window.setTimeout(arguments[arguments.length - 1], 500);'). + * then(function() { + * console.log( + * 'Elapsed time: ' + (new Date().getTime() - start) + ' ms'); + * }); + * + * __Example #2:__ Synchronizing a test with an AJAX application: + * + * var button = driver.findElement(By.id('compose-button')); + * button.click(); + * driver.executeAsyncScript( + * 'var callback = arguments[arguments.length - 1];' + + * 'mailClient.getComposeWindowWidget().onload(callback);'); + * driver.switchTo().frame('composeWidget'); + * driver.findElement(By.id('to')).sendKeys('dog@example.com'); + * + * __Example #3:__ Injecting a XMLHttpRequest and waiting for the result. In + * this example, the inject script is specified with a function literal. When + * using this format, the function is converted to a string for injection, so it + * should not reference any symbols not defined in the scope of the page under + * test. + * + * driver.executeAsyncScript(function() { + * var callback = arguments[arguments.length - 1]; + * var xhr = new XMLHttpRequest(); + * xhr.open('GET', '/resource/data.json', true); + * xhr.onreadystatechange = function() { + * if (xhr.readyState == 4) { + * callback(xhr.responseText); + * } + * } + * xhr.send(''); + * }).then(function(str) { + * console.log(JSON.parse(str)['food']); + * }); + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {!promise.Promise.} A promise that will resolve to the + * scripts return value. + * @template T + */ + executeAsyncScript(script: string | Function, ...var_args: any[]): promise.Promise; + + /** + * Schedules a command to execute a custom function. + * @param {function(...): (T|promise.Promise.)} fn The function to + * execute. + * @param {Object=} opt_scope The object in whose scope to execute the function. + * @param {...*} var_args Any arguments to pass to the function. + * @return {!promise.Promise.} A promise that will be resolved' + * with the function's result. + * @template T + */ + call(fn: (...var_args: any[]) => (T | promise.Promise), opt_scope?: any, ...var_args: any[]): promise.Promise; + + /** + * Schedules a command to wait for a condition to hold. The condition may be + * specified by a {@link until.Condition}, as a custom function, or + * as a {@link promise.Promise}. + * + * For a {@link until.Condition} or function, the wait will repeatedly + * evaluate the condition until it returns a truthy value. If any errors occur + * while evaluating the condition, they will be allowed to propagate. In the + * event a condition returns a {@link promise.Promise promise}, the + * polling loop will wait for it to be resolved and use the resolved value for + * whether the condition has been satisified. Note the resolution time for + * a promise is factored into whether a wait has timed out. + * + * *Example:* waiting up to 10 seconds for an element to be present and visible + * on the page. + * + * var button = driver.wait(until.elementLocated(By.id('foo'), 10000); + * button.click(); + * + * This function may also be used to block the command flow on the resolution + * of a {@link promise.Promise promise}. When given a promise, the + * command will simply wait for its resolution before completing. A timeout may + * be provided to fail the command if the promise does not resolve before the + * timeout expires. + * + * *Example:* Suppose you have a function, `startTestServer`, that returns a + * promise for when a server is ready for requests. You can block a `WebDriver` + * client on this promise with: + * + * var started = startTestServer(); + * driver.wait(started, 5 * 1000, 'Server should start within 5 seconds'); + * driver.get(getServerUrl()); + * + * @param {!(promise.Promise| + * until.Condition| + * function(!WebDriver): T)} condition The condition to + * wait on, defined as a promise, condition object, or a function to + * evaluate as a condition. + * @param {number=} opt_timeout How long to wait for the condition to be true. + * @param {string=} opt_message An optional message to use if the wait times + * out. + * @return {!promise.Promise} A promise that will be fulfilled + * with the first truthy value returned by the condition function, or + * rejected if the condition times out. + * @template T + */ + wait(condition: promise.Promise | until.Condition | ((driver: WebDriver) => T) | Function, timeout?: number, opt_message?: string): promise.Promise; + + /** + * Schedules a command to make the driver sleep for the given amount of time. + * @param {number} ms The amount of time, in milliseconds, to sleep. + * @return {!promise.Promise.} A promise that will be resolved + * when the sleep has finished. + */ + sleep(ms: number): promise.Promise; + + /** + * Schedules a command to retrieve they current window handle. + * @return {!promise.Promise.} A promise that will be + * resolved with the current window handle. + */ + getWindowHandle(): promise.Promise; + + /** + * Schedules a command to retrieve the current list of available window handles. + * @return {!promise.Promise.>} A promise that will + * be resolved with an array of window handles. + */ + getAllWindowHandles(): promise.Promise; + + /** + * Schedules a command to retrieve the current page's source. The page source + * returned is a representation of the underlying DOM: do not expect it to be + * formatted or escaped in the same way as the response sent from the web + * server. + * @return {!promise.Promise.} A promise that will be + * resolved with the current page source. + */ + getPageSource(): promise.Promise; + + /** + * Schedules a command to close the current window. + * @return {!promise.Promise.} A promise that will be resolved + * when this command has completed. + */ + close(): promise.Promise; + + /** + * Schedules a command to navigate to the given URL. + * @param {string} url The fully qualified URL to open. + * @return {!promise.Promise.} A promise that will be resolved + * when the document has finished loading. + */ + get(url: string): promise.Promise; + + /** + * Schedules a command to retrieve the URL of the current page. + * @return {!promise.Promise.} A promise that will be + * resolved with the current URL. + */ + getCurrentUrl(): promise.Promise; + + /** + * Schedules a command to retrieve the current page's title. + * @return {!promise.Promise.} A promise that will be + * resolved with the current page's title. + */ + getTitle(): promise.Promise; + + /** + * Schedule a command to find an element on the page. If the element cannot be + * found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned + * by the driver. Unlike other commands, this error cannot be suppressed. In + * other words, scheduling a command to find an element doubles as an assert + * that the element is present on the page. To test whether an element is + * present on the page, use {@link #isElementPresent} instead. + * + * The search criteria for an element may be defined using one of the + * factories in the {@link By} namespace, or as a short-hand + * {@link By.Hash} object. For example, the following two statements + * are equivalent: + * + * var e1 = driver.findElement(By.id('foo')); + * var e2 = driver.findElement({id:'foo'}); + * + * You may also provide a custom locator function, which takes as input this + * instance and returns a {@link WebElement}, or a promise that will resolve + * to a WebElement. If the returned promise resolves to an array of + * WebElements, WebDriver will use the first element. For example, to find the + * first visible link on a page, you could write: + * + * var link = driver.findElement(firstVisibleLink); + * + * function firstVisibleLink(driver) { + * var links = driver.findElements(By.tagName('a')); + * return promise.filter(links, function(link) { + * return link.isDisplayed(); + * }); + * } + * + * @param {!(by.By|Function)} locator The locator to use. + * @return {!WebElementPromise} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: By | Function): WebElementPromise; + + /** + * Schedules a command to test if an element is present on the page. + * + * If given a DOM element, this function will check if it belongs to the + * document the driver is currently focused on. Otherwise, the function will + * test if at least one element can be found with the given search criteria. + * + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise} A promise that will resolve + * with whether the element is present on the page. + * @deprecated This method will be removed in Selenium 3.0 for consistency + * with the other Selenium language bindings. This method is equivalent + * to + * + * driver.findElements(locator).then(e => !!e.length); + */ + isElementPresent(locatorOrElement: By | Function): promise.Promise; + + /** + * Schedule a command to search for multiple elements on the page. + * + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise.>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: By | Function): promise.Promise; + + /** + * Schedule a command to take a screenshot. The driver makes a best effort to + * return a screenshot of the following, in order of preference: + * + * 1. Entire page + * 2. Current window + * 3. Visible portion of the current frame + * 4. The entire display containing the browser + * + * @return {!promise.Promise} A promise that will be + * resolved to the screenshot as a base-64 encoded PNG. + */ + takeScreenshot(): promise.Promise; + + /** + * @return {!Options} The options interface for this + * instance. + */ + manage(): Options; + + /** + * @return {!Navigation} The navigation interface for this + * instance. + */ + navigate(): Navigation; + + /** + * @return {!TargetLocator} The target locator interface for + * this instance. + */ + switchTo(): TargetLocator; + + // endregion +} + +interface IWebElementId { + [ELEMENT: string]: string; +} + +/** + * Represents a DOM element. WebElements can be found by searching from the + * document root using a {@code WebDriver} instance, or by searching + * under another {@code WebElement}: + *

              
              + *   driver.get('http://www.google.com');
              + *   var searchForm = driver.findElement(By.tagName('form'));
              + *   var searchBox = searchForm.findElement(By.name('q'));
              + *   searchBox.sendKeys('webdriver');
              + * 
              + * + * The WebElement is implemented as a promise for compatibility with the promise + * API. It will always resolve itself when its internal state has been fully + * resolved and commands may be issued against the element. This can be used to + * catch errors when an element cannot be located on the page: + *
              
              + *   driver.findElement(By.id('not-there')).then(function(element) {
              + *     alert('Found an element that was not expected to be there!');
              + *   }, function(error) {
              + *     alert('The element was not found, as expected');
              + *   });
              + * 
              + */ +interface IWebElement { + // region Methods + + /** + * Schedules a command to click on this element. + * @return {!promise.Promise} A promise that will be resolved when + * the click command has completed. + */ + click(): promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by + * this instance. + * + * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the key sequence, that key state is toggled until one of the + * following occurs: + * + * - The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down + * events). + * - The {@link input.Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys('text was', + * Key.CONTROL, 'a', Key.NULL, + * 'now text is'); + * // Alternatively: + * element.sendKeys('text was', + * Key.chord(Key.CONTROL, 'a'), + * 'now text is'); + * + * - The end of the key sequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying + * keyup events). + * + * If this element is a file input ({@code }), the + * specified key sequence should specify the path to the file to attach to + * the element. This is analogous to the user clicking 'Browse...' and entering + * the path into the file select dialog. + * + * var form = driver.findElement(By.css('form')); + * var element = form.findElement(By.css('input[type=file]')); + * element.sendKeys('/path/to/file.txt'); + * form.submit(); + * + * For uploads to function correctly, the entered path must reference a file + * on the _browser's_ machine, not the local machine running this script. When + * running against a remote Selenium server, a {@link input.FileDetector} + * may be used to transparently copy files to the remote machine before + * attempting to upload them in the browser. + * + * __Note:__ On browsers where native keyboard events are not supported + * (e.g. Firefox on OS X), key events will be synthesized. Special + * punctuation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...(number|string|!IThenable<(number|string)>)} var_args The + * sequence of keys to type. Number keys may be referenced numerically or + * by string (1 or '1'). All arguments will be joined into a single + * sequence. + * @return {!promise.Promise} A promise that will be resolved when all + * keys have been typed. + */ + sendKeys(...var_args: Array>): promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!promise.Promise} A promise that will be resolved with the + * element's tag name. + */ + getTagName(): promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + *

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

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

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

                + *
              • 'class' + *
              • 'readonly' + *
              + * @param {string} attributeName The name of the attribute to query. + * @return {!promise.Promise} A promise that will be resolved with the + * attribute's value. + */ + getAttribute(attributeName: string): promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!promise.Promise} A promise that will be resolved with the + * element's visible text. + */ + getText(): promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!promise.Promise} A promise that will be resolved with the + * element's size as a {@code {width:number, height:number}} object. + */ + getSize(): promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!promise.Promise} A promise that will be resolved to the + * element's location as a {@code {x:number, y:number}} object. + */ + getLocation(): promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!promise.Promise} A promise that will be resolved with + * whether this element is currently enabled. + */ + isEnabled(): promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!promise.Promise} A promise that will be resolved with + * whether this element is currently selected. + */ + isSelected(): promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!promise.Promise} A promise that will be resolved when + * the form has been submitted. + */ + submit(): promise.Promise; + + /** + * Schedules a command to clear the {@code value} of this element. This command + * has no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!promise.Promise} A promise that will be resolved when + * the element has been cleared. + */ + clear(): promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!promise.Promise} A promise that will be resolved with + * whether this element is currently visible on the page. + */ + isDisplayed(): promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!promise.Promise} A promise that will be resolved with + * the element's outer HTML. + */ + getOuterHtml(): promise.Promise; + + /** + * @return {!promise.Promise.} A promise + * that resolves to this element's JSON representation as defined by the + * WebDriver wire protocol. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol + */ + getId(): promise.Promise; + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): promise.Promise; + + // endregion +} + +interface IWebElementFinders { + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@code #isElementPresent} instead. + * + *

              The search criteria for an element may be defined using one of the + * factories in the {@link By} namespace, or as a short-hand + * {@link By.Hash} object. For example, the following two statements + * are equivalent: + *

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

              You may also provide a custom locator function, which takes as input + * this WebDriver instance and returns a {@link WebElement}, or a + * promise that will resolve to a WebElement. For example, to find the first + * visible link on a page, you could write: + *

              +   * var link = element.findElement(firstVisibleLink);
              +   *
              +   * function firstVisibleLink(element) {
              +   *   var links = element.findElements(By.tagName('a'));
              +   *   return promise.filter(links, function(link) {
              +   *     return links.isDisplayed();
              +   *   }).then(function(visibleLinks) {
              +   *     return visibleLinks[0];
              +   *   });
              +   * }
              +   * 
              + * + * @param {!(Locator|By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: By | Function): WebElementPromise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + * @param {!(Locator|By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!promise.Promise.} A promise that will be + * resolved with whether an element could be located on the page. + */ + isElementPresent(locator: By | Function): promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that + * match the given search criteria. + * + * @param {!(Locator|By.Hash|Function)} locator The + * locator strategy to use when searching for the elements. + * @return {!promise.Promise.>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: By | Function): promise.Promise; +} + +/** + * Defines an object that can be asynchronously serialized to its WebDriver + * wire representation. + * + * @constructor + * @template T + */ +interface Serializable { + /** + * Returns either this instance's serialized represention, if immediately + * available, or a promise for its serialized representation. This function is + * conceptually equivalent to objects that have a {@code toJSON()} property, + * except the serialize() result may be a promise or an object containing a + * promise (which are not directly JSON friendly). + * + * @return {!(T|IThenable.)} This instance's serialized wire format. + */ + serialize(): T | promise.IThenable; +} + +/** + * Represents a DOM element. WebElements can be found by searching from the + * document root using a {@link WebDriver} instance, or by searching + * under another WebElement: + * + * driver.get('http://www.google.com'); + * var searchForm = driver.findElement(By.tagName('form')); + * var searchBox = searchForm.findElement(By.name('q')); + * searchBox.sendKeys('webdriver'); + * + * The WebElement is implemented as a promise for compatibility with the promise + * API. It will always resolve itself when its internal state has been fully + * resolved and commands may be issued against the element. This can be used to + * catch errors when an element cannot be located on the page: + * + * driver.findElement(By.id('not-there')).then(function(element) { + * alert('Found an element that was not expected to be there!'); + * }, function(error) { + * alert('The element was not found, as expected'); + * }); + * + * @extends {Serializable.} + */ +export class WebElement implements Serializable { + /** + * @param {!WebDriver} driver the parent WebDriver instance for this element. + * @param {(!IThenable|string)} id The server-assigned opaque ID for + * the underlying DOM element. + */ + constructor(driver: WebDriver, id: promise.Promise | string); + + /** + * @param {string} id The raw ID. + * @param {boolean=} opt_noLegacy Whether to exclude the legacy element key. + * @return {!Object} The element ID for use with WebDriver's wire protocol. + */ + static buildId(id: string, opt_noLegacy?: boolean): Object; + + /** + * Extracts the encoded WebElement ID from the object. + * + * @param {?} obj The object to extract the ID from. + * @return {string} the extracted ID. + * @throws {TypeError} if the object is not a valid encoded ID. + */ + static extractId(obj: IWebElementId): string; + + /** + * @param {?} obj the object to test. + * @return {boolean} whether the object is a valid encoded WebElement ID. + */ + static isId(obj: IWebElementId): boolean; + + /** + * Compares two WebElements for equality. + * + * @param {!WebElement} a A WebElement. + * @param {!WebElement} b A WebElement. + * @return {!promise.Promise} A promise that will be + * resolved to whether the two WebElements are equal. + */ + static equals(a: WebElement, b: WebElement): promise.Promise; + + /** + * @return {!WebDriver} The parent driver for this instance. + */ + getDriver(): WebDriver; + + /** + * @return {!promise.Promise} A promise that resolves to + * the server-assigned opaque ID assigned to this element. + */ + getId(): promise.Promise; + + /** + * @deprecated Use {@link #getId()} instead. + */ + getRawId(): any; + + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@link #isElementPresent} instead. + * + * The search criteria for an element may be defined using one of the + * factories in the {@link By} namespace, or as a short-hand + * {@link By.Hash} object. For example, the following two statements + * are equivalent: + * + * var e1 = element.findElement(By.id('foo')); + * var e2 = element.findElement({id:'foo'}); + * + * You may also provide a custom locator function, which takes as input + * this WebDriver instance and returns a {@link WebElement}, or a + * promise that will resolve to a WebElement. For example, to find the first + * visible link on a page, you could write: + * + * var link = element.findElement(firstVisibleLink); + * + * function firstVisibleLink(element) { + * var links = element.findElements(By.tagName('a')); + * return promise.filter(links, function(link) { + * return links.isDisplayed(); + * }).then(function(visibleLinks) { + * return visibleLinks[0]; + * }); + * } + * + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!WebElementPromise} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: By | Function): WebElementPromise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!promise.Promise} A promise that will be + * resolved with whether an element could be located on the page. + * @deprecated This method will be removed in Selenium 3.0 for consistency + * with the other Selenium language bindings. This method is equivalent + * to + * + * element.findElements(locator).then(e => !!e.length); + */ + isElementPresent(locator: By | Function): promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that + * match the given search criteria. + * + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!promise.Promise>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: By | Function): promise.Promise; + + /** + * Schedules a command to click on this element. + * @return {!promise.Promise.} A promise that will be resolved + * when the click command has completed. + */ + click(): promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by this + * promsieinstance. + * + * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the keysequence, that key state is toggled until one of the + * following occurs: + * + * - The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + * - The {@link Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys('text was', + * Key.CONTROL, 'a', Key.NULL, + * 'now text is'); + * // Alternatively: + * element.sendKeys('text was', + * Key.chord(Key.CONTROL, 'a'), + * 'now text is'); + * + * - The end of the keysequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying keyup + * events). + * + * If this element is a file input ({@code }), the + * specified key sequence should specify the path to the file to attach to + * the element. This is analgous to the user clicking 'Browse...' and entering + * the path into the file select dialog. + * + * var form = driver.findElement(By.css('form')); + * var element = form.findElement(By.css('input[type=file]')); + * element.sendKeys('/path/to/file.txt'); + * form.submit(); + * + * For uploads to function correctly, the entered path must reference a file + * on the _browser's_ machine, not the local machine running this script. When + * running against a remote Selenium server, a {@link FileDetector} + * may be used to transparently copy files to the remote machine before + * attempting to upload them in the browser. + * + * __Note:__ On browsers where native keyboard events are not supported + * (e.g. Firefox on OS X), key events will be synthesized. Special + * punctionation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...(string|!promise.Promise)} var_args The sequence + * of keys to type. All arguments will be joined into a single sequence. + * @return {!promise.Promise.} A promise that will be resolved + * when all keys have been typed. + */ + sendKeys(...var_args: Array>): promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!promise.Promise.} A promise that will be + * resolved with the element's tag name. + */ + getTagName(): promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + * + * _Warning:_ the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!promise.Promise} A promise that will be + * resolved with the requested CSS value. + */ + getCssValue(cssStyleProperty: string): promise.Promise; + + /** + * Schedules a command to query for the value of the given attribute of the + * element. Will return the current value, even if it has been modified after + * the page has been loaded. More exactly, this method will return the value of + * the given attribute, unless that attribute is not present, in which case the + * value of the property with the same name is returned. If neither value is + * set, null is returned (for example, the 'value' property of a textarea + * element). The 'style' attribute is converted as best can be to a + * text representation with a trailing semi-colon. The following are deemed to + * be 'boolean' attributes and will return either 'true' or null: + * + * async, autofocus, autoplay, checked, compact, complete, controls, declare, + * defaultchecked, defaultselected, defer, disabled, draggable, ended, + * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, + * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, + * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, + * selected, spellcheck, truespeed, willvalidate + * + * Finally, the following commonly mis-capitalized attribute/property names + * are evaluated as expected: + * + * - 'class' + * - 'readonly' + * + * @param {string} attributeName The name of the attribute to query. + * @return {!promise.Promise.} A promise that will be + * resolved with the attribute's value. The returned value will always be + * either a string or null. + */ + getAttribute(attributeName: string): promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!promise.Promise.} A promise that will be + * resolved with the element's visible text. + */ + getText(): promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!promise.Promise.<{width: number, height: number}>} A + * promise that will be resolved with the element's size as a + * {@code {width:number, height:number}} object. + */ + getSize(): promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!promise.Promise.<{x: number, y: number}>} A promise that + * will be resolved to the element's location as a + * {@code {x:number, y:number}} object. + */ + getLocation(): promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!promise.Promise.} A promise that will be + * resolved with whether this element is currently enabled. + */ + isEnabled(): promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!promise.Promise.} A promise that will be + * resolved with whether this element is currently selected. + */ + isSelected(): promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!promise.Promise.} A promise that will be resolved + * when the form has been submitted. + */ + submit(): promise.Promise; + + /** + * Schedules a command to clear the `value` of this element. This command has + * no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!promise.Promise} A promise that will be resolved + * when the element has been cleared. + */ + clear(): promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!promise.Promise.} A promise that will be + * resolved with whether this element is currently visible on the page. + */ + isDisplayed(): promise.Promise; + + /** + * Take a screenshot of the visible region encompassed by this element's + * bounding rectangle. + * + * @param {boolean=} opt_scroll Optional argument that indicates whether the + * element should be scrolled into view before taking a screenshot. + * Defaults to false. + * @return {!promise.Promise} A promise that will be + * resolved to the screenshot as a base-64 encoded PNG. + */ + takeScreenshot(opt_scroll?: boolean): promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!promise.Promise.} A promise that will be + * resolved with the element's outer HTML. + */ + getOuterHtml(): promise.Promise; + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): promise.Promise; + + /** @override */ + serialize(): promise.Promise; +} + +/** + * WebElementPromise is a promise that will be fulfilled with a WebElement. + * This serves as a forward proxy on WebElement, allowing calls to be + * scheduled without directly on this instance before the underlying + * WebElement has been fulfilled. In other words, the following two statements + * are equivalent: + *
              
              + *     driver.findElement({id: 'my-button'}).click();
              + *     driver.findElement({id: 'my-button'}).then(function(el) {
              + *       return el.click();
              + *     });
              + * 
              + * + * @param {!WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!promise.Promise.} el A promise + * that will resolve to the promised element. + * @constructor + * @extends {WebElement} + * @implements {promise.Thenable.} + * @final + */ +export class WebElementPromise extends WebElement implements promise.IThenable { + /** + * @param {!WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!promise.Promise} el A promise + * that will resolve to the promised element. + */ + constructor(driver: WebDriver, el: promise.Promise); + + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. This method is a no-op if the promise has alreayd been resolved. + * + * @param {string=} opt_reason The reason this promise is being cancelled. + */ + cancel(opt_reason?: string): void; + + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: WebElement) => promise.Promise, opt_errback?: (error: any) => any): promise.Promise; + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: WebElement) => R, opt_errback?: (error: any) => any): promise.Promise; + + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *
              
              +   *   // Synchronous API:
              +   *   try {
              +   *     doSynchronousWork();
              +   *   } catch (ex) {
              +   *     console.error(ex);
              +   *   }
              +   *
              +   *   // Asynchronous promise API:
              +   *   doAsynchronousWork().thenCatch(function(ex) {
              +   *     console.error(ex);
              +   *   });
              +   * 
              + * + * @param {function(*): (R|promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): promise.Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *
              
              +   *   // Synchronous API:
              +   *   try {
              +   *     doSynchronousWork();
              +   *   } finally {
              +   *     cleanUp();
              +   *   }
              +   *
              +   *   // Asynchronous promise API:
              +   *   doAsynchronousWork().thenFinally(cleanUp);
              +   * 
              + * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *
              
              +   *   try {
              +   *     throw Error('one');
              +   *   } finally {
              +   *     throw Error('two');  // Hides Error: one
              +   *   }
              +   *
              +   *   promise.rejected(Error('one'))
              +   *       .thenFinally(function() {
              +   *         throw Error('two');  // Hides Error: one
              +   *       });
              +   * 
              + * + * + * @param {function(): (R|promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: () => any): promise.Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): promise.Promise; +} + +/** + * Contains information about a WebDriver session. + */ +export class Session { + + // region Constructors + + /** + * @param {string} id The session ID. + * @param {!(Object|Capabilities)} capabilities The session + * capabilities. + * @constructor + */ + constructor(id: string, capabilities: Capabilities | Object); + + // endregion + + // region Methods + + /** + * @return {string} This session's ID. + */ + getId(): string; + + /** + * @return {!Capabilities} This session's capabilities. + */ + getCapabilities(): Capabilities; + + /** + * Retrieves the value of a specific capability. + * @param {string} key The capability to retrieve. + * @return {*} The capability value. + */ + getCapability(key: string): any; + + /** + * Returns the JSON representation of this object, which is just the string + * session ID. + * @return {string} The JSON representation of this Session. + */ + toJSON(): string; + + // endregion +} diff --git a/selenium-webdriver/v2/opera.d.ts b/selenium-webdriver/v2/opera.d.ts new file mode 100644 index 0000000000..9976995e65 --- /dev/null +++ b/selenium-webdriver/v2/opera.d.ts @@ -0,0 +1,174 @@ +/* tslint:disable */ +import * as webdriver from './index'; +import * as remote from './remote'; + +/** + * Creates {@link remote.DriverService} instances that manages an + * [OperaDriver](https://github.com/operasoftware/operachromiumdriver) + * server in a child process. + */ +export class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the operadriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the operadriver + * cannot be found on the PATH. + */ + constructor(opt_exe?: string); + + /** + * Sets the port to start the OperaDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; + + /** + * Sets the path of the log file the driver should log to. If a log file is + * not specified, the driver will log to stderr. + * @param {string} path Path of the log file to use. + * @return {!ServiceBuilder} A self reference. + */ + loggingTo(path: string): ServiceBuilder; + + /** + * Enables verbose logging. + * @return {!ServiceBuilder} A self reference. + */ + enableVerboseLogging(): ServiceBuilder; + + /** + * Silence sthe drivers output. + * @return {!ServiceBuilder} A self reference. + */ + silent(): ServiceBuilder; + + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array)} + * config The configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string | Array): ServiceBuilder; + + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: Object): ServiceBuilder; + + /** + * Creates a new DriverService using this instance's current configuration. + * @return {!remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; +} + +/** + * Sets the default service to use for new OperaDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ +export function setDefaultService(service: remote.DriverService): any; + +/** + * Returns the default OperaDriver service. If such a service has not been + * configured, one will be constructed using the default configuration for + * a OperaDriver executable found on the system PATH. + * @return {!remote.DriverService} The default OperaDriver service. + */ +export function getDefaultService(): remote.DriverService; + +/** + * Class for managing {@linkplain Driver OperaDriver} specific options. + */ +export class Options { + /** + * Extracts the OperaDriver specific options from the given capabilities + * object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The OperaDriver options. + */ + static fromCapabilities(caps: webdriver.Capabilities): Options; + + /** + * Add additional command line arguments to use when launching the Opera + * browser. Each argument may be specified with or without the '--' prefix + * (e.g. '--foo' and 'foo'). Arguments with an associated value should be + * delimited by an '=': 'foo=bar'. + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: string[]): Options; + + /** + * Add additional extensions to install when launching Opera. Each extension + * should be specified as the path to the packed CRX file, or a Buffer for an + * extension. + * @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The + * extensions to add. + * @return {!Options} A self reference. + */ + addExtensions(...var_args: any[]): Options; + + /** + * Sets the path to the Opera binary to use. On Mac OS X, this path should + * reference the actual Opera executable, not just the application binary. The + * binary path be absolute or relative to the operadriver server executable, but + * it must exist on the machine that will launch Opera. + * + * @param {string} path The path to the Opera binary to use. + * @return {!Options} A self reference. + */ + setOperaBinaryPath(path: string): Options; + + /** + * Sets the logging preferences for the new session. + * @param {!./lib/logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; +} + +export class Driver extends webdriver.WebDriver { + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@link getDefaultService default service} by default. + * @param {promise.ControlFlow=} opt_flow The control flow to use, + * or {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities | Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; +} diff --git a/selenium-webdriver/v2/remote.d.ts b/selenium-webdriver/v2/remote.d.ts new file mode 100644 index 0000000000..de31a0fbe7 --- /dev/null +++ b/selenium-webdriver/v2/remote.d.ts @@ -0,0 +1,106 @@ +/* tslint:disable */ +import * as webdriver from './index'; + +/** + * A record object that defines the configuration options for a DriverService + * instance. + * + * @record + */ +interface ServiceOptions { } + +/** + * Manages the life and death of a native executable WebDriver server. + * + * It is expected that the driver server implements the + * https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol. + * Furthermore, the managed server should support multiple concurrent sessions, + * so that this class may be reused for multiple clients. + */ +export class DriverService { + /** + * @param {string} executable Path to the executable to run. + * @param {!ServiceOptions} options Configuration options for the service. + */ + constructor(executable: string, options: ServiceOptions); + + /** + * @return {!promise.Promise} A promise that resolves to + * the server's address. + * @throws {Error} If the server has not been started. + */ + address(): webdriver.promise.Promise; + + /** + * Returns whether the underlying process is still running. This does not take + * into account whether the process is in the process of shutting down. + * @return {boolean} Whether the underlying service process is running. + */ + isRunning(): boolean; + + /** + * Starts the server if it is not already running. + * @param {number=} opt_timeoutMs How long to wait, in milliseconds, for the + * server to start accepting requests. Defaults to 30 seconds. + * @return {!promise.Promise} A promise that will resolve + * to the server's base URL when it has started accepting requests. If the + * timeout expires before the server has started, the promise will be + * rejected. + */ + start(opt_timeoutMs?: number): webdriver.promise.Promise; + + /** + * Stops the service if it is not currently running. This function will kill + * the server immediately. To synchronize with the active control flow, use + * {@link #stop()}. + * @return {!promise.Promise} A promise that will be resolved when + * the server has been stopped. + */ + kill(): webdriver.promise.Promise; + + /** + * Schedules a task in the current control flow to stop the server if it is + * currently running. + * @return {!promise.Promise} A promise that will be resolved when + * the server has been stopped. + */ + stop(): webdriver.promise.Promise; +} + +/** + * A {@link webdriver.FileDetector} that may be used when running + * against a remote + * [Selenium server](http://selenium-release.storage.googleapis.com/index.html). + * + * When a file path on the local machine running this script is entered with + * {@link webdriver.WebElement#sendKeys WebElement#sendKeys}, this file detector + * will transfer the specified file to the Selenium server's host; the sendKeys + * command will be updated to use the transfered file's path. + * + * __Note:__ This class depends on a non-standard command supported on the + * Java Selenium server. The file detector will fail if used with a server that + * only supports standard WebDriver commands (such as the ChromeDriver). + * + * @final + */ +export class FileDetector extends webdriver.FileDetector { + /** + * @constructor + **/ + constructor(); + + /** + * Prepares a `file` for use with the remote browser. If the provided path + * does not reference a normal file (i.e. it does not exist or is a + * directory), then the promise returned by this method will be resolved with + * the original file path. Otherwise, this method will upload the file to the + * remote server, which will return the file's path on the remote system so + * it may be referenced in subsequent commands. + * + * @param {!webdriver.WebDriver} driver The driver for the current browser. + * @param {string} file The path of the file to process. + * @return {!webdriver.promise.Promise} A promise for the processed + * file path. + */ + handleFile(driver: webdriver.WebDriver, file: string): webdriver.promise.Promise; +} diff --git a/selenium-webdriver/v2/safari.d.ts b/selenium-webdriver/v2/safari.d.ts new file mode 100644 index 0000000000..0633f9f782 --- /dev/null +++ b/selenium-webdriver/v2/safari.d.ts @@ -0,0 +1,90 @@ +/* tslint:disable */ +import * as webdriver from './index'; + +export class Server { } + +/** + * @return {!Promise} A promise that will resolve with the path + * to Safari on the current system. + */ +export function findSafariExecutable(): any; + +/** + * @param {string} serverUrl The URL to connect to. + * @return {!Promise} A promise for the path to a file that Safari can + * open on start-up to trigger a new connection to the WebSocket server. + */ +export function createConnectFile(serverUrl: string): any; + +/** + * Deletes all session data files if so desired. + * @param {!Object} desiredCapabilities . + * @return {!Array} A list of promises for the deleted files. + */ +export function cleanSession(desiredCapabilities: webdriver.Capabilities): any[]; + +/** @return {string} . */ +export function getRandomString(): string; + +/** + * @implements {command.Executor} + */ +export class CommandExecutor { +} + +/** + * Configuration options specific to the {@link Driver SafariDriver}. + */ +export class Options { + /** + * Extracts the SafariDriver specific options from the given capabilities + * object. + * @param {!Capabilities} capabilities The capabilities object. + * @return {!Options} The ChromeDriver options. + */ + static fromCapabilities(capabilities: webdriver.Capabilities): Options; + + /** + * Sets whether to force Safari to start with a clean session. Enabling this + * option will cause all global browser data to be deleted. + * @param {boolean} clean Whether to make sure the session has no cookies, + * cache entries, local storage, or databases. + * @return {!Options} A self reference. + */ + setCleanSession(clean: boolean): Options; + + /** + * Sets the logging preferences for the new session. + * @param {!./lib/logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Converts this options instance to a {@link Capabilities} object. + * @param {Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; +} + +/** + * A WebDriver client for Safari. This class should never be instantiated + * directly; instead, use the {@linkplain ./builder.Builder Builder}: + * + * var driver = new Builder() + * .forBrowser('safari') + * .build(); + * + */ +export class Driver extends webdriver.WebDriver { + /** + * @param {(Options|Capabilities)=} opt_config The configuration + * options for the new session. + * @param {promise.ControlFlow=} opt_flow The control flow to create + * the driver under. + */ + constructor(opt_config?: Options | webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); + +} diff --git a/selenium-webdriver/v2/test/chrome.ts b/selenium-webdriver/v2/test/chrome.ts new file mode 100644 index 0000000000..f9c896fbee --- /dev/null +++ b/selenium-webdriver/v2/test/chrome.ts @@ -0,0 +1,62 @@ +/* tslint:disable */ +import * as chrome from 'selenium-webdriver/chrome'; +import * as remote from 'selenium-webdriver/remote'; +import * as webdriver from 'selenium-webdriver'; + +function TestChromeDriver() { + var driver: chrome.Driver = new chrome.Driver(); + driver = new chrome.Driver(webdriver.Capabilities.chrome()); + driver = new chrome.Driver(webdriver.Capabilities.chrome(), + new remote.DriverService('executable', new chrome.Options()), + new webdriver.promise.ControlFlow()); + + var baseDriver: webdriver.WebDriver = driver; +} + +function TestChromeOptions() { + var options: chrome.Options = new chrome.Options(); + options = chrome.Options.fromCapabilities(webdriver.Capabilities.chrome()); + + options = options.addArguments('a', 'b', 'c'); + options = options.addExtensions('a', 'b', 'c'); + options = options.excludeSwitches('a', 'b', 'c'); + options = options.detachDriver(true); + options = options.setChromeBinaryPath('path'); + options = options.setChromeLogFile('logfile'); + options = options.setLocalState('state'); + options = options.androidActivity('com.example.Activity'); + options = options.androidDeviceSerial('emulator-5554'); + options = options.androidChrome(); + options = options.androidPackage('com.android.chrome'); + options = options.androidProcess('com.android.chrome'); + options = options.androidUseRunningApp(true); + options = options.setLoggingPrefs(new webdriver.logging.Preferences()); + options = options.setPerfLoggingPrefs({ + enableNetwork: true, enablePage: true, enableTimeline: true, + tracingCategories: 'category', bufferUsageReportingInterval: 1000 }); + options = options.setProxy({ proxyType: 'proxyType' }); + options = options.setUserPreferences('preferences'); + var capabilities: webdriver.Capabilities = options.toCapabilities(); + capabilities = options.toCapabilities(webdriver.Capabilities.chrome()); +} + +function TestServiceBuilder() { + var builder: chrome.ServiceBuilder = new chrome.ServiceBuilder(); + builder = new chrome.ServiceBuilder('exe'); + + var anything: any = builder.build(); + builder = builder.usingPort(8080); + builder = builder.setAdbPort(5037); + builder = builder.loggingTo('path'); + builder = builder.enableVerboseLogging(); + builder = builder.setNumHttpThreads(5); + builder = builder.setUrlBasePath('path'); + builder = builder.setStdio('config'); + builder = builder.setStdio(['A', 'B']); + builder = builder.withEnvironment({ A: 'a', B: 'b' }); +} + +function TestChromeModule() { + var service: any = chrome.getDefaultService(); + chrome.setDefaultService(new remote.DriverService('executable', new chrome.Options())); +} diff --git a/selenium-webdriver/v2/test/firefox.ts b/selenium-webdriver/v2/test/firefox.ts new file mode 100644 index 0000000000..2f3aeb928c --- /dev/null +++ b/selenium-webdriver/v2/test/firefox.ts @@ -0,0 +1,55 @@ +/* tslint:disable */ +import * as firefox from 'selenium-webdriver/firefox'; +import * as remote from 'selenium-webdriver/remote'; +import * as webdriver from 'selenium-webdriver'; + +function TestBinary() { + var binary: firefox.Binary = new firefox.Binary(); + binary = new firefox.Binary('exe'); + + binary.addArguments('A', 'B', 'C'); + var promise: webdriver.promise.Promise = binary.kill(); + binary.launch('profile').then((result: any) => {}); +} + +function TestFirefoxDriver() { + var driver: firefox.Driver = new firefox.Driver(); + driver = new firefox.Driver(webdriver.Capabilities.firefox()); + driver = new firefox.Driver(webdriver.Capabilities.firefox(), new webdriver.promise.ControlFlow()); + + var baseDriver: webdriver.WebDriver = driver; +} + +function TestFirefoxOptions() { + var options: firefox.Options = new firefox.Options(); + + options = options.setBinary('binary'); + options = options.setBinary(new firefox.Binary()); + options = options.setLoggingPreferences(new webdriver.logging.Preferences()); + options = options.setProfile('profile'); + options = options.setProfile(new firefox.Profile()); + options = options.setProxy({ proxyType: 'proxy' }); + var capabilities: webdriver.Capabilities = options.toCapabilities(); +} + +function TestFirefoxProfile() { + var profile: firefox.Profile = new firefox.Profile(); + profile = new firefox.Profile('dir'); + + var bool: boolean = profile.acceptUntrustedCerts(); + profile.addExtension('ext'); + bool = profile.assumeUntrustedCertIssuer(); + profile.encode().then((prof: string) => {}); + var num: number = profile.getPort(); + var anything: any = profile.getPreference('key'); + bool = profile.nativeEventsEnabled(); + profile.setAcceptUntrustedCerts(true); + profile.setAssumeUntrustedCertIssuer(true); + profile.setNativeEventsEnabled(true); + profile.setPort(8080); + profile.setPreference('key', 'value'); + profile.setPreference('key', 5); + profile.setPreference('key', true); + var stringPromise: webdriver.promise.Promise = profile.writeToDisk(); + stringPromise = profile.writeToDisk(true); +} diff --git a/selenium-webdriver/v2/test/index.ts b/selenium-webdriver/v2/test/index.ts new file mode 100644 index 0000000000..ba783f86fc --- /dev/null +++ b/selenium-webdriver/v2/test/index.ts @@ -0,0 +1,1051 @@ +/* tslint:disable */ +import * as webdriver from 'selenium-webdriver'; +import * as chrome from 'selenium-webdriver/chrome'; +import * as firefox from 'selenium-webdriver/firefox'; +import * as remote from 'selenium-webdriver/remote'; +import * as executors from 'selenium-webdriver/executors'; +import * as testing from 'selenium-webdriver/testing'; + +function TestExecutors() { + var exec: webdriver.Executor = executors.createExecutor('url'); + var promise: webdriver.promise.Promise; + exec = executors.createExecutor(promise); +} + +function TestBuilder() { + var builder: webdriver.Builder = new webdriver.Builder(); + + var driver: webdriver.WebDriver = builder.build(); + builder = builder.forBrowser('name'); + builder = builder.forBrowser('name', 'version'); + builder = builder.forBrowser('name', 'version', 'platform'); + + var cap: webdriver.Capabilities = builder.getCapabilities(); + var str: string = builder.getServerUrl(); + + builder = builder.setAlertBehavior('behavior'); + builder = builder.setChromeOptions(new chrome.Options()); + builder = builder.setControlFlow(new webdriver.promise.ControlFlow()); + builder = builder.setEnableNativeEvents(true); + builder = builder.setFirefoxOptions(new firefox.Options()); + builder = builder.setLoggingPrefs(new webdriver.logging.Preferences()); + builder = builder.setLoggingPrefs({ key: 'value' }); + builder = builder.setProxy({ proxyType: 'type' }); + builder = builder.setScrollBehavior(1); + builder = builder.usingServer('http://someserver'); + builder = builder.withCapabilities(new webdriver.Capabilities()); + builder = builder.withCapabilities({ something: true }); +} + +function TestActionSequence() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var sequence: webdriver.ActionSequence = new webdriver.ActionSequence(driver); + var element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId'); + var promise: webdriver.promise.Promise; + element = new webdriver.WebElement(driver, promise); + + // Click + sequence = sequence.click(); + sequence = sequence.click(webdriver.Button.LEFT); + sequence = sequence.click(element); + sequence = sequence.click(element, webdriver.Button.LEFT); + + // DoubleClick + sequence = sequence.doubleClick(); + sequence = sequence.doubleClick(webdriver.Button.LEFT); + sequence = sequence.doubleClick(element); + sequence = sequence.doubleClick(element, webdriver.Button.LEFT); + + // DragAndDrop + sequence = sequence.dragAndDrop(element, element); + sequence = sequence.dragAndDrop(element, { x: 1, y: 2 }); + + // KeyDown + sequence = sequence.keyDown(webdriver.Key.ADD); + + // KeyUp + sequence = sequence.keyUp(webdriver.Key.ADD); + + // MouseDown + sequence = sequence.mouseDown(); + sequence = sequence.mouseDown(webdriver.Button.LEFT); + sequence = sequence.mouseDown(element); + sequence = sequence.mouseDown(element, webdriver.Button.LEFT); + + // MouseMove + sequence = sequence.mouseMove(element); + sequence = sequence.mouseMove({ x: 1, y: 1 }); + sequence = sequence.mouseMove(element, { x: 1, y: 2 }); + + // MouseUp + sequence = sequence.mouseUp(); + sequence = sequence.mouseUp(webdriver.Button.LEFT); + sequence = sequence.mouseUp(element); + sequence = sequence.mouseUp(element, webdriver.Button.LEFT); + + // SendKeys + sequence = sequence.sendKeys('A', 'B', 'C'); + sequence = sequence.sendKeys('A', webdriver.Key.NULL); + + sequence.perform().then(() => {}); +} + +function TestTouchSequence() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + var element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId'); + + var sequence: webdriver.TouchSequence = new webdriver.TouchSequence(driver); + + sequence = sequence.tap(element); + sequence = sequence.doubleTap(element); + sequence = sequence.longPress(element); + sequence = sequence.tapAndHold({ x: 100, y: 100 }); + sequence = sequence.move({ x: 100, y: 100 }); + sequence = sequence.release({ x: 100, y: 100 }); + sequence = sequence.scroll({ x: 100, y: 100 }); + sequence = sequence.scrollFromElement(element, { x: 100, y: 100 }); + sequence = sequence.flick({ xspeed: 100, yspeed: 100 }); + sequence = sequence.flickElement(element, { x: 100, y: 100 }, 100); + + sequence.perform().then(() => {}); +} + +function TestAlert() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var alert: webdriver.Alert = driver.switchTo().alert(); + + alert.accept().then(() => {}); + alert.dismiss().then(() => {}); + alert.getText().then((text: string) => {}); + alert.sendKeys('ABC').then(() => {}); +} + +function TestBrowser() { + var browser: string; + + browser = webdriver.Browser.ANDROID; + browser = webdriver.Browser.CHROME; + browser = webdriver.Browser.FIREFOX; + browser = webdriver.Browser.HTMLUNIT; + browser = webdriver.Browser.INTERNET_EXPLORER; + browser = webdriver.Browser.IPAD; + browser = webdriver.Browser.IPHONE; + browser = webdriver.Browser.OPERA; + browser = webdriver.Browser.PHANTOM_JS; + browser = webdriver.Browser.SAFARI; +} + +function TestButton() { + var button: string; + + button = webdriver.Button.LEFT; + button = webdriver.Button.MIDDLE; + button = webdriver.Button.RIGHT; +} + +function TestCapabilities() { + var capabilities: webdriver.Capabilities = new webdriver.Capabilities(); + capabilities = new webdriver.Capabilities(webdriver.Capabilities.chrome()); + var objCapabilities: any = {}; + objCapabilities[webdriver.Capability.BROWSER_NAME] = webdriver.Browser.PHANTOM_JS; + capabilities = new webdriver.Capabilities(objCapabilities); + + var anything: any = capabilities.get(webdriver.Capability.SECURE_SSL); + var check: boolean = capabilities.has(webdriver.Capability.SECURE_SSL); + capabilities = capabilities.merge(capabilities); + capabilities = capabilities.merge(objCapabilities); + capabilities = capabilities.set(webdriver.Capability.VERSION, { abc: 'def' }); + capabilities = capabilities.set(webdriver.Capability.VERSION, null); + capabilities = capabilities.setLoggingPrefs(new webdriver.logging.Preferences()); + capabilities = capabilities.setLoggingPrefs({ key: 'value' }); + capabilities = capabilities.setProxy({ proxyType: 'Type' }); + capabilities = capabilities.setEnableNativeEvents(true); + capabilities = capabilities.setScrollBehavior(1); + capabilities = capabilities.setAlertBehavior('accept'); + + anything = capabilities.toJSON(); + + capabilities = webdriver.Capabilities.android(); + capabilities = webdriver.Capabilities.chrome(); + capabilities = webdriver.Capabilities.firefox(); + capabilities = webdriver.Capabilities.htmlunit(); + capabilities = webdriver.Capabilities.htmlunitwithjs(); + capabilities = webdriver.Capabilities.ie(); + capabilities = webdriver.Capabilities.ipad(); + capabilities = webdriver.Capabilities.iphone(); + capabilities = webdriver.Capabilities.opera(); + capabilities = webdriver.Capabilities.phantomjs(); + capabilities = webdriver.Capabilities.safari(); +} + +function TestCapability() { + var capability: string; + + capability = webdriver.Capability.ACCEPT_SSL_CERTS; + capability = webdriver.Capability.BROWSER_NAME; + capability = webdriver.Capability.ELEMENT_SCROLL_BEHAVIOR; + capability = webdriver.Capability.HANDLES_ALERTS; + capability = webdriver.Capability.LOGGING_PREFS; + capability = webdriver.Capability.NATIVE_EVENTS; + capability = webdriver.Capability.PLATFORM; + capability = webdriver.Capability.PROXY; + capability = webdriver.Capability.ROTATABLE; + capability = webdriver.Capability.SECURE_SSL; + capability = webdriver.Capability.SUPPORTS_APPLICATION_CACHE; + capability = webdriver.Capability.SUPPORTS_CSS_SELECTORS; + capability = webdriver.Capability.SUPPORTS_JAVASCRIPT; + capability = webdriver.Capability.SUPPORTS_LOCATION_CONTEXT; + capability = webdriver.Capability.TAKES_SCREENSHOT; + capability = webdriver.Capability.UNEXPECTED_ALERT_BEHAVIOR; + capability = webdriver.Capability.VERSION; +} + +function TestCommand() { + var command: webdriver.Command = new webdriver.Command(webdriver.CommandName.ADD_COOKIE); + + var name: string = command.getName(); + var param: any = command.getParameter('param'); + + var params: any = command.getParameters(); + + command = command.setParameter('param', 123); + command = command.setParameters({ param: 123 }); +} + +function TestDeferredExecutor() { + var promise: webdriver.promise.Promise; + var executor: webdriver.DeferredExecutor = new webdriver.DeferredExecutor(promise); +} + +function TestCommandName() { + var command: string; + + command = webdriver.CommandName.ACCEPT_ALERT; + command = webdriver.CommandName.ADD_COOKIE; + command = webdriver.CommandName.CLEAR_APP_CACHE; + command = webdriver.CommandName.CLEAR_ELEMENT; + command = webdriver.CommandName.CLEAR_LOCAL_STORAGE; + command = webdriver.CommandName.CLEAR_SESSION_STORAGE; + command = webdriver.CommandName.CLICK; + command = webdriver.CommandName.CLICK_ELEMENT; + command = webdriver.CommandName.CLOSE; + command = webdriver.CommandName.DELETE_ALL_COOKIES; + command = webdriver.CommandName.DELETE_COOKIE; + command = webdriver.CommandName.DESCRIBE_SESSION; + command = webdriver.CommandName.DISMISS_ALERT; + command = webdriver.CommandName.DOUBLE_CLICK; + command = webdriver.CommandName.ELEMENT_EQUALS; + command = webdriver.CommandName.EXECUTE_ASYNC_SCRIPT; + command = webdriver.CommandName.EXECUTE_SCRIPT; + command = webdriver.CommandName.EXECUTE_SQL; + command = webdriver.CommandName.FIND_CHILD_ELEMENT; + command = webdriver.CommandName.FIND_CHILD_ELEMENTS; + command = webdriver.CommandName.FIND_ELEMENT; + command = webdriver.CommandName.FIND_ELEMENTS; + command = webdriver.CommandName.GET; + command = webdriver.CommandName.GET_ACTIVE_ELEMENT; + command = webdriver.CommandName.GET_ALERT_TEXT; + command = webdriver.CommandName.GET_ALL_COOKIES; + command = webdriver.CommandName.GET_APP_CACHE; + command = webdriver.CommandName.GET_APP_CACHE_STATUS; + command = webdriver.CommandName.GET_AVAILABLE_LOG_TYPES; + command = webdriver.CommandName.GET_COOKIE; + command = webdriver.CommandName.GET_CURRENT_URL; + command = webdriver.CommandName.GET_CURRENT_WINDOW_HANDLE; + command = webdriver.CommandName.GET_ELEMENT_ATTRIBUTE; + command = webdriver.CommandName.GET_ELEMENT_LOCATION; + command = webdriver.CommandName.GET_ELEMENT_LOCATION_IN_VIEW; + command = webdriver.CommandName.GET_ELEMENT_SIZE; + command = webdriver.CommandName.GET_ELEMENT_TAG_NAME; + command = webdriver.CommandName.GET_ELEMENT_TEXT; + command = webdriver.CommandName.GET_ELEMENT_VALUE_OF_CSS_PROPERTY; + command = webdriver.CommandName.GET_LOCAL_STORAGE_ITEM; + command = webdriver.CommandName.GET_LOCAL_STORAGE_KEYS; + command = webdriver.CommandName.GET_LOCAL_STORAGE_SIZE; + command = webdriver.CommandName.GET_LOCATION; + command = webdriver.CommandName.GET_LOG; + command = webdriver.CommandName.GET_PAGE_SOURCE; + command = webdriver.CommandName.GET_SCREEN_ORIENTATION; + command = webdriver.CommandName.GET_SERVER_STATUS; + command = webdriver.CommandName.GET_SESSION_LOGS; + command = webdriver.CommandName.GET_SESSION_STORAGE_ITEM; + command = webdriver.CommandName.GET_SESSION_STORAGE_KEYS; + command = webdriver.CommandName.GET_SESSION_STORAGE_SIZE; + command = webdriver.CommandName.GET_SESSIONS; + command = webdriver.CommandName.GET_TITLE; + command = webdriver.CommandName.GET_WINDOW_HANDLES; + command = webdriver.CommandName.GET_WINDOW_POSITION; + command = webdriver.CommandName.GET_WINDOW_SIZE; + command = webdriver.CommandName.GO_BACK; + command = webdriver.CommandName.GO_FORWARD; + command = webdriver.CommandName.IMPLICITLY_WAIT; + command = webdriver.CommandName.IS_BROWSER_ONLINE; + command = webdriver.CommandName.IS_ELEMENT_DISPLAYED; + command = webdriver.CommandName.IS_ELEMENT_ENABLED; + command = webdriver.CommandName.IS_ELEMENT_SELECTED; + command = webdriver.CommandName.MAXIMIZE_WINDOW; + command = webdriver.CommandName.MOUSE_DOWN; + command = webdriver.CommandName.MOUSE_UP; + command = webdriver.CommandName.MOVE_TO; + command = webdriver.CommandName.NEW_SESSION; + command = webdriver.CommandName.QUIT; + command = webdriver.CommandName.REFRESH; + command = webdriver.CommandName.REMOVE_LOCAL_STORAGE_ITEM; + command = webdriver.CommandName.REMOVE_SESSION_STORAGE_ITEM; + command = webdriver.CommandName.SCREENSHOT; + command = webdriver.CommandName.SEND_KEYS_TO_ACTIVE_ELEMENT; + command = webdriver.CommandName.SEND_KEYS_TO_ELEMENT; + command = webdriver.CommandName.SET_ALERT_TEXT; + command = webdriver.CommandName.SET_BROWSER_ONLINE; + command = webdriver.CommandName.SET_LOCAL_STORAGE_ITEM; + command = webdriver.CommandName.SET_LOCATION; + command = webdriver.CommandName.SET_SCREEN_ORIENTATION; + command = webdriver.CommandName.SET_SCRIPT_TIMEOUT; + command = webdriver.CommandName.SET_SESSION_STORAGE_ITEM; + command = webdriver.CommandName.SET_TIMEOUT; + command = webdriver.CommandName.SET_WINDOW_POSITION; + command = webdriver.CommandName.SET_WINDOW_SIZE; + command = webdriver.CommandName.SUBMIT_ELEMENT; + command = webdriver.CommandName.SWITCH_TO_FRAME; + command = webdriver.CommandName.SWITCH_TO_WINDOW; + command = webdriver.CommandName.TOUCH_DOUBLE_TAP; + command = webdriver.CommandName.TOUCH_DOWN; + command = webdriver.CommandName.TOUCH_FLICK; + command = webdriver.CommandName.TOUCH_LONG_PRESS; + command = webdriver.CommandName.TOUCH_MOVE; + command = webdriver.CommandName.TOUCH_SCROLL; + command = webdriver.CommandName.TOUCH_SINGLE_TAP; + command = webdriver.CommandName.TOUCH_UP; +} + +function TestEventEmitter() { + var emitter: webdriver.EventEmitter = new webdriver.EventEmitter(); + + var callback = (a: number, b: number, c: number) => {}; + + emitter = emitter.addListener('ABC', callback); + emitter = emitter.addListener('ABC', callback, this); + + emitter.emit('ABC', 1, 2, 3); + + var listeners = emitter.listeners('ABC'); + if (listeners[0].oneshot) { + listeners[0].fn.apply(listeners[0].scope); + } + var length: number = listeners.length; + var listenerInfo = listeners[0]; + if (listenerInfo.oneshot) { + listenerInfo.fn.apply(listenerInfo.scope, [1, 2, 3]); + } + + emitter = emitter.on('ABC', callback); + emitter = emitter.on('ABC', callback, this); + + emitter = emitter.once('ABC', callback); + emitter = emitter.once('ABC', callback, this); + + emitter = emitter.removeListener('ABC', callback); + + emitter.removeAllListeners('ABC'); + emitter.removeAllListeners(); +} + +function TestKey() { + var key: string; + + key = webdriver.Key.ADD; + key = webdriver.Key.ALT; + key = webdriver.Key.ARROW_DOWN; + key = webdriver.Key.ARROW_LEFT; + key = webdriver.Key.ARROW_RIGHT; + key = webdriver.Key.ARROW_UP; + key = webdriver.Key.BACK_SPACE; + key = webdriver.Key.CANCEL; + key = webdriver.Key.CLEAR; + key = webdriver.Key.COMMAND; + key = webdriver.Key.CONTROL; + key = webdriver.Key.DECIMAL; + key = webdriver.Key.DELETE; + key = webdriver.Key.DIVIDE; + key = webdriver.Key.DOWN; + key = webdriver.Key.END; + key = webdriver.Key.ENTER; + key = webdriver.Key.EQUALS; + key = webdriver.Key.ESCAPE; + key = webdriver.Key.F1; + key = webdriver.Key.F2; + key = webdriver.Key.F3; + key = webdriver.Key.F4; + key = webdriver.Key.F5; + key = webdriver.Key.F6; + key = webdriver.Key.F7; + key = webdriver.Key.F8; + key = webdriver.Key.F9; + key = webdriver.Key.F10; + key = webdriver.Key.F11; + key = webdriver.Key.F12; + key = webdriver.Key.HELP; + key = webdriver.Key.HOME; + key = webdriver.Key.INSERT; + key = webdriver.Key.LEFT; + key = webdriver.Key.META; + key = webdriver.Key.MULTIPLY; + key = webdriver.Key.NULL; + key = webdriver.Key.NUMPAD0; + key = webdriver.Key.NUMPAD1; + key = webdriver.Key.NUMPAD2; + key = webdriver.Key.NUMPAD3; + key = webdriver.Key.NUMPAD4; + key = webdriver.Key.NUMPAD5; + key = webdriver.Key.NUMPAD6; + key = webdriver.Key.NUMPAD7; + key = webdriver.Key.NUMPAD8; + key = webdriver.Key.NUMPAD9; + key = webdriver.Key.PAGE_DOWN; + key = webdriver.Key.PAGE_UP; + key = webdriver.Key.PAUSE; + key = webdriver.Key.RETURN; + key = webdriver.Key.RIGHT; + key = webdriver.Key.SEMICOLON; + key = webdriver.Key.SEPARATOR; + key = webdriver.Key.SHIFT; + key = webdriver.Key.SPACE; + key = webdriver.Key.SUBTRACT; + key = webdriver.Key.TAB; + key = webdriver.Key.UP; +} + +function TestBy() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var locator: webdriver.By = new webdriver.By('class name', 'class'); + + var str: string = locator.toString(); + + locator = webdriver.By.className('class'); + locator = webdriver.By.css('css'); + locator = webdriver.By.id('id'); + locator = webdriver.By.linkText('link'); + locator = webdriver.By.name('name'); + locator = webdriver.By.partialLinkText('text'); + locator = webdriver.By.tagName('tag'); + locator = webdriver.By.xpath('xpath'); + + // Can import 'By' without import declarations + var By = webdriver.By; + + var locatorHash: webdriver.ByHash; + locatorHash = { className: 'class' }; + locatorHash = { css: 'css' }; + locatorHash = { id: 'id' }; + locatorHash = { linkText: 'link' }; + locatorHash = { name: 'name' }; + locatorHash = { partialLinkText: 'text' }; + locatorHash = { tagName: 'tag' }; + locatorHash = { xpath: 'xpath' }; + + webdriver.By.js('script', 1, 2, 3)(driver).then((abc: number) => {}); +} + +function TestSession() { + var session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android()); + var capabilitiesObj: any = {}; + capabilitiesObj[webdriver.Capability.BROWSER_NAME] = webdriver.Browser.ANDROID; + capabilitiesObj[webdriver.Capability.PLATFORM] = 'ANDROID'; + session = new webdriver.Session('ABC', capabilitiesObj); + + var capabilities: webdriver.Capabilities = session.getCapabilities(); + var capability: any = session.getCapability(webdriver.Capability.BROWSER_NAME); + var id: string = session.getId(); + var data: string = session.toJSON(); +} + +function TestUnhandledAlertError() { + var someFunc = (error: webdriver.UnhandledAlertError) => { + var baseError: Error = error; + var str: string = error.getAlertText(); + str = error.toString(); + }; +} + +function TestWebDriverFileDetector() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var fileDetector: webdriver.FileDetector = new webdriver.FileDetector(); + + fileDetector.handleFile(driver, 'path/to/file').then((path: string) => {}); +} + +function TestWebDriverLogs() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var logs: webdriver.Logs = new webdriver.Logs(driver); + + logs.get(webdriver.logging.Type.BROWSER).then((entries: webdriver.logging.Entry[]) => {}); + logs.getAvailableLogTypes().then((types: string[]) => {}); +} + +function TestWebDriverNavigation() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var navigation: webdriver.Navigation = new webdriver.Navigation(driver); + + navigation.back().then(() => {}); + navigation.forward().then(() => {}); + navigation.refresh().then(() => {}); + navigation.to('http://google.com').then(() => {}); +} + +function TestWebDriverOptions() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var options: webdriver.Options = new webdriver.Options(driver); + var promise: webdriver.promise.Promise; + + // Add Cookie + promise = options.addCookie('name', 'value'); + promise = options.addCookie('name', 'value', 'path'); + promise = options.addCookie('name', 'value', 'path', 'domain'); + promise = options.addCookie('name', 'value', 'path', 'domain', true); + promise = options.addCookie('name', 'value', 'path', 'domain', true, 123); + promise = options.addCookie('name', 'value', 'path', 'domain', true, Date.now()); + + promise = options.deleteAllCookies(); + promise = options.deleteCookie('name'); + options.getCookie('name').then((cookies: webdriver.IWebDriverOptionsCookie) => {}); + options.getCookies().then((cookies: webdriver.IWebDriverOptionsCookie[]) => {}); + + var logs: webdriver.Logs = options.logs(); + var timeouts: webdriver.Timeouts = options.timeouts(); + var window: webdriver.Window = options.window(); +} + +function TestWebDriverTargetLocator() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var locator: webdriver.TargetLocator = new webdriver.TargetLocator(driver); + var promise: webdriver.promise.Promise; + + var element: webdriver.WebElement = locator.activeElement(); + var alert: webdriver.Alert = locator.alert(); + promise = locator.defaultContent(); + promise = locator.frame(1); + promise = locator.window('nameOrHandle'); +} + +function TestWebDriverTimeouts() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var timeouts: webdriver.Timeouts = new webdriver.Timeouts(driver); + var promise: webdriver.promise.Promise; + + promise = timeouts.implicitlyWait(123); + promise = timeouts.pageLoadTimeout(123); + promise = timeouts.setScriptTimeout(123); +} + +function TestWebDriverWindow() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var window: webdriver.Window = new webdriver.Window(driver); + var locationPromise: webdriver.promise.Promise; + var sizePromise: webdriver.promise.Promise; + var voidPromise: webdriver.promise.Promise; + + locationPromise = window.getPosition(); + sizePromise = window.getSize(); + voidPromise = window.maximize(); + voidPromise = window.setPosition(12, 34); + voidPromise = window.setSize(12, 34); +} + +function TestWebDriver() { + var session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android()); + var sessionPromise: webdriver.promise.Promise; + var executor: webdriver.Executor = executors.createExecutor('http://someserver'); + var flow: webdriver.promise.ControlFlow = new webdriver.promise.ControlFlow(); + var driver: webdriver.WebDriver = new webdriver.WebDriver(session, executor); + driver = new webdriver.WebDriver(session, executor, flow); + driver = new webdriver.WebDriver(sessionPromise, executor); + driver = new webdriver.WebDriver(sessionPromise, executor, flow); + + var voidPromise: webdriver.promise.Promise; + var stringPromise: webdriver.promise.Promise; + var booleanPromise: webdriver.promise.Promise; + + var actions: webdriver.ActionSequence = driver.actions(); + var touchActions: webdriver.TouchSequence = driver.touchActions(); + + // call + stringPromise = driver.call(() => 'value'); + stringPromise = driver.call(() => stringPromise); + stringPromise = driver.call(() => { var d: any = this; return 'value'; }, driver); + stringPromise = driver.call((a: number) => 'value', driver, 1); + + voidPromise = driver.close(); + flow = driver.controlFlow(); + + // executeAsyncScript + stringPromise = driver.executeAsyncScript('function(){}'); + stringPromise = driver.executeAsyncScript('function(){}', 1, 2, 3); + stringPromise = driver.executeAsyncScript(() => {}); + stringPromise = driver.executeAsyncScript((a: number) => {}, 1); + + // executeScript + stringPromise = driver.executeScript('function(){}'); + stringPromise = driver.executeScript('function(){}', 1, 2, 3); + stringPromise = driver.executeScript(() => {}); + stringPromise = driver.executeScript((a: number) => {}, 1); + + // findElement + var element: webdriver.WebElement; + element = driver.findElement(webdriver.By.id('ABC')); + element = driver.findElement(webdriver.By.js('function(){}')); + + // findElements + driver.findElements(webdriver.By.className('ABC')).then((elements: webdriver.WebElement[]) => {}); + driver.findElements(webdriver.By.js('function(){}')).then((elements: webdriver.WebElement[]) => {}); + + voidPromise = driver.get('http://www.google.com'); + driver.getAllWindowHandles().then((handles: string[]) => {}); + driver.getCapabilities().then((caps: webdriver.Capabilities) => {}); + stringPromise = driver.getCurrentUrl(); + stringPromise = driver.getPageSource(); + driver.getSession().then((session: webdriver.Session) => {}); + stringPromise = driver.getTitle(); + stringPromise = driver.getWindowHandle(); + + booleanPromise = driver.isElementPresent(webdriver.By.className('ABC')); + booleanPromise = driver.isElementPresent(webdriver.By.js('function(){}')); + + var options: webdriver.Options = driver.manage(); + var navigation: webdriver.Navigation = driver.navigate(); + var locator: webdriver.TargetLocator = driver.switchTo(); + + var fileDetector: webdriver.FileDetector = new webdriver.FileDetector(); + driver.setFileDetector(fileDetector); + + voidPromise = driver.quit(); + voidPromise = driver.schedule(new webdriver.Command(webdriver.CommandName.CLICK), 'ABC'); + voidPromise = driver.sleep(123); + stringPromise = driver.takeScreenshot(); + + var booleanCondition: webdriver.until.Condition; + booleanPromise = driver.wait(booleanPromise); + booleanPromise = driver.wait(booleanCondition); + booleanPromise = driver.wait((driver: webdriver.WebDriver) => true); + let conditionFunction: Function; // tslint:disable-line:prefer-const + booleanPromise = driver.wait(conditionFunction); + booleanPromise = driver.wait(booleanPromise, 123); + booleanPromise = driver.wait(booleanPromise, 123, 'Message'); + + driver = webdriver.WebDriver.attachToSession(executor, 'ABC'); + driver = webdriver.WebDriver.createSession(executor, webdriver.Capabilities.android()); +} + +function TestSerializable() { + var serializable: webdriver.Serializable; + var serial: string | webdriver.promise.IThenable = serializable.serialize(); +} + +function TestWebElement() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var promise: webdriver.promise.Promise; + var element: webdriver.WebElement; + + element = new webdriver.WebElement(driver, 'elementId'); + element = new webdriver.WebElement(driver, promise); + + var voidPromise: webdriver.promise.Promise; + var stringPromise: webdriver.promise.Promise; + var booleanPromise: webdriver.promise.Promise; + + voidPromise = element.clear(); + voidPromise = element.click(); + + element = element.findElement(webdriver.By.id('ABC')); + element.findElements(webdriver.By.className('ABC')).then((elements: webdriver.WebElement[]) => {}); + booleanPromise = element.isElementPresent(webdriver.By.className('ABC')); + + stringPromise = element.getAttribute('class'); + stringPromise = element.getCssValue('display'); + driver = element.getDriver(); + stringPromise = element.getInnerHtml(); + element.getLocation().then((location: webdriver.ILocation) => {}); + stringPromise = element.getOuterHtml(); + element.getSize().then((size: webdriver.ISize) => {}); + stringPromise = element.getTagName(); + stringPromise = element.getText(); + booleanPromise = element.isDisplayed(); + booleanPromise = element.isEnabled(); + booleanPromise = element.isSelected(); + voidPromise = element.sendKeys('A', 'B', 'C'); + voidPromise = element.sendKeys(1, 2, 3); + voidPromise = element.sendKeys(webdriver.Key.BACK_SPACE); + voidPromise = element.sendKeys(stringPromise, stringPromise, stringPromise); + voidPromise = element.sendKeys('A', 1, webdriver.Key.BACK_SPACE, stringPromise); + voidPromise = element.submit(); + element.getId().then((id: string) => {}); + element.getRawId().then((id: string) => {}); + element.serialize().then((id: webdriver.IWebElementId) => {}); + + booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, 'elementId')); +} + +function TestWebElementPromise() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var elementPromise: webdriver.WebElementPromise = driver.findElement(webdriver.By.id('id')); + + elementPromise.cancel(); + elementPromise.cancel('reason'); + + var bool: boolean = elementPromise.isPending(); + + elementPromise.then(); + elementPromise.then((element: webdriver.WebElement) => {}); + elementPromise.then((element: webdriver.WebElement) => {}, (error: any) => {}); + elementPromise.then((element: webdriver.WebElement) => 'foo', (error: any) => {}).then((result: string) => {}); + + elementPromise.thenCatch((error: any) => {}).then((value: any) => {}); + + elementPromise.thenFinally(() => {}); +} + +function TestLogging() { + var preferences: webdriver.logging.Preferences = new webdriver.logging.Preferences(); + preferences.setLevel(webdriver.logging.Type.BROWSER, webdriver.logging.Level.ALL); + var prefs: any = preferences.toJSON(); + + var level: webdriver.logging.Level = webdriver.logging.getLevel('OFF'); + level = webdriver.logging.getLevel(1); + + level = webdriver.logging.Level.ALL; + level = webdriver.logging.Level.DEBUG; + level = webdriver.logging.Level.INFO; + level = webdriver.logging.Level.OFF; + level = webdriver.logging.Level.SEVERE; + level = webdriver.logging.Level.WARNING; + + var name: string = level.name; + var value: number = level.value; + + var type: string; + type = webdriver.logging.Type.BROWSER; + type = webdriver.logging.Type.CLIENT; + type = webdriver.logging.Type.DRIVER; + type = webdriver.logging.Type.PERFORMANCE; + type = webdriver.logging.Type.SERVER; +} + +function TestLoggingEntry() { + var entry: webdriver.logging.Entry; + + entry = new webdriver.logging.Entry(webdriver.logging.Level.ALL, 'ABC'); + entry = new webdriver.logging.Entry('ALL', 'ABC'); + entry = new webdriver.logging.Entry(webdriver.logging.Level.ALL, 'ABC', 123); + entry = new webdriver.logging.Entry('ALL', 'ABC', 123); + entry = new webdriver.logging.Entry(webdriver.logging.Level.ALL, 'ABC', 123, webdriver.logging.Type.BROWSER); + entry = new webdriver.logging.Entry('ALL', 'ABC', 123, webdriver.logging.Type.BROWSER); + + var entryObj: any = entry.toJSON(); + + var message: string = entry.message; + var timestamp: number = entry.timestamp; + var type: string = entry.type; +} + +function TestPromiseModule() { + var cancellationError: webdriver.promise.CancellationError = new webdriver.promise.CancellationError(); + cancellationError = new webdriver.promise.CancellationError('message'); + var str: string = cancellationError.message; + str = cancellationError.name; + + var stringPromise: webdriver.promise.Promise; + var numberPromise: webdriver.promise.Promise; + var booleanPromise: webdriver.promise.Promise; + var voidPromise: webdriver.promise.Promise; + + webdriver.promise.all([stringPromise]).then((values: string[]) => {}); + + webdriver.promise.asap('abc', (value: any) => true); + webdriver.promise.asap('abc', (value: any) => {}, (err: any) => 'ABC'); + + stringPromise = webdriver.promise.checkedNodeCall((err: any, value: any) => 'abc'); + + webdriver.promise.consume(() => { + return 5; + }).then((value: number) => {}); + webdriver.promise.consume(() => { + return 5; + }, this).then((value: number) => {}); + webdriver.promise.consume((a: number, b: number, c: number) => 5, this, 1, 2, 3) + .then((value: number) => {}); + + var numbersPromise: webdriver.promise.Promise = webdriver.promise.filter([1, 2, 3], (element: number, type: any, index: number, arr: number[]) => { + return true; + }); + numbersPromise = webdriver.promise.filter([1, 2, 3], (element: number, type: any, index: number, arr: number[]) => { + return true; + }, this); + numbersPromise = webdriver.promise.filter(numbersPromise, (element: number, type: any, index: number, arr: number[]) => { + return true; + }); + numbersPromise = webdriver.promise.filter(numbersPromise, (element: number, type: any, index: number, arr: number[]) => { + return true; + }, this); + + numbersPromise = webdriver.promise.map([1, 2, 3], (el: number, type: any, index: number, arr: number[]) => { + return true; + }); + numbersPromise = webdriver.promise.map([1, 2, 3], (el: number, type: any, index: number, arr: number[]) => { + return true; + }, this); + numbersPromise = webdriver.promise.map(numbersPromise, (el: number, type: any, index: number, arr: number[]) => { + return true; + }); + numbersPromise = webdriver.promise.map(numbersPromise, (el: number, type: any, index: number, arr: number[]) => { + return true; + }, this); + + var flow: webdriver.promise.ControlFlow = webdriver.promise.controlFlow(); + + stringPromise = webdriver.promise.createFlow((newFlow: webdriver.promise.ControlFlow) => 'ABC'); + + var deferred: webdriver.promise.Deferred; + deferred = webdriver.promise.defer(); + deferred = webdriver.promise.defer(); + + stringPromise = deferred.promise; + + deferred.fulfill('ABC'); + deferred.reject('error'); + + voidPromise = webdriver.promise.delayed(123); + + voidPromise = webdriver.promise.fulfilled(); + stringPromise = webdriver.promise.fulfilled('abc'); + + stringPromise = webdriver.promise.fullyResolved('abc'); + + var bool: boolean = webdriver.promise.isGenerator(() => {}); + var isPromise: boolean = webdriver.promise.isPromise('ABC'); + + stringPromise = webdriver.promise.rejected('{a: 123}'); + + webdriver.promise.setDefaultFlow(new webdriver.promise.ControlFlow()); + + numberPromise = webdriver.promise.when('abc', (value: any) => 123, (err: Error) => 123); +} + +function TestUntilModule() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var conditionB: webdriver.until.Condition = new webdriver.until.Condition('message', (driver: webdriver.WebDriver) => true); + var conditionBBase: webdriver.until.Condition = conditionB; + var conditionWebElement: webdriver.until.Condition; + var conditionWebElements: webdriver.until.Condition; + + conditionB = webdriver.until.ableToSwitchToFrame(5); + var conditionAlert: webdriver.until.Condition = webdriver.until.alertIsPresent(); + var el: webdriver.WebElement = driver.findElement(webdriver.By.id('id')); + conditionB = webdriver.until.elementIsDisabled(el); + conditionB = webdriver.until.elementIsEnabled(el); + conditionB = webdriver.until.elementIsNotSelected(el); + conditionB = webdriver.until.elementIsNotVisible(el); + conditionB = webdriver.until.elementIsSelected(el); + conditionB = webdriver.until.elementIsVisible(el); + conditionB = webdriver.until.elementTextContains(el, 'text'); + conditionB = webdriver.until.elementTextIs(el, 'text'); + conditionB = webdriver.until.elementTextMatches(el, /text/); + conditionB = webdriver.until.stalenessOf(el); + conditionB = webdriver.until.titleContains('text'); + conditionB = webdriver.until.titleIs('text'); + conditionB = webdriver.until.titleMatches(/text/); + + conditionWebElement = webdriver.until.elementLocated(webdriver.By.id('id')); + conditionWebElements = webdriver.until.elementsLocated(webdriver.By.className('class')); +} + +function TestControlFlow() { + var flow: webdriver.promise.ControlFlow; + flow = new webdriver.promise.ControlFlow(); + + var emitter: webdriver.EventEmitter = flow; + + var eventType: string; + + eventType = webdriver.promise.ControlFlow.EventType.IDLE; + eventType = webdriver.promise.ControlFlow.EventType.RESET; + eventType = webdriver.promise.ControlFlow.EventType.SCHEDULE_TASK; + eventType = webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION; + + var stringPromise: webdriver.promise.Promise; + stringPromise = flow.execute(() => 'value'); + stringPromise = flow.execute(() => stringPromise); + stringPromise = flow.execute(() => stringPromise, 'Description'); + + var schedule: string; + schedule = flow.toString(); + schedule = flow.getSchedule(); + schedule = flow.getSchedule(true); + + flow.reset(); + + var voidPromise: webdriver.promise.Promise = flow.timeout(123); + voidPromise = flow.timeout(123, 'Description'); + + stringPromise = flow.wait(stringPromise); + + voidPromise = flow.wait(() => true); + voidPromise = flow.wait(() => true, 123); + voidPromise = flow.wait(() => stringPromise, 123, 'Timeout Message'); +} + +function TestDeferred() { + var deferred: webdriver.promise.Deferred; + + deferred = new webdriver.promise.Deferred(); + deferred = new webdriver.promise.Deferred(new webdriver.promise.ControlFlow()); + + var promise: webdriver.promise.Promise = deferred.promise; + + deferred.errback(new Error('Error')); + deferred.errback('Error'); + deferred.fulfill('abc'); + deferred.reject(new Error('Error')); + deferred.reject('Error'); + deferred.removeAll(); +} + +function TestPromiseClass() { + var controlFlow: webdriver.promise.ControlFlow; + var promise: webdriver.promise.Promise; + promise = new webdriver.promise.Promise((resolve: (value: string) => void, reject: () => void) => {}); + promise = new webdriver.promise.Promise((resolve: (value: webdriver.promise.Promise) => void, reject: () => void) => {}); + promise = new webdriver.promise.Promise((resolve: (value: string) => void, reject: () => void) => {}, controlFlow); + + promise.cancel('Abort'); + + var isPending: boolean = promise.isPending(); + + promise = promise.then(); + promise = promise.then((a: string) => 'cde'); + promise = promise.then((a: string) => 'cde', (e: any) => {}); + promise = promise.then((a: string) => 'cde', (e: any) => 123); + + promise = promise.thenCatch((error: any) => {}); + + promise.thenFinally(() => {}); +} + +function TestThenableClass() { + var thenable: webdriver.promise.Promise = new webdriver.promise.Promise((resolve, reject) => { + resolve('a'); + }); + + thenable.cancel('Abort'); + + var isPending: boolean = thenable.isPending(); + + thenable = thenable.then((a: string) => 'cde'); + thenable = thenable.then((a: string) => 'cde', (e: any) => {}); + thenable = thenable.then((a: string) => 'cde', (e: any) => 123); + + thenable = thenable.thenCatch((error: any) => {}); + + thenable.thenFinally(() => {}); +} + +function TestErrorCode() { + var errorCode: number; + + errorCode = new webdriver.error.ElementNotSelectableError().code(); + errorCode = new webdriver.error.ElementNotVisibleError().code(); + errorCode = new webdriver.error.InvalidArgumentError().code(); + errorCode = new webdriver.error.InvalidCookieDomainError().code(); + errorCode = new webdriver.error.InvalidElementCoordinatesError().code(); + errorCode = new webdriver.error.InvalidElementStateError().code(); + errorCode = new webdriver.error.InvalidSelectorError().code(); + errorCode = new webdriver.error.NoSuchSessionError().code(); + errorCode = new webdriver.error.JavascriptError().code(); + errorCode = new webdriver.error.MoveTargetOutOfBoundsError().code(); + errorCode = new webdriver.error.NoSuchAlertError().code(); + errorCode = new webdriver.error.NoSuchElementError().code(); + errorCode = new webdriver.error.NoSuchFrameError().code(); + errorCode = new webdriver.error.NoSuchWindowError().code(); + errorCode = new webdriver.error.ScriptTimeoutError().code(); + errorCode = new webdriver.error.SessionNotCreatedError().code(); + errorCode = new webdriver.error.StaleElementReferenceError().code(); + errorCode = new webdriver.error.TimeoutError().code(); + errorCode = new webdriver.error.UnableToSetCookieError().code(); + errorCode = new webdriver.error.UnableToCaptureScreenError().code(); + errorCode = new webdriver.error.UnexpectedAlertOpenError().code(); + errorCode = new webdriver.error.UnknownCommandError().code(); + errorCode = new webdriver.error.UnknownMethodError().code(); + errorCode = new webdriver.error.UnsupportedOperationError().code(); +} + +async function TestAsyncAwaitable() { + var thenable: webdriver.promise.Promise = new webdriver.promise.Promise((resolve, reject) => resolve('foo')); + var str: string = await thenable; +} + +function TestTestingModule() { + testing.before(() => { + }); + + testing.beforeEach(() => { + }); + + testing.describe('My test suite', () => { + testing.it('My test', () => { + }); + + testing.iit('My exclusive test.', () => { + }); + + }); + + testing.xdescribe('My disabled suite', () => { + testing.xit('My disabled test.', () => { + }); + }); + + testing.after(() => { + }); + + testing.afterEach(() => { + }); +} diff --git a/selenium-webdriver/v2/test/remote.ts b/selenium-webdriver/v2/test/remote.ts new file mode 100644 index 0000000000..08722d5b1f --- /dev/null +++ b/selenium-webdriver/v2/test/remote.ts @@ -0,0 +1,13 @@ +/* tslint:disable */ + +import * as remote from "selenium-webdriver/remote"; +import * as webdriver from "selenium-webdriver"; + +function TestRemoteFileDetector() { + const driver: webdriver.WebDriver = new webdriver.Builder() + .withCapabilities(webdriver.Capabilities.chrome()) + .build(); + + const fileDetector: remote.FileDetector = new remote.FileDetector(); + fileDetector.handleFile(driver, 'path/to/file').then((path: string) => { /* empty */ }); +} diff --git a/selenium-webdriver/v2/testing.d.ts b/selenium-webdriver/v2/testing.d.ts new file mode 100644 index 0000000000..ec8e7123d7 --- /dev/null +++ b/selenium-webdriver/v2/testing.d.ts @@ -0,0 +1,60 @@ +/* tslint:disable */ +/** +* Registers a new test suite. +* @param name The suite name. +* @param fn The suite function, or {@code undefined} to define a pending test suite. +*/ +export function describe(name: string, fn: Function): void; + +/** + * Defines a suppressed test suite. + * @param name The suite name. + * @param fn The suite function, or {@code undefined} to define a pending test suite. + */ +export function xdescribe(name: string, fn: Function): void; + +/** + * Register a function to call after the current suite finishes. + * @param fn + */ +export function after(fn: Function): void; + +/** + * Register a function to call after each test in a suite. + * @param fn + */ +export function afterEach(fn: Function): void; + +/** + * Register a function to call before the current suite starts. + * @param fn + */ +export function before(fn: Function): void; + +/** + * Register a function to call before each test in a suite. + * @param fn + */ +export function beforeEach(fn: Function): void; + +/** + * Add a test to the current suite. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ +export function it(name: string, fn: Function): void; + +/** + * An alias for {@link #it()} that flags the test as the only one that should + * be run within the current suite. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ +export function iit(name: string, fn: Function): void; + +/** + * Adds a test to the current suite while suppressing it so it is not run. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ +export function xit(name: string, fn: Function): void; diff --git a/selenium-webdriver/v2/tsconfig.json b/selenium-webdriver/v2/tsconfig.json new file mode 100644 index 0000000000..2849e3669b --- /dev/null +++ b/selenium-webdriver/v2/tsconfig.json @@ -0,0 +1,40 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": false, + "strictNullChecks": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "selenium-webdriver": ["selenium-webdriver/v2"], + "selenium-webdriver/*": ["selenium-webdriver/v2/*"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "chrome.d.ts", + "edge.d.ts", + "executors.d.ts", + "firefox.d.ts", + "http.d.ts", + "ie.d.ts", + "opera.d.ts", + "remote.d.ts", + "safari.d.ts", + "testing.d.ts", + "test/index.ts", + "test/chrome.ts", + "test/firefox.ts", + "test/remote.ts" + ] +} \ No newline at end of file diff --git a/selenium-webdriver/v2/tslint.json b/selenium-webdriver/v2/tslint.json new file mode 100644 index 0000000000..ad51895c20 --- /dev/null +++ b/selenium-webdriver/v2/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "dt-header": false + } +} diff --git a/semver/index.d.ts b/semver/index.d.ts index a1ace1a134..60e7275f7a 100644 --- a/semver/index.d.ts +++ b/semver/index.d.ts @@ -1,186 +1,154 @@ -// Type definitions for semver v5.3.0 +// Type definitions for semver 5.3 // Project: https://github.com/npm/node-semver // Definitions by: Bart van der Schoor // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/semver -declare namespace SemVerModule { - /** - * Return the parsed version, or null if it's not valid. - */ - function valid(v: string, loose?: boolean): string; - /** - * Returns cleaned (removed leading/trailing whitespace, remove '=v' prefix) and parsed version, or null if version is invalid. - */ - function clean(version: string, loose?: boolean): string; - /** - * Return the version incremented by the release type (major, minor, patch, or prerelease), or null if it's not valid. - */ - function inc(v: string, release: string, loose?: boolean): string; - /** - * Return the major version number. - */ - function major(v: string, loose?: boolean): number; - /** - * Return the minor version number. - */ - function minor(v: string, loose?: boolean): number; - /** - * Return the patch version number. - */ - function patch(v: string, loose?: boolean): number; - /** - * Returns an array of prerelease components, or null if none exist. - */ - function prerelease(v: string, loose?: boolean): string[]; +export const SEMVER_SPEC_VERSION: "2.0.0"; - // Comparison - /** - * v1 > v2 - */ - function gt(v1: string, v2: string, loose?: boolean): boolean; - /** - * v1 >= v2 - */ - function gte(v1: string, v2: string, loose?: boolean): boolean; - /** - * v1 < v2 - */ - function lt(v1: string, v2: string, loose?: boolean): boolean; - /** - * v1 <= v2 - */ - function lte(v1: string, v2: string, loose?: boolean): boolean; - /** - * v1 == v2 This is true if they're logically equivalent, even if they're not the exact same string. You already know how to compare strings. - */ - function eq(v1: string, v2: string, loose?: boolean): boolean; - /** - * v1 != v2 The opposite of eq. - */ - function neq(v1: string, v2: string, loose?: boolean): boolean; - /** - * Pass in a comparison string, and it'll call the corresponding semver comparison function. "===" and "!==" do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided. - */ - function cmp(v1: string, comparator: any, v2: string, loose?: boolean): boolean; - /** - * Return 0 if v1 == v2, or 1 if v1 is greater, or -1 if v2 is greater. Sorts in ascending order if passed to Array.sort(). - */ - function compare(v1: string, v2: string, loose?: boolean): number; - /** - * The reverse of compare. Sorts an array of versions in descending order when passed to Array.sort(). - */ - function rcompare(v1: string, v2: string, loose?: boolean): number; - /** - * Returns difference between two versions by the release type (major, premajor, minor, preminor, patch, prepatch, or prerelease), or null if the versions are the same. - */ - function diff(v1: string, v2: string, loose?: boolean): string; +/** + * Return the parsed version, or null if it's not valid. + */ +export function valid(v: string, loose?: boolean): string; +/** + * Returns cleaned (removed leading/trailing whitespace, remove '=v' prefix) and parsed version, or null if version is invalid. + */ +export function clean(version: string, loose?: boolean): string; +/** + * Return the version incremented by the release type (major, minor, patch, or prerelease), or null if it's not valid. + */ +export function inc(v: string, release: string, loose?: boolean): string; +/** + * Return the major version number. + */ +export function major(v: string, loose?: boolean): number; +/** + * Return the minor version number. + */ +export function minor(v: string, loose?: boolean): number; +/** + * Return the patch version number. + */ +export function patch(v: string, loose?: boolean): number; +/** + * Returns an array of prerelease components, or null if none exist. + */ +export function prerelease(v: string, loose?: boolean): string[]; - // Ranges - /** - * Return the valid range or null if it's not valid - */ - function validRange(range: string, loose?: boolean): string; - /** - * Return true if the version satisfies the range. - */ - function satisfies(version: string, range: string, loose?: boolean): boolean; - /** - * Return the highest version in the list that satisfies the range, or null if none of them do. - */ - function maxSatisfying(versions: string[], range: string, loose?: boolean): string; - /** - * Return the lowest version in the list that satisfies the range, or null if none of them do. - */ - function minSatisfying(versions: string[], range: string, loose?: boolean): string; - /** - * Return true if version is greater than all the versions possible in the range. - */ - function gtr(version: string, range: string, loose?: boolean): boolean; - /** - * Return true if version is less than all the versions possible in the range. - */ - function ltr(version: string, range: string, loose?: boolean): boolean; - /** - * Return true if the version is outside the bounds of the range in either the high or low direction. The hilo argument must be either the string '>' or '<'. (This is the function called by gtr and ltr.) - */ - function outside(version: string, range: string, hilo: string, loose?: boolean): boolean; +// Comparison +/** + * v1 > v2 + */ +export function gt(v1: string, v2: string, loose?: boolean): boolean; +/** + * v1 >= v2 + */ +export function gte(v1: string, v2: string, loose?: boolean): boolean; +/** + * v1 < v2 + */ +export function lt(v1: string, v2: string, loose?: boolean): boolean; +/** + * v1 <= v2 + */ +export function lte(v1: string, v2: string, loose?: boolean): boolean; +/** + * v1 == v2 This is true if they're logically equivalent, even if they're not the exact same string. You already know how to compare strings. + */ +export function eq(v1: string, v2: string, loose?: boolean): boolean; +/** + * v1 != v2 The opposite of eq. + */ +export function neq(v1: string, v2: string, loose?: boolean): boolean; +/** + * Pass in a comparison string, and it'll call the corresponding semver comparison function. + * "===" and "!==" do simple string comparison, but are included for completeness. + * Throws if an invalid comparison string is provided. + */ +export function cmp(v1: string, comparator: any, v2: string, loose?: boolean): boolean; +/** + * Return 0 if v1 == v2, or 1 if v1 is greater, or -1 if v2 is greater. Sorts in ascending order if passed to Array.sort(). + */ +export function compare(v1: string, v2: string, loose?: boolean): number; +/** + * The reverse of compare. Sorts an array of versions in descending order when passed to Array.sort(). + */ +export function rcompare(v1: string, v2: string, loose?: boolean): number; +/** + * Returns difference between two versions by the release type (major, premajor, minor, preminor, patch, prepatch, or prerelease), or null if the versions are the same. + */ +export function diff(v1: string, v2: string, loose?: boolean): string; - class SemVerBase { - raw: string; - loose: boolean; - format(): string; - inspect(): string; - toString(): string; - } +// Ranges +/** + * Return the valid range or null if it's not valid + */ +export function validRange(range: string, loose?: boolean): string; +/** + * Return true if the version satisfies the range. + */ +export function satisfies(version: string, range: string, loose?: boolean): boolean; +/** + * Return the highest version in the list that satisfies the range, or null if none of them do. + */ +export function maxSatisfying(versions: string[], range: string, loose?: boolean): string; +/** + * Return the lowest version in the list that satisfies the range, or null if none of them do. + */ +export function minSatisfying(versions: string[], range: string, loose?: boolean): string; +/** + * Return true if version is greater than all the versions possible in the range. + */ +export function gtr(version: string, range: string, loose?: boolean): boolean; +/** + * Return true if version is less than all the versions possible in the range. + */ +export function ltr(version: string, range: string, loose?: boolean): boolean; +/** + * Return true if the version is outside the bounds of the range in either the high or low direction. + * The hilo argument must be either the string '>' or '<'. (This is the function called by gtr and ltr.) + */ +export function outside(version: string, range: string, hilo: string, loose?: boolean): boolean; - class SemVer extends SemVerBase { - constructor(version: string, loose?: boolean); +export class SemVer { + constructor(version: string, loose?: boolean); - major: number; - minor: number; - patch: number; - version: string; - build: string[]; - prerelease: string[]; + raw: string; + loose: boolean; + format(): string; + inspect(): string; - compare(other:SemVer): number; - compareMain(other:SemVer): number; - comparePre(other:SemVer): number; - inc(release: string): SemVer; - } + major: number; + minor: number; + patch: number; + version: string; + build: string[]; + prerelease: string[]; - class Comparator extends SemVerBase { - constructor(comp: string, loose?: boolean); - - semver: SemVer; - operator: string; - value: boolean; - parse(comp: string): void; - test(version:SemVer): boolean; - } - - class Range extends SemVerBase { - constructor(range: string, loose?: boolean); - - set: Comparator[][]; - parseRange(range: string): Comparator[]; - test(version: SemVer): boolean; - } + compare(other: SemVer): number; + compareMain(other: SemVer): number; + comparePre(other: SemVer): number; + inc(release: string): SemVer; } -interface SemVerStatic { - SemVer(version: string, loose?: boolean): SemVerModule.SemVer; - Comparator(comp: string, loose?: boolean): SemVerModule.Comparator; - Range(range: string, loose?: boolean): SemVerModule.Range; - clean(version: string, loose?: boolean): string; +export class Comparator { + constructor(comp: string, loose?: boolean); - SEMVER_SPEC_VERSION: string; - - valid(v: string, loose?: boolean): string; - inc(v: string, release: string, loose?: boolean): string; - major(v: string, loose?: boolean): number; - minor(v: string, loose?: boolean): number; - patch(v: string, loose?: boolean): number; - gt(v1: string, v2: string, loose?: boolean): boolean; - gte(v1: string, v2: string, loose?: boolean): boolean; - lt(v1: string, v2: string, loose?: boolean): boolean; - lte(v1: string, v2: string, loose?: boolean): boolean; - eq(v1: string, v2: string, loose?: boolean): boolean; - neq(v1: string, v2: string, loose?: boolean): boolean; - cmp(v1: string, comparator: any, v2: string, loose?: boolean): boolean; - compare(v1: string, v2: string, loose?: boolean): number; - rcompare(v1: string, v2: string, loose?: boolean): number; - diff(v1: string, v2: string, loose?: boolean): string; - validRange(range: string, loose?: boolean): string; - satisfies(version: string, range: string, loose?: boolean): boolean; - maxSatisfying(versions: string[], range: string, loose?: boolean): string; - gtr(version: string, range: string, loose?: boolean): boolean; - ltr(version: string, range: string, loose?: boolean): boolean; - outside(version: string, range: string, hilo: string, loose?: boolean): boolean; + semver: SemVer; + operator: string; + value: boolean; + parse(comp: string): void; + test(version: SemVer): boolean; } -declare var semver: SemVerStatic; +export class Range { + constructor(range: string, loose?: boolean); -declare module "semver" { - export = SemVerModule; + raw: string; + loose: boolean; + format(): string; + inspect(): string; + + set: Comparator[][]; + parseRange(range: string): Comparator[]; + test(version: SemVer): boolean; } diff --git a/semver/semver-tests.ts b/semver/semver-tests.ts index 62511ef425..f1be6ca533 100644 --- a/semver/semver-tests.ts +++ b/semver/semver-tests.ts @@ -1,56 +1,54 @@ +import * as semver from "semver"; +var obj: {}; +var bool: boolean; +var num: number; +var str: string; +var diff: string; +var x: any = null; +var arr: any[]; +var exp: RegExp; +var strArr: string[]; +var numArr: string[]; -var obj:Object; -var bool:boolean; -var num:number; -var str:string; -var diff:string; -var x:any = null; -var arr:any[]; -var exp:RegExp; -var strArr:string[]; -var numArr:string[]; +var v1: string, v2: string; +var version: string; +var versions: string[]; +var loose: boolean; -var mod:typeof SemVerModule; +str = semver.valid(str); +str = semver.clean(str); -var v1:string, v2:string; -var version:string; -var versions:string[]; -var loose:boolean; - -str = mod.valid(str); -str = mod.clean(str); - -str = mod.valid(str, loose); -str = mod.clean(str, loose); -str = mod.inc(str, str, loose); -num = mod.major(str, loose); -num = mod.minor(str, loose); -num = mod.patch(str, loose); -strArr = mod.prerelease(str, loose); +str = semver.valid(str, loose); +str = semver.clean(str, loose); +str = semver.inc(str, str, loose); +num = semver.major(str, loose); +num = semver.minor(str, loose); +num = semver.patch(str, loose); +strArr = semver.prerelease(str, loose); // Comparison -bool = mod.gt(v1, v2, loose); -bool = mod.gte(v1, v2, loose); -bool = mod.lt(v1, v2, loose); -bool = mod.lte(v1, v2, loose); -bool = mod.eq(v1, v2, loose); -bool = mod.neq(v1, v2, loose); -bool = mod.cmp(v1, x, v2, loose); -num = mod.compare(v1, v2, loose); -num = mod.rcompare(v1, v2, loose); -diff = mod.diff(v1, v2, loose); +bool = semver.gt(v1, v2, loose); +bool = semver.gte(v1, v2, loose); +bool = semver.lt(v1, v2, loose); +bool = semver.lte(v1, v2, loose); +bool = semver.eq(v1, v2, loose); +bool = semver.neq(v1, v2, loose); +bool = semver.cmp(v1, x, v2, loose); +num = semver.compare(v1, v2, loose); +num = semver.rcompare(v1, v2, loose); +diff = semver.diff(v1, v2, loose); // Ranges -str = mod.validRange(str, loose); -bool = mod.satisfies(version, str, loose); -str = mod.maxSatisfying(versions, str, loose); -str = mod.minSatisfying(versions, str, loose); -bool = mod.gtr(version, str, loose); -bool = mod.ltr(version, str, loose); -bool = mod.outside(version, str, str, loose); +str = semver.validRange(str, loose); +bool = semver.satisfies(version, str, loose); +str = semver.maxSatisfying(versions, str, loose); +str = semver.minSatisfying(versions, str, loose); +bool = semver.gtr(version, str, loose); +bool = semver.ltr(version, str, loose); +bool = semver.outside(version, str, str, loose); -var ver = new mod.SemVer(str, bool); +var ver = new semver.SemVer(str, bool); str = ver.raw; bool = ver.loose; str = ver.format(); @@ -70,11 +68,7 @@ num = ver.comparePre(ver); ver = ver.inc(str); -var comp = new SemVerModule.Comparator(str, bool); -str = comp.raw; -bool = comp.loose; -str = comp.format(); -str = comp.inspect(); +var comp = new semver.Comparator(str, bool); str = comp.toString(); ver = comp.semver; @@ -84,7 +78,7 @@ comp.parse(str); bool = comp.test(ver); -var range = new SemVerModule.Range(str, bool); +var range = new semver.Range(str, bool); str = range.raw; bool = range.loose; str = range.format(); @@ -93,65 +87,8 @@ str = range.toString(); bool = range.test(ver); -var sets:SemVerModule.Comparator[][]; +var sets: semver.Comparator[][]; sets = range.set; -var lims:SemVerModule.Comparator[]; +var lims: semver.Comparator[]; lims = range.parseRange(str); - -/** - * Test Static version - */ -var semver: SemVerStatic = semver; -var testString: string; -var testNumber: number; -var testBoolean: boolean; - -testString = semver.SEMVER_SPEC_VERSION; - -testString = semver.valid('v1.0.0'); -testString = semver.clean(' =v1.0.0 '); -testString = semver.valid('v1.0.0', true); -testString = semver.clean(' =v1.0.0 ', true); -testString = semver.inc('v1.0.0', 'major'); -testString = semver.inc('v1.0.0', 'major', true); -testNumber = semver.major('v1.0.0'); -testNumber = semver.major('v1.0.0', true); -testNumber = semver.minor('v1.0.0'); -testNumber = semver.minor('v1.0.0', true); -testNumber = semver.patch('v1.0.0'); -testNumber = semver.patch('v1.0.0', true); - -testBoolean = semver.gt('v1.0.0', 'v2.0.0'); -testBoolean = semver.gt('v1.0.0', 'v2.0.0', true); -testBoolean = semver.gte('v1.0.0', 'v2.0.0'); -testBoolean = semver.gte('v1.0.0', 'v2.0.0', true); -testBoolean = semver.lt('v1.0.0', 'v2.0.0'); -testBoolean = semver.lt('v1.0.0', 'v2.0.0', true); -testBoolean = semver.lte('v1.0.0', 'v2.0.0'); -testBoolean = semver.lte('v1.0.0', 'v2.0.0', true); -testBoolean = semver.eq('v1.0.0', 'v2.0.0'); -testBoolean = semver.eq('v1.0.0', 'v2.0.0', true); -testBoolean = semver.neq('v1.0.0', 'v2.0.0'); -testBoolean = semver.neq('v1.0.0', 'v2.0.0', true); -testBoolean = semver.cmp('v1.0.0', '===', 'v2.0.0'); -testBoolean = semver.cmp('v1.0.0', '!==', 'v2.0.0', true); -testNumber = semver.compare('v1.0.0', 'v2.0.0'); -testNumber = semver.compare('v1.0.0', 'v2.0.0', true); -testNumber = semver.rcompare('v1.0.0', 'v2.0.0'); -testNumber = semver.rcompare('v1.0.0', 'v2.0.0', true); -testString = semver.diff('v1.0.0', 'v2.0.0'); -testString = semver.diff('v1.0.0', 'v2.0.0', true); - -testString = semver.validRange('^1.0.0'); -testString = semver.validRange('^1.0.0', true); -testBoolean = semver.satisfies('v1.0.0', '^1.0.0'); -testBoolean = semver.satisfies('v1.0.0', '^1.0.0', true); -testString = semver.maxSatisfying(['v1.0.0', 'v2.0.0'], '^1.0.0'); -testString = semver.maxSatisfying(['v1.0.0', 'v2.0.0'], '^1.0.0', true); -testBoolean = semver.gtr('v1.0.0', '^1.0.0'); -testBoolean = semver.gtr('v1.0.0', '^1.0.0', true); -testBoolean = semver.ltr('v1.0.0', '^1.0.0'); -testBoolean = semver.ltr('v1.0.0', '^1.0.0', true); -testBoolean = semver.outside('v1.0.0', '^1.0.0', '<'); -testBoolean = semver.outside('v1.0.0', '^1.0.0', '>', true); diff --git a/semver/tslint.json b/semver/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/semver/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/sequelize/index.d.ts b/sequelize/index.d.ts index fda7cad2f5..e21d8f6f88 100644 --- a/sequelize/index.d.ts +++ b/sequelize/index.d.ts @@ -3183,7 +3183,7 @@ declare namespace sequelize { /** * A hash of attributes to describe your search. See above for examples. */ - where?: WhereOptions | Array
    ; + where?: WhereOptions | fn | Array; /** * A list of the attributes that you want to select. To rename an attribute, you can pass an array, with @@ -3671,7 +3671,7 @@ declare namespace sequelize { * @return Model A reference to the model, with the scope(s) applied. Calling scope again on the returned * model will clear the previous scope. */ - scope(options?: string | string[] | ScopeOptions | WhereOptions): this; + scope(options?: string | ScopeOptions | WhereOptions | Array): this; /** * Search for multiple instances. @@ -4876,6 +4876,11 @@ declare namespace sequelize { */ underscoredAll?: boolean; + /** + * Indicates if the model's table has a trigger associated with it. Default false. + */ + hasTrigger?: boolean; + /** * If freezeTableName is true, sequelize will not try to alter the DAO name to get the table name. * Otherwise, the dao name will be pluralized. Default false. @@ -5216,6 +5221,12 @@ declare namespace sequelize { */ transactionType?: string; + /** + * Print query execution time in milliseconds when logging SQL. + * + * Defaults to false + */ + benchmark?: boolean; } /** diff --git a/sequelize/sequelize-tests.ts b/sequelize/sequelize-tests.ts index 20af1246d4..ceff709a6b 100644 --- a/sequelize/sequelize-tests.ts +++ b/sequelize/sequelize-tests.ts @@ -853,11 +853,14 @@ User.schema( 'special' ).create( { age : 3 }, { logging : function( ) {} } ); User.getTableName(); User.addScope('lowAccess', { where : { parent_id : 2 } }); -User.addScope('lowAccess', function() { } ); User.addScope('lowAccess', { where : { parent_id : 2 } }, { override: true }); +User.addScope('lowAccessWithParam', function(id: number) { + return { where : { parent_id : id } } +} ); User.scope( 'lowAccess' ).count(); User.scope( { where : { parent_id : 2 } } ); +User.scope( [ 'lowAccess', { method: ['lowAccessWithParam', 2] }, { where : { parent_id : 2 } } ] ) User.findAll(); User.findAll( { where : { data : { employment : null } } } ); @@ -905,6 +908,7 @@ User.findAll( { attributes: [[s.fn('count', Sequelize.col('*')), 'count']] }); User.findAll( { attributes: [[s.fn('count', Sequelize.col('*')), 'count']], group: ['sex'] }); User.findAll( { attributes: [s.cast(s.fn('count', Sequelize.col('*')), 'INTEGER')] }); User.findAll( { attributes: [[s.cast(s.fn('count', Sequelize.col('*')), 'INTEGER'), 'count']] }); +User.findAll( { where : s.fn('count', [0, 10]) } ); User.findById( 'a string' ); @@ -925,6 +929,7 @@ User.findOne( { where : { name : 'worker' }, include : [User] } ); User.findOne( { where : { name : 'Boris' }, include : [User, { model : User, as : 'Photos' }] } ); User.findOne( { where : { username : 'someone' }, include : [User] } ); User.findOne( { where : { username : 'barfooz' }, raw : true } ); +User.findOne( { where : s.fn('count', []) } ); /* NOTE https://github.com/DefinitelyTyped/DefinitelyTyped/pull/5590 User.findOne( { updatedAt : { ne : null } } ); */ @@ -1534,6 +1539,27 @@ s.define( 'User', { paranoid : true } ); +s.define( 'TriggerTest', { + id : { + type : Sequelize.INTEGER, + field : 'test_id', + autoIncrement : true, + primaryKey : true, + validate : { + min : 1 + } + }, + title : { + allowNull : false, + type : Sequelize.STRING( 255 ), + field : 'test_title' + } +}, { + timestamps : false, + underscored : true, + hasTrigger : true +} ); + // // Transaction // ~~~~~~~~~~~~~ diff --git a/sequelize/v3/index.d.ts b/sequelize/v3/index.d.ts index 9142dc9a6c..f44fcbbd46 100644 --- a/sequelize/v3/index.d.ts +++ b/sequelize/v3/index.d.ts @@ -3648,7 +3648,7 @@ declare namespace sequelize { * @return Model A reference to the model, with the scope(s) applied. Calling scope again on the returned * model will clear the previous scope. */ - scope(options?: string | string[] | ScopeOptions | WhereOptions): this; + scope(options?: string | ScopeOptions | WhereOptions | Array): this; /** * Search for multiple instances. @@ -4843,6 +4843,11 @@ declare namespace sequelize { */ underscoredAll?: boolean; + /** + * Indicates if the model's table has a trigger associated with it. Default false. + */ + hasTrigger?: boolean; + /** * If freezeTableName is true, sequelize will not try to alter the DAO name to get the table name. * Otherwise, the dao name will be pluralized. Default false. @@ -5183,6 +5188,12 @@ declare namespace sequelize { */ transactionType?: string; + /** + * Print query execution time in milliseconds when logging SQL. + * + * Defaults to false + */ + benchmark?: boolean; } /** diff --git a/sequelize/v3/sequelize-tests.ts b/sequelize/v3/sequelize-tests.ts index 04a55062c8..83c4536a71 100644 --- a/sequelize/v3/sequelize-tests.ts +++ b/sequelize/v3/sequelize-tests.ts @@ -840,11 +840,14 @@ User.schema( 'special' ).create( { age : 3 }, { logging : function( ) {} } ); User.getTableName(); User.addScope('lowAccess', { where : { parent_id : 2 } }); -User.addScope('lowAccess', function() { } ); User.addScope('lowAccess', { where : { parent_id : 2 } }, { override: true }); +User.addScope('lowAccessWithParam', function(id: number) { + return { where : { parent_id : id } } +} ); User.scope( 'lowAccess' ).count(); User.scope( { where : { parent_id : 2 } } ); +User.scope( [ 'lowAccess', { method: ['lowAccessWithParam', 2] }, { where : { parent_id : 2 } } ] ) User.findAll(); User.findAll( { where : { data : { employment : null } } } ); @@ -1515,6 +1518,27 @@ s.define( 'User', { paranoid : true } ); +s.define( 'TriggerTest', { + id : { + type : Sequelize.INTEGER, + field : 'test_id', + autoIncrement : true, + primaryKey : true, + validate : { + min : 1 + } + }, + title : { + allowNull : false, + type : Sequelize.STRING( 255 ), + field : 'test_title' + } +}, { + timestamps : false, + underscored : true, + hasTrigger : true +} ); + // // Transaction // ~~~~~~~~~~~~~ diff --git a/service_worker_api/index.d.ts b/service_worker_api/index.d.ts index 715fc4efbe..3f7e07acaa 100644 --- a/service_worker_api/index.d.ts +++ b/service_worker_api/index.d.ts @@ -576,12 +576,90 @@ interface ServiceWorkerRegistration extends EventTarget { * before it is unregistered. */ unregister(): Promise; + + /** + * Returns a Promise that resolves to an array of Notification objects. + * @param [options] An options object that can contain options to filter the notifications returned. + */ + getNotifications(options?: ServiceWorkerGetNotificationOptions): Promise; // need to be replaced with `Notification[]` when possible + + /** + * Displays the notification with the requested title. + * @param [title] The title that must be shown within the notification + * @param [options] An object that allows to configure the notification. + */ + showNotification(title: string, options?: ServiceWorkerNotificationOptions): Promise; } +/** + * An options object to provide options upon a ServiceWorkerRegistration. + * @param [scope] A USVString representing a URL that defines a service worker's registration scope; what range of + * URLs a service worker can control. This is usually a relative URL, and it defaults to '/' when not specified. + */ interface ServiceWorkerRegisterOptions { scope: string; } +/** + * Action to display in a notification. + * @param [action] A DOMString identifying a user action to be displayed on the notification. + * @param [title] A DOMString containing action text to be shown to the user. + * @param [icon] A USVString containg the URL of an icon to display with the action. + */ +interface NotificationAction { // TODO: Maybe need to moved if NotificationApi types are defined + action: string; + title: string; + icon?: string; +} + +/** + * Object that allows to configure a notification. + * @param [actions] An array of actions to display in the notification. + * Appropriate responses are built using event.action within the notificationclick event. + * @param [badge] The URL of an image to represent the notification when there is not enough space to display the + * notification itself such as, for example, the Android Notification Bar. On Android devices, the badge should + * accommodate devices up to 4x resolution, about 96 by 96 px, and the image will be automatically masked. + * @param [body] A string representing an extra content to display within the notification. + * @param [dir] The direction of the notification; it can be auto, ltr, or rtl. + * @param [icon] The URL of an image to be used as an icon by the notification. + * @param [image] A USVSTring containing the URL of an image to be displayed in the notification. + * @param [lang] Specify the lang used within the notification. This string must be a valid BCP 47 language tag. + * @param [renotify] A boolean that indicates whether to supress vibrations and audible alerts when resusing a tag + * value. The default is false. + * @param [requireInteraction] Indicates that on devices with sufficiently large screens, a notification should remain + * active until the user clicks or dismisses it. If this value is absent or false, the desktop version of Chrome + * will auto-minimize notifications after approximately twenty seconds. The default value is false. + * @param [tag] An ID for a given notification that allows you to find, replace, or remove the notification using + * script if necessary. + * @param [vibrate] A vibration pattern to run with the display of the notification. A vibration pattern can be an + * array with as few as one member. The values are times in milliseconds where the even indices (0, 2, 4, etc.) indicate + * how long to vibrate and the odd indices indicate how long to pause. For example [300, 100, 400] would vibrate + * 300ms, pause 100ms, then vibrate 400ms. + * @param [data] Arbitrary data that you want associated with the notification. This can be of any data type. + */ +interface ServiceWorkerNotificationOptions { + actions?: NotificationAction[]; + badge?: string; + body?: string; + dir?: 'auto' | 'ltr' | 'rtl'; + icon?: string; + lang?: string; + renotify?: boolean; + requireInteraction?: boolean; + tag?: string; + vibrate?: number[]; + data?: any; +} + +/** + * An options object that can contain options to filter notifications. + * @param [tag] A DOMString representing a notification tag. If specified, only notifications that have this tag + * will be returned. + */ +interface ServiceWorkerGetNotificationOptions { + tag: string; +} + /** * Provides an object representing the service worker as an overall unit in the * network ecosystem, including facilities to register, unregister and update @@ -629,10 +707,6 @@ interface ServiceWorkerContainer extends EventTarget { * * @param scriptURL The URL of the service worker script. * @param [options] An options object to provide options upon registration. - * Currently available options are: scope: A USVString representing a URL - * that defines a service worker's registration scope; what range of URLs a - * service worker can control. This is usually a relative URL, and it - * defaults to '/' when not specified. */ register(scriptURL: string, options?: ServiceWorkerRegisterOptions): Promise; diff --git a/service_worker_api/service_worker_api-tests.ts b/service_worker_api/service_worker_api-tests.ts index 5cfae785cc..27c2b85c20 100644 --- a/service_worker_api/service_worker_api-tests.ts +++ b/service_worker_api/service_worker_api-tests.ts @@ -191,3 +191,16 @@ self.addEventListener('notificationclick', (event: NotificationEvent) => { return self.clients.openWindow('/'); })); }); + +navigator.serviceWorker.ready.then(function(registration) { + registration.showNotification('Notification Sample', { + body: 'This is a sample notification!', + icon: '/sw-test/star-wars-logo.jpg', + tag: 'notification-sample' + }); +}); + +self.registration.getNotifications({tag: 'notification-sample'}) + .then(function(notifications) { + console.log(notifications); + }); diff --git a/session-file-store/index.d.ts b/session-file-store/index.d.ts new file mode 100644 index 0000000000..f8238cf109 --- /dev/null +++ b/session-file-store/index.d.ts @@ -0,0 +1,287 @@ +// Type definitions for express session-file-store 1.0 +// Project: https://github.com/valery-barysok/session-file-store +// Definitions by: Gevik Babakhani +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +export = FileStore; + +declare namespace FileStore { + + /** + * FileStore Options + * + * @interface Options + */ + interface Options { + + /** + * The directory where the session files will be stored. Defaults to `./sessions` + * + * @type {string} + * @memberOf Options + */ + path?: string; + + /** + * Session time to live in seconds. Defaults to `3600` + * + * @type {number} + * @memberOf Options + */ + ttl?: number; + + /** + * The number of retries to get session data from a session file. Defaults to `5` + * + * @type {number} + * @memberOf Options + */ + retries?: number; + + /** + * The exponential factor to use for retry. Defaults to `1` + * + * @type {number} + * @memberOf Options + */ + factor?: number; + + /** + * The number of milliseconds before starting the first retry. Defaults to `50` + * + * @type {number} + * @memberOf Options + */ + minTimeout?: number; + + /** + * The maximum number of milliseconds between two retries. Defaults to `100` + * + * @type {number} + * @memberOf Options + */ + maxTimeout?: number; + + /** + * [OUT] Contains intervalObject if reap was scheduled + * + * @type {*} + * @memberOf Options + */ + reapIntervalObject?: any; + + /** + * Interval to clear expired sessions in seconds or -1 if do not need. Defaults to `1 hour` + * + * @type {number} + * @memberOf Options + */ + reapInterval?: number; + + /** + * Undocumented + * + * @type {number} + * @memberOf Options + */ + reapMaxConcurrent?: number; + + /** + * Use distinct worker process for removing stale sessions. Defaults to `false` + * + * @type {boolean} + * @memberOf Options + */ + reapAsync?: boolean; + + /** + * Reap stale sessions synchronously if can not do it asynchronously. Default to `false` + * + * @type {boolean} + * @memberOf Options + */ + reapSyncFallback?: boolean; + + /** + * Log messages. Defaults to `console.log` + * + * @type {Function} + * @memberOf Options + */ + logFn?: (...args: any[]) => void; + + /** + * Returns fallback session object after all failed retries. No defaults + * + * @type {Function} + * @memberOf Options + */ + fallbackSessionFn?: (...args: any[]) => void; + + /** + * Object-to-text text encoding. Can be null. Defaults to `'utf8'` + * + * @type {string} + * @memberOf Options + */ + encoding?: string; + + /** + * Encoding function. Takes object, returns encoded data. Defaults to `JSON.stringify` + * + * @type {Function} + * @memberOf Options + */ + encoder?: (...args: any[]) => void; + + /** + * Decoding function. Takes encoded data, returns object. Defaults to `JSON.parse` + * + * @type {Function} + * @memberOf Options + */ + decoder?: (...args: any[]) => void; + + /** + * If secret string is specified then enables encryption of the session before + * writing the file and also decryption when reading it. + * + * @type {string} + * @memberOf Options + */ + secret?: string; + + /** + * Encryption output encoding. Defaults to `'hex'` + * + * @type {string} + * @memberOf Options + */ + encryptEncoding?: string; + + /** + * File extension of saved files. Defaults to `'.json'` + * + * @type {string} + * @memberOf Options + */ + fileExtension?: string; + + /** + * Undocumented + * + * @type {RegExp} + * @memberOf Options + */ + filePattern?: RegExp; + + /** + * Encryption key retrieval function. Takes secret andsession id, returns key. + * Defaults to `function(secret, sessionId){return secret + sessionId;}` + * + * + * @memberOf Options + */ + keyFunction?: (secret: string, sessionId: string) => string; + } +} + +/** + * Session file store is a provision for storing session data in + * the session file + * + * @class FileStore + */ +declare class FileStore { + + /** + * Creates an instance of FileStore. + * @param {FileStore.Options} options + * + * @memberOf FileStore + */ + constructor(options: FileStore.Options); + + /** + * Attempts to fetch session from a session file by the given `sessionId` + * + * @param {string} sessionId + * @param {(err: any, session: Express.Session) => void} callback + * + * @memberOf FileStore + */ + get(sessionId: string, callback: (err: any, session: Express.Session) => void): void; + + /** + * Attempts to commit the given session associated with the given `sessionId` to a session file + * + * @param {string} sessionId + * @param {Express.Session} session + * @param {(err: any) => void} callback + * + * @memberOf FileStore + */ + set(sessionId: string, session: Express.Session, callback: (err: any) => void): void; + + /** + * Touch the given session object associated with the given `sessionId` + * + * @param {string} sessionId + * @param {Express.Session} session + * @param {(err: any) => void} callback + * + * @memberOf FileStore + */ + touch(sessionId: string, session: Express.Session, callback: (err: any) => void): void; + + /** + * Attempts to unlink a given session by its id + * + * @param {string} sessionId + * @param {(err: any) => void} callback + * + * @memberOf FileStore + */ + destroy(sessionId: string, callback: (err: any) => void): void; + + /** + * Attempts to fetch number of the session files + * + * @param {(err: any, length: number) => void} callback + * + * @memberOf FileStore + */ + length(callback: (err: any, length: number) => void): void; + + /** + * Attempts to clear out all of the existing session files + * + * @param {(err: any) => void} callback + * + * @memberOf FileStore + */ + clear(callback: (err: any) => void): void; + + /** + * + * + * @param {(err: any, files: Array) => void} callback + * + * @memberOf FileStore + */ + list(callback: (err: any, files: string[]) => void): void; + + /** + * Attempts to detect whether a session file is already expired or not + * + * @param {string} sessionId + * @param {(errr: any, isExpired: boolean) => void} callback + * + * @memberOf FileStore + */ + expired(sessionId: string, callback: (errr: any, isExpired: boolean) => void): void; + +} diff --git a/session-file-store/session-file-store-tests.ts b/session-file-store/session-file-store-tests.ts new file mode 100644 index 0000000000..b268aea8b0 --- /dev/null +++ b/session-file-store/session-file-store-tests.ts @@ -0,0 +1,14 @@ +import FileStore = require("session-file-store"); + +const options:FileStore.Options = { + path: "./tmp/sessions/", + logFn:function(a:string) { + + } +}; + +const sessionStore = new FileStore(options); + +sessionStore.list(function (err: any, file: Array) { + +}); diff --git a/session-file-store/tsconfig.json b/session-file-store/tsconfig.json new file mode 100644 index 0000000000..9fd97e3168 --- /dev/null +++ b/session-file-store/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "session-file-store-tests.ts" + ] +} diff --git a/session-file-store/tslint.json b/session-file-store/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/session-file-store/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/shelljs/shelljs-tests.ts b/shelljs/shelljs-tests.ts index 6c155e5aee..03f439af02 100644 --- a/shelljs/shelljs-tests.ts +++ b/shelljs/shelljs-tests.ts @@ -1,11 +1,5 @@ -// Tests for shelljs.d.ts -// Project: http://shelljs.org -// Definitions by: Niklas Mollenhauer -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Tests taken from documentation samples. -/// - import shell = require("shelljs"); if (!shell.which("git")) diff --git a/showdown/index.d.ts b/showdown/index.d.ts index e73405bfec..6ffaeaa1d1 100644 --- a/showdown/index.d.ts +++ b/showdown/index.d.ts @@ -255,6 +255,14 @@ declare namespace Showdown { * @param extensions */ removeExtension(extensions: ShowdownExtension[] | ShowdownExtension): void; + + /** + * Set a "local" flavor for THIS Converter instance + * + * @param flavor name + */ + setFlavor(name: string): void; + } interface ConverterStatic { @@ -353,4 +361,11 @@ declare namespace Showdown { * Reset extensions. */ function resetExtensions(): void; + + /** + * Setting a "global" flavor affects all instances of showdown + * + * @param name + */ + function setFlavor(name: string): void; } diff --git a/sinon-as-promised/index.d.ts b/sinon-as-promised/index.d.ts index ab75217011..5efe4df979 100644 --- a/sinon-as-promised/index.d.ts +++ b/sinon-as-promised/index.d.ts @@ -6,17 +6,22 @@ import * as s from "sinon"; declare module "sinon" { - interface SinonStub { - - /** - * When called, the stub will return a "thenable" object which will return a promise for the provided value. Any Promises/A+ compliant library will handle this object properly. - */ - resolves(value:any):SinonStub; - - /** - * When called, the stub will return a thenable which ill return a reject promise with the provided err. If err is a string, it will be set as the message on an Error object. - */ - rejects(err:any):SinonStub; - } + interface SinonStub { + /** + * Causes the stub to resolve with the provided value. + * + * @param value Resolve value. + * @remarks Any Promises/A+ compliant library will handle this object properly. + */ + resolves(value: T): SinonStub; + /** + * Causes the stub to reject with the provided error. + * + * @param error Rejection error. + * @returns A thenable which will return a rejected promise with the provided error. + * @remarks If error is a string, it will be set as the message on an Error object. + */ + rejects(error: any): SinonStub; + } } diff --git a/sinon-as-promised/sinon-as-promised-tests.ts b/sinon-as-promised/sinon-as-promised-tests.ts index 10602a3e8d..4663c1df12 100644 --- a/sinon-as-promised/sinon-as-promised-tests.ts +++ b/sinon-as-promised/sinon-as-promised-tests.ts @@ -1,5 +1,3 @@ -/// - function testResolve() { sinon.stub().resolves('test val'); } diff --git a/sinon-mongoose/sinon-mongoose-tests.ts b/sinon-mongoose/sinon-mongoose-tests.ts index b58a4e5e58..c64030240e 100644 --- a/sinon-mongoose/sinon-mongoose-tests.ts +++ b/sinon-mongoose/sinon-mongoose-tests.ts @@ -1,5 +1,3 @@ -/// - function testChain() { sinon.stub().chain('exec'); } diff --git a/sitemap2/index.d.ts b/sitemap2/index.d.ts new file mode 100644 index 0000000000..75108ff603 --- /dev/null +++ b/sitemap2/index.d.ts @@ -0,0 +1,52 @@ +// Type definitions for sitemap2 1.0 +// Project: https://github.com/vlkosinov/sitemap2 +// Definitions by: Yuichi Shundo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare var sitemap2: Sitemap; + +export = sitemap2; + +declare interface Sitemap { + new (conf?: SitemapConfig): Sitemap; + + addUrl(urlData: UrlData | UrlData[] | string | string[]): this + addSitemap(sm: Sitemap): this; + toXML(): SitemapXml[]; + + hostName: string; + fileName: string; + limit: number; + urls: string[]; + childrens: Sitemap[]; +} + +declare interface SitemapConfig { + hostName?: string; + fileName?: string; + limit?: number; + cacheTime?: number; + xslUrl?: string; + urls?: string[]; + childrens?: Sitemap[]; +} + +declare interface UrlData { + url: string; + chengefreq?: string; + priority?: number | string; + lastmod?: Date; + lastmodWithTime?: boolean; + lastmodInISO?: boolean; + video?: { + title: string; + description: string; + thumbnail_loc: string; + content_loc: string; + } +} + +declare interface SitemapXml { + fileName: string; + xml: string; +} diff --git a/sitemap2/sitemap2-tests.ts b/sitemap2/sitemap2-tests.ts new file mode 100644 index 0000000000..235cbb93a4 --- /dev/null +++ b/sitemap2/sitemap2-tests.ts @@ -0,0 +1,51 @@ +import Sitemap = require('sitemap2'); + +let sitemap = new Sitemap({ + hostName: ('https://example.com/'), + fileName: 'sitemap.xml', + limit: 50000, + cacheTime: 1000, +}); + +sitemap.addUrl('https://example.com/'); +sitemap.addUrl(['https://example.com/']); +sitemap.addUrl({ + url: 'https://example.com/', + chengefreq: 'chengefreq', + priority: 0.6, + lastmod: new Date(), + lastmodWithTime: true, + lastmodInISO: false, + video: { + title: 'title', + description: 'description', + content_loc: 'content_loc', + thumbnail_loc: 'thumbnail_loc' + }, +}); +sitemap.addUrl([ + { + url: 'https://example.com/', + chengefreq: 'chengefreq', + priority: 0.6, + lastmod: new Date(), + lastmodWithTime: true, + lastmodInISO: false, + video: { + title: 'title', + description: 'description', + content_loc: 'content_loc', + thumbnail_loc: 'thumbnail_loc' + }, + }, + { + url: 'http://example.com/' + } +]); + +let sitemap2 = new Sitemap(); +sitemap.addSitemap(sitemap2); + +const xmlList = sitemap.toXML(); +var str = xmlList[0].fileName; +var str = xmlList[0].xml; diff --git a/sitemap2/tsconfig.json b/sitemap2/tsconfig.json new file mode 100644 index 0000000000..6fd2aba277 --- /dev/null +++ b/sitemap2/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sitemap2-tests.ts" + ] +} \ No newline at end of file diff --git a/sitemap2/tslint.json b/sitemap2/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/sitemap2/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/slick-carousel/slick-carousel-tests.ts b/slick-carousel/slick-carousel-tests.ts index 5cb75a619d..3cf05a2e0c 100644 --- a/slick-carousel/slick-carousel-tests.ts +++ b/slick-carousel/slick-carousel-tests.ts @@ -1,7 +1,3 @@ -/// -/// - - // -------------------------------------------------------- // ------------------- WEBSITE EXAMPLE -------------------- // ---------- http://kenwheeler.github.io/slick/ ---------- diff --git a/slickgrid/test/index.ts b/slickgrid/test/index.ts index e6570c2985..d87bc2240c 100644 --- a/slickgrid/test/index.ts +++ b/slickgrid/test/index.ts @@ -1,6 +1,3 @@ -/// - - interface MyData extends Slick.SlickData { title: string; duration: string; diff --git a/soap/index.d.ts b/soap/index.d.ts index 151e914f63..eda277d575 100644 --- a/soap/index.d.ts +++ b/soap/index.d.ts @@ -49,4 +49,31 @@ export interface Server extends events.EventEmitter { log(type: any, data: any): any; } export function listen(server: any, path: string, service: any, wsdl: string): Server; -declare function createClient(wsdlPath: string, options: any, fn: (err: any, client: Client) => void): void; +declare function createClient(wsdlPath: string, options: Option, fn: (err: any, client: Client) => void): void; + +export interface Option { + attributesKey?: string; + disableCache?: boolean; + endpoint?: string; + envelopeKey?: string; + escapeXML?: boolean; + forceSoap12Headers?: boolean; + httpClient?: HttpClient; + ignoreBaseNameSpaces?: boolean, + ignoredNamespaces?: string[] | {namespaces: string[], override: boolean}; + overrideRootElement?: {namespace: string, xmlnsAttributes?: string[]}; + request?: (options: any, callback?: (error: any, res: any, body: any) => void) => void; + stream?: boolean; + valueKey?: string; + wsdl_headers?: { [key: string]: any }; + wsdl_options?: { [key: string]: any }; + xmlKey?: string; +} + +export class HttpClient { + constructor(options?: Option); + buildRequest(rurl: string, data: any | string, exheaders?: { [key: string]: any }, exoptions?: { [key: string]: any }): any; + handleResponse(req: any, res: any, body: any | string): any | string; + request(rurl: string, data: any | string, callback: (err: any, res: any, body: any | string) => void, exheaders?: { [key: string]: any }, exoptions?: { [key: string]: any }): any; + requestStream(rurl: string, data: any | string, exheaders?: { [key: string]: any }, exoptions?: { [key: string]: any }): any; +} diff --git a/soap/soap-tests.ts b/soap/soap-tests.ts index 9771b26efc..f07346988e 100644 --- a/soap/soap-tests.ts +++ b/soap/soap-tests.ts @@ -1,10 +1,27 @@ import * as soap from 'soap'; import * as events from 'events'; -import * as fs from "fs"; -import * as http from "http"; +import * as fs from 'fs'; +import * as http from 'http'; const url = 'http://example.com/wsdl?wsdl'; -const wsdlOptions = { name: 'value' }; +// wsdlOptions set only default values +const wsdlOptions = { + attributesKey: 'attributes', + disableCache: false, + endpoint: url, + envelopeKey: 'soap', + escapeXML: true, + forceSoap12Headers: false, + httpClient: new soap.HttpClient(), + ignoreBaseNameSpaces: false, + ignoredNamespaces: ['tns', 'targetNamespace', 'typedNamespace'], + request: require('request'), + stream: false, + wsdl_headers: [], + wsdl_options: [], + valueKey: '$value', + xmlKey: '$xml' +}; soap.createClient(url, wsdlOptions, function(err: any, client: soap.Client) { let securityOptions = { hasTimeStamp: false }; @@ -74,7 +91,7 @@ var myService = { var xml = fs.readFileSync('myservice.wsdl', 'utf8'), server = http.createServer(function(request,response) { - response.end("404: Not Found: " + request.url); + response.end('404: Not Found: ' + request.url); }); server.listen(8000); diff --git a/socket.io-redis/socket.io-redis-tests.ts b/socket.io-redis/socket.io-redis-tests.ts index 28b0f9873f..6ced0b31de 100644 --- a/socket.io-redis/socket.io-redis-tests.ts +++ b/socket.io-redis/socket.io-redis-tests.ts @@ -1,5 +1,3 @@ -/// - import socketIO = require('socket.io'); import ioRedis = require('socket.io-redis'); import redis = require('redis'); diff --git a/socket.io.users/socket.io.users-tests.ts b/socket.io.users/socket.io.users-tests.ts index 565f6a7d7b..24557ef6c5 100644 --- a/socket.io.users/socket.io.users-tests.ts +++ b/socket.io.users/socket.io.users-tests.ts @@ -1,7 +1,3 @@ -/// - -/// - var express = require('express'); var app = express(); var httpServer = require('http').createServer(app); diff --git a/source-list-map/source-list-map-tests.ts b/source-list-map/source-list-map-tests.ts index 5fe932efc5..8c367d582c 100644 --- a/source-list-map/source-list-map-tests.ts +++ b/source-list-map/source-list-map-tests.ts @@ -1,4 +1,3 @@ -/// import * as slm from 'source-list-map'; const node = new slm.CodeNode('hello'); diff --git a/spatialite/tsconfig.json b/spatialite/tsconfig.json index ddcef0c7ac..a432ff2004 100644 --- a/spatialite/tsconfig.json +++ b/spatialite/tsconfig.json @@ -19,4 +19,4 @@ "index.d.ts", "spatialite-tests.ts" ] -} \ No newline at end of file +} diff --git a/spectrum/spectrum-tests.ts b/spectrum/spectrum-tests.ts index e9bf388bbe..e52bd36ce9 100644 --- a/spectrum/spectrum-tests.ts +++ b/spectrum/spectrum-tests.ts @@ -1,6 +1,3 @@ -/// - - $("#picker").spectrum(); $("#picker").spectrum({ diff --git a/split/split-tests.ts b/split/split-tests.ts index 204a044b68..98308fbc10 100644 --- a/split/split-tests.ts +++ b/split/split-tests.ts @@ -1,6 +1,3 @@ - -/// - import stream = require("stream"); import split = require("split"); diff --git a/sql.js/sql.js-tests.ts b/sql.js/sql.js-tests.ts index 0829f7692a..52f44c7438 100644 --- a/sql.js/sql.js-tests.ts +++ b/sql.js/sql.js-tests.ts @@ -1,6 +1,3 @@ -/// - - import fs = require("fs"); import * as SQL from "sql.js"; diff --git a/ss-utils/ss-utils-tests.ts b/ss-utils/ss-utils-tests.ts index 71934fed54..9bbd30da9a 100644 --- a/ss-utils/ss-utils-tests.ts +++ b/ss-utils/ss-utils-tests.ts @@ -1,6 +1,3 @@ -/// - - declare var EventSource : ssutils.IEventSourceStatic; function test_ssutils() { @@ -13,7 +10,7 @@ function test_ssutils() { onHeartbeat: function(msg:ssutils.SSEHeartbeat, e:MessageEvent){}, onJoin: function(msg:ssutils.SSEJoin) {}, onLeave: function(msg:ssutils.SSELeave) {}, - onUpdate: function(msg:ssutils.SSEUpdate) {} + onUpdate: function(msg:ssutils.SSEUpdate) {} }, receivers: { tv: { @@ -26,7 +23,7 @@ function test_ssutils() { announce: function (msg:string) {} }) .on('customEvent', function (e, msg, msgEvent) { }); - + $.ss.handlers["changeChannel"]("home"); } @@ -39,7 +36,7 @@ function test_jQuery_functions(){ overrideMessages: true, messages: {"NotFound": "Not Found"}, errorFilter: function(errorMsg, errorCode, type){} - }); + }); $("form").applyValues({ "Key": "Value" }); @@ -58,8 +55,8 @@ 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"}); @@ -69,7 +66,7 @@ function test_ssutils_Static(){ $.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) {}); - + $.ss.listenOn = "click onmousedown"; $.ss.eventReceivers = { "document": document }; $.ss.handlers["changeChannel"]("home"); diff --git a/static-eval/static-eval-tests.ts b/static-eval/static-eval-tests.ts index d4307c50f4..bfe30f723f 100644 --- a/static-eval/static-eval-tests.ts +++ b/static-eval/static-eval-tests.ts @@ -1,5 +1,3 @@ -/// - import evaluate = require('static-eval'); import esprima = require('esprima'); import * as ESTree from 'estree'; diff --git a/steed/tslint.json b/steed/tslint.json index f05741c59b..0f47deabb4 100644 --- a/steed/tslint.json +++ b/steed/tslint.json @@ -3,4 +3,4 @@ "rules": { "forbidden-types": false } -} +} \ No newline at end of file diff --git a/stream-buffers/index.d.ts b/stream-buffers/index.d.ts new file mode 100644 index 0000000000..d3871b1efa --- /dev/null +++ b/stream-buffers/index.d.ts @@ -0,0 +1,40 @@ +// Type definitions for stream-buffers 3.0 +// Project: https://github.com/samcday/node-stream-buffer#readme +// Definitions by: Jason Dent +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import * as stream from 'stream'; + +export interface WritableStreamBufferOptions extends stream.WritableOptions { + initialSize?: number; + incrementAmount?: number; +} + +export declare class WritableStreamBuffer extends stream.Writable { + constructor(options?: WritableStreamBufferOptions); + size(): number; + maxSize(): number; + getContents(length?: number): any; + getContentsAsString(encoding?: string, length?: number): string; +} + +export interface ReadableStreamBufferOptions extends stream.ReadableOptions { + frequency?: number; + chunkSize?: number; + initialSize?: number; + incrementAmount?: number; +} + +export declare class ReadableStreamBuffer extends stream.Readable { + constructor(options?: ReadableStreamBufferOptions); + put(data: string | Buffer, encoding?: string): void; + stop(): void; + size(): number; + maxSize(): number; +} + +export declare const DEFAULT_INITIAL_SIZE: number; +export declare const DEFAULT_INCREMENT_AMOUNT: number; +export declare const DEFAULT_FREQUENCY: number; +export declare const DEFAULT_CHUNK_SIZE: number; diff --git a/stream-buffers/stream-buffers-tests.ts b/stream-buffers/stream-buffers-tests.ts new file mode 100644 index 0000000000..7bccc43f15 --- /dev/null +++ b/stream-buffers/stream-buffers-tests.ts @@ -0,0 +1,48 @@ +import * as streamBuffers from 'stream-buffers'; + +// The following are examples from README.md +// https://github.com/samcday/node-stream-buffer + +var myWritableStreamBuffer = new streamBuffers.WritableStreamBuffer({ + initialSize: (100 * 1024), // start at 100 kilobytes. + incrementAmount: (10 * 1024) // grow by 10 kilobytes each time buffer overflows. +}); + +var a = streamBuffers.DEFAULT_INITIAL_SIZE; // (8 * 1024) +var b = streamBuffers.DEFAULT_INCREMENT_AMOUNT; // (8 * 1024) +var c = streamBuffers.DEFAULT_CHUNK_SIZE; // (1024) +var d = streamBuffers.DEFAULT_FREQUENCY; // (1) + +const buffer = new Buffer('ASDF'); +myWritableStreamBuffer.write('ASDF'); +myWritableStreamBuffer.write(buffer); +myWritableStreamBuffer.size(); +myWritableStreamBuffer.maxSize(); + +// Gets all held data as a Buffer. +myWritableStreamBuffer.getContents(); + +// Gets all held data as a utf8 string. +myWritableStreamBuffer.getContentsAsString('utf8'); + +// Gets first 5 bytes as a Buffer. +myWritableStreamBuffer.getContents(5); + +// Gets first 5 bytes as a utf8 string. +myWritableStreamBuffer.getContentsAsString('utf8', 5); + +var myReadableStreamBuffer = new streamBuffers.ReadableStreamBuffer({ + frequency: 10, // in milliseconds. + chunkSize: 2048 // in bytes. +}); + +myReadableStreamBuffer.put('A String', 'utf8'); +myReadableStreamBuffer.put(buffer); + +myReadableStreamBuffer.on('data', (data) => { + // streams1.x style data + // assert.isTrue(data instanceof Buffer); +}); + +myReadableStreamBuffer.put('the last data this stream will ever see'); +myReadableStreamBuffer.stop(); diff --git a/stream-buffers/tsconfig.json b/stream-buffers/tsconfig.json new file mode 100644 index 0000000000..827ea2a3fe --- /dev/null +++ b/stream-buffers/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "stream-buffers-tests.ts" + ] +} diff --git a/stream-buffers/tslint.json b/stream-buffers/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/stream-buffers/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/stream-to-array/stream-to-array-tests.ts b/stream-to-array/stream-to-array-tests.ts index c011f3e542..6b3ccc84fb 100644 --- a/stream-to-array/stream-to-array-tests.ts +++ b/stream-to-array/stream-to-array-tests.ts @@ -1,6 +1,3 @@ - -/// - import toArray = require('stream-to-array'); var rs: NodeJS.ReadableStream; diff --git a/stringify-object/index.d.ts b/stringify-object/index.d.ts new file mode 100644 index 0000000000..bfccb83300 --- /dev/null +++ b/stringify-object/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for stringify-object 3.1 +// Project: https://github.com/yeoman/stringify-object +// Definitions by: Chris Khoo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace stringifyObject { } + +declare function stringifyObject(o: any, options?: { + indent?: string, + singleQuotes?: boolean, + filter?: (o: any, prop: string) => boolean, + inlineCharacterLimit?: number +}): string; + +export = stringifyObject; diff --git a/stringify-object/stringify-object-tests.ts b/stringify-object/stringify-object-tests.ts new file mode 100644 index 0000000000..a00be6f1c0 --- /dev/null +++ b/stringify-object/stringify-object-tests.ts @@ -0,0 +1,26 @@ +import * as stringifyObject from 'stringify-object'; + +stringifyObject({ a: 1, b: 2, c: 3 }); + +stringifyObject('abc', { + indent: ' ' +}); + +stringifyObject('123', { + indent: ' ' +}); + +stringifyObject(123, { + indent: ' ', + singleQuotes: false +}); + +stringifyObject([1, 2, 3], { + indent: ' ', + singleQuotes: false, + inlineCharacterLimit: 12 +}); + +stringifyObject([1, 2, 3], { + filter: (o, prop) => prop !== '_hidden_' +}); diff --git a/stringify-object/tsconfig.json b/stringify-object/tsconfig.json new file mode 100644 index 0000000000..00574d2429 --- /dev/null +++ b/stringify-object/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "stringify-object-tests.ts" + ] +} diff --git a/stringify-object/tslint.json b/stringify-object/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/stringify-object/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/strong-cluster-control/tsconfig.json b/strong-cluster-control/tsconfig.json index 6d625c44b6..9294ca211a 100644 --- a/strong-cluster-control/tsconfig.json +++ b/strong-cluster-control/tsconfig.json @@ -19,4 +19,4 @@ "index.d.ts", "strong-cluster-control-tests.ts" ] -} \ No newline at end of file +} diff --git a/stylelint/index.d.ts b/stylelint/index.d.ts new file mode 100644 index 0000000000..2ec479d2e1 --- /dev/null +++ b/stylelint/index.d.ts @@ -0,0 +1,44 @@ +// Type definitions for stylelint 7.9 +// Project: https://github.com/stylelint/stylelint +// Definitions by: Alan Agius +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface LinterOptions { + code?: string; + codeFilename?: string; + config?: JSON; + configBasedir?: string; + configFile?: string; + configOverrides?: JSON; + files?: string | string[]; + formatter?: "json" | "string" | "verbose"; + ignoreDisables?: boolean; + reportNeedlessDisables?: boolean; + ignorePath?: boolean; + syntax?: "scss" | "less" | "sugarss"; + customSyntax?: string; +} + +export interface LinterResult { + errored: boolean; + output: string; + postcssResults: any[]; + results: LintResult[]; +} + +export interface LintResult { + source: string; + errored: boolean | undefined; + ignored: boolean | undefined; + warnings: string[]; + deprecations: string[]; + invalidOptionWarnings: any[]; +} + +export namespace formatters { + function json(results: LintResult[]): string; + function string(results: LintResult[]): string; + function verbose(results: LintResult[]): string; +} + +export function lint(options?: LinterOptions): Promise; diff --git a/stylelint/stylelint-tests.ts b/stylelint/stylelint-tests.ts new file mode 100644 index 0000000000..0eeb0bdec8 --- /dev/null +++ b/stylelint/stylelint-tests.ts @@ -0,0 +1,18 @@ +import { LinterOptions, lint, LintResult, LinterResult } from "stylelint"; + +const options: LinterOptions = { + code: "div { color: red }", + files: ["**/**.scss"], + formatter: "json", + ignoreDisables: true, + reportNeedlessDisables: true, + ignorePath: true, + syntax: "scss" +}; + +lint(options).then((x: LinterResult) => { + const err: boolean = x.errored; + const output: string = x.output; + const postcssResults: any[] = x.postcssResults; + const results: LintResult[] = x.results; +}); diff --git a/stylelint/tsconfig.json b/stylelint/tsconfig.json new file mode 100644 index 0000000000..d57b85c2b3 --- /dev/null +++ b/stylelint/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "stylelint-tests.ts" + ] +} diff --git a/stylus/stylus-tests.ts b/stylus/stylus-tests.ts index 7c5a8b1e45..248b6a9a04 100644 --- a/stylus/stylus-tests.ts +++ b/stylus/stylus-tests.ts @@ -1,13 +1,9 @@ -/** - * Test suite created by Maxime LUCE - * +/** + * Test suite created by Maxime LUCE + * * Created by using code samples from https://github.com/LearnBoost/stylus/blob/master/docs/js.md. */ -/// - - - import stylus = require("stylus"); var str = "This is a stylus test"; diff --git a/superagent/superagent-tests.ts b/superagent/superagent-tests.ts index 3252b01c96..3b8539ffe5 100644 --- a/superagent/superagent-tests.ts +++ b/superagent/superagent-tests.ts @@ -1,6 +1,3 @@ - -/// - // via: http://visionmedia.github.io/superagent/ import * as request from 'superagent'; diff --git a/supertest-as-promised/index.d.ts b/supertest-as-promised/index.d.ts index 385f25867b..1f58455f16 100644 --- a/supertest-as-promised/index.d.ts +++ b/supertest-as-promised/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/WhoopInc/supertest-as-promised // Definitions by: Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as supertest from "supertest"; import * as superagent from "superagent"; diff --git a/supertest-as-promised/supertest-as-promised-tests.ts b/supertest-as-promised/supertest-as-promised-tests.ts index c20f9a92b6..23e47ee319 100644 --- a/supertest-as-promised/supertest-as-promised-tests.ts +++ b/supertest-as-promised/supertest-as-promised-tests.ts @@ -1,9 +1,9 @@ - -/// - import * as request from 'supertest-as-promised'; import * as express from 'express'; +declare function describe(desc: string, f: () => void): void; +declare function it(desc: string, f: () => void): void; + var app = express(); // chain your requests like you were promised: @@ -29,12 +29,8 @@ request(app) // ... }); -describe("GET /kittens", () => { - it("should work", () => { - return request(app).get("/kittens").expect(200); - }); -}); +request(app).get("/kittens").expect(200); // Agents var agent = request.agent(app); diff --git a/swagger-schema-official/index.d.ts b/swagger-schema-official/index.d.ts index 172fca0d4e..f0f2e60183 100644 --- a/swagger-schema-official/index.d.ts +++ b/swagger-schema-official/index.d.ts @@ -96,13 +96,13 @@ export interface Operation { description?: string; externalDocs?: ExternalDocs; operationId?: string; - produces?: [string]; - consumes?: [string]; - parameters?: [Parameter]; - schemes?: [string]; + produces?: string[]; + consumes?: string[]; + parameters?: Parameter[]; + schemes?: string[]; deprecated?: boolean; - security?: [Secuirty]; - tags?: [string]; + security?: Security[]; + tags?: string[]; } // ----------------------------- Response ------------------------------------ @@ -132,14 +132,14 @@ interface BaseSchema { uniqueItems?: boolean; maxProperties?: number; minProperties?: number; - enum?: [string|boolean|number|{}]; + enum?: (string|boolean|number|{})[]; type?: string; - items?: Schema|[Schema]; + items?: Schema|Schema[]; } export interface Schema extends BaseSchema { $ref?: string; - allOf?: [Schema]; + allOf?: Schema[]; additionalProperties?: boolean; properties?: {[propertyName: string]: Schema}; discriminator?: string; @@ -147,7 +147,7 @@ export interface Schema extends BaseSchema { xml?: XML; externalDocs?: ExternalDocs; example?: {[exampleName: string]: {}}; - required?: [string]; + required?: string[]; } export interface XML { @@ -184,25 +184,25 @@ export interface OAuth2ImplicitSecurity extends BaseOAuthSecuirty { export interface OAuth2PasswordSecurity extends BaseOAuthSecuirty { tokenUrl: string; - scopes?: [OAuthScope]; + scopes?: OAuthScope[]; } export interface OAuth2ApplicationSecurity extends BaseOAuthSecuirty { tokenUrl: string; - scopes?: [OAuthScope]; + scopes?: OAuthScope[]; } export interface OAuth2AccessCodeSecurity extends BaseOAuthSecuirty { tokenUrl: string; authorizationUrl: string; - scopes?: [OAuthScope]; + scopes?: OAuthScope[]; } export interface OAuthScope { [scopeName: string]: string; } -type Secuirty = +type Security = BasicAuthenticationSecurity | OAuth2AccessCodeSecurity | OAuth2ApplicationSecurity | @@ -217,14 +217,14 @@ export interface Spec { externalDocs?: ExternalDocs; host?: string; basePath?: string; - schemes?: [string]; - consumes?: [string]; - produces?: [string]; + schemes?: string[]; + consumes?: string[]; + produces?: string[]; paths: {[pathName: string]: Path}; definitions?: {[definitionsName: string]: Schema }; parameters?: {[parameterName: string]: BodyParameter|QueryParameter}; responses?: {[responseName: string]: Response }; - security?: [Secuirty]; - securityDefinitions?: { [securityDefinitionName: string]: Secuirty}; - tags?: [Tag]; + security?: Security[]; + securityDefinitions?: { [securityDefinitionName: string]: Security}; + tags?: Tag[]; } diff --git a/systemjs/index.d.ts b/systemjs/index.d.ts index 876e4fdb4d..cf37862975 100644 --- a/systemjs/index.d.ts +++ b/systemjs/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for SystemJS 0.20.5 +// Type definitions for SystemJS 0.20 // Project: https://github.com/systemjs/systemjs // Definitions by: Ludovic HENIN , Nathan Walker , Giedrius Grabauskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,9 +6,13 @@ declare namespace SystemJSLoader { - type ModulesList = { [bundleName: string]: Array }; + interface ModulesList { + [bundleName: string]: string[]; + } - type PackageList = { [packageName: string]: T }; + interface PackageList { + [packageName: string]: T; + } /** * The following module formats are supported: @@ -27,7 +31,7 @@ declare namespace SystemJSLoader { * Represents a module name for System.import that must resolve to either Traceur, Babel or TypeScript. * When set to traceur, babel or typescript, loading will be automatically configured as far as possible. */ - type Transpiler = "plugin-traceur" | "plugin-babel" | "plugin-typescript" | "traceur" | "babel" | "typescript" | boolean; + type Transpiler = "plugin-traceur" | "plugin-babel" | "plugin-typescript" | "traceur" | "babel" | "typescript" | false; type ConfigMap = PackageList>; @@ -49,7 +53,7 @@ declare namespace SystemJSLoader { * Dependencies to load before this module. Goes through regular paths and map normalization. * Only supported for the cjs, amd and global formats. */ - deps?: Array; + deps?: string[]; /** * A map of global names to module names that should be defined only for the execution of this module. @@ -225,13 +229,29 @@ declare namespace SystemJSLoader { * Sets the TypeScript transpiler options. */ //TODO: Import Typescript.CompilerOptions - typescriptOptions?: any; + typescriptOptions?: { + /** + * A boolean flag which instructs the plugin to load configuration from "tsconfig.json". + * To override the location of the file set this option to the path of the configuration file, + * which will be resolved using normal SystemJS resolution. + * Note: This setting is specific to plugin-typescript. + */ + tsconfig?: boolean | string, + /** + * A flag which controls whether the files are type-checked or simply transpiled. + * Set this option to "strict" to have the builds fail when compiler errors are encountered. + * Note: The strict option only affects builds and bundles via the SystemJS or JSPM Builder. + * Note: This setting is specific to plugin-typescript. + */ + typeCheck?: boolean | "strict", + [key: string]: any + }; } interface SystemJSSystemFields { env: string; loaderErrorStack: boolean; - packageConfigPaths: Array; + packageConfigPaths: string[]; pluginFirst: boolean; version: string; warnings: boolean; @@ -241,12 +261,12 @@ declare namespace SystemJSLoader { /** * For backwards-compatibility with AMD environments, set window.define = System.amdDefine. */ - amdDefine: Function; + amdDefine: (...args: any[]) => void; /** * For backwards-compatibility with AMD environments, set window.require = System.amdRequire. */ - amdRequire: Function; + amdRequire: (deps: string[], callback: (...modules: any[]) => void) => void; /** * SystemJS configuration helper function. @@ -257,7 +277,7 @@ declare namespace SystemJSLoader { /** * This represents the System base class, which can be extended or reinstantiated to create a custom System instance. */ - constructor: new() => System; + constructor: new () => System; /** * Deletes a module from the registry by normalized name. @@ -273,7 +293,7 @@ declare namespace SystemJSLoader { /** * Returns a clone of the internal SystemJS configuration in use. */ - getConfig(): Config + getConfig(): Config; /** * Returns whether a given module exists in the registry by normalized module name. @@ -303,15 +323,15 @@ declare namespace SystemJSLoader { /** * Declaration function for defining modules of the System.register polyfill module format. */ - register(name: string, deps: Array, declare: Function): void; - register(deps: Array, declare: Function): void; + register(name: string, deps: string[], declare: (...modules: any[]) => any): void; + register(deps: string[], declare: (...modules: any[]) => any): void; /** * Companion module format to System.register for non-ES6 modules. * Provides a