From 403894c47328ead23d90b576d564558fda447dd2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Va=CC=81clav=20Ostroz=CC=8Cli=CC=81k?= Date: Wed, 20 May 2015 21:54:16 +0200 Subject: [PATCH 001/144] React-router 0.13 support --- react-router/react-router-test.ts | 86 ++--- react-router/react-router.d.ts | 559 +++++++++++++++--------------- 2 files changed, 324 insertions(+), 321 deletions(-) diff --git a/react-router/react-router-test.ts b/react-router/react-router-test.ts index 41b352af36..fa335e9346 100644 --- a/react-router/react-router-test.ts +++ b/react-router/react-router-test.ts @@ -7,7 +7,7 @@ import Router = require('react-router'); // Mixin class NavigationTest { v: T; - + makePath() { var v1: string = this.v.makePath('to'); var v2: string = this.v.makePath('to', {id: 1}); @@ -35,27 +35,27 @@ class NavigationTest { class StateTest { v: T; - + getPath() { var v1: string = this.v.getPath(); } - + getRoutes() { var v1: Router.Route[] = this.v.getRoutes(); } - + getPathname() { var v1: string = this.v.getPathname(); } - + getParams() { var v1: {} = this.v.getParams(); } - + getQuery() { var v1: {} = this.v.getQuery(); } - + isActive() { var v1: boolean = this.v.isActive('to'); var v2: boolean = this.v.isActive('to', {id: 1}); @@ -63,35 +63,23 @@ class StateTest { } } -class RouteHandlerMixinTest { - v: T; - - getRouteDepth() { - var v1: number = this.v.getRouteDepth(); - } - - createChildRouteHandler() { - var v1: Router.RouteHandler = this.v.createChildRouteHandler({ref: 'hoge'}); - } -} - // Location -class LocationTest { +class LocationTest { v: T; - + push() { var v1: void = this.v.push('path/to/hoge'); } - + replace() { var v1: void = this.v.replace('path/to/hoge'); } - + pop() { var v1: void = this.v.pop(); } - + getCurrentPath() { var v1: void = this.v.getCurrentPath(); } @@ -102,11 +90,11 @@ new LocationTest(); class LocationListenerTest { v: T; - + addChangeListener() { var v1: void = this.v.addChangeListener(() => console.log(1)); } - + removeChangeListener() { var v1: void = this.v.removeChangeListener(() => console.log(1)); } @@ -118,7 +106,7 @@ new LocationListenerTest(); // Behavior class ScrollBehaviorTest { v: T; - + updateScrollPosition() { var v1: void = this.v.updateScrollPosition({x: 33, y: 102}, 'scrollTop'); } @@ -130,12 +118,12 @@ new ScrollBehaviorTest(); // Component class DefaultRouteTest { v: Router.DefaultRoute; - + props() { var name: string = this.v.props.name; var handler: React.ComponentClass = this.v.props.handler; } - + createElement() { var Handler: React.ComponentClass; React.createElement(Router.DefaultRoute, null); @@ -145,12 +133,12 @@ class DefaultRouteTest { class LinkTest { v: Router.Link; - + constructor() { new NavigationTest(); new StateTest(); } - + props() { var activeClassName: string = this.v.props.activeClassName; var to: string = this.v.props.to; @@ -158,15 +146,15 @@ class LinkTest { var query: {} = this.v.props.query; var onClick: Function = this.v.props.onClick; } - + getHref() { var v1: string = this.v.getHref(); } - + getClassName() { var v1: string = this.v.getClassName(); } - + createElement() { React.createElement(Router.Link, null); React.createElement(Router.Link, {to: 'home'}); @@ -182,12 +170,12 @@ class LinkTest { class NotFoundRouteTest { v: Router.NotFoundRoute; - + props() { var name: string = this.v.props.name; var handler: React.ComponentClass = this.v.props.handler; } - + createElement() { var Handler: React.ComponentClass; React.createElement(Router.NotFoundRoute, null); @@ -198,13 +186,13 @@ class NotFoundRouteTest { class RedirectTest { v: Router.Redirect; - + props() { var path: string = this.v.props.path; var from: string = this.v.props.from; var to: string = this.v.props.to; } - + createElement() { React.createElement(Router.Redirect, null); React.createElement(Router.Redirect, {}); @@ -214,14 +202,14 @@ class RedirectTest { class RouteTest { v: Router.Route; - + props() { var name: string = this.v.props.name; var path: string = this.v.props.path; var handler: React.ComponentClass = this.v.props.handler; var ignoreScrollBehavior: boolean = this.v.props.ignoreScrollBehavior; } - + createElement() { var Handler: React.ComponentClass; React.createElement(Router.Route, null); @@ -232,11 +220,7 @@ class RouteTest { class RouteHandlerTest { v: Router.RouteHandler; - - constructor() { - new RouteHandlerMixinTest(); - } - + createElement() { React.createElement(Router.RouteHandler, null); React.createElement(Router.RouteHandler, {}); @@ -247,11 +231,11 @@ class RouteHandlerTest { // History class HistoryTest { v: Router.History; - + length() { var v1: number = this.v.length; } - + back() { var v1: void = this.v.back(); } @@ -261,7 +245,7 @@ class HistoryTest { // Router class CreateTest { v: Router.Router; - + constructor() { // React.createElement() version this.v = Router.create({ @@ -272,7 +256,7 @@ class CreateTest { location: Router.HistoryLocation, scrollBehavior: Router.ImitateBrowserBehavior }); - + // React.createFactory() version this.v = Router.create({ routes: React.createFactory(Router.Route)() @@ -283,7 +267,7 @@ class CreateTest { scrollBehavior: Router.ImitateBrowserBehavior }); } - + run() { this.v.run((Handler) => console.log(Handler)); this.v.run((Handler, state) => console.log(Handler, state)); @@ -299,7 +283,7 @@ class RunTest { var v2: Router.Router = Router.run(React.createElement(Router.Route, null), Router.HistoryLocation, (Handler, state) => { React.render(React.createElement(Handler, null), document.body); }); - + // React.createFactory() version var v3: Router.Router = Router.run(React.createFactory(Router.Route)(), (Handler) => { React.render(React.createElement(Handler, null), document.body); diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index 58ec9069a4..c02892ffe1 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -1,278 +1,297 @@ -// Type definitions for React Router 0.12.0 +// Type definitions for React Router 0.13.3 // Project: https://github.com/rackt/react-router -// Definitions by: Yuichi Murata +// Definitions by: Yuichi Murata , Václav Ostrožlík // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// -declare module ReactRouter { - // - // Mixin - // ---------------------------------------------------------------------- - interface Navigation { - makePath(to: string, params?: {}, query?: {}): string; - makeHref(to: string, params?: {}, query?: {}): string; - transitionTo(to: string, params?: {}, query?: {}): void; - replaceWith(to: string, params?: {}, query?: {}): void; - goBack(): void; - } - - interface RouteHandlerMixin { - getRouteDepth(): number; - createChildRouteHandler(props: {}): RouteHandler; - } - - interface State { - getPath(): string; - getRoutes(): Route[]; - getPathname(): string; - getParams(): {}; - getQuery(): {}; - isActive(to: string, params?: {}, query?: {}): boolean; - } - - var Navigation: Navigation; - var State: State; - var RouteHandlerMixin: RouteHandlerMixin; - - - // - // Component - // ---------------------------------------------------------------------- - // DefaultRoute - interface DefaultRouteProp { - name?: string; - handler: React.ComponentClass; - } - interface DefaultRoute extends React.ReactElement { - __react_router_default_route__: any; // dummy - } - interface DefaultRouteClass extends React.ComponentClass { - __react_router_default_route__: any; // dummy - } - - // Link - interface LinkProp { - activeClassName?: string; - to: string; - params?: {}; - query?: {}; - onClick?: Function; - } - interface Link extends React.ReactElement, Navigation, State { - __react_router_link__: any; // dummy - - getHref(): string; - getClassName(): string; - } - interface LinkClass extends React.ComponentClass { - __react_router_link__: any; // dummy - } - - // NotFoundRoute - interface NotFoundRouteProp { - name?: string; - handler: React.ComponentClass; - } - interface NotFoundRoute extends React.ReactElement { - __react_router_not_found_route__: any; // dummy - } - interface NotFoundRouteClass extends React.ComponentClass { - __react_router_not_found_route__: any; // dummy - } - - // Redirect - interface RedirectProp { - path?: string; - from?: string; - to?: string; - } - interface Redirect extends React.ReactElement { - __react_router_redirect__: any; // dummy - } - interface RedirectClass extends React.ComponentClass { - __react_router_redirect__: any; // dummy - } - - // Route - interface RouteProp { - name?: string; - path?: string; - handler?: React.ComponentClass; - ignoreScrollBehavior?: boolean; - } - interface Route extends React.ReactElement { - __react_router_route__: any; // dummy - } - interface RouteClass extends React.ComponentClass { - __react_router_route__: any; // dummy - } - - // RouteHandler - interface RouteHandlerProp {} - interface RouteHandler extends React.ReactElement, RouteHandlerMixin { - __react_router_route_handler__: any; // dummy - } - interface RouteHandlerClass extends React.ReactElement { - __react_router_route_handler__: any; // dummy - } - - var DefaultRoute: DefaultRouteClass; - var Link: LinkClass; - var NotFoundRoute: NotFoundRouteClass; - var Redirect: RedirectClass; - var Route: RouteClass; - var RouteHandler: RouteHandlerClass; - - - // - // Location - // ---------------------------------------------------------------------- - interface LocationBase { - push(path: string): void; - replace(path: string): void; - pop(): void; - getCurrentPath(): void; - } - - interface LocationListener { - addChangeListener(listener: Function): void; - removeChangeListener(listener: Function): void; - } - - interface HashLocation extends LocationBase, LocationListener {} - interface HistoryLocation extends LocationBase, LocationListener {} - interface RefreshLocation extends LocationBase {} - - var HashLocation: HashLocation; - var HistoryLocation: HistoryLocation; - var RefreshLocation: RefreshLocation; - - - // - // Behavior - // ---------------------------------------------------------------------- - interface ScrollBehaviorBase { - updateScrollPosition(position: {x: number; y: number;}, actionType: string): void; - } - interface ImitateBrowserBehavior extends ScrollBehaviorBase {} - interface ScrollToTopBehavior extends ScrollBehaviorBase {} - - var ImitateBrowserBehavior: ImitateBrowserBehavior; - var ScrollToTopBehavior: ScrollToTopBehavior; - - - // - // Router - // ---------------------------------------------------------------------- - interface Router extends React.ReactElement { - run(callback: RouterRunCallback): void; - } - - interface RouterState { - path: string; - action: string; - pathname: string; - params: {}; - query: {}; - routes : Route[]; - } - - interface RouterCreateOption { - routes: React.ReactElement; - location?: LocationBase; - scrollBehavior?: ScrollBehaviorBase; - } - - type RouterRunCallback = (Handler: Router, state: RouterState) => void; - - function create(options: RouterCreateOption): Router; - function run(routes: React.ReactElement, callback: RouterRunCallback): Router; - function run(routes: React.ReactElement, location: LocationBase, callback: RouterRunCallback): Router; - - - // - // History - // ---------------------------------------------------------------------- - interface History { - back(): void; - length: number; - } - var History: History; - - - // - // Transition - // ---------------------------------------------------------------------- - interface Transition { - abort(): void; - redirect(to: string, params?: {}, query?: {}): void; - retry(): void; - } - - interface TransitionStaticLifecycle { - willTransitionTo?( - transition: Transition, - params: {}, - query: {}, - callback: Function - ): void; - - willTransitionFrom?( - transition: Transition, - component: React.ReactElement, - callback: Function - ): void; - } +declare module "react-router" { + + import React = require("react"); + + // + // Transition + // ---------------------------------------------------------------------- + interface Transition { + path: string; + abortReason: any; + retry(): void; + abort(reason?: any): void; + redirect(to: string, params?: {}, query?: {}): void; + cancel(): void; + from: (transition: Transition, routes: Route[], components?: React.ReactElement[], callback?: (error?: any) => void) => void; + to: (transition: Transition, routes: Route[], params?: {}, query?: {}, callback?: (error?: any) => void) => void; + } + + interface TransitionStaticLifecycle { + willTransitionTo?( + transition: Transition, + params: {}, + query: {}, + callback: Function + ): void; + + willTransitionFrom?( + transition: Transition, + component: React.ReactElement, + callback: Function + ): void; + } + + // + // Route Configuration + // ---------------------------------------------------------------------- + // DefaultRoute + interface DefaultRouteProp { + name?: string; + handler: React.ComponentClass; + } + interface DefaultRoute extends React.ReactElement {} + interface DefaultRouteClass extends React.ComponentClass {} + + // NotFoundRoute + interface NotFoundRouteProp { + name?: string; + handler: React.ComponentClass; + } + interface NotFoundRoute extends React.ReactElement {} + interface NotFoundRouteClass extends React.ComponentClass {} + + // Redirect + interface RedirectProp { + path?: string; + from?: string; + to?: string; + } + interface Redirect extends React.ReactElement {} + interface RedirectClass extends React.ComponentClass {} + + // Route + interface RouteProp { + name?: string; + path?: string; + handler?: React.ComponentClass; + ignoreScrollBehavior?: boolean; + } + interface Route extends React.ReactElement {} + interface RouteClass extends React.ComponentClass {} + + var DefaultRoute: DefaultRouteClass; + var NotFoundRoute: NotFoundRouteClass; + var Redirect: RedirectClass; + var Route: RouteClass; + + interface CreateRouteOptions { + name?: string; + path?: string; + ignoreScrollBehavior?: boolean; + isDefault?: boolean; + isNotFound?: boolean; + onEnter?: (transition: Transition, params: {}, query: {}, callback: Function) => void; + onLeave?: (transition: Transition, wtf: any, callback: Function) => void; + handler?: Function; + parentRoute?: Route; + } + + type CreateRouteCallback = (route: Route) => void; + + function createRoute(callback: CreateRouteCallback): Route; + function createRoute(options: CreateRouteOptions | string, callback: CreateRouteCallback): Route; + function createDefaultRoute(options?: CreateRouteOptions | string): Route; + function createNotFoundRoute(options?: CreateRouteOptions | string): Route; + + interface CreateRedirectOptions extends CreateRouteOptions { + path?: string; + from?: string; + to: string; + params?: {}; + query?: {}; + } + function createRedirect(options: CreateRedirectOptions): Redirect; + function createRoutesFromReactChildren(children: Route): Route[]; + + // + // Components + // ---------------------------------------------------------------------- + // Link + interface LinkProp { + activeClassName?: string; + activeStyle?: {}; + to: string; + params?: {}; + query?: {}; + onClick?: Function; + } + interface Link extends React.ReactElement, Navigation, State { + handleClick(event: any): void; + getHref(): string; + getClassName(): string; + getActiveState(): boolean; + } + interface LinkClass extends React.ComponentClass {} + + // RouteHandler + interface RouteHandlerProp { } + interface RouteHandlerChildContext { + routeDepth: number; + } + interface RouteHandler extends React.ReactElement { + getChildContext(): RouteHandlerChildContext; + getRouteDepth(): number; + createChildRouteHandler(props: {}): RouteHandler; + } + interface RouteHandlerClass extends React.ReactElement {} + + var Link: LinkClass; + var RouteHandler: RouteHandlerClass; + + + // + // Top-Level + // ---------------------------------------------------------------------- + interface Router extends React.ReactElement { + run(callback: RouterRunCallback): void; + } + + interface RouterState { + path: string; + action: string; + pathname: string; + params: {}; + query: {}; + routes: Route[]; + } + + interface RouterCreateOption { + routes: Route; + location?: LocationBase; + scrollBehavior?: ScrollBehaviorBase; + onError?: (error: any) => void; + onAbort?: (error: any) => void; + } + + type RouterRunCallback = (Handler: RouteClass, state: RouterState) => void; + + function create(options: RouterCreateOption): Router; + function run(routes: Route, callback: RouterRunCallback): Router; + function run(routes: Route, location: LocationBase, callback: RouterRunCallback): Router; + + + // + // Location + // ---------------------------------------------------------------------- + interface LocationBase { + getCurrentPath(): void; + toString(): string; + } + interface Location extends LocationBase { + push(path: string): void; + replace(path: string): void; + pop(): void; + } + + interface LocationListener { + addChangeListener(listener: Function): void; + removeChangeListener(listener: Function): void; + } + + interface HashLocation extends Location, LocationListener { } + interface HistoryLocation extends Location, LocationListener { } + interface RefreshLocation extends Location { } + interface StaticLocation extends LocationBase { } + interface TestLocation extends Location, LocationListener { } + + var HashLocation: HashLocation; + var HistoryLocation: HistoryLocation; + var RefreshLocation: RefreshLocation; + var StaticLocation: StaticLocation; + var TestLocation: TestLocation; + + + // + // Behavior + // ---------------------------------------------------------------------- + interface ScrollBehaviorBase { + updateScrollPosition(position: { x: number; y: number; }, actionType: string): void; + } + interface ImitateBrowserBehavior extends ScrollBehaviorBase { } + interface ScrollToTopBehavior extends ScrollBehaviorBase { } + + var ImitateBrowserBehavior: ImitateBrowserBehavior; + var ScrollToTopBehavior: ScrollToTopBehavior; + + + // + // Mixin + // ---------------------------------------------------------------------- + interface Navigation { + makePath(to: string, params?: {}, query?: {}): string; + makeHref(to: string, params?: {}, query?: {}): string; + transitionTo(to: string, params?: {}, query?: {}): void; + replaceWith(to: string, params?: {}, query?: {}): void; + goBack(): void; + } + + interface State { + getPath(): string; + getRoutes(): Route[]; + getPathname(): string; + getParams(): {}; + getQuery(): {}; + isActive(to: string, params?: {}, query?: {}): boolean; + } + + var Navigation: Navigation; + var State: State; + + + // + // History + // ---------------------------------------------------------------------- + interface History { + back(): void; + length: number; + } + var History: History; } -declare module 'react-router' { - import Export = ReactRouter; - export = Export; -} -declare module React { - interface TopLevelAPI { - // for DefaultRoute - createElement( - type: ReactRouter.DefaultRouteClass, - props: ReactRouter.DefaultRouteProp, - ...children: ReactNode[] - ): ReactRouter.DefaultRoute; - - // for Link - createElement( - type: ReactRouter.LinkClass, - props: ReactRouter.LinkProp, - ...children: ReactNode[] - ): ReactRouter.Link; - - // for NotFoundRoute - createElement( - type: ReactRouter.NotFoundRouteClass, - props: ReactRouter.NotFoundRouteProp, - ...children: ReactNode[] - ): ReactRouter.NotFoundRoute; - - // for Redirect - createElement( - type: ReactRouter.RedirectClass, - props: ReactRouter.RedirectProp, - ...children: ReactNode[] - ): ReactRouter.Redirect; - - // for Route - createElement( - type: ReactRouter.RouteClass, - props: ReactRouter.RouteProp, - ...children: ReactNode[] - ): ReactRouter.Route; - - // for RouteHandler - createElement( - type: ReactRouter.RouteHandlerClass, - props: ReactRouter.RouteHandlerProp, - ...children: ReactNode[] - ): ReactRouter.RouteHandler; - } +declare module "react" { + import ReactRouter = require("react-router"); + + // for DefaultRoute + function createElement( + type: ReactRouter.DefaultRouteClass, + props: ReactRouter.DefaultRouteProp, + ...children: ReactNode[]): ReactRouter.DefaultRoute; + + // for Link + function createElement( + type: ReactRouter.LinkClass, + props: ReactRouter.LinkProp, + ...children: ReactNode[]): ReactRouter.Link; + + // for NotFoundRoute + function createElement( + type: ReactRouter.NotFoundRouteClass, + props: ReactRouter.NotFoundRouteProp, + ...children: ReactNode[]): ReactRouter.NotFoundRoute; + + // for Redirect + function createElement( + type: ReactRouter.RedirectClass, + props: ReactRouter.RedirectProp, + ...children: ReactNode[]): ReactRouter.Redirect; + + // for Route + function createElement( + type: ReactRouter.RouteClass, + props: ReactRouter.RouteProp, + ...children: ReactNode[]): ReactRouter.Route; + + // for RouteHandler + function createElement( + type: ReactRouter.RouteHandlerClass, + props: ReactRouter.RouteHandlerProp, + ...children: ReactNode[]): ReactRouter.RouteHandler; } From 3e467db265658e0dbc80de8c1be71e4531a52530 Mon Sep 17 00:00:00 2001 From: Chris Wrench Date: Wed, 27 May 2015 17:24:46 +0100 Subject: [PATCH 002/144] Begin update of Google Maps definitions to v3.20 As part of #4364, update some of the Google Maps API to the latest version, v3.20. Changes include: - Addition of `LatLngLiteral` type; - Remove `MarkerImage` type; - Update `Marker` class. The following areas of the API have been updated and checked for consistency with the latest API reference: - Map; - Controls; - Data; - Overlays; - Services; - Save to Google Maps; - Base; - MVC. All other areas of the API still need to be updated. --- googlemaps/google.maps.d.ts | 328 ++++++++++++++++++++++-------------- 1 file changed, 202 insertions(+), 126 deletions(-) diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index fe4e7459cd..f5d197773f 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Maps JavaScript API 3.19 +// Type definitions for Google Maps JavaScript API 3.20 // Project: https://developers.google.com/maps/ // Definitions by: Folia A/S , Chris Wrench // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -29,34 +29,6 @@ THE SOFTWARE. declare module google.maps { - /***** MVC *****/ - export class MVCObject { - constructor (); - addListener(eventName: string, handler: (...args: any[]) => void): MapsEventListener; - bindTo(key: string, target: MVCObject, targetKey?: string, noNotify?: boolean): void; - changed(key: string): void; - get(key: string): any; - notify(key: string): void; - set(key: string, value: any): void; - setValues(values: any): void; - unbind(key: string): void; - unbindAll(): void; - } - - export class MVCArray extends MVCObject { - constructor (array?: any[]); - clear(): void; - forEach(callback: (elem: any, index: number) => void ): void; - getArray(): any[]; - getAt(i: number): any; - getLength(): number; - insertAt(i: number, elem: any): void; - pop(): void; - push(elem: any): number; - removeAt(i: number): any; - setAt(i: number, elem: any): void; - } - /***** Map *****/ export class Map extends MVCObject { constructor (mapDiv: Element, opts?: MapOptions); @@ -65,17 +37,17 @@ declare module google.maps { getCenter(): LatLng; getDiv(): Element; getHeading(): number; - getMapTypeId(): MapTypeId; + getMapTypeId(): MapTypeId|string; getProjection(): Projection; getStreetView(): StreetViewPanorama; getTilt(): number; getZoom(): number; panBy(x: number, y: number): void; - panTo(latLng: LatLng): void; + panTo(latLng: LatLng|LatLngLiteral): void; panToBounds(latLngBounds: LatLngBounds): void; - setCenter(latlng: LatLng): void; + setCenter(latlng: LatLng|LatLngLiteral): void; setHeading(heading: number): void; - setMapTypeId(mapTypeId: MapTypeId): void; + setMapTypeId(mapTypeId: MapTypeId|string): void; setOptions(options: MapOptions): void; setStreetView(panorama: StreetViewPanorama): void; setTilt(tilt: number): void; @@ -99,8 +71,6 @@ declare module google.maps { mapMaker?: boolean; mapTypeControl?: boolean; mapTypeControlOptions?: MapTypeControlOptions; - navigationControl?: boolean; - navigationControlOptions?: NavigationControlOptions; mapTypeId?: MapTypeId; maxZoom?: number; minZoom?: number; @@ -133,7 +103,7 @@ declare module google.maps { /***** Controls *****/ export interface MapTypeControlOptions { - mapTypeIds?: MapTypeId[]; + mapTypeIds?: MapTypeId[]|string[]; position?: ControlPosition; style?: MapTypeControlStyle; } @@ -157,7 +127,6 @@ declare module google.maps { } export interface ScaleControlOptions { - position?: ControlPosition; style?: ScaleControlStyle; } @@ -195,18 +164,6 @@ declare module google.maps { TOP_RIGHT } - export interface NavigationControlOptions { - position?: ControlPosition; - style?: NavigationControlStyle; - } - - export enum NavigationControlStyle { - DEFAULT, - SMALL, - ANDROID, - ZOOM_PAN - } - /***** Data *****/ export class Data extends MVCObject { constructor(options?: Data.DataOptions); @@ -214,6 +171,9 @@ declare module google.maps { addGeoJson(geoJson: Object, options?: Data.GeoJsonOptions): Data.Feature[]; contains(feature: Data.Feature): boolean; forEach(callback: (feature: Data.Feature) => void): void; + getControlPosition(): ControlPosition; + getControls(): string[]; + getDrawingMode(): string; getFeatureById(id: number|string): Data.Feature; getMap(): Map; getStyle(): Data.StylingFunction|Data.StyleOptions; @@ -221,6 +181,9 @@ declare module google.maps { overrideStyle(feature: Data.Feature, style: Data.StyleOptions): void; remove(feature: Data.Feature): void; revertStyle(feature?: Data.Feature): void; + setControlPosition(controlPosition: ControlPosition): void; + setControls(controls: string[]): void; + setDrawingMode(drawingMode: string): void; setMap(map: Map): void; setStyle(style: Data.StylingFunction|Data.StyleOptions): void; toGeoJson(callback: (feature: Object) => void): void; @@ -228,6 +191,10 @@ declare module google.maps { export module Data { export interface DataOptions { + controlPosition?: ControlPosition; + controls?: string[]; + drawingMode?: string; + featureFactory?: (geometry: Data.Geometry) => Data.Feature; map?: Map; style?: Data.StylingFunction|Data.StyleOptions; } @@ -239,9 +206,11 @@ declare module google.maps { export interface StyleOptions { clickable?: boolean; cursor?: string; + draggable?: boolean; + editable?: boolean; fillColor?: string; fillOpacity?: number; - icon?: any; // TODO string|Icon|Symbol; + icon?: string|Icon|Symbol; shape?: MarkerShape; strokeColor?: string; strokeOpacity?: number; @@ -260,13 +229,13 @@ declare module google.maps { getId(): number|string; getProperty(name: string): any; removeProperty(name: string): void; - setGeometry(newGeometry: Data.Geometry|LatLng): void; // TODO LatLngLiteral + setGeometry(newGeometry: Data.Geometry|LatLng|LatLngLiteral): void; setProperty(name: string, newValue: any): void toGeoJson(callback: (feature: Object) => void): void } export interface FeatureOptions { - geometry?: Data.Geometry|LatLng; // TODO LatLngLiteral + geometry?: Data.Geometry|LatLng|LatLngLiteral; id?: number|string; properties?: Object; } @@ -276,53 +245,54 @@ declare module google.maps { } export class Point extends Data.Geometry { - constructor(latLng: LatLng); // TODO LatLngLiteral + constructor(latLng: LatLng|LatLngLiteral); get(): LatLng; } export class MultiPoint extends Data.Geometry { - constructor(elements: LatLng[]); // TODO LatLngLiteral + constructor(elements: LatLng[]|LatLngLiteral[]); + getArray(): LatLng[]; getAt(n: number): LatLng; getLength(): number; } export class LineString extends Data.Geometry { - constructor(elements: LatLng[]); // TODO LatLngLiteral + constructor(elements: LatLng[]|LatLngLiteral[]); getArray(): LatLng[]; getAt(n: number): LatLng; getLength(): number; } export class MultiLineString extends Data.Geometry { - constructor(elements: Data.LineString[]|LatLng[]); // TODO LatLngLiteral + constructor(elements: Data.LineString[]|LatLng[]|LatLngLiteral[]); getArray(): Data.LineString[]; getAt(n: number): Data.LineString; getLength(): number; } export class LinearRing extends Data.Geometry { - constructor(elements: LatLng[]); // TODO LatLngLiteral + constructor(elements: LatLng[]|LatLngLiteral[]); getArray(): LatLng[]; getAt(n: number): LatLng; getLength(): number; } export class Polygon extends Data.Geometry { - constructor(elements: LinearRing[]|LatLng[][]); // TODO LatLngLiteral - getArray(): LinearRing[]; - getAt(n: number): LinearRing; + constructor(elements: Data.LinearRing[]|LatLng[][]|LatLngLiteral[][]); + getArray(): Data.LinearRing[]; + getAt(n: number): Data.LinearRing; getLength(): number; } export class MultiPolygon extends Data.Geometry { - constructor(elements: Data.Polygon[]|LinearRing[][]|LatLng[][][]); // TODO LatLngLiteral + constructor(elements: Data.Polygon[]|LinearRing[][]|LatLng[][][]|LatLngLiteral[][][]); getArray(): Data.Polygon[]; getAt(n: number): Data.Polygon; getLength(): number; } export class GeometryCollection extends Data.Geometry { - constructor(elements: Data.Geometry[]|LatLng[]); // TODO LatLngLiteral + constructor(elements: Data.Geometry[]|LatLng[]|LatLngLiteral[]); getArray(): Data.Geometry[]; getAt(n: number): Data.Geometry; getLength(): number; @@ -365,31 +335,30 @@ declare module google.maps { static MAX_ZINDEX: number; constructor (opts?: MarkerOptions); getAnimation(): Animation; + getAttribution(): Attribution; getClickable(): boolean; getCursor(): string; getDraggable(): boolean; - getFlat(): boolean; - getIcon(): MarkerImage; - getMap(): any; // Map or StreetViewPanorama + getIcon(): string|Icon|Symbol; + getMap(): Map|StreetViewPanorama; + getOpacity(): number; + getPlace(): Place; getPosition(): LatLng; - getShadow(): MarkerImage; getShape(): MarkerShape; getTitle(): string; getVisible(): boolean; getZIndex(): number; setAnimation(animation: Animation): void; + setAttribution(attribution: Attribution): void; setClickable(flag: boolean): void; setCursor(cursor: string): void; setDraggable(flag: boolean): void; - setFlat(flag: boolean): void; - setIcon(icon: MarkerImage): void; - setIcon(icon: string): void; - setMap(map: Map): void; - setMap(map: StreetViewPanorama): void; + setIcon(icon: string|Icon|Symbol): void; + setMap(map: Map|StreetViewPanorama): void; + getOpacity(opacity: number): void; setOptions(options: MarkerOptions): void; - setPosition(latlng: LatLng): void; - setShadow(shadow: MarkerImage): void; - setShadow(shadow: string): void; + setPlace(place: Place): void; + setPosition(latlng: LatLng|LatLngLiteral): void; setShape(shape: MarkerShape): void; setTitle(title: string): void; setVisible(visible: boolean): void; @@ -397,30 +366,31 @@ declare module google.maps { } export interface MarkerOptions { + anchorPoint?:Point; animation?: Animation; + attribution?: Attribution; clickable?: boolean; + crossOnDrag?: boolean; cursor?: string; draggable?: boolean; - flat?: boolean; - icon?: any; - map?: any; + icon?: string|Icon|Symbol; + map?: Map|StreetViewPanorama; + opacity?: number; optimized?: boolean; + place?: Place; position?: LatLng; - raiseOnDrag?: boolean; - shadow?: any; shape?: MarkerShape; title?: string; visible?: boolean; zIndex?: number; } - export class MarkerImage { - constructor (url: string, size?: Size, origin?: Point, anchor?: Point, scaledSize?: Size); - anchor: Point; - origin: Point; - scaledSize: Size; - size: Size; - url: string; + export interface Icon { + anchor?: Point; + origin?: Point; + scaledSize?: Size; + size?: Size; + url?: string; } export interface MarkerShape { @@ -432,7 +402,7 @@ declare module google.maps { anchor?: Point; fillColor?: string; fillOpacity?: number; - path?: any; + path?: SymbolPath|string; rotation?: number; scale?: number; strokeColor?: string; @@ -456,24 +426,22 @@ declare module google.maps { export class InfoWindow extends MVCObject { constructor (opts?: InfoWindowOptions); close(): void; - getContent(): any; // string or Element + getContent(): string|Element; getPosition(): LatLng; getZIndex(): number; - open(map?: Map, anchor?: MVCObject): void; - open(map?: StreetViewPanorama, anchor?: MVCObject): void; - setContent(content: Node): void; - setContent(content: string): void; + open(map?: Map|StreetViewPanorama, anchor?: MVCObject): void; + setContent(content: string|Node): void; setOptions(options: InfoWindowOptions): void; setPosition(position: LatLng): void; setZIndex(zIndex: number): void; } export interface InfoWindowOptions { - content?: any; + content?: string|Node; disableAutoPan?: boolean; maxWidth?: number; pixelOffset?: Size; - position?: LatLng; + position?: LatLng|LatLngLiteral; zIndex?: number; } @@ -482,14 +450,13 @@ declare module google.maps { getDraggable(): boolean; getEditable(): boolean; getMap(): Map; - getPath(): MVCArray; + getPath(): MVCArray; // MVCArray getVisible(): boolean; setDraggable(draggable: boolean): void; setEditable(editable: boolean): void; setMap(map: Map): void; setOptions(options: PolylineOptions): void; - setPath(path: MVCArray): void; - setPath(path: LatLng[]): void; + setPath(path: MVCArray|LatLng[]|LatLngLiteral[]): void; // MVCArray|Array setVisible(visible: boolean): void; } @@ -500,7 +467,7 @@ declare module google.maps { geodesic?: boolean; icons?: IconSequence[]; map?: Map; - path?: any[]; + path?: MVCArray|LatLng[]|LatLngLiteral[]; // MVCArray|Array strokeColor?: string; strokeOpacity?: number; strokeWeight?: number; @@ -520,19 +487,20 @@ declare module google.maps { getDraggable(): boolean; getEditable(): boolean; getMap(): Map; - getPath(): MVCArray; - getPaths(): MVCArray; + getPath(): MVCArray; // MVCArray + getPaths(): MVCArray; // MVCArray> getVisible(): boolean; setDraggable(draggable: boolean): void; setEditable(editable: boolean): void; setMap(map: Map): void; setOptions(options: PolygonOptions): void; - setPath(path: MVCArray): void; - setPath(path: LatLng[]): void; + setPath(path: MVCArray|LatLng[]|LatLngLiteral[]): void; setPaths(paths: MVCArray): void; setPaths(paths: MVCArray[]): void; setPaths(path: LatLng[]): void; setPaths(path: LatLng[][]): void; + setPaths(path: LatLngLiteral[]): void; + setPaths(path: LatLngLiteral[][]): void; setVisible(visible: boolean): void; } @@ -544,7 +512,7 @@ declare module google.maps { fillOpacity?: number; geodesic?: boolean; map?: Map; - paths?: any[]; + paths?: any[]; // MVCArray>|MVCArray|Array>|Array strokeColor?: string; strokeOpacity?: number; strokePosition?: StrokePosition; @@ -599,7 +567,7 @@ declare module google.maps { getMap(): Map; getRadius(): number; getVisible(): boolean; - setCenter(center: LatLng): void; + setCenter(center: LatLng|LatLngLiteral): void; setDraggable(draggable: boolean): void; setEditable(editable: boolean): void; setMap(map: Map): void; @@ -649,23 +617,20 @@ declare module google.maps { export class OverlayView extends MVCObject { draw(): void; - getMap(): Map; + getMap(): Map|StreetViewPanorama; getPanes(): MapPanes; getProjection(): MapCanvasProjection; onAdd(): void; onRemove(): void; - setMap(map: Map): void; - setMap(map: StreetViewPanorama): void; + setMap(map: Map|StreetViewPanorama): void; } export interface MapPanes { floatPane: Element; - floatShadow: Element; mapPane: Element; - overlayImage: Element; + markerLayer: Element; overlayLayer: Element; overlayMouseTarget: Element; - overlayShadow: Element; } export class MapCanvasProjection extends MVCObject { @@ -678,17 +643,25 @@ declare module google.maps { /***** Services *****/ export class Geocoder { - constructor (); geocode(request: GeocoderRequest, callback: (results: GeocoderResult[], status: GeocoderStatus) => void ): void; } export interface GeocoderRequest { address?: string; bounds?: LatLngBounds; - location?: LatLng; + componentRestrictions: GeocoderComponentRestrictions; + location?: LatLng|LatLngLiteral; region?: string; } + export interface GeocoderComponentRestrictions { + administrativeArea: string; + country: string; + locality: string; + postalCode: string; + route: string; + } + export enum GeocoderStatus { ERROR, INVALID_REQUEST, @@ -703,6 +676,8 @@ declare module google.maps { address_components: GeocoderAddressComponent[]; formatted_address: string; geometry: GeocoderGeometry; + partial_match: boolean; + postcode_localities: string[] types: string[]; } @@ -757,16 +732,17 @@ declare module google.maps { } export class DirectionsService { - constructor (); route(request: DirectionsRequest, callback: (result: DirectionsResult, status: DirectionsStatus) => void ): void; } export interface DirectionsRequest { + avoidFerries?: boolean; avoidHighways?: boolean; avoidTolls?: boolean; - destination?: any; + destination?: LatLng|string; + durationInTraffic?: boolean; optimizeWaypoints?: boolean; - origin?: any; + origin?: LatLng|string; provideRouteAlternatives?: boolean; region?: string; transitOptions?: TransitOptions; @@ -790,10 +766,28 @@ declare module google.maps { export interface TransitOptions { arrivalTime?: Date; departureTime?: Date; + modes: TransitMode[]; + routingPreference: TransitRoutePreference; } + export enum TransitMode { + BUS, + RAIL, + SUBWAY, + TRAIN, + TRAM + } + + export enum TransitRoutePreference + { + FEWER_TRANSFERS, + LESS_WALKING + } + + export interface TransitFare { } + export interface DirectionsWaypoint { - location: any; + location: LatLng|string; stopover: boolean; } @@ -815,17 +809,20 @@ declare module google.maps { export interface DirectionsRoute { bounds: LatLngBounds; copyrights: string; + fare: TransitFare; legs: DirectionsLeg[]; overview_path: LatLng[]; + overview_polyline: string; warnings: string[]; waypoint_order: number[]; } export interface DirectionsLeg { - arrival_time: Distance; - departure_time: Duration; + arrival_time: Time; + departure_time: Time; distance: Distance; duration: Duration; + duration_in_traffic: Duration; end_address: string; end_location: LatLng; start_address: string; @@ -899,11 +896,31 @@ declare module google.maps { icon: string; local_icon: string; name: string; - type: string; + type: VehicleType; + } + + export enum VehicleType + { + BUS, + CABLE_CAR, + COMMUTER_TRAIN, + FERRY, + FUNICULAR, + GONDOLA_LIFT, + HEAVY_RAIL, + HIGH_SPEED_TRAIN, + INTERCITY_BUS, + METRO_RAIL, + MONORAIL, + OTHER, + RAIL, + SHARE_TAXI, + SUBWAY, + TRAM, + TROLLEYBUS } export class ElevationService { - constructor (); getElevationAlongPath(request: PathElevationRequest, callback: (results: ElevationResult[], status: ElevationStatus) => void ): void; getElevationForLocations(request: LocationElevationRequest, callback: (results: ElevationResult[], status: ElevationStatus) => void ): void; } @@ -932,8 +949,7 @@ declare module google.maps { } export class MaxZoomService { - constructor (); - getMaxZoomAtLatLng(latlng: LatLng, callback: (result: MaxZoomResult) => void ): void; + getMaxZoomAtLatLng(latlng: LatLng|LatLngLiteral, callback: (result: MaxZoomResult) => void ): void; } export interface MaxZoomResult { @@ -947,16 +963,18 @@ declare module google.maps { } export class DistanceMatrixService { - constructor (); getDistanceMatrix(request: DistanceMatrixRequest, callback: (response: DistanceMatrixResponse, status: DistanceMatrixStatus) => void ): void; } export interface DistanceMatrixRequest { + avoidFerries?: boolean; avoidHighways?: boolean; avoidTolls?: boolean; - destinations?: any[]; - origins?: any[]; + destinations?: LatLng[]|string[]; + durationInTraffic?: boolean; + origins?: LatLng[]|string[]; region?: string; + transitOptions?: TransitOptions; travelMode?: TravelMode; unitSystem?: UnitSystem; } @@ -974,6 +992,7 @@ declare module google.maps { export interface DistanceMatrixResponseElement { distance: Distance; duration: Duration; + fare: TransitFare; status: DistanceMatrixElementStatus; } @@ -992,6 +1011,33 @@ declare module google.maps { OK, ZERO_RESULTS } + + /***** Save to Google Maps *****/ + export interface Attribution { + iosDeepLinkId?: string; + source?: string; + webUrl?: string; + } + + export interface Place { + location?: LatLng|LatLngLiteral; + placeId?: string; + query?: string; + } + + export class SaveWidget { + constructor(container: Node, opts?: SaveWidgetOptions); + getAttribution(): Attribution; + getPlace(): Place; + setAttribution(attribution: Attribution): void; + setOptions(opts: SaveWidgetOptions): void; + setPlace(place: Place): void; + } + + export interface SaveWidgetOptions{ + attribution?: Attribution; + place?: Place; + } /***** Map Types *****/ export interface MapType { @@ -1333,7 +1379,7 @@ declare module google.maps { ZERO_RESULTS } - /***** Event *****/ + /***** Events *****/ export interface MapsEventListener { } export class event { @@ -1367,6 +1413,8 @@ declare module google.maps { } + export type LatLngLiteral = { lat: number; lng: number } + export class LatLngBounds { constructor (sw?: LatLng, ne?: LatLng); contains(latLng: LatLng): boolean; @@ -1399,6 +1447,34 @@ declare module google.maps { toString(): string; } + /***** MVC *****/ + export class MVCObject { + constructor (); + addListener(eventName: string, handler: (...args: any[]) => void): MapsEventListener; + bindTo(key: string, target: MVCObject, targetKey?: string, noNotify?: boolean): void; + changed(key: string): void; + get(key: string): any; + notify(key: string): void; + set(key: string, value: any): void; + setValues(values: any): void; + unbind(key: string): void; + unbindAll(): void; + } + + export class MVCArray extends MVCObject { + constructor (array?: any[]); + clear(): void; + forEach(callback: (elem: any, i: number) => void): void; + getArray(): any[]; + getAt(i: number): any; + getLength(): number; + insertAt(i: number, elem: any): void; + pop(): any; + push(elem: any): number; + removeAt(i: number): any; + setAt(i: number, elem: any): void; + } + /***** Geometry Library *****/ export module geometry { export class encoding { From f9c3edf6c6c32726e7e424fc3690da5ff1b0eef6 Mon Sep 17 00:00:00 2001 From: Haskell Camargo Date: Sun, 14 Jun 2015 23:21:47 -0300 Subject: [PATCH 003/144] Each is not void, it returns a parameter of type A[] --- prelude-ls/prelude-ls-tests.ts | 16 ++++++++++------ prelude-ls/prelude-ls.d.ts | 6 ++++-- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/prelude-ls/prelude-ls-tests.ts b/prelude-ls/prelude-ls-tests.ts index b6e50e2256..8c37a1e717 100644 --- a/prelude-ls/prelude-ls-tests.ts +++ b/prelude-ls/prelude-ls-tests.ts @@ -1,23 +1,27 @@ +/// + import prelude = require("prelude-ls"); -prelude.id(5); //=> 5 -prelude.id({}); //=> {} +var five: number = prelude.id(5); //=> 5 +var emptyObj: Object = prelude.id({}); //=> {} -prelude.isType("Undefined", void 8); //=> true +var expectBool: boolean = prelude.isType("Undefined", void 8); //=> true prelude.isType("Boolean", true); //=> true prelude.isType("Number", 1); //=> true prelude.isType("String", "hi"); //=> true prelude.isType("Object", {}); //=> true prelude.isType("Array", []); //=> true -prelude.replicate(4, 3); //=> [3, 3, 3, 3] -prelude.replicate(4, "a"); //=> ["a", "a", "a", "a"] +var numberArray: Array = prelude.replicate(4, 3); //=> [3, 3, 3, 3] +var strArray: Array = + prelude.replicate(4, "a"); //=> ["a", "a", "a", "a"] prelude.replicate(0, "a"); //=> [] // List -prelude.each(x => x.push("boom"), [["a"], ["b"], ["c"]]); +var dblStrArray: Array> = + prelude.each(x => x.push("boom"), [["a"], ["b"], ["c"]]); //=> [["a", "boom"], ["b", "boom"], ["c", "boom"]] prelude.map(x => x * 2, [1, 2, 3, 4, 5]); //=> [2, 4, 6, 8, 10] diff --git a/prelude-ls/prelude-ls.d.ts b/prelude-ls/prelude-ls.d.ts index 848077c822..0de28f63a8 100644 --- a/prelude-ls/prelude-ls.d.ts +++ b/prelude-ls/prelude-ls.d.ts @@ -3,6 +3,8 @@ // Definitions by: Aya Morisawa // Definitions: https://github.com/borisyankov/DefinitelyTyped +// Change [0]: 2015/06/14 - Marcelo Camargo + declare module "prelude-ls" { module PreludeLS { export function id(x: A): A; @@ -14,8 +16,8 @@ declare module "prelude-ls" { // List - export function each(f: (x: A) => void): (xs: A[]) => void; - export function each(f: (x: A) => void, xs: A[]): void; + export function each(f: (x: A) => void): (xs: A[]) => A[]; + export function each(f: (x: A) => void, xs: A[]): A[]; export function map(f: (x: A) => B): (xs: A[]) => B[]; export function map(f: (x: A) => B, xs: A[]): B[]; export function compact(xs: A[]): A[]; From 19795463b32a83f4f68b55e8c8068f3956a4b7d3 Mon Sep 17 00:00:00 2001 From: Haskell Camargo Date: Sun, 14 Jun 2015 23:31:32 -0300 Subject: [PATCH 004/144] Correction on return types for find, head and last --- prelude-ls/prelude-ls-tests.ts | 30 +++++++++++++++++++----------- prelude-ls/prelude-ls.d.ts | 8 ++++---- 2 files changed, 23 insertions(+), 15 deletions(-) diff --git a/prelude-ls/prelude-ls-tests.ts b/prelude-ls/prelude-ls-tests.ts index 8c37a1e717..080f40afbd 100644 --- a/prelude-ls/prelude-ls-tests.ts +++ b/prelude-ls/prelude-ls-tests.ts @@ -20,32 +20,40 @@ prelude.replicate(0, "a"); //=> [] // List -var dblStrArray: Array> = +var eachRes: Array> = prelude.each(x => x.push("boom"), [["a"], ["b"], ["c"]]); //=> [["a", "boom"], ["b", "boom"], ["c", "boom"]] -prelude.map(x => x * 2, [1, 2, 3, 4, 5]); //=> [2, 4, 6, 8, 10] +var mapRes: Array = + prelude.map(x => x.toString(), [1, 2, 3, 4, 5]) //=> ["1", "2", "3", "4", "5"] + prelude.map(x => x.toUpperCase(), ["ha", "ma"]); //=> ["HA", "MA"] prelude.map(x => x.num, [{num: 3}, {num: 1}]); //=> [3, 1] -prelude.compact([0, 1, false, true, "", "ha"]) //=> [1, true, "ha"] +var compactRes: Array = + prelude.compact([0, 1, false, true, "", "ha"]) //=> [1, true, "ha"] -prelude.filter(x => x < 3, [1, 2, 3, 4, 5]); //=> [1, 2] +var filterRes: Array = + prelude.filter(x => x < 3, [1, 2, 3, 4, 5]); //=> [1, 2] prelude.filter(prelude.even, [3, 4, 0]); //=> [4, 0] -prelude.reject(prelude.odd, [1, 2, 3, 4, 5]); //=> [2, 4] +var rejectRes: Array = + prelude.reject(prelude.odd, [1, 2, 3, 4, 5]); //=> [2, 4] -prelude.partition(x => x > 60, [49, 58, 76, 43, 88, 77, 90]); //=> [[76, 88, 77, 90], [49, 58, 43]] +var partitionRes: Array> = + prelude.partition(x => x > 60, [49, 58, 76, 43, 88, 77, 90]); + //=> [[76, 88, 77, 90], [49, 58, 43]] -prelude.find(prelude.odd, [2, 4, 6, 7, 8, 9, 10]); //=> 7 +var findRes: number = prelude.find(prelude.odd, [2, 4, 6, 7, 8, 9, 10]); //=> 7 -prelude.head([1, 2, 3, 4, 5]); //=> 1 +var headRes: number = prelude.head([1, 2, 3, 4, 5]); //=> 1 -prelude.tail([1, 2, 3, 4, 5]); //=> [2, 3, 4, 5] +var tailRes: Array = prelude.tail([1, 2, 3, 4, 5]); //=> [2, 3, 4, 5] -prelude.last([1, 2, 3, 4, 5]); //=> 5 +var lastRes: number = prelude.last([1, 2, 3, 4, 5]); //=> 5 -prelude.initial([1, 2, 3, 4, 5]); //=> [1, 2, 3, 4] +var initialRes: Array = + prelude.initial([1, 2, 3, 4, 5]); //=> [1, 2, 3, 4] prelude.empty([]); //=> true diff --git a/prelude-ls/prelude-ls.d.ts b/prelude-ls/prelude-ls.d.ts index 0de28f63a8..f72db01800 100644 --- a/prelude-ls/prelude-ls.d.ts +++ b/prelude-ls/prelude-ls.d.ts @@ -27,11 +27,11 @@ declare module "prelude-ls" { export function reject(f: (x: A) => boolean, xs: A[]): A[]; export function partition(f: (x: A) => Boolean): (xs: A[]) => [A[], A[]]; export function partition(f: (x: A) => Boolean, xs: A[]): [A[], A[]]; - export function find(f: (x: A) => Boolean): (xs: A[]) => (A | void); - export function find(f: (x: A) => Boolean, xs: A[]): (A | void); - export function head(xs: A[]): (A | void); + export function find(f: (x: A) => Boolean): (xs: A[]) => A; + export function find(f: (x: A) => Boolean, xs: A[]): A; + export function head(xs: A[]): A; export function tail(xs: A[]): A[]; - export function last(xs: A[]): (A | void); + export function last(xs: A[]): A; export function initial(xs: A[]): A[]; export function empty(xs: A[]): boolean; export function reverse(xs: A[]): A[]; From c5eee1bdc66ce227a58140a8ae166de4485bd883 Mon Sep 17 00:00:00 2001 From: Haskell Camargo Date: Sun, 14 Jun 2015 23:40:03 -0300 Subject: [PATCH 005/144] Correction on argument types for intersection and union --- prelude-ls/prelude-ls-tests.ts | 56 ++++++++++++++++++++++------------ prelude-ls/prelude-ls.d.ts | 4 +-- 2 files changed, 38 insertions(+), 22 deletions(-) diff --git a/prelude-ls/prelude-ls-tests.ts b/prelude-ls/prelude-ls-tests.ts index 080f40afbd..d3d5fcd4dd 100644 --- a/prelude-ls/prelude-ls-tests.ts +++ b/prelude-ls/prelude-ls-tests.ts @@ -55,41 +55,57 @@ var lastRes: number = prelude.last([1, 2, 3, 4, 5]); //=> 5 var initialRes: Array = prelude.initial([1, 2, 3, 4, 5]); //=> [1, 2, 3, 4] -prelude.empty([]); //=> true +var emptyRes: boolean = prelude.empty([]); //=> true -prelude.reverse([1, 2, 3]); //=> [3, 2, 1] +var reverseRes: Array = prelude.reverse([1, 2, 3]); //=> [3, 2, 1] -prelude.unique([1, 1, 1, 3, 3, 6, 7, 8]); //=> [1, 3, 6, 7, 8] +var uniqueRes: Array = + prelude.unique([1, 1, 1, 3, 3, 6, 7, 8]); //=> [1, 3, 6, 7, 8] -prelude.uniqueBy(x => x.length, ["and", "here", "are", "some", "words"]); //=> ["and", "here", "words"] +var uniqueByRes: Array = + prelude.uniqueBy(x => x.length, ["and", "here", "are", "some", "words"]); //=> ["and", "here", "words"] -prelude.fold(x => y => x + y, 0, [1, 2, 3, 4, 5]); //=> 15 -var product = prelude.fold(x => y => x * y, 1); +var foldRes: number = + prelude.fold(x => y => x + y, 0, [1, 2, 3, 4, 5]); //=> 15 -prelude.fold1(x => y => x + y, [1, 2, 3]); //=> 6 +var fold1Res: number = + prelude.fold1(x => y => x + y, [1, 2, 3]); //=> 6 -prelude.foldr(x => y => x - y, 9, [1, 2, 3, 4]); //=> 7 -prelude.foldr(x => y => x + y, "e", ["a", "b", "c", "d"]); //=> "abcde" +var foldrRes: number = + prelude.foldr(x => y => x - y, 9, [1, 2, 3, 4]); //=> 7 -prelude.foldr1(x => y => x - y, [1, 2, 3, 4, 9]); //=> 7 +var foldrStrRes: string = + prelude.foldr(x => y => x + y, "e", ["a", "b", "c", "d"]); //=> "abcde" -prelude.unfoldr(x => x === 0 ? null : [x, x - 1], 10); -//=> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] +var foldr1Res: number = + prelude.foldr1(x => y => x - y, [1, 2, 3, 4, 9]); //=> 7 -prelude.concat([[1], [2, 3], [4]]); //=> [1, 2, 3, 4] +var unfoldrRes: Array = + prelude.unfoldr(x => x === 0 ? null : [x, x - 1], 10); + //=> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] -prelude.concatMap(x => ["hoge", x, x + 2], [1, 2, 3]); //=> ["hoge", 1, 3, "hoge", 2, 4, "hoge", 3, 5] +var concatRes: Array = + prelude.concat([[1], [2, 3], [4]]); //=> [1, 2, 3, 4] -prelude.flatten([1, [[2], 3], [4, [[5]]]]); //=> [1, 2, 3, 4, 5] +var concatMapRes: Array = + prelude.concatMap(x => ["hoge", x, x + 2], [1, 2, 3]); + //=> ["hoge", 1, 3, "hoge", 2, 4, "hoge", 3, 5] -prelude.difference([1, 2, 3], [1]); //=> [2, 3] +var flattenRes: Array = + prelude.flatten([1, [[2], 3], [4, [[5]]]]); //=> [1, 2, 3, 4, 5] + +var differenceRes: Array = + prelude.difference([1, 2, 3], [1]); //=> [2, 3] prelude.difference([1, 2, 3, 4, 5], [5, 2, 10], [9]); //=> [1, 3, 4] -prelude.intersection([2, 3], [9, 8], [12, 1], [99]); //=> [] -prelude.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1], [-1, 0, 1, 2]); //=> [1, 2] -prelude.intersection([1, 2, 3], [2, 1, 3], [3, 1, 2]); //=> [1, 2, 3] +prelude.intersection([2, 3], [9, 8], [12, 1], [99]); //=> [] +var intersectionRes: Array = + prelude.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1], [-1, 0, 1, 2]); +//=> [1, 2] +prelude.intersection([1, 2, 3], [2, 1, 3], [3, 1, 2]); //=> [1, 2, 3] -prelude.union([1, 5, 7], [3, 5], []); //=> [1, 5, 7, 3] +var unionRes: Array = + prelude.union([1, 5, 7], [3, 5], []); //=> [1, 5, 7, 3] prelude.countBy(prelude.floor, [4.2, 6.1, 6.4]); //=> {4: 1, 6: 2} prelude.countBy(x => x.length, ["one", "two", "three"]); //=> {3: 2, 5: 1} diff --git a/prelude-ls/prelude-ls.d.ts b/prelude-ls/prelude-ls.d.ts index f72db01800..fde6ed1578 100644 --- a/prelude-ls/prelude-ls.d.ts +++ b/prelude-ls/prelude-ls.d.ts @@ -60,8 +60,8 @@ declare module "prelude-ls" { export function concatMap(f: (x: A) => B[], xs: A[]): B[]; export function flatten(xs: any[]): any[]; export function difference(...xss: A[][]): A[]; - export function intersection(...xss: A[]): A[]; - export function union(...xss: A[]): A[]; + export function intersection(...xss: A[][]): A[]; + export function union(...xss: A[][]): A[]; export function countBy(f: (x: A) => B): (xs: A[]) => any; export function countBy(f: (x: A) => B, xs: A[]): any; export function groupBy(f: (x: A) => B): (xs: A[]) => any; From b64f70ca142cb7932abfd2c2db501c182362ab25 Mon Sep 17 00:00:00 2001 From: Haskell Camargo Date: Sun, 14 Jun 2015 23:50:43 -0300 Subject: [PATCH 006/144] Added tests for numbers and strings, with assignment --- prelude-ls/prelude-ls-tests.ts | 80 +++++++++++++++++++--------------- 1 file changed, 44 insertions(+), 36 deletions(-) diff --git a/prelude-ls/prelude-ls-tests.ts b/prelude-ls/prelude-ls-tests.ts index d3d5fcd4dd..5bc034bc48 100644 --- a/prelude-ls/prelude-ls-tests.ts +++ b/prelude-ls/prelude-ls-tests.ts @@ -107,6 +107,8 @@ prelude.intersection([1, 2, 3], [2, 1, 3], [3, 1, 2]); //=> [1, 2, 3] var unionRes: Array = prelude.union([1, 5, 7], [3, 5], []); //=> [1, 5, 7, 3] +// --- UNION --- + prelude.countBy(prelude.floor, [4.2, 6.1, 6.4]); //=> {4: 1, 6: 2} prelude.countBy(x => x.length, ["one", "two", "three"]); //=> {3: 2, 5: 1} @@ -300,94 +302,100 @@ prelude.Str.breakStr(x => x === "h", "mmmmmhmm"); //=> ["mmmmm", "hmm"] // Func -prelude.apply((x, y) => x + y, [2, 3]); //=> 5 +var applyRes: number = prelude.apply((x, y) => x + y, [2, 3]); //=> 5 var add = (x: number, y: number) => x + y; var addCurried = prelude.curry(add); var addFour = addCurried(4); addFour(2); //=> 6 -var invertedPower = prelude.flip(x => y => Math.pow(x, y)); -invertedPower(2)(3); //=> 9 +var flipRes: (x: number) => (y: number) => number + = prelude.flip(x => y => Math.pow(x, y)); -prelude.fix((fib: (n: number) => number) => (n: number) => n <= 1 ? 1 : fib(n - 1) + fib(n - 2))(9); //=> 55 +var fixRes: number = prelude.fix( + (fib: (n: number) => number) => (n: number) => + n <= 1 + ? 1 + : fib(n - 1) + fib(n - 2) +)(9); //=> 55 -var sameLength = prelude.over((x, y) => x == y, x => x.length); +var sameLength: (x: string, y: string) => boolean + = prelude.over((x, y) => x == y, x => x.length); sameLength('hi', 'me'); //=> true sameLength('one', 'boom'); //=> false // Num prelude.max(3, 1); //=> 3 -prelude.max("a", "c"); //=> "c" +var maxRes: string = prelude.max("a", "c"); //=> "c" -prelude.min(3, 1); //=> 1 +var minRes: number = prelude.min(3, 1); //=> 1 prelude.min("a", "c"); //=> "a" -prelude.negate(3); //=> -3 +var negateRes: number = prelude.negate(3); //=> -3 prelude.negate(-2); //=> 2 -prelude.abs(-2); //=> 2 +var absRes: number = prelude.abs(-2); //=> 2 prelude.abs(2); //=> 2 -prelude.signum(-5); //=> -1 +var signumRes: number = prelude.signum(-5); //=> -1 prelude.signum(0); //=> 0 prelude.signum(9); //=> 1 -prelude.quot(-20, 3); //=> -6 +var quotRes: number = prelude.quot(-20, 3); //=> -6 -prelude.rem(-20, 3); //=> -2 +var remRes: number = prelude.rem(-20, 3); //=> -2 -prelude.div(-20, 3); //=> -7 +var divRes: number = prelude.div(-20, 3); //=> -7 -prelude.mod(-20, 3); //=> 1 +var modRes: number = prelude.mod(-20, 3); //=> 1 -prelude.recip(4); //=> 0.25 +var recipRes: number = prelude.recip(4); //=> 0.25 -prelude.pi; //=> 3.141592653589793 +var piRes: number = prelude.pi; //=> 3.141592653589793 -prelude.tau; //=> 6.283185307179586 +var tauRes: number = prelude.tau; //=> 6.283185307179586 -prelude.exp(1); //=> 2.718281828459045 +var expRes: number = prelude.exp(1); //=> 2.718281828459045 -prelude.sqrt(4); //=> 2 +var sqrtRes: number = prelude.sqrt(4); //=> 2 -prelude.ln(10); //=> 2.302585092994046 +var lnRes: number = prelude.ln(10); //=> 2.302585092994046 -prelude.pow(-2, 2); //=> 4 +var powRes: number = prelude.pow(-2, 2); //=> 4 -prelude.sin(prelude.pi / 2); //=> 1 +var sinRes: number = prelude.sin(prelude.pi / 2); //=> 1 -prelude.cos(prelude.pi); //=> -1 +var cosRes: number = prelude.cos(prelude.pi); //=> -1 -prelude.tan(prelude.pi / 4); //=> 1 +var aTanRes: number = prelude.tan(prelude.pi / 4); //=> 1 -prelude.asin(0); //=> 0 +var asinRes: number = prelude.asin(0); //=> 0 -prelude.acos(1); //=> 0 +var acosRes: number = prelude.acos(1); //=> 0 prelude.atan(0); //=> 0 -prelude.atan2(1, 0); //=> 1.5707963267948966 +var atanRes: number = prelude.atan2(1, 0); //=> 1.5707963267948966 -prelude.truncate(-1.5); //=> -1 +var truncateRes: number = prelude.truncate(-1.5); //=> -1 prelude.truncate(1.5); //=> 1 -prelude.round(0.6); //=> 1 +var roundRes: number = prelude.round(0.6); //=> 1 prelude.round(0.5); //=> 1 prelude.round(0.4); //=> 0 -prelude.ceiling(0.1); //=> 1 +var ceilingRes: number = prelude.ceiling(0.1); //=> 1 -prelude.floor(0.9); //=> 0 +var floorRes: number = prelude.floor(0.9); //=> 0 -prelude.isItNaN(prelude.sqrt(-1)); //=> true +var isItNanRes: boolean = prelude.isItNaN(prelude.sqrt(-1)); //=> true -prelude.even(4); //=> true +var evenRes: boolean = prelude.even(4); //=> true prelude.even(0); //=> true -prelude.odd(3); //=> true +var oddRes: boolean = prelude.odd(3); //=> true -prelude.gcd(12, 18); //=> 6 +var gcdRes: number = prelude.gcd(12, 18); //=> 6 -prelude.lcm(12, 18); //=> 36 \ No newline at end of file +var lcmRes: number = prelude.lcm(12, 18); //=> 36 \ No newline at end of file From 827ec75fbbf3d125a680b0b74e10f0c5e6beb567 Mon Sep 17 00:00:00 2001 From: Haskell Camargo Date: Sun, 14 Jun 2015 23:56:22 -0300 Subject: [PATCH 007/144] sortBy should return A[] instead of A --- prelude-ls/prelude-ls-tests.ts | 36 ++++++++++++++++++++++------------ prelude-ls/prelude-ls.d.ts | 4 ++-- 2 files changed, 25 insertions(+), 15 deletions(-) diff --git a/prelude-ls/prelude-ls-tests.ts b/prelude-ls/prelude-ls-tests.ts index 5bc034bc48..c04fb2277e 100644 --- a/prelude-ls/prelude-ls-tests.ts +++ b/prelude-ls/prelude-ls-tests.ts @@ -107,28 +107,31 @@ prelude.intersection([1, 2, 3], [2, 1, 3], [3, 1, 2]); //=> [1, 2, 3] var unionRes: Array = prelude.union([1, 5, 7], [3, 5], []); //=> [1, 5, 7, 3] -// --- UNION --- - -prelude.countBy(prelude.floor, [4.2, 6.1, 6.4]); //=> {4: 1, 6: 2} +var countByRes: Object = prelude.countBy(prelude.floor, [4.2, 6.1, 6.4]); +//=> {4: 1, 6: 2} prelude.countBy(x => x.length, ["one", "two", "three"]); //=> {3: 2, 5: 1} -prelude.groupBy(prelude.floor, [4.2, 6.1, 6.4]); //=> {4: [4.2], 6: [6.1, 6.4]} -prelude.groupBy(x => x.length, ["one", "two", "three"]); //=> {3: ["one", "two"], 5: ["three"]} +var groupByRes: Object = prelude.groupBy(prelude.floor, [4.2, 6.1, 6.4]); +//=> {4: [4.2], 6: [6.1, 6.4]} +prelude.groupBy(x => x.length, ["one", "two", "three"]); +//=> {3: ["one", "two"], 5: ["three"]} -prelude.andList([true, 2 + 2 == 4]); //=> true +var andListRes: boolean = prelude.andList([true, 2 + 2 == 4]); //=> true prelude.andList([true, true, false]); //=> false prelude.andList([]); //=> true -prelude.orList([false, false, true, false]); //=> true +var orListRes: boolean = prelude.orList([false, false, true, false]); //=> true prelude.orList([]); //=> false -prelude.any(prelude.even, [3, 5, 7, 8, 9]); //=> true +var anyRes: boolean = prelude.any(prelude.even, [3, 5, 7, 8, 9]); //=> true prelude.any(prelude.even, []); //=> false -prelude.all(prelude.isType("String"), ["ha", "ma", "la"]); //=> true +var allRes: boolean = prelude.all(prelude.isType("String"), ["ha", "ma", "la"]); +//=> true prelude.all(prelude.isType("String"), []); //=> true -prelude.sort([3, 1, 5, 2, 4, 6]); //=> [1, 2, 3, 4, 5, 6] +var sortRes: Array = prelude.sort([3, 1, 5, 2, 4, 6]); +//=> [1, 2, 3, 4, 5, 6] var f = (x: string) => (y: string) => x.length > y.length ? @@ -137,11 +140,18 @@ var f = (x: string) => (y: string) => -1 : 0; -prelude.sortWith(f, ["three", "one", "two"]); //=> ["one", "two", "three"] -prelude.sortBy(x => x.length, ["there", "hey", "a", "ha"]); //=> ["a", "ha", "hey", "there"] +var sortWithRes: Array = prelude.sortWith(f, ["three", "one", "two"]); +//=> ["one", "two", "three"] -var table = [{ +var sortByRes: Array = + prelude.sortBy(x => x.length, ["there", "hey", "a", "ha"]); + //=> ["a", "ha", "hey", "there"] + +var table: Array<{ + id: number, + name: string +}> = [{ id: 1, name: "george" }, { diff --git a/prelude-ls/prelude-ls.d.ts b/prelude-ls/prelude-ls.d.ts index fde6ed1578..26c1890d4f 100644 --- a/prelude-ls/prelude-ls.d.ts +++ b/prelude-ls/prelude-ls.d.ts @@ -75,8 +75,8 @@ declare module "prelude-ls" { export function sort(xs: A[]): A[]; export function sortWith(f: (x: A) => (y: A) => number): (xs: A[]) => A[]; export function sortWith(f: (x: A) => (y: A) => number, xs: A[]): A[]; - export function sortBy(f: (x: A) => B): (xs: A[]) => A; - export function sortBy(f: (x: A) => B, xs: A[]): A; + export function sortBy(f: (x: A) => B): (xs: A[]) => A[]; + export function sortBy(f: (x: A) => B, xs: A[]): A[]; export function sum(xs: number[]): number[]; export function product(xs: number[]): number[]; export function mean(xs: number[]): number[]; From d8822b4a8c471de06715e6bb23a494e62a643c68 Mon Sep 17 00:00:00 2001 From: Haskell Camargo Date: Mon, 15 Jun 2015 00:00:47 -0300 Subject: [PATCH 008/144] Return type for sum, product and mean are number, not number[] --- prelude-ls/prelude-ls-tests.ts | 20 +++++++++++--------- prelude-ls/prelude-ls.d.ts | 6 +++--- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/prelude-ls/prelude-ls-tests.ts b/prelude-ls/prelude-ls-tests.ts index c04fb2277e..a92c3c4243 100644 --- a/prelude-ls/prelude-ls-tests.ts +++ b/prelude-ls/prelude-ls-tests.ts @@ -162,23 +162,25 @@ var table: Array<{ name: "donald" }]; prelude.sortBy(x => x.name, table); -//=> [{"id": 3, "name": "donald"}, {"id": 1, "name": "george"}, {"id": 2, "name": "mike"}] +//=> [{"id": 3, "name": "donald"}, +// {"id": 1, "name": "george"}, +// {"id": 2, "name": "mike"}] -prelude.sum([1, 2, 3, 4, 5]); //=> 15 +var sumRes: number = prelude.sum([1, 2, 3, 4, 5]); //=> 15 prelude.sum([]); //=> 0 -prelude.product([1, 2, 3]); //=> 6 +var productRes: number = prelude.product([1, 2, 3]); //=> 6 prelude.product([]); //=> 1 -prelude.mean([1, 2, 3, 4, 5]); //=> 3 +var meanRes: number = prelude.mean([1, 2, 3, 4, 5]); //=> 3 -prelude.maximum([4, 1, 9, 3]); //=> 9 +var maximumRes: number = prelude.maximum([4, 1, 9, 3]); //=> 9 -prelude.minimum(["c", "e", "a", "d", "b"]); //=> "a" +var minimumRes: string = prelude.minimum(["c", "e", "a", "d", "b"]); //=> "a" -prelude.maximumBy(x => x.length, ["hi", "there", "I", "am", "looooong"]); //=> "looooong" - -prelude.maximumBy(x => x.length, ["hi", "there", "I", "am", "looooong"]); //=> "looooong" +var maximumByRes: string = + prelude.maximumBy(x => x.length, ["hi", "there", "I", "am", "looooong"]); + //=> "looooong" prelude.scan(x => y => x + y, 0, [1, 2, 3]); //=> [0, 1, 3, 6] diff --git a/prelude-ls/prelude-ls.d.ts b/prelude-ls/prelude-ls.d.ts index 26c1890d4f..053ed53a4a 100644 --- a/prelude-ls/prelude-ls.d.ts +++ b/prelude-ls/prelude-ls.d.ts @@ -77,9 +77,9 @@ declare module "prelude-ls" { export function sortWith(f: (x: A) => (y: A) => number, xs: A[]): A[]; export function sortBy(f: (x: A) => B): (xs: A[]) => A[]; export function sortBy(f: (x: A) => B, xs: A[]): A[]; - export function sum(xs: number[]): number[]; - export function product(xs: number[]): number[]; - export function mean(xs: number[]): number[]; + export function sum(xs: number[]): number; + export function product(xs: number[]): number; + export function mean(xs: number[]): number; export function maximum(xs: A[]): A; export function minimum(xs: A[]): A; export function maximumBy(f: (x: A) => B): (xs: A[]) => A; From e7c93592608108364fcbb09771c4a3222d9ac9dc Mon Sep 17 00:00:00 2001 From: Haskell Camargo Date: Mon, 15 Jun 2015 00:07:00 -0300 Subject: [PATCH 009/144] Passed tests for Prelude.List --- prelude-ls/prelude-ls-tests.ts | 51 ++++++++++++++++++++++------------ 1 file changed, 33 insertions(+), 18 deletions(-) diff --git a/prelude-ls/prelude-ls-tests.ts b/prelude-ls/prelude-ls-tests.ts index a92c3c4243..e21893e525 100644 --- a/prelude-ls/prelude-ls-tests.ts +++ b/prelude-ls/prelude-ls-tests.ts @@ -182,48 +182,63 @@ var maximumByRes: string = prelude.maximumBy(x => x.length, ["hi", "there", "I", "am", "looooong"]); //=> "looooong" -prelude.scan(x => y => x + y, 0, [1, 2, 3]); //=> [0, 1, 3, 6] +var scanRes: Array = prelude.scan(x => y => x + y, 0, [1, 2, 3]); +//=> [0, 1, 3, 6] -prelude.scan1(x => y => x + y, [1, 2, 3]); //=> [1, 3, 6] +var scan1Res: Array = prelude.scan1(x => y => x + y, [1, 2, 3]); +//=> [1, 3, 6] -prelude.scanr(x => y => x + y, 0, [1, 2, 3]); //=> [6, 5, 3, 0] +var scanrRes: Array = prelude.scanr(x => y => x + y, 0, [1, 2, 3]); +//=> [6, 5, 3, 0] -prelude.scanr1(x => y => x + y, [1, 2, 3]); //=> [6, 5, 3] +var scanr1Res: Array = prelude.scanr1(x => y => x + y, [1, 2, 3]); +//=> [6, 5, 3] -prelude.slice(2, 4, [1, 2, 3, 4, 5]); //=> [3, 4] +var sliceRes: Array = prelude.slice(2, 4, [1, 2, 3, 4, 5]); //=> [3, 4] -prelude.take(2, [1, 2, 3, 4, 5]); //=> [1, 2] +var takeRes: Array = prelude.take(2, [1, 2, 3, 4, 5]); //=> [1, 2] -prelude.drop(2, [1, 2, 3, 4, 5]); //=> [3, 4, 5] +var dropRes: Array = prelude.drop(2, [1, 2, 3, 4, 5]); //=> [3, 4, 5] -prelude.splitAt(2, [1, 2, 3, 4, 5]); //=> [[1, 2], [3, 4, 5]] +var splitAtRes: Array> = + prelude.splitAt(2, [1, 2, 3, 4, 5]); //=> [[1, 2], [3, 4, 5]] -prelude.takeWhile(prelude.odd, [1, 3, 5, 4, 8, 7, 9]); //=> [1, 3, 5] +var takeWhileRes: Array = + prelude.takeWhile(prelude.odd, [1, 3, 5, 4, 8, 7, 9]); //=> [1, 3, 5] -prelude.dropWhile(prelude.even, [2, 4, 5, 6]); //=> [5, 6] +var dropWhileRes: Array = + prelude.dropWhile(prelude.even, [2, 4, 5, 6]); //=> [5, 6] +var spanRes: Array> = prelude.span(prelude.even, [2, 4, 5, 6]); //=> [[2, 4], [5, 6]] -prelude.breakList(x => x == 3, [1, 2, 3, 4, 5]); //=> [[1, 2], [3, 4, 5]] +var breakListRes: Array> = + prelude.breakList(x => x == 3, [1, 2, 3, 4, 5]); //=> [[1, 2], [3, 4, 5]] -prelude.zip([1, 2, 3], [4, 5, 6]); //=> [[1, 4], [2, 5], [3, 6]] +var zipRes: Array> = prelude.zip([1, 2, 3], [4, 5, 6]); +//=> [[1, 4], [2, 5], [3, 6]] -prelude.zipWith(x => y => x + y, [1, 2, 3], [4, 5, 6]); //=> [5, 7, 9] +var zipWithRes: Array = + prelude.zipWith(x => y => x + y, [1, 2, 3], [4, 5, 6]); //=> [5, 7, 9] +var zipAllRes: Array> = prelude.zipAll([1, 2, 3], [4, 5, 6], [7, 8, 9]); //=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]] +var zipAllWithRes: Array = prelude.zipAllWith((a, b, c) => a + b + c, [1, 2, 3], [3, 2, 1], [1, 1, 1]); //=> [5, 5, 5] -prelude.at(2, [1, 2, 3, 4]); //=> 3 +var atRes: number = prelude.at(2, [1, 2, 3, 4]); //=> 3 prelude.at(-3, [1, 2, 3, 4]); //=> 2 -prelude.elemIndex("a", ["c", "a", "b", "a"]); //=> 1 +var elemIndexRes: number = prelude.elemIndex("a", ["c", "a", "b", "a"]); //=> 1 -prelude.elemIndices("a", ["c", "a", "b", "a"]); //=> [1, 3] +var elemIndicesRes: Array = + prelude.elemIndices("a", ["c", "a", "b", "a"]); //=> [1, 3] -prelude.findIndex(prelude.even, [1, 2, 3, 4]); //=> 1 +var findIndexRes: number = prelude.findIndex(prelude.even, [1, 2, 3, 4]); //=> 1 -prelude.findIndices(prelude.even, [1, 2, 3, 4]); //=> [1, 3] +var findIndicesRes: Array = + prelude.findIndices(prelude.even, [1, 2, 3, 4]); //=> [1, 3] // Obj From 835b936c5a3080da4f960631f23dadd0ccd69fe4 Mon Sep 17 00:00:00 2001 From: Haskell Camargo Date: Mon, 15 Jun 2015 00:16:37 -0300 Subject: [PATCH 010/144] Final tests --- prelude-ls/prelude-ls-tests.ts | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/prelude-ls/prelude-ls-tests.ts b/prelude-ls/prelude-ls-tests.ts index e21893e525..bea29403b2 100644 --- a/prelude-ls/prelude-ls-tests.ts +++ b/prelude-ls/prelude-ls-tests.ts @@ -242,19 +242,27 @@ var findIndicesRes: Array = // Obj -prelude.keys({a: 2, b: 3, c: 9}); //=> ["a", "b", "c"] +var keysRes: Array = prelude.keys({a: 2, b: 3, c: 9}); +//=> ["a", "b", "c"] -prelude.values({a: 2, b: 3, c: 9}); //=> [2, 3, 9] +var valuesRes: Array = prelude.values({a: 2, b: 3, c: 9}); +//=> [2, 3, 9] -prelude.pairsToObj([["a", "b"], ["c", "d"], ["e", 1]]); //=> {a: "b", c: "d", e: 1} +var pairsToObjRes: Object = + prelude.pairsToObj([["a", "b"], ["c", "d"], ["e", 1]]); //=> {a: "b", c: "d", e: 1} -prelude.objToPairs({a: "b", c: "d", e: 1}); //=> [["a", "b"], ["c", "d"], ["e", 1]] +var objToPairsRes: Array> = + prelude.objToPairs({a: "b", c: "d", e: 1}); + //=> [["a", "b"], ["c", "d"], ["e", 1]] -prelude.listsToObj(["a", "b", "c"], [1, 2, 3]); //=> {a: 1, b: 2, c: 3} +var listsToObjRes: Object = + prelude.listsToObj(["a", "b", "c"], [1, 2, 3]); //=> {a: 1, b: 2, c: 3} -prelude.objToLists({a: 1, b: 2, c: 3}); //=> [["a", "b", "c"], [1, 2, 3]] +var objToListsRes = + prelude.objToLists({a: 1, b: 2, c: 3}); + //=> [["a", "b", "c"], [1, 2, 3]] -prelude.Obj.empty({}); //=> true +var objEmptyRes: boolean = prelude.Obj.empty({}); //=> true var count = 4; prelude.Obj.each(x => count += x, {a: 1, b: 2, c: 3}); From 87ed92fda4291cbb83e58241ad7956ada6895662 Mon Sep 17 00:00:00 2001 From: Haskell Camargo Date: Mon, 15 Jun 2015 00:25:15 -0300 Subject: [PATCH 011/144] (;) for Travis --- prelude-ls/prelude-ls-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/prelude-ls/prelude-ls-tests.ts b/prelude-ls/prelude-ls-tests.ts index bea29403b2..dc36e9913b 100644 --- a/prelude-ls/prelude-ls-tests.ts +++ b/prelude-ls/prelude-ls-tests.ts @@ -149,8 +149,8 @@ var sortByRes: Array = //=> ["a", "ha", "hey", "there"] var table: Array<{ - id: number, - name: string + id: number; + name: string; }> = [{ id: 1, name: "george" From ed0860feecfaa4aab5ca62ffbe36c5e0fd0fa7fa Mon Sep 17 00:00:00 2001 From: Calvin Fernandez Date: Wed, 24 Jun 2015 18:59:57 -0400 Subject: [PATCH 012/144] added typings for codemirror's lint addon --- codemirror/codemirror-tests.ts | 30 ++++++++++++++++++++ codemirror/codemirror.d.ts | 51 ++++++++++++++++++++++++++++++++-- 2 files changed, 78 insertions(+), 3 deletions(-) diff --git a/codemirror/codemirror-tests.ts b/codemirror/codemirror-tests.ts index d81838ba95..d0da7f5228 100644 --- a/codemirror/codemirror-tests.ts +++ b/codemirror/codemirror-tests.ts @@ -16,3 +16,33 @@ var myCodeMirror4: CodeMirror.Editor = CodeMirror.fromTextArea(myTextArea); var doc: CodeMirror.Doc = new CodeMirror.Doc('text'); var doc2: CodeMirror.Doc = CodeMirror(document.body).getDoc(); + +var lintStateOptions: CodeMirror.LintStateOptions = { + async: true, + hasGutters: true +}; + +var lintOptions: CodeMirror.LintOptions = { + async: true, + hasGutters: true, + getAnnotations: (content: string, + updateLintingCallback: CodeMirror.UpdateLintingCallback, + options: CodeMirror.LintStateOptions, + codeMirror: CodeMirror.Editor) => {} +}; + +var updateLintingCallback: CodeMirror.UpdateLintingCallback = (codeMirror: CodeMirror.Editor, + annotations: CodeMirror.Annotation[]) => {}; + +var annotation: CodeMirror.Annotation = { + from: { + ch: 0, + line: 0 + }, + to: { + ch: 1, + line: 0 + }, + message: "test", + severity: "warning" +}; diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index 65692cf1c1..4b0a7ca6d4 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -761,7 +761,10 @@ declare module CodeMirror { This affects the amount of updates needed when scrolling, and the amount of work that such an update does. You should usually leave it at its default, 10. Can be set to Infinity to make sure the whole document is always rendered, and thus the browser's text search works on it. This will have bad effects on performance of big documents. */ - viewportMargin?: number; + viewportMargin?: number; + + /** Optional lint configuration to be used in conjunction with CodeMirror's linter addon. */ + lint?: LintOptions; } interface TextMarkerOptions { @@ -1004,6 +1007,48 @@ declare module CodeMirror { * Both modes get to parse all of the text, but when both assign a non-null style to a piece of code, the overlay wins, unless * the combine argument was true and not overridden, or state.overlay.combineTokens was true, in which case the styles are combined. */ - function overlayMode(base: Mode, overlay: Mode, combine?: boolean): Mode - + function overlayMode(base: Mode, overlay: Mode, combine?: boolean): Mode + + /** + * async specifies that the lint process runs asynchronously. hasGutters specifies that lint errors should be displayed in the CodeMirror + * gutter, note that you must use this in conjunction with [ "CodeMirror-lint-markers" ] as an element in the gutters argument on + * initialization of the CodeMirror instance. + */ + interface LintStateOptions { + async: boolean; + hasGutters: boolean; + } + + /** + * Adds the getAnnotations callback to LintStateOptions which may be overridden by the user if they choose use their own + * linter. + */ + interface LintOptions extends LintStateOptions { + getAnnotations: AnnotationsCallback; + } + + /** + * A function that calls the updateLintingCallback with any errors found during the linting process. + */ + interface AnnotationsCallback { + (content: string, updateLintingCallback: UpdateLintingCallback, options: LintStateOptions, codeMirror: Editor): void; + } + + /** + * A function that, given an array of annotations, updates the CodeMirror linting GUI with those annotations + */ + interface UpdateLintingCallback { + (codeMirror: Editor, annotations: Annotation[]): void; + } + + /** + * An annotation contains a description of a lint error, detailing the location of the error within the code, the severity of the error, + * and an explaination as to why the error was thrown. + */ + interface Annotation { + from: Position; + message?: string; + severity?: string; + to?: Position; + } } From 6a7dd893937af193d609f56cc2437d7838f0d154 Mon Sep 17 00:00:00 2001 From: mick delaney Date: Mon, 29 Jun 2015 14:43:57 +0100 Subject: [PATCH 013/144] Adding angular-rx --- angular-rx/rx.angular-tests.ts | 16 ++++++++++++++++ angular-rx/rx.angular.d.ts | 0 2 files changed, 16 insertions(+) create mode 100644 angular-rx/rx.angular-tests.ts create mode 100644 angular-rx/rx.angular.d.ts diff --git a/angular-rx/rx.angular-tests.ts b/angular-rx/rx.angular-tests.ts new file mode 100644 index 0000000000..f01d8e629f --- /dev/null +++ b/angular-rx/rx.angular-tests.ts @@ -0,0 +1,16 @@ +/// + +var app = angular.module('testModule'); + +interface AppScope extends rx.angular.IRxScope { +} + +app.controller('Ctrl', ($scope: AppScope) => { + + this.inputObservable = $scope.$toObservable('term') + .throttle(400) + .safeApply($scope, (results: any) => { + this.results = results; + }); + +}); diff --git a/angular-rx/rx.angular.d.ts b/angular-rx/rx.angular.d.ts new file mode 100644 index 0000000000..e69de29bb2 From fbe275ecb869091340e7c03adda1082a28cfe5d2 Mon Sep 17 00:00:00 2001 From: mick delaney Date: Mon, 29 Jun 2015 14:44:12 +0100 Subject: [PATCH 014/144] Adding angular-rx --- angular-rx/rx.angular.d.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/angular-rx/rx.angular.d.ts b/angular-rx/rx.angular.d.ts index e69de29bb2..f32933f6d2 100644 --- a/angular-rx/rx.angular.d.ts +++ b/angular-rx/rx.angular.d.ts @@ -0,0 +1,18 @@ +/// +/// +/// + +declare module Rx { + + interface IObservable { + safeApply($scope: ng.IScope, callback: (data: any) => void); + } +} + +declare module rx.angular { + + export interface IRxScope extends ng.IScope { + $toObservable(property: string): Rx.Observable; + } +} + From 5c6f06e42fc68dc2b7b2a6b7bc15277c9eb6c496 Mon Sep 17 00:00:00 2001 From: Luke Page Date: Tue, 30 Jun 2015 14:25:10 +0100 Subject: [PATCH 015/144] angular mocks - global inject is an alias Adjust the global inject to be an actual alias to the inject definition. This allows you to use the strict di version globally. Also updated links to new format. --- angularjs/angular-mocks.d.ts | 44 +++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/angularjs/angular-mocks.d.ts b/angularjs/angular-mocks.d.ts index 1c1966c1b0..e6b668a7b7 100644 --- a/angularjs/angular-mocks.d.ts +++ b/angularjs/angular-mocks.d.ts @@ -15,12 +15,6 @@ declare module "angular-mocks/ngAnimateMock" { export = _; } -/////////////////////////////////////////////////////////////////////////////// -// functions attached to global object (window) -/////////////////////////////////////////////////////////////////////////////// -declare var module: (...modules: any[]) => any; -declare var inject: (...fns: Function[]) => any; - /////////////////////////////////////////////////////////////////////////////// // ngMock module (angular-mocks.js) /////////////////////////////////////////////////////////////////////////////// @@ -33,30 +27,32 @@ declare module angular { interface IAngularStatic { mock: IMockStatic; } + + // see https://docs.angularjs.org/api/ngMock/function/angular.mock.inject + interface IInjectStatic { + (...fns: Function[]): any; + (...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works + strictDi(val?: boolean): void; + } interface IMockStatic { - // see http://docs.angularjs.org/api/angular.mock.dump + // see https://docs.angularjs.org/api/ngMock/function/angular.mock.dump dump(obj: any): string; - // see http://docs.angularjs.org/api/angular.mock.inject - inject: { - (...fns: Function[]): any; - (...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works - strictDi(val?: boolean): void; - } + inject: IInjectStatic - // see http://docs.angularjs.org/api/angular.mock.module + // see https://docs.angularjs.org/api/ngMock/function/angular.mock.module module(...modules: any[]): any; - // see http://docs.angularjs.org/api/angular.mock.TzDate + // see https://docs.angularjs.org/api/ngMock/type/angular.mock.TzDate TzDate(offset: number, timestamp: number): Date; TzDate(offset: number, timestamp: string): Date; } /////////////////////////////////////////////////////////////////////////// // ExceptionHandlerService - // see http://docs.angularjs.org/api/ngMock.$exceptionHandler - // see http://docs.angularjs.org/api/ngMock.$exceptionHandlerProvider + // see https://docs.angularjs.org/api/ngMock/service/$exceptionHandler + // see https://docs.angularjs.org/api/ngMock/provider/$exceptionHandlerProvider /////////////////////////////////////////////////////////////////////////// interface IExceptionHandlerProvider extends IServiceProvider { mode(mode: string): void; @@ -64,7 +60,7 @@ declare module angular { /////////////////////////////////////////////////////////////////////////// // TimeoutService - // see http://docs.angularjs.org/api/ngMock.$timeout + // see https://docs.angularjs.org/api/ngMock/service/$timeout // Augments the original service /////////////////////////////////////////////////////////////////////////// interface ITimeoutService { @@ -75,7 +71,7 @@ declare module angular { /////////////////////////////////////////////////////////////////////////// // IntervalService - // see http://docs.angularjs.org/api/ngMock.$interval + // see https://docs.angularjs.org/api/ngMock/service/$interval // Augments the original service /////////////////////////////////////////////////////////////////////////// interface IIntervalService { @@ -84,7 +80,7 @@ declare module angular { /////////////////////////////////////////////////////////////////////////// // LogService - // see http://docs.angularjs.org/api/ngMock.$log + // see https://docs.angularjs.org/api/ngMock/service/$log // Augments the original service /////////////////////////////////////////////////////////////////////////// interface ILogService { @@ -98,7 +94,7 @@ declare module angular { /////////////////////////////////////////////////////////////////////////// // HttpBackendService - // see http://docs.angularjs.org/api/ngMock.$httpBackend + // see https://docs.angularjs.org/api/ngMock/service/$httpBackend /////////////////////////////////////////////////////////////////////////// interface IHttpBackendService { flush(count?: number): void; @@ -237,3 +233,9 @@ declare module angular { } } + +/////////////////////////////////////////////////////////////////////////////// +// functions attached to global object (window) +/////////////////////////////////////////////////////////////////////////////// +declare var module: (...modules: any[]) => any; +declare var inject: angular.IInjectStatic; From 3623794ae9233b33a2d48f670226d0d99d74860e Mon Sep 17 00:00:00 2001 From: mick delaney Date: Wed, 1 Jul 2015 12:04:31 +0100 Subject: [PATCH 016/144] Updating Rx.Angular --- angular-rx/rx.angular-tests.ts | 5 +++++ angular-rx/rx.angular.d.ts | 7 ++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/angular-rx/rx.angular-tests.ts b/angular-rx/rx.angular-tests.ts index f01d8e629f..3caf011701 100644 --- a/angular-rx/rx.angular-tests.ts +++ b/angular-rx/rx.angular-tests.ts @@ -1,3 +1,8 @@ +// Type definitions for angularjs extensions to rxjs +// Project: http://reactivex.io/ +// Definitions by: Mick Delaney +// Definitions: https://github.com/borisyankov/DefinitelyTyped + /// var app = angular.module('testModule'); diff --git a/angular-rx/rx.angular.d.ts b/angular-rx/rx.angular.d.ts index f32933f6d2..e2d0ec8c5e 100644 --- a/angular-rx/rx.angular.d.ts +++ b/angular-rx/rx.angular.d.ts @@ -1,3 +1,8 @@ +// Type definitions for angularjs extensions to rxjs +// Project: http://reactivex.io/ +// Definitions by: Mick Delaney +// Definitions: https://github.com/borisyankov/DefinitelyTyped + /// /// /// @@ -5,7 +10,7 @@ declare module Rx { interface IObservable { - safeApply($scope: ng.IScope, callback: (data: any) => void); + safeApply($scope: ng.IScope, callback: (data: any) => void): Rx.Observable; } } From 37c762000842cb8152bb64a920e22552f6fc7c14 Mon Sep 17 00:00:00 2001 From: Tim Perry Date: Wed, 1 Jul 2015 14:45:36 +0100 Subject: [PATCH 017/144] More specific _.flatten type, remove types for non-existent methods --- lodash/lodash-tests.ts | 11 ++-- lodash/lodash.d.ts | 129 ++++++----------------------------------- 2 files changed, 24 insertions(+), 116 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index e0f2b82269..cd84de4175 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -239,10 +239,13 @@ result = _([1, 2, 3]).take(function (num) { result = _(foodsOrganic).take('organic').value(); result = _(foodsType).take({ 'type': 'fruit' }).value(); -result = _.flatten([1, [2], [3, [[4]]]]); -result = _.flatten([1, [2], [3, [[4]]]], true); -var result: any -result = _.flatten(stoogesQuotes, 'quotes'); +result = >_.flatten([[1, 2], [3, 4]]); +result = >_.flatten([[1, 2], [3, 4], 5, 6]); +result = >>>_.flatten([1, [2], [3, [[4]]]]); + +result = >_.flatten([1, [2], [[3]]], true); +result = >_.flatten([1, [2], [3, [[4]]]], true); +result = >_.flatten([1, [2], [3, [[false]]]], true); result = <_.LoDashArrayWrapper>_([1, [2], [3, [[4]]]]).flatten(); result = <_.LoDashArrayWrapper>_([1, [2], [3, [[4]]]]).flatten(true); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index a906b907f3..8c265cb8fe 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -769,123 +769,28 @@ declare module _ { take(whereValue: W): LoDashArrayWrapper; } + interface MaybeNestedList extends List> { } + interface RecursiveList extends List> { } + //_.flatten interface LoDashStatic { /** - * Flattens a nested array (the nesting can be to any depth). If isShallow is truey, the - * array will only be flattened a single level. If a callback is provided each element of - * the array is passed through the callback before flattening. The callback is bound to - * thisArg and invoked with three arguments; (value, index, array). - * - * If a property name is provided for callback the created "_.pluck" style callback will - * return the property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will return - * true for elements that have the properties of the given object, else false. - * @param array The array to flatten. - * @param shallow If true then only flatten one level, optional, default = false. - * @return `array` flattened. - **/ - flatten(array: Array, isShallow?: boolean): T[]; + * Flattens a nested array. + * + * @param array The array to flatten. + * @return `array` flattened. + **/ + flatten(array: MaybeNestedList): T[]; /** - * @see _.flatten - **/ - flatten(array: List, isShallow?: boolean): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: Array, - isShallow: boolean, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: List, - isShallow: boolean, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: Array, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: List, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: Array, - isShallow: boolean, - whereValue: W): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: List, - isShallow: boolean, - whereValue: W): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: Array, - whereValue: W): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: List, - whereValue: W): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: Array, - isShallow: boolean, - pluckValue: string): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: List, - isShallow: boolean, - pluckValue: string): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: Array, - pluckValue: string): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: List, - pluckValue: string): T[]; + * Flattens a nested array. If isDeep is true the array is recursively flattened, otherwise it is only + * flattened a single level. + * + * @param array The array to flatten. + * @param deep Specify a deep flatten. + * @return `array` flattened. + **/ + flatten(array: RecursiveList, isDeep: boolean): T[]; } interface LoDashArrayWrapper { From 36f2158f0c594efabc7b2ce30ae5a34bd042d6bc Mon Sep 17 00:00:00 2001 From: Tim Perry Date: Wed, 1 Jul 2015 14:58:39 +0100 Subject: [PATCH 018/144] Fix _().flatten() - remove non-existent methods, small type improvement Previously type was too specific, and thereby often wrong. It's now less specific, but never wrong. --- lodash/lodash-tests.ts | 5 +++-- lodash/lodash.d.ts | 44 ++++-------------------------------------- 2 files changed, 7 insertions(+), 42 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index cd84de4175..709151f166 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -247,9 +247,10 @@ result = >_.flatten([1, [2], [[3]]], true); result = >_.flatten([1, [2], [3, [[4]]]], true); result = >_.flatten([1, [2], [3, [[false]]]], true); -result = <_.LoDashArrayWrapper>_([1, [2], [3, [[4]]]]).flatten(); +result = <_.LoDashArrayWrapper>_([[1, 2], [3, 4], 5, 6]).flatten(); +result = <_.LoDashArrayWrapper>>>_([1, [2], [3, [[4]]]]).flatten(); + result = <_.LoDashArrayWrapper>_([1, [2], [3, [[4]]]]).flatten(true); -result = <_.LoDashArrayWrapper>_(stoogesQuotes).flatten('quotes'); result = _.indexOf([1, 2, 3, 1, 2, 3], 2); result = _.indexOf([1, 2, 3, 1, 2, 3], 2, 3); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 8c265cb8fe..c0f0bd5d5f 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -795,50 +795,14 @@ declare module _ { interface LoDashArrayWrapper { /** - * @see _.flatten - **/ - flatten(isShallow?: boolean): LoDashArrayWrapper; + * @see _.flatten + **/ + flatten(): LoDashArrayWrapper; /** * @see _.flatten **/ - flatten( - isShallow: boolean, - callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; - - /** - * @see _.flatten - **/ - flatten( - callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; - - /** - * @see _.flatten - **/ - flatten( - isShallow: boolean, - pluckValue: string): LoDashArrayWrapper; - - /** - * @see _.flatten - **/ - flatten( - pluckValue: string): LoDashArrayWrapper; - - /** - * @see _.flatten - **/ - flatten( - isShallow: boolean, - whereValue: W): LoDashArrayWrapper; - - /** - * @see _.flatten - **/ - flatten( - whereValue: W): LoDashArrayWrapper; + flatten(isShallow: boolean): LoDashArrayWrapper; } //_.indexOf From ed15e4bd3806d00223f40803a7d13d0d3ada111e Mon Sep 17 00:00:00 2001 From: Tim Perry Date: Wed, 1 Jul 2015 16:14:31 +0100 Subject: [PATCH 019/144] Make _.flatten(array, bool) slightly more general --- lodash/lodash.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c0f0bd5d5f..e79eb64f81 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -790,7 +790,7 @@ declare module _ { * @param deep Specify a deep flatten. * @return `array` flattened. **/ - flatten(array: RecursiveList, isDeep: boolean): T[]; + flatten(array: RecursiveList, isDeep: boolean): List | RecursiveList; } interface LoDashArrayWrapper { From 85c339b16f12d33f4ace6eaa6fe8607509d32724 Mon Sep 17 00:00:00 2001 From: Eric HILLAH Date: Thu, 2 Jul 2015 17:18:07 +0200 Subject: [PATCH 020/144] Adds blob-stream definition files --- blob-stream/blob-stream-tests.ts | 6 ++++++ blob-stream/blob-stream.d.ts | 20 ++++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 blob-stream/blob-stream-tests.ts create mode 100644 blob-stream/blob-stream.d.ts diff --git a/blob-stream/blob-stream-tests.ts b/blob-stream/blob-stream-tests.ts new file mode 100644 index 0000000000..85878c0238 --- /dev/null +++ b/blob-stream/blob-stream-tests.ts @@ -0,0 +1,6 @@ +/// + +var bl = BlobStream(); + +var blob = bl.toBlob("aplication/PDF"); +var brl = bl.toBlobURL("app/JSON"); \ No newline at end of file diff --git a/blob-stream/blob-stream.d.ts b/blob-stream/blob-stream.d.ts new file mode 100644 index 0000000000..17f142bbbd --- /dev/null +++ b/blob-stream/blob-stream.d.ts @@ -0,0 +1,20 @@ +// Type definitions for Pdfkit v0.7.1 +// Project: https://github.com/devongovett/blob-stream +// Definitions by: Eric Hillah +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare function BlobStream(): BlobStream.IBlobStream; + +declare module BlobStream { + + interface IBlobStream extends NodeJS.WritableStream{ + toBlob(type: string): Blob; + toBlobURL(type: string): string; + } +} + +declare module "blob-stream" { + export = BlobStream; +} From 0c3aca7cf598a53d44ef39fcaf899a1292532b84 Mon Sep 17 00:00:00 2001 From: Tanguy Krotoff Date: Thu, 2 Jul 2015 18:47:57 +0200 Subject: [PATCH 021/144] Improve returning type for insert, update and delete --- knex/knex-test.ts | 20 ++++++++++++-------- knex/knex.d.ts | 10 +++++----- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/knex/knex-test.ts b/knex/knex-test.ts index 39b441d6b0..d15786736d 100644 --- a/knex/knex-test.ts +++ b/knex/knex-test.ts @@ -198,6 +198,7 @@ knex('books').insert({title: 'Slaughterhouse Five'}); knex('coords').insert([{x: 20}, {y: 30}, {x: 10, y: 20}]); knex.insert([{title: 'Great Gatsby'}, {title: 'Fahrenheit 451'}], 'id').into('books'); +knex.insert([{title: 'Great Gatsby'}, {title: 'Fahrenheit 451'}], ['id', 'title']).into('books'); knex('books') .returning('id') @@ -207,17 +208,20 @@ knex('books') .returning('id') .insert([{title: 'Great Gatsby'}, {title: 'Fahrenheit 451'}]); -knex('books') - .where('published_date', '<', 2000) - .update({ - status: 'archived' - }); +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']); knex('books').update('title', 'Slaughterhouse Five'); +knex('books').update('title', 'Slaughterhouse Five', 'id'); +knex('books').update('title', 'Slaughterhouse Five', ['id', 'title']); -knex('accounts') - .where('activated', false) - .del(); +knex('accounts').where('activated', false).del(); +knex('accounts').where('activated', false).del('id'); +knex('accounts').where('activated', false).del(['id', 'title']); +knex('accounts').where('activated', false).delete(); +knex('accounts').where('activated', false).delete('id'); +knex('accounts').where('activated', false).delete(['id', 'title']); var someExternalMethod: Function; diff --git a/knex/knex.d.ts b/knex/knex.d.ts index c4408aecb3..5300cd3c47 100644 --- a/knex/knex.d.ts +++ b/knex/knex.d.ts @@ -131,13 +131,13 @@ declare module "knex" { debug(enabled?: boolean): QueryBuilder; pluck(column: string): QueryBuilder; - insert(data: any, returning?: string): QueryBuilder; - update(data: any, returning?: string): QueryBuilder; - update(columnName: string, value: Value, returning?: string): QueryBuilder; + insert(data: any, returning?: string | string[]): QueryBuilder; + update(data: any, returning?: string | string[]): QueryBuilder; + update(columnName: string, value: Value, returning?: string | string[]): QueryBuilder; returning(column: string): QueryBuilder; - del(returning?: string): QueryBuilder; - delete(returning?: string): QueryBuilder; + del(returning?: string | string[]): QueryBuilder; + delete(returning?: string | string[]): QueryBuilder; truncate(): QueryBuilder; transacting(trx: Transaction): QueryBuilder; From eb2d3502caf0dbc723cf03897f1d27fa5042584f Mon Sep 17 00:00:00 2001 From: Stefan Steinhart Date: Thu, 2 Jul 2015 21:26:28 +0200 Subject: [PATCH 022/144] + typings for angular-throttle --- angular-throttle/angular-throttle-tests.ts | 8 ++++++++ angular-throttle/angular-throttle.d.ts | 12 ++++++++++++ 2 files changed, 20 insertions(+) create mode 100644 angular-throttle/angular-throttle-tests.ts create mode 100644 angular-throttle/angular-throttle.d.ts diff --git a/angular-throttle/angular-throttle-tests.ts b/angular-throttle/angular-throttle-tests.ts new file mode 100644 index 0000000000..5577e08c52 --- /dev/null +++ b/angular-throttle/angular-throttle-tests.ts @@ -0,0 +1,8 @@ +/// +/// + +var throttledFn = angular.throttle(function (someArg:any) { + return someArg; +}, 100); + +var result = throttledFn(10); diff --git a/angular-throttle/angular-throttle.d.ts b/angular-throttle/angular-throttle.d.ts new file mode 100644 index 0000000000..eeca0d1bca --- /dev/null +++ b/angular-throttle/angular-throttle.d.ts @@ -0,0 +1,12 @@ +// Type definitions for angular-throttle +// Project: https://github.com/BaggersIO/angular.throttle +// Definitions by: Stefan Steinhart +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module angular { + interface IAngularStatic { + throttle:( fn:Function, throttle:number, options?:{leading?:boolean; trailing?:boolean;} ) => Function; + } +} From f1b0c27ff14a851f8dd2dcb55f27fee79f8fec2a Mon Sep 17 00:00:00 2001 From: mick delaney Date: Fri, 3 Jul 2015 15:58:31 +0100 Subject: [PATCH 023/144] Move angular-rx to rx-angular, match Rx conventions --- {angular-rx => rx-angular}/rx.angular-tests.ts | 0 {angular-rx => rx-angular}/rx.angular.d.ts | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename {angular-rx => rx-angular}/rx.angular-tests.ts (100%) rename {angular-rx => rx-angular}/rx.angular.d.ts (100%) diff --git a/angular-rx/rx.angular-tests.ts b/rx-angular/rx.angular-tests.ts similarity index 100% rename from angular-rx/rx.angular-tests.ts rename to rx-angular/rx.angular-tests.ts diff --git a/angular-rx/rx.angular.d.ts b/rx-angular/rx.angular.d.ts similarity index 100% rename from angular-rx/rx.angular.d.ts rename to rx-angular/rx.angular.d.ts From bfefac3091b80691e921a0be49feb0fefcf4b128 Mon Sep 17 00:00:00 2001 From: Stefan Steinhart Date: Fri, 3 Jul 2015 18:57:21 +0200 Subject: [PATCH 024/144] renaming to angular.throttle --- .../angular.throttle-tests.ts | 2 +- .../angular.throttle.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename angular-throttle/angular-throttle-tests.ts => angular.throttle/angular.throttle-tests.ts (78%) rename angular-throttle/angular-throttle.d.ts => angular.throttle/angular.throttle.d.ts (90%) diff --git a/angular-throttle/angular-throttle-tests.ts b/angular.throttle/angular.throttle-tests.ts similarity index 78% rename from angular-throttle/angular-throttle-tests.ts rename to angular.throttle/angular.throttle-tests.ts index 5577e08c52..2234adbc37 100644 --- a/angular-throttle/angular-throttle-tests.ts +++ b/angular.throttle/angular.throttle-tests.ts @@ -1,4 +1,4 @@ -/// +/// /// var throttledFn = angular.throttle(function (someArg:any) { diff --git a/angular-throttle/angular-throttle.d.ts b/angular.throttle/angular.throttle.d.ts similarity index 90% rename from angular-throttle/angular-throttle.d.ts rename to angular.throttle/angular.throttle.d.ts index eeca0d1bca..0a3033e67a 100644 --- a/angular-throttle/angular-throttle.d.ts +++ b/angular.throttle/angular.throttle.d.ts @@ -1,4 +1,4 @@ -// Type definitions for angular-throttle +// Type definitions for angular.throttle // Project: https://github.com/BaggersIO/angular.throttle // Definitions by: Stefan Steinhart // Definitions: https://github.com/borisyankov/DefinitelyTyped From 4c0cb630a819d47d5386082ce31d807810815bc8 Mon Sep 17 00:00:00 2001 From: Eric HILLAH Date: Fri, 3 Jul 2015 22:23:49 +0200 Subject: [PATCH 025/144] Change comment --- blob-stream/blob-stream-tests.ts | 5 +++-- blob-stream/blob-stream.d.ts | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/blob-stream/blob-stream-tests.ts b/blob-stream/blob-stream-tests.ts index 85878c0238..574dfc044d 100644 --- a/blob-stream/blob-stream-tests.ts +++ b/blob-stream/blob-stream-tests.ts @@ -1,6 +1,7 @@ /// +/// -var bl = BlobStream(); +var bl = require('blob-stream'); var blob = bl.toBlob("aplication/PDF"); -var brl = bl.toBlobURL("app/JSON"); \ No newline at end of file +var brl = bl.toBlobURL("app/JSON"); diff --git a/blob-stream/blob-stream.d.ts b/blob-stream/blob-stream.d.ts index 17f142bbbd..5c62155b64 100644 --- a/blob-stream/blob-stream.d.ts +++ b/blob-stream/blob-stream.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Pdfkit v0.7.1 +// Type definitions for blob-stream v0.1.3 // Project: https://github.com/devongovett/blob-stream // Definitions by: Eric Hillah // Definitions: https://github.com/borisyankov/DefinitelyTyped From 1c19445106678aa3296f993f2dc0aa15a034fa5a Mon Sep 17 00:00:00 2001 From: vote539 Date: Fri, 3 Jul 2015 16:05:38 -0700 Subject: [PATCH 026/144] Update stylus.d.ts The Stylus "middleware" function accepts either a string or an options hash as its argument. See https://github.com/stylus/stylus/blob/master/lib/middleware.js#L86 --- stylus/stylus.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/stylus/stylus.d.ts b/stylus/stylus.d.ts index d6fd6ef5ba..5809570b90 100644 --- a/stylus/stylus.d.ts +++ b/stylus/stylus.d.ts @@ -43,6 +43,7 @@ declare module Stylus { * Expose middleware. */ middleware(dir: string): Middleware; + middleware(options: any): Middleware; /** * Convert the given `css` to `stylus` source. From 97f251cef19e557391588889493103c15fffde12 Mon Sep 17 00:00:00 2001 From: Toshiya Nakakura Date: Sun, 5 Jul 2015 13:16:47 +0900 Subject: [PATCH 027/144] add webvr-api definition --- webvr-api/webvr-api-test.ts | 62 +++++++++++++ webvr-api/webvr-api.d.ts | 175 ++++++++++++++++++++++++++++++++++++ 2 files changed, 237 insertions(+) create mode 100644 webvr-api/webvr-api-test.ts create mode 100644 webvr-api/webvr-api.d.ts diff --git a/webvr-api/webvr-api-test.ts b/webvr-api/webvr-api-test.ts new file mode 100644 index 0000000000..df2a72438a --- /dev/null +++ b/webvr-api/webvr-api-test.ts @@ -0,0 +1,62 @@ +/// + +function fieldOfViewToProjectionMatrix(fov: WebVRApi.VRFieldOfView, zNear: number, zFar: number) { + var upTan = Math.tan(fov.upDegrees * Math.PI/180.0); + var downTan = Math.tan(fov.downDegrees * Math.PI/180.0); + var leftTan = Math.tan(fov.leftDegrees * Math.PI/180.0); + var rightTan = Math.tan(fov.rightDegrees * Math.PI/180.0); + var xScale = 2.0 / (leftTan + rightTan); + var yScale = 2.0 / (upTan + downTan); + + var out = new Float32Array(16); + out[0] = xScale; + out[1] = 0.0; + out[2] = 0.0; + out[3] = 0.0; + out[4] = 0.0; + out[5] = yScale; + out[6] = 0.0; + out[7] = 0.0; + out[8] = -((leftTan - rightTan) * xScale * 0.5); + out[9] = ((upTan - downTan) * yScale * 0.5); + out[10] = -(zNear + zFar) / (zFar - zNear); + out[11] = -1.0; + out[12] = 0.0; + out[13] = 0.0; + out[14] = -(2.0 * zFar * zNear) / (zFar - zNear); + out[15] = 0.0; + + return out; +} + +var hmd: HMDVRDevice; +var leftEyeParams = hmd.getEyeParameters("left"); +var rightEyeParams = hmd.getEyeParameters("right"); +var leftEyeRect = leftEyeParams.renderRect; +var rightEyeRect = rightEyeParams.renderRect; + +var canvas: HTMLCanvasElement; +canvas.width = rightEyeRect.x + rightEyeRect.width; +canvas.height = Math.max(leftEyeRect.y + leftEyeRect.height, rightEyeRect.y + rightEyeRect.height); + +var gHMD: WebVRApi.VRDevice; +var gPositionSensor: WebVRApi.VRDevice; + +navigator.getVRDevices().then(function(devices) { + for (var i = 0; i < devices.length; ++i) { + if (devices[i] instanceof HMDVRDevice) { + gHMD = devices[i]; + break; + } + } + + if (gHMD) { + for (var i = 0; i < devices.length; ++i) { + if (devices[i] instanceof PositionSensorVRDevice && + devices[i].hardwareUnitId == gHMD.hardwareUnitId) { + gPositionSensor = devices[i]; + break; + } + } + } +}); diff --git a/webvr-api/webvr-api.d.ts b/webvr-api/webvr-api.d.ts new file mode 100644 index 0000000000..16918cf303 --- /dev/null +++ b/webvr-api/webvr-api.d.ts @@ -0,0 +1,175 @@ +// Type definitions for WebVR API +// Project: http://mozvr.github.io/webvr-spec/webvr.html +// Definitions by: Toshiya Nakakura +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare type VREye = string; + +declare module WebVRApi { + export interface VRFieldOfViewReadOnly { + upDegrees: number; + rightDegrees: number; + downDegrees: number; + leftDegrees: number; + } + + export interface VRFieldOfViewInit { + upDegrees: number; + rightDegrees: number; + downDegrees: number; + leftDegrees: number; + } + + export interface VRFieldOfView extends VRFieldOfViewReadOnly { + constructor(upDegrees:number, rightDegrees:number, downDegrees:number, leftDegrees:number): VRFieldOfView; + upDegrees: number; + rightDegrees: number; + downDegrees: number; + leftDegrees: number; + } + + export interface VRPositionState { + /** + * Monotonically increasing value that allows the author to determine if position state data been updated from the hardware. + */ + timeStamp: number; + /** + * True if the position attribute is valid. If false position MUST be null. + */ + hasPosition: boolean; + /** + * Position of the sensor at timeStamp as a 3D vector. + */ + position?: GeometryDom.DOMPoint; + /** + * Linear velocity of the sensor at timeStamp. + */ + linearVelocity?: GeometryDom.DOMPoint; + /** + * Linear acceleration of the sensor at timeStamp. + */ + linearAcceleration?: GeometryDom.DOMPoint; + /** + * True if the orientation attribute is valid. If false orientation MUST be null. + */ + hasOrientation: boolean; + /** + * Orientation of the sensor at timeStamp as a quaternion. + */ + orientation?: GeometryDom.DOMPoint; + /** + * Angular velocity of the sensor at timeStamp. + */ + angularVelocity?: GeometryDom.DOMPoint; + /** + * Angular acceleration of the sensor at timeStamp. + */ + angularAcceleration?: GeometryDom.DOMPoint; + } + + export interface VREyeParameters { + /** + * Describes the minimum supported field of view for the eye. + */ + minimumFieldOfView: VRFieldOfView; + /** + * Describes the maximum supported field of view for the eye. + */ + maximumFieldOfView: VRFieldOfView; + /** + * Describes the recommended field of view for the eye. + */ + recommendedFieldOfView: VRFieldOfView; + /** + * Offset from the center of the users head to the eye in meters. + */ + eyeTranslation: GeometryDom.DOMPoint; + /** + * The current field of view for the eye, as specified by setFieldOfView. + */ + currentFieldOfView: VRFieldOfView; + /** + * Describes the viewport of a canvas into which visuals for this eye should be rendered. + */ + renderRect: GeometryDom.DOMRect; + } + + export interface VRDevice { + /** + * An identifier for the distinct hardware unit that this VRDevice is a part of. + */ + hardwareUnitId: string; + /** + * An identifier for this distinct sensor/device on a physical hardware device. + */ + deviceId: string; + /** + * A user-readable name identifying the device. + */ + deviceName: string; + } +} + +declare class HMDVRDevice implements WebVRApi.VRDevice { + /** + * An identifier for the distinct hardware unit that this VRDevice is a part of. + */ + hardwareUnitId: string; + /** + * An identifier for this distinct sensor/device on a physical hardware device. + */ + deviceId: string; + /** + * A user-readable name identifying the device. + */ + deviceName: string; + + /** + * Return the current VREyeParameters for the given eye. + */ + getEyeParameters(whichEye: VREye): WebVRApi.VREyeParameters; + /** + * Set the field of view for both eyes. If + */ + setFieldOfView(leftFOV?: WebVRApi.VRFieldOfViewInit, rightFOV?: WebVRApi.VRFieldOfViewInit, zNear?: number, zFar?: number): void; +} + +declare class PositionSensorVRDevice implements WebVRApi.VRDevice { + /** + * An identifier for the distinct hardware unit that this VRDevice is a part of. + */ + hardwareUnitId: string; + /** + * An identifier for this distinct sensor/device on a physical hardware device. + */ + deviceId: string; + /** + * A user-readable name identifying the device. + */ + deviceName: string; + + /** + * Return a VRPositionState dictionary containing the state of this position sensor state for the current frame (if within a requestAnimationFrame context) or for the previous frame. + */ + getState(): WebVRApi.VRPositionState; + /** + * Return the current instantaneous sensor state. + */ + getImmediateState(): WebVRApi.VRPositionState; + + /** + * Reset this sensor, treating its current position and orientation yaw as the "origin/zero" values. + */ + resetSensor(): void; +} + +interface Navigator { + /** + * Return a Promise which resolves to a list of available VRDevices. + */ + getVRDevices(): Promise>; +} + From 38f9105341f7f8d1044690c3e533f7fc6b1b5531 Mon Sep 17 00:00:00 2001 From: Andrey Kurdyumov Date: Sun, 5 Jul 2015 15:56:44 +0600 Subject: [PATCH 028/144] Add support for node-steam library --- steam/steam-tests.ts | 13 +++++++++ steam/steam.d.ts | 64 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 steam/steam-tests.ts create mode 100644 steam/steam.d.ts diff --git a/steam/steam-tests.ts b/steam/steam-tests.ts new file mode 100644 index 0000000000..4bca1059ee --- /dev/null +++ b/steam/steam-tests.ts @@ -0,0 +1,13 @@ +// Type definitions for steam +// Project: https://github.com/seishun/node-steam +// Definitions by: Andrey Kurdyumov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +var bot = new Steam.SteamClient(); +bot.logOn({ + accountName: 'username', + password: 'password' +}); +bot.on('loggedOn', function () { /* ... */ }); diff --git a/steam/steam.d.ts b/steam/steam.d.ts new file mode 100644 index 0000000000..3f31aef3f1 --- /dev/null +++ b/steam/steam.d.ts @@ -0,0 +1,64 @@ +// Type definitions for steam +// Project: https://github.com/seishun/node-steam +// Definitions by: Andrey Kurdyumov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Steam { + export var servers: any; + + export interface LogonOptions { + accountName: string; + password: string; + shaSentryfile?: string; + authCode?: string; + } + + export enum EResult { + AccountLogonDenied + } + + export enum EPersonaState { + Online + } + + export enum EChatEntryType { + ChatMsg + } + + export enum EChatMemberStateChange { + Kicked + } + + export class SteamClient implements NodeJS.EventEmitter { + sessionId: string; + cookie: string[]; + steamID: string; + users: {}; + + logOn(options: LogonOptions): void; + webLogOn(callback: (cookie: any[]) => void): void; + + joinChat(chatId: string): void; + sendMessage(source: any, message: string, entryType: EChatEntryType): void; + + setPersonaState(state: EPersonaState): void; + setPersonaName(name: string): void; + + // Event emitter + addListener(event: string, listener: Function): NodeJS.EventEmitter; + on(event: string, listener: Function): NodeJS.EventEmitter; + once(event: string, listener: Function): NodeJS.EventEmitter; + removeListener(event: string, listener: Function): NodeJS.EventEmitter; + removeAllListeners(event?: string): NodeJS.EventEmitter; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + } +} + +declare module "steam" { + export = Steam; +} + From e893bff332cc3a77ef18828392d98463f2f1e2cf Mon Sep 17 00:00:00 2001 From: Legokichi Duckscallion Date: Mon, 6 Jul 2015 00:44:30 +0900 Subject: [PATCH 029/144] MediaStream extends EventTarget --- webrtc/MediaStream-tests.ts | 2 ++ webrtc/MediaStream.d.ts | 5 ++--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/webrtc/MediaStream-tests.ts b/webrtc/MediaStream-tests.ts index fde0d65dfb..0d4e710b83 100644 --- a/webrtc/MediaStream-tests.ts +++ b/webrtc/MediaStream-tests.ts @@ -23,6 +23,7 @@ navigator.webkitGetUserMedia(mediaStreamConstraints, console.log('label:' + stream.label); console.log('ended:' + stream.ended); stream.onended = (event:Event) => console.log('Stream ended'); + stream.addEventListener("ended", (event:Event) => console.log('Stream ended')); var objectUrl = URL.createObjectURL(stream); var wkObjectUrl = webkitURL.createObjectURL(stream); }, @@ -37,6 +38,7 @@ navigator.mozGetUserMedia(mediaStreamConstraints, console.log('label:' + stream.label); console.log('ended:' + stream.ended); stream.onended = (event:Event) => console.log('Stream ended'); + stream.addEventListener("ended", (event:Event) => console.log('Stream ended')); var objectUrl = URL.createObjectURL(stream); var wkObjectUrl = webkitURL.createObjectURL(stream); }, diff --git a/webrtc/MediaStream.d.ts b/webrtc/MediaStream.d.ts index 98afabf47d..54de34e386 100644 --- a/webrtc/MediaStream.d.ts +++ b/webrtc/MediaStream.d.ts @@ -88,7 +88,7 @@ declare var webkitMediaStreamTrackList: { new (): MediaStreamTrackList; }; -interface MediaStream { +interface MediaStream extends EventTarget{ label: string; id: string; getAudioTracks(): MediaStreamTrackList; @@ -126,7 +126,7 @@ interface LocalMediaStream extends MediaStream { stop(): void; } -interface MediaStreamTrack { +interface MediaStreamTrack extends EventTarget{ kind: string; label: string; enabled: boolean; @@ -163,4 +163,3 @@ declare var webkitURL: { new (): streamURL; createObjectURL(stream: MediaStream): string; }; - From 5d139c17006438dfa12c790551808a7980e07c5b Mon Sep 17 00:00:00 2001 From: Moes Date: Mon, 6 Jul 2015 12:23:51 +1000 Subject: [PATCH 030/144] Update jquery.fileuplade.d.ts Extend JQueryFileUpload from JQuery to enable chaining, add JQuerySupport Interface --- jquery.fileupload/jquery.fileupload.d.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/jquery.fileupload/jquery.fileupload.d.ts b/jquery.fileupload/jquery.fileupload.d.ts index 0ac8b98f96..3774cb6e1c 100644 --- a/jquery.fileupload/jquery.fileupload.d.ts +++ b/jquery.fileupload/jquery.fileupload.d.ts @@ -5,7 +5,6 @@ /// - // Interface options for the plugin interface JQueryFileInputOptions { @@ -152,13 +151,15 @@ interface JQueryFileInputOptions { } -interface JQueryFileUpload { - +interface JQueryFileUpload extends JQuery { contentType:string; } -interface JQuery -{ +interface JQuery { // Interface to the main method of jQuery File Upload fileupload(settings: JQueryFileInputOptions): JQueryFileUpload; -} \ No newline at end of file +} + +interface JQuerySupport { + fileInput?: boolean; +} From fbb93b57aabec8d126c4cad17c6103833da3f0b4 Mon Sep 17 00:00:00 2001 From: RareGrass Date: Mon, 6 Jul 2015 10:57:07 +0800 Subject: [PATCH 031/144] Update node.d.ts Add the http.METHODS string array --- node/node.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/node/node.d.ts b/node/node.d.ts index 2865aedd4e..6544d3c10c 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -539,6 +539,8 @@ declare module "http" { destroy(): void; } + export var METHODS: string[]; + export var STATUS_CODES: { [errorCode: number]: string; [errorCode: string]: string; From b313d0eb6b3690751f7a4e5820319d1d49c2932f Mon Sep 17 00:00:00 2001 From: Marcelo Camargo Date: Mon, 6 Jul 2015 02:24:21 -0300 Subject: [PATCH 032/144] FullCalendar also accepts strings as dates --- fullCalendar/fullCalendar.d.ts | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/fullCalendar/fullCalendar.d.ts b/fullCalendar/fullCalendar.d.ts index feb537e67b..f73dc2d8bf 100644 --- a/fullCalendar/fullCalendar.d.ts +++ b/fullCalendar/fullCalendar.d.ts @@ -1,6 +1,6 @@ // Type definitions for FullCalendar 1.6.1 // Project: http://arshaw.com/fullcalendar/ -// Definitions by: Neil Stalker +// Definitions by: Neil Stalker , Marcelo Camargo // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -99,7 +99,7 @@ declare module FullCalendar { selectHelper?: any; // Boolean/Function unselectAuto?: boolean; unselectCancel?: string; - select?: (startDate: Date, endDate: Date, allDay: boolean, jsEvent: MouseEvent, view: View) => void; + select?: (startDate: Date | string, endDate: Date | string, allDay: boolean, jsEvent: MouseEvent, view: View) => void; unselect?: (view: View, jsEvent: Event) => void; // Event Data - http://arshaw.com/fullcalendar/docs/event_data/ @@ -109,7 +109,7 @@ declare module FullCalendar { * * - EventObject[] * - string (JSON feed) - * - (start: Date, end: Date, callback: {(events: EventObject[]) => void;}) => void; + * - (start: Date | string, end: Date | string, callback: {(events: EventObject[]) => void;}) => void; */ events?: any; @@ -119,7 +119,7 @@ declare module FullCalendar { * - EventSource * - EventObject[] * - string (JSON feed) - * - (start: Date, end: Date, callback: {(events: EventObject[]) => void;}) => void; + * - (start: Date | string, end: Date | string, callback: {(events: EventObject[]) => void;}) => void; */ eventSources?: any[]; @@ -164,8 +164,8 @@ declare module FullCalendar { export interface View { name: string; title: string; - start: Date; - end: Date; + start: Date | string; + end: Date | string; visStart: Date; visEnd: Date; } @@ -214,8 +214,8 @@ declare module FullCalendar { id?: any // String/number title: string; allDay?: boolean; - start: Date; - end?: Date; + start: Date | string; + end?: Date | string; url?: string; className?: any; // string/Array editable?: boolean; @@ -233,7 +233,7 @@ declare module FullCalendar { * * - EventObject[] * - string (JSON feed) - * - (start: Date, end: Date, callback: {(events: EventObject[]) => void;}) => void; + * - (start: Date | string, end: Date | string, callback: {(events: EventObject[]) => void;}) => void; */ events?: any; @@ -312,7 +312,7 @@ interface JQuery { /** * Moves the calendar to an arbitrary date. */ - fullCalendar(method: 'gotoDate', date: Date): void; + fullCalendar(method: 'gotoDate', date: Date | string): void; /** * Moves the calendar forward/backward an arbitrary amount of time. From 7708aa1148349e0e2cdf07be651a888d8ccc87de Mon Sep 17 00:00:00 2001 From: Vadim Macagon Date: Mon, 6 Jul 2015 14:34:33 +0700 Subject: [PATCH 033/144] Add typings for Atom's event-kit library --- event-kit/.editorconfig | 3 ++ event-kit/event-kit-tests.ts | 65 ++++++++++++++++++++++++++++ event-kit/event-kit.d.ts | 82 ++++++++++++++++++++++++++++++++++++ 3 files changed, 150 insertions(+) create mode 100644 event-kit/.editorconfig create mode 100644 event-kit/event-kit-tests.ts create mode 100644 event-kit/event-kit.d.ts diff --git a/event-kit/.editorconfig b/event-kit/.editorconfig new file mode 100644 index 0000000000..570211f898 --- /dev/null +++ b/event-kit/.editorconfig @@ -0,0 +1,3 @@ +[*.ts] +indent_style = tab +indent_size = 4 diff --git a/event-kit/event-kit-tests.ts b/event-kit/event-kit-tests.ts new file mode 100644 index 0000000000..2c759506a2 --- /dev/null +++ b/event-kit/event-kit-tests.ts @@ -0,0 +1,65 @@ +/// + +// The following line only works in TypeScript 1.5 +//import { Disposable, CompositeDisposable, Emitter } from "event-kit"; +// DefinitelyTyped is still using TypeScript 1.4 to run tests +// so until they upgrade we have to do the following instead +import eventKit = require('event-kit'); +type Disposable = AtomEventKit.Disposable; +var Disposable = eventKit.Disposable; +type CompositeDisposable = AtomEventKit.CompositeDisposable; +var CompositeDisposable = eventKit.CompositeDisposable; +type Emitter = AtomEventKit.Emitter; +var Emitter = eventKit.Emitter; + +// Emitter + +class User { + private emitter: Emitter; + name: string; + + constructor() { + this.emitter = new Emitter(); + } + + onDidChangeName(callback: (name: string) => void): Disposable { + return this.emitter.on('did-change-name', callback); + } + + setName(name: string): void { + if (this.name != name) { + this.name = name; + this.emitter.emit('did-change-name', name); + } + } + + destroy(): void { + this.emitter.dispose(); + } +} + +// Disposable + +var disposable = new Disposable(() => { + // cleanup +}); +disposable.dispose(); + +var user = new User(); +var subscription = user.onDidChangeName((name: string) => { + console.log('User name change to: ' + name); +}); +subscription.dispose(); + +// CompositeDisposable + +var subscriptions = new CompositeDisposable(); +subscriptions.add( + user.onDidChangeName((name: string) => { + console.log('subscriber #1'); + }), + user.onDidChangeName((name: string) => { + console.log('subscriber #2'); + }) +); +subscriptions.dispose(); diff --git a/event-kit/event-kit.d.ts b/event-kit/event-kit.d.ts new file mode 100644 index 0000000000..6363edf1cd --- /dev/null +++ b/event-kit/event-kit.d.ts @@ -0,0 +1,82 @@ +// Type definitions for event-kit v1.2.0 +// Project: https://github.com/atom/event-kit +// Definitions by: Vadim Macagon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module AtomEventKit { + interface IDisposable { + dispose(): void; + } + + /** Static side of the Disposable class. */ + interface DisposableStatic { + prototype: Disposable; + new (disposalAction: Function): Disposable; + } + + /** Instance side of the Disposable class. */ + interface Disposable extends IDisposable { + disposed: boolean; + + constructor: DisposableStatic; + } + + /** A class that represent a handle to a resource that can be disposed. */ + var Disposable: DisposableStatic; + + /** Static side of the CompositeDisposable class. */ + interface CompositeDisposableStatic { + prototype: CompositeDisposable; + new (...disposables: IDisposable[]): CompositeDisposable; + } + + /** Instance side of the CompositeDisposable class. */ + interface CompositeDisposable extends IDisposable { + disposed: boolean; + + constructor: CompositeDisposableStatic; + add(...disposables: IDisposable[]): void; + remove(disposable: IDisposable): void; + clear(): void; + } + + /** + * A class that aggregates multiple [[Disposable]] instances together into a single disposable, + * so that they can all be disposed as a group. + */ + var CompositeDisposable: CompositeDisposableStatic; + + /** Static side of the Emitter class. */ + interface EmitterStatic { + prototype: Emitter; + new (): Emitter; + } + + /** Instance side of the Emitter class. */ + interface Emitter { + isDisposed: boolean; + + constructor: EmitterStatic; + dispose(): void; + /** + * Registers a handler to be invoked whenever the given event is emitted. + * @return An object that will unregister the handler when disposed. + */ + on(eventName: string, handler: (value: any) => void, unshift?: boolean): Disposable; + /** + * Registers a handler to be invoked *before* all previously registered handlers for + * the given event. + * @return An object that will unregister the handler when disposed. + */ + preempt(eventName: string, handler: (value: any) => void): Disposable; + /** Invokes any registered handlers for the given event. */ + emit(eventName: string, value: any): void; + } + + /** A utility class for implementing event-based APIs. */ + var Emitter: EmitterStatic; +} + +declare module "event-kit" { + export = AtomEventKit; +} From 7eadcd7bb05d7619a89f492d80bf4d1c68a27823 Mon Sep 17 00:00:00 2001 From: Slavo Vojacek Date: Mon, 6 Jul 2015 09:50:54 +0100 Subject: [PATCH 034/144] Update lodash.d.ts Not really sure why some functions are not here at all, but I needed this one (_.fill) in one of my projects so contributing back. --- lodash/lodash.d.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index b4eaf75091..a0223e9e01 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -2494,6 +2494,25 @@ declare module _ { collection: Dictionary, whereValue: W): boolean; } + + interface LoDashStatic { + /** + * Fills elements of array with value from start up to, but not including, end. + * + * Note: This method mutates array. + * + * @param array (Array): The array to fill. + * @param value (*): The value to fill array with. + * @param [start=0] (number): The start position. + * @param [end=array.length] (number): The end position. + * @return (Array): Returns array. + **/ + fill( + array: Array, + value: any, + start?: number, + end?: number): T; + } //_.filter interface LoDashStatic { From 72bd5e2a679da7593d1bd19884610317203f238a Mon Sep 17 00:00:00 2001 From: Slavo Vojacek Date: Mon, 6 Jul 2015 10:02:25 +0100 Subject: [PATCH 035/144] Update lodash.d.ts --- lodash/lodash.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index a0223e9e01..3723f497dd 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -2508,10 +2508,10 @@ declare module _ { * @return (Array): Returns array. **/ fill( - array: Array, + array: Array, value: any, start?: number, - end?: number): T; + end?: number): Array; } //_.filter From 550470d7e239ad4c3b792d7d4795908e3ab6517d Mon Sep 17 00:00:00 2001 From: Eric HILLAH Date: Mon, 6 Jul 2015 11:02:36 +0200 Subject: [PATCH 036/144] change blob-stream type argument to be optional --- blob-stream/blob-stream-tests.ts | 2 +- blob-stream/blob-stream.d.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/blob-stream/blob-stream-tests.ts b/blob-stream/blob-stream-tests.ts index 574dfc044d..fab0932068 100644 --- a/blob-stream/blob-stream-tests.ts +++ b/blob-stream/blob-stream-tests.ts @@ -3,5 +3,5 @@ var bl = require('blob-stream'); -var blob = bl.toBlob("aplication/PDF"); +var blob = bl.toBlob(); var brl = bl.toBlobURL("app/JSON"); diff --git a/blob-stream/blob-stream.d.ts b/blob-stream/blob-stream.d.ts index 5c62155b64..b55cd13c6f 100644 --- a/blob-stream/blob-stream.d.ts +++ b/blob-stream/blob-stream.d.ts @@ -10,8 +10,8 @@ declare function BlobStream(): BlobStream.IBlobStream; declare module BlobStream { interface IBlobStream extends NodeJS.WritableStream{ - toBlob(type: string): Blob; - toBlobURL(type: string): string; + toBlob(type?: string): Blob; + toBlobURL(type?: string): string; } } From cca3141ba59e2b3f2e4cbb2563a2002f348075b7 Mon Sep 17 00:00:00 2001 From: Tanguy Krotoff Date: Mon, 6 Jul 2015 13:49:47 +0200 Subject: [PATCH 037/144] Add definitions for gulp-rev (https://github.com/sindresorhus/gulp-rev) --- gulp-rev/gulp-rev-tests.ts | 36 ++++++++++++++++++++++++++++++++++++ gulp-rev/gulp-rev.d.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 gulp-rev/gulp-rev-tests.ts create mode 100644 gulp-rev/gulp-rev.d.ts diff --git a/gulp-rev/gulp-rev-tests.ts b/gulp-rev/gulp-rev-tests.ts new file mode 100644 index 0000000000..37661424f1 --- /dev/null +++ b/gulp-rev/gulp-rev-tests.ts @@ -0,0 +1,36 @@ +/// +/// + +import gulp = require('gulp'); +import rev = require('gulp-rev'); + +gulp.task('default', () => + gulp.src('src/*.css') + .pipe(rev()) + .pipe(gulp.dest('dist')) +); + +gulp.task('default', () => + // by default, gulp would pick `assets/css` as the base, + // so we need to set it explicitly: + gulp.src(['assets/css/*.css', 'assets/js/*.js'], {base: 'assets'}) + .pipe(gulp.dest('build/assets')) // copy original assets to build dir + .pipe(rev()) + .pipe(gulp.dest('build/assets')) // write rev'd assets to build dir + .pipe(rev.manifest()) + .pipe(gulp.dest('build/assets')) // write manifest to build dir +); + +gulp.task('default', () => + // by default, gulp would pick `assets/css` as the base, + // so we need to set it explicitly: + gulp.src(['assets/css/*.css', 'assets/js/*.js'], {base: 'assets'}) + .pipe(gulp.dest('build/assets')) + .pipe(rev()) + .pipe(gulp.dest('build/assets')) + .pipe(rev.manifest({ + base: 'build/assets', + merge: true // merge with the existing manifest (if one exists) + })) + .pipe(gulp.dest('build/assets')) +); diff --git a/gulp-rev/gulp-rev.d.ts b/gulp-rev/gulp-rev.d.ts new file mode 100644 index 0000000000..6cd432b0de --- /dev/null +++ b/gulp-rev/gulp-rev.d.ts @@ -0,0 +1,26 @@ +// Type definitions for gulp-csso v5.0.1 +// Project: https://github.com/sindresorhus/gulp-rev +// Definitions by: Tanguy Krotoff +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'gulp-rev' { + interface IOptions { + base?: string; + cwd?: string; + merge?: boolean; + } + + interface IRev { + (): NodeJS.ReadWriteStream; + + manifest(): NodeJS.ReadWriteStream; + manifest(path?: string): NodeJS.ReadWriteStream; + manifest(options?: IOptions): NodeJS.ReadWriteStream; + manifest(path?: string, options?: IOptions): NodeJS.ReadWriteStream; + } + + var rev: IRev; + export = rev; +} From 9709e638900e0bf7cba208dc9580b1881fee48b7 Mon Sep 17 00:00:00 2001 From: Tanguy Krotoff Date: Mon, 6 Jul 2015 14:03:20 +0200 Subject: [PATCH 038/144] Add definitions for gulp-useref (https://github.com/jonkemp/gulp-useref) --- gulp-useref/gulp-useref-tests.ts | 15 +++++++++++++++ gulp-useref/gulp-useref.d.ts | 25 +++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 gulp-useref/gulp-useref-tests.ts create mode 100644 gulp-useref/gulp-useref.d.ts diff --git a/gulp-useref/gulp-useref-tests.ts b/gulp-useref/gulp-useref-tests.ts new file mode 100644 index 0000000000..95c35662dc --- /dev/null +++ b/gulp-useref/gulp-useref-tests.ts @@ -0,0 +1,15 @@ +/// +/// + +import gulp = require('gulp'); +import useref = require('gulp-useref'); + +gulp.task('default', () => { + var assets = useref.assets(); + + return gulp.src('app/*.html') + .pipe(assets) + .pipe(assets.restore()) + .pipe(useref()) + .pipe(gulp.dest('dist')); +}); diff --git a/gulp-useref/gulp-useref.d.ts b/gulp-useref/gulp-useref.d.ts new file mode 100644 index 0000000000..b1628aa5fb --- /dev/null +++ b/gulp-useref/gulp-useref.d.ts @@ -0,0 +1,25 @@ +// Type definitions for gulp-useref v1.2.0 +// Project: https://github.com/jonkemp/gulp-useref +// Definitions by: Tanguy Krotoff +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'gulp-useref' { + interface IAssetsOptions { + searchPath?: string | string[]; + noconcat?: boolean; + } + + interface IAssetsStream extends NodeJS.ReadWriteStream { + restore(): NodeJS.ReadWriteStream; + } + + interface IUseref { + (options?: any): NodeJS.ReadWriteStream; + assets(options?: IAssetsOptions): IAssetsStream; + } + + var useref: IUseref; + export = useref; +} From c2a9eb74ce15ecf5d2808e5090eef6164e867943 Mon Sep 17 00:00:00 2001 From: Tanguy Krotoff Date: Mon, 6 Jul 2015 14:17:46 +0200 Subject: [PATCH 039/144] Add definitions for gulp-rev-replace (https://github.com/jamesknelson/gulp-rev-replace) --- gulp-rev-replace/gulp-rev-replace-tests.ts | 63 ++++++++++++++++++++++ gulp-rev-replace/gulp-rev-replace.d.ts | 21 ++++++++ 2 files changed, 84 insertions(+) create mode 100644 gulp-rev-replace/gulp-rev-replace-tests.ts create mode 100644 gulp-rev-replace/gulp-rev-replace.d.ts diff --git a/gulp-rev-replace/gulp-rev-replace-tests.ts b/gulp-rev-replace/gulp-rev-replace-tests.ts new file mode 100644 index 0000000000..57515c9aca --- /dev/null +++ b/gulp-rev-replace/gulp-rev-replace-tests.ts @@ -0,0 +1,63 @@ +/// +/// +/// +/// + +import gulp = require('gulp'); +import revReplace = require('gulp-rev-replace'); +import rev = require('gulp-rev'); +import useref = require('gulp-useref'); + +gulp.task("index", () => { + var userefAssets = useref.assets(); + + return gulp.src("src/index.html") + .pipe(userefAssets) // Concatenate with gulp-useref + .pipe(rev()) // Rename the concatenated files + .pipe(userefAssets.restore()) + .pipe(useref()) + .pipe(revReplace()) // Substitute in new filenames + .pipe(gulp.dest('public')); +}); + + +var opt = { + srcFolder: 'src', + distFolder: 'dist' +} + +gulp.task("revision", ["dist:css", "dist:js"], () => + gulp.src(["dist/**/*.css", "dist/**/*.js"]) + .pipe(rev()) + .pipe(gulp.dest(opt.distFolder)) + .pipe(rev.manifest()) + .pipe(gulp.dest(opt.distFolder)) +); + +gulp.task("revreplace", ["revision"], () => { + var manifest = gulp.src("./" + opt.distFolder + "/rev-manifest.json"); + + return gulp.src(opt.srcFolder + "/index.html") + .pipe(revReplace({manifest: manifest})) + .pipe(gulp.dest(opt.distFolder)); +}); + + +function replaceJsIfMap(filename: string): string { + if (filename.indexOf('.map') > -1) { + return filename.replace('js/', ''); + } + return filename; +} + +gulp.task("revreplace", ["revision"], () => { + var manifest = gulp.src("./" + opt.distFolder + "/rev-manifest.json"); + + return gulp.src(opt.distFolder + '**/*.js') + .pipe(revReplace({ + manifest: manifest, + modifyUnreved: replaceJsIfMap, + modifyReved: replaceJsIfMap + })) + .pipe(gulp.dest(opt.distFolder)); +}); diff --git a/gulp-rev-replace/gulp-rev-replace.d.ts b/gulp-rev-replace/gulp-rev-replace.d.ts new file mode 100644 index 0000000000..3e683d183d --- /dev/null +++ b/gulp-rev-replace/gulp-rev-replace.d.ts @@ -0,0 +1,21 @@ +// Type definitions for gulp-rev-replace v0.2.1 +// Project: https://github.com/jamesknelson/gulp-rev-replace +// Definitions by: Tanguy Krotoff +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'gulp-rev-replace' { + interface IOptions { + canonicalUris?: boolean; + replaceInExtensions?: Array; + prefix?: string; + manifest?: NodeJS.ReadWriteStream; + modifyUnreved?: Function; + modifyReved?: Function; + } + + function revReplace(options?: IOptions): NodeJS.ReadWriteStream; + + export = revReplace; +} From efd764c6430fb5ad0294d38a694c0ceac66dd291 Mon Sep 17 00:00:00 2001 From: Chris Wrench Date: Mon, 6 Jul 2015 13:22:22 +0100 Subject: [PATCH 040/144] Fix typo in license --- googlemaps/google.maps.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index f4823cc088..b6091ef55b 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -14,7 +14,7 @@ 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: -h + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. From a0cf73c965e5deb8c8a66da1547f998801f64101 Mon Sep 17 00:00:00 2001 From: Tanguy Krotoff Date: Mon, 6 Jul 2015 14:26:28 +0200 Subject: [PATCH 041/144] Add definitions for gulp-debug (https://github.com/sindresorhus/gulp-debug) --- gulp-debug/gulp-debug-tests.ts | 14 ++++++++++++++ gulp-debug/gulp-debug.d.ts | 17 +++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 gulp-debug/gulp-debug-tests.ts create mode 100644 gulp-debug/gulp-debug.d.ts diff --git a/gulp-debug/gulp-debug-tests.ts b/gulp-debug/gulp-debug-tests.ts new file mode 100644 index 0000000000..e6485d8da9 --- /dev/null +++ b/gulp-debug/gulp-debug-tests.ts @@ -0,0 +1,14 @@ +/// +/// + +import gulp = require('gulp'); +import debug = require('gulp-debug'); + +gulp.task('default', () => + gulp.src('foo.js') + .pipe(debug({title: 'unicorn:'})) + .pipe(gulp.dest('dist')) +); + + +debug(); diff --git a/gulp-debug/gulp-debug.d.ts b/gulp-debug/gulp-debug.d.ts new file mode 100644 index 0000000000..743f5f5eb1 --- /dev/null +++ b/gulp-debug/gulp-debug.d.ts @@ -0,0 +1,17 @@ +// Type definitions for gulp-debug v2.0.1 +// Project: https://github.com/sindresorhus/gulp-debug +// Definitions by: Tanguy Krotoff +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'gulp-debug' { + interface IOptions { + title?: string; + minimal?: boolean; + } + + function debug(options?: IOptions): NodeJS.ReadWriteStream; + + export = debug; +} From 5e981dddcc7d27a644b0901d2f5f7fe0deb412ca Mon Sep 17 00:00:00 2001 From: Tanguy Krotoff Date: Mon, 6 Jul 2015 14:30:45 +0200 Subject: [PATCH 042/144] Add definitions for gulp-size (https://github.com/sindresorhus/gulp-size) --- gulp-size/gulp-size-tests.ts | 27 +++++++++++++++++++++++++++ gulp-size/gulp-size.d.ts | 23 +++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 gulp-size/gulp-size-tests.ts create mode 100644 gulp-size/gulp-size.d.ts diff --git a/gulp-size/gulp-size-tests.ts b/gulp-size/gulp-size-tests.ts new file mode 100644 index 0000000000..bfa2c6a04b --- /dev/null +++ b/gulp-size/gulp-size-tests.ts @@ -0,0 +1,27 @@ +/// +/// +/// + +import gulp = require('gulp'); +import size = require('gulp-size'); +import debug = require('gulp-debug'); + +gulp.task('default', () => + gulp.src('fixture.js') + .pipe(size()) + .pipe(gulp.dest('dist')) +); + + +gulp.task('default', () => { + var s = size(); + + return gulp.src('fixture.js') + .pipe(s) + .pipe(gulp.dest('dist')) + .pipe(debug({title: 'Total size ' + s.prettySize})); +}); + + +size(); +size({showFiles: true, gzip: true}); diff --git a/gulp-size/gulp-size.d.ts b/gulp-size/gulp-size.d.ts new file mode 100644 index 0000000000..d25f6ed94b --- /dev/null +++ b/gulp-size/gulp-size.d.ts @@ -0,0 +1,23 @@ +// Type definitions for gulp-size v1.2.3 +// Project: https://github.com/sindresorhus/gulp-size +// Definitions by: Tanguy Krotoff +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'gulp-size' { + interface IOptions { + showFiles?: boolean; + gzip?: boolean; + title?: string; + } + + interface ISizeStream extends NodeJS.ReadWriteStream { + size: number; + prettySize: string; + } + + function size(options?: IOptions): ISizeStream; + + export = size; +} From 2a0e473e347959cf7dd58c48ec3193a64d63bb08 Mon Sep 17 00:00:00 2001 From: Tanguy Krotoff Date: Mon, 6 Jul 2015 14:39:25 +0200 Subject: [PATCH 043/144] Add definitions for gulp-watch (https://github.com/floatdrop/gulp-watch) --- gulp-watch/gulp-watch-tests.ts | 19 +++++++++++++++++++ gulp-watch/gulp-watch.d.ts | 27 +++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 gulp-watch/gulp-watch-tests.ts create mode 100644 gulp-watch/gulp-watch.d.ts diff --git a/gulp-watch/gulp-watch-tests.ts b/gulp-watch/gulp-watch-tests.ts new file mode 100644 index 0000000000..5e158a0456 --- /dev/null +++ b/gulp-watch/gulp-watch-tests.ts @@ -0,0 +1,19 @@ +/// +/// + +import gulp = require('gulp'); +import watch = require('gulp-watch'); + +gulp.task('stream', () => + gulp.src('css/**/*.css') + .pipe(watch('css/**/*.css')) + .pipe(gulp.dest('build')) +); + +gulp.task('callback', (cb) => + watch('css/**/*.css', () => + gulp.src('css/**/*.css') + .pipe(watch('css/**/*.css')) + .on('end', cb) + ) +); diff --git a/gulp-watch/gulp-watch.d.ts b/gulp-watch/gulp-watch.d.ts new file mode 100644 index 0000000000..b3a16bbdd2 --- /dev/null +++ b/gulp-watch/gulp-watch.d.ts @@ -0,0 +1,27 @@ +// Type definitions for gulp-watch v4.1.1 +// Project: https://github.com/floatdrop/gulp-watch +// Definitions by: Tanguy Krotoff +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'gulp-watch' { + interface IOptions { + ignoreInitial?: boolean; + events?: Array; + base?: string; + name?: string; + verbose?: boolean; + readDelay?: number; + } + + interface IWatchStream extends NodeJS.ReadWriteStream { + add(path: string | Array): NodeJS.ReadWriteStream; + unwatch(path: string | Array): NodeJS.ReadWriteStream; + close(): NodeJS.ReadWriteStream; + } + + function watch(glob: string, options?: IOptions, callback?: Function): IWatchStream; + + export = watch; +} From 84ef6b154838451339e4d13787a564d245e2a12a Mon Sep 17 00:00:00 2001 From: Vlad Kuimov Date: Mon, 6 Jul 2015 15:41:48 +0300 Subject: [PATCH 044/144] Update jqueryui.d.ts --- jqueryui/jqueryui.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index 26e2d6cdcb..10a4e7159c 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -507,7 +507,7 @@ declare module JQueryUI { interface ProgressbarOptions { disabled?: boolean; - value?: number; + value?: number | boolean; } interface ProgressbarUIParams { From b73d1fd0bf09d9ec89fb3f704285f6a5b05062e6 Mon Sep 17 00:00:00 2001 From: Tanguy Krotoff Date: Mon, 6 Jul 2015 14:59:18 +0200 Subject: [PATCH 045/144] Add definitions for merge2 (https://github.com/teambition/merge2) --- merge2/merge2-tests.ts | 64 ++++++++++++++++++++++++++++++++++++++++++ merge2/merge2.d.ts | 21 ++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 merge2/merge2-tests.ts create mode 100644 merge2/merge2.d.ts diff --git a/merge2/merge2-tests.ts b/merge2/merge2-tests.ts new file mode 100644 index 0000000000..bba0dd0a34 --- /dev/null +++ b/merge2/merge2-tests.ts @@ -0,0 +1,64 @@ +/// +/// + +import gulp = require('gulp'); +import merge2 = require('merge2'); + +gulp.task('app-js', () => + merge2( + gulp.src('static/src/tpl/*.html'), + gulp.src([ + 'static/src/js/app.js', + 'static/src/js/locale_zh-cn.js', + 'static/src/js/router.js', + 'static/src/js/tools.js', + 'static/src/js/services.js', + 'static/src/js/filters.js', + 'static/src/js/directives.js', + 'static/src/js/controllers.js' + ]) + ) + .pipe(gulp.dest('static/dist/js/')) +); + + +var stream1 = gulp.src('*.html'); +var stream2 = gulp.src('*.html'); +var stream3 = gulp.src('*.html'); +var stream4 = gulp.src('*.html'); +var stream5 = gulp.src('*.html'); +var stream6 = gulp.src('*.html'); +var stream7 = gulp.src('*.html'); + + +var stream = merge2([stream1, stream2], stream3, {end: false}) +//... +stream.add(stream4, stream5); +//.. +stream.end(); + + +// equal to merge2([stream1, stream2], stream3) +var stream = merge2(); +stream.add([stream1, stream2]); +stream.add(stream3); + + +// merge order: +// 1. merge `stream1`; +// 2. merge `stream2` and `stream3` in parallel after `stream1` merged; +// 3. merge 'stream4' after `stream2` and `stream3` merged; +var stream = merge2(stream1, [stream2, stream3], stream4); + +// merge order: +// 1. merge `stream5` and `stream6` in parallel after `stream4` merged; +// 2. merge 'stream7' after `stream5` and `stream6` merged; +stream.add([stream5, stream6], stream7); + + +// nest merge +// equal to merge2(stream1, stream2, stream6, stream3, [stream4, stream5]); +var streamA = merge2(stream1, stream2); +var streamB = merge2(stream3, [stream4, stream5]); +var stream = merge2(streamA, streamB); +streamA.add(stream6); diff --git a/merge2/merge2.d.ts b/merge2/merge2.d.ts new file mode 100644 index 0000000000..ebf1df758f --- /dev/null +++ b/merge2/merge2.d.ts @@ -0,0 +1,21 @@ +// Type definitions for merge2 v0.3.6 +// Project: https://github.com/teambition/merge2 +// Definitions by: Tanguy Krotoff +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'merge2' { + interface IOptions { + end?: boolean; + objectMode?: boolean; + } + + interface IMerge2Stream extends NodeJS.ReadWriteStream { + add(...args: Array>): IMerge2Stream; + } + + function merge2(...args: Array | IOptions>): IMerge2Stream; + + export = merge2; +} From dbcd2f192cb6e0bc4418db5fc8dc82ec436f00f8 Mon Sep 17 00:00:00 2001 From: Tanguy Krotoff Date: Mon, 6 Jul 2015 15:10:22 +0200 Subject: [PATCH 046/144] Add definitions for Karma public API (https://github.com/karma-runner/karma) --- karma/karma-tests.ts | 26 ++++++++++++++++++++++++++ karma/karma.d.ts | 24 ++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 karma/karma-tests.ts create mode 100644 karma/karma.d.ts diff --git a/karma/karma-tests.ts b/karma/karma-tests.ts new file mode 100644 index 0000000000..b70e7273be --- /dev/null +++ b/karma/karma-tests.ts @@ -0,0 +1,26 @@ +/// +/// + +import gulp = require('gulp'); +import karma = require('karma'); + +function runKarma(singleRun: boolean): void { + karma.server.start({ + configFile: __dirname + '/karma.conf.js', + singleRun: singleRun + }); +} + +gulp.task('test:unit:karma', ['build:test:unit'], () => runKarma(true)); + + +karma.server.start({port: 9876}, (exitCode) => { + console.log('Karma has exited with ' + exitCode); + process.exit(exitCode); +}); + + +karma.runner.run({port: 9876}, (exitCode) => { + console.log('Karma has exited with ' + exitCode); + process.exit(exitCode); +}); diff --git a/karma/karma.d.ts b/karma/karma.d.ts new file mode 100644 index 0000000000..c66e6fe06a --- /dev/null +++ b/karma/karma.d.ts @@ -0,0 +1,24 @@ +// Type definitions for karma v0.12.37 +// Project: https://github.com/karma-runner/karma +// Definitions by: Tanguy Krotoff +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module 'karma' { + // See Karma public API https://karma-runner.github.io/0.12/dev/public-api.html + + interface IKarmaServer { + start(options?: any, callback?: (exitCode: number) => void): void; + } + + interface IKarmaRunner { + run(options?: any, callback?: (exitCode: number) => void): void; + } + + interface IKarma { + server: IKarmaServer; + runner: IKarmaRunner; + } + + var karma: IKarma; + export = karma; +} From 82d33fabbcfb74efa176a948892aa66ffab8abd1 Mon Sep 17 00:00:00 2001 From: Tanguy Krotoff Date: Mon, 6 Jul 2015 15:20:55 +0200 Subject: [PATCH 047/144] Add definitions for gulp-jasmine-browser (https://github.com/jasmine/gulp-jasmine-browser) --- .../gulp-jasmine-browser-tests.ts | 32 +++++++++++++++++++ .../gulp-jasmine-browser.d.ts | 17 ++++++++++ 2 files changed, 49 insertions(+) create mode 100644 gulp-jasmine-browser/gulp-jasmine-browser-tests.ts create mode 100644 gulp-jasmine-browser/gulp-jasmine-browser.d.ts diff --git a/gulp-jasmine-browser/gulp-jasmine-browser-tests.ts b/gulp-jasmine-browser/gulp-jasmine-browser-tests.ts new file mode 100644 index 0000000000..c28b312f42 --- /dev/null +++ b/gulp-jasmine-browser/gulp-jasmine-browser-tests.ts @@ -0,0 +1,32 @@ +/// +/// + +import gulp = require('gulp'); +import jasmineBrowser = require('gulp-jasmine-browser'); + +gulp.task('jasmine', () => + gulp.src(['src/**/*.js', 'spec/**/*_spec.js']) + .pipe(jasmineBrowser.specRunner()) + .pipe(jasmineBrowser.server({port: 8888})) +); + + +gulp.task('jasmine-phantom', () => + gulp.src(['src/**/*.js', 'spec/**/*_spec.js']) + .pipe(jasmineBrowser.specRunner({console: true})) + .pipe(jasmineBrowser.headless()) +); + + +gulp.task('jasmine-slimerjs', () => + gulp.src(['src/**/*.js', 'spec/**/*_spec.js']) + .pipe(jasmineBrowser.specRunner({console: true})) + .pipe(jasmineBrowser.headless({driver: 'slimerjs'})) +); + + +gulp.task('jasmine', () => + gulp.src('spec/**/*_spec.js') + .pipe(jasmineBrowser.specRunner()) + .pipe(jasmineBrowser.server()) +); diff --git a/gulp-jasmine-browser/gulp-jasmine-browser.d.ts b/gulp-jasmine-browser/gulp-jasmine-browser.d.ts new file mode 100644 index 0000000000..e2e7179699 --- /dev/null +++ b/gulp-jasmine-browser/gulp-jasmine-browser.d.ts @@ -0,0 +1,17 @@ +// Type definitions for gulp-jasmine-browser v0.1.4 +// Project: https://github.com/jasmine/gulp-jasmine-browser +// Definitions by: Tanguy Krotoff +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'gulp-jasmine-browser' { + interface IJasmineBrowser { + specRunner(options?: any): NodeJS.ReadWriteStream; + server(options?: any): NodeJS.ReadWriteStream; + headless(options?: any): NodeJS.ReadWriteStream; + } + + var jasmineBrowser: IJasmineBrowser; + export = jasmineBrowser; +} From 224116760a83fa74c26d684fbf6014833b360f7f Mon Sep 17 00:00:00 2001 From: Tanguy Krotoff Date: Mon, 6 Jul 2015 15:34:37 +0200 Subject: [PATCH 048/144] Add definitions for gulp-protractor (https://github.com/mllrsohn/gulp-protractor) --- gulp-protractor/gulp-protractor-tests.ts | 20 +++++++++++++++++++ gulp-protractor/gulp-protractor.d.ts | 25 ++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 gulp-protractor/gulp-protractor-tests.ts create mode 100644 gulp-protractor/gulp-protractor.d.ts diff --git a/gulp-protractor/gulp-protractor-tests.ts b/gulp-protractor/gulp-protractor-tests.ts new file mode 100644 index 0000000000..4224084d8b --- /dev/null +++ b/gulp-protractor/gulp-protractor-tests.ts @@ -0,0 +1,20 @@ +/// +/// + +import gulp = require('gulp'); +import protractor = require('gulp-protractor'); + +gulp.src(["./src/tests/*.js"]) + .pipe(protractor.protractor({ + configFile: "test/protractor.config.js", + args: ['--baseUrl', 'http://127.0.0.1:8000'] + })) + + +gulp.task('webdriver_standalone', protractor.webdriver_standalone); + + +gulp.task('webdriver-update', protractor.webdriver_update); + + +console.log(protractor.getProtractorDir()); diff --git a/gulp-protractor/gulp-protractor.d.ts b/gulp-protractor/gulp-protractor.d.ts new file mode 100644 index 0000000000..d0317e2e2d --- /dev/null +++ b/gulp-protractor/gulp-protractor.d.ts @@ -0,0 +1,25 @@ +// Type definitions for gulp-protractor v1.0.0 +// Project: https://github.com/mllrsohn/gulp-protractor +// Definitions by: Tanguy Krotoff +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module 'gulp-protractor' { + interface IOptions { + configFile?: string; + args?: Array; + debug?: boolean; + } + + interface IGulpProtractor { + getProtractorDir(): string; + protractor(options?: IOptions): NodeJS.ReadWriteStream; + webdriver_standalone: gulp.ITaskCallback; + webdriver_update: gulp.ITaskCallback; + } + + var protractor: IGulpProtractor; + export = protractor; +} From de2541fc1b9c622010f2165c7782c41c0536b7f1 Mon Sep 17 00:00:00 2001 From: Tanguy Krotoff Date: Mon, 6 Jul 2015 15:43:15 +0200 Subject: [PATCH 049/144] glob can be an array of strings --- gulp-watch/gulp-watch-tests.ts | 11 +++++++++++ gulp-watch/gulp-watch.d.ts | 2 +- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/gulp-watch/gulp-watch-tests.ts b/gulp-watch/gulp-watch-tests.ts index 5e158a0456..9d9303ac22 100644 --- a/gulp-watch/gulp-watch-tests.ts +++ b/gulp-watch/gulp-watch-tests.ts @@ -17,3 +17,14 @@ gulp.task('callback', (cb) => .on('end', cb) ) ); + +gulp.task('build', () => { + var files = [ + 'app/**/*.ts', + 'lib/**/*.ts', + 'components/**/*.ts', + ]; + + gulp.src(files, { base: '..' }) + .pipe(watch(files, { base: '..' })); +}); diff --git a/gulp-watch/gulp-watch.d.ts b/gulp-watch/gulp-watch.d.ts index b3a16bbdd2..35fb7de955 100644 --- a/gulp-watch/gulp-watch.d.ts +++ b/gulp-watch/gulp-watch.d.ts @@ -21,7 +21,7 @@ declare module 'gulp-watch' { close(): NodeJS.ReadWriteStream; } - function watch(glob: string, options?: IOptions, callback?: Function): IWatchStream; + function watch(glob: string | Array, options?: IOptions, callback?: Function): IWatchStream; export = watch; } From 480a6334716d1ae14d77935d5a1d2aef555f24c1 Mon Sep 17 00:00:00 2001 From: Andrew Done Date: Mon, 6 Jul 2015 15:55:19 +0100 Subject: [PATCH 050/144] Use correct templateProvider and url definitions in angular.ui.IState. - See https://github.com/angular-ui/ui-router/wiki/URL-Routing#urlmatcherfactory-and-urlmatchers for a use of url that is non-string. - templateProvider needs to accept an Array to allow it to participate in by-name DI within Angular. --- angular-ui-router/angular-ui-router.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/angular-ui-router/angular-ui-router.d.ts b/angular-ui-router/angular-ui-router.d.ts index acc9342d92..18a6fb3970 100644 --- a/angular-ui-router/angular-ui-router.d.ts +++ b/angular-ui-router/angular-ui-router.d.ts @@ -20,7 +20,7 @@ declare module angular.ui { /** * Function, returns HTML content string */ - templateProvider?: Function; + templateProvider?: Function | Array; /** * A controller paired to the state. Function OR name as String */ @@ -41,7 +41,7 @@ declare module angular.ui { /** * A url with optional parameters. When a state is navigated or transitioned to, the $stateParams service will be populated with any parameters that were passed. */ - url?: string; + url?: string | IUrlMatcher; /** * A map which optionally configures parameters declared in the url, or defines additional non-url parameters. Only use this within a state if you are not using url. Otherwise you can specify your parameters within the url. When a state is navigated or transitioned to, the $stateParams service will be populated with any parameters that were passed. */ From 62f6c2822c9fed4534284ede302d8650df323ac4 Mon Sep 17 00:00:00 2001 From: Matt Brooks Date: Mon, 6 Jul 2015 17:43:17 +0100 Subject: [PATCH 051/144] Add Microsoft JQuery Unobtrusive Validation --- .../jquery.validation.unobtrusive-tests.ts | 13 ++++++++ .../jquery.validation.unobtrusive.d.ts | 33 +++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 jquery.validation.unobtrusive/jquery.validation.unobtrusive-tests.ts create mode 100644 jquery.validation.unobtrusive/jquery.validation.unobtrusive.d.ts diff --git a/jquery.validation.unobtrusive/jquery.validation.unobtrusive-tests.ts b/jquery.validation.unobtrusive/jquery.validation.unobtrusive-tests.ts new file mode 100644 index 0000000000..169fc1c5b7 --- /dev/null +++ b/jquery.validation.unobtrusive/jquery.validation.unobtrusive-tests.ts @@ -0,0 +1,13 @@ +/// + +$.validator.unobtrusive.adapters.add("adapter", () => { }); +$.validator.unobtrusive.adapters.add("adapter", function () { +}); + +$.validator.unobtrusive.adapters.addBool("adapter"); + +$.validator.unobtrusive.adapters.addMethod("adapter",(value, element) => { + return true; +}) + +$.validator.unobtrusive.parse(document); diff --git a/jquery.validation.unobtrusive/jquery.validation.unobtrusive.d.ts b/jquery.validation.unobtrusive/jquery.validation.unobtrusive.d.ts new file mode 100644 index 0000000000..866d6607dd --- /dev/null +++ b/jquery.validation.unobtrusive/jquery.validation.unobtrusive.d.ts @@ -0,0 +1,33 @@ +// Type definitions for Microsoft jQuery Unobtrusive Validation v3.2.3 +// Project: http://aspnetwebstack.codeplex.com/ +// Definitions by: Matt Brooks +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module MicrosoftJQueryUnobtrusiveValidation { + type JQuerySelector = string | Document | Element | JQuery; + + interface Adapters { + [key: string]: Function; + add(adapterName: string, fn: Function): Adapters; + add(adapterName: string, params: any, fn: Function): Adapters; + addMinMax(adapterName: string, minRuleName: string, maxRuleName: string, minMaxRuleName: string, minAttribute?: string, maxAttribute?: string): Adapters; + addSingleVal(adapterName: string, ruleName: string): Adapters; + addSingleVal(adapterName: string, attribute: string, ruleName: string): Adapters; + addBool(adapterName: string, ruleName?: string): Adapters; + addMethod(adapterName: string, fn: (value: string, element: Element, params: any) => any): Adapters; + } + + interface Validator { + adapters: Adapters; + parseElement(element: JQuerySelector, skipAttach?: boolean): void; + parse(selector: JQuerySelector): void; + } +} + +declare module JQueryValidation { + interface ValidatorStatic { + unobtrusive: MicrosoftJQueryUnobtrusiveValidation.Validator; + } +} From bfcf082b40c4ad008fe36c2d881dc5243ea573a3 Mon Sep 17 00:00:00 2001 From: Ryan Cavanaugh Date: Mon, 6 Jul 2015 15:58:01 -0700 Subject: [PATCH 052/144] Go back to old style of React typings and merge in JSX to both --- react/react-addons-global.d.ts | 2 +- react/react-global.d.ts | 930 +++++++++++++++++++++++++++++++++ react/react-jsx.d.ts | 147 ------ react/react.d.ts | 157 +++++- 4 files changed, 1083 insertions(+), 153 deletions(-) create mode 100644 react/react-global.d.ts delete mode 100644 react/react-jsx.d.ts diff --git a/react/react-addons-global.d.ts b/react/react-addons-global.d.ts index ed6096fa6f..508ae05225 100644 --- a/react/react-addons-global.d.ts +++ b/react/react-addons-global.d.ts @@ -2,7 +2,7 @@ // Project: http://facebook.github.io/react/ // Definitions by: Asana , AssureSign // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// declare module React { // diff --git a/react/react-global.d.ts b/react/react-global.d.ts new file mode 100644 index 0000000000..3c1a69e439 --- /dev/null +++ b/react/react-global.d.ts @@ -0,0 +1,930 @@ +// Type definitions for React v0.13.1 (internal module) +// Project: http://facebook.github.io/react/ +// Definitions by: Asana , AssureSign , Microsoft +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module React { + // + // React Elements + // ---------------------------------------------------------------------- + + type ReactType = ComponentClass | string; + + interface ReactElement

{ + type: string | ComponentClass

; + props: P; + key: string | number; + ref: string | ((component: Component) => any); + } + + interface ClassicElement

extends ReactElement

{ + type: string | ClassicComponentClass

; + ref: string | ((component: ClassicComponent) => any); + } + + interface DOMElement

extends ClassicElement

{ + type: string; + ref: string | ((component: DOMComponent

) => any); + } + + type HTMLElement = DOMElement; + type SVGElement = DOMElement; + + // + // Factories + // ---------------------------------------------------------------------- + + interface Factory

{ + (props?: P, ...children: ReactNode[]): ReactElement

; + } + + interface ClassicFactory

extends Factory

{ + (props?: P, ...children: ReactNode[]): ClassicElement

; + } + + interface DOMFactory

extends ClassicFactory

{ + (props?: P, ...children: ReactNode[]): DOMElement

; + } + + type HTMLFactory = DOMFactory; + type SVGFactory = DOMFactory; + type SVGElementFactory = DOMFactory; + + // + // React Nodes + // http://facebook.github.io/react/docs/glossary.html + // ---------------------------------------------------------------------- + + type ReactText = string | number; + type ReactChild = ReactElement | ReactText; + + // Should be Array but type aliases cannot be recursive + type ReactFragment = {} | Array; + type ReactNode = ReactChild | ReactFragment | boolean; + + // + // Top Level API + // ---------------------------------------------------------------------- + + function createClass(spec: ComponentSpec): ClassicComponentClass

; + + function createFactory

(type: string): DOMFactory

; + function createFactory

(type: ClassicComponentClass

| string): ClassicFactory

; + function createFactory

(type: ComponentClass

): Factory

; + + function createElement

( + type: string, + props?: P, + ...children: ReactNode[]): DOMElement

; + function createElement

( + type: ClassicComponentClass

| string, + props?: P, + ...children: ReactNode[]): ClassicElement

; + function createElement

( + type: ComponentClass

, + props?: P, + ...children: ReactNode[]): ReactElement

; + + function cloneElement

( + element: DOMElement

, + props?: P, + ...children: ReactNode[]): DOMElement

; + function cloneElement

( + element: ClassicElement

, + props?: P, + ...children: ReactNode[]): ClassicElement

; + function cloneElement

( + element: ReactElement

, + props?: P, + ...children: ReactNode[]): ReactElement

; + + function render

( + element: DOMElement

, + container: Element, + callback?: () => any): DOMComponent

; + function render( + element: ClassicElement

, + container: Element, + callback?: () => any): ClassicComponent; + function render( + element: ReactElement

, + container: Element, + callback?: () => any): Component; + + function unmountComponentAtNode(container: Element): boolean; + function renderToString(element: ReactElement): string; + function renderToStaticMarkup(element: ReactElement): string; + function isValidElement(object: {}): boolean; + function initializeTouchEvents(shouldUseTouch: boolean): void; + + function findDOMNode( + componentOrElement: Component | Element): TElement; + function findDOMNode( + componentOrElement: Component | Element): Element; + + var DOM: ReactDOM; + var PropTypes: ReactPropTypes; + var Children: ReactChildren; + + // + // Component API + // ---------------------------------------------------------------------- + + // Base component for plain JS classes + class Component implements ComponentLifecycle { + constructor(props?: P, context?: any); + setState(f: (prevState: S, props: P) => S, callback?: () => any): void; + setState(state: S, callback?: () => any): void; + forceUpdate(): void; + props: P; + state: S; + context: any; + refs: { + [key: string]: Component + }; + } + + interface ClassicComponent extends Component { + replaceState(nextState: S, callback?: () => any): void; + getDOMNode(): TElement; + getDOMNode(): Element; + isMounted(): boolean; + getInitialState?(): S; + setProps(nextProps: P, callback?: () => any): void; + replaceProps(nextProps: P, callback?: () => any): void; + } + + interface DOMComponent

extends ClassicComponent { + tagName: string; + } + + type HTMLComponent = DOMComponent; + type SVGComponent = DOMComponent; + + interface ChildContextProvider { + getChildContext(): CC; + } + + // + // Class Interfaces + // ---------------------------------------------------------------------- + + interface ComponentClass

{ + new(props?: P, context?: any): Component; + propTypes?: ValidationMap

; + contextTypes?: ValidationMap; + childContextTypes?: ValidationMap; + defaultProps?: P; + } + + interface ClassicComponentClass

extends ComponentClass

{ + new(props?: P, context?: any): ClassicComponent; + getDefaultProps?(): P; + displayName?: string; + } + + // + // Component Specs and Lifecycle + // ---------------------------------------------------------------------- + + 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; + componentWillUnmount?(): void; + } + + interface Mixin extends ComponentLifecycle { + mixins?: Mixin; + statics?: { + [key: string]: any; + }; + + displayName?: string; + propTypes?: ValidationMap; + contextTypes?: ValidationMap; + childContextTypes?: ValidationMap + + getDefaultProps?(): P; + getInitialState?(): S; + } + + interface ComponentSpec extends Mixin { + render(): ReactElement; + } + + // + // Event System + // ---------------------------------------------------------------------- + + interface SyntheticEvent { + bubbles: boolean; + cancelable: boolean; + currentTarget: EventTarget; + defaultPrevented: boolean; + eventPhase: number; + isTrusted: boolean; + nativeEvent: Event; + preventDefault(): void; + stopPropagation(): void; + target: EventTarget; + timeStamp: Date; + type: string; + } + + interface DragEvent extends SyntheticEvent { + dataTransfer: DataTransfer; + } + + interface ClipboardEvent extends SyntheticEvent { + clipboardData: DataTransfer; + } + + interface KeyboardEvent extends SyntheticEvent { + altKey: boolean; + charCode: number; + ctrlKey: boolean; + getModifierState(key: string): boolean; + key: string; + keyCode: number; + locale: string; + location: number; + metaKey: boolean; + repeat: boolean; + shiftKey: boolean; + which: number; + } + + interface FocusEvent extends SyntheticEvent { + relatedTarget: EventTarget; + } + + interface FormEvent extends SyntheticEvent { + } + + interface MouseEvent extends SyntheticEvent { + altKey: boolean; + button: number; + buttons: number; + clientX: number; + clientY: number; + ctrlKey: boolean; + getModifierState(key: string): boolean; + metaKey: boolean; + pageX: number; + pageY: number; + relatedTarget: EventTarget; + screenX: number; + screenY: number; + shiftKey: boolean; + } + + interface TouchEvent extends SyntheticEvent { + altKey: boolean; + changedTouches: TouchList; + ctrlKey: boolean; + getModifierState(key: string): boolean; + metaKey: boolean; + shiftKey: boolean; + targetTouches: TouchList; + touches: TouchList; + } + + interface UIEvent extends SyntheticEvent { + detail: number; + view: AbstractView; + } + + interface WheelEvent extends SyntheticEvent { + deltaMode: number; + deltaX: number; + deltaY: number; + deltaZ: number; + } + + // + // Event Handler Types + // ---------------------------------------------------------------------- + + interface EventHandler { + (event: E): void; + } + + interface DragEventHandler extends EventHandler {} + interface ClipboardEventHandler extends EventHandler {} + interface KeyboardEventHandler extends EventHandler {} + interface FocusEventHandler extends EventHandler {} + interface FormEventHandler extends EventHandler {} + interface MouseEventHandler extends EventHandler {} + interface TouchEventHandler extends EventHandler {} + interface UIEventHandler extends EventHandler {} + interface WheelEventHandler extends EventHandler {} + + // + // Props / DOM Attributes + // ---------------------------------------------------------------------- + + interface Props { + children?: ReactNode; + key?: string | number; + ref?: string | ((component: T) => any); + } + + interface DOMAttributes extends Props> { + onCopy?: ClipboardEventHandler; + onCut?: ClipboardEventHandler; + onPaste?: ClipboardEventHandler; + onKeyDown?: KeyboardEventHandler; + onKeyPress?: KeyboardEventHandler; + onKeyUp?: KeyboardEventHandler; + onFocus?: FocusEventHandler; + onBlur?: FocusEventHandler; + onChange?: FormEventHandler; + onInput?: FormEventHandler; + onSubmit?: FormEventHandler; + onClick?: MouseEventHandler; + onDoubleClick?: MouseEventHandler; + onDrag?: DragEventHandler; + onDragEnd?: DragEventHandler; + onDragEnter?: DragEventHandler; + onDragExit?: DragEventHandler; + onDragLeave?: DragEventHandler; + onDragOver?: DragEventHandler; + onDragStart?: DragEventHandler; + onDrop?: DragEventHandler; + onMouseDown?: MouseEventHandler; + onMouseEnter?: MouseEventHandler; + onMouseLeave?: MouseEventHandler; + onMouseMove?: MouseEventHandler; + onMouseOut?: MouseEventHandler; + onMouseOver?: MouseEventHandler; + onMouseUp?: MouseEventHandler; + onTouchCancel?: TouchEventHandler; + onTouchEnd?: TouchEventHandler; + onTouchMove?: TouchEventHandler; + onTouchStart?: TouchEventHandler; + onScroll?: UIEventHandler; + onWheel?: WheelEventHandler; + + dangerouslySetInnerHTML?: { + __html: string; + }; + } + + // This interface is not complete. Only properties accepting + // unitless numbers are listed here (see CSSProperty.js in React) + interface CSSProperties { + boxFlex?: number; + boxFlexGroup?: number; + columnCount?: number; + flex?: number | string; + flexGrow?: number; + flexShrink?: number; + fontWeight?: number | string; + lineClamp?: number; + lineHeight?: number | string; + opacity?: number; + order?: number; + orphans?: number; + widows?: number; + zIndex?: number; + zoom?: number; + + // SVG-related properties + fillOpacity?: number; + strokeOpacity?: number; + strokeWidth?: number; + } + + interface HTMLAttributes extends DOMAttributes { + ref?: string | ((component: HTMLComponent) => void); + + accept?: string; + acceptCharset?: string; + accessKey?: string; + action?: string; + allowFullScreen?: boolean; + allowTransparency?: boolean; + alt?: string; + async?: boolean; + autoComplete?: boolean; + autoFocus?: boolean; + autoPlay?: boolean; + cellPadding?: number | string; + cellSpacing?: number | string; + charSet?: string; + checked?: boolean; + classID?: string; + className?: string; + cols?: number; + colSpan?: number; + content?: string; + contentEditable?: boolean; + contextMenu?: string; + controls?: any; + coords?: string; + crossOrigin?: string; + data?: string; + dateTime?: string; + defer?: boolean; + dir?: string; + disabled?: boolean; + download?: any; + draggable?: boolean; + encType?: string; + form?: string; + formAction?: string; + formEncType?: string; + formMethod?: string; + formNoValidate?: boolean; + formTarget?: string; + frameBorder?: number | string; + headers?: string; + height?: number | string; + hidden?: boolean; + high?: number; + href?: string; + hrefLang?: string; + htmlFor?: string; + httpEquiv?: string; + icon?: string; + id?: string; + label?: string; + lang?: string; + list?: string; + loop?: boolean; + low?: number; + manifest?: string; + marginHeight?: number; + marginWidth?: number; + max?: number | string; + maxLength?: number; + media?: string; + mediaGroup?: string; + method?: string; + min?: number | string; + multiple?: boolean; + muted?: boolean; + name?: string; + noValidate?: boolean; + open?: boolean; + optimum?: number; + pattern?: string; + placeholder?: string; + poster?: string; + preload?: string; + radioGroup?: string; + readOnly?: boolean; + rel?: string; + required?: boolean; + role?: string; + rows?: number; + rowSpan?: number; + sandbox?: string; + scope?: string; + scoped?: boolean; + scrolling?: string; + seamless?: boolean; + selected?: boolean; + shape?: string; + size?: number; + sizes?: string; + span?: number; + spellCheck?: boolean; + src?: string; + srcDoc?: string; + srcSet?: string; + start?: number; + step?: number | string; + style?: CSSProperties; + tabIndex?: number; + target?: string; + title?: string; + type?: string; + useMap?: string; + value?: string; + width?: number | string; + wmode?: string; + + // Non-standard Attributes + autoCapitalize?: boolean; + autoCorrect?: boolean; + property?: string; + itemProp?: string; + itemScope?: boolean; + itemType?: string; + unselectable?: boolean; + } + + interface SVGElementAttributes extends HTMLAttributes { + viewBox?: string; + preserveAspectRatio?: string; + } + + interface SVGAttributes extends DOMAttributes { + ref?: string | ((component: SVGComponent) => void); + + cx?: number | string; + cy?: number | string; + d?: string; + dx?: number | string; + dy?: number | string; + fill?: string; + fillOpacity?: number | string; + fontFamily?: string; + fontSize?: number | string; + fx?: number | string; + fy?: number | string; + gradientTransform?: string; + gradientUnits?: string; + markerEnd?: string; + markerMid?: string; + markerStart?: string; + offset?: number | string; + opacity?: number | string; + patternContentUnits?: string; + patternUnits?: string; + points?: string; + preserveAspectRatio?: string; + r?: number | string; + rx?: number | string; + ry?: number | string; + spreadMethod?: string; + stopColor?: string; + stopOpacity?: number | string; + stroke?: string; + strokeDasharray?: string; + strokeLinecap?: string; + strokeOpacity?: number | string; + strokeWidth?: number | string; + textAnchor?: string; + transform?: string; + version?: string; + viewBox?: string; + x1?: number | string; + x2?: number | string; + x?: number | string; + y1?: number | string; + y2?: number | string + y?: number | string; + } + + // + // React.DOM + // ---------------------------------------------------------------------- + + interface ReactDOM { + // HTML + a: HTMLFactory; + abbr: HTMLFactory; + address: HTMLFactory; + area: HTMLFactory; + article: HTMLFactory; + aside: HTMLFactory; + audio: HTMLFactory; + b: HTMLFactory; + base: HTMLFactory; + bdi: HTMLFactory; + bdo: HTMLFactory; + big: HTMLFactory; + blockquote: HTMLFactory; + body: HTMLFactory; + br: HTMLFactory; + button: HTMLFactory; + canvas: HTMLFactory; + caption: HTMLFactory; + cite: HTMLFactory; + code: HTMLFactory; + col: HTMLFactory; + colgroup: HTMLFactory; + data: HTMLFactory; + datalist: HTMLFactory; + dd: HTMLFactory; + del: HTMLFactory; + details: HTMLFactory; + dfn: HTMLFactory; + dialog: HTMLFactory; + div: HTMLFactory; + dl: HTMLFactory; + dt: HTMLFactory; + em: HTMLFactory; + embed: HTMLFactory; + fieldset: HTMLFactory; + figcaption: HTMLFactory; + figure: HTMLFactory; + footer: HTMLFactory; + form: HTMLFactory; + h1: HTMLFactory; + h2: HTMLFactory; + h3: HTMLFactory; + h4: HTMLFactory; + h5: HTMLFactory; + h6: HTMLFactory; + head: HTMLFactory; + header: HTMLFactory; + hr: HTMLFactory; + html: HTMLFactory; + i: HTMLFactory; + iframe: HTMLFactory; + img: HTMLFactory; + input: HTMLFactory; + ins: HTMLFactory; + kbd: HTMLFactory; + keygen: HTMLFactory; + label: HTMLFactory; + legend: HTMLFactory; + li: HTMLFactory; + link: HTMLFactory; + main: HTMLFactory; + map: HTMLFactory; + mark: HTMLFactory; + menu: HTMLFactory; + menuitem: HTMLFactory; + meta: HTMLFactory; + meter: HTMLFactory; + nav: HTMLFactory; + noscript: HTMLFactory; + object: HTMLFactory; + ol: HTMLFactory; + optgroup: HTMLFactory; + option: HTMLFactory; + output: HTMLFactory; + p: HTMLFactory; + param: HTMLFactory; + picture: HTMLFactory; + pre: HTMLFactory; + progress: HTMLFactory; + q: HTMLFactory; + rp: HTMLFactory; + rt: HTMLFactory; + ruby: HTMLFactory; + s: HTMLFactory; + samp: HTMLFactory; + script: HTMLFactory; + section: HTMLFactory; + select: HTMLFactory; + small: HTMLFactory; + source: HTMLFactory; + span: HTMLFactory; + strong: HTMLFactory; + style: HTMLFactory; + sub: HTMLFactory; + summary: HTMLFactory; + sup: HTMLFactory; + table: HTMLFactory; + tbody: HTMLFactory; + td: HTMLFactory; + textarea: HTMLFactory; + tfoot: HTMLFactory; + th: HTMLFactory; + thead: HTMLFactory; + time: HTMLFactory; + title: HTMLFactory; + tr: HTMLFactory; + track: HTMLFactory; + u: HTMLFactory; + ul: HTMLFactory; + "var": HTMLFactory; + video: HTMLFactory; + wbr: HTMLFactory; + + // SVG + svg: SVGElementFactory; + circle: SVGFactory; + defs: SVGFactory; + ellipse: SVGFactory; + g: SVGFactory; + line: SVGFactory; + linearGradient: SVGFactory; + mask: SVGFactory; + path: SVGFactory; + pattern: SVGFactory; + polygon: SVGFactory; + polyline: SVGFactory; + radialGradient: SVGFactory; + rect: SVGFactory; + stop: SVGFactory; + text: SVGFactory; + tspan: SVGFactory; + } + + // + // React.PropTypes + // ---------------------------------------------------------------------- + + interface Validator { + (object: T, key: string, componentName: string): Error; + } + + interface Requireable extends Validator { + isRequired: Validator; + } + + interface ValidationMap { + [key: string]: Validator; + } + + interface ReactPropTypes { + any: Requireable; + array: Requireable; + bool: Requireable; + func: Requireable; + number: Requireable; + object: Requireable; + string: Requireable; + node: Requireable; + element: Requireable; + instanceOf(expectedClass: {}): Requireable; + oneOf(types: any[]): Requireable; + oneOfType(types: Validator[]): Requireable; + arrayOf(type: Validator): Requireable; + objectOf(type: Validator): Requireable; + shape(type: ValidationMap): Requireable; + } + + // + // React.Children + // ---------------------------------------------------------------------- + + interface ReactChildren { + map(children: ReactNode, fn: (child: ReactChild) => T): { [key:string]: T }; + forEach(children: ReactNode, fn: (child: ReactChild) => any): void; + count(children: ReactNode): number; + only(children: ReactNode): ReactChild; + } + + // + // Browser Interfaces + // https://github.com/nikeee/2048-typescript/blob/master/2048/js/touch.d.ts + // ---------------------------------------------------------------------- + + interface AbstractView { + styleMedia: StyleMedia; + document: Document; + } + + interface Touch { + identifier: number; + target: EventTarget; + screenX: number; + screenY: number; + clientX: number; + clientY: number; + pageX: number; + pageY: number; + } + + interface TouchList { + [index: number]: Touch; + length: number; + item(index: number): Touch; + identifiedTouch(identifier: number): Touch; + } +} + +declare module JSX { + interface Element extends React.ReactElement { } + interface ElementClass extends React.Component { + render(): JSX.Element; + } + interface ElementAttributesProperty { props: {}; } + + interface IntrinsicElements { + // HTML + a: React.HTMLAttributes; + abbr: React.HTMLAttributes; + address: React.HTMLAttributes; + area: React.HTMLAttributes; + article: React.HTMLAttributes; + aside: React.HTMLAttributes; + audio: React.HTMLAttributes; + b: React.HTMLAttributes; + base: React.HTMLAttributes; + bdi: React.HTMLAttributes; + bdo: React.HTMLAttributes; + big: React.HTMLAttributes; + blockquote: React.HTMLAttributes; + body: React.HTMLAttributes; + br: React.HTMLAttributes; + button: React.HTMLAttributes; + canvas: React.HTMLAttributes; + caption: React.HTMLAttributes; + cite: React.HTMLAttributes; + code: React.HTMLAttributes; + col: React.HTMLAttributes; + colgroup: React.HTMLAttributes; + data: React.HTMLAttributes; + datalist: React.HTMLAttributes; + dd: React.HTMLAttributes; + del: React.HTMLAttributes; + details: React.HTMLAttributes; + dfn: React.HTMLAttributes; + dialog: React.HTMLAttributes; + div: React.HTMLAttributes; + dl: React.HTMLAttributes; + dt: React.HTMLAttributes; + em: React.HTMLAttributes; + embed: React.HTMLAttributes; + fieldset: React.HTMLAttributes; + figcaption: React.HTMLAttributes; + figure: React.HTMLAttributes; + footer: React.HTMLAttributes; + form: React.HTMLAttributes; + h1: React.HTMLAttributes; + h2: React.HTMLAttributes; + h3: React.HTMLAttributes; + h4: React.HTMLAttributes; + h5: React.HTMLAttributes; + h6: React.HTMLAttributes; + head: React.HTMLAttributes; + header: React.HTMLAttributes; + hr: React.HTMLAttributes; + html: React.HTMLAttributes; + i: React.HTMLAttributes; + iframe: React.HTMLAttributes; + img: React.HTMLAttributes; + input: React.HTMLAttributes; + ins: React.HTMLAttributes; + kbd: React.HTMLAttributes; + keygen: React.HTMLAttributes; + label: React.HTMLAttributes; + legend: React.HTMLAttributes; + li: React.HTMLAttributes; + link: React.HTMLAttributes; + main: React.HTMLAttributes; + map: React.HTMLAttributes; + mark: React.HTMLAttributes; + menu: React.HTMLAttributes; + menuitem: React.HTMLAttributes; + meta: React.HTMLAttributes; + meter: React.HTMLAttributes; + nav: React.HTMLAttributes; + noscript: React.HTMLAttributes; + object: React.HTMLAttributes; + ol: React.HTMLAttributes; + optgroup: React.HTMLAttributes; + option: React.HTMLAttributes; + output: React.HTMLAttributes; + p: React.HTMLAttributes; + param: React.HTMLAttributes; + picture: React.HTMLAttributes; + pre: React.HTMLAttributes; + progress: React.HTMLAttributes; + q: React.HTMLAttributes; + rp: React.HTMLAttributes; + rt: React.HTMLAttributes; + ruby: React.HTMLAttributes; + s: React.HTMLAttributes; + samp: React.HTMLAttributes; + script: React.HTMLAttributes; + section: React.HTMLAttributes; + select: React.HTMLAttributes; + small: React.HTMLAttributes; + source: React.HTMLAttributes; + span: React.HTMLAttributes; + strong: React.HTMLAttributes; + style: React.HTMLAttributes; + sub: React.HTMLAttributes; + summary: React.HTMLAttributes; + sup: React.HTMLAttributes; + table: React.HTMLAttributes; + tbody: React.HTMLAttributes; + td: React.HTMLAttributes; + textarea: React.HTMLAttributes; + tfoot: React.HTMLAttributes; + th: React.HTMLAttributes; + thead: React.HTMLAttributes; + time: React.HTMLAttributes; + title: React.HTMLAttributes; + tr: React.HTMLAttributes; + track: React.HTMLAttributes; + u: React.HTMLAttributes; + ul: React.HTMLAttributes; + "var": React.HTMLAttributes; + video: React.HTMLAttributes; + wbr: React.HTMLAttributes; + + // SVG + svg: React.SVGElementAttributes; + + circle: React.SVGAttributes; + defs: React.SVGAttributes; + ellipse: React.SVGAttributes; + g: React.SVGAttributes; + line: React.SVGAttributes; + linearGradient: React.SVGAttributes; + mask: React.SVGAttributes; + path: React.SVGAttributes; + pattern: React.SVGAttributes; + polygon: React.SVGAttributes; + polyline: React.SVGAttributes; + radialGradient: React.SVGAttributes; + rect: React.SVGAttributes; + stop: React.SVGAttributes; + text: React.SVGAttributes; + tspan: React.SVGAttributes; + } +} diff --git a/react/react-jsx.d.ts b/react/react-jsx.d.ts deleted file mode 100644 index 26ee4b2201..0000000000 --- a/react/react-jsx.d.ts +++ /dev/null @@ -1,147 +0,0 @@ -// Type definitions for React v0.13.1 (JSX support) -// Project: http://facebook.github.io/react/ -// Definitions by: Asana , AssureSign , Microsoft -// Definitions: https://github.com/borisyankov/DefinitelyTyped -/// - -declare module JSX { - interface Element extends React.ReactElement { } - interface ElementClass extends React.Component { } - interface ElementAttributesProperty { props: {}; } - - interface IntrinsicElements { - // HTML - a: React.HTMLAttributes; - abbr: React.HTMLAttributes; - address: React.HTMLAttributes; - area: React.HTMLAttributes; - article: React.HTMLAttributes; - aside: React.HTMLAttributes; - audio: React.HTMLAttributes; - b: React.HTMLAttributes; - base: React.HTMLAttributes; - bdi: React.HTMLAttributes; - bdo: React.HTMLAttributes; - big: React.HTMLAttributes; - blockquote: React.HTMLAttributes; - body: React.HTMLAttributes; - br: React.HTMLAttributes; - button: React.HTMLAttributes; - canvas: React.HTMLAttributes; - caption: React.HTMLAttributes; - cite: React.HTMLAttributes; - code: React.HTMLAttributes; - col: React.HTMLAttributes; - colgroup: React.HTMLAttributes; - data: React.HTMLAttributes; - datalist: React.HTMLAttributes; - dd: React.HTMLAttributes; - del: React.HTMLAttributes; - details: React.HTMLAttributes; - dfn: React.HTMLAttributes; - dialog: React.HTMLAttributes; - div: React.HTMLAttributes; - dl: React.HTMLAttributes; - dt: React.HTMLAttributes; - em: React.HTMLAttributes; - embed: React.HTMLAttributes; - fieldset: React.HTMLAttributes; - figcaption: React.HTMLAttributes; - figure: React.HTMLAttributes; - footer: React.HTMLAttributes; - form: React.HTMLAttributes; - h1: React.HTMLAttributes; - h2: React.HTMLAttributes; - h3: React.HTMLAttributes; - h4: React.HTMLAttributes; - h5: React.HTMLAttributes; - h6: React.HTMLAttributes; - head: React.HTMLAttributes; - header: React.HTMLAttributes; - hr: React.HTMLAttributes; - html: React.HTMLAttributes; - i: React.HTMLAttributes; - iframe: React.HTMLAttributes; - img: React.HTMLAttributes; - input: React.HTMLAttributes; - ins: React.HTMLAttributes; - kbd: React.HTMLAttributes; - keygen: React.HTMLAttributes; - label: React.HTMLAttributes; - legend: React.HTMLAttributes; - li: React.HTMLAttributes; - link: React.HTMLAttributes; - main: React.HTMLAttributes; - map: React.HTMLAttributes; - mark: React.HTMLAttributes; - menu: React.HTMLAttributes; - menuitem: React.HTMLAttributes; - meta: React.HTMLAttributes; - meter: React.HTMLAttributes; - nav: React.HTMLAttributes; - noscript: React.HTMLAttributes; - object: React.HTMLAttributes; - ol: React.HTMLAttributes; - optgroup: React.HTMLAttributes; - option: React.HTMLAttributes; - output: React.HTMLAttributes; - p: React.HTMLAttributes; - param: React.HTMLAttributes; - picture: React.HTMLAttributes; - pre: React.HTMLAttributes; - progress: React.HTMLAttributes; - q: React.HTMLAttributes; - rp: React.HTMLAttributes; - rt: React.HTMLAttributes; - ruby: React.HTMLAttributes; - s: React.HTMLAttributes; - samp: React.HTMLAttributes; - script: React.HTMLAttributes; - section: React.HTMLAttributes; - select: React.HTMLAttributes; - small: React.HTMLAttributes; - source: React.HTMLAttributes; - span: React.HTMLAttributes; - strong: React.HTMLAttributes; - style: React.HTMLAttributes; - sub: React.HTMLAttributes; - summary: React.HTMLAttributes; - sup: React.HTMLAttributes; - table: React.HTMLAttributes; - tbody: React.HTMLAttributes; - td: React.HTMLAttributes; - textarea: React.HTMLAttributes; - tfoot: React.HTMLAttributes; - th: React.HTMLAttributes; - thead: React.HTMLAttributes; - time: React.HTMLAttributes; - title: React.HTMLAttributes; - tr: React.HTMLAttributes; - track: React.HTMLAttributes; - u: React.HTMLAttributes; - ul: React.HTMLAttributes; - "var": React.HTMLAttributes; - video: React.HTMLAttributes; - wbr: React.HTMLAttributes; - - // SVG - svg: React.SVGElementAttributes; - - circle: React.SVGAttributes; - defs: React.SVGAttributes; - ellipse: React.SVGAttributes; - g: React.SVGAttributes; - line: React.SVGAttributes; - linearGradient: React.SVGAttributes; - mask: React.SVGAttributes; - path: React.SVGAttributes; - pattern: React.SVGAttributes; - polygon: React.SVGAttributes; - polyline: React.SVGAttributes; - radialGradient: React.SVGAttributes; - rect: React.SVGAttributes; - stop: React.SVGAttributes; - text: React.SVGAttributes; - tspan: React.SVGAttributes; - } -} diff --git a/react/react.d.ts b/react/react.d.ts index b23a8240ea..5fbad0d227 100644 --- a/react/react.d.ts +++ b/react/react.d.ts @@ -1,9 +1,9 @@ -// Type definitions for React v0.13.1 (internal and external module) +// Type definitions for React v0.13.1 (external module) // Project: http://facebook.github.io/react/ -// Definitions by: Asana , AssureSign +// Definitions by: Asana , AssureSign , Microsoft // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module React { +declare module __React { // // React Elements // ---------------------------------------------------------------------- @@ -48,6 +48,7 @@ declare module React { type HTMLFactory = DOMFactory; type SVGFactory = DOMFactory; + type SVGElementFactory = DOMFactory; // // React Nodes @@ -691,6 +692,7 @@ declare module React { wbr: HTMLFactory; // SVG + svg: SVGElementFactory; circle: SVGFactory; defs: SVGFactory; ellipse: SVGFactory; @@ -705,7 +707,6 @@ declare module React { radialGradient: SVGFactory; rect: SVGFactory; stop: SVGFactory; - svg: SVGFactory; text: SVGFactory; tspan: SVGFactory; } @@ -785,5 +786,151 @@ declare module React { } declare module "react" { - export = React; + export = __React; +} + +declare module JSX { + import React = __React; + + interface Element extends React.ReactElement { } + interface ElementClass extends React.Component { + render(): JSX.Element; + } + interface ElementAttributesProperty { props: {}; } + + interface IntrinsicElements { + // HTML + a: React.HTMLAttributes; + abbr: React.HTMLAttributes; + address: React.HTMLAttributes; + area: React.HTMLAttributes; + article: React.HTMLAttributes; + aside: React.HTMLAttributes; + audio: React.HTMLAttributes; + b: React.HTMLAttributes; + base: React.HTMLAttributes; + bdi: React.HTMLAttributes; + bdo: React.HTMLAttributes; + big: React.HTMLAttributes; + blockquote: React.HTMLAttributes; + body: React.HTMLAttributes; + br: React.HTMLAttributes; + button: React.HTMLAttributes; + canvas: React.HTMLAttributes; + caption: React.HTMLAttributes; + cite: React.HTMLAttributes; + code: React.HTMLAttributes; + col: React.HTMLAttributes; + colgroup: React.HTMLAttributes; + data: React.HTMLAttributes; + datalist: React.HTMLAttributes; + dd: React.HTMLAttributes; + del: React.HTMLAttributes; + details: React.HTMLAttributes; + dfn: React.HTMLAttributes; + dialog: React.HTMLAttributes; + div: React.HTMLAttributes; + dl: React.HTMLAttributes; + dt: React.HTMLAttributes; + em: React.HTMLAttributes; + embed: React.HTMLAttributes; + fieldset: React.HTMLAttributes; + figcaption: React.HTMLAttributes; + figure: React.HTMLAttributes; + footer: React.HTMLAttributes; + form: React.HTMLAttributes; + h1: React.HTMLAttributes; + h2: React.HTMLAttributes; + h3: React.HTMLAttributes; + h4: React.HTMLAttributes; + h5: React.HTMLAttributes; + h6: React.HTMLAttributes; + head: React.HTMLAttributes; + header: React.HTMLAttributes; + hr: React.HTMLAttributes; + html: React.HTMLAttributes; + i: React.HTMLAttributes; + iframe: React.HTMLAttributes; + img: React.HTMLAttributes; + input: React.HTMLAttributes; + ins: React.HTMLAttributes; + kbd: React.HTMLAttributes; + keygen: React.HTMLAttributes; + label: React.HTMLAttributes; + legend: React.HTMLAttributes; + li: React.HTMLAttributes; + link: React.HTMLAttributes; + main: React.HTMLAttributes; + map: React.HTMLAttributes; + mark: React.HTMLAttributes; + menu: React.HTMLAttributes; + menuitem: React.HTMLAttributes; + meta: React.HTMLAttributes; + meter: React.HTMLAttributes; + nav: React.HTMLAttributes; + noscript: React.HTMLAttributes; + object: React.HTMLAttributes; + ol: React.HTMLAttributes; + optgroup: React.HTMLAttributes; + option: React.HTMLAttributes; + output: React.HTMLAttributes; + p: React.HTMLAttributes; + param: React.HTMLAttributes; + picture: React.HTMLAttributes; + pre: React.HTMLAttributes; + progress: React.HTMLAttributes; + q: React.HTMLAttributes; + rp: React.HTMLAttributes; + rt: React.HTMLAttributes; + ruby: React.HTMLAttributes; + s: React.HTMLAttributes; + samp: React.HTMLAttributes; + script: React.HTMLAttributes; + section: React.HTMLAttributes; + select: React.HTMLAttributes; + small: React.HTMLAttributes; + source: React.HTMLAttributes; + span: React.HTMLAttributes; + strong: React.HTMLAttributes; + style: React.HTMLAttributes; + sub: React.HTMLAttributes; + summary: React.HTMLAttributes; + sup: React.HTMLAttributes; + table: React.HTMLAttributes; + tbody: React.HTMLAttributes; + td: React.HTMLAttributes; + textarea: React.HTMLAttributes; + tfoot: React.HTMLAttributes; + th: React.HTMLAttributes; + thead: React.HTMLAttributes; + time: React.HTMLAttributes; + title: React.HTMLAttributes; + tr: React.HTMLAttributes; + track: React.HTMLAttributes; + u: React.HTMLAttributes; + ul: React.HTMLAttributes; + "var": React.HTMLAttributes; + video: React.HTMLAttributes; + wbr: React.HTMLAttributes; + + // SVG + svg: React.SVGElementAttributes; + + circle: React.SVGAttributes; + defs: React.SVGAttributes; + ellipse: React.SVGAttributes; + g: React.SVGAttributes; + line: React.SVGAttributes; + linearGradient: React.SVGAttributes; + mask: React.SVGAttributes; + path: React.SVGAttributes; + pattern: React.SVGAttributes; + polygon: React.SVGAttributes; + polyline: React.SVGAttributes; + radialGradient: React.SVGAttributes; + rect: React.SVGAttributes; + stop: React.SVGAttributes; + text: React.SVGAttributes; + tspan: React.SVGAttributes; + } } From b592e40b32a0f82a05915e851468b57c6b06f1ab Mon Sep 17 00:00:00 2001 From: Jacob Foshee Date: Mon, 6 Jul 2015 18:21:24 -0500 Subject: [PATCH 053/144] Corrected linearGradient members (not 0 based) See documentation: "Linear gradients in Highcharts have a similar syntax to that of SVG" ... "linearGradient holds another object literal that defines the start position (x1, y1) and the end position (x2, y2)" http://www.highcharts.com/docs/chart-design-and-style/colors http://www.w3schools.com/svg/svg_grad_linear.asp --- highcharts/highcharts.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/highcharts/highcharts.d.ts b/highcharts/highcharts.d.ts index 584d61c9ba..9bda29782d 100644 --- a/highcharts/highcharts.d.ts +++ b/highcharts/highcharts.d.ts @@ -166,7 +166,7 @@ interface HighchartsChartEvents { interface HighchartsGradient { linearGradient?: { - x0: number; y0: number; x1: number; y1: number; + x1: number; y1: number; x2: number; y2: number; }; radialGradient?: { cx: number; cy: number; r: number; From 9376c750d6d6fd8c6894588d95566e7da52980f6 Mon Sep 17 00:00:00 2001 From: Jacob Foshee Date: Mon, 6 Jul 2015 18:35:14 -0500 Subject: [PATCH 054/144] Update highcharts-tests.ts --- highcharts/highcharts-tests.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/highcharts/highcharts-tests.ts b/highcharts/highcharts-tests.ts index 464f536d99..9918df9535 100644 --- a/highcharts/highcharts-tests.ts +++ b/highcharts/highcharts-tests.ts @@ -23,10 +23,10 @@ var animate: HighchartsAnimation = { var gradient: HighchartsGradient = { linearGradient: { - x0: 0, - y0: 0, - x1: 500, - y1: 500 + x1: 0, + y1: 0, + x2: 500, + y2: 500 }, stops: [ [0, 'rgb(255, 255, 255)'], @@ -136,4 +136,4 @@ var highChartSettings: HighchartsOptions = { var container = $("#container").highcharts(highChartSettings, (chart) => { chart.series[0].setVisible(true, true); -}); \ No newline at end of file +}); From 779cfc550ad53c17fa5c7f133106fa28dc113e7d Mon Sep 17 00:00:00 2001 From: Jordan Potter Date: Mon, 6 Jul 2015 17:03:24 -0700 Subject: [PATCH 055/144] Make Flux definitions global/external agnostic --- flux/flux.d.ts | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/flux/flux.d.ts b/flux/flux.d.ts index 8a9dbf967d..bf5bafac4b 100644 --- a/flux/flux.d.ts +++ b/flux/flux.d.ts @@ -3,14 +3,14 @@ // Definitions by: Steve Baker // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module 'flux' { +declare module Flux { /** * Dispatcher class * Create an instance to use throughout the application. * Or extend it to create a derived dispatcher class. * - * Specify a type in the 'TPayload' generic argument to use strongly-typed payloads, + * Specify a type in the 'TPayload' generic argument to use strongly-typed payloads, * otherwise specify 'any' * * Examples: @@ -23,41 +23,45 @@ declare module 'flux' { /** * Create an instance of the Dispatcher class to use throughout the application. * - * Specify a type in the 'TPayload' generic argument to use strongly-typed payloads, + * Specify a type in the 'TPayload' generic argument to use strongly-typed payloads, * otherwise specify 'any' * * Examples: * var dispatcher = new flux.Dispatcher() * var typedDispatcher = new flux.Dispatcher() */ - constructor() + constructor(); /** * Registers a callback that will be invoked with every payload sent to the dispatcher. * Returns a string token to identify the callback to be used with waitFor() or unregister. */ - register(callback: (payload: TPayload) => void): string - + register(callback: (payload: TPayload) => void): string; + /** * Unregisters a callback with the given ID token */ - unregister(id: string): void + unregister(id: string): void; /** * Waits for the callbacks with the specified IDs to be invoked before continuing execution - * of the current callback. This method should only be used by a callback in response + * of the current callback. This method should only be used by a callback in response * to a dispatched payload. */ - waitFor(IDs: string[]): void + waitFor(IDs: string[]): void; /** * Dispatches a payload to all registered callbacks */ - dispatch(payload: TPayload): void + dispatch(payload: TPayload): void; /** * Gets whether the dispatcher is currently dispatching */ - isDispatching(): boolean + isDispatching(): boolean; } -} \ No newline at end of file +} + +declare module "flux" { + export = Flux; +} From 5a55b05ad98267b8b898c6e5c3436d3123704c5e Mon Sep 17 00:00:00 2001 From: Vadim Macagon Date: Sun, 5 Jul 2015 13:27:50 +0700 Subject: [PATCH 056/144] Add typings for Atom's first-mate library --- first-mate/.editorconfig | 3 + first-mate/first-mate-tests.ts | 15 +++++ first-mate/first-mate.d.ts | 108 +++++++++++++++++++++++++++++++++ 3 files changed, 126 insertions(+) create mode 100644 first-mate/.editorconfig create mode 100644 first-mate/first-mate-tests.ts create mode 100644 first-mate/first-mate.d.ts diff --git a/first-mate/.editorconfig b/first-mate/.editorconfig new file mode 100644 index 0000000000..570211f898 --- /dev/null +++ b/first-mate/.editorconfig @@ -0,0 +1,3 @@ +[*.ts] +indent_style = tab +indent_size = 4 diff --git a/first-mate/first-mate-tests.ts b/first-mate/first-mate-tests.ts new file mode 100644 index 0000000000..1a181de4a9 --- /dev/null +++ b/first-mate/first-mate-tests.ts @@ -0,0 +1,15 @@ +/// + +import firstMate = require('first-mate'); +var GrammarRegistry = firstMate.GrammarRegistry; +var Grammar = firstMate.GrammarRegistry; +type IToken = AtomFirstMate.IToken; +// The import and type aliasing above can be done more concisely in TypeScript 1.5+: +//import { GrammarRegistry, Grammar, IToken } from "first-mate"; + +var registry = new GrammarRegistry({ maxTokensPerLine: 100 }); +var grammar = registry.loadGrammarSync('javascript.json'); +var result = grammar.tokenizeLine('var text = "hello world";'); +result.tokens.forEach((token) => { + console.log("Token text: '" + token.value + "' with scopes: " + token.scopes); +}); diff --git a/first-mate/first-mate.d.ts b/first-mate/first-mate.d.ts new file mode 100644 index 0000000000..d780116c2d --- /dev/null +++ b/first-mate/first-mate.d.ts @@ -0,0 +1,108 @@ +// Type definitions for first-mate v4.1.7 +// Project: https://github.com/atom/first-mate/ +// Definitions by: Vadim Macagon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module AtomFirstMate { + type Disposable = AtomEventKit.Disposable; + + interface IToken { + value: string; + scopes: string[]; + } + + /** Result returned by `Grammar.tokenizeLine`. */ + interface TokenizeLineResult { + /** Text that was tokenized. */ + line: string; + tags: any[]; + /** + * This is a dynamic property that will only be available if `Grammar.tokenizeLine` was called + * with `compatibilityMode` set to `true` (the default). + */ + tokens?: IToken[]; + /** + * The tokenized state at the end of the line. This should be passed back into `tokenizeLine` + * when tokenizing the next line in the file/buffer. + */ + ruleStack: Rule[] + } + + /** Instance side of Rule class. */ + interface Rule { + } + + /** Static side of Grammar class. */ + interface GrammarStatic { + prototype: Grammar; + new (registry: GrammarRegistry, options?: any): Grammar; + } + + /** Instance side of Grammar class. */ + interface Grammar { + constructor: GrammarStatic; + onDidUpdate(callback: Function): Disposable; + /** + * Tokenizes all lines in a string. + * + * @param text A string containing one or more lines. + * @return An array of token arrays, one token array per line. + */ + tokenizeLines(text: string): Array>; + /** + * Tokenizes a line of text. + * + * @param line Text to be tokenized. + * @param firstLine Indicates whether `line` is the first line in the file/buffer, + * defaults to `false`. + * @param compatibilityMode `true` by default. + * @return An object containing tokens for the given line. + */ + tokenizeLine( + line: string, ruleStack?: Rule[], firstLine?: boolean, compatibilityMode?: boolean + ): TokenizeLineResult; + } + + /** Grammar that tokenizes lines of text. */ + var Grammar: GrammarStatic; + + /** Static side of GrammarRegistry class. */ + interface GrammarRegistryStatic { + prototype: GrammarRegistry; + new (options?: { maxTokensPerLine: number }): GrammarRegistry; + } + + /** Instance side of GrammarRegistry class. */ + interface GrammarRegistry { + constructor: GrammarRegistryStatic; + + // Event Subscription + + onDidAddGrammar(callback: (grammar: Grammar) => void): Disposable; + onDidUpdateGrammar(callback: (grammar: Grammar) => void): Disposable; + + // Managing Grammars + + getGrammars(): Grammar[]; + grammarForScopeName(scopeName: string): Grammar; + addGrammar(grammar: Grammar): Disposable; + removeGrammarForScopeName(scopeName: string): Grammar; + readGrammarSync(grammarPath: string): Grammar; + readGrammar(grammarPath: string, callback: (error: Error, grammar: Grammar) => void): void; + loadGrammarSync(grammarPath: string): Grammar; + loadGrammar(grammarPath: string, callback: (error: Error, grammar: Grammar) => void): void; + grammarOverrideForPath(filePath: string): Grammar; + setGrammarOverrideForPath(filePath: string, scopeName: string): Grammar; + clearGrammarOverrides(): void; + selectGrammar(filePath: string, fileContents: string): Grammar; + } + + /** Registry containing one or more grammars. */ + var GrammarRegistry: GrammarRegistryStatic; +} + +declare module 'first-mate' { + export = AtomFirstMate; +} From ec21c91b3c34f9651f271aeb61003921885f78fe Mon Sep 17 00:00:00 2001 From: Matt Brooks Date: Tue, 7 Jul 2015 08:41:43 +0100 Subject: [PATCH 057/144] Align definition name with Bower package name --- .../jquery-validation-unobtrusive-tests.ts | 2 +- .../jquery-validation-unobtrusive.d.ts | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename jquery.validation.unobtrusive/jquery.validation.unobtrusive-tests.ts => jquery-validation-unobtrusive/jquery-validation-unobtrusive-tests.ts (83%) rename jquery.validation.unobtrusive/jquery.validation.unobtrusive.d.ts => jquery-validation-unobtrusive/jquery-validation-unobtrusive.d.ts (100%) diff --git a/jquery.validation.unobtrusive/jquery.validation.unobtrusive-tests.ts b/jquery-validation-unobtrusive/jquery-validation-unobtrusive-tests.ts similarity index 83% rename from jquery.validation.unobtrusive/jquery.validation.unobtrusive-tests.ts rename to jquery-validation-unobtrusive/jquery-validation-unobtrusive-tests.ts index 169fc1c5b7..f50535e9d7 100644 --- a/jquery.validation.unobtrusive/jquery.validation.unobtrusive-tests.ts +++ b/jquery-validation-unobtrusive/jquery-validation-unobtrusive-tests.ts @@ -1,4 +1,4 @@ -/// +/// $.validator.unobtrusive.adapters.add("adapter", () => { }); $.validator.unobtrusive.adapters.add("adapter", function () { diff --git a/jquery.validation.unobtrusive/jquery.validation.unobtrusive.d.ts b/jquery-validation-unobtrusive/jquery-validation-unobtrusive.d.ts similarity index 100% rename from jquery.validation.unobtrusive/jquery.validation.unobtrusive.d.ts rename to jquery-validation-unobtrusive/jquery-validation-unobtrusive.d.ts From 4618f92d024f4b554476f4bb5f55850da7e28755 Mon Sep 17 00:00:00 2001 From: Matt Brooks Date: Tue, 7 Jul 2015 08:55:54 +0100 Subject: [PATCH 058/144] Add more tests --- .../jquery-validation-unobtrusive-tests.ts | 44 +++++++++++++++++-- 1 file changed, 40 insertions(+), 4 deletions(-) diff --git a/jquery-validation-unobtrusive/jquery-validation-unobtrusive-tests.ts b/jquery-validation-unobtrusive/jquery-validation-unobtrusive-tests.ts index f50535e9d7..94bd18bdc7 100644 --- a/jquery-validation-unobtrusive/jquery-validation-unobtrusive-tests.ts +++ b/jquery-validation-unobtrusive/jquery-validation-unobtrusive-tests.ts @@ -1,13 +1,49 @@ /// +// Test overloads for `add` method $.validator.unobtrusive.adapters.add("adapter", () => { }); $.validator.unobtrusive.adapters.add("adapter", function () { + return true; +}); +$.validator.unobtrusive.adapters.add("adapter", ["param1", "param2"], () => { }); + +// Test overloads for `addMinMax` method +$.validator.unobtrusive.adapters.addMinMax("adapter", "minRule", "maxRule", "minMaxRule"); +$.validator.unobtrusive.adapters.addMinMax("adapter", "minRule", "maxRule", "minMaxRule", "minAttr"); +$.validator.unobtrusive.adapters.addMinMax("adapter", "minRule", "maxRule", "minMaxRule", "minAttr", "maxAttr"); + +// Test overloads for `addSingleVal` method +$.validator.unobtrusive.adapters.addSingleVal("adapter", "rule"); +$.validator.unobtrusive.adapters.addSingleVal("adapter", "attr", "rule"); + +// Test overloads for `addBool` method +$.validator.unobtrusive.adapters.addBool("adapter"); +$.validator.unobtrusive.adapters.addBool("adapter", "rule"); + +// Test `addMethod` +$.validator.unobtrusive.adapters.addMethod("adapter", (value, element, params) => { + return true; }); -$.validator.unobtrusive.adapters.addBool("adapter"); +// Test method chaining +$.validator.unobtrusive.adapters + .add("required", () => { }) + .addMinMax("length", "minlength", "maxlength", "rangelength") + .addSingleVal("regex", "pattern") + .addBool("url") + .addMethod("nonalphamin", (value, element, nonalphamin) => { + return null; + }); -$.validator.unobtrusive.adapters.addMethod("adapter",(value, element) => { - return true; -}) +// Test overloads for `parseElement` +$.validator.unobtrusive.parseElement("form"); +$.validator.unobtrusive.parseElement(document); +$.validator.unobtrusive.parseElement(document.getElementById("the-form")); +$.validator.unobtrusive.parseElement($("#the-form")); +$.validator.unobtrusive.parseElement($("#the-form"), true); +// Test overloads for `parse` +$.validator.unobtrusive.parse("form"); $.validator.unobtrusive.parse(document); +$.validator.unobtrusive.parse(document.getElementById("the-form")); +$.validator.unobtrusive.parse($("#the-form")); From a549443564ccc7c243ef86b09364ed3010847f04 Mon Sep 17 00:00:00 2001 From: Matt Brooks Date: Tue, 7 Jul 2015 09:22:39 +0100 Subject: [PATCH 059/144] Fix `Adapters` definition --- .../jquery-validation-unobtrusive-tests.ts | 13 +++++++++++++ .../jquery-validation-unobtrusive.d.ts | 11 ++++++++--- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/jquery-validation-unobtrusive/jquery-validation-unobtrusive-tests.ts b/jquery-validation-unobtrusive/jquery-validation-unobtrusive-tests.ts index 94bd18bdc7..96ccbe325a 100644 --- a/jquery-validation-unobtrusive/jquery-validation-unobtrusive-tests.ts +++ b/jquery-validation-unobtrusive/jquery-validation-unobtrusive-tests.ts @@ -35,6 +35,19 @@ $.validator.unobtrusive.adapters return null; }); +// Test `Adapters` indexer +var adapterName = $.validator.unobtrusive.adapters[0].name; + +// Test `Adapters` iterator +$.each($.validator.unobtrusive.adapters, function (index, adapter) { + console.log(adapter.name); + console.log(adapter.params); + console.log(adapter.adapt); +}); + +// Test `Adapters` array +$.validator.unobtrusive.adapters.push({ name: "adapter", params: ["param1"], adapt: () => { } }); + // Test overloads for `parseElement` $.validator.unobtrusive.parseElement("form"); $.validator.unobtrusive.parseElement(document); diff --git a/jquery-validation-unobtrusive/jquery-validation-unobtrusive.d.ts b/jquery-validation-unobtrusive/jquery-validation-unobtrusive.d.ts index 866d6607dd..f14b589139 100644 --- a/jquery-validation-unobtrusive/jquery-validation-unobtrusive.d.ts +++ b/jquery-validation-unobtrusive/jquery-validation-unobtrusive.d.ts @@ -8,10 +8,15 @@ declare module MicrosoftJQueryUnobtrusiveValidation { type JQuerySelector = string | Document | Element | JQuery; - interface Adapters { - [key: string]: Function; + interface Adapter { + name: string; + params: string[]; + adapt: Function + } + + interface Adapters extends Array { add(adapterName: string, fn: Function): Adapters; - add(adapterName: string, params: any, fn: Function): Adapters; + add(adapterName: string, params: string[], fn: Function): Adapters; addMinMax(adapterName: string, minRuleName: string, maxRuleName: string, minMaxRuleName: string, minAttribute?: string, maxAttribute?: string): Adapters; addSingleVal(adapterName: string, ruleName: string): Adapters; addSingleVal(adapterName: string, attribute: string, ruleName: string): Adapters; From e553601092f0bf0722139a9dd0ba98ea1e484084 Mon Sep 17 00:00:00 2001 From: Stephen Remde Date: Tue, 7 Jul 2015 13:19:10 +0100 Subject: [PATCH 060/144] added missing 'bytesWritten' field to fs.WriteStream --- node/node-0.10.d.ts | 1 + node/node.d.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/node/node-0.10.d.ts b/node/node-0.10.d.ts index 5c095596c4..2f3824462d 100644 --- a/node/node-0.10.d.ts +++ b/node/node-0.10.d.ts @@ -910,6 +910,7 @@ declare module "fs" { } export interface WriteStream extends stream.Writable { close(): void; + bytesWritten: number; } export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; diff --git a/node/node.d.ts b/node/node.d.ts index 2865aedd4e..fa3881e83b 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1054,6 +1054,7 @@ declare module "fs" { } export interface WriteStream extends stream.Writable { close(): void; + bytesWritten: number; } /** From 3387b8b71553573ec44125b9daf81d9c6e22efa9 Mon Sep 17 00:00:00 2001 From: pafflique Date: Tue, 7 Jul 2015 16:57:09 +0300 Subject: [PATCH 061/144] Collection.add signature fix http://backbonejs.org/#Collection-add - "Returns the added (or preexisting, if duplicate) models." --- backbone/backbone.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index 9d54361d5e..b9039be351 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -181,8 +181,8 @@ declare module Backbone { comparator(element: TModel): number; comparator(compare: TModel, to?: TModel): number; - add(model: TModel, options?: AddOptions): Collection; - add(models: TModel[], options?: AddOptions): Collection; + add(model: TModel, options?: AddOptions): TModel; + add(models: TModel[], options?: AddOptions): TModel[]; at(index: number): TModel; /** * Get a model from a collection, specified by an id, a cid, or by passing in a model. From 70761a5ae8f624f2ce3517540a93bc68de5f3f4c Mon Sep 17 00:00:00 2001 From: pafflique Date: Tue, 7 Jul 2015 17:11:04 +0300 Subject: [PATCH 062/144] Allow mixed content in Collection.add Valid for TypeScript 1.4 --- backbone/backbone.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index b9039be351..275dba237b 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -181,8 +181,8 @@ declare module Backbone { comparator(element: TModel): number; comparator(compare: TModel, to?: TModel): number; - add(model: TModel, options?: AddOptions): TModel; - add(models: TModel[], options?: AddOptions): TModel[]; + add(model: {}|TModel, options?: AddOptions): TModel; + add(models: ({}|TModel)[], options?: AddOptions): TModel[]; at(index: number): TModel; /** * Get a model from a collection, specified by an id, a cid, or by passing in a model. From e850267d120af0863d617be2a7b3e043a36fb800 Mon Sep 17 00:00:00 2001 From: Alexandre BODIN Date: Tue, 7 Jul 2015 18:10:41 +0200 Subject: [PATCH 063/144] Add Object type for tls in server.connection options --- hapi/hapi-8.2.0.d.ts | 2212 ++++++++++++++++++++++++++++++++++++++ hapi/hapi-tests-8.2.0.ts | 99 ++ hapi/hapi.d.ts | 150 +-- 3 files changed, 2386 insertions(+), 75 deletions(-) create mode 100644 hapi/hapi-8.2.0.d.ts create mode 100644 hapi/hapi-tests-8.2.0.ts diff --git a/hapi/hapi-8.2.0.d.ts b/hapi/hapi-8.2.0.d.ts new file mode 100644 index 0000000000..8d3da2620b --- /dev/null +++ b/hapi/hapi-8.2.0.d.ts @@ -0,0 +1,2212 @@ +// Type definitions for hapi 8.2.0 +// Project: http://github.com/spumko/hapi +// Definitions by: Jason Swearingen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +//This is a total rewrite of Hakubo's original hapi.d.ts, as it was out of date/incomplete. + + +/// +/// + + + + +declare module "hapi" { + import http = require("http"); + import stream = require("stream"); + import Events = require("events"); + + interface IDictionary { + [key: string]: T; + } + + /** Boom Module for errors. https://github.com/hapijs/boom + * boom provides a set of utilities for returning HTTP errors. Each utility returns a Boom error response object (instance of Error) which includes the following properties: */ + export interface IBoom extends Error { + /** if true, indicates this is a Boom object instance. */ + isBoom: boolean; + /** convenience bool indicating status code >= 500. */ + isServer: boolean; + /** the error message. */ + message: string; + /** the formatted response.Can be directly manipulated after object construction to return a custom error response.Allowed root keys: */ + output: { + /** the HTTP status code (typically 4xx or 5xx). */ + statusCode: number; + /** an object containing any HTTP headers where each key is a header name and value is the header content. */ + headers: IDictionary; + /** the formatted object used as the response payload (stringified).Can be directly manipulated but any changes will be lost if reformat() is called.Any content allowed and by default includes the following content: */ + payload: { + /** the HTTP status code, derived from error.output.statusCode. */ + statusCode: number; + /** the HTTP status message (e.g. 'Bad Request', 'Internal Server Error') derived from statusCode. */ + error: string; + /** the error message derived from error.message. */ + message: string; + }; + }; + /** reformat()rebuilds error.output using the other object properties. */ + reformat(): void; + + } + + /** cache functionality via the "CatBox" module. */ + export interface ICatBoxCacheOptions { + /** a prototype function or catbox engine object. */ + engine: any; + /** an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well. */ + name?: string; + /** if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. */ + shared?: boolean; + } + + /** Any connections configuration server defaults can be included to override and customize the individual connection. */ + export interface ISeverConnectionOptions extends IConnectionConfigurationServerDefaults { + /** - the public hostname or IP address. Used only to set server.info.host and server.info.uri. If not configured, defaults to the operating system hostname and if not available, to 'localhost'.*/ + host?: string; + /** - sets the host name or IP address the connection will listen on.If not configured, defaults to host if present, otherwise to all available network interfaces (i.e. '0.0.0.0').Set to 127.0.0.1 or localhost to restrict connection to only those coming from the same machine.*/ + address?: string; + /** - the TCP port the connection will listen to.Defaults to an ephemeral port (0) which uses an available port when the server is started (and assigned to server.info.port).If port is a string containing a '/' character, it is used as a UNIX domain socket path and if it starts with '\.\pipe' as a Windows named pipe.*/ + port?: string|number; + /** - the full public URI without the path (e.g. 'http://example.com:8080').If present, used as the connection info.uri otherwise constructed from the connection settings.*/ + uri?: string; + /** - optional node.js HTTP (or HTTPS) http.Server object or any compatible object.If the listener needs to be manually started, set autoListen to false.If the listener uses TLS, set tls to true.*/ + listener?: any; + /** - indicates that the connection.listener will be started manually outside the framework.Cannot be specified with a port setting.Defaults to true.*/ + autoListen?: boolean; + /** caching headers configuration: */ + cache?: { + /** - an array of HTTP response status codes (e.g. 200) which are allowed to include a valid caching directive.Defaults to [200]. */ + statuses: number[]; + }; + /** - a string or string array of labels used to server.select() specific connections matching the specified labels.Defaults to an empty array [](no labels).*/ + labels?: string|string[]; + /** - used to create an HTTPS connection.The tls object is passed unchanged as options to the node.js HTTPS server as described in the node.js HTTPS documentation.Set to true when passing a listener object that has been configured to use TLS directly. */ + tls?: boolean; + + } + + export interface IConnectionConfigurationServerDefaults { + /** application-specific connection configuration which can be accessed via connection.settings.app. Provides a safe place to store application configuration without potential conflicts with the framework internals. Should not be used to configure plugins which should use plugins[name]. Note the difference between connection.settings.app which is used to store configuration values and connection.app which is meant for storing run-time state. */ + app?: any; + /** connection load limits configuration where: */ + load?: { + /** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxHeapUsedBytes: number; + /** maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxRssBytes: number; + /** maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxEventLoopDelay: number; + }; + /** plugin-specific configuration which can later be accessed via connection.settings.plugins. Provides a place to store and pass connection-specific plugin configuration. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between connection.settings.plugins which is used to store configuration values and connection.plugins which is meant for storing run-time state. */ + plugins?: any; + /** controls how incoming request URIs are matched against the routing table: */ + router?: { + /** determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to true. */ + isCaseSensitive: boolean; + /** removes trailing slashes on incoming paths. Defaults to false. */ + stripTrailingSlash: boolean; + }; + /** a route options object used to set the default configuration for every route. */ + routes?: IRouteAdditionalConfigurationOptions; + state?: IServerState; + } + + /** Note that the options object is deeply cloned and cannot contain any values that are unsafe to perform deep copy on.*/ + export interface IServerOptions { + /** application-specific configuration which can later be accessed via server.settings.app. Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time state. Defaults to {}. */ + app?: any; + /** sets up server-side caching. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and capabilities. hapi uses catbox for its cache which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, and Riak). Caching is only utilized if methods and plugins explicitly store their state in the cache. The server cache configuration only defines the storage container itself. cache can be assigned: + a prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')). + a configuration object with the following options: + enginea prototype function or catbox engine object. + namean identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well. + sharedif true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. + other options passed to the catbox strategy used. + an array of the above object for configuring multiple cache instances, each with a unique name. When an array of objects is provided, multiple cache connections are established and each array item (except one) must include a name. */ + cache?: string|ICatBoxCacheOptions|Array|any; + /** sets the default connections configuration which can be overridden by each connection where: */ + connections?: IConnectionConfigurationServerDefaults; + /** determines which logged events are sent to the console (this should only be used for development and does not affect which events are actually logged internally and recorded). Set to false to disable all console logging, or to an object*/ + debug?: boolean|{ + /** - a string array of server log tags to be displayed via console.error() when the events are logged via server.log() as well as internally generated server logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. */ + log: string[]; + /** - a string array of request log tags to be displayed via console.error() when the events are logged via request.log() as well as internally generated request logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error.*/ + request: string[]; + }; + /** file system related settings*/ + files?: { + /** sets the maximum number of file etag hash values stored in the etags cache. Defaults to 10000.*/ + etagsCacheMaxSize?: number; + }; + /** process load monitoring*/ + load?: { + /** the frequency of sampling in milliseconds. Defaults to 0 (no sampling).*/ + sampleInterval?: number; + }; + + /** options passed to the mimos module (https://github.com/hapijs/mimos) when generating the mime database used by the server and accessed via server.mime.*/ + mime?: any; + /** if true, does not load the inert (file and directory support), h2o2 (proxy support), and vision (views support) plugins automatically. The plugins can be loaded manually after construction. Defaults to false (plugins loaded). */ + minimal?: boolean; + /** plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. Defaults to {}.*/ + plugins?: IDictionary; + + } + + export interface IServerViewCompile { + (template: string, options: any): void; + (template: string, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: boolean) => void) => void) => void): void; + } + + export interface IServerViewsAdditionalOptions { + /** path - the root file path used to resolve and load the templates identified when calling reply.view().Defaults to current working directory.*/ + path?: string; + /**partialsPath - the root file path where partials are located.Partials are small segments of template code that can be nested and reused throughout other templates.Defaults to no partials support (empty path). + */ + partialsPath?: string; + /**helpersPath - the directory path where helpers are located.Helpers are functions used within templates to perform transformations and other data manipulations using the template context or other inputs.Each '.js' file in the helpers directory is loaded and the file name is used as the helper name.The files must export a single method with the signature function(context) and return a string.Sub - folders are not supported and are ignored.Defaults to no helpers support (empty path).Note that jade does not support loading helpers this way.*/ + helpersPath?: string; + /**relativeTo - a base path used as prefix for path and partialsPath.No default.*/ + relativeTo?: string; + + /**layout - if set to true or a layout filename, layout support is enabled.A layout is a single template file used as the parent template for other view templates in the same engine.If true, the layout template name must be 'layout.ext' where 'ext' is the engine's extension. Otherwise, the provided filename is suffixed with the engine's extension and loaded.Disable layout when using Jade as it will handle including any layout files independently.Defaults to false.*/ + layout?: boolean; + /**layoutPath - the root file path where layout templates are located (using the relativeTo prefix if present). Defaults to path.*/ + layoutPath?: string; + /**layoutKeyword - the key used by the template engine to denote where primary template content should go.Defaults to 'content'.*/ + layoutKeywork?: string; + /**encoding - the text encoding used by the templates when reading the files and outputting the result.Defaults to 'utf8'.*/ + encoding?: string; + /**isCached - if set to false, templates will not be cached (thus will be read from file on every use).Defaults to true.*/ + isCached?: boolean; + /**allowAbsolutePaths - if set to true, allows absolute template paths passed to reply.view().Defaults to false.*/ + allowAbsolutePaths?: boolean; + /**allowInsecureAccess - if set to true, allows template paths passed to reply.view() to contain '../'.Defaults to false.*/ + allowInsecureAccess?: boolean; + /**compileOptions - options object passed to the engine's compile function. Defaults to empty options {}.*/ + compileOptions?: any; + /**runtimeOptions - options object passed to the returned function from the compile operation.Defaults to empty options {}.*/ + runtimeOptions?: any; + /**contentType - the content type of the engine results.Defaults to 'text/html'.*/ + contentType?: string; + /**compileMode - specify whether the engine compile() method is 'sync' or 'async'.Defaults to 'sync'.*/ + compileMode?: string; + /**context - a global context used with all templates.The global context option can be either an object or a function that takes no arguments and returns a context object.When rendering views, the global context will be merged with any context object specified on the handler or using reply.view().When multiple context objects are used, values from the global context always have lowest precedence.*/ + context?: any; + } + + export interface IServerViewsEnginesOptions extends IServerViewsAdditionalOptions { + /**- the npm module used for rendering the templates.The module object must contain: "module", the rendering function. The required function signature depends on the compileMode settings. + * If the compileMode is 'sync', the signature is compile(template, options), the return value is a function with signature function(context, options), and the method is allowed to throw errors.If the compileMode is 'async', the signature is compile(template, options, callback) where callback has the signature function(err, compiled) where compiled is a function with signature function(context, options, callback) and callback has the signature function(err, rendered).*/ + module: { + compile? (template: any, options: any): (context: any, options: any) => void; + compile? (template: any, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: any) => void) => void) => void): void; + }; + } + + /**Initializes the server views manager + var Hapi = require('hapi'); + var server = new Hapi.Server(); + + server.views({ + engines: { + html: require('handlebars'), + jade: require('jade') + }, + path: '/static/templates' + }); + When server.views() is called within a plugin, the views manager is only available to plugins methods. + */ + export interface IServerViewsConfiguration extends IServerViewsAdditionalOptions { + /** - required object where each key is a file extension (e.g. 'html', 'hbr'), mapped to the npm module used for rendering the templates.Alternatively, the extension can be mapped to an object with the following options:*/ + engines: IDictionary|IServerViewsEnginesOptions; + /** defines the default filename extension to append to template names when multiple engines are configured and not explicit extension is provided for a given template. No default value.*/ + defaultExtension?: string; + } + + /** Concludes the handler activity by setting a response and returning control over to the framework where: + erran optional error response. + resultan optional response payload. + Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. + FLOW CONTROL: + When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ + export interface IReply { + (err: Error, + result?: string|number|boolean|Buffer|stream.Stream | Promise | T, + /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ + credentialData?: any + ): IBoom; + /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ + (result: string|number|boolean|Buffer|stream.Stream | Promise | T): Response; + + /** Returns control back to the framework without setting a response. If called in the handler, the response defaults to an empty payload with status code 200. + * The data argument is only used for passing back authentication data and is ignored elsewhere. */ + continue(credentialData?: any): void; + + /** Transmits a file from the file system. The 'Content-Type' header defaults to the matching mime type based on filename extension. The response flow control rules do not apply. */ + file( + /** the file path. */ + path: string, + /** optional settings: */ + options?: { + /** - an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path*/ + filename?: string; + /** specifies whether to include the 'Content-Disposition' header with the response. Available values: + false - header is not included. This is the default value. + 'attachment' + 'inline'*/ + mode?: boolean|string; + /** if true, looks for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. */ + lookupCompressed: boolean; + }): void; + /** Concludes the handler activity by returning control over to the router with a templatized view response. + the response flow control rules apply. */ + + view( + /** the template filename and path, relative to the templates path configured via the server views manager. */ + template: string, + /** optional object used by the template to render context-specific result. Defaults to no context {}. */ + context?: {}, + /** optional object used to override the server's views manager configuration for this response. Cannot override isCached, partialsPath, or helpersPath which are only loaded at initialization. */ + options?: any): Response; + /** Concludes the handler activity by returning control over to the router and informing the router that a response has already been sent back directly via request.raw.res and that no further response action is needed + The response flow control rules do not apply. */ + close(options?: { + /** if false, the router will not call request.raw.res.end()) to ensure the response was ended. Defaults to true. */ + end?: boolean; + }): void; + /** Proxies the request to an upstream endpoint. + the response flow control rules do not apply. */ + + proxy(/** an object including the same keys and restrictions defined by the route proxy handler options. */ + options: IProxyHandlerConfig): void; + /** Redirects the client to the specified uri. Same as calling reply().redirect(uri). + he response flow control rules apply. */ + redirect(uri: string): Response; + } + + export interface ISessionHandler { + (request: Request, reply: IReply): void; + } + export interface IRequestHandler { + (request: Request): T; + } + + + export interface IFailAction { + (source: string, error: any, next: () => void): void + } + /** generates a reverse proxy handler */ + export interface IProxyHandlerConfig { + /** the upstream service host to proxy requests to. The same path on the client request will be used as the path on the host.*/ + host?: string; + /** the upstream service port. */ + port?: number; + /** The protocol to use when making a request to the proxied host: + 'http' + 'https'*/ + protocol?: string; + /** an absolute URI used instead of the incoming host, port, protocol, path, and query. Cannot be used with host, port, protocol, or mapUri.*/ + uri?: string; + /** if true, forwards the headers sent from the client to the upstream service being proxied to, headers sent from the upstream service will also be forwarded to the client. Defaults to false.*/ + passThrough?: boolean; + /** localStatePassThrough - if false, any locally defined state is removed from incoming requests before being passed upstream. This is a security feature to prevent local state (e.g. authentication cookies) from leaking upstream to other servers along with the cookies intended for those servers. This value can be overridden on a per state basis via the server.state() passThrough option. Defaults to false.*/ + localStatePassThrough?: boolean; + /**acceptEncoding - if false, does not pass-through the 'Accept-Encoding' HTTP header which is useful when using an onResponse post-processing to avoid receiving an encoded response (e.g. gzipped). Can only be used together with passThrough. Defaults to true (passing header).*/ + acceptEncoding?: boolean; + /** rejectUnauthorized - sets the rejectUnauthorized property on the https agent making the request. This value is only used when the proxied server uses TLS/SSL. When set it will override the node.js rejectUnauthorized property. If false then ssl errors will be ignored. When true the server certificate is verified and an 500 response will be sent when verification fails. This shouldn't be used alongside the agent setting as the agent will be used instead. Defaults to the https agent default value of true.*/ + rejectUnauthorized?: boolean; + /**if true, sets the 'X-Forwarded-For', 'X-Forwarded-Port', 'X-Forwarded-Proto' headers when making a request to the proxied upstream endpoint. Defaults to false.*/ + xforward?: boolean; + /** the maximum number of HTTP redirections allowed, to be followed automatically by the handler. Set to false or 0 to disable all redirections (the response will contain the redirection received from the upstream service). If redirections are enabled, no redirections (301, 302, 307, 308) will be passed along to the client, and reaching the maximum allowed redirections will return an error response. Defaults to false.*/ + redirects?: boolean|number; + /**number of milliseconds before aborting the upstream request. Defaults to 180000 (3 minutes).*/ + timeout?: number; + /** a function used to map the request URI to the proxied URI. Cannot be used together with host, port, protocol, or uri. The function signature is function(request, callback) where: + request - is the incoming request object. + callback - is function(err, uri, headers) where: + err - internal error condition. + uri - the absolute proxy URI. + headers - optional object where each key is an HTTP request header and the value is the header content.*/ + mapUri?: (request: Request, callback: (err: any, uri: string, headers?: { [key: string]: string }) => void) => void; + /** a custom function for processing the response from the upstream service before sending to the client. Useful for custom error handling of responses from the proxied endpoint or other payload manipulation. Function signature is function(err, res, request, reply, settings, ttl) where: - err - internal or upstream error returned from attempting to contact the upstream proxy. - res - the node response object received from the upstream service. res is a readable stream (use the wreck module read method to easily convert it to a Buffer or string). - request - is the incoming request object. - reply - the reply interface function. - settings - the proxy handler configuration. - ttl - the upstream TTL in milliseconds if proxy.ttl it set to 'upstream' and the upstream response included a valid 'Cache-Control' header with 'max-age'.*/ + onResponse?: ( + err: any, + res: http.ServerResponse, + req: Request, + reply: () => void, + settings: IProxyHandlerConfig, + ttl: number + ) => void; + /** if set to 'upstream', applies the upstream response caching policy to the response using the response.ttl() method (or passed as an argument to the onResponse method if provided).*/ + ttl?: number; + /** - a node http(s) agent to be used for connections to upstream server. see https://nodejs.org/api/http.html#http_class_http_agent */ + agent?: http.Agent; + /** sets the maximum number of sockets available per outgoing proxy host connection. false means use the wreck module default value (Infinity). Does not affect non-proxy outgoing client connections. Defaults to Infinity.*/ + maxSockets?: boolean|number; + } + /** TODO: fill in joi definition */ + export interface IJoi { + + } + /** a validation function using the signature function(value, options, next) */ + export interface IValidationFunction { + + (/** the object containing the path parameters. */ + value: any, + /** the server validation options. */ + options: any, + /** the callback function called when validation is completed. */ + next: (err: any, value: any) => void): void; + } + /** a custom error handler function with the signature 'function(request, reply, source, error)` */ + export interface IRouteFailFunction { + /** a custom error handler function with the signature 'function(request, reply, source, error)` */ + ( + /** - the [request object]. */ + request: Request, + /** the continuation reply interface. */ + reply: IReply, + /** the source of the invalid field (e.g. 'path', 'query', 'payload'). */ + source: string, + /** the error object prepared for the client response (including the validation function error under error.data). */ + error: any): void; + } + + /** Each route can be customize to change the default behavior of the request lifecycle using the following options: */ + export interface IRouteAdditionalConfigurationOptions { + /** application specific configuration.Should not be used by plugins which should use plugins[name] instead. */ + app?: any; + /** authentication configuration.Value can be: false to disable authentication if a default strategy is set. + a string with the name of an authentication strategy registered with server.auth.strategy(). + an object */ + auth?: boolean|string| + { + /** the authentication mode.Defaults to 'required' if a server authentication strategy is configured, otherwise defaults to no authentication.Available values: + 'required'authentication is required. + 'optional'authentication is optional (must be valid if present). + 'try'same as 'optional' but allows for invalid authentication. */ + mode: string; + /** a string array of strategy names in order they should be attempted.If only one strategy is used, strategy can be used instead with the single string value.Defaults to the default authentication strategy which is available only when a single strategy is configured. */ + strategies: string | Array; + /** if set, the payload (in requests other than 'GET' and 'HEAD') is authenticated after it is processed.Requires a strategy with payload authentication support (e.g.Hawk).Cannot be set to a value other than 'required' when the scheme sets the options.payload to true.Available values: + falseno payload authentication.This is the default value. + 'required'payload authentication required.This is the default value when the scheme sets options.payload to true. + 'optional'payload authentication performed only when the client includes payload authentication information (e.g.hash attribute in Hawk). */ + payload?: string; + /** the application scope required to access the route.Value can be a scope string or an array of scope strings.The authenticated credentials object scope property must contain at least one of the scopes defined to access the route.Set to false to remove scope requirements.Defaults to no scope required. */ + scope?: string|Array|boolean; + /** the required authenticated entity type.If set, must match the entity value of the authentication credentials.Available values: + anythe authentication can be on behalf of a user or application.This is the default value. + userthe authentication must be on behalf of a user. + appthe authentication must be on behalf of an application. */ + entity?: string; + }; + /** an object passed back to the provided handler (via this) when called. */ + bind?: any; + /** if the route method is 'GET', the route can be configured to include caching directives in the response using the following options */ + cache?: { + /** mines the privacy flag included in clientside caching using the 'Cache-Control' header.Values are: + fault'no privacy flag.This is the default setting. + 'public'mark the response as suitable for public caching. + 'private'mark the response as suitable only for private caching. */ + privacy: string; + /** relative expiration expressed in the number of milliseconds since the item was saved in the cache.Cannot be used together with expiresAt. */ + expiresIn: number; + /** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire.Cannot be used together with expiresIn. */ + expiresAt: string; + }; + /** the Cross- Origin Resource Sharing protocol allows browsers to make cross- origin API calls.CORS is required by web applications running inside a browser which are loaded from a different domain than the API server.CORS headers are disabled by default. To enable, set cors to true, or to an object with the following options: */ + cors?: { + /** a strings array of allowed origin servers ('Access-Control-Allow-Origin').The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '' character, or a single `''origin string. Defaults to any origin['*']`. */ + origin?: Array; + /** if true, matches the value of the incoming 'Origin' header to the list of origin values ('*' matches anything) and if a match is found, uses that as the value of the 'Access-Control-Allow-Origin' response header.When false, the origin config is returned as- is.Defaults to true. */ + matchOrigin?: boolean; + /** if false, prevents the connection from returning the full list of non- wildcard origin values if the incoming origin header does not match any of the values.Has no impact if matchOrigin is set to false.Defaults to true. */ + isOriginExposed?: boolean; + /** number of seconds the browser should cache the CORS response ('Access-Control-Max-Age').The greater the value, the longer it will take before the browser checks for changes in policy.Defaults to 86400 (one day). */ + maxAge?: number; + /** a strings array of allowed headers ('Access-Control-Allow-Headers').Defaults to ['Authorization', 'Content-Type', 'If-None-Match']. */ + headers?: string[]; + /** a strings array of additional headers to headers.Use this to keep the default headers in place. */ + additionalHeaders?: string[]; + /** a strings array of allowed HTTP methods ('Access-Control-Allow-Methods').Defaults to ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'OPTIONS']. */ + methods?: string[]; + /** a strings array of additional methods to methods.Use this to keep the default methods in place. */ + additionalMethods?: string[]; + /** a strings array of exposed headers ('Access-Control-Expose-Headers').Defaults to ['WWW-Authenticate', 'Server-Authorization']. */ + exposedHeaders?: string[]; + /** a strings array of additional headers to exposedHeaders.Use this to keep the default headers in place. */ + additionalExposedHeaders?: string[]; + /** if true, allows user credentials to be sent ('Access-Control-Allow-Credentials').Defaults to false. */ + credentials?: boolean; + /** if false, preserves existing CORS headers set manually before the response is sent.Defaults to true. */ + override?: boolean; + }; + /** defines the behavior for serving static resources using the built-in route handlers for files and directories: */ + files?: {/** determines the folder relative paths are resolved against when using the file and directory handlers. */ + relativeTo: string; + }; + + /** an alternative location for the route handler option. */ + handler?: ISessionHandler | string | IRouteHandlerConfig; + /** an optional unique identifier used to look up the route using server.lookup(). */ + id?: number; + /** optional arguments passed to JSON.stringify() when converting an object or error response to a string payload.Supports the following: */ + json?: { + /** the replacer function or array.Defaults to no action. */ + replacer?: Function | string[]; + /** number of spaces to indent nested object keys.Defaults to no indentation. */ + space?: number|string; + /** string suffix added after conversion to JSON string.Defaults to no suffix. */ + suffix?: string; + }; + /** enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload.For example, if the value is 'callback', a request comes in with 'callback=me', and the JSON response is '{ "a":"b" }', the payload will be 'me({ "a":"b" });'.Does not work with stream responses. */ + jsonp?: string; + /** determines how the request payload is processed: */ + payload?: { + /** the type of payload representation requested. The value must be one of: + 'data'the incoming payload is read fully into memory.If parse is true, the payload is parsed (JSON, formdecoded, multipart) based on the 'Content- Type' header.If parse is false, the raw Buffer is returned.This is the default value except when a proxy handler is used. + 'stream'the incoming payload is made available via a Stream.Readable interface.If the payload is 'multipart/form-data' and parse is true, fields values are presented as text while files are provided as streams.File streams from a 'multipart/form-data' upload will also have a property hapi containing filename and headers properties. + 'file'the incoming payload in written to temporary file in the directory specified by the server's payload.uploads settings. If the payload is 'multipart/ formdata' and parse is true, fields values are presented as text while files are saved. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform any needed cleaup. */ + output?: string; + /** can be true, false, or gunzip; determines if the incoming payload is processed or presented raw. true and gunzip includes gunzipping when the appropriate 'Content-Encoding' is specified on the received request. If parsing is enabled and the 'Content-Type' is known (for the whole payload as well as parts), the payload is converted into an object when possible. If the format is unknown, a Bad Request (400) error response is sent. Defaults to true, except when a proxy handler is used. The supported mime types are: + 'application/json' + 'application/x-www-form-urlencoded' + 'application/octet-stream' + 'text/ *' + 'multipart/form-data' */ + parse?: string | boolean; + /** a string or an array of strings with the allowed mime types for the endpoint.Defaults to any of the supported mime types listed above.Note that allowing other mime types not listed will not enable them to be parsed, and that if parsing mode is 'parse', the request will result in an error response. */ + allow?: string | string[]; + /** a mime type string overriding the 'Content-Type' header value received.Defaults to no override. */ + override?: string; + /** limits the size of incoming payloads to the specified byte count.Allowing very large payloads may cause the server to run out of memory.Defaults to 1048576 (1MB). */ + maxBytes?: number; + /** payload reception timeout in milliseconds.Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) error response.Set to false to disable.Defaults to 10000 (10 seconds). */ + timeout?: number; + /** the directory used for writing file uploads.Defaults to os.tmpDir(). */ + uploads?: string; + /** determines how to handle payload parsing errors. Allowed values are: + 'error'return a Bad Request (400) error response. This is the default value. + 'log'report the error but continue processing the request. + 'ignore'take no action and continue processing the request. */ + failAction?: string; + }; + /** pluginspecific configuration.plugins is an object where each key is a plugin name and the value is the plugin configuration. */ + plugins?: IDictionary; + /** an array with [route prerequisites] methods which are executed in serial or in parallel before the handler is called. */ + pre?: any[]; + /** validation rules for the outgoing response payload (response body).Can only validate object response: */ + response?: { + /** the default response object validation rules (for all non-error responses) expressed as one of: + trueany payload allowed (no validation performed). This is the default. + falseno payload allowed. + a Joi validation object. + a validation function using the signature function(value, options, next) where: + valuethe object containing the response object. + optionsthe server validation options. + next(err)the callback function called when validation is completed. */ + schema: boolean|any; + /** HTTP status- codespecific validation rules.The status key is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema.If a response status code is not present in the status object, the schema definition is used, expect for errors which are not validated by default. */ + status: number; + /** the percent of responses validated (0100).Set to 0 to disable all validation.Defaults to 100 (all responses). */ + sample: number; + /** defines what to do when a response fails validation.Options are: + errorreturn an Internal Server Error (500) error response.This is the default value. + loglog the error but send the response. */ + failAction: string; + /** if true, applies the validation rule changes to the response.Defaults to false. */ + modify: boolean; + /** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */ + options: any; + }; + /** sets common security headers (disabled by default).To enable set security to true or to an object with the following options */ + security?: boolean| { + /** controls the 'Strict-Transport-Security' header.If set to true the header will be set to max- age=15768000, if specified as a number the maxAge parameter will be set to that number.Defaults to true.You may also specify an object with the following fields: */ + hsts: boolean|number|{ + /** the max- age portion of the header, as a number.Default is 15768000. */ + maxAge?: number; + /** a boolean specifying whether to add the includeSubdomains flag to the header. */ + includeSubdomains?: boolean; + }; + /** controls the 'X-Frame-Options' header.When set to true the header will be set to DENY, you may also specify a string value of 'deny' or 'sameorigin'.To use the 'allow-from' rule, you must set this to an object with the following fields: */ + xframe: { + /** either 'deny', 'sameorigin', or 'allow-from' */ + rule: string; + /** when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored.If rule is 'allow-from' but source is unset, the rule will be automatically changed to 'sameorigin'. */ + source: string; + }; + /** boolean that controls the 'X-XSS-PROTECTION' header for IE.Defaults to true which sets the header to equal '1; mode=block'.NOTE: This setting can create a security vulnerability in versions of IE below 8, as well as unpatched versions of IE8.See here and here for more information.If you actively support old versions of IE, it may be wise to explicitly set this flag to false. */ + xss: boolean; + /** boolean controlling the 'X-Download-Options' header for IE, preventing downloads from executing in your context.Defaults to true setting the header to 'noopen'. */ + noOpen: boolean; + /** boolean controlling the 'X-Content-Type-Options' header.Defaults to true setting the header to its only and default option, 'nosniff'. */ + noSniff: boolean; + }; + /** HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265).state supports the following options: */ + state?: { + /** determines if incoming 'Cookie' headers are parsed and stored in the request.state object.Defaults to true. */ + parse: boolean; + /** determines how to handle cookie parsing errors.Allowed values are: + 'error'return a Bad Request (400) error response.This is the default value. + 'log'report the error but continue processing the request. + 'ignore'take no action. */ + failAction: string; + }; + /** request input validation rules for various request components.When using a Joi validation object, the values of the other inputs (i.e.headers, query, params, payload, and auth) are made available under the validation context (accessible in rules as Joi.ref('$query.key')).Note that validation is performed in order(i.e.headers, params, query, payload) and if type casting is used (converting a string to number), the value of inputs not yet validated will reflect the raw, unvalidated and unmodified values.The validate object supports: */ + validate?: { + /** validation rules for incoming request headers.Values allowed: + * trueany headers allowed (no validation performed).This is the default. + falseno headers allowed (this will cause all valid HTTP requests to fail). + a Joi validation object. + a validation function using the signature function(value, options, next) where: + valuethe object containing the request headers. + optionsthe server validation options. + next(err, value)the callback function called when validation is completed. + */ + headers?: boolean | IJoi | IValidationFunction; + + + /** validation rules for incoming request path parameters, after matching the path against the route and extracting any parameters then stored in request.params.Values allowed: + trueany path parameters allowed (no validation performed).This is the default. + falseno path variables allowed. + a Joi validation object. + a validation function using the signature function(value, options, next) where: + valuethe object containing the path parameters. + optionsthe server validation options. + next(err, value)the callback function called when validation is completed. */ + params?: boolean | IJoi | IValidationFunction; + /** validation rules for an incoming request URI query component (the key- value part of the URI between '?' and '#').The query is parsed into its individual key- value pairs (using the qs module) and stored in request.query prior to validation.Values allowed: + trueany query parameters allowed (no validation performed).This is the default. + falseno query parameters allowed. + a Joi validation object. + a validation function using the signature function(value, options, next) where: + valuethe object containing the query parameters. + optionsthe server validation options. + next(err, value)the callback function called when validation is completed. */ + query?: boolean | IJoi | IValidationFunction; + /** validation rules for an incoming request payload (request body).Values allowed: + trueany payload allowed (no validation performed).This is the default. + falseno payload allowed. + a Joi validation object. + a validation function using the signature function(value, options, next) where: + valuethe object containing the payload object. + optionsthe server validation options. + next(err, value)the callback function called when validation is completed. */ + payload?: boolean | IJoi | IValidationFunction; + /** an optional object with error fields copied into every validation error response. */ + errorFields?: any; + /** determines how to handle invalid requests.Allowed values are: + 'error'return a Bad Request (400) error response.This is the default value. + 'log'log the error but continue processing the request. + 'ignore'take no action. + OR a custom error handler function with the signature 'function(request, reply, source, error)` where: + requestthe request object. + replythe continuation reply interface. + sourcethe source of the invalid field (e.g. 'path', 'query', 'payload'). + errorthe error object prepared for the client response (including the validation function error under error.data). */ + failAction?: string | IRouteFailFunction; + /** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */ + options?: any; + }; + /** define timeouts for processing durations: */ + timeout?: { + /** response timeout in milliseconds.Sets the maximum time allowed for the server to respond to an incoming client request before giving up and responding with a Service Unavailable (503) error response.Disabled by default (false). */ + server: boolean|number; + /** by default, node sockets automatically timeout after 2 minutes.Use this option to override this behavior.Defaults to undefined which leaves the node default unchanged.Set to false to disable socket timeouts. */ + socket: boolean|number; + }; + + /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). + *route description used for generating documentation (string). + */ + description?: string; + /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). + *route notes used for generating documentation (string or array of strings). + */ + notes?: string|string[]; + /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). + *route tags used for generating documentation (array of strings). + */ + tags?: string[] + } + /** server.realm http://hapijs.com/api#serverrealm + The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), + the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). + Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. + The server.realm object should be considered read-only and must not be changed directly except for the plugins property can be directly manipulated by the plugins (each setting its own under plugins[name]). + exports.register = function (server, options, next) { + console.log(server.realm.modifiers.route.prefix); + return next(); + }; + */ + export interface IServerRealm { + /** when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method */ + modifiers: { + /** routes preferences: */ + route: { + /** - the route path prefix used by any calls to server.route() from the server. */ + prefix: string; + /** the route virtual host settings used by any calls to server.route() from the server. */ + vhost: string; + }; + + }; + /** the active plugin name (empty string if at the server root). */ + plugin: string; + /** plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. */ + plugins: IDictionary; + /** settings overrides */ + settings: { + files: { + relativeTo: any; + }; + bind: any; + } + } + /** server.state(name, [options]) http://hapijs.com/api#serverstatename-options + HTTP state management uses client cookies to persist a state across multiple requests. Registers a cookie definitions where:*/ + export interface IServerState { +/** - the cookie name string. */name: string; + +/** - are the optional cookie settings: */options: { +/** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/ttl: number; +/** - sets the 'Secure' flag.Defaults to false.*/isSecure: boolean; +/** - sets the 'HttpOnly' flag.Defaults to false.*/isHttpOnly: boolean +/** - the path scope.Defaults to null (no path).*/path: any; +/** - the domain scope.Defaults to null (no domain). */domain: any; + /** if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value. The value can be a function with signature function(request, next) where: + request - the request object. + next - the continuation function using the function(err, value) signature.*/ + autoValue: (request: Request, next: (err: any, value: any) => void) => void; + /** - encoding performs on the provided value before serialization. Options are: + 'none' - no encoding. When used, the cookie value must be a string. This is the default value. + 'base64' - string value is encoded using Base64. + 'base64json' - object value is JSON-stringified than encoded using Base64. + 'form' - object value is encoded using the x-www-form-urlencoded method. + 'iron' - Encrypts and sign the value using iron.*/ + encoding: string; +/** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are:*/sign: { +/** - algorithm options.Defaults to require('iron').defaults.integrity.*/integrity: any; +/** - password used for HMAC key generation.*/password: string; + }; +/** - password used for 'iron' encoding.*/password: string; +/** - options for 'iron' encoding.Defaults to require('iron').defaults.*/iron: any; +/** - if false, errors are ignored and treated as missing cookies.*/ignoreErrors: boolean; +/** - if true, automatically instruct the client to remove invalid cookies.Defaults to false.*/clearInvalid: boolean; +/** - if false, allows any cookie value including values in violation of RFC 6265. Defaults to true.*/strictHeader: boolean; +/** - overrides the default proxy localStatePassThrough setting.*/passThrough: any; + }; + } + + export interface IFileHandlerConfig { + /** a path string or function as described above.*/ + path: string; + /** an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path*/ + filename?: string; + /**- specifies whether to include the 'Content-Disposition' header with the response. Available values: + false - header is not included. This is the default value. + 'attachment' + 'inline'*/ + mode?: boolean| string; + /** if true, looks for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false.*/ + lookupCompressed: boolean; + } + + /**http://hapijs.com/api#route-handler + Built-in handlers + + The framework comes with a few built-in handler types available by setting the route handler config to an object containing one of these keys.*/ + export interface IRouteHandlerConfig { + /** generates a static file endpoint for serving a single file. file can be set to: + a relative or absolute file path string (relative paths are resolved based on the route files configuration). + a function with the signature function(request) which returns the relative or absolute file path. + an object with the following options */ + file?: string | IRequestHandler |IFileHandlerConfig; + /** directory - generates a directory endpoint for serving static content from a directory. Routes using the directory handler must include a path parameter at the end of the path string (e.g. /path/to/somewhere/{param} where the parameter name does not matter). The path parameter can use any of the parameter options (e.g. {param} for one level files only, {param?} for one level files or the directory root, {param*} for any level, or {param*3} for a specific level). If additional path parameters are present, they are ignored for the purpose of selecting the file system resource. The directory handler is an object with the following options: + path - (required) the directory root path (relative paths are resolved based on the route files configuration). Value can be: + a single path string used as the prefix for any resources requested by appending the request path parameter to the provided string. + an array of path strings. Each path will be attempted in order until a match is found (by following the same process as the single path string). + a function with the signature function(request) which returns the path string or an array of path strings. If the function returns an error, the error is passed back to the client in the response. + index - optional boolean|string|string[], determines if an index file will be served if found in the folder when requesting a directory. The given string or strings specify the name(s) of the index file to look for. If true, looks for 'index.html'. Any falsy value disables index file lookup. Defaults to true. + listing - optional boolean, determines if directory listing is generated when a directory is requested without an index document. Defaults to false. + showHidden - optional boolean, determines if hidden files will be shown and served. Defaults to false. + redirectToSlash - optional boolean, determines if requests for a directory without a trailing slash are redirected to the same path with the missing slash. Useful for ensuring relative links inside the response are resolved correctly. Disabled when the server config router.stripTrailingSlash is true.Defaults to false. + lookupCompressed - optional boolean, instructs the file processor to look for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. + defaultExtension - optional string, appended to file requests if the requested file is not found. Defaults to no extension.*/ + directory?: { + path: string |Array | IRequestHandler | IRequestHandler>; + index?: boolean; + listing?: boolean; + showHidden?: boolean; + redirectToSlash?: boolean; + lookupCompressed?: boolean; + defaultExtension?: string; + }; + proxy?: IProxyHandlerConfig; + view?: string | { + template: string; + context: { + payload: any; + params: any; + query: any; + pre: any; + } + }; + config?: { + handler: any; + bind: any; + app: any; + plugins: { + [name: string]: any; + }; + pre: Array<() => void>; + validate: { + headers: any; + params: any; + query: any; + payload: any; + errorFields?: any; + failAction?: string | IFailAction; + }; + payload: { + output: { + data: any; + stream: any; + file: any; + }; + parse?: any; + allow?: string|Array; + override?: string; + maxBytes?: number; + uploads?: number; + failAction?: string; + }; + response: { + schema: any; + sample: number; + failAction: string; + }; + cache: { + privacy: string; + expiresIn: number; + expiresAt: number; + }; + auth: string|boolean|{ + mode: string; + strategies: Array; + payload?: boolean|string; + tos?: boolean|string; + scope?: string|Array; + entity: string; + }; + cors?: boolean; + jsonp?: string; + description?: string; + notes?: string|Array; + tags?: Array; + }; + } + /** Route configuration + The route configuration object*/ + export interface IRouteConfiguration { + /** - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the connection router configuration option.The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters.*/ + path: string; + /** - (required) the HTTP method.Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'.Any HTTP method is allowed, except for 'HEAD'.Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). + * Can be assigned an array of methods which has the same result as adding the same route with different methods manually.*/ + method: string|string[]; + /** - an optional domain string or an array of domain strings for limiting the route to only requests with a matching host header field.Matching is done against the hostname part of the header only (excluding the port).Defaults to all hosts.*/ + vhost?: string; + /** - (required) the function called to generate the response after successful authentication and validation.The handler function is described in Route handler.If set to a string, the value is parsed the same way a prerequisite server method string shortcut is processed.Alternatively, handler can be assigned an object with a single key using the name of a registered handler type and value with the options passed to the registered handler.*/ + handler: ISessionHandler | string | IRouteHandlerConfig; + /** - additional route options.*/ + config?: IRouteAdditionalConfigurationOptions; + } + /** Route public interface When route information is returned or made available as a property. http://hapijs.com/api#route-public-interface */ + export interface IRoute { + + + /** the route HTTP method. */ + method: string; + /** the route path. */ + path: string; + /** the route vhost option if configured. */ + vhost?: string|Array; + /** the [active realm] associated with the route.*/ + realm: IServerRealm; + /** the [route options] object with all defaults applied. */ + settings: IRouteAdditionalConfigurationOptions; + } + + export interface IServerAuthScheme { + /** authenticate(request, reply) - required function called on each incoming request configured with the authentication scheme where: + request - the request object. + reply - the reply interface the authentication method must call when done authenticating the request where: + reply(err, response, result) - is called if authentication failed where: + err - any authentication error. + response - any authentication response action such as redirection. Ignored if err is present, otherwise required. + result - an object containing: + credentials - the authenticated credentials. + artifacts - optional authentication artifacts. + reply.continue(result) - is called if authentication succeeded where: + result - same object as result above. + When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route. + .If the err returned by the reply() method includes a message, no additional strategies will be attempted. + If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + var scheme = function (server, options) { + return { + authenticate: function (request, reply) { + var req = request.raw.req; + var authorization = req.headers.authorization; + if (!authorization) { + return reply(Boom.unauthorized(null, 'Custom')); + } + return reply(null, { credentials: { user: 'john' } }); + } + }; + }; + server.auth.scheme('custom', scheme);*/ + authenticate(request: Request, reply: IReply): void; + /** payload(request, reply) - optional function called to authenticate the request payload where: + request - the request object. + reply(err, response) - is called if authentication failed where: + err - any authentication error. + response - any authentication response action such as redirection. Ignored if err is present, otherwise required. + reply.continue() - is called if payload authentication succeeded. + When the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'.*/ + payload? (request: Request, reply: IReply): void; + /** response(request, reply) - optional function called to decorate the response with authentication headers before the response headers or payload is written where: + request - the request object. + reply(err, response) - is called if an error occurred where: + err - any authentication error. + response - any authentication response to send instead of the current response. Ignored if err is present, otherwise required. + reply.continue() - is called if the operation succeeded.*/ + response? (request: Request, reply: IReply): void; + /** an optional object */ + options?: { + /** if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false.*/ + payload: boolean; + } + } + + + + export interface IServerInject { + (options: { + /** the request HTTP method (e.g. 'POST'). Defaults to 'GET'.*/ + method: string; + /** the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers.*/ + url: string; + /** an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default Shot headers.*/ + headers: IDictionary; + /**- an optional string or buffer containing the request payload (object must be manually converted to a string first). Defaults to no payload. Note that payload processing defaults to 'application/json' if no 'Content-Type' header provided.*/ + payload: string|Buffer; + /**an optional credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Defaults to no credentials.*/ + credentials: any; + /**object with options used to simulate client request stream conditions for testing: + error - if true, emits an 'error' event after payload transmission (if any). Defaults to false. + close - if true, emits a 'close' event after payload transmission (if any). Defaults to false. + end - if false, does not end the stream. Defaults to true.*/ + simulate: { + error: boolean; + close: boolean; + end: boolean; + }; + }, + callback: ( + /**the response object where: + statusCode - the HTTP status code. + headers - an object containing the headers set. + payload - the response payload string. + rawPayload - the raw response payload buffer. + raw - an object with the injection request and response objects: + req - the simulated node request object. + res - the simulated node response object. + result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string). + request - the request object.*/ + res: { statusCode: number; headers: IDictionary; payload: string; rawPayload: Buffer; raw: { req: http.ClientRequest; res: http.ServerResponse }; result: string; request: Request }) => void + ):void; + + } + + + /** host - optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts. + The return value is an array where each item is an object containing: + info - the connection.info the connection the table was generated for. + labels - the connection labels. + table - an array of routes where each route contains: + settings - the route config with defaults applied. + method - the HTTP method in lower case. + path - the route path.*/ + export interface IConnectionTable { + info: any; + labels: any; + table: IRoute[]; + } + + export interface ICookieSettings { + /** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/ + ttl?: number; + /** - sets the 'Secure' flag.Defaults to false.*/ + isSecure?: boolean; + /** - sets the 'HttpOnly' flag.Defaults to false.*/ + isHttpOnly?: boolean; + /** - the path scope.Defaults to null (no path).*/ + path?: string; + /** - the domain scope.Defaults to null (no domain).*/ + domain?: any; + /** - if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value.The value can be a function with signature function(request, next) where: + request - the request object. + next - the continuation function using the function(err, value) signature.*/ + autoValue?: (request: Request, next: (err: any, value: any) => void) => void; + /** - encoding performs on the provided value before serialization.Options are: + 'none' - no encoding.When used, the cookie value must be a string.This is the default value. + 'base64' - string value is encoded using Base64. + 'base64json' - object value is JSON- stringified than encoded using Base64. + 'form' - object value is encoded using the x- www - form - urlencoded method. */ + encoding?: string; + /** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are: + integrity - algorithm options.Defaults to require('iron').defaults.integrity. + password - password used for HMAC key generation. */ + sign?: { integrity: any; password: string; } + password?: string; + iron?: any; + ignoreErrors?: boolean; + clearInvalid?: boolean; + strictHeader?: boolean; + passThrough?: any; + } + + /** method - the method function with the signature is one of: + function(arg1, arg2, ..., argn, next) where: + arg1, arg2, etc. - the method function arguments. + next - the function called when the method is done with the signature function(err, result, ttl) where: + err - error response if the method failed. + result - the return value. + ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. + function(arg1, arg2, ..., argn) where: + arg1, arg2, etc. - the method function arguments. + the callback option is set to false. + the method must returns a value (result, Error, or a promise) or throw an Error.*/ + export interface IServerMethod { + //(): void; + //(next: (err: any, result: any, ttl: number) => void): void; + //(arg1: any): void; + //(arg1: any, arg2: any, next: (err: any, result: any, ttl: number) => void): void; + //(arg1: any, arg2: any): void; + (...args: any[]): void; + + } + /** options - optional configuration: + bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. + cache - the same cache configuration used in server.cache(). + callback - if false, expects the method to be a synchronous function. Note that using a synchronous function with caching will convert the method interface to require a callback as an additional argument with the signature function(err, result, cached, report) since the cache interface cannot return values synchronously. Defaults to true. + generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the callback argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated).*/ + export interface IServerMethodOptions { + bind?: any; + cache?: ICatBoxCacheOptions; + callback?: boolean; + generateKey?(args: any[]): string; + } + /** Request object + + The request object is created internally for each incoming request. It is different from the node.js request object received from the HTTP server callback (which is available in request.raw.req). The request object methods and properties change throughout the request lifecycle. + Request events + + The request object supports the following events: + + 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + 'finish' - emitted when the request payload finished reading. The event method signature is function (). + 'disconnect' - emitted when a request errors or aborts unexpectedly. + var Crypto = require('crypto'); + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.ext('onRequest', function (request, reply) { + + var hash = Crypto.createHash('sha1'); + request.on('peek', function (chunk) { + + hash.update(chunk); + }); + + request.once('finish', function () { + + console.log(hash.digest('hex')); + }); + + request.once('disconnect', function () { + + console.error('request aborted'); + }); + + return reply.continue(); + });*/ + export class Request extends Events.EventEmitter { + /** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].*/ + app: any; + /** authentication information*/ + auth: { + /** true is the request has been successfully authenticated, otherwise false.*/ + isAuthenticated: boolean; + /** the credential object received during the authentication process. The presence of an object does not mean successful authentication.*/ + credentials: any; + /** an artifact object received from the authentication strategy and used in authentication-related actions.*/ + artifacts: any; + /** the route authentication mode.*/ + mode: any; + /** the authentication error is failed and mode set to 'try'.*/ + error: any; + /** an object used by the ['cookie' authentication scheme] https://github.com/hapijs/hapi-auth-cookie */ + session: any + }; + /** the node domain object used to protect against exceptions thrown in extensions, handlers and route prerequisites. Can be used to manually bind callback functions otherwise bound to other domains.*/ + domain: any; + /** the raw request headers (references request.raw.headers).*/ + headers: IDictionary; + /** a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}').*/ + id: number; + /** request information */ + info: { + /** request reception timestamp. */ + received: number; + /** request response timestamp (0 is not responded yet). */ + responded: number; + /** remote client IP address. */ + + remoteAddress: string; + /** remote client port. */ + remotePort: number; + /** content of the HTTP 'Referrer' (or 'Referer') header. */ + referrer: string; + /** content of the HTTP 'Host' header (e.g. 'example.com:8080'). */ + host: string; + /** the hostname part of the 'Host' header (e.g. 'example.com').*/ + hostname: string; + }; + /** the request method in lower case (e.g. 'get', 'post'). */ + method: string; + /** the parsed content-type header. Only available when payload parsing enabled and no payload error occurred. */ + mime: string; + /** an object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed.*/ + orig: { + params: any; + query: any; + payload: any; + }; + /** an object where each key is a path parameter name with matching value as described in Path parameters.*/ + params: IDictionary; + /** an array containing all the path params values in the order they appeared in the path.*/ + paramsArray: string[]; + /** the request URI's path component. */ + path: string; + /** the request payload based on the route payload.output and payload.parse settings.*/ + payload: any; + /** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state.*/ + plugins: any; + /** an object where each key is the name assigned by a route prerequisites function. The values are the raw values provided to the continuation function as argument. For the wrapped response object, use responses.*/ + pre: IDictionary; + /** the response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to override with a different response. Contains null when no response has been set (e.g. when a request terminates prematurely when the client disconnects).*/ + response: Response; + /**preResponses - same as pre but represented as the response object created by the pre method.*/ + preResponses: any; + /**an object containing the query parameters.*/ + query: any; + /** an object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended.*/ + raw: { + req: http.ClientRequest; + res: http.ServerResponse; + }; + /** the route public interface.*/ + route: IRoute; + /** the server object. */ + server: Server; + /** Special key reserved for plugins implementing session support. Plugins utilizing this key must check for null value to ensure there is no conflict with another similar server. */ + session: any; + /** an object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. */ + state: any; + /** complex object contining details on the url */ + url: { + /** null when i tested */ + auth: any; + /** null when i tested */ + hash: any; + /** null when i tested */ + host: any; + /** null when i tested */ + hostname: any; + href: string; + path: string; + /** path without search*/ + pathname: string; + /** null when i tested */ + port: any; + /** null when i tested */ + protocol: any; + /** querystring parameters*/ + query: IDictionary; + /** querystring parameters as a string*/ + search: string; + /** null when i tested */ + slashes: any; + }; + /** request.setUrl(url) + + Available only in 'onRequest' extension methods. + + Changes the request URI before the router begins processing the request where: + + url - the new request path value. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.ext('onRequest', function (request, reply) { + + // Change all requests to '/test' + request.setUrl('/test'); + return reply.continue(); + });*/ + setUrl(url: string): void; + /** request.setMethod(method) + + Available only in 'onRequest' extension methods. + + Changes the request method before the router begins processing the request where: + + method - is the request HTTP method (e.g. 'GET'). + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.ext('onRequest', function (request, reply) { + + // Change all requests to 'GET' + request.setMethod('GET'); + return reply.continue(); + });*/ + setMethod(method: string): void; + /** request.log(tags, [data, [timestamp]]) + + Always available. + + Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are: + + data - an optional message string or object with the application data being logged. + timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). + Any logs generated by the server internally will be emitted only on the 'request-internal' channel and will include the event.internal flag set to true. + + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.on('request', function (request, event, tags) { + + if (tags.error) { + console.log(event); + } + }); + + var handler = function (request, reply) { + + request.log(['test', 'error'], 'Test event'); + return reply(); + }; + */ + log( + /** a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events.*/ + tags: string|string[], + /** an optional message string or object with the application data being logged.*/ + data?: string, + /** an optional timestamp expressed in milliseconds. Defaults to Date.now() (now).*/ + timestamp?: number): void; + /** request.getLog([tags], [internal]) + + Always available. + + Returns an array containing the events matching any of the tags specified (logical OR) + request.getLog(); + request.getLog('error'); + request.getLog(['error', 'auth']); + request.getLog(['error'], true); + request.getLog(false);*/ + + getLog( + /** is a single tag string or array of tag strings. If no tags specified, returns all events.*/ + tags?: string, + /** filters the events to only those with a matching event.internal value. If true, only internal logs are included. If false, only user event are included. Defaults to all events (undefined).*/ + internal?: boolean): string[]; + + /** request.tail([name]) + + Available until immediately after the 'response' event is emitted. + + Adds a request tail which has to complete before the request lifecycle is complete where: + + name - an optional tail name used for logging purposes. + Returns a tail function which must be called when the tail activity is completed. + + Tails are actions performed throughout the request lifecycle, but which may end after a response is sent back to the client. For example, a request may trigger a database update which should not delay sending back a response. However, it is still desirable to associate the activity with the request when logging it (or an error associated with it). + + When all tails completed, the server emits a 'tail' event. + + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + var get = function (request, reply) { + + var dbTail = request.tail('write to database'); + + db.save('key', 'value', function () { + + dbTail(); + }); + + return reply('Success!'); + }; + + server.route({ method: 'GET', path: '/', handler: get }); + + server.on('tail', function (request) { + + console.log('Request completed including db activity'); + });*/ + tail( + /** an optional tail name used for logging purposes.*/ + name?: string): Function; + } + /** Response events + + The response object supports the following events: + + 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + var Crypto = require('crypto'); + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.ext('onPreResponse', function (request, reply) { + + var response = request.response; + if (response.isBoom) { + return reply(); + } + + var hash = Crypto.createHash('sha1'); + response.on('peek', function (chunk) { + + hash.update(chunk); + }); + + response.once('finish', function () { + + console.log(hash.digest('hex')); + }); + + return reply.continue(); + });*/ + export class Response extends Events.EventEmitter { + /** the HTTP response status code. Defaults to 200 (except for errors).*/ + statusCode: number; + /** an object containing the response headers where each key is a header field name. Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepare for transmission.*/ + headers: IDictionary; + /** the value provided using the reply interface.*/ + source: any; + /** a string indicating the type of source with available values: + 'plain' - a plain response such as string, number, null, or simple object (e.g. not a Stream, Buffer, or view). + 'buffer' - a Buffer. + 'view' - a view generated with reply.view(). + 'file' - a file generated with reply.file() of via the directory handler. + 'stream' - a Stream. + 'promise' - a Promise object. */ + variety: string; + /** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].*/ + app: any; + /** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. */ + plugins: any; + /** settings - response handling flags: + charset - the 'Content-Type' HTTP header 'charset' property. Defaults to 'utf-8'. + encoding - the string encoding scheme used to serial data into the HTTP payload when source is a string or marshals into a string. Defaults to 'utf8'. + passThrough - if true and source is a Stream, copies the statusCode and headers of the stream to the outbound response. Defaults to true. + stringify - options used for source value requiring stringification. Defaults to no replacer and no space padding. + ttl - if set, overrides the route cache expiration milliseconds value set in the route config. Defaults to no override. + varyEtag - if true, a suffix will be automatically added to the 'ETag' header at transmission time (separated by a '-' character) when the HTTP 'Vary' header is present.*/ + settings: { + charset: string; + encoding: string; + passThrough: boolean; + stringify: any; + ttl: number; + varyEtag: boolean; + } + + /** sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) where: + length - the header value. Must match the actual payload size.*/ + bytes(length: number): void; + /** sets the 'Content-Type' HTTP header 'charset' property where: charset - the charset property value.*/ + charset(charset: string): void; + + /** sets the HTTP status code where: + statusCode - the HTTP status code.*/ + code(statusCode: number): void; + /** sets the HTTP status code to Created (201) and the HTTP 'Location' header where: uri - an absolute or relative URI used as the 'Location' header value.*/ + created(uri: string): void; + + + /** encoding(encoding) - sets the string encoding scheme used to serial data into the HTTP payload where: encoding - the encoding property value (see node Buffer encoding).*/ + encoding(encoding: string): void; + + /** etag(tag, options) - sets the representation entity tag where: + tag - the entity tag string without the double-quote. + options - optional settings where: + weak - if true, the tag will be prefixed with the 'W/' weak signifier. Weak tags will fail to match identical tags for the purpose of determining 304 response status. Defaults to false. + vary - if true and content encoding is set or applied to the response (e.g 'gzip' or 'deflate'), the encoding name will be automatically added to the tag at transmission time (separated by a '-' character). Ignored when weak is true. Defaults to true.*/ + etag(tag: string, options: { + weak: boolean; vary: boolean; + }): void; + + /**header(name, value, options) - sets an HTTP header where: + name - the header name. + value - the header value. + options - optional settings where: + append - if true, the value is appended to any existing header value using separator. Defaults to false. + separator - string used as separator when appending to an exiting value. Defaults to ','. + override - if false, the header value is not set if an existing value present. Defaults to true.*/ + header(name: string, value: string, options?: { + append: boolean; + separator: string; + override: boolean; + }): void; + + /** location(uri) - sets the HTTP 'Location' header where: + uri - an absolute or relative URI used as the 'Location' header value.*/ + location(uri: string): void; + + /** redirect(uri) - sets an HTTP redirection response (302) and decorates the response with additional methods listed below, where: + uri - an absolute or relative URI used to redirect the client to another resource. */ + redirect(uri: string): void; + + /** replacer(method) - sets the JSON.stringify() replacer argument where: + method - the replacer function or array. Defaults to none.*/ + replacer(method: Function| Array): void; + + /** spaces(count) - sets the JSON.stringify() space argument where: + count - the number of spaces to indent nested object keys. Defaults to no indentation. */ + spaces(count: number): void; + /**state(name, value, [options]) - sets an HTTP cookie where: + name - the cookie name. + value - the cookie value. If no encoding is defined, must be a string. + options - optional configuration. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others).*/ + state(name: string, value: string, options?: any): void; + + } + + + + /** Server http://hapijs.com/api#server + rver object is the main application container. The server manages all incoming connections along with all the facilities provided by the framework. A server can contain more than one connection (e.g. listen to port 80 and 8080). + Server events + The server object inherits from Events.EventEmitter and emits the following events: + 'log' - events logged with server.log() and server events generated internally by the framework. + 'start' - emitted when the server is started using server.start(). + 'stop' - emitted when the server is stopped using server.stop(). + 'request' - events generated by request.log(). Does not include any internally generated events. + 'request-internal' - request events generated internally by the framework (multiple events per request). + 'request-error' - emitted whenever an Internal Server Error (500) error response is sent. Single event per request. + 'response' - emitted after the response is sent back to the client (or when the client connection closed and no response sent, in which case request.response is null). Single event per request. + 'tail' - emitted when a request finished processing, including any registered tails. Single event per request. + Note that the server object should not be used to emit application events as its internal implementation is designed to fan events out to the various plugin selections and not for application events. + MORE EVENTS HERE: http://hapijs.com/api#server-events*/ + export class Server extends Events.EventEmitter { + + constructor(options?: IServerOptions); + /** Provides a safe place to store server-specific run-time application data without potential conflicts with the framework internals. The data can be accessed whenever the server is accessible. Initialized with an empty object. + var Hapi = require('hapi'); + server = new Hapi.Server(); + server.app.key = 'value'; + var handler = function (request, reply) { + return reply(request.server.app.key); + }; */ + app: any; + /** An array containing the server's connections. When the server object is returned from server.select(), the connections array only includes the connections matching the selection criteria. + var server = new Hapi.Server(); + server.connection({ port: 80, labels: 'a' }); + server.connection({ port: 8080, labels: 'b' }); + // server.connections.length === 2 + var a = server.select('a'); + // a.connections.length === 1*/ + connections: Array; + /** When the server contains exactly one connection, info is an object containing information about the sole connection. + * When the server contains more than one connection, each server.connections array member provides its own connection.info. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + // server.info.port === 80 + server.connection({ port: 8080 }); + // server.info === null + // server.connections[1].info.port === 8080 + */ + info: { + /** - a unique connection identifier (using the format '{hostname}:{pid}:{now base36}').*/ + id: string; + /** - the connection creation timestamp.*/ + created: number; + /** - the connection start timestamp (0 when stopped).*/ + started: number; + /** the connection port based on the following rules: + the configured port value before the server has been started. + the actual port assigned when no port is configured or set to 0 after the server has been started.*/ + port: number; + + /** - the host name the connection was configured to. Defaults to the operating system hostname when available, otherwise 'localhost'.*/ + host: string; + /** - the active IP address the connection was bound to after starting.Set to undefined until the server has been started or when using a non TCP port (e.g. UNIX domain socket).*/ + address: string; + /** - the protocol used: + 'http' - HTTP. + 'https' - HTTPS. + 'socket' - UNIX domain socket or Windows named pipe.*/ + protocol: string; + /** a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the uri setting if provided, otherwise constructed from the available settings. If no port is available or set to 0, the uri will not include a port component.*/ + uri: string; + }; + /** An object containing the process load metrics (when load.sampleInterval is enabled): + rss - RSS memory usage. + var Hapi = require('hapi'); + var server = new Hapi.Server({ load: { sampleInterval: 1000 } }); + console.log(server.load.rss);*/ + load: { + /** - event loop delay milliseconds.*/ + eventLoopDelay: number; + /** - V8 heap usage.*/ + heapUsed: number; + }; + /** When the server contains exactly one connection, listener is the node HTTP server object of the sole connection. + When the server contains more than one connection, each server.connections array member provides its own connection.listener. + var Hapi = require('hapi'); + var SocketIO = require('socket.io'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + var io = SocketIO.listen(server.listener); + io.sockets.on('connection', function(socket) { + socket.emit({ msg: 'welcome' }); + });*/ + listener: http.Server; + + /** server.methods + An object providing access to the server methods where each server method name is an object property. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.method('add', function (a, b, next) { + return next(null, a + b); + }); + server.methods.add(1, 2, function (err, result) { + // result === 3 + });*/ + methods: IDictionary; + + /** server.mime + Provides access to the server MIME database used for setting content-type information. The object must not be modified directly but only through the mime server setting. + var Hapi = require('hapi'); + var options = { + mime: { + override: { + 'node/module': { + source: 'steve', + compressible: false, + extensions: ['node', 'module', 'npm'], + type: 'node/module' + } + } + } + }; + var server = new Hapi.Server(options); + // server.mime.path('code.js').type === 'application/javascript' + // server.mime.path('file.npm').type === 'node/module'*/ + mime: any; + /**server.plugins + An object containing the values exposed by each plugin registered where each key is a plugin name and the values are the exposed properties by each plugin using server.expose(). Plugins may set the value of the server.plugins[name] object directly or via the server.expose() method. + exports.register = function (server, options, next) { + server.expose('key', 'value'); + // server.plugins.example.key === 'value' + return next(); + }; + exports.register.attributes = { + name: 'example' + };*/ + plugins: IDictionary; + /** server.realm + The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. + modifiers - when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method and includes: + route - routes preferences: + prefix - the route path prefix used by any calls to server.route() from the server. + vhost - the route virtual host settings used by any calls to server.route() from the server. + plugin - the active plugin name (empty string if at the server root). + plugins - plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. + settings - settings overrides: + files.relativeTo + bind + The server.realm object should be considered read-only and must not be changed directly except for the plugins property can be directly manipulated by the plugins (each setting its own under plugins[name]). + exports.register = function (server, options, next) { + console.log(server.realm.modifiers.route.prefix); + return next(); + };*/ + realm: IServerRealm; + + /** server.root + The root server object containing all the connections and the root server methods (e.g. start(), stop(), connection()).*/ + root: Server; + /** server.settings + The server configuration object after defaults applied. + var Hapi = require('hapi'); + var server = new Hapi.Server({ + app: { + key: 'value' + } + }); + // server.settings.app === { key: 'value' }*/ + settings: IServerOptions; + + /** server.version + The hapi module version number. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + // server.version === '8.0.0'*/ + version: string; + + /** server.after(method, [dependencies]) + Adds a method to be called after all the plugin dependencies have been registered and before the server starts (only called if the server is started) where: + after - the method with signature function(plugin, next) where: + server - server object the after() method was called on. + next - the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where: + err - internal error which is returned back via the server.start() callback. + dependencies - a string or array of string with the plugin names to call this method after their after() methods. There is no requirement for the other plugins to be registered. Setting dependencies only arranges the after methods in the specified order. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.after(function () { + // Perform some pre-start logic + }); + server.start(function (err) { + // After method already executed + }); + server.auth.default(options)*/ + after(method: (plugin: any, next: (err: any) => void) => void, dependencies: string|string[]): void; + + auth: { + /** server.auth.default(options) + Sets a default strategy which is applied to every route where: + options - a string with the default strategy name or an object with a specified strategy or strategies using the same format as the route auth handler options. + The default does not apply when the route config specifies auth as false, or has an authentication strategy configured. Otherwise, the route authentication config is applied to the defaults. Note that the default only applies at time of route configuration, not at runtime. Calling default() after adding a route will have no impact on routes added prior. + The default auth strategy configuration can be accessed via connection.auth.settings.default. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.auth.scheme('custom', scheme); + server.auth.strategy('default', 'custom'); + server.auth.default('default'); + server.route({ + method: 'GET', + path: '/', + handler: function (request, reply) { + return reply(request.auth.credentials.user); + } + });*/ + default(options: string):void; + /** server.auth.scheme(name, scheme) + Registers an authentication scheme where: + name - the scheme name. + scheme - the method implementing the scheme with signature function(server, options) where: + server - a reference to the server object the scheme is added to. + options - optional scheme settings used to instantiate a strategy.*/ + scheme(name: string, + /** When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route. If the err returned by the reply() method includes a message, no additional strategies will be attempted. If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference. + n the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'. + server = new Hapi.Server(); + server.connection({ port: 80 }); + scheme = function (server, options) { + urn { + authenticate: function (request, reply) { + req = request.raw.req; + var authorization = req.headers.authorization; + if (!authorization) { + return reply(Boom.unauthorized(null, 'Custom')); + } + urn reply(null, { credentials: { user: 'john' } }); + } + }; + }; + */ + scheme: (server: Server, options: any) => IServerAuthScheme): void; + + /** server.auth.strategy(name, scheme, [mode], [options]) + Registers an authentication strategy where: + name - the strategy name. + scheme - the scheme name (must be previously registered using server.auth.scheme()). + mode - if true, the scheme is automatically assigned as a required strategy to any route without an auth config. Can only be assigned to a single server strategy. Value must be true (which is the same as 'required') or a valid authentication mode ('required', 'optional', 'try'). Defaults to false. + options - scheme options based on the scheme requirements. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.auth.scheme('custom', scheme); + server.auth.strategy('default', 'custom'); + server.route({ + method: 'GET', + path: '/', + config: { + auth: 'default', + handler: function (request, reply) { + return reply(request.auth.credentials.user); + } + } + });*/ + strategy(name: string, scheme: any, mode?: boolean, options?: any):void; + + /** server.auth.test(strategy, request, next) + Tests a request against an authentication strategy where: + strategy - the strategy name registered with server.auth.strategy(). + request - the request object. + next - the callback function with signature function(err, credentials) where: + err - the error if authentication failed. + credentials - the authentication credentials object if authentication was successful. + Note that the test() method does not take into account the route authentication configuration. It also does not perform payload authentication. It is limited to the basic strategy authentication execution. It does not include verifying scope, entity, or other route properties. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.auth.scheme('custom', scheme); + server.auth.strategy('default', 'custom'); + server.route({ + method: 'GET', + path: '/', + handler: function (request, reply) { + request.server.auth.test('default', request, function (err, credentials) { + if (err) { + return reply({ status: false }); + } + return reply({ status: true, user: credentials.name }); + }); + } + });*/ + test(strategy: string, request: Request, next: (err: any, credentials: any) => void): void; + }; + /** server.bind(context) + Sets a global context used as the default bind object when adding a route or an extension where: + context - the object used to bind this in handler and extension methods. + When setting context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set. + var handler = function (request, reply) { + return reply(this.message); + }; + exports.register = function (server, options, next) { + var bind = { + message: 'hello' + }; + server.bind(bind); + server.route({ method: 'GET', path: '/', handler: handler }); + return next(); + };*/ + bind(context: any): void; + + + /** server.cache(options) + Provisions a cache segment within the server cache facility where: + options - catbox policy configuration where: + expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. + expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn. + generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) where: - id - the id string or object provided to the get() method. - next - the method called when the new item is returned with the signature function(err, value, ttl) where: - err - an error condition. - value - the new value generated. - ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy. + staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. + staleTimeout - number of milliseconds to wait before checking if an item is stale. + generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. + cache - the cache name configured in 'server.cache`. Defaults to the default cache. + segment - string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. Required when called outside of a plugin. + shared - if true, allows multiple cache provisions to share the same segment. Default to false. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + var cache = server.cache({ segment: 'countries', expiresIn: 60 * 60 * 1000 }); + cache.set('norway', { capital: 'oslo' }, null, function (err) { + cache.get('norway', function (err, value, cached, log) { + // value === { capital: 'oslo' }; + }); + });*/ + cache(options: ICatBoxCacheOptions): void; + + /** server.connection([options]) + Adds an incoming server connection + Returns a server object with the new connection selected. + Must be called before any other server method that modifies connections is called for it to apply to the new connection (e.g. server.state()). + Note that the options object is deeply cloned (with the exception of listener which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + var web = server.connection({ port: 8000, host: 'example.com', labels: ['web'] }); + var admin = server.connection({ port: 8001, host: 'example.com', labels: ['admin'] }); + // server.connections.length === 2 + // web.connections.length === 1 + // admin.connections.length === 1 */ + connection(options: ISeverConnectionOptions): Server; + /** server.decorate(type, property, method) + Extends various framework interfaces with custom methods where: + type - the interface being decorated. Supported types: + 'reply' - adds methods to the reply interface. + 'server' - adds methods to the Server object. + property - the object decoration key name. + method - the extension function. + Note that decorations apply to the entire server and all its connections regardless of current selection. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.decorate('reply', 'success', function () { + return this.response({ status: 'ok' }); + }); + server.route({ + method: 'GET', + path: '/', + handler: function (request, reply) { + return reply.success(); + } + });*/ + decorate(type: string, property: string, method: Function):void; + + /** server.dependency(dependencies, [after]) + Used within a plugin to declares a required dependency on other plugins where: + dependencies - a single string or array of plugin name strings which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is started. Does not provide version dependency which should be implemented using npm peer dependencies. + after - an optional function called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is started. If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). The function signature is function(server, next) where: + server - the server the dependency() method was called on. + next - the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where: + err - internal error condition, which is returned back via the server.start() callback. + exports.register = function (server, options, next) { + server.dependency('yar', after); + return next(); + }; + var after = function (server, next) { + // Additional plugin registration logic + return next(); + };*/ + dependency(dependencies: string|string[], after?: (server: Server, next: (err: any) => void) => void): void; + + + /** server.expose(key, value) + Used within a plugin to expose a property via server.plugins[name] where: + key - the key assigned (server.plugins[name][key]). + value - the value assigned. + exports.register = function (server, options, next) { + server.expose('util', function () { console.log('something'); }); + return next(); + };*/ + expose(key: string, value: any): void; + + /** server.expose(obj) + Merges a deep copy of an object into to the existing content of server.plugins[name] where: + obj - the object merged into the exposed properties container. + exports.register = function (server, options, next) { + server.expose({ util: function () { console.log('something'); } }); + return next(); + };*/ + expose(obj: any): void; + + /** server.ext(event, method, [options]) + Registers an extension function in one of the available extension points where: + event - the event name. + method - a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is function(request, reply) where: + request - the request object. + reply - the reply interface which is used to return control back to the framework. To continue normal execution of the request lifecycle, reply.continue() must be called. To abort processing and return a response to the client, call reply(value) where value is an error or any other valid response. + this - the object provided via options.bind or the current active context set with server.bind(). + options - an optional object with the following: + before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + bind - a context object passed back to the provided method (via this) when called. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.ext('onRequest', function (request, reply) { + // Change all requests to '/test' + request.setUrl('/test'); + return reply.continue(); + }); + var handler = function (request, reply) { + return reply({ status: 'ok' }); + }; + server.route({ method: 'GET', path: '/test', handler: handler }); + server.start(); + // All requests will get routed to '/test'*/ + ext(event: string, method: (request: Request, reply: IReply, bind?: any) => void, options?: { before: string|string[]; after: string|string[]; bind?: any }): void; + + /** server.handler(name, method) + Registers a new handler type to be used in routes where: + name - string name for the handler being registered. Cannot override the built-in handler types (directory, file, proxy, and view) or any previously registered type. + method - the function used to generate the route handler using the signature function(route, options) where: + route - the route public interface object. + options - the configuration object provided in the handler config. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ host: 'localhost', port: 8000 }); + // Defines new handler for routes on this server + server.handler('test', function (route, options) { + return function (request, reply) { + return reply('new handler: ' + options.msg); + } + }); + server.route({ + method: 'GET', + path: '/', + handler: { test: { msg: 'test' } } + }); + server.start(); + The method function can have a defaults object or function property. If the property is set to an object, that object is used as the default route config for routes using this handler. If the property is set to a function, the function uses the signature function(method) and returns the route default configuration. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ host: 'localhost', port: 8000 }); + var handler = function (route, options) { + return function (request, reply) { + return reply('new handler: ' + options.msg); + } + }; + // Change the default payload processing for this handler + handler.defaults = { + payload: { + output: 'stream', + parse: false + } + }; + server.handler('test', handler);*/ + handler(name: string, method: (route: IRoute, options: THandlerConfig) => ISessionHandler): void; + /** When the server contains exactly one connection, injects a request into the sole connection simulating an incoming HTTP request without making an actual socket connection. + Injection is useful for testing purposes as well as for invoking routing logic internally without the overhead or limitations of the network stack. + Utilizes the [shot module | https://github.com/hapijs/shot ] for performing injections, with some additional options and response properties + * When the server contains more than one connection, each server.connections array member provides its own connection.inject(). + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + var handler = function (request, reply) { + return reply('Success!'); + }; + server.route({ method: 'GET', path: '/', handler: handler }); + server.inject('/', function (res) { + console.log(res.result); + }); + */ + inject: IServerInject; + + /** server.log(tags, [data, [timestamp]]) + Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or output to the console. The arguments are: + tags - a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information. + data - an optional message string or object with the application data being logged. + timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.on('log', function (event, tags) { + if (tags.error) { + console.log(event); + } + }); + server.log(['test', 'error'], 'Test event');*/ + log(tags: string|string[], data?: string|any, timestamp?: number): void; + /**server.lookup(id) + When the server contains exactly one connection, looks up a route configuration where: + id - the route identifier as set in the route options. + returns the route public interface object if found, otherwise null. + var server = new Hapi.Server(); + server.connection(); + server.route({ + method: 'GET', + path: '/', + config: { + handler: function (request, reply) { return reply(); }, + id: 'root' + } + }); + var route = server.lookup('root'); + When the server contains more than one connection, each server.connections array member provides its own connection.lookup() method.*/ + lookup(id: string): IRoute; + /** server.match(method, path, [host]) + When the server contains exactly one connection, looks up a route configuration where: + method - the HTTP method (e.g. 'GET', 'POST'). + path - the requested path (must begin with '/'). + host - optional hostname (to match against routes with vhost). + returns the route public interface object if found, otherwise null. + var server = new Hapi.Server(); + server.connection(); + server.route({ + method: 'GET', + path: '/', + config: { + handler: function (request, reply) { return reply(); }, + id: 'root' + } + }); + var route = server.match('get', '/'); + When the server contains more than one connection, each server.connections array member provides its own connection.match() method.*/ + match(method: string, path: string, host?: string): IRoute; + + + + + /** server.method(name, method, [options]) + Registers a server method. Server methods are functions registered with the server and used throughout the application as a common utility. Their advantage is in the ability to configure them to use the built-in cache and share across multiple request handlers without having to create a common module. + Methods are registered via server.method(name, method, [options]) + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + // Simple arguments + var add = function (a, b, next) { + return next(null, a + b); + }; + server.method('sum', add, { cache: { expiresIn: 2000 } }); + server.methods.sum(4, 5, function (err, result) { + console.log(result); + }); + // Object argument + var addArray = function (array, next) { + var sum = 0; + array.forEach(function (item) { + sum += item; + }); + return next(null, sum); + }; + server.method('sumObj', addArray, { + cache: { expiresIn: 2000 }, + generateKey: function (array) { + return array.join(','); + } + }); + server.methods.sumObj([5, 6], function (err, result) { + console.log(result); + }); + // Synchronous method with cache + var addSync = function (a, b) { + return a + b; + }; + server.method('sumSync', addSync, { cache: { expiresIn: 2000 }, callback: false }); + server.methods.sumSync(4, 5, function (err, result) { + console.log(result); + }); */ + method( + /** a unique method name used to invoke the method via server.methods[name]. When configured with caching enabled, server.methods[name].cache.drop(arg1, arg2, ..., argn, callback) can be used to clear the cache for a given key. Supports using nested names such as utils.users.get which will automatically create the missing path under server.methods and can be accessed for the previous example via server.methods.utils.users.get.*/ + name: string, + method: IServerMethod, + options?: IServerMethodOptions):void; + + + /**server.method(methods) + Registers a server method function as described in server.method() using a configuration object where: + methods - an object or an array of objects where each one contains: + name - the method name. + method - the method function. + options - optional settings. + var add = function (a, b, next) { + next(null, a + b); + }; + server.method({ + name: 'sum', + method: add, + options: { + cache: { + expiresIn: 2000 + } + } + });*/ + method(methods: { + name: string; method: IServerMethod; options?: IServerMethodOptions + }| Array<{ + name: string; method: IServerMethod; options?: IServerMethodOptions + }>):void; + /**server.path(relativeTo) + Sets the path prefix used to locate static resources (files and view templates) when relative paths are used where: + relativeTo - the path prefix added to any relative file path starting with '.'. + Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the connection files.relativeTo configuration is used. The path only applies to routes added after it has been set. + exports.register = function (server, options, next) { + server.path(__dirname + '../static'); + server.route({ path: '/file', method: 'GET', handler: { file: './test.html' } }); + next(); + };*/ + path(relativeTo: string): void; + /**server.register(plugins, [options], callback) + Registers a plugin where: + plugins - an object or array of objects where each one is either: + a plugin registration function. + an object with the following: + register - the plugin registration function. + options - optional options passed to the registration function when called. + options - optional registration options (different from the options passed to the registration function): + select - a string or array of string labels used to pre-select connections for plugin registration. + routes - modifiers applied to each route added by the plugin: + prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. + vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + callback - the callback function with signature function(err) where: + err - an error returned from the registration function. Note that exceptions thrown by the registration function are not handled by the framework. + server.register({ + register: require('plugin_name'), + options: { + message: 'hello' + } + }, function (err) { + if (err) { + console.log('Failed loading plugin'); + } + });*/ + register(plugins: any|any[], options: { + select: string|string[]; + routes: { + prefix: string; vhost?: string|string[] + }; + } + , callback: (err: any) => void):void; + + register(plugins: any|any[], callback: (err: any) => void):void; + + /**server.render(template, context, [options], callback) + Utilizes the server views manager to render a template where: + template - the template filename and path, relative to the views manager templates path (path or relativeTo). + context - optional object used by the template to render context-specific result. Defaults to no context ({}). + options - optional object used to override the views manager configuration. + callback - the callback function with signature function (err, rendered, config) where: + err - the rendering error if any. + rendered - the result view string. + config - the configuration used to render the template. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.views({ + engines: { html: require('handlebars') }, + path: __dirname + '/templates' + }); + var context = { + title: 'Views Example', + message: 'Hello, World' + }; + server.render('hello', context, function (err, rendered, config) { + console.log(rendered); + });*/ + render(template: string, context: any, options: any, callback: (err: any, rendered: any, config: any) => void):void; + /** server.route(options) + Adds a connection route where: + options - a route configuration object or an array of configuration objects. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.route({ method: 'GET', path: '/', handler: function (request, reply) { return reply('ok'); } }); + server.route([ + { method: 'GET', path: '/1', handler: function (request, reply) { return reply('ok'); } }, + { method: 'GET', path: '/2', handler: function (request, reply) { return reply('ok'); } } + ]);*/ + route(options: IRouteConfiguration):void; + route(options: IRouteConfiguration[]):void; + /**server.select(labels) + Selects a subset of the server's connections where: + labels - a single string or array of strings of labels used as a logical OR statement to select all the connections with matching labels in their configuration. + Returns a server object with connections set to the requested subset. Selecting again on a selection operates as a logic AND statement between the individual selections. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80, labels: ['a', 'b'] }); + server.connection({ port: 8080, labels: ['a', 'c'] }); + server.connection({ port: 8081, labels: ['b', 'c'] }); + var a = server.select('a'); // 80, 8080 + var ac = a.select('c'); // 8080*/ + select(labels: string|string[]): void; + /** server.start([callback]) + Starts the server connections by listening for incoming requests on the configured port of each listener (unless the connection was configured with autoListen set to false), where: + callback - optional callback when server startup is completed or failed with the signature function(err) where: + err - any startup error condition. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.start(function (err) { + console.log('Server started at: ' + server.info.uri); + });*/ + start(callback?: (err: any) => void): void; + /** server.state(name, [options]) + HTTP state management uses client cookies to persist a state across multiple requests. Registers a cookie definitions + State defaults can be modified via the server connections.routes.state configuration option. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + // Set cookie definition + server.state('session', { + ttl: 24 * 60 * 60 * 1000, // One day + isSecure: true, + path: '/', + encoding: 'base64json' + }); + // Set state in route handler + var handler = function (request, reply) { + var session = request.state.session; + if (!session) { + session = { user: 'joe' }; + } + session.last = Date.now(); + return reply('Success').state('session', session); + }; + Registered cookies are automatically parsed when received. Parsing rules depends on the route state.parse configuration. If an incoming registered cookie fails parsing, it is not included in request.state, regardless of the state.failAction setting. When state.failAction is set to 'log' and an invalid cookie value is received, the server will emit a 'request-internal' event. To capture these errors subscribe to the 'request-internal' events and filter on 'error' and 'state' tags: + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.on('request-internal', function (request, event, tags) { + if (tags.error && tags.state) { + console.error(event); + } + }); */ + state(name: string, options?: ICookieSettings): void; + + /** server.stop([options], [callback]) + Stops the server's connections by refusing to accept any new connections or requests (existing connections will continue until closed or timeout), where: + options - optional object with: + timeout - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to 5000 (5 seconds). + callback - optional callback method with signature function() which is called once all the connections have ended and it is safe to exit the process. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.stop({ timeout: 60 * 1000 }, function () { + console.log('Server stopped'); + });*/ + stop(options?: { timeout: number }, callback?: () => void): void; + /**server.table([host]) + Returns a copy of the routing table where: + host - optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts. + The return value is an array where each item is an object containing: + info - the connection.info the connection the table was generated for. + labels - the connection labels. + table - an array of routes where each route contains: + settings - the route config with defaults applied. + method - the HTTP method in lower case. + path - the route path. + Note that if the server has not been started and multiple connections use port 0, the table items will override each other and will produce an incomplete result. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80, host: 'example.com' }); + server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } }); + var table = server.table(); + When calling connection.table() directly on each connection, the return value is the same as the array table item value of an individual connection: + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80, host: 'example.com' }); + server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } }); + var table = server.connections[0].table(); + //[ + // { + // method: 'get', + // path: '/example', + // settings: { ... } + // } + //] + */ + table(host?: any): IConnectionTable; + + /**server.views(options) + Initializes the server views manager + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.views({ + engines: { + html: require('handlebars'), + jade: require('jade') + }, + path: '/static/templates' + }); + When server.views() is called within a plugin, the views manager is only available to plugins methods.*/ + views(options: IServerViewsConfiguration): void; + + } +} \ No newline at end of file diff --git a/hapi/hapi-tests-8.2.0.ts b/hapi/hapi-tests-8.2.0.ts new file mode 100644 index 0000000000..11ad81d2dd --- /dev/null +++ b/hapi/hapi-tests-8.2.0.ts @@ -0,0 +1,99 @@ +/// + +import Hapi = require("hapi"); + +// Create a server with a host and port +var server = new Hapi.Server(); +server.connection({ + host: "localhost", + port: 8000, +}); + +// Add plugins +var plugin: any = { + register: function (plugin: Object, options: Object, next: Function) { + next(); + } +}; + +plugin.register.attributes = { + name: "test", + version: "1.0.0" +}; + +// optional options parameter +server.register({}, function (err) {}); + +// optional options.routes.vhost parameter +server.register({}, { select: 'api', routes: { prefix: '/prefix' } }, function (err) {}); + +//server.pack.register(plugin, (err: Object) => { +// if (err) { throw err; } +//}); + +//server.pack.register([plugin], (err: Object) => { +// if (err) { throw err; } +//}); + +// Add server method +var add = function (a: number, b: number, next: (err: any, result?: any, ttl?: number) => void) { + next(null, a + b); +}; + +server.method("sum", add);//, { cache: { expiresIn: 2000 } }); + +server.methods["sum"](4, 5, (err: any, result: any) => { + console.log(result); +}); + +var addArray = function (array: Array, next: (err: any, result?: any, ttl?: number) => void) { + var sum: number = 0; + array.forEach((item: number) => { + sum += item; + }); + next(null, sum); +}; + +server.method("sumObj", addArray, { + //cache: { expiresIn: 2000 }, + generateKey: (array: Array) => { + return array.join(','); + } +}); + +server.methods["sumObj"]([5, 6], (err: any, result: any) => { + console.log(result); +}); + +// Add the route +server.route({ + method: 'GET', + path: '/hello', + handler: function (request: Hapi.Request, reply: Function) { + reply('hello world'); + } +}); + +server.route([{ + method: 'GET', + path: '/hello2', + handler: function (request: Hapi.Request, reply: Function) { + reply('hello world2'); + } +}]); + +// config.validate parameters should be optional +server.route([{ + method: 'GET', + path: '/hello2', + handler: function(request: Hapi.Request, reply: Function) { + reply('hello world2'); + }, + config: { + validate: { + } + } +}]); + +// Start the server +server.start(); diff --git a/hapi/hapi.d.ts b/hapi/hapi.d.ts index 8d3da2620b..04b9416c7d 100644 --- a/hapi/hapi.d.ts +++ b/hapi/hapi.d.ts @@ -1,4 +1,4 @@ -// Type definitions for hapi 8.2.0 +// Type definitions for hapi 8.8.0 // Project: http://github.com/spumko/hapi // Definitions by: Jason Swearingen // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -83,7 +83,7 @@ declare module "hapi" { /** - a string or string array of labels used to server.select() specific connections matching the specified labels.Defaults to an empty array [](no labels).*/ labels?: string|string[]; /** - used to create an HTTPS connection.The tls object is passed unchanged as options to the node.js HTTPS server as described in the node.js HTTPS documentation.Set to true when passing a listener object that has been configured to use TLS directly. */ - tls?: boolean; + tls?: boolean|Object; } @@ -209,7 +209,7 @@ declare module "hapi" { /**Initializes the server views manager var Hapi = require('hapi'); var server = new Hapi.Server(); - + server.views({ engines: { html: require('handlebars'), @@ -229,8 +229,8 @@ declare module "hapi" { /** Concludes the handler activity by setting a response and returning control over to the framework where: erran optional error response. resultan optional response payload. - Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. - FLOW CONTROL: + Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. + FLOW CONTROL: When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ export interface IReply { (err: Error, @@ -241,7 +241,7 @@ declare module "hapi" { /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ (result: string|number|boolean|Buffer|stream.Stream | Promise | T): Response; - /** Returns control back to the framework without setting a response. If called in the handler, the response defaults to an empty payload with status code 200. + /** Returns control back to the framework without setting a response. If called in the handler, the response defaults to an empty payload with status code 200. * The data argument is only used for passing back authentication data and is ignored elsewhere. */ continue(credentialData?: any): void; @@ -384,7 +384,7 @@ declare module "hapi" { an object */ auth?: boolean|string| { - /** the authentication mode.Defaults to 'required' if a server authentication strategy is configured, otherwise defaults to no authentication.Available values: + /** the authentication mode.Defaults to 'required' if a server authentication strategy is configured, otherwise defaults to no authentication.Available values: 'required'authentication is required. 'optional'authentication is optional (must be valid if present). 'try'same as 'optional' but allows for invalid authentication. */ @@ -569,7 +569,7 @@ declare module "hapi" { */ headers?: boolean | IJoi | IValidationFunction; - + /** validation rules for incoming request path parameters, after matching the path against the route and extracting any parameters then stored in request.params.Values allowed: trueany path parameters allowed (no validation performed).This is the default. falseno path variables allowed. @@ -634,8 +634,8 @@ declare module "hapi" { tags?: string[] } /** server.realm http://hapijs.com/api#serverrealm - The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), - the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). + The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), + the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. The server.realm object should be considered read-only and must not be changed directly except for the plugins property can be directly manipulated by the plugins (each setting its own under plugins[name]). exports.register = function (server, options, next) { @@ -716,9 +716,9 @@ declare module "hapi" { lookupCompressed: boolean; } - /**http://hapijs.com/api#route-handler + /**http://hapijs.com/api#route-handler Built-in handlers - + The framework comes with a few built-in handler types available by setting the route handler config to an object containing one of these keys.*/ export interface IRouteHandlerConfig { /** generates a static file endpoint for serving a single file. file can be set to: @@ -815,7 +815,7 @@ declare module "hapi" { export interface IRouteConfiguration { /** - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the connection router configuration option.The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters.*/ path: string; - /** - (required) the HTTP method.Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'.Any HTTP method is allowed, except for 'HEAD'.Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). + /** - (required) the HTTP method.Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'.Any HTTP method is allowed, except for 'HEAD'.Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). * Can be assigned an array of methods which has the same result as adding the same route with different methods manually.*/ method: string|string[]; /** - an optional domain string or an array of domain strings for limiting the route to only requests with a matching host header field.Matching is done against the hostname part of the header only (excluding the port).Defaults to all hosts.*/ @@ -828,7 +828,7 @@ declare module "hapi" { /** Route public interface When route information is returned or made available as a property. http://hapijs.com/api#route-public-interface */ export interface IRoute { - + /** the route HTTP method. */ method: string; /** the route path. */ @@ -853,8 +853,8 @@ declare module "hapi" { artifacts - optional authentication artifacts. reply.continue(result) - is called if authentication succeeded where: result - same object as result above. - When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route. - .If the err returned by the reply() method includes a message, no additional strategies will be attempted. + When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route. + .If the err returned by the reply() method includes a message, no additional strategies will be attempted. If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference. var server = new Hapi.Server(); server.connection({ port: 80 }); @@ -1014,12 +1014,12 @@ declare module "hapi" { generateKey?(args: any[]): string; } /** Request object - + The request object is created internally for each incoming request. It is different from the node.js request object received from the HTTP server callback (which is available in request.raw.req). The request object methods and properties change throughout the request lifecycle. Request events - + The request object supports the following events: - + 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). 'finish' - emitted when the request payload finished reading. The event method signature is function (). 'disconnect' - emitted when a request errors or aborts unexpectedly. @@ -1027,25 +1027,25 @@ declare module "hapi" { var Hapi = require('hapi'); var server = new Hapi.Server(); server.connection({ port: 80 }); - + server.ext('onRequest', function (request, reply) { - + var hash = Crypto.createHash('sha1'); request.on('peek', function (chunk) { - + hash.update(chunk); }); - + request.once('finish', function () { - + console.log(hash.digest('hex')); }); - + request.once('disconnect', function () { - + console.error('request aborted'); }); - + return reply.continue(); });*/ export class Request extends Events.EventEmitter { @@ -1157,64 +1157,64 @@ declare module "hapi" { slashes: any; }; /** request.setUrl(url) - + Available only in 'onRequest' extension methods. - + Changes the request URI before the router begins processing the request where: - + url - the new request path value. var Hapi = require('hapi'); var server = new Hapi.Server(); server.connection({ port: 80 }); - + server.ext('onRequest', function (request, reply) { - + // Change all requests to '/test' request.setUrl('/test'); return reply.continue(); });*/ setUrl(url: string): void; /** request.setMethod(method) - + Available only in 'onRequest' extension methods. - + Changes the request method before the router begins processing the request where: - + method - is the request HTTP method (e.g. 'GET'). var Hapi = require('hapi'); var server = new Hapi.Server(); server.connection({ port: 80 }); - + server.ext('onRequest', function (request, reply) { - + // Change all requests to 'GET' request.setMethod('GET'); return reply.continue(); });*/ setMethod(method: string): void; /** request.log(tags, [data, [timestamp]]) - + Always available. - + Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are: - + data - an optional message string or object with the application data being logged. timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). Any logs generated by the server internally will be emitted only on the 'request-internal' channel and will include the event.internal flag set to true. - + var Hapi = require('hapi'); var server = new Hapi.Server(); server.connection({ port: 80 }); - + server.on('request', function (request, event, tags) { - + if (tags.error) { console.log(event); } }); - + var handler = function (request, reply) { - + request.log(['test', 'error'], 'Test event'); return reply(); }; @@ -1227,9 +1227,9 @@ declare module "hapi" { /** an optional timestamp expressed in milliseconds. Defaults to Date.now() (now).*/ timestamp?: number): void; /** request.getLog([tags], [internal]) - + Always available. - + Returns an array containing the events matching any of the tags specified (logical OR) request.getLog(); request.getLog('error'); @@ -1244,38 +1244,38 @@ declare module "hapi" { internal?: boolean): string[]; /** request.tail([name]) - + Available until immediately after the 'response' event is emitted. - + Adds a request tail which has to complete before the request lifecycle is complete where: - + name - an optional tail name used for logging purposes. Returns a tail function which must be called when the tail activity is completed. - + Tails are actions performed throughout the request lifecycle, but which may end after a response is sent back to the client. For example, a request may trigger a database update which should not delay sending back a response. However, it is still desirable to associate the activity with the request when logging it (or an error associated with it). - + When all tails completed, the server emits a 'tail' event. - + var Hapi = require('hapi'); var server = new Hapi.Server(); server.connection({ port: 80 }); - + var get = function (request, reply) { - + var dbTail = request.tail('write to database'); - + db.save('key', 'value', function () { - + dbTail(); }); - + return reply('Success!'); }; - + server.route({ method: 'GET', path: '/', handler: get }); - + server.on('tail', function (request) { - + console.log('Request completed including db activity'); });*/ tail( @@ -1283,34 +1283,34 @@ declare module "hapi" { name?: string): Function; } /** Response events - + The response object supports the following events: - + 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). var Crypto = require('crypto'); var Hapi = require('hapi'); var server = new Hapi.Server(); server.connection({ port: 80 }); - + server.ext('onPreResponse', function (request, reply) { - + var response = request.response; if (response.isBoom) { return reply(); } - + var hash = Crypto.createHash('sha1'); response.on('peek', function (chunk) { - + hash.update(chunk); }); - + response.once('finish', function () { - + console.log(hash.digest('hex')); }); - + return reply.continue(); });*/ export class Response extends Events.EventEmitter { @@ -1412,7 +1412,7 @@ declare module "hapi" { /** Server http://hapijs.com/api#server - rver object is the main application container. The server manages all incoming connections along with all the facilities provided by the framework. A server can contain more than one connection (e.g. listen to port 80 and 8080). + rver object is the main application container. The server manages all incoming connections along with all the facilities provided by the framework. A server can contain more than one connection (e.g. listen to port 80 and 8080). Server events The server object inherits from Events.EventEmitter and emits the following events: 'log' - events logged with server.log() and server events generated internally by the framework. @@ -1734,7 +1734,7 @@ declare module "hapi" { cache(options: ICatBoxCacheOptions): void; /** server.connection([options]) - Adds an incoming server connection + Adds an incoming server connection Returns a server object with the new connection selected. Must be called before any other server method that modifies connections is called for it to apply to the new connection (e.g. server.state()). Note that the options object is deeply cloned (with the exception of listener which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. @@ -1872,8 +1872,8 @@ declare module "hapi" { }; server.handler('test', handler);*/ handler(name: string, method: (route: IRoute, options: THandlerConfig) => ISessionHandler): void; - /** When the server contains exactly one connection, injects a request into the sole connection simulating an incoming HTTP request without making an actual socket connection. - Injection is useful for testing purposes as well as for invoking routing logic internally without the overhead or limitations of the network stack. + /** When the server contains exactly one connection, injects a request into the sole connection simulating an incoming HTTP request without making an actual socket connection. + Injection is useful for testing purposes as well as for invoking routing logic internally without the overhead or limitations of the network stack. Utilizes the [shot module | https://github.com/hapijs/shot ] for performing injections, with some additional options and response properties * When the server contains more than one connection, each server.connections array member provides its own connection.inject(). var Hapi = require('hapi'); @@ -2209,4 +2209,4 @@ declare module "hapi" { views(options: IServerViewsConfiguration): void; } -} \ No newline at end of file +} From 48daae658413eb91583765fef12d7b9f87b5f441 Mon Sep 17 00:00:00 2001 From: CodySchaaf Date: Wed, 17 Jun 2015 16:24:32 -0700 Subject: [PATCH 064/144] Adds angular-animateCss definitions Re-adds deprecated ICookieStoreService since it can still be used...for now. Allow validators viewValue be an object, not just string. --- angularjs/angular-animate.d.ts | 155 ++++++++++++++++++++++++++++----- angularjs/angular-cookies.d.ts | 45 +++++++--- angularjs/angular.d.ts | 68 ++++++++------- 3 files changed, 207 insertions(+), 61 deletions(-) diff --git a/angularjs/angular-animate.d.ts b/angularjs/angular-animate.d.ts index 3ecc95b5b7..1ecc3d0d76 100644 --- a/angularjs/angular-animate.d.ts +++ b/angularjs/angular-animate.d.ts @@ -1,6 +1,6 @@ // Type definitions for Angular JS 1.3 (ngAnimate module) // Project: http://angularjs.org -// Definitions by: Michel Salib , Adi Dahiya , Raphael Schweizer +// Definitions by: Michel Salib , Adi Dahiya , Raphael Schweizer , Cody Schaaf // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -10,15 +10,22 @@ declare module "angular-animate" { export = _; } -/////////////////////////////////////////////////////////////////////////////// -// ngAnimate module (angular-animate.js) -/////////////////////////////////////////////////////////////////////////////// +/** + * ngAnimate module (angular-animate.js) + */ declare module angular.animate { + interface IAnimateFactory extends Function { + enter?: (element: ng.IAugmentedJQuery, doneFn: Function) => IAnimateCssRunner|void; + leave?: (element: ng.IAugmentedJQuery, doneFn: Function) => IAnimateCssRunner|void; + addClass?: (element: ng.IAugmentedJQuery, className: string, doneFn: Function) => IAnimateCssRunner|void; + removeClass?: (element: ng.IAugmentedJQuery, className: string, doneFn: Function) => IAnimateCssRunner|void; + setClass?: (element: ng.IAugmentedJQuery, className: string, doneFn: Function) => IAnimateCssRunner|void; + } - /////////////////////////////////////////////////////////////////////////// - // AnimateService - // see http://docs.angularjs.org/api/ngAnimate/service/$animate - /////////////////////////////////////////////////////////////////////////// + /** + * AnimateService + * see http://docs.angularjs.org/api/ngAnimate/service/$animate + */ interface IAnimateService extends angular.IAnimateService { /** * Globally enables / disables animations. @@ -113,10 +120,10 @@ declare module angular.animate { cancel(animationPromise: IPromise): void; } - /////////////////////////////////////////////////////////////////////////// - // AngularProvider - // see http://docs.angularjs.org/api/ngAnimate/provider/$animateProvider - /////////////////////////////////////////////////////////////////////////// + /** + * AngularProvider + * see http://docs.angularjs.org/api/ngAnimate/provider/$animateProvider + */ interface IAnimateProvider { /** * Registers a new injectable animation factory function. @@ -135,12 +142,120 @@ declare module angular.animate { classNameFilter(expression?: RegExp): RegExp; } - /////////////////////////////////////////////////////////////////////////// - // Angular Animation Options - // see https://docs.angularjs.org/api/ngAnimate/#applying-directive-specific-styles-to-an-animation - /////////////////////////////////////////////////////////////////////////// - interface IAnimationOptions { - to?: Object; - from?: Object; - } + /** + * Angular Animation Options + * see https://docs.angularjs.org/api/ngAnimate/#applying-directive-specific-styles-to-an-animation + */ + interface IAnimationOptions { + /** + * The ending CSS styles (a key/value object) that will be applied across the animation via a CSS transition. + */ + to?: Object; + + /** + * The starting CSS styles (a key/value object) that will be applied at the start of the animation. + */ + from?: Object; + + /** + * The DOM event (e.g. enter, leave, move). When used, a generated CSS class of ng-EVENT and + * ng-EVENT-active will be applied to the element during the animation. Multiple events can be provided when + * spaces are used as a separator. (Note that this will not perform any DOM operation.) + */ + event?: string; + + /** + * The CSS easing value that will be applied to the transition or keyframe animation (or both). + */ + easing?: string; + + /** + * The raw CSS transition style that will be used (e.g. 1s linear all). + */ + transition?: string; + + /** + * The raw CSS keyframe animation style that will be used (e.g. 1s my_animation linear). + */ + keyframe?: string; + + /** + * A space separated list of CSS classes that will be added to the element and spread across the animation. + */ + addClass?: string; + + /** + * A space separated list of CSS classes that will be removed from the element and spread across + * the animation. + */ + removeClass?: string; + + /** + * A number value representing the total duration of the transition and/or keyframe (note that a value + * of 1 is 1000ms). If a value of 0 is provided then the animation will be skipped entirely. + */ + duration?: number; + + /** + * A number value representing the total delay of the transition and/or keyframe (note that a value of + * 1 is 1000ms). If a value of true is used then whatever delay value is detected from the CSS classes will be + * mirrored on the elements styles (e.g. by setting delay true then the style value of the element will be + * transition-delay: DETECTED_VALUE). Using true is useful when you want the CSS classes and inline styles to + * all share the same CSS delay value. + */ + delay?: number; + + /** + * A numeric time value representing the delay between successively animated elements (Click here to + * learn how CSS-based staggering works in ngAnimate.) + */ + stagger?: number; + + /** + * The numeric index representing the stagger item (e.g. a value of 5 is equal to the sixth item + * in the stagger; therefore when a stagger option value of 0.1 is used then there will be a stagger delay of 600ms) + * applyClassesEarly - Whether or not the classes being added or removed will be used when detecting the animation. + * This is set by $animate when enter/leave/move animations are fired to ensure that the CSS classes are resolved in time. + * (Note that this will prevent any transitions from occuring on the classes being added and removed.) + */ + staggerIndex?: number; + } + + interface IAnimateCssRunner { + /** + * Starts the animation + * + * @returns The animation runner with a done function for supplying a callback. + */ + start(): IAnimateCssRunnerStart; + + /** + * Ends (aborts) the animation + */ + end(): void; + } + + interface IAnimateCssRunnerStart extends IPromise { + /** + * Allows you to add done callbacks to the running animation + * + * @param callbackFn: the callback function to be run + */ + done(callbackFn: (animationFinished: boolean) => void): void; + } + + /** + * AnimateCssService + * see http://docs.angularjs.org/api/ngAnimate/service/$animateCss + */ + interface IAnimateCssService { + (element: JQuery, animateCssOptions: IAnimationOptions): IAnimateCssRunner; + } + +} + +declare module angular { + interface IModule { + animate(cssSelector: string, animateFactory: angular.animate.IAnimateFactory): IModule; + } } diff --git a/angularjs/angular-cookies.d.ts b/angularjs/angular-cookies.d.ts index cdea69d369..e34518b8ab 100644 --- a/angularjs/angular-cookies.d.ts +++ b/angularjs/angular-cookies.d.ts @@ -11,23 +11,23 @@ declare module "angular-cookies" { export = _; } -/////////////////////////////////////////////////////////////////////////////// -// ngCookies module (angular-cookies.js) -/////////////////////////////////////////////////////////////////////////////// +/** + * ngCookies module (angular-cookies.js) + */ declare module angular.cookies { - /////////////////////////////////////////////////////////////////////////// - // CookieService - // see http://docs.angularjs.org/api/ngCookies.$cookies - /////////////////////////////////////////////////////////////////////////// + /** + * CookieService + * see http://docs.angularjs.org/api/ngCookies.$cookies + */ interface ICookiesService { [index: string]: any; } - /////////////////////////////////////////////////////////////////////////// - // CookieStoreService - // see http://docs.angularjs.org/api/ngCookies.$cookieStore - /////////////////////////////////////////////////////////////////////////// + /** + * CookieStoreService + * see http://docs.angularjs.org/api/ngCookies.$cookieStore + */ interface ICookiesService { get(key: string): string; getObject(key: string): any; @@ -37,4 +37,27 @@ declare module angular.cookies { remove(key: string, options?: any): void; } + /** + * CookieStoreService DEPRECATED + * see https://code.angularjs.org/1.2.26/docs/api/ngCookies/service/$cookieStore + */ + interface ICookieStoreService { + /** + * Returns the value of given cookie key + * @param key Id to use for lookup + */ + get(key: string): any; + /** + * Sets a value for given cookie key + * @param key Id for the value + * @param value Value to be stored + */ + put(key: string, value: any): void; + /** + * Remove given cookie + * @param key Id of the key-value pair to delete + */ + remove(key: string): void; + } + } diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index c7c90efe55..8906432985 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -249,12 +249,12 @@ declare module angular { isString(value: any): boolean; isUndefined(value: any): boolean; lowercase(str: string): string; - + /** * Deeply extends the destination object dst by copying own enumerable properties from the src object(s) to dst. You can specify multiple src objects. If you want to preserve original objects, you can do so by passing an empty object as the target: var object = angular.merge({}, object1, object2). - * + * * Unlike extend(), merge() recursively descends into object properties of source objects, performing a deep copy. - * + * * @param dst Destination object. * @param src Source object(s). */ @@ -524,11 +524,14 @@ declare module angular { } interface IModelValidators { - [index: string]: (modelValue: any, viewValue: string) => boolean; + /** + * viewValue is any because it can be an object that is called in the view like $viewValue.name:$viewValue.subName + */ + [index: string]: (modelValue: any, viewValue: any) => boolean; } interface IAsyncModelValidators { - [index: string]: (modelValue: any, viewValue: string) => IPromise; + [index: string]: (modelValue: any, viewValue: any) => IPromise; } interface IModelParser { @@ -560,11 +563,11 @@ declare module angular { /** * Dispatches an event name downwards to all child scopes (and their children) notifying the registered $rootScope.Scope listeners. - * + * * The event life cycle starts at the scope on which $broadcast was called. All listeners listening for name event on this scope get notified. Afterwards, the event propagates to all direct and indirect scopes of the current scope and calls all registered listeners along the way. The event cannot be canceled. - * + * * Any exception emitted from the listeners will be passed onto the $exceptionHandler service. - * + * * @param name Event name to broadcast. * @param args Optional one or more arguments which will be passed onto the event listeners. */ @@ -577,7 +580,7 @@ declare module angular { * The event life cycle starts at the scope on which $emit was called. All listeners listening for name event on this scope get notified. Afterwards, the event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it. * * Any exception emitted from the listeners will be passed onto the $exceptionHandler service. - * + * * @param name Event name to emit. * @param args Optional one or more arguments which will be passed onto the event listeners. */ @@ -757,16 +760,16 @@ declare module angular { /** * $filter - $filterProvider - service in module ng - * + * * Filters are used for formatting data displayed to the user. - * + * * see https://docs.angularjs.org/api/ng/service/$filter */ interface IFilterService { /** * Usage: * $filter(name); - * + * * @param name Name of the filter function to retrieve */ (name: string): Function; @@ -774,15 +777,15 @@ declare module angular { /** * $filterProvider - $filter - provider in module ng - * + * * Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To achieve this a filter definition consists of a factory function which is annotated with dependencies and is responsible for creating a filter function. - * + * * see https://docs.angularjs.org/api/ng/provider/$filterProvider */ interface IFilterProvider extends IServiceProvider { /** * register(name); - * + * * @param name Name of the filter function, or an object map of filters where the keys are the filter names and the values are the filter factories. Note: Filter names must be valid angular Expressions identifiers, such as uppercase or orderBy. Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace your filters, then you can use capitalization (myappSubsectionFilterx) or underscores (myapp_subsection_filterx). */ register(name: string | {}): IServiceProvider; @@ -1033,10 +1036,10 @@ declare module angular { interface IPromise { /** * Regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected. - * + * The successCallBack may return IPromise for when a $q.reject() needs to be returned * This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback. It also notifies via the return value of the notifyCallback method. The promise can not be resolved or rejected from the notifyCallback method. */ - then(successCallback: (promiseValue: T) => IHttpPromise|IPromise|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise; + then(successCallback: (promiseValue: T) => IHttpPromise|IPromise|TResult|IPromise, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise; /** * Shorthand for promise.then(null, errorCallback) @@ -1074,31 +1077,31 @@ declare module angular { /** * $cacheFactory - service in module ng - * + * * Factory that constructs Cache objects and gives access to them. - * + * * see https://docs.angularjs.org/api/ng/service/$cacheFactory */ interface ICacheFactoryService { /** * Factory that constructs Cache objects and gives access to them. - * + * * @param cacheId Name or id of the newly created cache. * @param optionsMap Options object that specifies the cache behavior. Properties: - * + * * capacity — turns the cache into LRU cache. */ (cacheId: string, optionsMap?: { capacity?: number; }): ICacheObject; /** - * Get information about all the caches that have been created. + * Get information about all the caches that have been created. * @returns key-value map of cacheId to the result of calling cache#info */ info(): any; /** * Get access to a cache object by the cacheId used when it was created. - * + * * @param cacheId Name or id of a cache to access. */ get(cacheId: string): ICacheObject; @@ -1106,9 +1109,9 @@ declare module angular { /** * $cacheFactory.Cache - type in module ng - * + * * A cache object used to store and retrieve data, primarily used by $http and the script directive to cache templates and other data. - * + * * see https://docs.angularjs.org/api/ng/type/$cacheFactory.Cache */ interface ICacheObject { @@ -1131,9 +1134,9 @@ declare module angular { /** * Inserts a named entry into the Cache object to be retrieved later, and incrementing the size of the cache if the key was not already present in the cache. If behaving like an LRU cache, it will also remove stale entries from the set. - * + * * It will not insert undefined values into the cache. - * + * * @param key the key under which the cached data is stored. * @param value the value to store alongside the key. If it is undefined, the key will not be stored. */ @@ -1141,14 +1144,14 @@ declare module angular { /** * Retrieves named data stored in the Cache object. - * + * * @param key the key of the data to be retrieved */ get(key: string): any; /** * Removes an entry from the Cache object. - * + * * @param key the key of the entry to be removed */ remove(key: string): void; @@ -1163,7 +1166,7 @@ declare module angular { */ destroy(): void; } - + /////////////////////////////////////////////////////////////////////////// // CompileService // see http://docs.angularjs.org/api/ng.$compile @@ -1416,6 +1419,11 @@ declare module angular { */ interface IHttpProviderDefaults { cache?: boolean; + /** + * Transform function or an array of such functions. The transform function takes the http request body and + * headers and returns its transformed (typically serialized) version. + */ + transformRequest?: ((data: any, headersGetter?: any) => any)|((data: any, headersGetter?: any) => any)[]; xsrfCookieName?: string; xsrfHeaderName?: string; withCredentials?: boolean; From dd41d58a41401acce5ee425c4fe852dab9ebdb4f Mon Sep 17 00:00:00 2001 From: Tanguy Krotoff Date: Tue, 7 Jul 2015 20:25:09 +0200 Subject: [PATCH 065/144] Rename boostrap to bootstrap --- ...tetimepicker-tests.ts => bootstrap.v3.datetimepicker-tests.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename bootstrap.v3.datetimepicker/{boostrap.v3.datetimepicker-tests.ts => bootstrap.v3.datetimepicker-tests.ts} (100%) diff --git a/bootstrap.v3.datetimepicker/boostrap.v3.datetimepicker-tests.ts b/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-tests.ts similarity index 100% rename from bootstrap.v3.datetimepicker/boostrap.v3.datetimepicker-tests.ts rename to bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-tests.ts From 2f7754dceb349d4d1058bd4c11f144e6d9013536 Mon Sep 17 00:00:00 2001 From: Daniel Beckwith Date: Tue, 7 Jul 2015 17:49:06 -0400 Subject: [PATCH 066/144] Fixes contains searching keys instead of values on objects, also adds "includes" alias. --- lodash/lodash-tests.ts | 9 +++++++-- lodash/lodash.d.ts | 38 +++++++++++++++++++++++++++++++++++--- 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index c7e6bf0241..0c73066c5f 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -363,14 +363,19 @@ result = _.at(['moe', 'larry', 'curly'], 0, 2); result = _.contains([1, 2, 3], 1); result = _.contains([1, 2, 3], 1, 2); -result = _.contains({ 'name': 'moe', 'age': 40 }, 'moe'); +result = _.contains({ 'moe': 30, 'larry': 40, 'curly': 67 }, 40); result = _.contains('curly', 'ur'); result = _.include([1, 2, 3], 1); result = _.include([1, 2, 3], 1, 2); -result = _.include({ 'name': 'moe', 'age': 40 }, 'moe'); +result = _.include({ 'moe': 30, 'larry': 40, 'curly': 67 }, 40); result = _.include('curly', 'ur'); +result = _.includes([1, 2, 3], 1); +result = _.includes([1, 2, 3], 1, 2); +result = _.includes({ 'moe': 30, 'larry': 40, 'curly': 67 }, 40); +result = _.includes('curly', 'ur'); + result = <_.Dictionary>_.countBy([4.3, 6.1, 6.4], function (num) { return Math.floor(num); }); result = <_.Dictionary>_.countBy([4.3, 6.1, 6.4], function (num) { return this.floor(num); }, Math); result = <_.Dictionary>_.countBy(['one', 'two', 'three'], 'length'); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index b4eaf75091..21bd2357f8 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -2198,11 +2198,11 @@ declare module _ { /** * @see _.contains * @param dictionary The dictionary to iterate over. - * @param key The key in the dictionary to search for. + * @param value The value in the dictionary to search for. **/ contains( dictionary: Dictionary, - key: string, + value: T, fromIndex?: number): boolean; /** @@ -2236,7 +2236,7 @@ declare module _ { **/ include( dictionary: Dictionary, - key: string, + value: T, fromIndex?: number): boolean; /** @@ -2246,6 +2246,38 @@ declare module _ { searchString: string, targetString: string, fromIndex?: number): boolean; + + /** + * @see _.contains + **/ + includes( + collection: Array, + target: T, + fromIndex?: number): boolean; + + /** + * @see _.contains + **/ + includes( + collection: List, + target: T, + fromIndex?: number): boolean; + + /** + * @see _.contains + **/ + includes( + dictionary: Dictionary, + value: T, + fromIndex?: number): boolean; + + /** + * @see _.contains + **/ + includes( + searchString: string, + targetString: string, + fromIndex?: number): boolean; } //_.countBy From 0e7631255570dac63f31beec9b73a4cbedd90b12 Mon Sep 17 00:00:00 2001 From: Geir Sagberg Date: Wed, 8 Jul 2015 00:02:27 +0200 Subject: [PATCH 067/144] Add 'firebase' CommonJS module support --- firebase/firebase.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/firebase/firebase.d.ts b/firebase/firebase.d.ts index f3c53b3ce8..6302336e12 100644 --- a/firebase/firebase.d.ts +++ b/firebase/firebase.d.ts @@ -306,6 +306,10 @@ interface FirebaseStatic { } declare var Firebase: FirebaseStatic; +declare module 'firebase' { + export = Firebase; +} + // Reference: https://www.firebase.com/docs/web/api/firebase/getauth.html interface FirebaseAuthData { uid: string; From 9436ac816b62aebb13ceb2c3ab8397898832789c Mon Sep 17 00:00:00 2001 From: Daniel Beckwith Date: Tue, 7 Jul 2015 18:07:52 -0400 Subject: [PATCH 068/144] Remove includes from sequelize definition, since it's in lodash's now. --- sequelize/sequelize.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/sequelize/sequelize.d.ts b/sequelize/sequelize.d.ts index 85d473f28d..1bb6be593e 100644 --- a/sequelize/sequelize.d.ts +++ b/sequelize/sequelize.d.ts @@ -2703,7 +2703,6 @@ declare module "sequelize" } interface Lodash extends _.LoDashStatic { - includes(str: string, needle: string): boolean; camelizeIf(str: string, condition: boolean): string; camelizeIf(str: string, condition: any): string; underscoredIf(str: string, condition: boolean): string; @@ -2785,4 +2784,4 @@ declare module "sequelize" var sequelize: sequelize.SequelizeStatic; export = sequelize; -} \ No newline at end of file +} From 5ce60e032b7b5523876f8269a2c4b25edeaa02ba Mon Sep 17 00:00:00 2001 From: Steven Salat Date: Tue, 7 Jul 2015 17:42:10 -0700 Subject: [PATCH 069/144] Updating jquery.autosize to the new API in 3.0.7 --- jquery.autosize/jquery.autosize-tests.ts | 13 +++++++++++++ jquery.autosize/jquery.autosize.d.ts | 24 +++++++++++------------- 2 files changed, 24 insertions(+), 13 deletions(-) create mode 100755 jquery.autosize/jquery.autosize-tests.ts diff --git a/jquery.autosize/jquery.autosize-tests.ts b/jquery.autosize/jquery.autosize-tests.ts new file mode 100755 index 0000000000..df4aef5b24 --- /dev/null +++ b/jquery.autosize/jquery.autosize-tests.ts @@ -0,0 +1,13 @@ +/// + +// from a NodeList +autosize(document.querySelectorAll('textarea')); + +// from a single Node +autosize(document.querySelector('textarea')); + +// from a jQuery collection +autosize($('textarea')); + +// from a single element +autosize(document.getElementById('my-textarea')); \ No newline at end of file diff --git a/jquery.autosize/jquery.autosize.d.ts b/jquery.autosize/jquery.autosize.d.ts index 5b9f9adfb3..508677b4a1 100644 --- a/jquery.autosize/jquery.autosize.d.ts +++ b/jquery.autosize/jquery.autosize.d.ts @@ -1,21 +1,19 @@ -// Type definitions for jquery.autosize (un-versioned) +// Type definitions for jquery.autosize 3.0.7 // Project: http://www.jacklmoore.com/autosize/ // Definitions by: Aaron T. King // Definitions: https://github.com/borisyankov/DefinitelyTyped /// - -interface AutosizeOptions { - className?: string; - append?: string; - callback?: Function; +declare module autosize { + interface AutosizeStatic { + (el: Element): void; + (el: NodeList): void; + (el: JQuery): void; + } } -interface Autosize { - (): JQuery; - (options: AutosizeOptions): JQuery; -} +declare var autosize: autosize.AutosizeStatic; -interface JQuery { - autosize: Autosize; -} \ No newline at end of file +declare module 'autosize' { + export = autosize; +} From 30c4a6ea1297b1c18bafbe0284d653f7dfa4a213 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Wed, 8 Jul 2015 17:39:45 +0900 Subject: [PATCH 070/144] Support Options#excludeSwitches --- selenium-webdriver/selenium-webdriver-tests.ts | 1 + selenium-webdriver/selenium-webdriver.d.ts | 10 ++++++++++ 2 files changed, 11 insertions(+) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 73ea8561e7..cbe4db9267 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -14,6 +14,7 @@ function TestChromeOptions() { 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"); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index c4af933c96..c48f16af0b 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -62,6 +62,16 @@ declare module chrome { 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 From 6c8a0d02aa4f8e7725543a1b853b490826d3b361 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Wed, 8 Jul 2015 17:53:08 +0900 Subject: [PATCH 071/144] Add Options#setPerfLoggingPrefs --- .../selenium-webdriver-tests.ts | 1 + selenium-webdriver/selenium-webdriver.d.ts | 34 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index cbe4db9267..4a08523c25 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -20,6 +20,7 @@ function TestChromeOptions() { options = options.setChromeLogFile("logfile"); options = options.setLocalState("state"); 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(); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index c48f16af0b..40a6bf2164 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -33,6 +33,14 @@ declare module chrome { prefs?: any; } + interface IPerfLoggingPrefs { + enableNetwork: boolean; + enablePage: boolean; + enableTimeline: boolean; + tracingCategories: string; + bufferUsageReportingInterval: number; + } + /** * Class for managing ChromeDriver specific options. */ @@ -124,6 +132,32 @@ declare module chrome { */ 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 From a766e1aef7c282c9ec9cc84a8daf31874496b5c2 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Wed, 8 Jul 2015 18:06:56 +0900 Subject: [PATCH 072/144] add Options#android* --- .../selenium-webdriver-tests.ts | 6 ++ selenium-webdriver/selenium-webdriver.d.ts | 63 +++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 4a08523c25..c743693022 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -19,6 +19,12 @@ function TestChromeOptions() { 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" }); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 40a6bf2164..25d22a7bdb 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -168,6 +168,69 @@ declare module chrome { 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. From 11daee6f62a67e3aed8a13739dd032ccef84cc3f Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Wed, 8 Jul 2015 18:14:21 +0900 Subject: [PATCH 073/144] Sort asserting order to following the definition --- selenium-webdriver/selenium-webdriver-tests.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index c743693022..13f42c6f8c 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -39,13 +39,13 @@ function TestServiceBuilder() { builder = new chrome.ServiceBuilder("exe"); var anything: any = builder.build(); - builder = builder.enableVerboseLogging(); + builder = builder.usingPort(8080); 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.setUrlBasePath("path"); - builder = builder.usingPort(8080); builder = builder.withEnvironment({ "A": "a", "B": "b" }); } From 666442816f16c1cb2296f11443a3e44d2dd5f7d0 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Wed, 8 Jul 2015 18:15:18 +0900 Subject: [PATCH 074/144] Add ServiceBuilder#setAdbPort --- selenium-webdriver/selenium-webdriver-tests.ts | 1 + selenium-webdriver/selenium-webdriver.d.ts | 11 +++++++++++ 2 files changed, 12 insertions(+) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 13f42c6f8c..4ad2a7be60 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -40,6 +40,7 @@ function TestServiceBuilder() { var anything: any = builder.build(); builder = builder.usingPort(8080); + builder = builder.setAdbPort(5037); builder = builder.loggingTo("path"); builder = builder.enableVerboseLogging(); builder = builder.setNumHttpThreads(5); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 25d22a7bdb..3950f78142 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -296,6 +296,17 @@ declare module chrome { 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. From d81624eaff638984450893a210ddf8f49f6f9a74 Mon Sep 17 00:00:00 2001 From: Kristof Mattei Date: Wed, 8 Jul 2015 13:12:06 +0200 Subject: [PATCH 075/144] Fixed the casing of the definition --- auth0/auth0.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/auth0/auth0.d.ts b/auth0/auth0.d.ts index 5d3149ead4..cefc35b99a 100644 --- a/auth0/auth0.d.ts +++ b/auth0/auth0.d.ts @@ -15,7 +15,7 @@ interface Location { /** This is the interface for the main Auth0 client. */ interface Auth0Static { - + new(options: Auth0ClientOptions): Auth0Static; changePassword(options: any, callback?: Function): void; decodeJwt(jwt: string): any; @@ -40,7 +40,7 @@ interface Auth0ClientOptions { callbackOnLoactionHash?: boolean; domain: string; forceJSONP?: boolean; -} +} /** Represents a normalized UserProfile. */ interface Auth0UserProfile { @@ -128,6 +128,6 @@ interface Auth0DelegationToken { declare var Auth0: Auth0Static; -declare module "Auth0" { +declare module "auth0" { export = Auth0 } From 8eab092b037dceea9194ca3c297461e620b8b9b1 Mon Sep 17 00:00:00 2001 From: David Sidlinger Date: Wed, 8 Jul 2015 10:39:45 -0500 Subject: [PATCH 076/144] Allow string or boolean for `fallbackLng` --- i18next/i18next.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/i18next/i18next.d.ts b/i18next/i18next.d.ts index f390954591..3d24c9b967 100644 --- a/i18next/i18next.d.ts +++ b/i18next/i18next.d.ts @@ -23,7 +23,7 @@ interface I18nextOptions { preload?: string[]; // Default value: [] lowerCaseLng?: boolean; // Default value: false returnObjectTrees?: boolean; // Default value: false - fallbackLng?: string; // Default value: 'dev' + fallbackLng?: string|boolean; // Default value: 'dev' detectLngQS?: string; // Default value: 'setLng' ns?: any; // Default value: 'translation' (string), can also be an object nsseparator?: string; // Default value: '::' @@ -135,4 +135,4 @@ declare module 'i18next' { declare module 'i18next-client' { export = i18n; -} \ No newline at end of file +} From 886bedbec7b6e2e2a80938ef60dd5012cfd7a289 Mon Sep 17 00:00:00 2001 From: Ben Tesser Date: Wed, 8 Jul 2015 15:14:03 -0400 Subject: [PATCH 077/144] Typings for angular-ui-grid. --- ui-grid/ui-grid-tests.ts | 88 ++++++ ui-grid/ui-grid.d.ts | 659 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 747 insertions(+) create mode 100644 ui-grid/ui-grid-tests.ts create mode 100644 ui-grid/ui-grid.d.ts diff --git a/ui-grid/ui-grid-tests.ts b/ui-grid/ui-grid-tests.ts new file mode 100644 index 0000000000..6bdae2f64c --- /dev/null +++ b/ui-grid/ui-grid-tests.ts @@ -0,0 +1,88 @@ +/// +/// + +var columnDef: uiGrid.IColumnDef; +columnDef.aggregationHideLabel = true; +columnDef.aggregationHideLabel = false; +columnDef.aggregationType = 1; +columnDef.aggregationType = function () { return 1; }; +columnDef.cellClass = 'test'; +columnDef.cellClass = function (gridRow: uiGrid.IGridRow, gridCol: uiGrid.IGridColumn, index: number) { + return 'pizza'; +}; +columnDef.cellFilter = 'date'; +columnDef.cellTemplate = '

hello
'; +columnDef.cellTooltip = 'blah'; +columnDef.cellTooltip = function (gridRow: uiGrid.IGridRow, gridCol: uiGrid.IGridColumn) { + return 'blah'; +}; +columnDef.displayName = 'Jumper'; +columnDef.enableColumnMenu = false; +columnDef.enableColumnMenus = false; +columnDef.enableFiltering = true; +columnDef.enableHiding = false; +columnDef.enableSorting = true; +columnDef.field = 'blam'; +columnDef.filter = { + condition: 2, + term: 'yes', + placeholder: 'testing', + noTerm: false, + flags: { + caseSensitive: true + }, + type: 1, + selectOptions: [{value: 4, label: 'test'}], + disableCancelButton: false +}; +columnDef.filterCellFiltered = false; +columnDef.filterHeaderTemplate = '
'; +columnDef.filters = [columnDef.filter]; +columnDef.footerCellClass = + (gridRow: uiGrid.IGridRow, rowRenderIndex: number, gridCol: uiGrid.IGridColumn, colRenderIndex: number) => { + return 'blah'; + }; +columnDef.footerCellClass = 'theClass'; +columnDef.footerCellFilter = 'currency:$'; +columnDef.footerCellTemplate = '
'; +columnDef.headerCellClass = + (gridRow: uiGrid.IGridRow, rowRenderIndex: number, gridCol: uiGrid.IGridColumn, colRenderIndex: number) => { + return 'blah'; + }; +columnDef.headerCellClass = 'classy'; +columnDef.headerCellFilter = 'currency:$'; +columnDef.headerCellTemplate = '
'; +columnDef.headerTooltip = false; +columnDef.headerTooltip = 'The Tooltip'; +columnDef.headerTooltip = (col: uiGrid.IGridColumn) => { + return 'tooly'; +}; +columnDef.maxWidth = 200; +columnDef.menuItems = [{ + title: 'title', + icon: 'ico', + action: ($event: ng.IAngularEvent) => { + alert('click'); + }, + shown: () => { return true; }, + active: () => { return false }, + context: {a: 'lala'}, + leaveOpen: false +}]; +columnDef.minWidth = 100; +columnDef.name = 'MyColumn'; +columnDef.sort = { + direction: 0, + ignoreSort: false, + priority: 1 +}; +columnDef.sortCellFiltered = false; +columnDef.sortingAlgorithm = (a: any, b: any) => { + return -1; +}; +columnDef.suppressRemoveSort = false; +columnDef.type = 'Date'; +columnDef.visible = true; +columnDef.width = 100; +columnDef.width = '*'; + diff --git a/ui-grid/ui-grid.d.ts b/ui-grid/ui-grid.d.ts new file mode 100644 index 0000000000..19d0a2c7f2 --- /dev/null +++ b/ui-grid/ui-grid.d.ts @@ -0,0 +1,659 @@ +// Type definitions for ui-grid +// Project: http://www.ui-grid.info/ +// Definitions by: Ben Tesser +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// These are very definitely preliminary. Please feel free to improve. + +// Changelog: +// 7/8/2015 ui-grid v3.0.0-rc.22-482dc67 +// Added primary interfaces for row, column, api, grid, columnDef, and gridOptions. Needs more tests! + +/// + +declare module uiGrid { + export interface IGridInstance { + appScope?: ng.IScope; + columnFooterHeight?: number; + footerHeight?: number; + isScrollingHorizontally?: boolean; + isScrollingVertically?: boolean; + scrollDirection?: number; + addRowHeaderColumn(column: IGridColumn): void; + assignTypes(): void; + buildColumnDefsFromData(rowBuilder: IRowBuilder): void; + buildColumns(options: IBuildColumnsOptions): ng.IPromise; + buildStyles(): void; + callDataChangeCallbacks(type: number): void; + clearAllFilters(refreshRows: boolean, clearConditions: boolean, clearFlags: boolean): void; + columnRefreshCallback(name: string): void; + createLeftContainer(): void; + createRightContainer(): void; + flagScrollingHorizontally(): void; + flagScrollingVertically(): void; + getCellDisplayValue(row: IGridRow, col: IGridColumn): string; + getCellValue(row: IGridRow, col: IGridColumn): any; + getColDef(name: string): IColumnDef; + getColumn(name: string): IGridColumn; + getColumnSorting(): Array; + getGridQualifiedColField(col: IGridColumn): any; + getOnlyDataColumns(): Array; + getRow(rowEntity: any, rows?: Array): IGridRow; + handleWindowResize(): void; + hasLeftContainer(): boolean; + hasRightContainer(): boolean; + hasLeftContainerColumns(): boolean; + hasRightContainerColumns(): boolean; + isRTL(): boolean; + isRowHeaderColumn(col: IGridColumn): boolean; + modifyRows(): void; + notifyDataChange(type: string): void; + precompileCellTemplates(): void; + processRowBuilders(gridRow: IGridRow): IGridRow; + processRowsCallback(name: string): void; + queueGridRefresh(): void; + queueRefresh(): void; + redrawCanvas(rowsAdded?: boolean): void; + refresh(rowsAltered?: boolean): void; + refreshCanvas(buildStyles?: boolean): ng.IPromise; + refreshRows(): ng.IPromise; + registerColumnBuilder(columnBuilder: IColumnBuilder): void; + registerColumnsProcessor(columnProcessor: IColumnProcessor, priority: number): void; + registerDataChangeCallback(callback: (grid: IGridInstance) => void, types: Array): Function; + registerRowBuilder(rowBuilder: IRowBuilder): void; + registerRowsProcessor(rowProcessor: IRowProcessor, priority: number): void; + registerStyleComputation(styleComputation: ($scope: ng.IScope) => string): void; + removeRowsProcessor(rows: IRowProcessor): void; + resetColumnSorting(excludedColumn: IGridColumn): void; + scrollTo(rowEntity: any, colDef: IColumnDef): ng.IPromise; + scrollToIfNecessary(gridRow: IGridRow, gridCol: IGridColumn): ng.IPromise; + sortColumn(column: IGridColumn, direction?: number, add?: boolean): ng.IPromise; + updateCanvasHeight(): void; + updateFooterHeightCallback(name: string): void; + } + export interface IBuildColumnsOptions { + orderByColumnDefs?: boolean; + } + export interface IColumnBuilder { + (colDef: IColumnDef, col: IGridColumn, gridOptions: IGridOptions): void; + } + export interface IRowBuilder { + (row: IGridRow, gridOptions: IGridOptions): void; + } + export interface IRowProcessor { + (renderedRowsToProcess: Array, columns: Array): Array; + } + export interface IColumnProcessor { + (renderedColumnsToProcess: Array, rows: Array): Array; + } + export interface IGridOptions { + aggregationCalcThrottle?: number; + appScopeProvider?: ng.IScope; + columnDefs?: IColumnDef; + columnFooterHeight?: number; + columnVirtualizationThreshold?: number; + data?: Array; + enableColumnMenus?: boolean; + enableFiltering?: boolean; + enableHorizontalScrollbar?: boolean; + enableMinHeightCheck?: boolean; + enableRowHashing?: boolean; + enableSorting?: boolean; + enableVerticalScrollbar?: boolean; + excessColumns?: number; + excessRows?: number; + excludeProperties?: Array; + flatEntityAccess?: boolean; + footerTemplate?: string; + gridFooterTemplate?: string; + gridMenuCustomItems?: Array; + gridMenuShowHideColumns?: boolean; + gridMenuTitleFilter: (title: string) => ng.IPromise | string; + headerTemplate?: string; + horizontalScrollThreshold?: number; + infiniteScrollDown?: boolean; + infiniteScrollRowsFromEnd?: number; + infiniteScrollUp?: boolean; + maxVisibleColumnCount?: number; + minRowsToShow?: number; + minimumColumnSize?: number; + onRegisterApi: (gridApi: IGridApi) => void; + rowHeight?: number; + rowTemplate?: string; + scrollDebounce?: number; + scrollThreshold?: number; + showColumnFooter?: boolean; + showGridFooter?: boolean; + showHeader?: boolean; + useExternalFiltering?: boolean; + useExternalSorting?: boolean; + virtualizationThreshold?: number; + wheelScrollThrottle?: number; + getRowIdentity(): any; + rowEquality(entityA: IGridRow, entityB: IGridRow): boolean; + rowIdentity(): any; + } + export interface IGridApiConstructor { + new(grid: IGridInstance): IGridApi; + } + export interface IGridApi { + /** + * Registers a new event for the given feature. The event will get a .raise and .on prepended to it + * + * .raise.eventName() - takes no arguments + * + * .on.eventName(scope, callBackFn, _this) + * scope - a scope reference to add a deregister call to the scopes .$on('destroy'). + * Scope is optional and can be a null value, but in this case you must deregister it yourself via the returned + * deregister function + * callBackFn - The function to call + * _this - optional this context variable for callbackFn. If omitted, grid.api will be used for the context + * + * .on.eventName returns a dereg function that will remove the listener. It's not necessary to use it as the + * listener will be removed when the scope is destroyed. + * @param featureName name of the feature that raises the event + * @param eventName name of the event + */ + registerEvent(featureName: string, eventName: string): void; + /** + * Registers features and events from a simple objectMap. + * eventObjectMap must be in this format (multiple features allowed) + * @param eventObjectMap map of feature/event names + */ + registerEventsFromObject(eventObjectMap: any): void; + /** + * Registers a new event for the given feature + * @param featureName name of the feature + * @param methodName name of the method + * @param callBackFn function to execute + * @param _this binds to callBackFn. Defaults to gridApi.grid + */ + registerMethod(featureName: string, methodName: string, callBackFn: Function, _this: any): void; + /** + * Registers features and methods from a simple objectMap. + * eventObjectMap must be in this format (multiple features allowed) + * {featureName: { methodNameOne:function(args){}, methodNameTwo:function(args){} } + * @param eventObjectMap map of feature/event names + * @param _this binds this to _this for all functions. Defaults to gridApi.grid + */ + registerMethodsFromObject(eventObjectMap: any, _this: any): void; + /** + * Used to execute a function while disabling the specified event listeners. + * Disables the listenerFunctions, executes the callbackFn, and then enables the listenerFunctions again + * @param listenerFuncs listenerFunc or array of listenerFuncs to suppress. + * These must be the same functions that were used in the .on.eventName method + * @param callBackFn function to execute + */ + suppressEvents(listenerFuncs: Function | Array, callBackFn: Function): void; + } + export interface IGridRowConstructor { + /** + * GridRow is the viewModel for one logical row on the grid. + * A grid Row is not necessarily a one-to-one relation to gridOptions.data. + * @param entity the array item from GridOptions.data + * @param index the current position of the row in the array + * @param reference to the parent grid + */ + new(entity: any, index: number, reference: IGridInstance): IGridRow; + } + export interface IGridRow { + /** A reference to an item in gridOptions.data[] */ + entity: any; + /** A reference back to the grid */ + grid: IGridInstance; + /** + * height of each individual row. changing the height will flag all + * row renderContainers to recalculate their canvas height + */ + height: number; + /** uniqueId of row */ + uid: string; + /** if true, row will be rendered */ + visible: boolean; + // Additional features enabled by other modules + /** enable editing on row, grouping for example might disable editing on group header rows */ + enableCellEdit: boolean; + /** + * Enable row selection for this row, only settable by internal code. + * + * The grouping feature, for example, might set group header rows to not be selectable. + * Defaults to true + * @default true + */ + enableSelection: boolean; + /** + * Selected state of row. + * Should be readonly. + * Make any changes to selected state using setSelected(). + * Defaults to false + * + * @readonly + * @default false + */ + isSelected: boolean; + /** + * If set to false, then don't export this row, + * notwithstanding visible or other settings + * Defaults to true + * @default true + */ + exporterEnableExporting: boolean; + /** + * Sets the isSelected property and updates the selectedCount + * Changes to isSelected state should only be made via this function + * @param selected Value to set + */ + setSelected(selected: boolean): void; + /** + * Clears an override on the row that forces it to always be invisible. + * Emits the rowsVisibleChanged event if it changed the row visibility. + * + * This method can be called from the api, passing in the gridRow we want altered. + * It should really work by calling gridRow.clearRowInvisible, + * but that's not the way I coded it, and too late to change now. + * Changed to just call the internal function row.clearThisRowInvisible(). + * @param row the row we want to clear the invisible flag + */ + clearRowInvisible(row: IGridRow): void; + /** + * Clears any override on the row visibility, returning it to normal visibility calculations. + * Emits the rowsVisibleChanged event + * @param reason the reason (usually the module) for the row to be invisible. E.g. grouping, user, filter + * @param fromRowsProcessor whether we were called from a rowsProcessor, passed through to evaluateRowVisibility + */ + clearRowInvisible(reason: string, fromRowsProcessor: boolean): void; + /** + * Determines whether the row should be visible based on invisibleReason, + * and if it changes the row visibility, then emits the rowsVisibleChanged event. + * Queues a grid refresh, but doesn't call it directly to avoid hitting lots of + * grid refreshes. + */ + evaluateRowVisibility(fromRowProcessor: boolean): void; + /** + * returns the qualified field name minus the row path ie: entity.fieldA + * @param col column instance + * @returns resulting name that can be evaluated against a row + */ + getEntityQualifiedColField(col: IGridColumn): string; + /** + * returns the qualified field name as it exists on scope ie: row.entity.fieldA + * @param col column instance + * @returns resulting name that can be evaluated on scope + */ + getQualifiedColField(col: IGridColumn): string; + /** + * Sets an override on the row that forces it to always be invisible. + * Emits the rowsVisibleChanged event if it changed the row visibility. + * This method can be called from the api, passing in the gridRow we want altered. + * It should really work by calling gridRow.setRowInvisible, + * but that's not the way I coded it, and too late to change now. + * Changed to just call the internal function row.setThisRowInvisible(). + * @param row the row we want to set to invisible + */ + setRowInvisible(row: IGridRow): void; + /** + * Sets an override on the row that forces it to always be invisible. + * Emits the rowsVisibleChanged event if it changed the row visibility + * @param reason the reason (usually the module) for the row to be invisible. E.g. grouping, user, filter + * @param fromRowsProcessor whether we were called from a rowsProcessor, passed through to evaluateRowVisibility + */ + setThisRowInvisible(reason: string, fromRowsProcessor: boolean): void; + } + + export interface IGridColumnConstructor { + /** + * Represents the viewModel for each column. + * Any state or methods needed for a Grid Column are defined on this prototype + * @param gridCol Column definition + * @param index the current position of the column in the array + * @param grid reference to the grid + */ + new(gridCol: IColumnDef, index: number, grid: IGridInstance): IGridColumn; + } + + export interface IGridColumn { + /** + * Column name that will be shown in the header. + * If displayName is not provided then one is generated using the name. + */ + displayName?: string; + /** + * field must be provided if you wish to bind to a property in the data source. + * Should be an angular expression that evaluates against grid.options.data array element. + * Can be a complex expression: employee.address.city, or can be a function: employee.getFullAddress(). + * See the angular docs on binding expressions. + */ + field?: string; + /** Filter on this column */ + filter?: IFilterOptions; + /** Filters for this column. Includes 'term' property bound to filter input elements */ + filters?: Array; + name?: string; + /** Algorithm to use for sorting this column. Takes 'a' and 'b' parameters like any normal sorting function. */ + sortingAlgorithm?: (a: any, b: any) => number; + /** + * Initializes a column + * @param colDef the column def to associate with this column + * @param uid The unique and immutable uid we'd like to allocate to this column + * @param grid the grid we'd like to create this column in + */ + GridColumn(colDef: IColumnDef, uid: number, grid: IGridInstance): void; + /** + * Gets the aggregation label from colDef.aggregationLabel if specified or by using i18n, + * including deciding whether or not to display based on colDef.aggregationHideLabel. + * @param label the i18n lookup value to use for the column label + */ + getAggregationText(label: string): void; + /** + * gets the aggregation value based on the aggregation type for this column. + * Debounced using scrollDebounce option setting + */ + getAggregationValue(): string; + /** + * Returns the class name for the column + * @param prefixDot if true, will return .className instead of className + */ + getColClass(prefixDot: boolean): string; + /** Returns the class definition for th column */ + getColClassDefinition(): string; + /** + * Returns the render container object that this column belongs to. + * Columns will be default be in the body render container + * if they aren't allocated to one specifically. + */ + getRenderContainer(): any; // @todo replace with interface for render container + /** Hides the column by setting colDef.visible = false */ + hideColumn(): void; + /** Returns true if column is in the left render container */ + isPinnedLeft(): boolean; + /** Returns true if column is in the right render container */ + isPinnedRight(): boolean; + /** + * Sets a property on the column using the passed in columnDef, + * and setting the defaultValue if the value cannot be found on the colDef + * @param colDef the column def to look in for the property value + * @param propName the property name we'd like to set + * @param defaultValue the value to use if the colDef doesn't provide the setting + */ + setPropertyOrDefault(colDef: IColumnDef, propName: string, defaultValue: any): void; + /** Makes the column visible by setting colDef.visible = true */ + showColumn(): void; + /** + * Moves settings from the columnDef down onto the column, and sets properties as appropriate + * @param colDef the column def to look in for property value + * @param isNew whether the column is being newly created, if not we're updating an existing + * column, and some items such as the sort shouldn't be copied down + */ + updateColumnDef(colDef: IColumnDef, isNew: boolean): void; + } + + /** + * Definition / configuration of an individual column, + * which would typically be one of many column definitions within the + * gridOptions.columnDefs array + */ + export interface IColumnDef { + /** + * defaults to false + * if set to true hides the label text in the aggregation footer, so only the value is displayed. + */ + aggregationHideLabel?: boolean; + /** + * The aggregation that you'd like to show in the columnFooter for this column. + * Valid values are in uiGridConstants, and currently include: + * uiGridConstants.aggregationTypes.count, uiGridConstants.aggregationTypes.sum, + * uiGridConstants.aggregationTypes.avg, uiGridConstants.aggregationTypes.min, + * uiGridConstants.aggregationTypes.max. + * + * You can also provide a function as the aggregation type, + * in this case your function needs to accept the full set of visible rows, + * and return a value that should be shown + */ + aggregationType: number | Function; + /** + * cellClass can be a string specifying the class to append to a cell + * or it can be a function(row,rowRenderIndex, col, colRenderIndex) + * that returns a class name + */ + cellClass?: string | ICellClassGetter; + /** cellFilter is a filter to apply to the content of each cell */ + cellFilter?: string; + /** + * a custom template for each cell in this column. + * The default is ui-grid/uiGridCell. + * If you are using the cellNav feature, + * this template must contain a div that can receive focus. + */ + cellTemplate?: string; + /** + * Whether or not to show a tooltip when a user hovers over the cell. + * If set to false, no tooltip. + * If true, the cell value is shown in the tooltip (useful if you have long values in your cells), + * if a function then that function is called passing in the row and the col cellTooltip(row, col) + * and the return value is shown in the tooltip, + * if it is a static string then displays that static string. + * Defaults to false + * @default false + */ + cellTooltip?: boolean | string | ICellTooltipGetter; + /** + * Column name that will be shown in the header. + * If displayName is not provided then one is generated using the name. + */ + displayName?: string; + /** + * if column menus are enabled, controls the column menus for this specific column + * (i.e. if gridOptions.enableColumnMenus, then you can control column menus using this option. + * If gridOptions.enableColumnMenus === false then you get no column menus irrespective of the value of this + * option + * ). Defaults to true. + * @default true + */ + enableColumnMenu?: boolean; + /** + * Override for column menus everywhere - if set to false then you get no column menus. + * Defaults to true + * @default true + */ + enableColumnMenus?: boolean; + /** turn off filtering for an individual column, where you've turned on filtering for the overall grid */ + enableFiltering?: boolean; + /** + * When set to false, this setting prevents a user from hiding the column using the column menu or the grid + * menu. + * @default true + */ + enableHiding?: boolean; + /** + * When enabled, this setting adds sort widgets to the column header, allowing sorting of the data in the + * individual column. + * @default true + */ + enableSorting?: boolean; + /** + * field must be provided if you wish to bind to a property in the data source. + * Should be an angular expression that evaluates against grid.options.data array element + * Can be a complex expression: employee.address.city, or can be a function: employee.getFullAddress(). + * See the angular docs on binding expressions. + */ + field?: string; + /** + * Specify a single filter field on this column. + * A filter consists of a condition, a term, and a placeholder: + */ + filter?: IFilterOptions; + /** + * @default false + * When true uiGrid will apply the cellFilter before applying search filters + */ + filterCellFiltered?: boolean; + /** + * a custom template for the filter input. The default is ui-grid/ui-grid-filter + */ + filterHeaderTemplate?: string; + /** Specify multiple filter fields */ + filters?: Array; + /** + * footerCellClass can be a string specifying the class to append to a cell or it can be + * a function(row,rowRenderIndex, col, colRenderIndex) that returns a class name + */ + footerCellClass?: string | IHeaderFooterCellClassGetter; + /** footerCellFilter is a filter to apply to the content of the column footer */ + footerCellFilter?: string; + /** a custom template for the footer for this column. The default is ui-grid/uiGridFooterCell */ + footerCellTemplate?: string; + /** + * headerCellClass can be a string specifying the class to append to a cell or it can be + * a function(row,rowRenderIndex, col, colRenderIndex) that returns a class name + */ + headerCellClass?: string | IHeaderFooterCellClassGetter; + /** headerCellFilter is a filter to apply to the content of the column header */ + headerCellFilter?: string; + /** a custom template for the header for this column. The default is ui-grid/uiGridHeaderCell */ + headerCellTemplate?: string; + /** + * Whether or not to show a tooltip when a user hovers over the header cell. + * If set to false, no tooltip. + * If true, the displayName is shown in the tooltip + * (useful if you have long values in your headers), + * if a function then that function is called passing in the row and the col + * headerTooltip( col ), and the return value is shown in the tooltip, + * if a static string then shows that static string. + * @default false + */ + headerTooltip?: boolean | string | IHeaderTooltipGetter; + /** sets the maximum column width */ + maxWidth?: number; + /** used to add menu items to a column. Refer to the tutorial on this functionality */ + menuItems?: Array; + /** Sets the minimum column width */ + minWidth?: number; + /** + * (mandatory) each column should have a name, + * although for backward compatibility with 2.x name can be omitted if field is present + */ + name?: string; + /** An object of sort information */ + sort?: ISortInfo; + /** + * @default false + * When true uiGrid will apply the cellFilter before sorting the data + * Note that when using this option uiGrid will assume that the displayed value is a string, + * and use the sortAlpha sortFn. + * It is possible to return a non-string value from an angularjs filter, + * in which case you should define a sortingAlgorithm for the column + * which handles the returned type. + * You may specify one of the sortingAlgorithms found in the rowSorter service. + */ + sortCellFiltered?: boolean; + /** Algorithm to use for sorting this column */ + sortingAlgorithm?: (a: any, b: any) => number; + /** + * When enabled, this setting hides the removeSort option in the menu, + * and prevents users from manually removing the sort + * @default false + */ + suppressRemoveSort?: boolean; + /** + * the type of the column, used in sorting. If not provided then the grid will guess the type. + * Add this only if the grid guessing is not to your satisfaction. + * Note that if you choose date, your dates should be in a javascript date type + * One of: + * 'string', 'boolean', 'number', 'date', 'object', 'numberStr' + */ + type?: string; + /** + * sets whether or not the column is visible + * @default true + */ + visible?: boolean; + /** + * sets the column width. Can be either a number or a percentage, or an * for auto. + */ + width?: number | string; + } + + export interface ICellClassGetter { + (gridRow?: IGridRow, gridCol?: IGridColumn, colRenderIndex?: number): string; + } + + export interface ICellTooltipGetter { + (gridRow: IGridRow, gridCol: IGridColumn): string; + } + export interface IHeaderTooltipGetter { + (gridCol: IGridColumn): string; + } + export interface IHeaderFooterCellClassGetter { + (gridRow: IGridRow, rowRenderIndex: number, gridCol: IGridColumn, colRenderIndex: number): string; + } + export interface IMenuItem { + /** controls the title that is displayed in the menu */ + title?: string; + /** the icon shown alongside that title */ + icon?: string; + /** the method to call when the menu is clicked */ + action?: ($event: ng.IAngularEvent) => void; + /** a function to evaluate to determine whether or not to show the item */ + shown?: () => boolean; + /** a function to evaluate to determine whether or not the item is currently selected */ + active?: () => boolean; + /** context to pass to the action function, available in this.context in your handler */ + context?: any; + /** if set to true, the menu should stay open after the action, defaults to false */ + leaveOpen?: boolean; + } + export interface ISortInfo { + direction?: number; + ignoreSort?: boolean; + priority?: number; + } + + export interface IFilterOptions { + /** + * condition defines how rows are chosen as matching the filter term. + * This can be set to one of the constants in uiGridConstants.filter, + * or you can supply a custom filter function that gets passed the + * following arguments: [searchTerm, cellValue, row, column]. + */ + condition?: number; + /** + * If set, the filter field will be pre-populated with this value + */ + term?: string; + /** String that will be set to the .placeholder attribute */ + placeholder?: string; + /** + * set this to true if you have defined a custom function in condition, + * and your custom function doesn't require a term + * (so it can run even when the term is null) + */ + noTerm?: boolean; + /** + * only flag currently available is caseSensitive, set to false if you don't want case sensitive matching + */ + flags?: IFilterFlags; + /** + * defaults to uiGridConstants.filter.INPUT, which gives a text box. If set to uiGridConstants.filter.SELECT + * then a select box will be shown with options selectOptions + */ + type?: number; + /** + * options in the format [{ value: 1, label: 'male' }]. No i18n filter is provided, you need to perform the i18n + * on the values before you provide them + */ + selectOptions?: Array; + /** + * If set to true then the 'x' button that cancels/clears the filter will not be shown. + * @default false + */ + disableCancelButton?: boolean; + } + export interface ISelectOption { + value: number; + label: string; + } + + export interface IFilterFlags { + caseSensitive?: boolean; + } +} From cb91a5b2c7b64bf627e036b5f8e8c7ed9af62179 Mon Sep 17 00:00:00 2001 From: Simon Sarris Date: Wed, 8 Jul 2015 16:33:31 -0400 Subject: [PATCH 078/144] GoJS typescript updated for 1.5.2 from the GoJS developers --- goJS/goJS-tests.ts | 434 +++--- goJS/goJS.d.ts | 3715 +++++++++++++++++++++++++++----------------- 2 files changed, 2540 insertions(+), 1609 deletions(-) diff --git a/goJS/goJS-tests.ts b/goJS/goJS-tests.ts index 18c37df251..bfde3b87f8 100644 --- a/goJS/goJS-tests.ts +++ b/goJS/goJS-tests.ts @@ -1,241 +1,243 @@ -// Test file for GoJS.d.ts +// Test file for goJS.d.ts // This is taken from http://gojs.net/latest/samples/basic.html -/* Copyright (C) 1998 - 2013 by Northwoods Software Corporation. */ +/* Copyright (C) 1998-2015 by Northwoods Software Corporation. */ -/// +/// function init() { - var $ = go.GraphObject.make; // for conciseness in defining templates + var $ = go.GraphObject.make; // for conciseness in defining templates - var myDiagram = - $(go.Diagram, "myDiagram", // create a Diagram for the DIV HTML element - { - // position the graph in the middle of the diagram - initialContentAlignment: go.Spot.Center, + var myDiagram: go.Diagram = + $(go.Diagram, "myDiagram", // create a Diagram for the DIV HTML element + { + // position the graph in the middle of the diagram + initialContentAlignment: go.Spot.Center, - // allow double-click in background to create a new node - "clickCreatingTool.archetypeNodeData": { text: "Node", color: "white" }, + // allow double-click in background to create a new node + "clickCreatingTool.archetypeNodeData": { text: "Node", color: "white" }, - // allow Ctrl-G to call groupSelection() - "commandHandler.archetypeGroupData": { text: "Group", isGroup: true, color: "blue" } - }); + // allow Ctrl-G to call groupSelection() + "commandHandler.archetypeGroupData": { text: "Group", isGroup: true, color: "blue" }, - // Define the appearance and behavior for Nodes: + // enable undo & redo + "undoManager.isEnabled": true + }); - // First, define the shared context menu for all Nodes, Links, and Groups. + // Define the appearance and behavior for Nodes: - // To simplify this code we define a function for creating a context menu button: - function makeButton(text: string, action, visiblePredicate?) { - if (visiblePredicate === undefined) visiblePredicate = function() { return true; }; - return $("ContextMenuButton", - $(go.TextBlock, text), - { click: action }, - new go.Binding("visible", "", visiblePredicate).ofObject()); - } + // First, define the shared context menu for all Nodes, Links, and Groups. - // a context menu is an Adornment with a bunch of buttons in them - var partContextMenu = - $(go.Adornment, "Vertical", - makeButton("Properties", - function(e, obj) { // the OBJ is this Button - var contextmenu = obj.part; // the Button is in the context menu Adornment - var part = contextmenu.adornedPart; // the adornedPart is the Part that the context menu adorns - // now can do something with PART, or with its data, or with the Adornment (the context menu) - if (part instanceof go.Link) alert(linkInfo(part.data)); - else if (part instanceof go.Group) alert(groupInfo(contextmenu)); - else alert(nodeInfo(part.data)); - }), - makeButton("Cut", - function(e, obj) { e.diagram.commandHandler.cutSelection(); }, - function(o) { return o.diagram.commandHandler.canCutSelection(); }), - makeButton("Copy", - function(e, obj) { e.diagram.commandHandler.copySelection(); }, - function(o) { return o.diagram.commandHandler.canCopySelection(); }), - makeButton("Paste", - function(e, obj) { e.diagram.commandHandler.pasteSelection(e.diagram.lastInput.documentPoint); }, - function(o) { return o.diagram.commandHandler.canPasteSelection(); }), - makeButton("Delete", - function(e, obj) { e.diagram.commandHandler.deleteSelection(); }, - function(o) { return o.diagram.commandHandler.canDeleteSelection(); }), - makeButton("Undo", - function(e, obj) { e.diagram.commandHandler.undo(); }, - function(o) { return o.diagram.commandHandler.canUndo(); }), - makeButton("Redo", - function(e, obj) { e.diagram.commandHandler.redo(); }, - function(o) { return o.diagram.commandHandler.canRedo(); }), - makeButton("Group", - function(e, obj) { e.diagram.commandHandler.groupSelection(); }, - function(o) { return o.diagram.commandHandler.canGroupSelection(); }), - makeButton("Ungroup", - function(e, obj) { e.diagram.commandHandler.ungroupSelection(); }, - function(o) { return o.diagram.commandHandler.canUngroupSelection(); }) - ); - - function nodeInfo(d) { // Tooltip info for a node data object - var str = "Node " + d.key + ": " + d.text + "\n"; - if (d.group) - str += "member of " + d.group; - else - str += "top-level node"; - return str; - } - - // These nodes have text surrounded by a rounded rectangle - // whose fill color is bound to the node data. - // The user can drag a node by dragging its TextBlock label. - // Dragging from the Shape will start drawing a new link. - myDiagram.nodeTemplate = - $(go.Node, "Auto", - { locationSpot: go.Spot.Center }, - $(go.Shape, "RoundedRectangle", - { - fill: "white", - portId: "", cursor: "pointer", // the Shape is the port, not the whole Node - // allow all kinds of links from and to this port - fromLinkable: true, fromLinkableSelfNode: true, fromLinkableDuplicates: true, - toLinkable: true, toLinkableSelfNode: true, toLinkableDuplicates: true - }, - new go.Binding("fill", "color")), - $(go.TextBlock, - { - margin: 4, // make some extra space for the shape around the text - isMultiline: false, // don't allow newlines in text - editable: true // allow in-place editing by user - }, - new go.Binding("text", "text").makeTwoWay()), // the label shows the node data's text - { // this tooltip Adornment is shared by all nodes - toolTip: - $(go.Adornment, "Auto", - $(go.Shape, { fill: "#FFFFCC" }), - $(go.TextBlock, { margin: 4 }, // the tooltip shows the result of calling nodeInfo(data) - new go.Binding("text", "", nodeInfo)) - ), - // this context menu Adornment is shared by all nodes - contextMenu: partContextMenu - } - ); - - // Define the appearance and behavior for Links: - - function linkInfo(d) { // Tooltip info for a link data object - return "Link:\nfrom " + d.from + " to " + d.to; - } - - // The link shape and arrowhead have their stroke brush data bound to the "color" property - myDiagram.linkTemplate = - $(go.Link, - { relinkableFrom: true, relinkableTo: true }, // allow the user to relink existing links - $(go.Shape, - { strokeWidth: 2 }, - new go.Binding("stroke", "color")), - $(go.Shape, - { toArrow: "Standard", stroke: null }, - new go.Binding("fill", "color")), - { // this tooltip Adornment is shared by all links - toolTip: - $(go.Adornment, "Auto", - $(go.Shape, { fill: "#FFFFCC" }), - $(go.TextBlock, { margin: 4 }, // the tooltip shows the result of calling linkInfo(data) - new go.Binding("text", "", linkInfo)) - ), - // the same context menu Adornment is shared by all links - contextMenu: partContextMenu - } - ); - - // Define the appearance and behavior for Groups: - - function groupInfo(adornment) { // takes the tooltip, not a group node data object - var g = adornment.adornedPart; // get the Group that the tooltip adorns - var mems = g.memberParts.count; - var links = 0; - var it = g.memberParts; - while (it.next()) { - if (it.value instanceof go.Link) links++; + // To simplify this code we define a function for creating a context menu button: + function makeButton(text: string, action: (e: go.InputEvent, obj: go.GraphObject) => void, visiblePredicate?: (obj: go.GraphObject) => boolean) { + if (visiblePredicate === undefined) visiblePredicate = function (o) { return true; }; + return $("ContextMenuButton", + $(go.TextBlock, text), + { click: action }, + // don't bother with binding GraphObject.visible if there's no predicate + visiblePredicate ? new go.Binding("visible", "", visiblePredicate).ofObject() : {}); } - return "Group " + g.data.key + ": " + g.data.text + "\n" + mems + " members including " + links + " links"; - } - // Groups consist of a title in the color given by the group node data - // above a translucent gray rectangle surrounding the member parts - myDiagram.groupTemplate = + // a context menu is an Adornment with a bunch of buttons in them + var partContextMenu = + $(go.Adornment, "Vertical", + makeButton("Properties", + function (e, obj) { // the OBJ is this Button + var contextmenu = obj.part; // the Button is in the context menu Adornment + var part = contextmenu.adornedPart; // the adornedPart is the Part that the context menu adorns + // now can do something with PART, or with its data, or with the Adornment (the context menu) + if (part instanceof go.Link) alert(linkInfo(part.data)); + else if (part instanceof go.Group) alert(groupInfo(contextmenu)); + else alert(nodeInfo(part.data)); + }), + makeButton("Cut", + function (e, obj) { e.diagram.commandHandler.cutSelection(); }, + function (o) { return o.diagram.commandHandler.canCutSelection(); }), + makeButton("Copy", + function (e, obj) { e.diagram.commandHandler.copySelection(); }, + function (o) { return o.diagram.commandHandler.canCopySelection(); }), + makeButton("Paste", + function (e, obj) { e.diagram.commandHandler.pasteSelection(e.diagram.lastInput.documentPoint); }, + function (o) { return o.diagram.commandHandler.canPasteSelection(); }), + makeButton("Delete", + function (e, obj) { e.diagram.commandHandler.deleteSelection(); }, + function (o) { return o.diagram.commandHandler.canDeleteSelection(); }), + makeButton("Undo", + function (e, obj) { e.diagram.commandHandler.undo(); }, + function (o) { return o.diagram.commandHandler.canUndo(); }), + makeButton("Redo", + function (e, obj) { e.diagram.commandHandler.redo(); }, + function (o) { return o.diagram.commandHandler.canRedo(); }), + makeButton("Group", + function (e, obj) { e.diagram.commandHandler.groupSelection(); }, + function (o) { return o.diagram.commandHandler.canGroupSelection(); }), + makeButton("Ungroup", + function (e, obj) { e.diagram.commandHandler.ungroupSelection(); }, + function (o) { return o.diagram.commandHandler.canUngroupSelection(); }) + ); + + function nodeInfo(d) { // Tooltip info for a node data object + var str = "Node " + d.key + ": " + d.text + "\n"; + if (d.group) + str += "member of " + d.group; + else + str += "top-level node"; + return str; + } + + // These nodes have text surrounded by a rounded rectangle + // whose fill color is bound to the node data. + // The user can drag a node by dragging its TextBlock label. + // Dragging from the Shape will start drawing a new link. + myDiagram.nodeTemplate = + $(go.Node, "Auto", + { locationSpot: go.Spot.Center }, + $(go.Shape, "RoundedRectangle", + { + fill: "white", // the default fill, if there is no data-binding + portId: "", cursor: "pointer", // the Shape is the port, not the whole Node + // allow all kinds of links from and to this port + fromLinkable: true, fromLinkableSelfNode: true, fromLinkableDuplicates: true, + toLinkable: true, toLinkableSelfNode: true, toLinkableDuplicates: true + }, + new go.Binding("fill", "color")), + $(go.TextBlock, + { + font: "bold 14px sans-serif", + stroke: '#333', + margin: 6, // make some extra space for the shape around the text + isMultiline: false, // don't allow newlines in text + editable: true // allow in-place editing by user + }, + new go.Binding("text", "text").makeTwoWay()), // the label shows the node data's text + { // this tooltip Adornment is shared by all nodes + toolTip: + $(go.Adornment, "Auto", + $(go.Shape, { fill: "#FFFFCC" }), + $(go.TextBlock, { margin: 4 }, // the tooltip shows the result of calling nodeInfo(data) + new go.Binding("text", "", nodeInfo)) + ), + // this context menu Adornment is shared by all nodes + contextMenu: partContextMenu + } + ); + + // Define the appearance and behavior for Links: + + function linkInfo(d) { // Tooltip info for a link data object + return "Link:\nfrom " + d.from + " to " + d.to; + } + + // The link shape and arrowhead have their stroke brush data bound to the "color" property + myDiagram.linkTemplate = + $(go.Link, + { relinkableFrom: true, relinkableTo: true }, // allow the user to relink existing links + $(go.Shape, + { strokeWidth: 2 }, + new go.Binding("stroke", "color")), + $(go.Shape, + { toArrow: "Standard", stroke: null }, + new go.Binding("fill", "color")), + { // this tooltip Adornment is shared by all links + toolTip: + $(go.Adornment, "Auto", + $(go.Shape, { fill: "#FFFFCC" }), + $(go.TextBlock, { margin: 4 }, // the tooltip shows the result of calling linkInfo(data) + new go.Binding("text", "", linkInfo)) + ), + // the same context menu Adornment is shared by all links + contextMenu: partContextMenu + } + ); + + // Define the appearance and behavior for Groups: + + function groupInfo(adornment: go.Adornment) { // takes the tooltip, not a group node data object + var g = adornment.adornedPart; // get the Group that the tooltip adorns + var mems = g.memberParts.count; + var links = 0; + g.memberParts.each(function (part) { + if (part instanceof go.Link) links++; + }); + return "Group " + g.data.key + ": " + g.data.text + "\n" + mems + " members including " + links + " links"; + } + + // Groups consist of a title in the color given by the group node data + // above a translucent gray rectangle surrounding the member parts + myDiagram.groupTemplate = $(go.Group, "Vertical", - { - selectionObjectName: "PANEL", // selection handle goes around shape, not label - ungroupable: true // enable Ctrl-Shift-G to ungroup a selected Group - }, - $(go.TextBlock, { - font: "bold 12pt sans-serif", - isMultiline: false, // don't allow newlines in text - editable: true // allow in-place editing by user + selectionObjectName: "PANEL", // selection handle goes around shape, not label + ungroupable: true // enable Ctrl-Shift-G to ungroup a selected Group }, - new go.Binding("text", "text").makeTwoWay(), - new go.Binding("stroke", "color")), - $(go.Panel, "Auto", - { name: "PANEL" }, - $(go.Shape, "Rectangle", // the rectangular shape around the members - { fill: "rgba(128,128,128,0.2)", stroke: "gray", strokeWidth: 3 }), - $(go.Placeholder, { padding: 5 }) // represents where the members are - ), - { // this tooltip Adornment is shared by all groups - toolTip: - $(go.Adornment, "Auto", - $(go.Shape, { fill: "#FFFFCC" }), - $(go.TextBlock, { margin: 4 }, - // bind to tooltip, not to Group.data, to allow access to Group properties - new go.Binding("text", "", groupInfo).ofObject()) - ), - // the same context menu Adornment is shared by all groups - contextMenu: partContextMenu - } - ); + $(go.TextBlock, + { + font: "bold 12pt sans-serif", + isMultiline: false, // don't allow newlines in text + editable: true // allow in-place editing by user + }, + new go.Binding("text", "text").makeTwoWay(), + new go.Binding("stroke", "color")), + $(go.Panel, "Auto", + { name: "PANEL" }, + $(go.Shape, "Rectangle", // the rectangular shape around the members + { fill: "rgba(128,128,128,0.2)", stroke: "gray", strokeWidth: 3 }), + $(go.Placeholder, { padding: 5 }) // represents where the members are + ), + { // this tooltip Adornment is shared by all groups + toolTip: + $(go.Adornment, "Auto", + $(go.Shape, { fill: "#FFFFCC" }), + $(go.TextBlock, { margin: 4 }, + // bind to tooltip, not to Group.data, to allow access to Group properties + new go.Binding("text", "", groupInfo).ofObject()) + ), + // the same context menu Adornment is shared by all groups + contextMenu: partContextMenu + } + ); - // Define the behavior for the Diagram background: + // Define the behavior for the Diagram background: - function diagramInfo(model) { // Tooltip info for the diagram's model - return "Model:\n" + model.nodeDataArray.length + " nodes, " + model.linkDataArray.length + " links"; - } + function diagramInfo(model: go.GraphLinksModel) { // Tooltip info for the diagram's model + return "Model:\n" + model.nodeDataArray.length + " nodes, " + model.linkDataArray.length + " links"; + } - // provide a tooltip for the background of the Diagram, when not over any Part - myDiagram.toolTip = + // provide a tooltip for the background of the Diagram, when not over any Part + myDiagram.toolTip = $(go.Adornment, "Auto", - $(go.Shape, { fill: "#FFFFCC" }), - $(go.TextBlock, { margin: 4 }, - new go.Binding("text", "", diagramInfo)) - ); + $(go.Shape, { fill: "#FFFFCC" }), + $(go.TextBlock, { margin: 4 }, + new go.Binding("text", "", diagramInfo)) + ); - // provide a context menu for the background of the Diagram, when not over any Part - myDiagram.contextMenu = + // provide a context menu for the background of the Diagram, when not over any Part + myDiagram.contextMenu = $(go.Adornment, "Vertical", - makeButton("Paste", - function(e, obj) { e.diagram.commandHandler.pasteSelection(e.diagram.lastInput.documentPoint); }, - function(o) { return o.diagram.commandHandler.canPasteSelection(); }), - makeButton("Undo", - function(e, obj) { e.diagram.commandHandler.undo(); }, - function(o) { return o.diagram.commandHandler.canUndo(); }), - makeButton("Redo", - function(e, obj) { e.diagram.commandHandler.redo(); }, - function(o) { return o.diagram.commandHandler.canRedo(); }) - ); + makeButton("Paste", + function (e, obj) { e.diagram.commandHandler.pasteSelection(e.diagram.lastInput.documentPoint); }, + function (o) { return o.diagram.commandHandler.canPasteSelection(); }), + makeButton("Undo", + function (e, obj) { e.diagram.commandHandler.undo(); }, + function (o) { return o.diagram.commandHandler.canUndo(); }), + makeButton("Redo", + function (e, obj) { e.diagram.commandHandler.redo(); }, + function (o) { return o.diagram.commandHandler.canRedo(); }) + ); - // Create the Diagram's Model: - var nodeDataArray = [ - { key: 1, text: "Alpha", color: "lightblue" }, - { key: 2, text: "Beta", color: "orange" }, - { key: 3, text: "Gamma", color: "lightgreen", group: 5 }, - { key: 4, text: "Delta", color: "pink", group: 5 }, - { key: 5, text: "Epsilon", color: "green", isGroup: true } - ]; - var linkDataArray = [ - { from: 1, to: 2, color: "blue" }, - { from: 2, to: 2 }, - { from: 3, to: 4, color: "green" }, - { from: 3, to: 1, color: "purple" } - ]; - myDiagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray); - - // now enable undo/redo, only after setting the Diagram.model - myDiagram.model.undoManager.isEnabled = true; + // Create the Diagram's Model: + var nodeDataArray = [ + { key: 1, text: "Alpha", color: "lightblue" }, + { key: 2, text: "Beta", color: "orange" }, + { key: 3, text: "Gamma", color: "lightgreen", group: 5 }, + { key: 4, text: "Delta", color: "pink", group: 5 }, + { key: 5, text: "Epsilon", color: "green", isGroup: true } + ]; + var linkDataArray = [ + { from: 1, to: 2, color: "blue" }, + { from: 2, to: 2 }, + { from: 3, to: 4, color: "green" }, + { from: 3, to: 1, color: "purple" } + ]; + myDiagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray); } diff --git a/goJS/goJS.d.ts b/goJS/goJS.d.ts index 6c25d148c0..063a1b3a86 100644 --- a/goJS/goJS.d.ts +++ b/goJS/goJS.d.ts @@ -1,45 +1,80 @@ -// Type definitions for GoJS 1.2 +// Type definitions for GoJS v1.5.0 // Project: http://gojs.net -// Definitions by: Barbara Duckworth -// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Definitions by: Northwoods Software +// Definitions: https://github.com/NorthwoodsSoftware/GoJS -/* Copyright (C) 1998-2013 by Northwoods Software Corporation. */ +/* Copyright (C) 1998-2015 by Northwoods Software Corporation. */ -// A number of types have been declared "any" because they would best be described by a union of specific types, -// not as truly "any" type, and TypeScript does not support union types. Most of the cases are due to: -// - a property of type Margin whose setter also accepts a number, for a uniform Margin of that thickness -// - a property of type Brush whose setter also accepts a string, a CSS color string for a solid color Brush -// - a boolean property that may also be null (tri-state) -// - a key type, which may be a string or a number, uniquely identifying a node data within a Model -// - a property that is string that names a property or that is a function that gets or sets a value, on an Object in a Model +// This is for TypeScript 1.4 +// TODO: TypeScript 1.5 modules and destructuring declare module go { + /** A number in place of a Margin object is treated as a uniform Margin with that thickness */ + type MarginLike = Margin | number; + + /** A string in place of a Brush object is treated as a Solid Brush of that color. */ + type BrushLike = Brush | string; + + /** A Key is the type of the unique identifier managed by Models for each node data object. */ + type Key = string | number; + + /** Either name a property or get the value of a property from an object. */ + type PropertyAccessor = string | ((data: any, newval: any) => any); + + /** A constructor */ + type Constructor = new (...args: any[]) => Object; + /** * An adornment is a special kind of Part that is associated with another Part, - * the Adornment#adornedPart. + * the Adornment.adornedPart. * Adornments are normally associated with a particular GraphObject in the adorned part -- - * that is the value of #adornedObject. - * However, the #adornedObject may be null, in which case the #adornedPart will also be null. + * that is the value of .adornedObject. + * However, the .adornedObject may be null, in which case the .adornedPart will also be null. */ class Adornment extends Part { /** - * @param {EnumValue=} type if not supplied, the default Panel type is Panel#Position. + * @param {EnumValue=} type if not supplied, the default Panel type is Panel.Position. */ constructor(type?: EnumValue); /**Gets or sets the GraphObject that is adorned.*/ adornedObject: GraphObject; - /**Gets the Part that contains the adorned object.*/ + /**This read-only property returns the Part that contains the adorned object.*/ adornedPart: Part; - /**Gets a Placeholder that this Adornment may contain in its visual tree.*/ + /**This read-only property returns a Placeholder that this Adornment may contain in its visual tree.*/ placeholder: Placeholder; } /** - * The Diagram#commandHandler implements various - * commands such as CommandHandler#deleteSelection or CommandHandler#redo. + * This class handles animations in a Diagram. Each Diagram has one, the Diagram.animationManager. + */ + class AnimationManager { + /**You do not normally need to create an instance of this class because one already exists as the Diagram.animationManager, which you can modify.*/ + constructor(); + + /**Gets or sets the duration for animations, in milliseconds. The default value is 600 milliseconds.*/ + duration: number; + + /**This read-only property is true when the AnimationManager is currently animating.*/ + isAnimating: boolean; + + /**Gets or sets whether this AnimationManager operates. The default value is true.*/ + isEnabled: boolean; + + /**This read-only property is true when the animation manager is in the middle of an animation tick.*/ + isTicking: boolean; + + /** + * Stops any running animation and updates the Diagram to its final state. + */ + stopAnimation(): void; + } + + /** + * The Diagram.commandHandler implements various + * commands such as CommandHandler.deleteSelection or CommandHandler.redo. * The CommandHandler includes keyboard event handling to interpret * key presses as commands. */ @@ -49,30 +84,42 @@ declare module go { */ constructor(); - /**Gets or sets a data object that is copied by #groupSelection when creating a new Group.*/ + /**Gets or sets a data object that is copied by .groupSelection when creating a new Group. The default value is null.*/ archetypeGroupData: Object; - /**Gets or sets whether #copySelection should also copy subtrees.*/ + /**Gets or sets whether copySelection should also copy Links that connect with selected Nodes.*/ + copiesConnectedLinks: boolean; + + /**Gets or sets whether copySelection and copyToClipboard copy the node data property whose value is the containing group data's key. The default value is false.*/ + copiesGroupKey: boolean; + + /**Gets or sets whether copySelection and copyToClipboard copy the node data property whose value is the tree-parent node data's key. The default value is false.*/ + copiesParentKey: boolean; + + /**Gets or sets whether .copySelection should also copy subtrees. The default value is false.*/ copiesTree: boolean; - /**Gets or sets whether #deleteSelection should also delete subtrees.*/ + /**Gets or sets the Diagram.scale set by resetZoom. The default value is 1.0.*/ + defaultScale: number; + + /**Gets or sets whether .deleteSelection should also delete subtrees. The default value is false.*/ deletesTree: boolean; - /**Gets the Diagram that is using this CommandHandler.*/ + /**This read-only property returns the Diagram that is using this CommandHandler.*/ diagram: Diagram; - /**Gets or sets the predicate that determines whether or not a node may become a member of a group.*/ + /**Gets or sets the predicate that determines whether or not a node may become a member of a group. The default predicate is null, which is equivalent to simply returning true.*/ memberValidation: (g: Group, p: Part) => boolean; - /**Gets or sets the amount by which #decreaseZoom and #increaseZoom change the Diagram#scale; default is 1.05.*/ + /**Gets or sets the amount by which .decreaseZoom and .increaseZoom change the Diagram.scale. The default value is 1.05 (5%).*/ zoomFactor: number; /** * Make sure all of the unnested Parts in the given collection are removed from any containing Groups. - * @param {Iterable} coll a collection of Parts. - * @param {boolean=} check whether to call #isValidMember to confirm that changing the Part to be a top-level Part is valid. + * @param {Iterable} coll a collection of Parts. + * @param {boolean=} check whether to call .isValidMember to confirm that changing the Part to be a top-level Part is valid. */ - addTopLevelParts(coll: Iterable, check?: boolean): boolean; + addTopLevelParts(coll: Iterable, check?: boolean): boolean; /** * This predicate controls whether the user can collapse expanded Groups. @@ -87,28 +134,28 @@ declare module go { canCollapseTree(node?: Node): boolean; /** - * This predicate controls whether or not the user can invoke the #copySelection command. + * This predicate controls whether or not the user can invoke the .copySelection command. */ canCopySelection(): boolean; /** - * This predicate controls whether or not the user can invoke the #cutSelection command. + * This predicate controls whether or not the user can invoke the .cutSelection command. */ canCutSelection(): boolean; /** - * This predicate controls whether or not the user can invoke the #decreaseZoom command. - * @param {number=} factor This defaults to 1/#zoomFactor. The value should be less than one. + * This predicate controls whether or not the user can invoke the .decreaseZoom command. + * @param {number=} factor This defaults to 1/.zoomFactor. The value should be less than one. */ canDecreaseZoom(factor?: number): boolean; /** - * This predicate controls whether or not the user can invoke the #deleteSelection command. + * This predicate controls whether or not the user can invoke the .deleteSelection command. */ canDeleteSelection(): boolean; /** - * This predicate controls whether or not the user can invoke the #editTextBlock command. + * This predicate controls whether or not the user can invoke the .editTextBlock command. * @param {TextBlock=} textblock the TextBlock to consider editing. */ canEditTextBlock(textblock?: TextBlock): boolean; @@ -126,55 +173,62 @@ declare module go { canExpandTree(node?: Node): boolean; /** - * This predicate controls whether or not the user can invoke the #groupSelection command. + * This predicate controls whether or not the user can invoke the .groupSelection command. */ canGroupSelection(): boolean; /** - * This predicate controls whether or not the user can invoke the #increaseZoom command. - * @param {number=} factor This defaults to #zoomFactor. The value should be greater than one. + * This predicate controls whether or not the user can invoke the .increaseZoom command. + * @param {number=} factor This defaults to .zoomFactor. The value should be greater than one. */ canIncreaseZoom(factor?: number): boolean; /** - * This predicate controls whether or not the user can invoke the #pasteSelection command. + * This predicate controls whether or not the user can invoke the .pasteSelection command. */ canPasteSelection(): boolean; /** - * This predicate controls whether or not the user can invoke the #redo command. + * This predicate controls whether or not the user can invoke the .redo command. */ canRedo(): boolean; /** - * This predicate controls whether or not the user can invoke the #resetZoom command. + * This predicate controls whether or not the user can invoke the .resetZoom command. * @param {number=} newscale This defaults to 1. The value should be greater than zero. */ canResetZoom(newscale?: number): boolean; /** - * This predicate controls whether or not the user can invoke the #selectAll command. + * This predicate controls whether or not the user can invoke the .selectAll command. */ canSelectAll(): boolean; + /** + * This predicate controls whether or not the user can invoke the .showContextMenu command. + * @param {GraphObject|Diagram=} obj a GraphObject or Diagram with a contextMenu defined. + * If none is given, this method will use the first selected object, or else the Diagram. + */ + canShowContextMenu(obj?: GraphObject | Diagram): boolean; + /** * This predicate controls whether the user may stop the current tool. */ canStopCommand(): boolean; /** - * This predicate controls whether or not the user can invoke the #undo command. + * This predicate controls whether or not the user can invoke the .undo command. */ canUndo(): boolean; /** - * This predicate controls whether or not the user can invoke the #ungroupSelection command. + * This predicate controls whether or not the user can invoke the .ungroupSelection command. * @param {Group=} group if supplied, ignore the selection and consider ungrouping this particular Group. */ canUngroupSelection(group?: Group): boolean; /** - * This predicate controls whether or not the user can invoke the #zoomToFit command. + * This predicate controls whether or not the user can invoke the .zoomToFit command. */ canZoomToFit(): boolean; @@ -182,79 +236,79 @@ declare module go { * Collapse all expanded selected Groups. * @param {Group=} group if supplied, ignore the selection and collapse this particular Group. */ - collapseSubGraph(group?: Group); + collapseSubGraph(group?: Group): void; /** * Collapse all expanded selected Nodes. * @param {Node=} node if supplied, ignore the selection and collapse this particular Node subtree. */ - collapseTree(node?: Node); + collapseTree(node?: Node): void; /** - * Copy the currently selected parts, Diagram#selection, from the Diagram into the clipboard. + * Copy the currently selected parts, Diagram.selection, from the Diagram into the clipboard. */ - copySelection(); + copySelection(): void; /** * This makes a copy of the given collection of Parts and stores it in a static variable acting as the clipboard. - * @param {Iterable} coll A collection of Parts. + * @param {Iterable} coll A collection of Parts. */ - copyToClipboard(coll: Iterable); + copyToClipboard(coll: Iterable): void; /** - * Execute a #copySelection followed by a #deleteSelection. + * Execute a .copySelection followed by a .deleteSelection. */ - cutSelection(); + cutSelection(): void; /** - * Decrease the Diagram#scale by a given factor. - * @param {number=} factor This defaults to 1/#zoomFactor. The value should be less than one. + * Decrease the Diagram.scale by a given factor. + * @param {number=} factor This defaults to 1/.zoomFactor. The value should be less than one. */ - decreaseZoom(factor?: number); + decreaseZoom(factor?: number): void; /** * Delete the currently selected parts from the diagram. */ - deleteSelection(); + deleteSelection(): void; /** * This is called by tools to handle keyboard commands. */ - doKeyDown(); + doKeyDown(): void; /** * This is called by tools to handle keyboard commands. */ - doKeyUp(); + doKeyUp(): void; /** * Start in-place editing of a TextBlock in the selected Part. * @param {TextBlock=} textblock the TextBlock to start editing. */ - editTextBlock(textblock?: TextBlock); + editTextBlock(textblock?: TextBlock): void; /** * Expand all collapsed selected Groups. * @param {Group=} group if supplied, ignore the selection and expand this particular Group. */ - expandSubGraph(group?: Group); + expandSubGraph(group?: Group): void; /** * Expand all collapsed selected Nodes. * @param {Node=} node if supplied, ignore the selection and collapse this particular Node subtree. */ - expandTree(node?: Node); + expandTree(node?: Node): void; /** - * Add a copy of #archetypeGroupData and add it to the diagram's model to create a new Group and then add the selected Parts to that new group. + * Add a copy of .archetypeGroupData and add it to the diagram's model to create a new Group and then add the selected Parts to that new group. */ - groupSelection(); + groupSelection(): void; /** - * Increase the Diagram#scale by a given factor. - * @param {number=} factor This defaults to #zoomFactor. The value should be greater than one. + * Increase the Diagram.scale by a given factor. + * @param {number=} factor This defaults to .zoomFactor. The value should be greater than one. */ - increaseZoom(factor?: Number); + increaseZoom(factor?: Number): void; /** * This predicate is called to determine whether a Node may be added as a member of a Group. @@ -264,52 +318,61 @@ declare module go { isValidMember(group: Group, part: Part): boolean; /** - * If the clipboard holds a collection of Parts, and if the Model#dataFormat matches that stored in the clipboard, this makes a copy of the clipboard's parts and adds the copies to this Diagram. + * If the clipboard holds a collection of Parts, and if the Model.dataFormat matches that stored in the clipboard, this makes a copy of the clipboard's parts and adds the copies to this Diagram. */ - pasteFromClipboard(): Set; + pasteFromClipboard(): Set; /** * Copy the contents of the clipboard into this diagram, and make those new parts the new selection. * @param {Point=} pos Point at which to center the newly pasted parts; if not present the parts are not moved. */ - pasteSelection(pos?: Point); + pasteSelection(pos?: Point): void; /** - * Call UndoManager#redo. + * Call UndoManager.redo. */ - redo(); + redo(): void; /** - * Set the Diagram#scale to a new scale value, by default 1. + * Set the Diagram.scale to a new scale value, by default 1. * @param {number=} newscale This defaults to 1. The value should be greater than zero. */ - resetZoom(newscale?: number); + resetZoom(newscale?: number): void; /** * Select all of the selectable Parts in the diagram. */ - selectAll(); + selectAll(): void; + + /** + * Open the context menu of a given GraphObject. + * The given GraphObject must have a GraphObject.contextMenu + * defined in order to show anything. + * @param {GraphObject|Diagram=} obj a GraphObject or Diagram with a contextMenu defined. + * If none is given, this method will use the first selected object, or else the Diagram. + */ + showContextMenu(obj?: GraphObject | Diagram): void; /** * Cancel the operation of the current tool. */ - stopCommand(); + stopCommand(): void; /** - * Call UndoManager#undo. + * Call UndoManager.undo. */ - undo(); + undo(): void; /** * Remove the group from the diagram without removing its members from the diagram. * @param {Group=} group if supplied, ignore the selection and consider ungrouping this particular Group. */ - ungroupSelection(group?: Group); + ungroupSelection(group?: Group): void; /** - * Change the Diagram#scale so that the Diagram#documentBounds fits within the viewport. + * Change the Diagram.scale so that the Diagram.documentBounds fits within the viewport. */ - zoomToFit(); + zoomToFit(): void; } /** @@ -322,7 +385,7 @@ declare module go { /** * Construct an empty Diagram for a particular DIV HTML element. * @param {HTMLDivElement} div A reference to a DIV HTML element in the DOM. - * If no DIV is supplied one will be created in memory. The Diagram's Diagram#div property + * If no DIV is supplied one will be created in memory. The Diagram's Diagram.div property * can then be set later on. */ constructor(div: HTMLDivElement); @@ -330,7 +393,7 @@ declare module go { /** * Construct an empty Diagram for a particular DIV HTML element. * @param {string=} div The ID of a DIV element in the DOM. - * If no DIV identifier is supplied one will be created in memory. The Diagram's Diagram#div property + * If no DIV identifier is supplied one will be created in memory. The Diagram's Diagram.div property * can then be set later on. */ constructor(div?: string); @@ -395,11 +458,14 @@ declare module go { /**Gets or sets whether the user may zoom into or out of the Diagram.*/ allowZoom: boolean; + /**This read-only property returns the AnimationManager for this Diagram.*/ + animationManager: AnimationManager; + /**Gets or sets the autoScale of the Diagram, controlling whether or not the Diagram's bounds automatically scale to fit the view.*/ autoScale: EnumValue; /**Gets or sets the Margin (or number for a uniform Margin) that describes the Diagram's autoScrollRegion.*/ - autoScrollRegion: any; + autoScrollRegion: MarginLike; /**Gets or sets the function to execute when the user single-primary-clicks on the background of the Diagram.*/ click: (e: InputEvent) => void; @@ -407,7 +473,7 @@ declare module go { /**Gets or sets the CommandHandler for this Diagram.*/ commandHandler: CommandHandler; - /**Gets or sets the content alignment Spot of this Diagram, to be used in determining how parts are positioned when the #viewportBounds width or height is smaller than the #documentBounds.*/ + /**Gets or sets the content alignment Spot of this Diagram, to be used in determining how parts are positioned when the .viewportBounds width or height is smaller than the .documentBounds.*/ contentAlignment: Spot; /**Gets or sets the function to execute when the user single-secondary-clicks on the background of the Diagram.*/ @@ -416,7 +482,7 @@ declare module go { /**This Adornment is shown when the use context clicks in the background.*/ contextMenu: Adornment; - /**Gets or sets the current cursor for the Diagram, overriding the #defaultCursor.*/ + /**Gets or sets the current cursor for the Diagram, overriding the .defaultCursor.*/ currentCursor: string; /**Gets or sets the current tool for this Diagram that handles all input events.*/ @@ -431,7 +497,7 @@ declare module go { /**Gets or sets the Diagram's HTMLDivElement, via an HTML Element ID.*/ div: HTMLDivElement; - /**Gets the model-coordinate bounds of the Diagram.*/ + /**This read-only property returns the model-coordinate bounds of the Diagram.*/ documentBounds: Rect; /**Gets or sets the function to execute when the user double-primary-clicks on the background of the Diagram.*/ @@ -440,20 +506,32 @@ declare module go { /**Gets or sets the most recent mouse-down InputEvent that occurred.*/ firstInput: InputEvent; - /**Gets or sets a fixed bounding rectangle to be returned by #documentBounds and #computeBounds.*/ + /**Gets or sets a fixed bounding rectangle to be returned by .documentBounds and .computeBounds.*/ fixedBounds: Rect; - /**Gets or sets a Panel of type Panel#Grid acting as the background grid extending across the whole viewport of this diagram.*/ + /**Gets or sets the scrollMode of the Diagram.*/ + scrollMode: EnumValue; + + /**Gets or sets the Margin (or number for a uniform Margin) that describes a scrollable area that surrounds the document bounds, allowing the user to scroll into empty space.*/ + scrollMargin: MarginLike; + + /**Gets or sets the function used to determine the position that this Diagram can be scrolled or moved to.*/ + positionComputation: (d: Diagram, p: Point) => Point; + + /**Gets or sets the function used to determine the scale that this Diagram can be set to.*/ + scaleComputation: (d: Diagram, s: number) => number; + + /**Gets or sets a Panel of type Panel.Grid acting as the background grid extending across the whole viewport of this diagram.*/ grid: Panel; /**Gets or sets the default selection Adornment template, used to adorn selected Groups.*/ groupSelectionAdornmentTemplate: Adornment; - /**Gets or sets the default Group template used as the archetype for group data that is added to the #model.*/ + /**Gets or sets the default Group template used as the archetype for group data that is added to the .model.*/ groupTemplate: Group; /**Gets or sets a Map mapping template names to Groups.*/ - groupTemplateMap: Map; + groupTemplateMap: Map; /**Gets or sets whether the Diagram has a horizontal Scrollbar.*/ hasHorizontalScrollbar: boolean; @@ -461,28 +539,31 @@ declare module go { /**Gets or sets whether the Diagram has a vertical Scrollbar.*/ hasVerticalScrollbar: boolean; + /**This read-only property returns the read-only collection of highlighted Parts.*/ + highlighteds: Set; + /**Gets or sets the initialAutoScale of the Diagram.*/ initialAutoScale: EnumValue; /**Gets or sets the initial content alignment Spot of this Diagram, to be used in determining how parts are positioned initially relative to the viewport.*/ initialContentAlignment: Spot; - /**Gets or sets the spot in the document's area that should be coincident with the #initialViewportSpot of the viewport when the document is first initialized.*/ + /**Gets or sets the spot in the document's area that should be coincident with the .initialViewportSpot of the viewport when the document is first initialized.*/ initialDocumentSpot: Spot; - /**Gets or sets the initial coordinates of this Diagram in the viewport, eventually setting the #position.*/ + /**Gets or sets the initial coordinates of this Diagram in the viewport, eventually setting the .position.*/ initialPosition: Point; - /**Gets or sets the initial scale of this Diagram in the viewport, eventually setting the #scale.*/ + /**Gets or sets the initial scale of this Diagram in the viewport, eventually setting the .scale.*/ initialScale: number; - /**Gets or sets the spot in the viewport that should be coincident with the #initialDocumentSpot of the document when the document is first initialized.*/ + /**Gets or sets the spot in the viewport that should be coincident with the .initialDocumentSpot of the document when the document is first initialized.*/ initialViewportSpot: Spot; /**Gets or sets whether the user may interact with the Diagram.*/ isEnabled: boolean; - /**Gets or sets whether the Diagram's Diagram#model is Model#isReadOnly.*/ + /**Gets or sets whether the Diagram's Diagram.model is Model.isReadOnly.*/ isModelReadOnly: boolean; /**Gets or sets whether this Diagram's state has been modified.*/ @@ -501,30 +582,30 @@ declare module go { lastInput: InputEvent; /**Gets an iterator for this Diagram's Layers.*/ - layers: Iterator; + layers: Iterator; /**Gets or sets the Layout used to position all of the top-level nodes and links in this Diagram.*/ layout: Layout; /**Returns an iterator of all Links in the Diagram.*/ - links: Iterator; + links: Iterator; /**Gets or sets the default selection Adornment template, used to adorn selected Links.*/ linkSelectionAdornmentTemplate: Adornment; - /**Gets or sets the default Link template used as the archetype for link data that is added to the #model.*/ + /**Gets or sets the default Link template used as the archetype for link data that is added to the .model.*/ linkTemplate: Link; /**Gets or sets a Map mapping template names to Links.*/ - linkTemplateMap: Map; + linkTemplateMap: Map; - /**Gets or sets the largest value that #scale may take.*/ + /**Gets or sets the largest value that .scale may take.*/ maxScale: number; /**Gets or sets the maximum number of selected objects.*/ maxSelectionCount: number; - /**Gets or sets the smallest value greater than zero that #scale may take.*/ + /**Gets or sets the smallest value greater than zero that .scale may take.*/ minScale: number; /**Gets or sets the Model holding data corresponding to the data-bound nodes and links of this Diagram.*/ @@ -546,22 +627,22 @@ declare module go { mouseOver: (e: InputEvent) => void; /**Returns an iterator of all Nodes and Groups in the Diagram.*/ - nodes: Iterator; + nodes: Iterator; /**Gets or sets the default selection Adornment template, used to adorn selected Parts other than Groups or Links.*/ nodeSelectionAdornmentTemplate: Adornment; - /**Gets or sets the default Node template used as the archetype for node data that is added to the #model.*/ + /**Gets or sets the default Node template used as the archetype for node data that is added to the .model.*/ nodeTemplate: Part; /**Gets or sets a Map mapping template names to Parts.*/ - nodeTemplateMap: Map; + nodeTemplateMap: Map; /**Gets or sets the Margin (or number for a uniform Margin) that describes the Diagram's padding, which controls how much extra space there is around the area occupied by the document.*/ - padding: any; + padding: MarginLike; /**Returns an iterator of all Parts in the Diagram that are not Nodes or Links or Adornments.*/ - parts: Iterator; + parts: Iterator; /**Gets or sets the coordinates of this Diagram in the viewport.*/ position: Point; @@ -575,114 +656,128 @@ declare module go { /**Gets or sets the distance in screen pixels that the vertical scrollbar will scroll when scrolling by a line.*/ scrollVerticalLineChange: number; - /**Gets the read-only collection of selected objects.*/ - selection: Set; + /**This read-only property returns the read-only collection of selected Parts.*/ + selection: Set; /**Gets or sets whether ChangedEvents are not recorded by the UndoManager.*/ skipsUndoManager: boolean; - /**Gets the UndoManager for this Diagram, which actually belongs to the #model.*/ + /**This read-only property returns the ToolManager for this Diagram.*/ toolManager: ToolManager; /**This Adornment is shown when the mouse stays motionless in the background.*/ toolTip: Adornment; - /**Gets the UndoManager for this Diagram, which actually belongs to the #model.*/ + /**This read-only property returns the UndoManager for this Diagram, which actually belongs to the .model.*/ undoManager: UndoManager; /**Gets or sets what kinds of graphs this diagram allows the user to draw.*/ validCycle: EnumValue; - /**Gets the bounds of the portion of the Diagram that is viewable from its HTML Canvas.*/ + /**This read-only property returns the bounds of the portion of the Diagram that is viewable from its HTML Canvas.*/ viewportBounds: Rect; - /**Gets or sets the point, in viewport coordinates, where changes to the #scale will keep the focus in the document.*/ + /**Gets or sets the point, in viewport coordinates, where changes to the .scale will keep the focus in the document.*/ zoomPoint: Point; /** - * Adds a Part to the Layer that matches the Part's Part#layerName, or else to the default layer, which is named with the empty string. + * Adds a Part to the Layer that matches the Part's Part.layerName, or else to the default layer, which is named with the empty string. * @param {Part} part */ - add(part: Part); + add(part: Part): void; /** * Register an event handler that is called when there is a ChangedEvent. * @param {function(ChangedEvent)} listener a function that takes a ChangedEvent as its argument. */ - addChangedListener(listener: (e: ChangedEvent) => void); + addChangedListener(listener: (e: ChangedEvent) => void ): void; /** * Register an event handler that is called when there is a DiagramEvent of a given name. * @param {string} name the name is normally capitalized, but this method uses case-insensitive comparison. * @param {function(DiagramEvent)} listener a function that takes a DiagramEvent as its argument. */ - addDiagramListener(name: string, listener: (e: DiagramEvent) => void); + addDiagramListener(name: string, listener: (e: DiagramEvent) => void ): void; /** * Adds a Layer to the list of layers. * @param {Layer} layer The Layer to add. */ - addLayer(layer: Layer); + addLayer(layer: Layer): void; /** * Adds a layer to the list of layers after a specified layer. * @param {Layer} layer The Layer to add. * @param {Layer} existingLayer The layer to insert after. */ - addLayerAfter(layer: Layer, existingLayer: Layer); + addLayerAfter(layer: Layer, existingLayer: Layer): void; /** * Adds a layer to the list of layers before a specified layer. * @param {Layer} layer The Layer to add. * @param {Layer} existingLayer The layer to insert before. */ - addLayerBefore(layer: Layer, existingLayer: Layer); + addLayerBefore(layer: Layer, existingLayer: Layer): void; /** - * Aligns the Diagram's #position based on a desired document Spot and viewport Spot. + * Aligns the Diagram's .position based on a desired document Spot and viewport Spot. * @param {Spot} documentspot * @param {Spot} viewportspot */ - alignDocument(documentspot: Spot, viewportspot: Spot); + alignDocument(documentspot: Spot, viewportspot: Spot): void; /** - * Modifies the #position to show a given Rect of the Diagram by centering the viewport on that Rect. + * Modifies the .position to show a given Rect of the Diagram by centering the viewport on that Rect. * @param {Rect} r */ - centerRect(r: Rect); + centerRect(r: Rect): void; /** * Removes all Parts from the Diagram, including unbound Parts and the background grid, and also clears out the Model and UndoManager. */ - clear(); + clear(): void; + + /** + * Remove highlights from all Parts. + */ + clearHighlighteds(): void; /** * Deselect all selected Parts. */ - clearSelection(); + clearSelection(): void; /** * Commit the changes of the current transaction. + * This just calls UndoManager.commitTransaction. * @param {string} tname a descriptive name for the transaction. */ commitTransaction(tname: string): boolean; /** - * This is called during a Diagram update to determine a new value for #documentBounds. + * This is called during a Diagram update to determine a new value for .documentBounds. */ computeBounds(): Rect; /** - * Find the union of the GraphObject#actualBounds of all of the Parts in the given collection. - * @param {Iterable} coll a collection of Parts. + * Find the union of the GraphObject.actualBounds of all of the Parts in the given collection. + * @param {Iterable} coll a collection of Parts. */ - computePartsBounds(coll: Iterable): Rect; + computePartsBounds(coll: Iterable): Rect; /** - * Updates the diagram immediately, then resets initialization flags so that actions taken in the argument function will be considered part of Diagram initialization, and will participate in initial layouts, #initialAutoScale, #initialContentAlignment, etc. + * Make a copy of a collection of Parts and return them in a Map mapping each original Part to its copy. + * @param {Iterable} coll A List or a Set or Iterator of Parts. + * @param {Diagram} diagram The destination diagram; if null, the copied parts are not added to this diagram. + * @param {boolean} check Whether to check Part.canCopy on each part. + */ + copyParts(coll: Iterable, diagram: Diagram, check: boolean): void; + + /** + * Updates the diagram immediately, then resets initialization flags so that actions taken in the argument function will be considered part of Diagram initialization, and will participate in initial layouts, .initialAutoScale, .initialContentAlignment, etc. * @param {function()|null=} func an optional function of actions to perform as part of another diagram initialization. */ - delayInitialization(func?: () => void); + delayInitialization(func?: () => void ): void; /** * Finds a layer with a given name. @@ -696,6 +791,13 @@ declare module go { */ findLinkForData(linkdata: Object): Link; + /** + * Return a collection of Links that are bound to data whose properties have values + * that match those specified by the given example data. + * @param {...Object} examples + */ + findLinksByExample(...examples: Array): Iterator; + /** * Look for a Node or Group corresponding to a model's node data object. * @param {Object} nodedata @@ -706,7 +808,14 @@ declare module go { * Look for a Node or Group corresponding to a model's node data object's unique key. * @param {*} key a string or number. */ - findNodeForKey(key: any): Node; + findNodeForKey(key: Key): Node; + + /** + * Return a collection of Nodes and Groups that are bound to data whose properties have values + * that match those specified by the given example data. + * @param {...Object} examples + */ + findNodesByExample(...examples: Array): Iterator; /** * Find the front-most GraphObject at the given point in document coordinates. @@ -730,8 +839,8 @@ declare module go { * defaulting to a predicate that always returns true. * @param {List|Set=} coll An optional collection (List or Set) to add the results to. */ - findObjectsAt(p: Point, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, coll?: List): Iterable; - findObjectsAt(p: Point, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, coll?: Set): Iterable; + findObjectsAt(p: Point, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, coll?: List): List; + findObjectsAt(p: Point, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, coll?: Set): Set; /** * Returns a collection of all GraphObjects that are inside or that intersect a given Rect in document coordinates. @@ -746,8 +855,8 @@ declare module go { * if it must be entirely inside the rectangular area (false). The default value is false. * @param {List|Set=} coll An optional collection (List or Set) to add the results to. */ - findObjectsIn(r: Rect, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, partialInclusion?: boolean, coll?: List): Iterable; - findObjectsIn(r: Rect, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, partialInclusion?: boolean, coll?: Set): Iterable; + findObjectsIn(r: Rect, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, partialInclusion?: boolean, coll?: List): List; + findObjectsIn(r: Rect, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, partialInclusion?: boolean, coll?: Set): Set; /** * Returns a collection of all GraphObjects that are within a certain distance of a given point in document coordinates. @@ -764,13 +873,13 @@ declare module go { * The default is true. * @param {List|Set=} coll An optional collection (List or Set) to add the results to. */ - findObjectsNear(p: Point, dist: number, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, partialInclusion?: boolean, coll?: List): Iterable; - findObjectsNear(p: Point, dist: number, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, partialInclusion?: boolean, coll?: Set): Iterable; + findObjectsNear(p: Point, dist: number, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, partialInclusion?: boolean, coll?: List): List; + findObjectsNear(p: Point, dist: number, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, partialInclusion?: boolean, coll?: Set): Set; /** * This convenience function finds the front-most Part that is at a given point and that might be selectable. * @param {Point} p a Point in document coordinates. - * @param {boolean} selectable Whether to only consider parts that are Part#selectable. + * @param {boolean} selectable Whether to only consider parts that are Part.selectable. */ findPartAt(p: Point, selectable: boolean): Part; @@ -784,45 +893,57 @@ declare module go { * Look for a Part or Node or Group corresponding to a model's data object's unique key. * @param {*} key a string or number. */ - findPartForKey(key: any): Part; + findPartForKey(key: Key): Part; /** * Returns an iterator of all Groups that are at top-level, in other words that are not themselves inside other Groups. */ - findTopLevelGroups(): Iterator; + findTopLevelGroups(): Iterator; /** * Returns an iterator of all top-level Nodes that have no tree parents. */ - findTreeRoots(): Iterator; + findTreeRoots(): Iterator; /** * Explicitly bring focus to the Diagram's canvas. */ - focus(); + focus(): void; /** - * This static method gets the Diagram that is attached to an HTML DIV element. + * This static function gets the Diagram that is attached to an HTML DIV element. * @param {HTMLDivElement} div */ static fromDiv(div: HTMLDivElement): Diagram; + /** + * Make the given part the only highlighted part. + * @param {Part} part + */ + highlight(part: Part): void; + + /** + * Highlight all of the Parts supplied in the given collection, and clear all other highlighted Parts. + * @param {Iterable|Array} coll an Iterable of Parts + */ + highlightCollection(coll: Iterable | Array): void; + /** * This static function declares that a class (constructor function) derives from another class -- but please note that most classes do not support inheritance. * @param {Function} derivedclass * @param {Function} baseclass */ - static inherit(derivedclass: new(...args: any[]) => Object, baseclass: new(...args: any[]) => Object); + static inherit(derivedclass: Constructor, baseclass: Constructor): void; /** * Perform all invalid layouts. - * @param {boolean=} invalidateAll If true, this will explicitly set Layout#isValidLayout to false on each Layout in the diagram. + * @param {boolean=} invalidateAll If true, this will explicitly set Layout.isValidLayout to false on each Layout in the diagram. */ - layoutDiagram(invalidateAll?: boolean); + layoutDiagram(invalidateAll?: boolean): void; /** * Create an HTMLImageElement that contains a bitmap of the current Diagram. - * @param {Object=} properties For details see the argument description of #makeImageData. + * @param {Object=} properties For details see the argument description of .makeImageData. */ makeImage(properties?: Object): HTMLImageElement; @@ -832,80 +953,123 @@ declare module go { scale: number, maxSize: Size, position: Point, - parts: Iterable, + parts: Iterable, padding: (Margin|number), showTemporary: boolean, showGrid: boolean, - + document: Document, type: string, - details: Object}=} properties a JavaScript object detailing optional arguments for image creation, to be passed to makeImageData. + details: * + }=} properties a JavaScript object detailing optional arguments for image creation, to be passed to makeImageData. */ makeImageData(properties?: Object): string; + /** + * Create an SVGElement that contains a SVG rendering of the current Diagram. + * By default this method returns a snapshot of the visible diagram, but optional arguments give more options. + * @param {{ size: Size, + scale: number, + maxSize: Size, + position: Point, + parts: Iterable, + padding: (Margin|number), + showTemporary: boolean, + showGrid: boolean, + document: Document, + elementFinished: function(GraphObject, SVGElement), + details: * + }=} properties a JavaScript object detailing optional arguments for SVG creation. + * @return {SVGElement} + */ + makeSvg(properties?: Object): SVGElement; + + /** + * Move a collection of Parts in this Diagram by a given offset. + * @param {Iterable} coll A List or a Set or Iterator of Parts. + * @param {Point} offset the X and Y change to be made to each Part, in document coordinates. + * @param {boolean} check Whether to check Part.canMove on each part. + */ + moveParts(coll: Iterable, offset: Point, check: boolean): void; + /** * Remove all of the Parts created from model data and then create them again. */ - rebuildParts(); + rebuildParts(): void; /** * Removes a Part from its Layer, provided the Layer is in this Diagram. * @param {Part} part */ - remove(part: Part); + remove(part: Part): void; /** * Unregister an event handler listener. * @param {function(ChangedEvent)} listener a function that takes a ChangedEvent as its argument. */ - removeChangedListener(listener: (e: ChangedEvent) => void); + removeChangedListener(listener: (e: ChangedEvent) => void ): void; /** * Unregister a DiagramEvent handler. * @param {string} name the name is normally capitalized, but this method uses case-insensitive comparison. * @param {function(DiagramEvent)} listener a function that takes a DiagramEvent as its argument. */ - removeDiagramListener(name: string, listener: (e: DiagramEvent) => void); + removeDiagramListener(name: string, listener: (e: DiagramEvent) => void ): void; /** * Removes the given layer from the list of layers. * @param {Layer} layer */ - removeLayer(layer: Layer); + removeLayer(layer: Layer): void; + + /** + * This method removes from this Diagram all of the Parts in a collection. + * @param {Iterable|Array} coll A List or Set or Iterator of Parts. + * @param {boolean} check Whether to check Part.canDelete on each part. + */ + removeParts(coll: Iterable | Array, check: boolean): void; /** * Rollback the current transaction, undoing any recorded changes. + * This just calls UndoManager.rollbackTransaction. */ rollbackTransaction(): boolean; /** - * Scrolling function used by primarily by #commandHandler's CommandHandler#doKeyDown. + * Scrolling function used by primarily by .commandHandler's CommandHandler.doKeyDown. * @param {string} unit A string representing the unit of the scroll operation. Can be 'pixel', 'line', or 'page'. * @param {string} dir The direction of the scroll operation. Can be 'up', 'down', 'left', or 'right'. * @param {number=} dist An optional distance multiplier, for multiple pixels, lines, or pages. Default is 1. */ - scroll(unit: string, dir: string, dist?: number); + scroll(unit: string, dir: string, dist?: number): void; /** - * Modifies the #position to show a given Rect of the Diagram by centering the viewport on that Rect. + * Modifies the .position to show a given Rect of the Diagram by centering the viewport on that Rect. * @param {Rect} r */ - scrollToRect(r: Rect); + scrollToRect(r: Rect): void; /** * Make the given object the only selected object. * @param {GraphObject} part a GraphObject that is already in a layer of this Diagram. * If the value is null, this does nothing. */ - select(part: Part); + select(part: Part): void; /** * Select all of the Parts supplied in the given collection. - * @param {Iterable} coll a List or Set of Parts to be selected. + * @param {Iterable|Array} coll a List or Set of Parts to be selected. */ - selectCollection(coll: Iterable); + selectCollection(coll: Iterable | Array): void; + + /** + * This method sets a collection of properties according to the property/value pairs that have been set on the given Object, + * in the same manner as GraphObject.make does when constructing a Diagram with an argument that is a simple JavaScript Object. + */ + setProperties(props: Object): void; /** * Begin a transaction, where the changes are held by a Transaction object in the UndoManager. + * This just calls UndoManager.startTransaction. * @param {string=} tname a descriptive name for the transaction. */ startTransaction(tname?: string): boolean; @@ -925,60 +1089,80 @@ declare module go { /** * Update all of the data-bound properties of Nodes and Links in this diagram. */ - updateAllTargetBindings(); + updateAllTargetBindings(): void; + + /** + * Update all of the references to nodes in case they had been modified in the model without + * properly notifying the model by calling GraphLinksModel.setGroupKeyForNodeData or + * GraphLinksModel.setToKeyForLinkData or other similar methods. + */ + updateAllRelationshipsFromData(): void; /** * Scales the Diagram to uniformly fit into the viewport. */ - zoomToFit(); + zoomToFit(): void; /** - * Modifies the #scale and #position of the Diagram so that the viewport displays a given document-coordinates rectangle. + * Modifies the .scale and .position of the Diagram so that the viewport displays a given document-coordinates rectangle. * @param {Rect} r rectangular bounds in document coordinates. - * @param {EnumValue=} scaling an optional value of either #Uniform (the default) or #UniformToFill. + * @param {EnumValue=} scaling an optional value of either .Uniform (the default) or .UniformToFill. */ - zoomToRect(r: Rect, scaling?: EnumValue); + zoomToRect(r: Rect, scaling?: EnumValue): void; - /**This value for Diagram#validCycle states that there are no restrictions on making cycles of links.*/ + /**This value for Diagram.validCycle states that there are no restrictions on making cycles of links.*/ static CycleAll: EnumValue; - /**This value for Diagram#validCycle states that any number of destination links may go out of a node, but at most one source link may come into a node, and there are no directed cycles.*/ + /**This value for Diagram.validCycle states that any number of destination links may go out of a node, but at most one source link may come into a node, and there are no directed cycles.*/ static CycleDestinationTree: EnumValue; - /**This value for Diagram#validCycle states that a valid link from a node will not produce a directed cycle in the graph.*/ + /**This value for Diagram.validCycle states that a valid link from a node will not produce a directed cycle in the graph.*/ static CycleNotDirected: EnumValue; - /**This value for Diagram#validCycle states that a valid link from a node will not produce an undirected cycle in the graph.*/ + /**This value for Diagram.validCycle states that a valid link from a node will not produce an undirected cycle in the graph.*/ static CycleNotUndirected: EnumValue; - /**This value for Diagram#validCycle states that any number of source links may come into a node, but at most one destination link may go out of a node, and there are no directed cycles.*/ + /**This value for Diagram.validCycle states that any number of source links may come into a node, but at most one destination link may go out of a node, and there are no directed cycles.*/ static CycleSourceTree: EnumValue; - /**The default autoScale type, used as the value of Diagram#autoScale: The Diagram does not attempt to scale its bounds to fit the view.*/ + /**The default autoScale type, used as the value of Diagram.autoScale: The Diagram does not attempt to scale its bounds to fit the view.*/ static None: EnumValue; - /**Diagrams with this autoScale type, used as the value of Diagram#autoScale, are scaled uniformly until the documentBounds fits in the view.*/ + /**Diagrams with this autoScale type, used as the value of Diagram.autoScale, are scaled uniformly until the documentBounds fits in the view.*/ static Uniform: EnumValue; - /**Diagrams with this autoScale type, used as the value of Diagram#autoScale, are scaled uniformly until the documentBounds fits in the view.*/ + /**Diagrams with this autoScale type, used as the value of Diagram.autoScale, are scaled uniformly until the documentBounds fits in the view.*/ static UniformToFill: EnumValue; - maybeUpdate(); // undocumented - requestUpdate(); // undocumented + /**This value for Diagram.scrollMode states that the viewport constrains scrolling to the Diagram document bounds.*/ + static DocumentScroll: EnumValue; + + /**This value for Diagram.scrollMode states that the viewport does not constrain scrolling to the Diagram document bounds.*/ + static InfiniteScroll: EnumValue; + + getRenderingHint(name: string): any; // undocumented + setRenderingHint(name: string, val: any): void; // undocumented + getInputOption(name: string): any; // undocumented + setInputOption(name: string, val: any): void; // undocumented + maybeUpdate(): void; // undocumented + requestUpdate(): void; // undocumented + reset(): void; // undocumented + simulatedMouseMove(e: Event, modelpt: Point, overdiag?: Diagram): boolean; // undocumented + simulatedMouseUp(e: Event, other: Diagram, modelpt: Point, curdiag?: Diagram): boolean; // undocumented } /** * A DiagramEvent represents a more abstract event than an InputEvent. * They are raised on the Diagram class. * One can receive such events by registering a DiagramEvent listener on a Diagram - * by calling Diagram#addDiagramListener. + * by calling Diagram.addDiagramListener. * Some DiagramEvents such as "ObjectSingleClicked" are normally * associated with InputEvents. * Some DiagramEvents such as "SelectionMoved" or "PartRotated" are associated with the * results of Tool-handled gestures or CommandHandler actions. * Some DiagramEvents are not necessarily associated with any input events at all, * such as "ViewportBoundsChanged", which can happen due to programmatic - * changes to the Diagram#position and Diagram#scale properties. + * changes to the Diagram.position and Diagram.scale properties. */ class DiagramEvent { /** @@ -989,7 +1173,7 @@ declare module go { /**Gets or sets whether any default actions associated with this diagram event should be avoided or cancelled.*/ cancel: boolean; - /**Gets the diagram associated with the event.*/ + /**This read-only property returns the diagram associated with the event.*/ diagram: Diagram; /**Gets or sets the name of the kind of diagram event that this represents.*/ @@ -999,7 +1183,7 @@ declare module go { parameter: any; /**Gets or sets an optional object that is the subject of the diagram event.*/ - subject: Object; + subject: any; } /** @@ -1011,19 +1195,19 @@ declare module go { */ constructor(); - /**Gets or sets the function to execute when the ActionTool is cancelled and this GraphObject's #isActionable is set to true.*/ + /**Gets or sets the function to execute when the ActionTool is cancelled and this GraphObject's .isActionable is set to true.*/ actionCancel: (e: InputEvent, obj: GraphObject) => void; - /**Gets or sets the function to execute on a mouse-down event when this GraphObject's #isActionable is set to true.*/ + /**Gets or sets the function to execute on a mouse-down event when this GraphObject's .isActionable is set to true.*/ actionDown: (e: InputEvent, obj: GraphObject) => void; - /**Gets or sets the function to execute on a mouse-move event when this GraphObject's #isActionable is set to true.*/ + /**Gets or sets the function to execute on a mouse-move event when this GraphObject's .isActionable is set to true.*/ actionMove: (e: InputEvent, obj: GraphObject) => void; - /**Gets or sets the function to execute on a mouse-up event when this GraphObject's #isActionable is set to true.*/ + /**Gets or sets the function to execute on a mouse-up event when this GraphObject's .isActionable is set to true.*/ actionUp: (e: InputEvent, obj: GraphObject) => void; - /**Gets the bounds of this GraphObject in container coordinates.*/ + /**This read-only property returns the bounds of this GraphObject in container coordinates.*/ actualBounds: Rect; /**Gets or sets the alignment Spot of this GraphObject used in Panel layouts, to determine where in the area allocated by the panel this object should be placed.*/ @@ -1036,10 +1220,10 @@ declare module go { angle: number; /**Gets or sets the areaBackground Brush (or CSS color string) of this GraphObject.*/ - areaBackground: any; + areaBackground: BrushLike; /**Gets or sets the background Brush (or CSS color string) of this GraphObject, filling the rectangle of this object's local coordinate space.*/ - background: any; + background: BrushLike; /**Gets or sets the function to execute when the user single-primary-clicks on this object.*/ click: (e: InputEvent, obj: GraphObject) => void; @@ -1062,7 +1246,7 @@ declare module go { /**Gets or sets the desired size of this GraphObject in local coordinates.*/ desiredSize: Size; - /**Gets the Diagram that this GraphObject is in, if it is.*/ + /**This read-only property returns the Diagram that this GraphObject is in, if it is.*/ diagram: Diagram; /**Gets or sets the function to execute when the user double-primary-clicks on this object.*/ @@ -1074,8 +1258,8 @@ declare module go { /**Gets or sets the length of the last segment of a link coming from this port.*/ fromEndSegmentLength: number; - /**Gets or sets whether the user may draw Links from this port.*/ - fromLinkable: any; + /**Gets or sets whether the user may draw Links from this port. The value must be either a boolean or null.*/ + fromLinkable: boolean; /**Gets or sets whether the user may draw duplicate Links from this port.*/ fromLinkableDuplicates: boolean; @@ -1101,16 +1285,16 @@ declare module go { /**Gets or sets whether a GraphObject is the "main" object for some types of Panel.*/ isPanelMain: boolean; - /**Gets the GraphObject's containing Layer, if there is any.*/ + /**This read-only property returns the GraphObject's containing Layer, if there is any.*/ layer: Layer; /**Gets or sets the size of empty area around this GraphObject, as a Margin (or number for a uniform Margin), in the containing Panel coordinates.*/ - margin: any; + margin: MarginLike; /**Gets or sets the maximum size of this GraphObject in container coordinates (either a Panel or the document).*/ maxSize: Size; - /**Gets the measuredBounds of the GraphObject in container coordinates (either a Panel or the document).*/ + /**This read-only property returns the measuredBounds of the GraphObject in container coordinates (either a Panel or the document).*/ measuredBounds: Rect; /**Gets or sets the minimum size of this GraphObject in container coordinates (either a Panel or the document).*/ @@ -1143,16 +1327,19 @@ declare module go { /**Gets or sets the name for this object.*/ name: string; - /**Gets the natural bounding rectangle of this GraphObject in local coordinates, before any transformation by #scale or #angle, and before any resizing due to #minSize or #maxSize or #stretch.*/ + /**This read-only property returns the natural bounding rectangle of this GraphObject in local coordinates, before any transformation by .scale or .angle, and before any resizing due to .minSize or .maxSize or .stretch.*/ naturalBounds: Rect; - /**Gets the GraphObject's containing Panel, or null if this object is not in a Panel.*/ + /**Gets or sets the multiplicative opacity for this GraphObject and (if a Panel) all nested elements.*/ + opacity: number; + + /**This read-only property returns the GraphObject's containing Panel, or null if this object is not in a Panel.*/ panel: Panel; - /**Gets the Part containing this object, if any.*/ + /**This read-only property returns the Part containing this object, if any.*/ part: Part; - /**Gets or sets whether or not this GraphObject can be chosen by visual "find" methods such as Diagram#findObjectAt.*/ + /**Gets or sets whether or not this GraphObject can be chosen by visual "find" methods such as Diagram.findObjectAt.*/ pickable: boolean; /**Gets or sets an identifier for an object acting as a port on a Node.*/ @@ -1191,8 +1378,8 @@ declare module go { /**Gets or sets the length of the last segment of a link going to this port.*/ toEndSegmentLength: number; - /**Gets or sets whether the user may draw Links to this port.*/ - toLinkable: any; + /**Gets or sets whether the user may draw Links to this port. The value must be either a boolean or null.*/ + toLinkable: boolean; /**Gets or sets whether the user may draw duplicate Links to this port.*/ toLinkableDuplicates: boolean; @@ -1222,13 +1409,20 @@ declare module go { * Add a data-binding of a property on this GraphObject to a property on a data object. * @param {Binding} binding */ - bind(binding: Binding); + bind(binding: Binding): void; /** * Creates a deep copy of this GraphObject and returns it. */ copy(): GraphObject; + /** + * This static function defines a named function that GraphObject.make can use to build objects. + * @param {string} name a capitalized name; must not be "" or "None" + * @param {function(Array<*>):Object} func + */ + static defineBuilder(name: string, func: (args: any[]) => Object): void; + /** * Returns the effective angle that the object is drawn at, in document coordinates. */ @@ -1262,10 +1456,16 @@ declare module go { isContainedBy(panel: GraphObject): boolean; /** - * This predicate is true if this object is #visible and each of its visual containing panels are also visible. + * This predicate is true if this object is .visible and each of its visual containing panels are also visible. */ isVisibleObject(): boolean; + /** + * This method sets a collection of properties according to the property/value pairs that have been set on the given Object, + * in the same manner as GraphObject.make does when constructing a GraphObject with an argument that is a simple JavaScript Object. + */ + setProperties(props: Object): void; + /** * This static function builds an object given its class and additional arguments providing initial properties or GraphObjects that become Panel elements. * @param {function()|string} type a class function or the name of a class in the "go" namespace, @@ -1279,28 +1479,33 @@ declare module go { * is recognized to take that value, * or a string that is used as the value of a commonly set property. */ - static make(type: any, ...initializers: any[]): any; + static make(type: Constructor | string, ...initializers: any[]): any; - /**GraphObjects with this as the value of GraphObject#stretch are stretched depending on the context they are used.*/ + /**GraphObjects with this as the value of GraphObject.stretch are stretched depending on the context they are used.*/ static Default: EnumValue; - /**GraphObjects with this as the value of GraphObject#stretch are scaled in both directions so as to fit exactly in the given bounds; there is no clipping but the aspect ratio may change, causing the object to appear stretched.*/ + /**GraphObjects with this as the value of GraphObject.stretch are scaled in both directions so as to fit exactly in the given bounds; there is no clipping but the aspect ratio may change, causing the object to appear stretched.*/ static Fill: EnumValue; - /**GraphObjects with this as the value of GraphObject#stretch are scaled as much as possible in the x-axis*/ + /**GraphObjects with this as the value of GraphObject.stretch are scaled as much as possible in the x-axis*/ static Horizontal: EnumValue; - /**GraphObjects with this as the value of GraphObject#stretch are not automatically scaled to fit in the given bounds; there may be clipping in one or both directions.*/ + /**GraphObjects with this as the value of GraphObject.stretch are not automatically scaled to fit in the given bounds; there may be clipping in one or both directions.*/ static None: EnumValue; - /**Pictures with this as the value of Picture#imageStretch are drawn with equal scale in both directions to fit the arranged (actual) bounds.*/ + /**Pictures with this as the value of Picture.imageStretch are drawn with equal scale in both directions to fit the arranged (actual) bounds.*/ static Uniform: EnumValue; - /**Pictures with this as the value of Picture#imageStretch are drawn with equal scale in both directions to fit the larger side of the image bounds.*/ + /**Pictures with this as the value of Picture.imageStretch are drawn with equal scale in both directions to fit the larger side of the image bounds.*/ static UniformToFill: EnumValue; - /**GraphObjects with this as the value of GraphObject#stretch are scaled as much as possible in the y-axis*/ + /**GraphObjects with this as the value of GraphObject.stretch are scaled as much as possible in the y-axis*/ static Vertical: EnumValue; + + protected cloneProtected(copy: GraphObject): void; // undocumented + static fromSvg(svg: string): GraphObject; // undocumented + static fromSvg(svg: Document): GraphObject; // undocumented + static getBuilders(): Map Object>; // undocumented } /** @@ -1314,10 +1519,19 @@ declare module go { */ constructor(type?: EnumValue); - /**Gets or sets whether the size of the area of the Group's #placeholder should remain the same during a DraggingTool move until a drop occurs.*/ + /**Gets or sets whether the size of the area of the Group's .placeholder should remain the same during a DraggingTool move until a drop occurs. The default value is false.*/ computesBoundsAfterDrag: boolean; - /**Gets or sets whether the subgraph contained by this group is expanded.*/ + /**Gets or sets whether the bounds of a Group's Placeholder includes the bounds of member Links. The default value is true.*/ + computesBoundsIncludingLinks: boolean; + + /**Gets or sets whether the bounds of a Group's Placeholder includes the previous Group.location. The default value is false.*/ + computesBoundsIncludingLocation: boolean; + + /**Gets or sets whether drag-and-drop events may be bubbled up to this Group if not handled by member Parts.*/ + handlesDragDropForMembers: boolean; + + /**Gets or sets whether the subgraph contained by this group is expanded. The default value is true.*/ isSubGraphExpanded: boolean; /**Gets or sets the Layout used to position all of the immediate member nodes and links in this group.*/ @@ -1326,8 +1540,8 @@ declare module go { /**Gets or sets the function that is called after a member Part has been added to this Group.*/ memberAdded: (a: Group, b: Part) => void; - /**Gets an iterator over the member Parts of this Group.*/ - memberParts: Iterator; + /**This read-only property returns an iterator over the member Parts of this Group.*/ + memberParts: Iterator; /**Gets or sets the function that is called after a member Part has been removed from this Group.*/ memberRemoved: (a: Group, b: Part) => void; @@ -1335,68 +1549,80 @@ declare module go { /**Gets or sets the predicate that determines whether or not a Part may become a member of this group.*/ memberValidation: (a: Group, b: Part) => boolean; - /**Gets a Placeholder that this group may contain in its visual tree.*/ + /**This read-only property returns a Placeholder that this group may contain in its visual tree.*/ placeholder: Placeholder; - /**Gets or sets the function that is called when #isSubGraphExpanded has changed value.*/ + /**Gets or sets the function that is called when .isSubGraphExpanded has changed value.*/ subGraphExpandedChanged: (a: Group) => void; /**Gets or sets whether the user may ungroup this group.*/ ungroupable: boolean; - /**Gets or sets whether the subgraph starting at this group had been collapsed by a call to #expandSubGraph on the containing Group.*/ + /**Gets or sets whether the subgraph starting at this group had been collapsed by a call to .expandSubGraph on the containing Group.*/ wasSubGraphExpanded: boolean; /** - * Add the Parts in the given collection as members of this Group for those Parts for which CommandHandler#isValidMember returns true. - * @param {Iterable} coll - * @param {boolean=} check whether to call CommandHandler#isValidMember to confirm that it is valid to add the Part to be a member of this Group. + * Add the Parts in the given collection as members of this Group for those Parts for which CommandHandler.isValidMember returns true. + * @param {Iterable} coll + * @param {boolean=} check whether to call CommandHandler.isValidMember to confirm that it is valid to add the Part to be a member of this Group. */ - addMembers(coll: Iterable, check?: boolean): boolean; + addMembers(coll: Iterable, check?: boolean): boolean; /** - * See if the given collection of Parts contains non-Links all for which CommandHandler#isValidMember returns true. - * @param {Iterable} coll + * See if the given collection of Parts contains non-Links all for which CommandHandler.isValidMember returns true. + * @param {Iterable} coll */ - canAddMembers(coll: Iterable): boolean; + canAddMembers(coll: Iterable): boolean; /** - * This predicate returns true if #ungroupable is true, if the layer's Layer#allowUngroup is true, and if the diagram's Diagram#allowUngroup is true. + * This predicate returns true if .ungroupable is true, if the layer's Layer.allowUngroup is true, and if the diagram's Diagram.allowUngroup is true. */ canUngroup(): boolean; /** * Hide each of the member nodes and links of this group, and recursively collapse any member groups. */ - collapseSubGraph(); + collapseSubGraph(): void; /** * Show each member node and link, and perhaps recursively expand nested subgraphs. */ - expandSubGraph(); + expandSubGraph(): void; + + /** + * Returns an iterator over all of the Links that connect with this group or any node contained by this group, + * in either direction, but that are not internal to this group. + */ + findExternalLinksConnected(): Iterator; + + /** + * Returns an iterator over all of the Nodes that are connected with this group or any node contained by this group, + * by a link in either direction, but that are not internal to this group. + */ + findExternalNodesConnected(): Iterator; /** * Return a collection of Parts that are all of the nodes and links that are members of this group, including inside nested groups, but excluding this group itself. */ - findSubGraphParts(): Set; + findSubGraphParts(): Set; /** * Move this Group and all of its member parts, recursively. * @param {Point} newpos a new Point in document coordinates. */ - move(newpos: Point); + move(newpos: Point): void; } /** * An InputEvent represents a mouse or keyboard event. * The principal properties hold information about a particular input event. - * These properties include the #documentPoint at which a mouse event + * These properties include the .documentPoint at which a mouse event * occurred in document coordinates, - * the corresponding point in view/element coordinates, #viewPoint, - * the #key for keyboard events, - * and the #modifiers and #button at the time. - * Additional descriptive properties include #clickCount, #delta, - * #timestamp, and the source event #event (if available). + * the corresponding point in view/element coordinates, .viewPoint, + * the .key for keyboard events, + * and the .modifiers and .button at the time. + * Additional descriptive properties include .clickCount, .delta, + * .timestamp, and the source event .event (if available). */ class InputEvent { /** @@ -1404,10 +1630,10 @@ declare module go { */ constructor(); - /**Gets whether the alt key is being held down.*/ + /**Gets or sets whether the alt key is being held down.*/ alt: boolean; - /**Gets or sets whether the underlying #event is prevented from bubbling up the hierarchy of HTML elements outside of the Diagram and whether any default action is canceled.*/ + /**Gets or sets whether the underlying .event is prevented from bubbling up the hierarchy of HTML elements outside of the Diagram and whether any default action is canceled.*/ bubbles: boolean; /**Gets or sets the button that caused this event.*/ @@ -1416,13 +1642,13 @@ declare module go { /**Gets or sets whether this event represents a click or a double-click.*/ clickCount: number; - /**Gets whether the control key is being held down.*/ + /**Gets or sets whether the control key is being held down.*/ control: boolean; /**Gets or sets the amount of change associated with a mouse-wheel rotation.*/ delta: number; - /**Gets the source diagram associated with the event.*/ + /**This read-only property returns the source diagram associated with the event.*/ diagram: Diagram; /**Gets or sets the point at which this input event occurred, in document coordinates.*/ @@ -1437,25 +1663,31 @@ declare module go { /**Gets or sets whether an InputEvent that applies to a GraphObject and bubbles up the chain of containing Panels is stopped from continuing up the chain.*/ handled: boolean; + /**This property is true when the InputEvent is caused by a touch event that registered more than one touch.*/ + isMultiTouch: boolean; + + /**This read-only property is true when the InputEvent is caused by a touch event.*/ + isTouchEvent: boolean; + /**Gets or sets the key pressed or released as this event.*/ key: string; - /**Gets whether the logical left mouse button is being held down.*/ + /**Gets or sets whether the logical left mouse button is being held down.*/ left: boolean; - /**Gets whether the meta key is being held down.*/ + /**Gets or sets whether the meta key is being held down.*/ meta: boolean; - /**Gets whether the logical middle mouse button is being held down.*/ + /**Gets or sets whether the logical middle mouse button is being held down.*/ middle: boolean; /**Gets or sets the modifier keys that were used with the mouse or keyboard event.*/ modifiers: number; - /**Gets whether the logical right mouse button is being held down.*/ + /**Gets or sets whether the logical right mouse button is being held down.*/ right: boolean; - /**Gets whether the shift key is being held down.*/ + /**Gets or sets whether the shift key is being held down.*/ shift: boolean; /**Gets or sets the diagram associated with the canvas that the event is currently targeting.*/ @@ -1485,7 +1717,7 @@ declare module go { */ class Layer { /** - * This constructs an empty Layer; you should set the #name before adding the Layer to a Diagram. + * This constructs an empty Layer; you should set the .name before adding the Layer to a Diagram. */ constructor(); @@ -1525,7 +1757,7 @@ declare module go { /**Gets or sets whether the user may ungroup existing groups in this layer.*/ allowUngroup: boolean; - /**Gets the Diagram that is using this Layer.*/ + /**This read-only property returns the Diagram that is using this Layer.*/ diagram: Diagram; /**Gets or sets whether the objects in this layer are considered temporary.*/ @@ -1537,13 +1769,13 @@ declare module go { /**Gets or sets the opacity for all parts in this layer.*/ opacity: number; - /**Gets an iterator for this Layer's Parts.*/ - parts: Iterator; + /**This read-only property returns an iterator for this Layer's Parts.*/ + parts: Iterator; - /**Gets a backwards iterator for this Layer's Parts, for iterating over the parts in reverse order.*/ - partsBackwards: Iterator; + /**This read-only property returns a backwards iterator for this Layer's Parts, for iterating over the parts in reverse order.*/ + partsBackwards: Iterator; - /**Gets or sets whether methods such as #findObjectAt find any of the objects in this layer.*/ + /**Gets or sets whether methods such as .findObjectAt find any of the objects in this layer.*/ pickable: boolean; /**Gets or sets whether the user may view any of the objects in this layer.*/ @@ -1571,8 +1803,8 @@ declare module go { * defaulting to a predicate that always returns true. * @param {List|Set=} coll An optional collection (List or Set) to add the results to. */ - findObjectsAt(p: Point, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, coll?: List): Iterable; - findObjectsAt(p: Point, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, coll?: Set): Iterable; + findObjectsAt(p: Point, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, coll?: List): List; + findObjectsAt(p: Point, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, coll?: Set): Set; /** * Returns a collection of all GraphObjects that are inside or that intersect a given Rect in document coordinates. @@ -1587,8 +1819,8 @@ declare module go { * if it must be entirely inside the rectangular area (false). The default value is false. * @param {List|Set=} coll An optional collection (List or Set) to add the results to. */ - findObjectsIn(r: Rect, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, partialInclusion?: boolean, coll?: List): Iterable; - findObjectsIn(r: Rect, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, partialInclusion?: boolean, coll?: Set): Iterable; + findObjectsIn(r: Rect, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, partialInclusion?: boolean, coll?: List): List; + findObjectsIn(r: Rect, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, partialInclusion?: boolean, coll?: Set): Set; /** * Returns a collection of all GraphObjects that are within a certain distance of a given point in document coordinates. @@ -1604,15 +1836,15 @@ declare module go { * if it must be entirely inside the circular area (false). The default value is true. * @param {List|Set=} coll An optional collection (List or Set) to add the results to. */ - findObjectsNear(p: Point, dist: number, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, partialInclusion?: boolean, coll?: List): Iterable; - findObjectsNear(p: Point, dist: number, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, partialInclusion?: boolean, coll?: Set): Iterable; + findObjectsNear(p: Point, dist: number, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, partialInclusion?: boolean, coll?: List): List; + findObjectsNear(p: Point, dist: number, navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean, partialInclusion?: boolean, coll?: Set): Set; } /** * A Link is a Part that connects Nodes. - * The link relationship is directional, going from Link#fromNode to Link#toNode. - * A link can connect to a specific port element in a node, as named by the Link#fromPortId - * and Link#toPortId properties. + * The link relationship is directional, going from Link.fromNode to Link.toNode. + * A link can connect to a specific port element in a node, as named by the Link.fromPortId + * and Link.toPortId properties. */ class Link extends Part { /** @@ -1623,13 +1855,13 @@ declare module go { /**Gets or sets how the route is computed, including whether it uses the points of its old route to determine the new route.*/ adjusting: EnumValue; - /**Gets or sets how rounded the corners are for adjacent line segments when the #curve is #None #JumpGap, or #JumpOver and the two line segments are orthogonal to each other.*/ + /**Gets or sets how rounded the corners are for adjacent line segments when the .curve is .None .JumpGap, or .JumpOver and the two line segments are orthogonal to each other.*/ corner: number; /**Gets or sets the way the path is generated from the route's points.*/ curve: EnumValue; - /**Gets or sets how far the control points are offset when the #curve is #Bezier or when there are multiple links between the same two ports.*/ + /**Gets or sets how far the control points are offset when the .curve is .Bezier or when there are multiple links between the same two ports.*/ curviness: number; /**Gets or sets how the direction of the last segment is computed when the node is rotated.*/ @@ -1641,7 +1873,7 @@ declare module go { /**Gets or sets the Node that this link comes from.*/ fromNode: Node; - /**Gets a GraphObject that is the "from" port that this link is connected from.*/ + /**This read-only property returns a GraphObject that is the "from" port that this link is connected from.*/ fromPort: GraphObject; /**Gets or sets the function that is called after this Link changes which Node or port it connects from.*/ @@ -1653,37 +1885,37 @@ declare module go { /**Gets or sets how far the end segment stops short of the actual port.*/ fromShortLength: number; - /**Gets or sets where this link should connect at the #fromPort.*/ + /**Gets or sets where this link should connect at the .fromPort.*/ fromSpot: Spot; - /**Gets the Geometry that is used by the #path, the link Shape based on the route points.*/ + /**This read-only property returns the Geometry that is used by the .path, the link Shape based on the route points.*/ geometry: Geometry; /**This read-only property is true when this Link has any label Nodes, Nodes that are owned by this Link and are arranged along its path.*/ isLabeledLink: boolean; - /**This read-only property true if #routing is a value that implies that the points of the route should be orthogonal, such that each point shares a common X or a common Y value with the immediately previous and next points.*/ + /**This read-only property true if .routing is a value that implies that the points of the route should be orthogonal, such that each point shares a common X or a common Y value with the immediately previous and next points.*/ isOrthogonal: boolean; - /**Gets or sets whether this Link is part of the tree for tree operations such as Node#findTreeChildrenNodes or Node#collapseTree.*/ + /**Gets or sets whether this Link is part of the tree for tree operations such as Node.findTreeChildrenNodes or Node.collapseTree.*/ isTreeLink: boolean; - /**Gets an iterator over the Nodes that act as labels on this Link.*/ - labelNodes: Iterator; + /**This read-only property returns an iterator over the Nodes that act as labels on this Link.*/ + labelNodes: Iterator; - /**Gets the angle of the path at the #midPoint.*/ + /**This read-only property returns the angle of the path at the .midPoint.*/ midAngle: number; - /**Gets the point at the middle of the path.*/ + /**This read-only property returns the point at the middle of the path.*/ midPoint: Point; - /**Gets the Shape representing the path of this Link.*/ + /**This read-only property returns the Shape representing the path of this Link.*/ path: Shape; - /**Gets or sets the List of Points in the route.*/ - points: List; + /**Gets or sets the List of Points in the route. Can also be set as an Array of numbers.*/ + points: List; - /**Gets the number of points in the route.*/ + /**This read-only property returns the number of points in the route.*/ pointsCount: number; /**Gets or sets whether the user may reconnect an existing link at the "from" end.*/ @@ -1698,10 +1930,10 @@ declare module go { /**Gets or sets whether the link's path tries to avoid other nodes.*/ routing: EnumValue; - /**Gets or sets how far the control points are from the points of the route when #routing is #Orthogonal and #curve is #Bezier.*/ + /**Gets or sets how far the control points are from the points of the route when .routing is .Orthogonal and .curve is .Bezier.*/ smoothness: number; - /**Gets or sets how far the control points are from the points of the route when #routing is #Orthogonal and #curve is #Bezier.*/ + /**Gets or sets how far the control points are from the points of the route when .routing is .Orthogonal and .curve is .Bezier.*/ toEndSegmentDirection: EnumValue; /**Gets or sets the length of the last segment.*/ @@ -1710,7 +1942,7 @@ declare module go { /**Gets or sets the Node that this link goes to.*/ toNode: Node; - /**Gets a GraphObject that is the "to" port that this link is connected to.*/ + /**This read-only property returns a GraphObject that is the "to" port that this link is connected to.*/ toPort: GraphObject; /**Gets or sets the function that is called after this Link changes which Node or port it connects to.*/ @@ -1722,16 +1954,16 @@ declare module go { /**Gets or sets how far the end segment stops short of the actual port.*/ toShortLength: number; - /**Gets or sets where this link should connect at the #toPort.*/ + /**Gets or sets where this link should connect at the .toPort.*/ toSpot: Spot; /** - * This predicate returns true if #relinkableFrom is true, if the layer's Layer#allowRelink is true, and if the diagram's Diagram#allowRelink is true. + * This predicate returns true if .relinkableFrom is true, if the layer's Layer.allowRelink is true, and if the diagram's Diagram.allowRelink is true. */ canRelinkFrom(): boolean; /** - * This predicate returns true if #relinkableTo is true, if the layer's Layer#allowRelink is true, and if the diagram's Diagram#allowRelink is true. + * This predicate returns true if .relinkableTo is true, if the layer's Layer.allowRelink is true, and if the diagram's Diagram.allowRelink is true. */ canRelinkTo(): boolean; @@ -1765,7 +1997,7 @@ declare module go { * @param {GraphObject} otherport the GraphObject port at the other end of the link. * @param {Point=} result an optional Point that is modified and returned; otherwise it allocates and returns a new Point */ - getLinkPoint(node: Node, port: GraphObject, spot: Spot, from: boolean, ortho: boolean, othernode: Node, otherport: GraphObject, result?: Point) + getLinkPoint(node: Node, port: GraphObject, spot: Spot, from: boolean, ortho: boolean, othernode: Node, otherport: GraphObject, result?: Point): Point; /** * Compute the intersection point for the edge of a particular port GraphObject, given a point, when no particular spot or side has been specified. @@ -1802,61 +2034,85 @@ declare module go { * Move this link to a new position. * @param {Point} newpos */ - move(newpos: Point); + move(newpos: Point): void; - /**Used as a value for Link#routing: each segment is horizontal or vertical, but the route tries to avoid crossing over nodes.*/ + /**Used as a value for Link.routing: each segment is horizontal or vertical, but the route tries to avoid crossing over nodes.*/ static AvoidsNodes: EnumValue; - /**Used as a value for Link#curve, to indicate that the link path uses Bezier curve segments.*/ + /**Used as a value for Link.curve, to indicate that the link path uses Bezier curve segments.*/ static Bezier: EnumValue; - /**Used as a value for Link#adjusting, to indicate that the link route computation should keep the intermediate points of the previous route, just modifying the first and/or last points; if the routing is orthogonal, it will only modify the first two and/or last two points.*/ + /**Used as a value for Link.adjusting, to indicate that the link route computation should keep the intermediate points of the previous route, just modifying the first and/or last points; if the routing is orthogonal, it will only modify the first two and/or last two points.*/ static End: EnumValue; - /**Used as a value for Link#curve, to indicate that orthogonal link segments will be discontinuous where they cross over other orthogonal link segments that have a Link#curve or JumpOver or JumpGap.*/ + /**Used as a value for Link.curve, to indicate that orthogonal link segments will be discontinuous where they cross over other orthogonal link segments that have a Link.curve or JumpOver or JumpGap.*/ static JumpGap: EnumValue; - /**Used as a value for Link#curve, to indicate that orthogonal link segments will veer around where they cross over other orthogonal link segments that have a Link#curve or JumpOver or JumpGap.*/ + /**Used as a value for Link.curve, to indicate that orthogonal link segments will veer around where they cross over other orthogonal link segments that have a Link.curve or JumpOver or JumpGap.*/ static JumpOver: EnumValue; - /**This is the default value for Link#curve and Link#adjusting, to indicate that the path geometry consists of straight line segments and to indicate that the link route computation does not depend on any previous route points; this can also be used as a value for GraphObject#segmentOrientation to indicate that the object is never rotated along the link route -- its angle is unchanged.*/ + /**This is the default value for Link.curve and Link.adjusting, to indicate that the path geometry consists of straight line segments and to indicate that the link route computation does not depend on any previous route points; this can also be used as a value for GraphObject.segmentOrientation to indicate that the object is never rotated along the link route -- its angle is unchanged.*/ static None: EnumValue; - /**Used as the default value for Link#routing: the route goes fairly straight between ports.*/ + /**Used as the default value for Link.routing: the route goes fairly straight between ports.*/ static Normal: EnumValue; - /**This value for GraphObject#segmentOrientation results in the GraphObject turned to have the same angle as the route: the GraphObject's angle is always the same as the angle of the link's route at the segment where the GraphObject is attached; use this orientation for arrow heads.*/ + /**This value for GraphObject.segmentOrientation results in the GraphObject turned to have the same angle as the route: the GraphObject's angle is always the same as the angle of the link's route at the segment where the GraphObject is attached; use this orientation for arrow heads.*/ static OrientAlong: EnumValue; - /**This value for GraphObject#segmentOrientation results in the GraphObject being turned counter-clockwise to be perpendicular to the route: the GraphObject's angle is always 90 degrees less than the angle of the link's route at the segment where the GraphObject is attached.*/ + /**This value for GraphObject.segmentOrientation results in the GraphObject being turned counter-clockwise to be perpendicular to the route: the GraphObject's angle is always 90 degrees less than the angle of the link's route at the segment where the GraphObject is attached.*/ static OrientMinus90: EnumValue; - /**This value for GraphObject#segmentOrientation results in the GraphObject turned counter-clockwise to be perpendicular to the route, just like Link#OrientMinus90, but is never upside down: the GraphObject's angle always being 90 degrees less than the angle of the link's route at the segment where the GraphObject is attached; this is typically only used for TextBlocks or Panels that contain text.*/ + /**This value for GraphObject.segmentOrientation results in the GraphObject turned counter-clockwise to be perpendicular to the route, just like Link.OrientMinus90, but is never upside down: the GraphObject's angle always being 90 degrees less than the angle of the link's route at the segment where the GraphObject is attached; this is typically only used for TextBlocks or Panels that contain text.*/ static OrientMinus90Upright: EnumValue; - /**This value for GraphObject#segmentOrientation results in the GraphObject's angle always being 180 degrees opposite from the angle of the link's route at the segment where the GraphObject is attached.*/ + /**This value for GraphObject.segmentOrientation results in the GraphObject's angle always being 180 degrees opposite from the angle of the link's route at the segment where the GraphObject is attached.*/ static OrientOpposite: EnumValue; - /**This value for GraphObject#segmentOrientation results in the GraphObject is turned clockwise to be perpendicular to the route: the GraphObject's angle is always 90 degrees more than the angle of the link's route at the segment where the GraphObject is attached.*/ + /**This value for GraphObject.segmentOrientation results in the GraphObject is turned clockwise to be perpendicular to the route: the GraphObject's angle is always 90 degrees more than the angle of the link's route at the segment where the GraphObject is attached.*/ static OrientPlus90: EnumValue; - /**This value for GraphObject#segmentOrientation results in the GraphObject turned clockwise to be perpendicular to the route, just like Link#OrientPlus90, but is never upside down: the GraphObject's angle always being 90 degrees more than the angle of the link's route at the segment where the GraphObject is attached; this is typically only used for TextBlocks or Panels that contain text.*/ + /**This value for GraphObject.segmentOrientation results in the GraphObject turned clockwise to be perpendicular to the route, just like Link.OrientPlus90, but is never upside down: the GraphObject's angle always being 90 degrees more than the angle of the link's route at the segment where the GraphObject is attached; this is typically only used for TextBlocks or Panels that contain text.*/ static OrientPlus90Upright: EnumValue; - /**This value for GraphObject#segmentOrientation results in the GraphObject turned to have the same angle as the route, just like Link#OrientAlong, but is never upside down: the GraphObject's angle always following the angle of the link's route at the segment where the GraphObject is attached; this is typically only used for TextBlocks or Panels that contain text.*/ + /**This value for GraphObject.segmentOrientation results in the GraphObject turned to have the same angle as the route, just like Link.OrientAlong, but is never upside down: the GraphObject's angle always following the angle of the link's route at the segment where the GraphObject is attached; this is typically only used for TextBlocks or Panels that contain text.*/ static OrientUpright: EnumValue; - /**This value for GraphObject#segmentOrientation results in the GraphObject's angle always following the angle of the link's route at the segment where the GraphObject is attached, but never upside down and never angled more than +/- 45 degrees: when the route's angle is within 45 degrees of vertical (90 or 270 degrees), the GraphObject's angle is set to zero; this is typically only used for TextBlocks or Panels that contain text.*/ + /**This value for GraphObject.segmentOrientation results in the GraphObject's angle always following the angle of the link's route at the segment where the GraphObject is attached, but never upside down and never angled more than +/- 45 degrees: when the route's angle is within 45 degrees of vertical (90 or 270 degrees), the GraphObject's angle is set to zero; this is typically only used for TextBlocks or Panels that contain text.*/ static OrientUpright45: EnumValue; - /**Used as a value for Link#routing: each segment is horizontal or vertical.*/ + /**Used as a value for Link.routing: each segment is horizontal or vertical.*/ static Orthogonal: EnumValue; - /**Used as a value for Link#adjusting, to indicate that the link route computation should scale and rotate the intermediate points so that the link's shape looks approximately the same; if the routing is orthogonal, this value is treated as if it were Link#End.*/ + /**Used as a value for Link.adjusting, to indicate that the link route computation should scale and rotate the intermediate points so that the link's shape looks approximately the same; if the routing is orthogonal, this value is treated as if it were Link.End.*/ static Scale: EnumValue; - /**Used as a value for Link#adjusting, to indicate that the link route computation should linearly interpolate the intermediate points so that the link's shape looks stretched; if the routing is orthogonal, this value is treated as if it were Link#End.*/ + /**Used as a value for Link.adjusting, to indicate that the link route computation should linearly interpolate the intermediate points so that the link's shape looks stretched; if the routing is orthogonal, this value is treated as if it were Link.End.*/ static Stretch: EnumValue; + + routeBounds: Rect; // undocumented + protected computeEndSegmentLength(node: Node, port: GraphObject, spot: Spot, from: boolean): number; // undocumented + protected computeSpot(from: boolean): Spot; // undocumented + protected computeOtherPoint(othernode: Node, otherport: GraphObject): Point; // undocumented + protected computeShortLength(from: boolean): number; // undocumented + protected computeCurve(): EnumValue; // undocumented + protected computeCorner(): number; // undocumented + protected computeCurviness(): number; // undocumented + protected computeThickness(): number; // undocumented + hasCurviness(): boolean; // undocumented + invalidateRoute(): void; // undocumented + updateRoute(): void; // undocumented + protected computePoints(): boolean; // undocumented + clearPoints(): void; // undocumented + addPoint(p: Point): void; // undocumented + addPointAt(x: number, y: number): void; // undocumented + insertPoint(i: number, p: Point): void; // undocumented + insertPointAt(i: number, x: number, y: number): void; // undocumented + removePoint(i: number): void; // undocumented + setPoint(i: number, p: Point): void; // undocumented + setPointAt(i: number, x: number, y: number): void; // undocumented + invalidateGeometry(): void; // undocumented + makeGeometry(): Geometry; // undocumented } /** @@ -1868,17 +2124,17 @@ declare module go { class Node extends Part { /** * Constructs an empty Node. - * @param {EnumValue=} type if not supplied, the default Panel type is Panel#Position. + * @param {EnumValue=} type if not supplied, the default Panel type is Panel.Position. */ constructor(type?: EnumValue); - /**Gets or sets whether this Node is to be avoided by Links whose Link#routing is Link#AvoidsNodes.*/ + /**Gets or sets whether this Node is to be avoided by Links whose Link.routing is Link.AvoidsNodes.*/ avoidable: boolean; /**Gets or sets the Margin (or number for a uniform Margin) around this Node in which avoidable links will not be routed.*/ - avoidableMargin: any; + avoidableMargin: MarginLike; - /**Gets whether a Node is a label node for a Link.*/ + /**This read-only property is true when this Node is a label node for a Link.*/ isLinkLabel: boolean; /**Gets or sets whether the subtree graph starting at this node is expanded.*/ @@ -1896,19 +2152,25 @@ declare module go { /**Gets or sets the function that is called after a Link has been disconnected from this Node.*/ linkDisconnected: (a: Node, b: Link, c: GraphObject) => void; - /**Gets an iterator over all of the Links that are connected with this node.*/ - linksConnected: Iterator; + /**Gets or sets a predicate that determines whether or not a Link may be connected with this node; any of the arguments may be null.*/ + linkValidation: (from: Node, fromPort: GraphObject, to: Node, toPort: GraphObject, link: Link) => boolean; - /**Get the primary GraphObject representing a port in this node.*/ + /**This read-only property returns an iterator over all of the Links that are connected with this node.*/ + linksConnected: Iterator; + + /**This read-only property returns the primary GraphObject representing a port in this node.*/ port: GraphObject; - /**Gets an iterator over all of the GraphObjects in this node that act as ports.*/ - ports: Iterator; + /**This read-only property returns an iterator over all of the GraphObjects in this node that act as ports.*/ + ports: Iterator; - /**Gets or sets the function that is called when #isTreeExpanded has changed value.*/ + /**Gets or sets how link points are computed when the port spot is a "side" spot.*/ + portSpreading: EnumValue; + + /**Gets or sets the function that is called when .isTreeExpanded has changed value.*/ treeExpandedChanged: (node: Node) => void; - /**Gets or sets whether the subtree graph starting at this node had been collapsed by a call to #expandTree on the parent node.*/ + /**Gets or sets whether the subtree graph starting at this node had been collapsed by a call to .expandTree on the parent node.*/ wasTreeExpanded: boolean; /** @@ -1916,7 +2178,7 @@ declare module go { * @param {number=} level How many levels of the tree, starting at this node, to keep expanded if already expanded; * the default is 1, hiding all tree children of this node. Values less than 1 are treated as 1. */ - collapseTree(level?: number); + collapseTree(level?: number): void; /** * Show each child node and the connecting link, and perhaps recursively expand their child nodes. @@ -1924,7 +2186,7 @@ declare module go { * the default is 2, showing all tree children of this node and potentially more. * Values less than 2 are treated as 2. */ - expandTree(level?: number); + expandTree(level?: number): void; /** * Returns an iterator over all of the Links that go from this node to another node or vice-versa, perhaps limited to a given port id on this node and a port id on the other node. @@ -1932,25 +2194,25 @@ declare module go { * @param {string|null=} pid A port identifier string; if null the link's portId is ignored and all links are included in the search. * @param {string|null=} otherpid A port identifier string; if null the link's portId is ignored and all links are included in the search. */ - findLinksBetween(othernode: Node, pid?: string, otherpid?: string): Iterator; + findLinksBetween(othernode: Node, pid?: string, otherpid?: string): Iterator; /** * Returns an iterator over all of the Links that connect with this node in either direction, perhaps limited to the given port id on this node. * @param {string|null=} pid A port identifier string; if null the link's portId is ignored and all links are included in the search. */ - findLinksConnected(pid?: string): Iterator; + findLinksConnected(pid?: string): Iterator; /** * Returns an iterator over all of the Links that go into this node, perhaps limited to the given port id on this node. * @param {string|null=} pid A port identifier string; if null the link's portId is ignored and all links are included in the search. */ - findLinksInto(pid?: string): Iterator; + findLinksInto(pid?: string): Iterator; /** * Returns an iterator over all of the Links that come out of this node, perhaps limited to the given port id on this node. * @param {string|null=} pid A port identifier string; if null the link's portId is ignored and all links are included in the search. */ - findLinksOutOf(pid?: string): Iterator; + findLinksOutOf(pid?: string): Iterator; /** * Returns an iterator over all of the Links that go from this node to another node, perhaps limited to a given port id on this node and a port id on the other node. @@ -1958,28 +2220,28 @@ declare module go { * @param {string|null=} pid A port identifier string; if null the link's portId is ignored and all links are included in the search. * @param {string|null=} otherpid A port identifier string; if null the link's portId is ignored and all links are included in the search. */ - findLinksTo(othernode: Node, pid?: string, otherpid?: string): Iterator; + findLinksTo(othernode: Node, pid?: string, otherpid?: string): Iterator; /** * Returns an iterator over the Nodes that are connected with this node in either direction, perhaps limited to the given port id on this node. * @param {string|null=} pid A port identifier string; if null the link's portId is ignored and all links are included in the search. */ - findNodesConnected(pid?: string): Iterator; + findNodesConnected(pid?: string): Iterator; /** * Returns an iterator over the Nodes that are connected with this node by links going into this node, perhaps limited to the given port id on this node. * @param {string|null=} pid A port identifier string; if null the link's portId is ignored and all links are included in the search. */ - findNodesInto(pid?: string): Iterator; + findNodesInto(pid?: string): Iterator; /** * Returns an iterator over the Nodes that are connected with this node by links coming out of this node, perhaps limited to the given port id on this node. * @param {string|null=} pid A port identifier string; if null the link's portId is ignored and all links are included in the search. */ - findNodesOutOf(pid?: string): Iterator; + findNodesOutOf(pid?: string): Iterator; /** - * Find a GraphObject with a given GraphObject#portId. + * Find a GraphObject with a given GraphObject.portId. * @param {string} pid */ findPort(pid: string): GraphObject; @@ -1987,15 +2249,21 @@ declare module go { /** * Returns an Iterator for the collection of Links that connect with the immediate tree children of this node. */ - findTreeChildrenLinks(): Iterator; + findTreeChildrenLinks(): Iterator; /** * Returns an Iterator for the collection of Nodes that are the immediate tree children of this node. */ - findTreeChildrenNodes(): Iterator; + findTreeChildrenNodes(): Iterator; /** - * Returns the Link that connects with the tree parent Node of this node if the graph is tree-structured, if there is such a link and Link#isTreeLink is true. + * Return how deep this node is in a tree structure. + * For tree root nodes, this returns zero. + */ + findTreeLevel(): number; + + /** + * Returns the Link that connects with the tree parent Node of this node if the graph is tree-structured, if there is such a link and Link.isTreeLink is true. */ findTreeParentLink(): Link; @@ -2009,7 +2277,7 @@ declare module go { * @param {number=} level How many levels of the tree, starting at this node, to include; * the default is Infinity, including all tree children of this node. Values less than 1 are treated as 1. */ - findTreeParts(level?: number): Set; + findTreeParts(level?: number): Set; /** * Return the Node that is at the root of the tree that this node is in, perhaps this node itself. @@ -2022,23 +2290,32 @@ declare module go { */ isInTreeOf(node: Node): boolean; - /**This value for GraphObject#fromEndSegmentDirection and GraphObject#toEndSegmentDirection indicates that the link's end segment angle stays the same even if the node is rotated.*/ + /**This value for GraphObject.fromEndSegmentDirection and GraphObject.toEndSegmentDirection indicates that the link's end segment angle stays the same even if the node is rotated.*/ static DirectionAbsolute: EnumValue; - /**This value for Link#fromEndSegmentDirection and Link#toEndSegmentDirection indicates that the real value is inherited from the corresponding connected port.*/ + /**This value for Link.fromEndSegmentDirection and Link.toEndSegmentDirection indicates that the real value is inherited from the corresponding connected port.*/ static DirectionDefault: EnumValue; - /**This value for GraphObject#fromEndSegmentDirection and GraphObject#toEndSegmentDirection indicates that the link's end segment angle is rotated to match the node's angle.*/ + /**This value for GraphObject.fromEndSegmentDirection and GraphObject.toEndSegmentDirection indicates that the link's end segment angle is rotated to match the node's angle.*/ static DirectionRotatedNode: EnumValue; - /**This value for GraphObject#fromEndSegmentDirection and GraphObject#toEndSegmentDirection indicates that the link's end segment angle is rotated to match the node's angle, but only in increments of 90 degrees.*/ + /**This value for GraphObject.fromEndSegmentDirection and GraphObject.toEndSegmentDirection indicates that the link's end segment angle is rotated to match the node's angle, but only in increments of 90 degrees.*/ static DirectionRotatedNodeOrthogonal: EnumValue; + + /**This value for Node.portSpreading indicates that links connecting with a port should be distributed evenly along the side(s) indicated by a Spot that is a "side" Spot.*/ + static SpreadingEvenly: EnumValue; + + /**This value for Node.portSpreading indicates that links connecting with a port should connect at a single point on the side(s) indicated by a Spot that is a "side" Spot.*/ + static SpreadingNone: EnumValue; + + /**This value for Node.portSpreading indicates that links connecting with a port should be packed together based on the link's shape's width on the side(s) indicated by a Spot that is a "side" Spot.*/ + static SpreadingPacked: EnumValue; } /** * An Overview is a Diagram that displays all of a different diagram, * with a rectangular box showing the viewport displayed by that other diagram. - * All you need to do is set Overview#observed. + * All you need to do is set Overview.observed. */ class Overview extends Diagram { /** @@ -2050,7 +2327,7 @@ declare module go { */ constructor(id?: string); - /**Gets or sets the rectangular Part that represents the viewport of the #observed Diagram.*/ + /**Gets or sets the rectangular Part that represents the viewport of the .observed Diagram.*/ box: Part; /**Gets or sets whether this overview draws the temporary layers of the observed Diagram.*/ @@ -2062,8 +2339,8 @@ declare module go { /** * Palette extends the Diagram class to allow objects to be dragged and placed onto other Diagrams. - * Its Diagram#layout is a GridLayout. - * The Palette is Diagram#isReadOnly but to support drag-and-drop its Diagram#allowDragOut is true. + * Its Diagram.layout is a GridLayout. + * The Palette is Diagram.isReadOnly but to support drag-and-drop its Diagram.allowDragOut is true. */ class Palette extends Diagram { /** @@ -2079,102 +2356,102 @@ declare module go { /** * A Panel is a GraphObject that holds other GraphObjects as its elements. * A Panel is responsible for sizing and positioning its elements. - * Every Panel has a #type and establishes its own coordinate system. The #type of a Panel + * Every Panel has a .type and establishes its own coordinate system. The .type of a Panel * determines how it will size and arrange its elements. */ class Panel extends GraphObject { /** - * Constructs an empty Panel of the given #type. - * @param {EnumValue=} type If not supplied, the default Panel type is Panel#Position. + * Constructs an empty Panel of the given .type. + * @param {EnumValue=} type If not supplied, the default Panel type is Panel.Position. */ constructor(type?: EnumValue); - /**Gets the number of columns in this Panel if it is of #type Panel#Table.*/ + /**This read-only property returns the number of columns in this Panel if it is of .type Panel.Table.*/ columnCount: number; - /**Gets or sets how this Panel's columns deal with extra space if the Panel is of #type Panel#Table.*/ + /**Gets or sets how this Panel's columns deal with extra space if the Panel is of .type Panel.Table.*/ columnSizing: EnumValue; /**Gets or sets the optional model data to which this panel is data-bound.*/ - data: Object; + data: any; - /**Gets or sets the default alignment spot of this Panel, used as the alignment for an element when its GraphObject#alignment value is Spot#Default.*/ + /**Gets or sets the default alignment spot of this Panel, used as the alignment for an element when its GraphObject.alignment value is Spot.Default.*/ defaultAlignment: Spot; /**Gets or sets the default dash array for a particular column's separator.*/ - defaultColumnSeparatorDashArray: any[]; + defaultColumnSeparatorDashArray: Array; - /**Gets or sets the default Brush stroke (or CSS color string) for columns in a Table Panel provided a given column has a nonzero RowColumnDefinition#separatorStrokeWidth.*/ - defaultColumnSeparatorStroke: any; + /**Gets or sets the default Brush stroke (or CSS color string) for columns in a Table Panel provided a given column has a nonzero RowColumnDefinition.separatorStrokeWidth.*/ + defaultColumnSeparatorStroke: BrushLike; /**Gets or sets the default stroke width for a particular column's separator.*/ defaultColumnSeparatorStrokeWidth: number; /**Gets or sets the default dash array for a particular row's separator.*/ - defaultRowSeparatorDashArray: any[]; + defaultRowSeparatorDashArray: Array; - /**Gets or sets the default Brush stroke (or CSS color string) for rows in a Table Panel provided a given row has a nonzero RowColumnDefinition#separatorStrokeWidth.*/ - defaultRowSeparatorStroke: any; + /**Gets or sets the default Brush stroke (or CSS color string) for rows in a Table Panel provided a given row has a nonzero RowColumnDefinition.separatorStrokeWidth.*/ + defaultRowSeparatorStroke: BrushLike; /**Gets or sets the default stroke width for a particular row's separator.*/ defaultRowSeparatorStrokeWidth: number; /**Gets or sets the additional padding for a particular row or column, a Margin (or number for a uniform Margin).*/ - defaultSeparatorPadding: any; + defaultSeparatorPadding: MarginLike; - /**Gets or sets the default stretch of this Panel, used as the stretch for an element when its GraphObject#stretch value is GraphObject#Default.*/ + /**Gets or sets the default stretch of this Panel, used as the stretch for an element when its GraphObject.stretch value is GraphObject.Default.*/ defaultStretch: EnumValue; - /**Gets an iterator over the collection of the GraphObjects that this panel manages.*/ - elements: Iterator; + /**This read-only property returns an iterator over the collection of the GraphObjects that this panel manages.*/ + elements: Iterator; - /**Gets or sets the distance between lines in a #Grid panel.*/ + /**Gets or sets the distance between lines in a .Grid panel.*/ gridCellSize: Size; - /**Gets or sets an origin point for the grid cells in a #Grid panel.*/ + /**Gets or sets an origin point for the grid cells in a .Grid panel.*/ gridOrigin: Point; /**Gets or sets a JavaScript Array of values or objects, each of which will be represented by a Panel as elements in this Panel.*/ - itemArray: any[]; + itemArray: Array; /**Gets or sets the name of the item data property that returns a string describing that data's category, or a function that takes an item data object and returns that string; the default value is the name 'category'.*/ - itemCategoryProperty: any; + itemCategoryProperty: PropertyAccessor; - /**Gets or sets the default Panel template used as the archetype for item data that are in #itemArray.*/ + /**This read-only property returns the index of the item in the containing Panel's Panel.itemArray that this Panel represents.*/ + itemIndex: number; + + /**Gets or sets the default Panel template used as the archetype for item data that are in .itemArray.*/ itemTemplate: Panel; /**Gets or sets a Map mapping template names to Panels.*/ - itemTemplateMap: Map; + itemTemplateMap: Map; - /**Gets or sets the first column that this Panel of #type Panel#Table displays.*/ + /**Gets or sets the first column that this Panel of .type Panel.Table displays.*/ leftIndex: number; - /**Gets or sets the multiplicative opacity for this Panel and all children.*/ - opacity: number; - /**Gets or sets the space between this Panel's border and its content, as a Margin (or number for a uniform Margin), depending on the type of panel.*/ - padding: any; + padding: MarginLike; - /**Gets the number of row in this Panel if it is of #type Panel#Table.*/ + /**This read-only property returns the number of row in this Panel if it is of .type Panel.Table.*/ rowCount: number; - /**Gets or sets how this Panel's rows deal with extra space if the Panel is of #type Panel#Table.*/ + /**Gets or sets how this Panel's rows deal with extra space if the Panel is of .type Panel.Table.*/ rowSizing: EnumValue; - /**Gets or sets the first row that this this Panel of #type Panel#Table displays.*/ + /**Gets or sets the first row that this this Panel of .type Panel.Table displays.*/ topIndex: number; /**Gets or sets the type of the Panel.*/ type: EnumValue; - /**Gets or sets how a #Viewbox panel will resize its content.*/ + /**Gets or sets how a .Viewbox panel will resize its content.*/ viewboxStretch: EnumValue; /** * Adds a GraphObject to the end of this Panel's list of elements, visually in front of all of the other elements. * @param {GraphObject} element A GraphObject. */ - add(element: GraphObject); + add(element: GraphObject): void; /** * Creates a deep copy of this Panel and returns it. @@ -2194,7 +2471,13 @@ declare module go { findColumnForLocalX(x: number): number; /** - * Search the visual tree starting at this Panel for a GraphObject whose GraphObject#name is the given name. + * Returns the first immediate child element with GraphObject.isPanelMain set to true, + * or if there is no such child element, just the first element. + */ + findMainElement(): GraphObject; + + /** + * Search the visual tree starting at this Panel for a GraphObject whose GraphObject.name is the given name. * @param {string} name The name to search for, using a case-sensitive string comparison. */ findObject(name: string): GraphObject; @@ -2222,64 +2505,64 @@ declare module go { * @param {number} index * @param {GraphObject} element A GraphObject. */ - insertAt(index: number, element: GraphObject); + insertAt(index: number, element: GraphObject): void; /** - * Create and add new GraphObjects corresponding to and bound to the data in the #itemArray, after removing all existing elements from this Panel. + * Create and add new GraphObjects corresponding to and bound to the data in the .itemArray, after removing all existing elements from this Panel. */ - rebuildItemElements(); + rebuildItemElements(): void; /** * Removes a GraphObject from this Panel's list of elements. * @param {GraphObject} element A GraphObject. */ - remove(element: GraphObject); + remove(element: GraphObject): void; /** * Removes an GraphObject from this Panel's list of elements at the specified index. * @param {number} idx */ - removeAt(idx: number); + removeAt(idx: number): void; /** * Removes the RowColumnDefinition for a particular row in this Table Panel. * @param {number} idx the non-negative zero-based integer row index. */ - removeColumnDefinition(idx: number); + removeColumnDefinition(idx: number): void; /** * Removes the RowColumnDefinition for a particular row in this Table Panel. * @param {number} idx the non-negative zero-based integer row index. */ - removeRowDefinition(idx: number); + removeRowDefinition(idx: number): void; /** - * Re-evaluate all data bindings on this panel, in order to assign new property values to the GraphObjects in this visual tree based on this this object's #data property values. + * Re-evaluate all data bindings on this panel, in order to assign new property values to the GraphObjects in this visual tree based on this this object's .data property values. * @param {string=} srcprop An optional source data property name: * when provided, only evaluates those Bindings that use that particular property; * when not provided or when it is the empty string, all bindings are evaluated. */ - updateTargetBindings(srcprop?: string); + updateTargetBindings(srcprop?: string): void; - /**This value for #type resizes the main element to fit around the other elements; the main element is the first GraphObject with GraphObject#isPanelMain set to true, or else the first GraphObject if none have that property set to true.*/ + /**This value for .type resizes the main element to fit around the other elements; the main element is the first GraphObject with GraphObject.isPanelMain set to true, or else the first GraphObject if none have that property set to true.*/ static Auto: EnumValue; - /**This value for #type is used to draw regular patterns of lines.*/ + /**This value for .type is used to draw regular patterns of lines.*/ static Grid: EnumValue; - /**This value for #type lays out the elements horizontally with their GraphObject#alignment property dictating their alignment on the Y-axis.*/ + /**This value for .type lays out the elements horizontally with their GraphObject.alignment property dictating their alignment on the Y-axis.*/ static Horizontal: EnumValue; - /**This value for #type is used for Links and adornments that act as Links.*/ + /**This value for .type is used for Links and adornments that act as Links.*/ static Link: EnumValue; - /**The default #type arranges each element according to their GraphObject#position.*/ + /**The default .type arranges each element according to their GraphObject.position.*/ static Position: EnumValue; - /**This value for #type arranges GraphObjects about a main element using the GraphObject#alignment and GraphObject#alignmentFocus properties; the main element is the first GraphObject with GraphObject#isPanelMain set to true, or else the first GraphObject if none have that property set to true.*/ + /**This value for .type arranges GraphObjects about a main element using the GraphObject.alignment and GraphObject.alignmentFocus properties; the main element is the first GraphObject with GraphObject.isPanelMain set to true, or else the first GraphObject if none have that property set to true.*/ static Spot: EnumValue; - /**This value for #type arranges GraphObjects into rows and columns; set the GraphObject#row and GraphObject#column properties on each element.*/ + /**This value for .type arranges GraphObjects into rows and columns; set the GraphObject.row and GraphObject.column properties on each element.*/ static Table: EnumValue; /**Organizational Panel type that is only valid inside of a Table panel.*/ @@ -2288,29 +2571,29 @@ declare module go { /**Organizational Panel type that is only valid inside of a Table panel.*/ static TableRow: EnumValue; - /**This value for #type lays out the elements vertically with their GraphObject#alignment property dictating their alignment on the X-axis.*/ + /**This value for .type lays out the elements vertically with their GraphObject.alignment property dictating their alignment on the X-axis.*/ static Vertical: EnumValue; - /**This value for #type rescales a single GraphObject to fit inside the panel depending on the element's GraphObject#stretch property.*/ + /**This value for .type rescales a single GraphObject to fit inside the panel depending on the element's GraphObject.stretch property.*/ static Viewbox: EnumValue; } /** * This is the base class for all user-manipulated top-level objects. - * Because it inherits from Panel}, it is automatically a visual container + * Because it inherits from Panel, it is automatically a visual container * of other GraphObjects. - * Because it thus also inherits from GraphObject}, it also has properties such as - * GraphObject#actualBounds}, GraphObject#contextMenu}, and GraphObject#visible}. + * Because it thus also inherits from GraphObject, it also has properties such as + * GraphObject.actualBounds, GraphObject.contextMenu, and GraphObject.visible. */ class Part extends Panel { /** * The constructor builds an empty Part. - * @param {EnumValue=} type if not supplied, the default Panel type is Panel#Position. + * @param {EnumValue=} type if not supplied, the default Panel type is Panel.Position. */ constructor(type?: EnumValue); - /**Gets an iterator over all of the Adornments associated with this part.*/ - adornments: Iterator; + /**This read-only property returns an iterator over all of the Adornments associated with this part.*/ + adornments: Iterator; /**Gets or sets the category of this part, typically used to distinguish different kinds of nodes or links.*/ category: string; @@ -2327,7 +2610,7 @@ declare module go { /**Gets or sets whether the user may delete this part.*/ deletable: boolean; - /**Gets the Diagram that this Part is in.*/ + /**This read-only property returns the Diagram that this Part is in.*/ diagram: Diagram; /**Gets or sets the function used to determine the location that this Part can be dragged to.*/ @@ -2336,6 +2619,12 @@ declare module go { /**Gets or sets whether the user may group this part to be a member of a new Group.*/ groupable: boolean; + /**Gets or sets whether this Part may be animated.*/ + isAnimated: boolean; + + /**Gets or sets whether this Part is highlighted.*/ + isHighlighted: boolean; + /**Gets or sets whether this Part is part of the document bounds.*/ isInDocumentBounds: boolean; @@ -2351,7 +2640,7 @@ declare module go { /**Gets whether this part is not member of any Group node nor is it a label node for a Link.*/ isTopLevel: boolean; - /**Gets the Layer that this Part is in.*/ + /**This read-only property returns the Layer that this Part is in.*/ layer: Layer; /**Gets or sets the function to execute when this part changes layers.*/ @@ -2363,16 +2652,16 @@ declare module go { /**Gets or sets "Layout..." flags that control when the Layout that is responsible for this Part is invalidated.*/ layoutConditions: number; - /**Gets or sets the position of this part in document coordinates, based on the #locationSpot in this part's #locationObject.*/ + /**Gets or sets the position of this part in document coordinates, based on the .locationSpot in this part's .locationObject.*/ location: Point; - /**Gets the GraphObject that determines the location of this Part.*/ + /**This read-only property returns the GraphObject that determines the location of this Part.*/ locationObject: GraphObject; /**Gets or sets the name of the GraphObject that provides the location of this Part.*/ locationObjectName: string; - /**Gets or sets the location Spot of this Node, the spot on the #locationObject that is used in positioning this part in the diagram.*/ + /**Gets or sets the location Spot of this Node, the spot on the .locationObject that is used in positioning this part in the diagram.*/ locationSpot: Spot; /**Gets or sets the maximum location of this Part to which the user may drag using the DraggingTool.*/ @@ -2396,7 +2685,7 @@ declare module go { /**Gets or sets the width and height multiples used when resizing.*/ resizeCellSize: Size; - /**Gets the GraphObject that should get resize handles when this part is selected.*/ + /**This read-only property returns the GraphObject that should get resize handles when this part is selected.*/ resizeObject: GraphObject; /**Gets or sets the name of the GraphObject that should get a resize handle when this part is selected.*/ @@ -2408,7 +2697,7 @@ declare module go { /**Gets or sets the adornment template used to create a rotation handle Adornment for this part.*/ rotateAdornmentTemplate: Adornment; - /**Gets the GraphObject that should get rotate handles when this part is selected.*/ + /**This read-only property returns the GraphObject that should get rotate handles when this part is selected.*/ rotateObject: GraphObject; /**Gets or sets the name of the GraphObject that should get a rotate handle when this part is selected.*/ @@ -2426,7 +2715,7 @@ declare module go { /**Gets or sets the function to execute when this part is selected or deselected.*/ selectionChanged: (p: Part) => void; - /**Gets the GraphObject that should get a selection handle when this part is selected.*/ + /**This read-only property returns the GraphObject that should get a selection handle when this part is selected.*/ selectionObject: GraphObject; /**Gets or sets the name of the GraphObject that should get a selection handle when this part is selected.*/ @@ -2444,7 +2733,7 @@ declare module go { /**Gets or sets a text string that is associated with this part.*/ text: string; - /**Gets or sets whether the user may do in-place text editing on TextBlocks in this part that have TextBlock#editable set to true.*/ + /**Gets or sets whether the user may do in-place text editing on TextBlocks in this part that have TextBlock.editable set to true.*/ textEditable: boolean; /** @@ -2452,25 +2741,25 @@ declare module go { * @param {string} category a string identifying the kind or role of the given adornment for this Part. * @param {Adornment} ad */ - addAdornment(category: string, ad: Adornment); + addAdornment(category: string, ad: Adornment): void; /** - * This predicate returns true if #copyable is true, if the layer's Layer#allowCopy is true, and if the diagram's Diagram#allowCopy is true. + * This predicate returns true if .copyable is true, if the layer's Layer.allowCopy is true, and if the diagram's Diagram.allowCopy is true. */ canCopy(): boolean; /** - * This predicate returns true if #deletable is true, if the layer's Layer#allowDelete is true, and if the diagram's Diagram#allowDelete is true. + * This predicate returns true if .deletable is true, if the layer's Layer.allowDelete is true, and if the diagram's Diagram.allowDelete is true. */ canDelete(): boolean; /** - * This predicate returns true if #textEditable is true, if the layer's Layer#allowTextEdit is true, and if the diagram's Diagram#allowTextEdit is true. + * This predicate returns true if .textEditable is true, if the layer's Layer.allowTextEdit is true, and if the diagram's Diagram.allowTextEdit is true. */ canEdit(): boolean; /** - * This predicate returns true if #groupable is true, if the layer's Layer#allowGroup is true, and if the diagram's Diagram#allowGroup is true. + * This predicate returns true if .groupable is true, if the layer's Layer.allowGroup is true, and if the diagram's Diagram.allowGroup is true. */ canGroup(): boolean; @@ -2480,34 +2769,34 @@ declare module go { canLayout(): boolean; /** - * This predicate returns true if #movable is true, if the layer's Layer#allowMove is true, and if the diagram's Diagram#allowMove is true. + * This predicate returns true if .movable is true, if the layer's Layer.allowMove is true, and if the diagram's Diagram.allowMove is true. */ canMove(): boolean; /** - * This predicate returns true if #reshapable is true, if the layer's Layer#allowReshape is true, and if the diagram's Diagram#allowReshape is true. + * This predicate returns true if .reshapable is true, if the layer's Layer.allowReshape is true, and if the diagram's Diagram.allowReshape is true. */ canReshape(): boolean; /** - * This predicate returns true if #resizable is true, if the layer's Layer#allowResize is true, and if the diagram's Diagram#allowResize is true. + * This predicate returns true if .resizable is true, if the layer's Layer.allowResize is true, and if the diagram's Diagram.allowResize is true. */ canResize(): boolean; /** - * This predicate returns true if #rotatable is true, if the layer's Layer#allowRotate is true, and if the diagram's Diagram#allowRotate is true. + * This predicate returns true if .rotatable is true, if the layer's Layer.allowRotate is true, and if the diagram's Diagram.allowRotate is true. */ canRotate(): boolean; /** - * This predicate returns true if #selectable is true, if the layer's Layer#allowSelect is true, and if the diagram's Diagram#allowSelect is true. + * This predicate returns true if .selectable is true, if the layer's Layer.allowSelect is true, and if the diagram's Diagram.allowSelect is true. */ canSelect(): boolean; /** * Remove all adornments associated with this part. */ - clearAdornments(); + clearAdornments(): void; /** * Find an Adornment of a given category associated with this Part. @@ -2522,7 +2811,13 @@ declare module go { findCommonContainingGroup(other: Part): Group; /** - * Gets the top-level Part for this part, which is itself when #isTopLevel is true. + * Return how deep this part is in the hierarchy of nested Groups. + * For top level parts, i.e. isTopLevel, this returns zero. + */ + findSubGraphLevel(): number; + + /** + * Gets the top-level Part for this part, which is itself when .isTopLevel is true. */ findTopLevelPart(): Part; @@ -2530,10 +2825,10 @@ declare module go { * Invalidate the Layout that is responsible for positioning this Part. * @param {number=} condition the reason that the layout should be invalidated -- * some combination of "Layout..." flag values; - * if this argument is not supplied, any value of #layoutConditions other than Part#LayoutNone + * if this argument is not supplied, any value of .layoutConditions other than Part.LayoutNone * will allow the layout to be invalidated. */ - invalidateLayout(condition?: number); + invalidateLayout(condition?: number): void; /** * This predicate is true if this part is a member of the given Part, perhaps indirectly. @@ -2550,62 +2845,73 @@ declare module go { * Move this part and any parts that are owned by this part to a new position. * @param {Point} newpos a new Point in document coordinates. */ - move(newpos: Point); + move(newpos: Point): void; /** * Remove any Adornment of the given category that may be associated with this Part. * @param {string} category a string identifying the kind or role of the given adornment for this Part. */ - removeAdornment(category: string); + removeAdornment(category: string): void; /** - * This is responsible for creating any selection Adornment (if this Part #isSelected) and any tool adornments for this part.*/ - updateAdornments(); + * This is responsible for creating any selection Adornment (if this Part .isSelected) and any tool adornments for this part.*/ + updateAdornments(): void; /** - * Re-evaluate all data bindings on this Part, in order to assign new property values to the GraphObjects in this visual tree based on this this object's #data property values. + * Re-evaluate all data bindings on this Part, in order to assign new property values to the GraphObjects in this visual tree based on this this object's .data property values. * @param {string=} srcprop An optional source data property name: * when provided, only evaluates those Bindings that use that particular property; * when not provided or when it is the empty string, all bindings are evaluated. */ - updateTargetBindings(srcprop?: string); + updateTargetBindings(srcprop?: string): void; - /**This flag may be combined with other "Layout" flags as the value of the Part#layoutConditions property to indicate that when a Part is added to a Diagram or Group, it invalidates the Layout responsible for the Part.*/ + /** + * Update all of the references to nodes in case they had been modified in the model without + * properly notifying the model by calling GraphLinksModel.setGroupKeyForNodeData or + * GraphLinksModel.setToKeyForLinkData or other similar methods. + */ + updateRelationshipsFromData(): void; + + /**This flag may be combined with other "Layout" flags as the value of the Part.layoutConditions property to indicate that when a Part is added to a Diagram or Group, it invalidates the Layout responsible for the Part.*/ static LayoutAdded: number; - /**This flag may be combined with other "Layout" flags as the value of the Part#layoutConditions property to indicate that when a Group has been laid out, it invalidates the Layout responsible for that Group; this flag is ignored for Parts that are not Groups.*/ + /**This flag may be combined with other "Layout" flags as the value of the Part.layoutConditions property to indicate that when a Group has been laid out, it invalidates the Layout responsible for that Group; this flag is ignored for Parts that are not Groups.*/ static LayoutGroupLayout: number; - /**This flag may be combined with other "Layout" flags as the value of the Part#layoutConditions property to indicate that when a Part's GraphObject#visible becomes false, it invalidates the Layout responsible for the Part.*/ + /**This flag may be combined with other "Layout" flags as the value of the Part.layoutConditions property to indicate that when a Part's GraphObject.visible becomes false, it invalidates the Layout responsible for the Part.*/ static LayoutHidden: number; - /**This flag may be combined with other "Layout" flags as the value of the Part#layoutConditions property to indicate that when a Part's GraphObject#actualBounds changes size, it invalidates the Layout responsible for the Part; this flag is ignored for Parts that are Links.*/ + /**This flag may be combined with other "Layout" flags as the value of the Part.layoutConditions property to indicate that when a Node or simple Part's .category changes, it invalidates the Layout responsible for the Part; this flag is ignored for Parts that are Links.*/ + static LayoutNodeReplaced: number; + + /**This flag may be combined with other "Layout" flags as the value of the Part.layoutConditions property to indicate that when a Part's GraphObject.actualBounds changes size, it invalidates the Layout responsible for the Part; this flag is ignored for Parts that are Links.*/ static LayoutNodeSized: number; - /**This value may be used as the value of the Part#layoutConditions property to indicate that no operation on this Part causes invalidation of the Layout responsible for this Part.*/ + /**This value may be used as the value of the Part.layoutConditions property to indicate that no operation on this Part causes invalidation of the Layout responsible for this Part.*/ static LayoutNone: number; - /**This flag may be combined with other "Layout" flags as the value of the Part#layoutConditions property to indicate that when a Part is removed from a Diagram or Group, it invalidates the Layout responsible for the Part.*/ + /**This flag may be combined with other "Layout" flags as the value of the Part.layoutConditions property to indicate that when a Part is removed from a Diagram or Group, it invalidates the Layout responsible for the Part.*/ static LayoutRemoved: number; - /**This flag may be combined with other "Layout" flags as the value of the Part#layoutConditions property to indicate that when a Part's GraphObject#visible becomes true, it invalidates the Layout responsible for the Part.*/ + /**This flag may be combined with other "Layout" flags as the value of the Part.layoutConditions property to indicate that when a Part's GraphObject.visible becomes true, it invalidates the Layout responsible for the Part.*/ static LayoutShown: number; - /**This is the default value for the Part#layoutConditions property: the Layout responsible for the Part is invalidated when the Part is added or removed from the Diagram or Group or when it changes visibility or size or when a Group's layout has been performed.*/ + /**This is the default value for the Part.layoutConditions property: the Layout responsible for the Part is invalidated when the Part is added or removed from the Diagram or Group or when it changes visibility or size or when a Group's layout has been performed.*/ static LayoutStandard: number; - ensureBounds(); // undocumented + ensureBounds(): void; // undocumented + moveTo(x: number, y: number): void; // undocumented } /** * A Picture is a GraphObject that shows an image, video-frame, or Canvas element. - * You can specify what to show by either setting the #source URL property - * to a URL string or the #element property to an HTMLImageElement, + * You can specify what to show by either setting the .source URL property + * to a URL string or the .element property to an HTMLImageElement, * HTMLCanvasElement, or HTMLVideoElement. */ class Picture extends GraphObject { /** - * The constructor creates a picture that shows nothing until the #source or #element is specified. + * The constructor creates a picture that shows nothing until the .source or .element is specified. */ constructor(); @@ -2618,52 +2924,57 @@ declare module go { /**Gets or sets how the Picture's image is stretched within its bounding box.*/ imageStretch: EnumValue; - /**Gets the natural size of this picture as determined by its source's width and height.*/ + /**This read-only property returns the natural size of this picture as determined by its source's width and height.*/ naturalBounds: Rect; /**Gets or sets the Picture's source URL, which can be any valid image (png, jpg, gif, etc) URL.*/ source: string; + /**Gets or sets a function that returns a value for image.crossOrigin, which is null by default.*/ + sourceCrossOrigin: (pic: Picture) => string; + /**Gets or sets the rectangular area of the source image that this picture should display.*/ sourceRect: Rect; + + static clearCache(url?: string): void; // undocumented } /** * If a Placeholder is in the visual tree of a Group, it represents the area of all of the member Parts of that Group. - * If a Placeholder is in the visual tree of an Adornment, it represents the area of the Adornment#adornedObject. + * If a Placeholder is in the visual tree of an Adornment, it represents the area of the Adornment.adornedObject. * It can only be used in the visual tree of a Group node or an Adornment. * There can be at most one Placeholder in a Group or an Adornment. */ class Placeholder extends GraphObject { /** - * The only common initialize of a Placeholder is to set its #padding. + * The only common initialize of a Placeholder is to set its .padding. */ constructor(); - /**Gets or sets the padding as a Margin (or number for a uniform Margin) around the members of the Group or around the Adornment#adornedObject GraphObject.*/ - padding: any; + /**Gets or sets the padding as a Margin (or number for a uniform Margin) around the members of the Group or around the Adornment.adornedObject GraphObject.*/ + padding: MarginLike; } /** * The RowColumnDefinition class describes constraints on a row or a column - * in a Panel of type Panel#Table. + * in a Panel of type Panel.Table. * It also provides information about the actual layout after the * Table Panel has been arranged. */ class RowColumnDefinition { /** - * You do not need to use this constructor, because calls to Panel#getRowDefinition or Panel#getColumnDefinition will automatically create and remember a RowColumnDefinition for you. + * You do not need to use this constructor, because calls to Panel.getRowDefinition or Panel.getColumnDefinition will automatically create and remember a RowColumnDefinition for you. */ constructor(); - /**Gets the usable row height or column width, after arrangement, that objects in this row or column can be placed within.*/ + /**This read-only property returns the usable row height or column width, after arrangement, that objects in this row or column can be placed within.*/ actual: number; /**Gets or sets a default alignment for elements that are in this row or column.*/ alignment: Spot; /**Gets or sets the background Brush (or CSS color string) for a particular row or column, which fills the entire span of the column, including any separatorPadding.*/ - background: any; + background: BrushLike; /**Determines whether or not the background, if there is one, is in front of or behind the separators.*/ coversSeparators: boolean; @@ -2671,10 +2982,10 @@ declare module go { /**Gets or sets the row height.*/ height: number; - /**Gets which row or column this RowColumnDefinition describes in the #panel.*/ + /**This read-only property returns which row or column this RowColumnDefinition describes in the .panel.*/ index: number; - /**Gets whether this describes a row or a column in the #panel.*/ + /**This read-only property returns whether this describes a row or a column in the .panel.*/ isRow: boolean; /**Gets or sets the maximum row height or column width.*/ @@ -2683,20 +2994,20 @@ declare module go { /**Gets or sets the minimum row height or column width.*/ minimum: number; - /**Gets the Panel that this row or column definition is in.*/ + /**This read-only property returns the Panel that this row or column definition is in.*/ panel: Panel; - /**Gets the actual arranged row or column starting position, after arrangement.*/ + /**This read-only property returns the actual arranged row or column starting position, after arrangement.*/ position: number; - /**Gets or sets the dash array for dashing the spacing provided this row or column has a nonzero RowColumnDefinition#separatorStrokeWidth and non-null RowColumnDefinition#separatorStroke.*/ - separatorDashArray: any[]; + /**Gets or sets the dash array for dashing the spacing provided this row or column has a nonzero RowColumnDefinition.separatorStrokeWidth and non-null RowColumnDefinition.separatorStroke.*/ + separatorDashArray: Array; /**Gets or sets the additional padding for a particular row or column, a Margin (or number for a uniform Margin).*/ - separatorPadding: any; + separatorPadding: MarginLike; - /**Gets or sets the Brush (or CSS color string) for a particular row or column, provided that row or column has a nonzero RowColumnDefinition#separatorStrokeWidth.*/ - separatorStroke: any; + /**Gets or sets the Brush (or CSS color string) for a particular row or column, provided that row or column has a nonzero RowColumnDefinition.separatorStrokeWidth.*/ + separatorStroke: BrushLike; /**Gets or sets the stroke width for a particular row or column's separator,*/ separatorStrokeWidth: number; @@ -2707,7 +3018,7 @@ declare module go { /**Gets or sets the default stretch for elements that are in this row or column.*/ stretch: EnumValue; - /**Gets the total arranged row height or column width, after arrangement.*/ + /**This read-only property returns the total arranged row height or column width, after arrangement.*/ total: number; /**Gets or sets the column width.*/ @@ -2717,27 +3028,30 @@ declare module go { * Add a data-binding of a property on this object to a property on a data object. * @param {Binding} binding */ - bind(binding: Binding); + bind(binding: Binding): void; - /**The default #sizing, which resolves to RowColumnDefinition#None or else the Table Panel's rowSizing and columnSizing if present.*/ + /**The default .sizing, which resolves to RowColumnDefinition.None or else the Table Panel's rowSizing and columnSizing if present.*/ static Default: EnumValue; - /**The default #sizing if none is specified on the Table Panel's rowSizing and columnSizing.*/ + /**The default .sizing if none is specified on the Table Panel's rowSizing and columnSizing.*/ static None: EnumValue; - /**If a Table Panel is larger than all the rows then this #sizing grants this row and any others with the same value the extra space, apportioned proportionally between them*/ + /**If a Table Panel is larger than all the rows then this .sizing grants this row and any others with the same value the extra space, apportioned proportionally between them*/ static ProportionalExtra: EnumValue; + + computeEffectiveSpacing(): number; // undocumented + computeEffectiveSpacingTop(): number; // undocumented } /** * A Shape is a GraphObject that shows a geometric figure. * The Geometry determines what is drawn; - * the properties #fill and #stroke + * the properties .fill and .stroke * (and other stroke properties) determine how it is drawn. */ class Shape extends GraphObject { /** - * A newly constructed Shape has a default #figure of "None", which constructs a rectangular geometry, and is filled and stroked with a black brush. + * A newly constructed Shape has a default .figure of "None", which constructs a rectangular geometry, and is filled and stroked with a black brush. */ constructor(); @@ -2745,7 +3059,7 @@ declare module go { figure: string; /**Gets or sets the Brush (or CSS color string) that describes the fill of the Shape.*/ - fill: any; + fill: BrushLike; /**Gets or sets the name of the kind of arrowhead that this shape should take when this shape is an element of a Link.*/ fromArrow: string; @@ -2756,16 +3070,16 @@ declare module go { /**Gets or sets how the shape's geometry is proportionally created given its computed size.*/ geometryStretch: EnumValue; - /**When set, creates a Geometry and normalizes it from a given path string, then sets the Geometry on this Shape and offsets the GraphObject#position by an appropriate amount.*/ + /**When set, creates a Geometry and normalizes it from a given path string, then sets the Geometry on this Shape and offsets the GraphObject.position by an appropriate amount.*/ geometryString: string; - /**Gets or sets how frequently this shape should be drawn within a Grid Panel, in multiples of the Panel#gridCellSize.*/ + /**Gets or sets how frequently this shape should be drawn within a Grid Panel, in multiples of the Panel.gridCellSize.*/ interval: number; - /**Gets or sets the whether the #position denotes the panel coordinates of the geometry or of the stroked area.*/ + /**Gets or sets the whether the .position denotes the panel coordinates of the geometry or of the stroked area.*/ isGeometryPositioned: boolean; - /**Gets the natural bounds of this Shape as determined by its #geometry's bounds.*/ + /**This read-only property returns the natural bounds of this Shape as determined by its .geometry's bounds.*/ naturalBounds: Rect; /**Gets or sets a property for parameterizing the construction of a Geometry from a figure.*/ @@ -2781,13 +3095,13 @@ declare module go { spot2: Spot; /**Gets or sets the Brush (or CSS color string) that describes the stroke of the Shape.*/ - stroke: any; + stroke: BrushLike; /**Gets or sets the style for the stroke's line cap.*/ strokeCap: string; /**Gets or sets the dash array for creating dashed lines.*/ - strokeDashArray: any[]; + strokeDashArray: Array; /**Gets or sets the offset for dashed lines, used in the phase pattern.*/ strokeDashOffset: number; @@ -2803,10 +3117,48 @@ declare module go { /**Gets or sets the name of the kind of arrowhead that this shape should take when this shape is an element of a Link.*/ toArrow: string; + + /** + * This static function returns a read-only Map of named geometry generators. + * @return {Map} the keys are figure names; the values are either synonymed names or generator functions + */ + static getFigureGenerators(): Map Geometry>; + + /** + * This static function defines a named figure geometry generator for Shapes. + * @param {string} name new figure name must start with an uppercase letter, and must not be "None" + * @param {function(Shape, number, number):Geometry} func returns a Geometry for the given Shape, width, and height + */ + static defineFigureGenerator(name: string, func: (shape: Shape, width: number, height: number) => Geometry): void; + /** + * This static function defines a synonym for a named figure geometry generator. + * @param {string} name the new figure name must start with an uppercase letter, and must not be "None" + * @param {string} synonym an existing figure name + */ + static defineFigureGenerator(name: string, synonym: string): void; + + /** + * This static function returns a read-only Map of named arrowhead geometries. + * @return {Map} the keys are arrowhead names; the values are Geometry objects + */ + static getArrowheadGeometries(): Map; + + /** + * This static function defines a named arrowhead geometry. + * @param {string} name the new arrowhead name must start with an uppercase letter, and must not be "None" + * @param {Geometry} geo the Geometry for the arrowhead + */ + static defineArrowheadGeometry(name: string, geo: Geometry): void; + /** + * This static function defines a named arrowhead geometry. + * @param {string} name the new arrowhead name must start with an uppercase letter, and must not be "None" + * @param {string} pathstr a geometry path string that will be passed to Geometry.parse + */ + static defineArrowheadGeometry(name: string, pathstr: string): void; } /** - * A TextBlock is a GraphObject that displays a #text string in a given #font. + * A TextBlock is a GraphObject that displays a .text string in a given .font. */ class TextBlock extends GraphObject { /** @@ -2814,7 +3166,7 @@ declare module go { */ constructor(); - /**Gets or sets whether or not this TextBlock allows in-place editing of the #text string by the user with the help of the TextEditingTool.*/ + /**Gets or sets whether or not this TextBlock allows in-place editing of the .text string by the user with the help of the TextEditingTool.*/ editable: boolean; /**Gets or sets the function to call if a text edit made with the TextEditingTool is invalid.*/ @@ -2832,14 +3184,20 @@ declare module go { /**Gets or sets whether or not the text is underlined.*/ isUnderline: boolean; - /**Gets the total number of lines in this TextBlock, including lines created from returns and wrapping.*/ + /**This read-only property returns the total number of lines in this TextBlock, including lines created from returns and wrapping.*/ lineCount: number; - /**Gets the natural bounds of this TextBlock in local coordinates, as determined by its #font and #text string.*/ + /**Gets or sets the maximum number of lines that this TextBlock may display.*/ + maxLines: number; + + /**This read-only property returns the natural bounds of this TextBlock in local coordinates, as determined by its .font and .text string.*/ naturalBounds: Rect; - /**Gets or sets the Brush (or CSS color string) that describes the stroke (color) of the #font.*/ - stroke: any; + /**Gets or sets how text that is too long to display should be handled.*/ + overflow: EnumValue; + + /**Gets or sets the Brush (or CSS color string) that describes the stroke (color) of the .font.*/ + stroke: BrushLike; /**Gets or sets the current text string.*/ text: string; @@ -2859,11 +3217,21 @@ declare module go { /**The TextBlock will not wrap its text.*/ static None: EnumValue; + /** Used as the default value for TextBlock.overflow: if the width is too small to display all text, the TextBlock will clip.*/ + static OverflowClip: EnumValue; + + /** Used as a value for TextBlock.overflow: if the width is too small to display all text, the TextBlock will display an ellipsis.*/ + static OverflowEllipsis: EnumValue; + /**The TextBlock will wrap text and the width of the TextBlock will be the desiredSize's width, if any.*/ static WrapDesiredSize: EnumValue; /**The TextBlock will wrap text, making the width of the TextBlock equal to the width of the longest line.*/ static WrapFit: EnumValue; + + static isValidFont(font: string): boolean; // undocumented + static getEllipsis(): string; // undocumented + static setEllipsis(val: string): void; // undocumented } @@ -2872,14 +3240,14 @@ declare module go { * of a Shape or the stroke of a shape or a TextBlock or the * background of any GraphObject. * A Brush must not be modified once it has been assigned to a GraphObject, - * such as the Shape#fill or TextBlock#stroke - * or GraphObject#background. + * such as the Shape.fill or TextBlock.stroke + * or GraphObject.background. * However, a Brush may be shared by multiple GraphObjects. */ class Brush { /** * Construct a Brush class of a given type. - * @param {EnumValue} type one of the values Brush#Solid, Brush#Linear, Brush#Radial, Brush#Pattern. + * @param {EnumValue} type one of the values Brush.Solid, Brush.Linear, Brush.Radial, Brush.Pattern. */ constructor(type: EnumValue); /** @@ -2892,7 +3260,7 @@ declare module go { color: string; /**Gets or sets a Map holding all of the color stops used in this gradient, where the key is a number, the fractional distance between zero and one (inclusive), and where the corresponding value is a color string.*/ - colorStops: Map; + colorStops: Map; /**Gets or sets the ending location for a linear or radial gradient.*/ end: Spot; @@ -2900,7 +3268,7 @@ declare module go { /**Gets or sets the radius of a radial brush at the end location.*/ endRadius: number; - /**Gets or sets the pattern of a brush of type Brush#Pattern, an HTMLImageElement or HTMLCanvasElement.*/ + /**Gets or sets the pattern of a brush of type Brush.Pattern, an HTMLImageElement or HTMLCanvasElement or HTMLVideoElement.*/ pattern: any; /**Gets or sets the starting location for a linear or radial gradient.*/ @@ -2914,13 +3282,13 @@ declare module go { /** * Specify a particular color at a particular fraction of the distance. - * If the #type is Brush#Solid, change the type to Brush#Linear. + * If the .type is Brush.Solid, change the type to Brush.Linear. * You should have a color stop at zero and a color stop at one. * You should not have duplicate color stop values at the same fractional distance. * @param {number} loc between zero and one, inclusive. * @param {string} color a CSS color string */ - addColorStop(loc: number, color: string); + addColorStop(loc: number, color: string): void; /** * Create a copy of this Brush, with the same values. @@ -2928,23 +3296,25 @@ declare module go { copy(): Brush; /** - * This static method can be used to generate a random color string. + * This static function can be used to generate a random color string. * @param {number=} min a number between zero and 255, defaults to 128. * @param {number=} max a number between zero and 255, defaults to 255. */ static randomColor(min?: number, max?: number): string; - /**For linear gradient brushes, used as the value for Brush#type.*/ + /**For linear gradient brushes, used as the value for Brush.type.*/ static Linear: EnumValue; - /**For pattern brushes, used as the value for Brush#type.*/ + /**For pattern brushes, used as the value for Brush.type.*/ static Pattern: EnumValue; - /**For radial gradient brushes, used as the value for Brush#type.*/ + /**For radial gradient brushes, used as the value for Brush.type.*/ static Radial: EnumValue; - /**For simple, solid color brushes, used as the value for Brush#type.*/ + /**For simple, solid color brushes, used as the value for Brush.type.*/ static Solid: EnumValue; + + static isValidColor(color: string): boolean; // undocumented } /** @@ -2958,38 +3328,48 @@ declare module go { /** * Construct an empty Geometry. * The geometry type must be one of the following values: - * Geometry#Line, Geometry#Ellipse, Geometry#Rectangle, Geometry#Path. - * @param {EnumValue=} type If not supplied, the default Geometry type is Geometry#Path. + * Geometry.Line, Geometry.Ellipse, Geometry.Rectangle, Geometry.Path. + * @param {EnumValue=} type If not supplied, the default Geometry type is Geometry.Path. */ constructor(type?: EnumValue); - /**Gets a rectangle that contains all points within the Geometry.*/ + /**This read-only property returns a rectangle that contains all points within the Geometry.*/ bounds: Rect; - /**Gets or sets the ending X coordinate of the Geometry if it is of type #Line, #Rectangle, or #Ellipse.*/ + /**Gets or sets the Shape.geometryStretch value the Shape should use by default.*/ + defaultStretch: EnumValue; + + /**Gets or sets the ending X coordinate of the Geometry if it is of type .Line, .Rectangle, or .Ellipse.*/ endX: number; - /**Gets or sets the ending Y coordinate of the Geometry if it is of type #Line, #Rectangle, or #Ellipse.*/ + /**Gets or sets the ending Y coordinate of the Geometry if it is of type .Line, .Rectangle, or .Ellipse.*/ endY: number; - /**Gets or sets the List of PathFigures that describes the content of the path for Geometries of type #Path.*/ - figures: List; + /**Gets or sets the List of PathFigures that describes the content of the path for Geometries of type .Path.*/ + figures: List; - /**Gets or sets the spot to use when the Shape#spot1 value is Spot#Default.*/ + /**Gets or sets the spot to use when the Shape.spot1 value is Spot.Default.*/ spot1: Spot; - /**Gets or sets the spot to use when the Shape#spot2 value is Spot#Default.*/ + /**Gets or sets the spot to use when the Shape.spot2 value is Spot.Default.*/ spot2: Spot; - /**Gets or sets the starting X coordinate of the Geometry if it is of type #Line, #Rectangle, or #Ellipse.*/ + /**Gets or sets the starting X coordinate of the Geometry if it is of type .Line, .Rectangle, or .Ellipse.*/ startX: number; - /**Gets or sets the starting Y coordinate of the Geometry if it is of type #Line, #Rectangle, or #Ellipse.*/ + /**Gets or sets the starting Y coordinate of the Geometry if it is of type .Line, .Rectangle, or .Ellipse.*/ startY: number; /**Gets or sets the type of the Geometry.*/ type: EnumValue; + /** + * Add a PathFigure to the figures list. + * @param {PathFigure} figure a newly allocated unshared PathFigure that will become owned by this Geometry + * @return {Geometry} this + */ + add(figure: PathFigure): Geometry; + /** * Computes the Geometry's bounds without adding an origin point, and returns those bounds as a rect. */ @@ -3016,8 +3396,9 @@ declare module go { * Offsets the Geometry in place by a given (x, y) amount * @param {number} x The x-axis offset factor. * @param {number} y The y-axis offset factor. + * @return {Geometry} this */ - offset(x: number, y: number); + offset(x: number, y: number): Geometry; /** * Produce a Geometry from a string that uses an SVG-like compact path geometry syntax. @@ -3036,18 +3417,20 @@ declare module go { * @param {number} angle The angle to rotate by. * @param {number=} x The optional X point to rotate the geometry about. If no point is given, this value is 0. * @param {number=} y The optional Y point to rotate the geometry about. If no point is given, this value is 0. + * @return {Geometry} this */ - rotate(angle: number, x?: number, y?: number); + rotate(angle: number, x?: number, y?: number): Geometry; /** * Scales the Geometry in place by a given (x, y) scale factor * @param {number} x The x-axis scale factor. * @param {number} y The y-axis scale factor. + * @return {Geometry} this */ - scale(x: number, y: number); + scale(x: number, y: number): Geometry; /** - * This static method can be used to write out a Geometry as a string + * This static function can be used to write out a Geometry as a string * that can be read by Geometry.parse. * The string produced by this method is a superset of the SVG path * string rules that contains some additional GoJS-specific tokens. @@ -3056,17 +3439,19 @@ declare module go { */ static stringify(val: Geometry): string; - /**For drawing an ellipse fitting within a rectangle; a value for Geometry#type.*/ + /**For drawing an ellipse fitting within a rectangle; a value for Geometry.type.*/ static Ellipse: EnumValue; - /**For drawing a simple straight line; a value for Geometry#type.*/ + /**For drawing a simple straight line; a value for Geometry.type.*/ static Line: EnumValue; - /**For drawing a complex path made of a list of PathFigures; a value for Geometry#type.*/ + /**For drawing a complex path made of a list of PathFigures; a value for Geometry.type.*/ static Path: EnumValue; - /**For drawing a rectangle; a value for Geometry#type.*/ + /**For drawing a rectangle; a value for Geometry.type.*/ static Rectangle: EnumValue; + + equalsApprox(g: Geometry): boolean; // undocumented } /** @@ -3142,14 +3527,14 @@ declare module go { isReal(): boolean; /** - * This static method can be used to read in a Margin from a string that was produced by Margin.stringify. + * This static function can be used to read in a Margin from a string that was produced by Margin.stringify. * @param {string} str */ static parse(str: string): Margin; /** - * Replace the transformation matrix of this Transform with those of another Transform. - * @param {Transform} t the other Transform from which to copy the transformation matrix. + * Modify this Margin so that its Top, Right, Bottom, and Left values are the same as the given Margin. + * @param {Margin} m the Margin whose values are to be copied */ set(m: Margin): Margin; @@ -3161,14 +3546,16 @@ declare module go { setTo(t: number, r: number, b: number, l: number): Margin; /** - * This static method can be used to write out a Margin as a string that can be read by Margin.parse. + * This static function can be used to write out a Margin as a string that can be read by Margin.parse. * @param {Margin} val */ static stringify(val: Margin): string; + + equalsApprox(m: Margin): boolean; // undocumented } /** - * A PathFigure represents a section of a Geometry}. + * A PathFigure represents a section of a Geometry. * It is a single connected series of * two-dimensional geometric PathSegments. */ @@ -3177,12 +3564,13 @@ declare module go { * Constructs an empty figure. * The optional arguments specify the starting point of the figure. * You'll want to add a new instance of a PathFigure to the - * Geometry#figures list of a Geometry. + * Geometry.figures list of a Geometry. * @param {number=} sx optional: the X coordinate of the start point (default is zero). * @param {number=} sy optional: the Y coordinate of the start point (default is zero). * @param {boolean=} filled optional: whether the figure is filled (default is true). + * @param {boolean=} shadowed optional: whether the figure may be drawn with a shadow (default is true). */ - constructor(sx?: number, sy?: number, filled?: boolean); + constructor(sx?: number, sy?: number, filled?: boolean, shadowed?: boolean); /**Gets or sets whether this PathFigure is drawn filled.*/ isFilled: boolean; @@ -3191,7 +3579,7 @@ declare module go { isShadowed: boolean; /**Gets or sets the List of PathSegments that define this PathFigure.*/ - segments: List; + segments: List; /**Gets or sets the starting point X coordinate of the PathFigure.*/ startX: number; @@ -3199,17 +3587,26 @@ declare module go { /**Gets or sets the starting point Y coordinate of the PathFigure.*/ startY: number; + /** + * Add a PathSegment to the segments list. + * @param {PathSegment} segment a newly allocated unshared PathSegment that will become owned by this PathFigure + * @return {PathFigure} this + */ + add(segment: PathSegment): PathFigure; + /** * Create a copy of this PathFigure, with the same values and segments. */ copy(): PathFigure; + + equalsApprox(f: PathFigure): boolean; // undocumented } /** * A PathSegment represents a straight line or curved segment of a path between - * two or more points that are part of a PathFigure}. - * A PathSegment must not be modified once its containing PathFigure}'s - * Geometry} has been assigned to a Shape}. + * two or more points that are part of a PathFigure. + * A PathSegment must not be modified once its containing PathFigure's + * Geometry has been assigned to a Shape. */ class PathSegment { /** @@ -3226,10 +3623,10 @@ declare module go { */ constructor(type: EnumValue, ex?: number, ey?: number, x1?: number, y1?: number, x2?: number, y2?: number, clockwise?: boolean); - /**Gets or sets the center X value of the Arc for a PathSegment of type #Arc.*/ + /**Gets or sets the center X value of the Arc for a PathSegment of type .Arc.*/ centerX: number; - /**Gets or sets the center Y value of the Arc for a PathSegment of type #Arc.*/ + /**Gets or sets the center Y value of the Arc for a PathSegment of type .Arc.*/ centerY: number; /**Gets or sets the X coordinate of the end point for all kinds of PathSegment.*/ @@ -3238,43 +3635,43 @@ declare module go { /**Gets or sets the Y coordinate of the end point for all kinds of PathSegment.*/ endY: number; - /**Gets or sets the sweep-flag for a PathSegment of type #SvgArc.*/ + /**Gets or sets the sweep-flag for a PathSegment of type .SvgArc.*/ isClockwiseArc: boolean; /**Gets or sets whether the path is closed after this PathSegment.*/ isClosed: boolean; - /**Gets or sets the large-arc-flag for a PathSegment of type #SvgArc.*/ + /**Gets or sets the large-arc-flag for a PathSegment of type .SvgArc.*/ isLargeArc: boolean; - /**Gets or sets the X value of the first control point for a PathSegment of type #Bezier or #QuadraticBezier.*/ + /**Gets or sets the X value of the first control point for a PathSegment of type .Bezier or .QuadraticBezier.*/ point1X: number; - /**Gets or sets the Y value of the first control point for a PathSegment of type #Bezier or #QuadraticBezier.*/ + /**Gets or sets the Y value of the first control point for a PathSegment of type .Bezier or .QuadraticBezier.*/ point1Y: number; - /**Gets or sets the X value of the second control point for a PathSegment of type cubic #Bezier.*/ + /**Gets or sets the X value of the second control point for a PathSegment of type cubic .Bezier.*/ point2X: number; - /**Gets or sets the Y value of the second control point for a PathSegment of type cubic #Bezier.*/ + /**Gets or sets the Y value of the second control point for a PathSegment of type cubic .Bezier.*/ point2Y: number; - /**Gets or sets the X value of the radius for a PathSegment of type #Arc.*/ + /**Gets or sets the X value of the radius for a PathSegment of type .Arc.*/ radiusX: number; - /**Gets or sets the Y value of the radius for a PathSegment of type #Arc.*/ + /**Gets or sets the Y value of the radius for a PathSegment of type .Arc.*/ radiusY: number; - /**Gets or sets the starting angle for a PathSegment of type #Arc.*/ + /**Gets or sets the starting angle for a PathSegment of type .Arc.*/ startAngle: number; - /**Gets or sets the length of angle in degrees, or amount of arc to "sweep" for a PathSegment of type #Arc.*/ + /**Gets or sets the length of angle in degrees, or amount of arc to "sweep" for a PathSegment of type .Arc.*/ sweepAngle: number; /**Gets or sets the type of the PathSegment.*/ type: EnumValue; - /**Gets or sets the X-axis rotation for a PathSegment of type #SvgArc.*/ + /**Gets or sets the X-axis rotation for a PathSegment of type .SvgArc.*/ xAxisRotation: number; /** @@ -3287,23 +3684,25 @@ declare module go { */ copy(): PathSegment; - /**For drawing an arc segment, a value for PathSegment#type.*/ + /**For drawing an arc segment, a value for PathSegment.type.*/ static Arc: EnumValue; - /**For drawing a cubic bezier segment, a value for PathSegment#type.*/ + /**For drawing a cubic bezier segment, a value for PathSegment.type.*/ static Bezier: EnumValue; - /**For drawing a straight line segment, a value for PathSegment#type.*/ + /**For drawing a straight line segment, a value for PathSegment.type.*/ static Line: EnumValue; - /**For beginning a new subpath, a value for PathSegment#type.*/ + /**For beginning a new subpath, a value for PathSegment.type.*/ static Move: EnumValue; - /**For drawing a quadratic bezier segment, a value for PathSegment#type.*/ + /**For drawing a quadratic bezier segment, a value for PathSegment.type.*/ static QuadraticBezier: EnumValue; - /**For drawing an SVG arc segment, a value for PathSegment#type.*/ + /**For drawing an SVG arc segment, a value for PathSegment.type.*/ static SvgArc: EnumValue; + + equalsApprox(s: PathSegment): boolean; // undocumented } /** @@ -3341,7 +3740,7 @@ declare module go { copy(): Point; /** - * This static method returns the angle in degrees of the line from point P to point Q. + * This static function returns the angle in degrees of the line from point P to point Q. * @param {number} px * @param {number} py * @param {number} qx @@ -3365,7 +3764,7 @@ declare module go { directionPoint(p: Point): number; /** - * This static method returns the square of the distance from the point P + * This static function returns the square of the distance from the point P * to the finite line segment from point A to point B. * @param {number} px * @param {number} py @@ -3384,7 +3783,7 @@ declare module go { distanceSquared(px: number, py: number): number; /** - * This static method returns the square of the distance from the point P to the point Q. + * This static function returns the square of the distance from the point P to the point Q. * @param {number} px * @param {number} py * @param {number} qx @@ -3432,11 +3831,27 @@ declare module go { offset(dx: number, dy: number): Point; /** - * This static method can be used to read in a Point from a string that was produced by Point.stringify. + * This static function can be used to read in a Point from a string that was produced by Point.stringify. * @param {string} str */ static parse(str: string): Point; + /** + * Modify this point to be the closest point to this point that is on a finite line segment given by (px,py) and (qx,qy). + * @param {number} px + * @param {number} py + * @param {number} qx + * @param {number} qy + */ + projectOntoLineSegment(px: number, py: number, qx: number, qy: number): Point; + + /** + * Modify this point to be the closest point to this point that is on a finite line segment given by P and Q. + * @param {Point} p + * @param {Point} q + */ + projectOntoLineSegmentPoint(p: Point, q: Point): Point; + /** * Modify this Point so that has been rotated about the origin by the given angle. * @param {number} angle an angle in degrees. @@ -3452,7 +3867,6 @@ declare module go { /** * Modify this Point so that its X and Y values are the same as the given Point. - * * @param {Point} p the given Point. */ set(p: Point): Point; @@ -3460,21 +3874,21 @@ declare module go { /** * Modify this Point so that its X and Y values correspond to a particular Spot * in a given Rect. - * The result is meaningless if Spot#isNoSpot is true for the given Spot. + * The result is meaningless if Spot.isNoSpot is true for the given Spot. * @param {Rect} r the Rect for which we are finding the point. - * @param {Spot} spot the Spot; Spot#isSpot must be true for this Spot. + * @param {Spot} spot the Spot; Spot.isSpot must be true for this Spot. */ setRectSpot(r: Rect, spot: Spot): Point; /** * Modify this Point so that its X and Y values correspond to a particular Spot * in a given rectangle. - * The result is meaningless if Spot#isNoSpot is true for the given Spot. + * The result is meaningless if Spot.isNoSpot is true for the given Spot. * @param {number} x The X coordinate of the Rect for which we are finding the point. * @param {number} y The Y coordinate of the Rect for which we are finding the point. * @param {number} w The Width of the Rect for which we are finding the point. * @param {number} h The Height of the Rect for which we are finding the point. - * @param {Spot} spot the Spot; Spot#isSpot must be true for this Spot. + * @param {Spot} spot the Spot; Spot.isSpot must be true for this Spot. */ setSpot(x: number, y: number, w: number, h: number, spot: Spot): Point; @@ -3486,7 +3900,25 @@ declare module go { setTo(x: number, y: number): Point; /** - * This static method can be used to write out a Point as a string that can be read by Point.parse. + * Modify this point to be at the nearest point on an infinite grid, + * given the grid's origin and size of each grid cell. + * @param {number} originx + * @param {number} originy + * @param {number} cellwidth + * @param {number} cellheight + */ + snapToGrid(originx: number, originy: number, cellwidth: number, cellheight: number): Point; + + /** + * Modify this point to be at the nearest point on an infinite grid, + * given the grid's origin and size of each grid cell. + * @param {Point} origin + * @param {Size} cellsize + */ + snapToGridPoint(origin: Point, cellsize: Size): Point; + + /** + * This static function can be used to write out a Point as a string that can be read by Point.parse. * @param {Point} val */ static stringify(val: Point): string; @@ -3497,6 +3929,8 @@ declare module go { * @param {Point} p The Point to subtract from the current Point. */ subtract(p: Point): Point; + + equalsApprox(p: Point): boolean; // undocumented } /** @@ -3588,7 +4022,7 @@ declare module go { contains(x: number, y: number, w?: number, h?: number): boolean; /** - * This static method indicates whether a Rect contains the given Point/Rect. + * This static function indicates whether a Rect contains the given Point/Rect. * @param {number} rx The X coordinate of a Rect. * @param {number} ry The Y coordinate of a Rect. * @param {number} rw The Width of a Rect. @@ -3671,7 +4105,7 @@ declare module go { intersectRect(r: Rect): Rect; /** - * This static method indicates whether a Rect partly or wholly overlaps the given Rect. + * This static function indicates whether a Rect partly or wholly overlaps the given Rect. * @param {number} rx The X coordinate of a Rect. * @param {number} ry The Y coordinate of a Rect. * @param {number} rw The Width of a Rect. @@ -3717,7 +4151,7 @@ declare module go { offset(dx: number, dy: number): Rect; /** - * This static method can be used to read in a Rect from a string that was produced by Rect.stringify. + * This static function can be used to read in a Rect from a string that was produced by Rect.stringify. * @param {string} str */ static parse(str: string): Rect; @@ -3743,10 +4177,10 @@ declare module go { /** * Modify this Rect so that a given Spot is at a given (x,y) point using this Rect's size. * Return this rectangle for which the spot is at that point, without modifying the size. - * The result is meaningless if Spot#isNoSpot is true. + * The result is meaningless if Spot.isNoSpot is true. * @param {number} x the point where the spot should be. * @param {number} y the point where the spot should be. - * @param {Spot} spot a Spot; Spot#isSpot must be true. + * @param {Spot} spot a Spot; Spot.isSpot must be true. */ setSpot(x: number, y: number, spot: Spot): Rect; @@ -3760,7 +4194,7 @@ declare module go { setTo(x: number, y: number, w: number, h: number): Rect; /** - * This static method can be used to write out a Rect as a string that can be read by Rect.parse. + * This static function can be used to write out a Rect as a string that can be read by Rect.parse. * @param {Rect} val */ static stringify(val: Rect): string; @@ -3792,6 +4226,8 @@ declare module go { * @param {Rect} r The Rect to include in the new bounds. */ unionRect(r: Rect): Rect; + + equalsApprox(r: Rect): boolean; // undocumented } /** @@ -3843,7 +4279,7 @@ declare module go { isReal(): boolean; /** - * This static method can be used to read in a Size from a string that was produced by Size.stringify. + * This static function can be used to read in a Size from a string that was produced by Size.stringify. * @param {string} str */ static parse(str: string): Size; @@ -3862,10 +4298,12 @@ declare module go { setTo(w: number, h: number): Size; /** - * This static method can be used to write out a Size as a string that can be read by Size.parse. + * This static function can be used to write out a Size as a string that can be read by Size.parse. * @param {Size} val */ static stringify(val: Size): string; + + equalsApprox(s: Size): boolean; // undocumented } /** @@ -3930,7 +4368,7 @@ declare module go { isDefault(): boolean; /** - * True if this is an unspecific special spot, such as Spot#None or one of the sides. + * True if this is an unspecific special spot, such as Spot.None or one of the sides. */ isNoSpot(): boolean; @@ -3940,7 +4378,7 @@ declare module go { isSide(): boolean; /** - * True if this is a specific spot, not a side nor Spot#None. + * True if this is a specific spot, not a side nor Spot.None. */ isSpot(): boolean; @@ -3950,7 +4388,7 @@ declare module go { opposite(): Spot; /** - * This static method can be used to read in a Spot from a string that was produced by Spot.stringify. + * This static function can be used to read in a Spot from a string that was produced by Spot.stringify. * @param {string} str */ static parse(str: string): Spot; @@ -3971,7 +4409,7 @@ declare module go { setTo(x: number, y: number, offx: number, offy: number): Spot; /** - * This static method can be used to write out a Spot as a string that can be read by Spot.parse. + * This static function can be used to write out a Spot as a string that can be read by Spot.parse. * @param {Spot} val */ static stringify(val: Spot): string; @@ -3979,7 +4417,7 @@ declare module go { /**The set of points on all sides of the bounding rectangle.*/ static AllSides: Spot; - /**A synonym for Spot#BottomCenter.*/ + /**A synonym for Spot.BottomCenter.*/ static Bottom: Spot; /**The specific point at the middle of the bottom side of bounding rectangle.*/ @@ -4006,7 +4444,7 @@ declare module go { /**Use this value to indicate that the real spot value is inherited from elsewhere.*/ static Default: Spot; - /**A synonym for Spot#LeftCenter.*/ + /**A synonym for Spot.LeftCenter.*/ static Left: Spot; /**The specific point at the middle of the left side of bounding rectangle.*/ @@ -4018,16 +4456,16 @@ declare module go { /**The set of points at the left side of the bounding rectangle.*/ static LeftSide: Spot; - /**A synonym for Spot#BottomCenter.*/ + /**A synonym for Spot.BottomCenter.*/ static MiddleBottom: Spot; - /**A synonym for Spot#LeftCenter.*/ + /**A synonym for Spot.LeftCenter.*/ static MiddleLeft: Spot; - /**A synonym for Spot#RightCenter.*/ + /**A synonym for Spot.RightCenter.*/ static MiddleRight: Spot; - /**A synonym for Spot#TopCenter.*/ + /**A synonym for Spot.TopCenter.*/ static MiddleTop: Spot; /**Use this Spot value to indicate no particular spot -- code looking for a particular point on an element will need to do their own calculations to determine the desired point depending on the circumstances.*/ @@ -4045,7 +4483,7 @@ declare module go { /**The set of points on all sides of the bounding rectangle except top side.*/ static NotTopSide: Spot; - /**A synonym for Spot#RightCenter.*/ + /**A synonym for Spot.RightCenter.*/ static Right: Spot; /**The specific point at the middle of the right side of bounding rectangle.*/ @@ -4054,7 +4492,7 @@ declare module go { /**The set of points at the right side of the bounding rectangle.*/ static RightSide: Spot; - /**A synonym for Spot#TopCenter.*/ + /**A synonym for Spot.TopCenter.*/ static Top: Spot; /**The set of points at the top or bottom sides of the bounding rectangle.*/ @@ -4081,7 +4519,7 @@ declare module go { /** - * A Binding describes how to automatically set a property on a GraphObject} + * A Binding describes how to automatically set a property on a GraphObject * to a value of a property of data in the model. * The target property name and the data source property name are strings. * All name matching is case-sensitive. @@ -4098,59 +4536,131 @@ declare module go { * @param {function(*,*=) | null=} conv A function converting the data property value to the value to set the target property. * If the function is null or not supplied, no conversion takes place. */ - constructor(targetprop?: string, sourceprop?: string, conv?: (a: any, b?: any) => any); + constructor(targetprop?: string, sourceprop?: string, conv?: (a: any, b: any) => any); - /**Gets or sets a converter function to apply to the GraphObject property value in order to produce the value to set to a data property.*/ - backConverter: (a: any, b?: any) => any; + /** + * Gets or sets a converter function to apply to the GraphObject property value + * in order to produce the value to set to a data property. + * This conversion function is only used in a TwoWay binding, + * when transferring a value from the target to the source. + * The default value is null -- no conversion takes place. + * Otherwise the value should be a function that takes one or two arguments + * and returns the desired value. + * However, the return value is ignored when the .sourceProperty + * is the empty string. + * The function is passed the value from the target + * (the first argument) and the source Panel.data object (the second argument). + * If the .sourceProperty is a property name, that property is set to + * the function's return value. + * If the .sourceProperty is the empty string, the function should + * modify the second argument, which will be the source data object. + */ + backConverter: (a: any, b: any) => any; - /**Gets or sets a converter function to apply to the data property value in order to produce the value to set to the target property.*/ - converter: (a: any, b?: any) => any; + /** + * Gets or sets a converter function to apply to the data property value + * in order to produce the value to set to the target property. + * This conversion function is used in both OneWay and TwoWay bindings, + * when transferring a value from the source to the target. + * The default value is null -- no conversion takes place. + * Otherwise the value should be a function that takes one or two arguments + * and returns the desired value. + * However, the return value is ignored when the .targetProperty + * is the empty string. + * The function is passed the value from the source + * (the first argument) and the target GraphObject (the second argument). + * If the .targetProperty is a property name, that property is set to + * the function's return value. + * If the .targetProperty is the empty string, the function should + * modify the second argument, which will be the target object. + */ + converter: (a: any, b: any) => any; - /**Gets or sets the directions and frequency in which the binding may be evaluated.*/ + /** + * Gets or sets the directions and frequency in which the binding may be evaluated. + * The default value is Binding.OneWay. + * Binding.TwoWay is the other choice. + * Use OneWay bindings to initialize GraphObject properties based on model data, + * or to modify GraphObject properties when the model data changes will a call to Model.setDataProperty. + * Use TwoWay bindings to keep model data in sync with changes to GraphObject properties. + * For efficiency, avoid TwoWay bindings on GraphObject properties that do not change value in your app. + * You should not have a TwoWay binding on a node data object's key property. + */ mode: EnumValue; - /**Gets or sets the name of the GraphObject that should act as a source object whose property should be gotten by this data binding.*/ + /** + * Gets or sets the name of the GraphObject that should act as a source object + * whose property should be gotten by this data binding. + * The default value is null, which uses the bound Panel.data as the source. + * If the value is a string, it should be the name of a GraphObject in the + * visual tree of the Panel that is bound to the data. + * Use the empty string to refer to the root panel. + */ sourceName: string; - /**Gets or sets the name of the property to get from the bound data object, the value of Panel#data.*/ + /** + * Gets or sets the name of the property to get from the bound data object, + * the value of Panel.data. + * The default value is the empty string, which results in setting the target + * property to the whole data object, rather than to a property value of the data object. + */ sourceProperty: string; - /**Gets or sets the name of the property to be set on the target GraphObject.*/ + /** + * Gets or sets the name of the property to be set on the target GraphObject. + * The default value is the empty string; you normally set this to be the name of a property. + */ targetProperty: string; /** - * Modify this Binding to set its #mode to be Binding#TwoWay, and + * Modify this Binding to set its .mode to be Binding.TwoWay, and * provide an optional conversion function to convert GraphObject property * values back to data values. - * + * Use TwoWay bindings to keep model data in sync with changes to GraphObject properties. + * For efficiency, avoid TwoWay bindings on GraphObject properties that do not change value in your app. * You should not have a TwoWay binding on a node data object's key property. * @param {function(*,*=) | null=} backconv */ - makeTwoWay(backconv?: (a: any, b?: any) => any): Binding; + makeTwoWay(backconv?: (a: any, b: any) => any): Binding; /** - * Modify this Binding to set its #sourceName property so as to identify + * Modify this Binding to set its .sourceName property so as to identify * a GraphObject in the visual tree of the bound Panel. - * @param {string=} srcname the GraphObject#name of an element in the visual tree of the bound Panel; + * @param {string=} srcname the GraphObject.name of an element in the visual tree of the bound Panel; * use an empty string to refer to the root panel of that visual tree. */ ofObject(srcname?: string): Binding; /** - * This static method can be used to create a function that parses a string into an enumerated value, given the class that the enumeration values are defined on and a default value if the string cannot be parsed successfully. + * This static function can be used to create a function that parses + * a string into an enumerated value, given the class that the enumeration values + * are defined on and a default value if the string cannot be parsed successfully. + * The normal usage is to pass the result of this function as the conversion function of a Binding. + * This binding will try to parse the string that is the value of the bound data's "dataPropName" property. + * If it is a legitimate enumerated value defined on the Link class, the conversion + * function will return that value. + * If the bound data's "dataPropName" property is not present or has an unrecognized value, + * the Link.routing property gets the default value, Link.Normal. + * @param {function()} ctor the class constructor that defines the enumerated values that are being parsed. + * @param {EnumValue} defval the default enumerated value to return if it fails to parse the given string. */ - static parseEnum(ctor: new(...args: any[]) => Object, defval: EnumValue): (a: string) => EnumValue; + static parseEnum(ctor: Constructor, defval: EnumValue): (a: string) => EnumValue; /** - * This static method can be used to convert an object to a string, looking for commonly defined data properties, such as "text", "name", "key", or "id". + * This static function can be used to convert an object to a string, + * looking for commonly defined data properties, such as "text", "name", "key", or "id". + * If none are found, this just calls toString() on it. + * @param {*} val */ static toString(val: any): string; - /**This value for Binding#mode uses data source values and sets GraphObject properties.*/ + /**This value for Binding.mode uses data source values and sets GraphObject properties.*/ static OneWay: EnumValue; - /**This value for Binding#mode uses data source values and GraphObject properties and keeps them in sync.*/ + /**This value for Binding.mode uses data source values and GraphObject properties and keeps them in sync.*/ static TwoWay: EnumValue; + + ofModel(): Binding; // undocumented } /** @@ -4158,8 +4668,8 @@ declare module go { * but also for model data, a Model, or a Diagram. * The most common case is for remembering the name of a property * and the before-and-after values for that property. - * You can listen for changed events on the model using Model#addChangedListener - * and on the Diagram using Diagram#addChangedListener. + * You can listen for changed events on the model using Model.addChangedListener + * and on the Diagram using Diagram.addChangedListener. */ class ChangedEvent { /** @@ -4173,10 +4683,13 @@ declare module go { /**Gets or sets the Diagram that was modified.*/ diagram: Diagram; + /**This read-only property is true when this ChangeEvent is of type ChangedEvent.Transaction and represents the end of a transactional change.*/ + isTransactionFinished: boolean; + /**Gets or sets the Model or TreeModel or GraphLinksModel that was modified.*/ model: Model; - /**Gets the name of the model change, reflecting a change to model data in addition to a change to the model itself.*/ + /**This read-only property returns the name of the model change, reflecting a change to model data in addition to a change to the model itself.*/ modelChange: string; /**Gets or sets an optional value associated with the new value.*/ @@ -4186,7 +4699,7 @@ declare module go { newValue: any; /**Gets or sets the Object that was modified.*/ - object: Object; + object: any; /**Gets or sets an optional value associated with the old value.*/ oldParam: any; @@ -4195,7 +4708,7 @@ declare module go { oldValue: any; /**Gets or sets the name of the property change.*/ - propertyName: any; + propertyName: PropertyAccessor; /** * This predicate returns true if you can call redo(). @@ -4210,7 +4723,7 @@ declare module go { /** * Forget any object references that this ChangedEvent may have. */ - clear(); + clear(): void; /** * Make a copy of this ChangedEvent. @@ -4234,23 +4747,23 @@ declare module go { /** * Re-perform this object change after an undo(). */ - redo(); + redo(): void; /** * Reverse the effects of this object change. */ - undo(); + undo(): void; - /**For inserting into collections, and used as the value for ChangedEvent#change.*/ + /**For inserting into collections, and used as the value for ChangedEvent.change.*/ static Insert: EnumValue; - /**For simple property changes, and used as the value for ChangedEvent#change.*/ + /**For simple property changes, and used as the value for ChangedEvent.change.*/ static Property: EnumValue; - /**For removing from collections, and used as the value for ChangedEvent#change.*/ + /**For removing from collections, and used as the value for ChangedEvent.change.*/ static Remove: EnumValue; - /**For informational events, such as transactions and undo/redo operations, and used as the value for ChangedEvent#change.*/ + /**For informational events, such as transactions and undo/redo operations, and used as the value for ChangedEvent.change.*/ static Transaction: EnumValue; } @@ -4263,22 +4776,41 @@ declare module go { */ class GraphLinksModel extends Model { /** - * This constructs an empty GraphLinksModel unless one provides arguments as the initial data array values for the Model#nodeDataArray and GraphLinksModel#linkDataArray properties. - * @param {Array=} nodedataarray an optional Array containing JavaScript objects to be represented by Nodes. - * @param {Array=} linkdataarray an optional Array containing JavaScript objects to be represented by Links. + * This constructs an empty GraphLinksModel unless one provides arguments as the initial data array values for the Model.nodeDataArray and GraphLinksModel.linkDataArray properties. + * @param {Array=} nodedataarray an optional Array containing JavaScript objects to be represented by Nodes. + * @param {Array=} linkdataarray an optional Array containing JavaScript objects to be represented by Links. */ constructor(nodedataarray?: Array, linkdataarray?: Array); - /**Gets or sets a data object that will be copied and added to the model as a new node data each time there is a link reference (either the "to" or the "from" of a link data) to a node key that does not yet exist in the model.*/ + /** + * Gets or sets a data object that will be copied and added to the model as a new node data each time there + * is a link reference (either the "to" or the "from" of a link data) to a node key that does not yet exist in the model. + * The default value is null -- node data is not automatically copied and added to the model + * when there is an unresolved reference in a link data. + * When adding or modifying a link data if there is a "from" or "to" key value for which Model.findNodeDataForKey returns null, + * it will call Model.copyNodeData on this property value and Model.addNodeData on the result. + */ archetypeNodeData: Object; - /**Gets or sets a function that makes a copy of a link data object.*/ + /** + * Gets or sets a function that makes a copy of a link data object. + * You may need to set this property in order to ensure that a copied Link is bound + * to data that does not share certain data structures between the original link data and the copied link data. + * The value may be null in order to cause .copyLinkData to make a shallow copy of a JavaScript Object. + * The default value is null. + */ copyLinkDataFunction: (obj: Object, model: GraphLinksModel) => Object; - /**Gets or sets the name of the data property that returns a string describing that data's category, or a function that takes a link data object and returns that category string; the default value is the name 'category'.*/ - linkCategoryProperty: any; + /** + * Gets or sets the name of the data property that returns a string naming that data's category, + * or a function that takes a link data object and returns that category string; + * the default value is the name 'category'. + * This is used by the diagram to distinguish between different kinds of links. + * The name must not be null. + */ + linkCategoryProperty: PropertyAccessor; - /**Gets or sets the array of link data objects that correspond to Links in the Diagram.*/ + /**Gets or sets the array of link data objects that correspond to Links in the Diagram; the initial value is an empty Array.*/ linkDataArray: Array; /** @@ -4288,50 +4820,94 @@ declare module go { * the default value is the name 'from'. * The name must not be null. * If the value is an empty string, - * #getFromKeyForLinkData will return undefined for all link data objects. + * .getFromKeyForLinkData will return undefined for all link data objects. */ - linkFromKeyProperty: any; + linkFromKeyProperty: PropertyAccessor; - /**Gets or sets the name of the data property that returns the optional parameter naming a "port" element on the node that the link data is connected from, or a function that takes a link data object and returns that string.*/ - linkFromPortIdProperty: any; + /** + * Gets or sets the name of the data property that returns the optional parameter naming a "port" element on the node that the link data is connected from, + * or a function that takes a link data object and returns that string. + * The default value is the empty string indicating that one cannot distinguish + * different logical connection points for any links. + * The name must not be null. + */ + linkFromPortIdProperty: PropertyAccessor; - /**Gets or sets the name of the data property that returns an array of keys of node data that are labels on that link data, or a function that takes a link data object and returns such an array; the default value is the empty string: ''.*/ - linkLabelKeysProperty: any; + /** + * Gets or sets the name of the data property that returns + * an array of keys of node data that are labels on that link data, + * or a function that takes a link data object and returns such an array; + * the default value is the empty string: ''. + * The name must not be null. + * If the value is an empty string, + * .getLabelKeysForLinkData will return an empty array for all link data objects. + * You will need to set this property in order to support nodes as link labels. + */ + linkLabelKeysProperty: PropertyAccessor; - /**Gets or sets the name of the data property that returns the key of the node data that the link data is going to, or a function that takes a link data object and returns that key; the default value is the name 'to'.*/ - linkToKeyProperty: any; + /** + * Gets or sets the name of the data property that returns + * the key of the node data that the link data is going to, + * or a function that takes a link data object and returns that key; + * the default value is the name 'to'. + * The name must not be null. + */ + linkToKeyProperty: PropertyAccessor; - /**Gets or sets the name of the data property that returns the optional parameter naming a "port" element on the node that the link data is connected to, or a function that takes a link data object and returns that string.*/ - linkToPortIdProperty: any; + /** + * Gets or sets the name of the data property that returns + * the optional parameter naming a "port" element on the node that the link data is connected to, + * or a function that takes a link data object and returns that string. + * The default value is the empty string indicating that one cannot distinguish + * different logical connection points for any links. + * The name must not be null. + */ + linkToPortIdProperty: PropertyAccessor; - /**Gets or sets the name of the property on node data that specifies the string or number key of the group data that "owns" that node data, or a function that takes a node data object and returns that group key.*/ - nodeGroupKeyProperty: any; + /** + * Gets or sets the name of the property on node data that specifies + * the string or number key of the group data that "owns" that node data, + * or a function that takes a node data object and returns that group key. + * the default value is the name 'group'. + * The value must not be null. + */ + nodeGroupKeyProperty: PropertyAccessor; - /**Gets or sets the name of the boolean property on node data that indicates whether the data should be represented as a group of nodes and links or as a simple node, or a function that takes a node data object and returns true or false; the default value is the name 'isGroup'.*/ - nodeIsGroupProperty: any; - - /**Gets or sets the name of the boolean property on node data that indicates whether the data should be represented as a node acting as a label on a link instead of being a regular node, or a function that takes a node data object and returns true or false; the default value is the empty string: ''.*/ - nodeIsLinkLabelProperty: any; + /** + * Gets or sets the name of the boolean property on node data that indicates + * whether the data should be represented as a group of nodes and links or + * as a simple node, + * or a function that takes a node data object and returns true or false; + * the default value is the name 'isGroup'. + * The value must not be null. + */ + nodeIsGroupProperty: PropertyAccessor; /** * Adds a node key value that identifies a node data acting as a new label node on the given link data. - * This method only works if #linkLabelKeysProperty has been set to something other than an empty string. + * This method only works if .linkLabelKeysProperty has been set to something other than an empty string. * @param {Object} linkdata a JavaScript object representing a link. - * @param {number|string} key a number or string that is the key of the new label node. + * @param {string|number} key a number or string that is the key of the new label node. */ - addLabelKeyForLinkData(linkdata: Object, key: any); + addLabelKeyForLinkData(linkdata: Object, key: Key): void; /** * When you want to add a link to the diagram, call this method with a new data object. - * This will add that data to the #linkDataArray and + * This will add that data to the .linkDataArray and * notify all listeners that a new link data object has been inserted into the collection. * Presumably the link data object will already have its "from" and "to" node key references set, * but it is also possible to set them after the link data is in the model - * by calling #setFromKeyForLinkData and #setToKeyForLinkData. - * This operation does nothing if the link data is already part of this model's #linkDataArray. + * by calling .setFromKeyForLinkData and .setToKeyForLinkData. + * This operation does nothing if the link data is already part of this model's .linkDataArray. * @param {Object} linkdata a JavaScript object representing a link. */ - addLinkData(linkdata: Object); + addLinkData(linkdata: Object): void; + + /** + * Add to this model all of the link data held in an Array or in an Iterable of link data objects. + * @param {Iterable|Array} coll a collection of link data objects to add to the .linkDataArray + */ + addLinkDataCollection(coll: Iterable | Array): void; /** * Decide if a given link data is in this model. @@ -4340,11 +4916,13 @@ declare module go { containsLinkData(linkdata: Object): boolean; /** - * Gets or sets a function that makes a copy of a link data object. - * You may need to set this property in order to ensure that a copied Link is bound - * to data that does not share certain data structures between the original link data and the copied link data. - * The value may be null in order to cause #copyLinkData to make a shallow copy of a JavaScript Object. - * The default value is null. + * Make a copy of a link data object. + * This uses the value of .copyLinkDataFunction to actually perform the copy, + * unless it is null, in which case this method just makes a shallow copy of the JavaScript Object. + * This does not modify the model -- the returned data object is not added to this model. + * This assumes that the data's constructor can be called with no arguments. + * This also makes sure there is no reference to either the "from" or the "to" node of the original data. + * @param {Object} linkdata a JavaScript object representing a link. */ copyLinkData(linkdata: Object): Object; @@ -4360,7 +4938,7 @@ declare module go { * from which this link is connected. * @param {Object} linkdata a JavaScript object representing a link. */ - getFromKeyForLinkData(linkdata: Object): any; + getFromKeyForLinkData(linkdata: Object): Key; /** * From a link data retrieve a value identifying the port object of the node @@ -4373,21 +4951,21 @@ declare module go { * If there is a container group for the given node data, return the group's key. * @param {Object} nodedata a JavaScript object representing a node, group, or non-link. */ - getGroupKeyForNodeData(nodedata: Object): any; + getGroupKeyForNodeData(nodedata: Object): Key; /** * Gets an Array of node key values that identify node data acting as labels on the given link data. - * This method only works if #linkLabelKeysProperty has been set to something other than an empty string. + * This method only works if .linkLabelKeysProperty has been set to something other than an empty string. * @param {Object} linkdata a JavaScript object representing a link. */ - getLabelKeysForLinkData(linkdata: Object): Array; + getLabelKeysForLinkData(linkdata: Object): Array; /** * From a link data retrieve a value uniquely identifying the node data * to which this link is connected. * @param {Object} linkdata a JavaScript object representing a link. */ - getToKeyForLinkData(linkdata: Object): any; + getToKeyForLinkData(linkdata: Object): Key; /** * From a link data retrieve a value identifying the port object of the node @@ -4404,55 +4982,52 @@ declare module go { */ isGroupForNodeData(nodedata: Object): boolean; - /** - * See if the given node data should act as a label on a link, in order to support - * the appearance and behavior of having links connected to links. - * This value must not change as long as the node data is part of the model. - * At the current time there is no setIsLinkLabelForNodeData method. - * @param {Object} nodedata a JavaScript object representing a node, group, or non-link. - */ - isLinkLabelForNodeData(nodedata: Object): boolean; - /** * Removes a node key value that identifies a node data acting as a former label node on the given link data. * Removing a reference to a node data from the collection of link label keys * does not automatically remove any node data from the model. - * This method only works if #linkLabelKeysProperty has been set to something other than an empty string. + * This method only works if .linkLabelKeysProperty has been set to something other than an empty string. * @param {Object} linkdata a JavaScript object representing a link. - * @param {number|string} key a number or string that is the key of the label node being removed from the link. + * @param {string|number} key a number or string that is the key of the label node being removed from the link. */ - removeLabelKeyForLinkData(linkdata: Object, key: any); + removeLabelKeyForLinkData(linkdata: Object, key: Key): void; /** * When you want to remove a link from the diagram, call this method with an existing link data object. - * This will remove that data from the #linkDataArray and + * This will remove that data from the .linkDataArray and * notify all listeners that a link data object has been removed from the collection. * Removing a link data from a model does not automatically remove * any associated label node data from the model. - * This operation does nothing if the link data is not present in the #linkDataArray. + * This operation does nothing if the link data is not present in the .linkDataArray. * @param {Object} linkdata a JavaScript object representing a link. */ - removeLinkData(linkdata: Object); + removeLinkData(linkdata: Object): void; + + /** + * Remove from this model all of the link data held in an Array or in an Iterable of link data objects. + * @param {Iterable|Array} coll a collection of link data objects to remove from the .linkDataArray + */ + removeLinkDataCollection(coll: Iterable | Array): void; /** * Change the category of a given link data, a string naming the link template * that the Diagram should use to represent the link data. * Changing the link template for a link data will cause the existing Link - * to be removed from the Diagram} and replaced with a new Link + * to be removed from the Diagram and be replaced with a new Link * created by copying the new link template and applying any data-bindings. * @param {Object} linkdata a JavaScript object representing a link. * @param {string} cat Must not be null. */ - setCategoryForLinkData(linkdata: Object, cat: string); + setCategoryForLinkData(linkdata: Object, cat: string): void; /** * Change the node key that the given link data references as the * source of the link. * @param {Object} linkdata a JavaScript object representing a link. - * @param {number|string|undefined} key This may be undefined if + * @param {string|number|undefined} key This may be undefined if * the link should no longer come from any node. */ - setFromKeyForLinkData(linkdata: Object, key: any); + setFromKeyForLinkData(linkdata: Object, key: Key): void; /** * Change the information that the given link data uses to identify the @@ -4461,31 +5036,31 @@ declare module go { * @param {string} portname This may be the empty string if * the link should no longer be associated with any particular "port". */ - setFromPortIdForLinkData(linkdata: Object, portname: string); + setFromPortIdForLinkData(linkdata: Object, portname: string): void; /** * Change the container group for the given node data, given a key for the new group. * @param {Object} nodedata a JavaScript object representing a node, group, or non-link. - * @param {number|string|undefined} key This may be undefined if there should be no containing group data. + * @param {string|number|undefined} key This may be undefined if there should be no containing group data. */ - setGroupKeyForNodeData(nodedata: Object, key: any); + setGroupKeyForNodeData(nodedata: Object, key: Key): void; /** * Replaces an Array of node key values that identify node data acting as labels on the given link data. - * This method only works if #linkLabelKeysProperty has been set to something other than an empty string. + * This method only works if .linkLabelKeysProperty has been set to something other than an empty string. * @param {Object} linkdata a JavaScript object representing a link. * @param arr an Array of node keys; an empty Array if the property was not present. */ - setLabelKeysForLinkData(linkdata: Object, arr: Array); + setLabelKeysForLinkData(linkdata: Object, arr: Array): void; /** * Change the node key that the given link data references as the * destination of the link. * @param {Object} linkdata a JavaScript object representing a link. - * @param {number|string|undefined} key This may be undefined if + * @param {string|number|undefined} key This may be undefined if * the link should no longer go to any node. */ - setToKeyForLinkData(linkdata: Object, key: any); + setToKeyForLinkData(linkdata: Object, key: Key): void; /** * Change the information that the given link data uses to identify the @@ -4494,7 +5069,7 @@ declare module go { * @param {string} portname This may be the empty string if * the link should no longer be associated with any particular "port". */ - setToPortIdForLinkData(linkdata: Object, portname: string); + setToPortIdForLinkData(linkdata: Object, portname: string): void; } /* @@ -4505,76 +5080,95 @@ declare module go { class Model { /** * You probably don't want to call this constructor, because this class does not support links (relationships between nodes) or groups (nodes and links and subgraphs as nodes): instead, create instances of a subclass such as GraphLinksModel or TreeModel. - * @param {Array=} nodedataarray an optional Array containing JavaScript objects to be represented by Parts. + * @param {Array=} nodedataarray an optional Array containing JavaScript objects to be represented by Parts. */ constructor(nodedataarray?: Array); - /**Gets or sets a function that makes a copy of a node data object.*/ + /**Gets or sets whether the default behavior for copyNodeData makes copies of property values that are Arrays.*/ + copiesArrays: boolean; + + /**Gets or sets whether the default behavior for copyNodeData when copying Arrays also copies array items that are Objects.*/ + copiesArrayObjects: boolean; + + /**Gets or sets a function that makes a copy of a node data object; the default value is null, resulting in the standard behavior which is to make a shallow copy of the object.*/ copyNodeDataFunction: (obj: Object, model: Model) => Object; - /**Gets or sets the name of the format of the diagram data.*/ + /**Gets or sets the name of the format of the diagram data; the default value is the empty string.*/ dataFormat: string; - /**Gets or sets whether this model may be modified, such as adding nodes.*/ + /**Gets or sets whether this model may be modified, such as adding nodes; by default this value is false.*/ isReadOnly: boolean; - /**Gets or sets a function that returns a unique id number or string for a node data object.*/ - makeUniqueKeyFunction: (model: Model, obj:Object) => any; + /**Gets or sets a function that returns a unique id number or string for a node data object; the default value is null.*/ + makeUniqueKeyFunction: (model: Model, obj: Object) => Key; - /**Gets or sets the name of this model.*/ + /**Gets a JavaScript Object that can hold programmer-defined property values for the model as a whole, rather than just for one node or one link; by default this is an object with no properties.*/ + modelData: any; + + /**Gets or sets the name of this model; the initial name is an empty string.*/ name: string; - /**Gets or sets the name of the node data property that returns a string describing that data's category, or a function that takes a node data object and returns the category name; the default value is the name 'category'.*/ - nodeCategoryProperty: any; + /**Gets or sets the name of the node data property that returns a string naming that data's category, or a function that takes a node data object and returns the category name; the default value is the name 'category'.*/ + nodeCategoryProperty: PropertyAccessor; - /**Gets or sets the array of node data objects that correspond to Nodes, Groups, or non-Link Parts in the Diagram.*/ + /**Gets or sets the array of node data objects that correspond to Nodes, Groups, or non-Link Parts in the Diagram; the initial value is an empty Array.*/ nodeDataArray: Array; /**Gets or sets the name of the data property that returns a unique id number or string for each node data object, or a function taking a node data object and returning the key value; the default value is the name 'key'.*/ - nodeKeyProperty: any; + nodeKeyProperty: PropertyAccessor; - /**Gets or sets whether ChangedEvents are not recorded by the UndoManager.*/ + /**Gets or sets whether ChangedEvents are not recorded by the UndoManager; the initial and normal value is false.*/ skipsUndoManager: boolean; - /**Gets or sets the UndoManager for this Model.*/ + /**Gets or sets the UndoManager for this Model; the default UndoManager has its UndoManager.isEnabled property set to false.*/ undoManager: UndoManager; /** - * Add an item at the end of a data array that may be data bound by a Panel as its Panel#itemArray, + * Add an item at the end of a data array that may be data bound by a Panel as its Panel.itemArray, * in a manner that can be undone/redone and that automatically updates any bindings. - * This also calls #raiseChangedEvent to notify all listeners about the ChangedEvent#Insert. - * If you want to add a new node or part to the diagram, call #addNodeData. - * @param {Array} arr an Array that is the value of some Panel's Panel#itemArray. + * This also calls .raiseChangedEvent to notify all listeners about the ChangedEvent.Insert. + * If you want to add a new node or part to the diagram, call .addNodeData. + * @param {Array<*>} arr an Array that is the value of some Panel's Panel.itemArray. * @param {*} val the new value to be pushed onto the array. */ - addArrayItem(arr: any[], val: any); + addArrayItem(arr: Array, val: any): void; /** * Register an event handler that is called when there is a ChangedEvent. * This registration does not raise a ChangedEvent. * @param {function(ChangedEvent)} listener a function that takes a ChangedEvent as its argument. */ - addChangedListener(listener: (e: ChangedEvent)=>void); + addChangedListener(listener: (e: ChangedEvent) => void ): void; /** * When you want to add a node or group to the diagram, * call this method with a new data object. - * This will add that data to the #nodeDataArray and + * This will add that data to the .nodeDataArray and * notify all listeners that a new node data object has been inserted into the collection. - * To remove a node from the diagram, you can remove its data object by calling #removeNodeData. - * To add or remove an object or value from an item array, call #insertArrayItem or #removeArrayItem. + * To remove a node from the diagram, you can remove its data object by calling .removeNodeData. + * To add or remove an object or value from an item array, call .insertArrayItem or .removeArrayItem. * @param {Object} nodedata a JavaScript object representing a node, group, or non-link. */ - addNodeData(nodedata: Object); + addNodeData(nodedata: Object): void; + + /** + * Add to this model all of the node data held in an Array or in an Iterable of node data objects. + * @param {Iterable|Array} coll a collection of node data objects to add to the .nodeDataArray + */ + addNodeDataCollection(coll: Iterable | Array): void; /** * Clear out all references to any model data. + * This also clears out the UndoManager, so this operation is not undoable. + * This method is called by Diagram.clear; it does not notify any Diagrams or other listeners. + * Instead of calling this method, you may prefer to set .nodeDataArray to an empty JavaScript Array. + * If this model is a GraphLinksModel, you would also want to set GraphLinksModel.linkDataArray to a separate empty JavaScript Array. */ - clear(); + clear(): void; /** * Commit the changes of the current transaction. - * This just calls UndoManager#commitTransaction. + * This just calls UndoManager.commitTransaction. * @param {string} tname a descriptive name for the transaction. */ commitTransaction(tname: string): boolean; @@ -4587,7 +5181,7 @@ declare module go { /** * Make a copy of a node data object. - * This uses the value of #copyNodeDataFunction to actually perform the copy, + * This uses the value of .copyNodeDataFunction to actually perform the copy, * unless it is null, in which case this method just makes a shallow copy of the JavaScript Object. * This does not modify the model -- the returned data object is not added to this model. * This assumes that the data's constructor can be called with no arguments. @@ -4600,14 +5194,17 @@ declare module go { * that uses the given value as its unique key. * @param {*} key a string or a number. */ - findNodeDataForKey(key: any): Object; + findNodeDataForKey(key: Key): any; /** - * This static method parses a string in JSON format and constructs, initializes, and returns a model. - * @param {string|Object} s a String in JSON format containing all of the persistent properties of the model, or an Object already read from JSON text. + * This static function parses a string in JSON format and constructs, initializes, and returns a model. + * Note that properties with values that are functions are not written out by .toJson, + * so reading in such a model will require constructing such a model, initializing its functional property values, + * and explicitly passing it in as the second argument. + * @param {string} s a String in JSON format containing all of the persistent properties of the model, or an Object already read from JSON text. * @param {model=} model an optional model to be modified; if not supplied, it constructs and returns a new model whose name is specified by the "class" property. */ - static fromJson(s: any, model?: Model): Model; + static fromJson(s: string | Object, model?: Model): Model; /** * Find the category of a given node data, a string naming the node template @@ -4619,41 +5216,42 @@ declare module go { /** * Given a node data object return its unique key: a number or a string. - * It is possible to change the key for a node data object by calling #setKeyForNodeData. + * This returns undefined if there is no key value. + * It is possible to change the key for a node data object by calling .setKeyForNodeData. * @param {Object} nodedata a JavaScript object representing a node, group, or non-link. */ - getKeyForNodeData(nodedata: Object): any; + getKeyForNodeData(nodedata: Object): Key; /** - * Add an item to a data array that may be data bound by a Panel as its Panel#itemArray, + * Add an item to a data array that may be data bound by a Panel as its Panel.itemArray, * given a new data value and the index at which to insert the new value, in a manner that can be undone/redone and that automatically updates any bindings. - * This also calls #raiseChangedEvent to notify all listeners about the ChangedEvent#Insert. - * If you want to add a new node or part to the diagram, call #addNodeData. - * @param {Array} arr an Array that is the value of some Panel's Panel#itemArray. + * This also calls .raiseChangedEvent to notify all listeners about the ChangedEvent.Insert. + * If you want to add a new node or part to the diagram, call .addNodeData. + * @param Array<*> arr an Array that is the value of some Panel's Panel.itemArray. * @param {number} idx the zero-based array index where the new value will be inserted; use -1 to push the new value on the end of the array. * @param {*} val the new value to be inserted into the array. */ - insertArrayItem(arr: any[], idx: number, val: any); + insertArrayItem(arr: Array, idx: number, val: any): void; /** * This method is called when a node data object is added to the model to make sure that - * #getKeyForNodeData returns a unique key value. + * .getKeyForNodeData returns a unique key value. * The key value should be unique within the set of data managed by this model: - * #nodeDataArray. + * .nodeDataArray. * If the key is already in use, this will assign an unused number to the - * #nodeKeyProperty property on the data. + * .nodeKeyProperty property on the data. * If you want to customize the way in which node data gets a unique key, - * you can set the #makeUniqueKeyFunction functional property. + * you can set the .makeUniqueKeyFunction functional property. * If the node data object is already in the model and you want to change its key value, - * call #setKeyForNodeData and give it a new unique key value. + * call .setKeyForNodeData and give it a new unique key value. * @param {Object} nodedata a JavaScript object representing a node, group, or non-link. */ - makeNodeDataKeyUnique(nodedata: Object); + makeNodeDataKeyUnique(nodedata: Object): void; /** * Call this method to notify that the model or its objects have changed. * This constructs a ChangedEvent and calls all Changed listeners. - * @param {EnumValue} change specifies the general nature of the change; typically the value is ChangedEvent#Property. + * @param {EnumValue} change specifies the general nature of the change; typically the value is ChangedEvent.Property. * @param {string|function(Object):*} propertyname names the property that was modified, or a function that takes an Object and returns the property value. * @param {Object} obj the object that was modified, typically a GraphObject, Diagram, or a Model. * @param {*} oldval the previous or older value. @@ -4661,13 +5259,13 @@ declare module go { * @param {*=} oldparam an optional value that helps describe the older value. * @param {*=} newparam an optional value that helps describe the newer value. */ - raiseChangedEvent(change: EnumValue, propertyname: any, obj: Object, oldval: any, newval: any, oldparam?: any, newparam?: any); + raiseChangedEvent(change: EnumValue, propertyname: PropertyAccessor, obj: Object, oldval: any, newval: any, oldparam?: any, newparam?: any): void; /** * Call this method to notify about a data property having changed value. * This constructs a ChangedEvent and calls all Changed listeners. * You should call this method only if the property value actually changed. - * This method is called by #setDataProperty. + * This method is called by .setDataProperty. * @param {Object} data the data object whose property changed value. * @param {string|function(Object):*} propertyname the name of the property, or a function that takes an Object and returns the property value. * @param {*} oldval the previous or old value for the property. @@ -4675,46 +5273,53 @@ declare module go { * @param {*=} oldparam an optional value additionally describing the old value. * @param {*=} newparam an optional value additionally describing the new value. */ - raiseDataChanged(data: Object, propertyname: any, oldval: any, newval: any, oldparam?: any, newparam?: any); + raiseDataChanged(data: Object, propertyname: PropertyAccessor, oldval: any, newval: any, oldparam?: any, newparam?: any): void; /** - * Remove an item from a data array that may be data bound by a Panel as its Panel#itemArray, + * Remove an item from a data array that may be data bound by a Panel as its Panel.itemArray, * given the index at which to remove a data value, in a manner that can be undone/redone and that automatically updates any bindings. - * This also calls #raiseChangedEvent to notify all listeners about the ChangedEvent#Remove. - * If you want to remove a node from the diagram, call #removeNodeData. + * This also calls .raiseChangedEvent to notify all listeners about the ChangedEvent.Remove. + * If you want to remove a node from the diagram, call .removeNodeData. * Note that there is no version of this method that takes an item value instead of an index into the array. * Because item arrays may hold any JavaScript value, including numbers and strings, there may be duplicate entries with that value in the array. * To avoid ambiguity, removing an item from an array requires an index. - * @param {Array} arr an Array that is the value of some Panel's Panel#itemArray. + * @param Array<*> arr an Array that is the value of some Panel's Panel.itemArray. * @param {number=} idx the zero-based array index of the data item to be removed from the array; * if not supplied it will remove the last item of the array. */ - removeArrayItem(arr: any[], idx?: number); + removeArrayItem(arr: Array, idx?: number): void; /** * Unregister an event handler listener. * This deregistration does not raise a ChangedEvent. * @param {function(ChangedEvent)} listener a function that takes a ChangedEvent as its argument. */ - removeChangedListener(listener: (e:ChangedEvent) => void); + removeChangedListener(listener: (e: ChangedEvent) => void ): void; /** * When you want to remove a node or group from the diagram, * call this method with an existing data object. - * This will remove that data from the #nodeDataArray and + * This will remove that data from the .nodeDataArray and * notify all listeners that a node data object has been removed from the collection. * Removing a node data from a model does not automatically remove * any connected link data from the model. * Removing a node data that represents a group does not automatically remove * any member node data or link data from the model. - * To add a node to the diagram, you can add its data object by calling #addNodeData. - * To add or remove an object or value from an item array, call #insertArrayItem or #removeArrayItem. + * To add a node to the diagram, you can add its data object by calling .addNodeData. + * To add or remove an object or value from an item array, call .insertArrayItem or .removeArrayItem. * @param {Object} nodedata a JavaScript object representing a node, group, or non-link. */ - removeNodeData(nodedata: Object); + removeNodeData(nodedata: Object): void; + + /** + * Remove from this model all of the node data held in an Array or in an Iterable of node data objects. + * @param {Iterable|Array} coll a collection of node data objects to remove from the .nodeDataArray + */ + removeNodeDataCollection(coll: Iterable | Array): void; /** * Rollback the current transaction, undoing any recorded changes. + * This just calls UndoManager.rollbackTransaction. */ rollbackTransaction(): boolean; @@ -4728,32 +5333,30 @@ declare module go { * @param {Object} nodedata a JavaScript object representing a node, group, or non-link. * @param {string} cat Must not be null. */ - setCategoryForNodeData(nodedata: Object, cat: string); + setCategoryForNodeData(nodedata: Object, cat: string): void; /** - * @ignore * Change the value of some property of a node data, a link data, or an item data, given a string naming the property * and the new value, in a manner that can be undone/redone and that automatically updates any bindings. - * This override handles link data as well as node data. * This gets the old value of the property; if the value is the same as the new value, no side-effects occur. - * @param {Object} data a JavaScript object representing a node, group, or non-link. + * @param {Object} data a JavaScript object representing a Node, Link, Group, simple Part, or item in a Panel.itemArray. * @param {string} propname a string that is not null or the empty string. * @param {*} val the new value for the property. */ - setDataProperty(data: Object, propname: string, val: any); + setDataProperty(data: Object, propname: string, val: any): void; /** * Change the unique key of a given node data that is already in this model. * The new key value must be unique -- i.e. not in use by another node data object. - * You can call #findNodeDataForKey to check if a proposed new key is already in use. + * You can call .findNodeDataForKey to check if a proposed new key is already in use. * This operation will check all data objects in the model and replace all references * using the old key value with the new one. * If this is called on a node data object that is not (yet) in this model, * this unconditionally modifies the property to the new key value. * @param {Object} nodedata a JavaScript object representing a node, group, or non-link. - * @param {number|string|undefined} key + * @param {string|number|undefined} key */ - setKeyForNodeData(nodedata: Object, key: any); + setKeyForNodeData(nodedata: Object, key: Key): void; /** * Begin a transaction, where the changes are held by a Transaction object in the UndoManager. @@ -4764,11 +5367,18 @@ declare module go { /** * Generate a string representation of the persistent data in this model, in JSON format. - * Object properties whose names start with "_" are not written out. + * Object properties that are not enumerable or whose names start with "_" are not written out. * Functions are not able to be written in JSON format, so any properties that have function values * will not be saved in the JSON string. * There must not be any circular references within the model data. * Any sharing of object references will be lost in the written JSON. + * Most object classes cannot be serialized into JSON without special knowledge and processing at both ends. + * The .toJson and Model.fromJson methods automatically do such processing for numbers that are NaN + * and for objects that are of class Point, Size, Rect, Margin, Spot, + * Brush (but not for brush patterns), and for Geometry. + * However, we recommend that you use Binding converters (static functions named "parse" and "stringify") + * to represent Points, Sizes, Rects, Margins, Spots, and Geometries as string values in your data, rather than as Objects. + * This makes the JSON text smaller and simpler and easier to read. * @param {string=} classname The optional name of the model class to use in the output; * for the standard models, this is their class name prefixed with "go.". */ @@ -4776,28 +5386,28 @@ declare module go { /** * Find a Part corresponding to the given data and - * call its Panel#updateTargetBindings method, in each Diagram + * call its Panel.updateTargetBindings method, in each Diagram * that uses this Model. * @param {Object} data The data object in this model that was modified. * @param {string=} srcpropname If not present or the empty string, * update all bindings on the target Part or item Panel; * otherwise update only those bindings using this source property name. */ - updateTargetBindings(data: Object, srcpropname?: string); + updateTargetBindings(data: Object, srcpropname?: string): void; } /** * A Transaction holds a list of ChangedEvents collected during a transaction, - * as the value of the read-only #changes} property. + * as the value of the read-only .changes property. */ class Transaction { /** - * Construct an object holding an empty list of ChangedEvents and no #name. + * Construct an object holding an empty list of ChangedEvents and no .name. */ constructor(); - /**Gets the list of ChangedEvents.*/ - changes: List; + /**This read-only property returns the list of ChangedEvents.*/ + changes: List; /**Gets or sets whether we can add more ChangedEvents to this list of changes.*/ isComplete: boolean; @@ -4806,29 +5416,29 @@ declare module go { name: string; /** - * This predicate returns true if you can call #redo, namely when #isComplete is true. + * This predicate returns true if you can call .redo, namely when .isComplete is true. */ canRedo(): boolean; /** - * This predicate returns true if you can call #undo, namely when #isComplete is true. + * This predicate returns true if you can call .undo, namely when .isComplete is true. */ canUndo(): boolean; /** * Clear all of the saved changes. */ - clear(); + clear(): void; /** - * Re-perform these changes after an #undo. + * Re-perform these changes after an .undo. */ - redo(); + redo(): void; /** * Undo all of the changes, in reverse order. */ - undo(); + undo(): void; } /** @@ -4838,22 +5448,34 @@ declare module go { */ class TreeModel extends Model { /** - * This constructs an empty TreeModel unless one provides arguments as the initial data array values for the Model#nodeDataArray property. - * @param {Array=} nodedataarray an optional Array containing JavaScript objects to be represented by Nodes. + * This constructs an empty TreeModel unless one provides arguments as the initial data array values for the Model.nodeDataArray property. + * @param {Array=} nodedataarray an optional Array containing JavaScript objects to be represented by Nodes. */ constructor(nodedataarray?: Array); - /**Gets or sets the name of the property on node data that specifies the string or number key of the node data that acts as the "parent" for this "child" node data, or a function that takes a node data object and returns that parent key; the default value is the name 'parent'.*/ - nodeParentKeyProperty: any; + /** + * Gets or sets the name of the property on node data that specifies + * the string or number key of the node data that acts as the "parent" for this "child" node data, + * or a function that takes a node data object and returns that parent key; + * the default value is the name 'parent'. + * The value must not be null nor an empty string. + */ + nodeParentKeyProperty: PropertyAccessor; - /**Gets or sets the name of the data property that returns a string describing that node data's parent link's category, or a function that takes a node data object and returns its parent link's category string; the default value is the name 'parentLinkCategory'.*/ - parentLinkCategoryProperty: any; + /** + * Gets or sets the name of the data property that returns a string describing that node data's parent link's category, + * or a function that takes a node data object and returns its parent link's category string; + * the default value is the name 'parentLinkCategory'. + * This is used by the diagram to distinguish between different kinds of links. + * The name must not be null. + */ + parentLinkCategoryProperty: PropertyAccessor; /** * If there is a parent node for the given node data, return the parent's key. * @param {Object} nodedata a JavaScript object representing a node. */ - getParentKeyForNodeData(nodedata: Object): any; + getParentKeyForNodeData(nodedata: Object): Key; /** * Find the category for the parent link of a given child node data, a string naming the link template @@ -4865,26 +5487,25 @@ declare module go { /** * Change the parent node for the given node data, given a key for the new parent, or undefined if there should be no parent. * @param {Object} nodedata a JavaScript object representing a node. - * @param {number|string|undefined} key This may be undefined if there should be no parent node data. + * @param {string|number|undefined} key This may be undefined if there should be no parent node data. */ - setParentKeyForNodeData(nodedata: Object, key: any); + setParentKeyForNodeData(nodedata: Object, key: Key): void; /** * Change the category for the parent link of a given child node data, a string naming the link template * that the Diagram should use to represent the link. - * * Changing the link template will cause any existing Link * to be removed from the Diagram and replaced with a new Link * created by copying the new link template and applying any data-bindings. * @param {Object} childdata a JavaScript object representing a node data. * @param {string} cat Must not be null. */ - setParentLinkCategoryForNodeData(childdata: Object, cat: string); + setParentLinkCategoryForNodeData(childdata: Object, cat: string): void; } /** * A Transaction holds a list of ChangedEvents collected during a transaction, - * as the value of the read-only #changes} property. + * as the value of the read-only .changes property. */ class UndoManager { /** @@ -4892,95 +5513,95 @@ declare module go { */ constructor(); - /**Gets the current Transaction for recording additional model change events.*/ + /**This read-only property returns the current Transaction for recording additional model change events.*/ currentTransaction: Transaction; - /**Gets the whole history, a list of all of the Transactions, each representing a transaction with some number of ChangedEvents.*/ - history: List; + /**This read-only property returns the whole history, a list of all of the Transactions, each representing a transaction with some number of ChangedEvents.*/ + history: List; - /**Gets the index into #history for the current undoable Transaction.*/ + /**This read-only property returns the index into .history for the current undoable Transaction.*/ hisotryIndex: number; /**Gets or sets whether this UndoManager records any changes.*/ isEnabled: boolean; - /**This property is true after the first call to #startTransaction and before a corresponding call to #commitTransaction or #rollbackTransaction.*/ + /**This property is true after the first call to .startTransaction and before a corresponding call to .commitTransaction or .rollbackTransaction.*/ isInTransaction: boolean; - /**This property is true during a call to #undo or #redo.*/ + /**This property is true during a call to .undo or .redo.*/ isUndoingRedoing: boolean; /**Gets or sets the maximum number of transactions that this undo manager will remember.*/ maxHistoryLength: number; - /**Gets an iterator for all of the Models that this UndoManager is handling.*/ - models: Iterator; + /**This read-only property returns an iterator for all of the Models that this UndoManager is handling.*/ + models: Iterator; - /**Gets a stack of ongoing transaction names.*/ - nestedTransactionNames: List; + /**This read-only property returns a stack of ongoing transaction names.*/ + nestedTransactionNames: List; - /**Gets the current transaction level.*/ + /**This read-only property returns the current transaction level.*/ transactionLevel: number; - /**Gets the Transaction in the #history to be redone next.*/ + /**This read-only property returns the Transaction in the .history to be redone next.*/ transactionToRedo: Transaction; - /**Gets the Transaction in the #history to be undone next.*/ + /**This read-only property returns the Transaction in the .history to be undone next.*/ transactionToUndo: Transaction; /** * Make sure this UndoManager knows about a Model for which it may receive ChangedEvents when the given Model is changed. * @param {Model} model */ - addModel(model: Model); + addModel(model: Model): void; /** - * This predicate returns true if you can call #redo. + * This predicate returns true if you can call .redo. */ canRedo(): boolean; /** - * This predicate returns true if you can call #undo. + * This predicate returns true if you can call .undo. */ canUndo(): boolean; /** * Clear all of the Transactions and clear all other state, including any ongoing transaction without rolling back. */ - clear(); + clear(): void; /** - * Commit the current transaction started by a call to #startTransaction. - * For convenience, this method is called by Model#commitTransaction and Diagram#commitTransaction. + * Commit the current transaction started by a call to .startTransaction. + * For convenience, this method is called by Model.commitTransaction and Diagram.commitTransaction. * If this call stops a top-level transaction, - * we mark the #currentTransaction as complete (Transaction#isComplete), - * we add the Transaction to the #history list, + * we mark the .currentTransaction as complete (Transaction.isComplete), + * we add the Transaction to the .history list, * and we return true. * Committing a transaction when there have been some undos without corresponding * redos will throw away the Transactions holding changes that happened * after the current state, before adding the new Transaction to the - * #history list. + * .history list. * @param {string} tname a short string describing the transaction. */ commitTransaction(tname: string): boolean; /** - * Maybe record a ChangedEvent in the #currentTransaction. - * This calls #skipsEvent to see if this should ignore the change. - * If #skipsEvent returns false, this creates a copy of the ChangedEvent - * and adds it to the #currentTransaction. - * If there is no #currentTransaction, this first creates and remembers it. + * Maybe record a ChangedEvent in the .currentTransaction. + * This calls .skipsEvent to see if this should ignore the change. + * If .skipsEvent returns false, this creates a copy of the ChangedEvent + * and adds it to the .currentTransaction. + * If there is no .currentTransaction, this first creates and remembers it. * This method always ignores all changes while performing - * an #undo or #redo. - * This method is also a no-op if #isEnabled is false. + * an .undo or .redo. + * This method is also a no-op if .isEnabled is false. * @param {ChangedEvent} e a ChangedEvent. */ - handleChanged(e: ChangedEvent); + handleChanged(e: ChangedEvent): void; /** - * Re-perform this object change after an #undo. + * Re-perform this object change after an .undo. */ - redo(); + redo(): void; /** * Inform this UndoManager that it will no longer be receiving ChangedEvents @@ -4991,34 +5612,34 @@ declare module go { * you should be careful that there are no ChangedEvents referring to that model in any Transactions. * @param {Model} model A Model that this UndoManager should no longer manage. */ - removeModel(model: Model); + removeModel(model: Model): void; /** - * Rollback the current transaction started by a call to #startTransaction, undoing any changes. + * Rollback the current transaction started by a call to .startTransaction, undoing any changes. */ rollbackTransaction(): boolean; /** - * This predicate is called by #handleChanged to decide if a ChangedEvent + * This predicate is called by .handleChanged to decide if a ChangedEvent * is not interesting enough to be remembered. - * Transactional events (of change type ChangedEvent#Transaction) are always skipped. - * Changed events for GraphObjects that are in Layer#isTemporary layers are also skipped. - * Sometimes changed events do not even get to #handleChanged because - * Model#skipsUndoManager or Diagram#skipsUndoManager is true. - * @param {ChangedEvent} e the ChangedEvent received by #handleChanged. + * Transactional events (of change type ChangedEvent.Transaction) are always skipped. + * Changed events for GraphObjects that are in Layer.isTemporary layers are also skipped. + * Sometimes changed events do not even get to .handleChanged because + * Model.skipsUndoManager or Diagram.skipsUndoManager is true. + * @param {ChangedEvent} e the ChangedEvent received by .handleChanged. */ skipsEvent(e: ChangedEvent): boolean; /** * Begin a transaction, where the changes are held by a Transaction object - * as the value of #currentTransaction. - * You must call either #commitTransaction or #rollbackTransaction afterwards. - * For convenience, this method is called by Model#startTransaction and Diagram#startTransaction. + * as the value of .currentTransaction. + * You must call either .commitTransaction or .rollbackTransaction afterwards. + * For convenience, this method is called by Model.startTransaction and Diagram.startTransaction. * Transactions can be nested. * Starting or ending a nested transaction will return false. * Nested transactions will share the same Transaction list of ChangedEvents. - * Starting a transaction will not necessarily cause #currentTransaction to be non-null. - * A Transaction object is usually only created by #handleChanged when a ChangedEvent first occurs. + * Starting a transaction will not necessarily cause .currentTransaction to be non-null. + * A Transaction object is usually only created by .handleChanged when a ChangedEvent first occurs. * @param {string=} tname a short string describing the transaction. */ startTransaction(tname?: string): boolean; @@ -5026,7 +5647,9 @@ declare module go { /** * Reverse the effects of this object change. */ - undo(); + undo(): void; + + checksTransactionLevel: boolean; // undocumented } @@ -5038,20 +5661,20 @@ declare module go { */ class CircularLayout extends Layout { /** - * Constructs a CircularLayout with no Layout#network and with no owning Layout#diagram. + * Constructs a CircularLayout with no Layout.network and with no owning Layout.diagram. */ constructor(); /**Returns the coordinates of the center of the laid-out ellipse.*/ actualCenter: Point; - /**Gets the effective spacing that may have been calculated by the layout.*/ + /**This read-only property returns the effective spacing that may have been calculated by the layout.*/ actualSpacing: number; - /**Gets the effective X radius that may have been calculated by the layout.*/ + /**This read-only property returns the effective X radius that may have been calculated by the layout.*/ actualXRadius: number; - /**Gets the effective Y radius that may have been calculated by the layout.*/ + /**This read-only property returns the effective Y radius that may have been calculated by the layout.*/ actualYRadius: number; /**Gets or sets how the nodes are spaced.*/ @@ -5060,7 +5683,7 @@ declare module go { /**Gets or sets the ratio of the arrangement's height to its width (1 for a circle, >1 for a vertically elongated ellipse).*/ aspectRatio: number; - /**Gets or sets the comparer which sorts the data when #sorting is set to CircularLayout#Ascending or CircularLayout#Descending.*/ + /**Gets or sets the comparer which sorts the data when .sorting is set to CircularLayout.Ascending or CircularLayout.Descending.*/ comparer: (a: CircularVertex, b: CircularVertex) => number; /**Gets or sets whether the nodes are arranged clockwise or counterclockwise.*/ @@ -5075,7 +5698,7 @@ declare module go { /**Gets or sets if and how the nodes are sorted.*/ sorting: EnumValue; - /**Gets or sets the distance between nodes (if #radius is NaN) or the minimum distance between nodes (if #radius is a number).*/ + /**Gets or sets the distance between nodes (if .radius is NaN) or the minimum distance between nodes (if .radius is a number).*/ spacing: number; /**Gets or sets the angle (in degrees, clockwise from the positive side of the X axis) of the first element.*/ @@ -5087,17 +5710,17 @@ declare module go { /** * Position each Node according to the Vertex position, and then position the Links. */ - commitLayout(); + commitLayout(): void; /** * Commit the position and routing of all edge links. */ - commitLinks(); + commitLinks(): void; /** * Commit the position of all vertex nodes. */ - commitNodes(); + commitNodes(): void; /** * Create a new LayoutNetwork of CircularVertexes and CircularEdges. @@ -5106,55 +5729,53 @@ declare module go { /** * Assign the positions of the vertexes in the network. - * @param {Diagram|Group|Iterable} coll A Diagram or a Group or a collection of Parts. + * @param {Diagram | Group | Iterable} coll A Diagram or a Group or a collection of Parts. */ - doLayout(coll: Diagram); - doLayout(coll: Group); - doLayout(coll: Iterable); + doLayout(coll: (Diagram | Group | Iterable)): void; - /**Nodes are sorted using the #comparer, in ascending order; This value is used for CircularLayout#sorting.*/ + /**Nodes are sorted using the .comparer, in ascending order; This value is used for CircularLayout.sorting.*/ static Ascending: EnumValue; - /**The ring is filled by alternating sides; the second node is counterclockwise from the first node; This value is used for CircularLayout#direction.*/ + /**The ring is filled by alternating sides; the second node is counterclockwise from the first node; This value is used for CircularLayout.direction.*/ static BidirectionalLeft: EnumValue; - /**The ring is filled by alternating sides; the second node is clockwise from the first node; This value is used for CircularLayout#direction.*/ + /**The ring is filled by alternating sides; the second node is clockwise from the first node; This value is used for CircularLayout.direction.*/ static BidirectionalRight: EnumValue; - /**The effective diameter is either the width or height of the node, whichever is larger; This will cause circular nodes to touch when CircularLayout#spacing is 0; This is ideal when the nodes are circular.*/ + /**The effective diameter is either the width or height of the node, whichever is larger; This will cause circular nodes to touch when CircularLayout.spacing is 0; This is ideal when the nodes are circular.*/ static Circular: EnumValue; - /**Rings are filled clockwise; This value is used for CircularLayout#direction.*/ + /**Rings are filled clockwise; This value is used for CircularLayout.direction.*/ static Clockwise: EnumValue; - /**The angular distance between the nodes is constant; This value is used for CircularLayout#arrangement.*/ + /**The angular distance between the nodes is constant; This value is used for CircularLayout.arrangement.*/ static ConstantAngle: EnumValue; - /**The distance between the centers of the nodes is constant; This value is used for CircularLayout#arrangement.*/ + /**The distance between the centers of the nodes is constant; This value is used for CircularLayout.arrangement.*/ static ConstantDistance: EnumValue; - /**The spacing between the idealized boundaries of the nodes is constant; This value is used for CircularLayout#arrangement.*/ + /**The spacing between the idealized boundaries of the nodes is constant; This value is used for CircularLayout.arrangement.*/ static ConstantSpacing: EnumValue; - /**Rings are filled counterclockwise; This value is used for CircularLayout#direction.*/ + /**Rings are filled counterclockwise; This value is used for CircularLayout.direction.*/ static Counterclockwise: EnumValue; - /**Nodes are sorted using the #comparer, in reverse ascending (descending) order; This value is used for CircularLayout#sorting.*/ + /**Nodes are sorted using the .comparer, in reverse ascending (descending) order; This value is used for CircularLayout.sorting.*/ static Descending: EnumValue; - /**Nodes are arranged in the order given; This value is used for CircularLayout#sorting.*/ + /**Nodes are arranged in the order given; This value is used for CircularLayout.sorting.*/ static Forwards: EnumValue; - /**Nodes are ordered to reduce link crossings; This value is used for CircularLayout#sorting.*/ + /**Nodes are ordered to reduce link crossings; This value is used for CircularLayout.sorting.*/ static Optimized: EnumValue; - /**The vertices are arranged as close together as possible considering the CircularLayout#spacing, assuming the nodes are rectangular; This value is used for CircularLayout#arrangement.*/ + /**The vertices are arranged as close together as possible considering the CircularLayout.spacing, assuming the nodes are rectangular; This value is used for CircularLayout.arrangement.*/ static Packed: EnumValue; - /**The effective diameter is sqrt(width^2+height^2); The corners of square nodes will touch at 45 degrees when CircularLayout#spacing is 0; This value is used for CircularLayout#nodeDiameterFormula.*/ + /**The effective diameter is sqrt(width^2+height^2); The corners of square nodes will touch at 45 degrees when CircularLayout.spacing is 0; This value is used for CircularLayout.nodeDiameterFormula.*/ static Pythagorean: EnumValue; - /**Nodes are arranged in the reverse of the order given; This value is used for CircularLayout#sorting.*/ + /**Nodes are arranged in the reverse of the order given; This value is used for CircularLayout.sorting.*/ static Reverse: EnumValue; } @@ -5182,38 +5803,38 @@ declare module go { */ class ForceDirectedLayout extends Layout { /** - * Constructs a ForceDirectedLayout with no Layout#network and with no owning Layout#diagram. + * Constructs a ForceDirectedLayout with no Layout.network and with no owning Layout.diagram. */ constructor(); /**Gets or sets the space between which the layout will position the connected graphs that together compose the network.*/ arrangementSpacing: Size; - /**Gets or sets whether #commitNodes should move all of the nodes so that the nodes all fit with the top-left corner at the Layout#arrangementOrigin.*/ + /**Gets or sets whether .commitNodes should move all of the nodes so that the nodes all fit with the top-left corner at the Layout.arrangementOrigin.*/ arrangesToOrigin: boolean; - /**Gets or sets whether this layout should find all Nodes whose category is "Comment" and whose anchors are nodes represented in the network, and add ForceDirectedVertexes representing those balloon comments as nodes in the network.*/ + /**Gets or sets whether to call .addComments.*/ comments: boolean; - /**Gets the current iteration count, valid during a call to #doLayout.*/ + /**This read-only property returns the current iteration count, valid during a call to .doLayout.*/ currentIteration: number; - /**Gets or sets the default value computed by #electricalCharge.*/ + /**Gets or sets the default value computed by .electricalCharge.*/ defaultCommentElectricalCharge: number; - /**Gets or sets the default value computed by #springLength.*/ + /**Gets or sets the default value computed by .springLength.*/ defaultCommentSpringLength: number; - /**Gets or sets the default value computed by #electricalCharge.*/ + /**Gets or sets the default value computed by .electricalCharge.*/ defaultElectricalCharge: number; - /**Gets or sets the default value computed by #gravitationalMass.*/ + /**Gets or sets the default value computed by .gravitationalMass.*/ defaultGravitationalMass: number; - /**Gets or sets the default value computed by #springLength.*/ + /**Gets or sets the default value computed by .springLength.*/ defaultSpringLength: number; - /**Gets or sets the default value computed by #springStiffness.*/ + /**Gets or sets the default value computed by .springStiffness.*/ defaultSpringStiffness: number; /**Gets or sets approximately how far a node must move in order for the iterations to continue.*/ @@ -5225,23 +5846,32 @@ declare module go { /**Gets or sets the maximum number of iterations to perform when doing the force-directed auto layout.*/ maxIterations: number; - /**Gets or sets whether the fromSpot and the toSpot of every Link should be set to Spot#Default.*/ + /**Gets or sets a random number generator with a random() method; set to null in order to use and reset an internal repeatable pseudo-random number generator.*/ + randomNumberGenerator: { random: () => number }; + + /**Gets or sets whether the fromSpot and the toSpot of every Link should be set to Spot.Default.*/ setsPortSpots: boolean; + /** + * Find associated objects to be positioned along with the vertex. + * @param {LayoutVertex} v + */ + addComments(v: LayoutVertex): void; + /** * Position the Nodes according to the Vertex positions. */ - commitLayout(); + commitLayout(): void; /** * Commit the position and routing of all edge links. */ - commitLinks(); + commitLinks(): void; /** * Commit the position of all vertex nodes. */ - commitNodes(); + commitNodes(): void; /** * Create a new LayoutNetwork of ForceDirectedVertexes and ForceDirectedEdges. @@ -5250,16 +5880,14 @@ declare module go { /** * Assign the positions of the vertexes in the network. - * @param {Diagram|Group|Iterable} coll A Diagram or a Group or a collection of Parts. + * @param {(Diagram | Group | Iterable)} coll A Diagram or a Group or a collection of Parts. */ - doLayout(coll: Diagram); - doLayout(coll: Group); - doLayout(coll: Iterable); + doLayout(coll: (Diagram | Group | Iterable)): void; /** * Returns the charge of the vertex, - * the value of ForceDirectedVertex#charge if it's a number, - * or else the value of #defaultElectricalCharge. + * the value of ForceDirectedVertex.charge if it's a number, + * or else the value of .defaultElectricalCharge. * @param {ForceDirectedVertex} v */ electricalCharge(v: ForceDirectedVertex): number; @@ -5310,8 +5938,8 @@ declare module go { /** * Returns the mass of the vertex, - * the value of ForceDirectedVertex#mass if it's a number, - * or else the value of #defaultGravitationalMass. + * the value of ForceDirectedVertex.mass if it's a number, + * or else the value of .defaultGravitationalMass. * @param {ForceDirectedVertex} v */ gravitationalMass(v: ForceDirectedVertex): number; @@ -5319,11 +5947,18 @@ declare module go { /** * This predicate returns true if the vertex should not be moved * by the layout algorithm but still have an effect on nearby and connected vertexes. - * The default implementation returns ForceDirectedVertex#isFixed. + * The default implementation returns ForceDirectedVertex.isFixed. * @param {ForceDirectedVertex} v */ isFixed(v: ForceDirectedVertex): boolean; + /** + * Maybe move a vertex that isFixed. + * This is called each iteration on each such vertex. + * By default this does nothing. + */ + moveFixedVertex(v: ForceDirectedVertex): void; + /** * Returns the length of the spring representing an edge. * The two vertexes connected by the edge E are acted upon by a force of magnitude @@ -5381,7 +6016,7 @@ declare module go { */ constructor(); - /**Gets or sets whether the Part#location or the position should be used to arrange each part.*/ + /**Gets or sets whether the Part.location or the position should be used to arrange each part.*/ alignment: EnumValue; /**Gets or sets how to arrange the parts.*/ @@ -5391,7 +6026,7 @@ declare module go { cellSize: Size; /**Gets or sets the comparison function used to sort the parts.*/ - comparer: (a:Part, b:Part) => number; + comparer: (a: Part, b: Part) => number; /**Gets or sets what order to place the parts.*/ sorting: EnumValue; @@ -5407,34 +6042,32 @@ declare module go { /** * Assign the positions of the parts, ignoring any links. - * @param {Diagram|Group|Iterable} coll A Diagram or a Group or a collection of Parts. + * @param {(Diagram | Group | Iterable)} coll A Diagram or a Group or a collection of Parts. */ - doLayout(coll: Diagram); - doLayout(coll: Group); - doLayout(coll: Iterable); + doLayout(coll: (Diagram | Group | Iterable)): void; - /**Lay out each child according to the sort order given by GridLayout#comparer; This value is used for GridLayout#sorting.*/ + /**Lay out each child according to the sort order given by GridLayout.comparer; This value is used for GridLayout.sorting.*/ static Ascending: EnumValue; - /**Lay out each child in reverse sort order given by GridLayout#comparer; This value is used for GridLayout#sorting.*/ + /**Lay out each child in reverse sort order given by GridLayout.comparer; This value is used for GridLayout.sorting.*/ static Descending: EnumValue; - /**Lay out each child in the order in which they were found; This value is used for GridLayout#sorting.*/ + /**Lay out each child in the order in which they were found; This value is used for GridLayout.sorting.*/ static Forward: EnumValue; - /**Fill each row from left to right; This value is used for GridLayout#arrangement.*/ + /**Fill each row from left to right; This value is used for GridLayout.arrangement.*/ static LeftToRight: EnumValue; - /**Position the part's Part#location at a grid point; This value is used for GridLayout#alignment.*/ + /**Position the part's Part.location at a grid point; This value is used for GridLayout.alignment.*/ static Location: EnumValue; - /**Position the top-left corner of each part at a grid point; This value is used for GridLayout#alignment.*/ + /**Position the top-left corner of each part at a grid point; This value is used for GridLayout.alignment.*/ static Position: EnumValue; - /**Lay out each child in reverse order from which they were found; This value is used for GridLayout#sorting.*/ + /**Lay out each child in reverse order from which they were found; This value is used for GridLayout.sorting.*/ static Reverse: EnumValue; - /**Fill each row from right to left; This value is used for GridLayout#arrangement.*/ + /**Fill each row from right to left; This value is used for GridLayout.arrangement.*/ static RightToLeft: EnumValue; } @@ -5447,7 +6080,7 @@ declare module go { */ class LayeredDigraphLayout extends Layout { /** - * Constructs a LayeredDigraphLayout with no Layout#network and with no owning Layout#diagram. + * Constructs a LayeredDigraphLayout with no Layout.network and with no owning Layout.diagram. */ constructor(); @@ -5475,46 +6108,54 @@ declare module go { /**Gets or sets the size of each layer.*/ layerSpacing: number; - /**Gets the largest column value.*/ + /**This read-only property returns the largest column value.*/ maxColumn: number; - /**Gets the largest index value.*/ + /**This read-only property returns the largest index value.*/ maxIndex: number; - /**Gets the larges index layer.*/ + /**This read-only property returns the larges index layer.*/ maxIndexLayer: number; - /**Gets the largest layer value.*/ + /**This read-only property returns the largest layer value.*/ maxLayer: number; - /**Gets the smallest index layer.*/ + /**This read-only property returns the smallest index layer.*/ minIndexLayer: number; - /**Gets or sets the options used by the straighten and pack function, The default value is LayeredDigraphLayout#PackAll.*/ + /**Gets or sets the options used by the straighten and pack function, The default value is LayeredDigraphLayout.PackAll.*/ packOption: number; - /**Gets or sets whether the FromSpot and ToSpot of each link should be set to values appropriate for the given value of LayeredDigraphLayout#direction.*/ + /**Gets or sets whether the FromSpot and ToSpot of each link should be set to values appropriate for the given value of LayeredDigraphLayout.direction.*/ setsPortSpots: boolean; /** * Assigns every vertex in the input network to a layer. */ - assignLayers(); + assignLayers(): void; + + /** + * This overridable method is called by commitLayout + * to support custom arrangement of bands or labels across each layout layer. + * @param Array<*> layerRects an Array of Rects with the bounds of each of the "layers" + * @param {Point} offset the position of the top-left corner of the banded area relative to the coordinates given by the layerRects + */ + commitLayers(layerRects: Array, offset: Point): void; /** * Updates the physical location of "real" nodes and links to reflect the layout. */ - commitLayout(); + commitLayout(): void; /** * Routes the links. */ - commitLinks(); + commitLinks(): void; /** * Lays out the nodes. */ - commitNodes(); + commitNodes(): void; /** * Create a new LayoutNetwork of LayeredDigraphVertexes and LayeredDigraphEdges. @@ -5523,59 +6164,60 @@ declare module go { /** * Assign the positions of the vertexes in the network. - * @param {Diagram|Group|Iterable} coll A Diagram or a Group or a collection of Parts. + * @param {(Diagram | Group | Iterable)} coll A Diagram or a Group or a collection of Parts. */ - doLayout(coll: Diagram); - doLayout(coll: Group); - doLayout(coll: Iterable); + doLayout(coll: (Diagram | Group | Iterable)): void; - /**The faster, less aggressive, crossing reduction algorithm; a valid value for LayeredDigraphLayout#aggressiveOption.*/ + /**The faster, less aggressive, crossing reduction algorithm; a valid value for LayeredDigraphLayout.aggressiveOption.*/ static AggressiveLess: EnumValue; - /**The slower, more aggressive, crossing reduction algorithm, a valid value for LayeredDigraphLayout#aggressiveOption.*/ + /**The slower, more aggressive, crossing reduction algorithm, a valid value for LayeredDigraphLayout.aggressiveOption.*/ static AggressiveMore: EnumValue; - /**The fastest, but poorest, crossing reduction algorithm; a valid value for LayeredDigraphLayout#aggressiveOption.*/ + /**The fastest, but poorest, crossing reduction algorithm; a valid value for LayeredDigraphLayout.aggressiveOption.*/ static AggressiveNone: EnumValue; - /**Remove cycles using depth first cycle removal; a valid value of LayeredDigraphLayout#cycleRemoveOption.*/ + /**Remove cycles using depth first cycle removal; a valid value of LayeredDigraphLayout.cycleRemoveOption.*/ static CycleDepthFirst: EnumValue; - /**Remove cycles using greedy cycle removal; a valid value of LayeredDigraphLayout#cycleRemoveOption.*/ + /**Remove cycles using greedy cycle removal; a valid value of LayeredDigraphLayout.cycleRemoveOption.*/ static CycleGreedy: EnumValue; - /**Initialize using depth first in initialization; a valid value for LayeredDigraphLayout#initializeOption.*/ + /**Initialize using depth first in initialization; a valid value for LayeredDigraphLayout.initializeOption.*/ static InitDepthFirstIn: EnumValue; - /**Initialize using depth first out initialization; a valid value for LayeredDigraphLayout#initializeOption.*/ + /**Initialize using depth first out initialization; a valid value for LayeredDigraphLayout.initializeOption.*/ static InitDepthFirstOut: EnumValue; - /**Initialize using naive initialization; a valid value for LayeredDigraphLayout#initializeOption.*/ + /**Initialize using naive initialization; a valid value for LayeredDigraphLayout.initializeOption.*/ static InitNaive: EnumValue; - /**Assign layers using longest path sink layering; a valid value for LayeredDigraphLayout#layeringOption.*/ + /**Assign layers using longest path sink layering; a valid value for LayeredDigraphLayout.layeringOption.*/ static LayerLongestPathSink: EnumValue; - /**Assign layers using longest path source layering; a valid value for LayeredDigraphLayout#layeringOption.*/ + /**Assign layers using longest path source layering; a valid value for LayeredDigraphLayout.layeringOption.*/ static LayerLongestPathSource: EnumValue; - /**Assign layers using optimal link length layering; A valid value for LayeredDigraphLayout#layeringOption.*/ + /**Assign layers using optimal link length layering; A valid value for LayeredDigraphLayout.layeringOption.*/ static LayerOptimalLinkLength: EnumValue; - /**Enable all options for the LayeredDigraphLayout#packOption property; See also LayeredDigraphLayout#PackExpand, LayeredDigraphLayout#PackStraighten, and LayeredDigraphLayout#PackMedian.*/ + /**Enable all options for the LayeredDigraphLayout.packOption property; See also LayeredDigraphLayout.PackExpand, LayeredDigraphLayout.PackStraighten, and LayeredDigraphLayout.PackMedian.*/ static PackAll: number; - /**This option gives more chances for the packing algorithm to improve the network, but is very expensive in time for large networks; a valid value for LayeredDigraphLayout#packOption.*/ + /**This option gives more chances for the packing algorithm to improve the network, but is very expensive in time for large networks; a valid value for LayeredDigraphLayout.packOption.*/ static PackExpand: number; - /**This option tries to have the packing algorithm center groups of nodes based on their relationships with nodes in other layers, a valid value for LayeredDigraphLayout#packOption.*/ + /**This option tries to have the packing algorithm center groups of nodes based on their relationships with nodes in other layers, a valid value for LayeredDigraphLayout.packOption.*/ static PackMedian: number; - /**Does minimal work in packing the nodes; a valid value for LayeredDigraphLayout#packOption.*/ + /**Does minimal work in packing the nodes; a valid value for LayeredDigraphLayout.packOption.*/ static PackNone: number; - /**This option tries to have the packing algorithm straighten many of the links that cross layers, a valid value for LayeredDigraphLayout#packOption.*/ + /**This option tries to have the packing algorithm straighten many of the links that cross layers, a valid value for LayeredDigraphLayout.packOption.*/ static PackStraighten: number; + + protected nodeMinLayerSpace(v: LayeredDigraphVertex, tl: boolean): number; // undocumented + protected nodeMinColumnSpace(v: LayeredDigraphVertex, tl: boolean): number; // undocumented } /** This holds LayeredDigraphLayout-specific information about Link s.*/ @@ -5638,16 +6280,16 @@ declare module go { /**Gets or sets the top-left point for where the graph should be positioned when laid out.*/ arrangementOrigin: Point; - /**Gets the Diagram that owns this layout, if it is the value of Diagram#layout.*/ + /**This read-only property returns the Diagram that owns this layout, if it is the value of Diagram.layout.*/ diagram: Diagram; - /**Gets the Group that uses this layout, if it is the value of a group's Group#layout.*/ + /**This read-only property returns the Group that uses this layout, if it is the value of a group's Group.layout.*/ group: Group; /**Gets or sets whether this layout is performed on an initial layout.*/ isInitial: boolean; - /**Gets or sets whether this layout can be invalidated by #invalidateLayout.*/ + /**Gets or sets whether this layout can be invalidated by .invalidateLayout.*/ isOngoing: boolean; /**Gets or sets whether this layout be performed in real-time, before the end of a transaction.*/ @@ -5659,7 +6301,7 @@ declare module go { /**Gets or sets whether this layout needs to be performed again.*/ isValidLayout: boolean; - /**Gets or sets whether this layout depends on the Diagram#viewportBounds's size.*/ + /**Gets or sets whether this layout depends on the Diagram.viewportBounds's size.*/ isViewportSized: boolean; /**Gets or sets the LayoutNetwork used by this Layout, if any.*/ @@ -5668,7 +6310,7 @@ declare module go { /** * When using a LayoutNetwork, commit changes to the diagram by setting Node positions and by routing the Links. */ - commitLayout(); + commitLayout(): void; /** * Creates a copy of this Layout and returns it. @@ -5681,30 +6323,29 @@ declare module go { createNetwork(): LayoutNetwork; /** - * Position all of the nodes that do not have an assigned Part#location in the manner of a simple rectangular array. - * @param {Diagram|Group|Iterable} coll A Diagram or a Group or a collection of Parts. + * Position all of the nodes that do not have an assigned Part.location in the manner of a simple rectangular array. + * @param {(Diagram | Group | Iterable)} coll A Diagram or a Group or a collection of Parts. */ - doLayout(coll: Diagram); - doLayout(coll: Group); - doLayout(coll: Iterable); + doLayout(coll: (Diagram | Group | Iterable)): void; /** - * If #isOngoing is true and if an initial layout has not yet been performed, set the #isValidLayout property to false, and ask to perform another layout in the near future. + * If .isOngoing is true and if an initial layout has not yet been performed, set the .isValidLayout property to false, and ask to perform another layout in the near future. */ - invalidateLayout(); + invalidateLayout(): void; /** * Create and initialize a LayoutNetwork with the given nodes and links. - * @param {Diagram|Group|Iterable} coll A Diagram or a Group or a collection of Parts. + * @param {(Diagram | Group | Iterable)} coll A Diagram or a Group or a collection of Parts. */ - makeNetwork(coll: Diagram): LayoutNetwork; - makeNetwork(coll: Group): LayoutNetwork; - makeNetwork(coll: Iterable): LayoutNetwork; + makeNetwork(coll: (Diagram | Group | Iterable)): LayoutNetwork; /** * When using a LayoutNetwork, update the "physical" node positionings and link routings. */ - updateParts(); + updateParts(): void; + + protected cloneProtected(copy: Layout): void; // undocumented + collectParts(coll: Iterable): void; // undocumented } /** @@ -5719,19 +6360,19 @@ declare module go { constructor(); /**Gets a collection of all of the LayoutEdges in this network.*/ - edges: Set; + edges: Set; - /**Gets the Layout that uses this network of LayoutVertexes and LayoutEdges.*/ + /**This read-only property returns the Layout that uses this network of LayoutVertexes and LayoutEdges.*/ layout: Layout; /**Gets a collection of all of the LayoutVertexes in this network.*/ - vertexes: Set; + vertexes: Set; /** * Adds a LayoutEdge to the network. * @param {LayoutEdge} edge */ - addEdge(edge: LayoutEdge); + addEdge(edge: LayoutEdge): void; /** * This convenience method makes sure there is a LayoutEdge in this network corresponding to a Link. @@ -5748,16 +6389,19 @@ declare module go { /** * Creates a network of LayoutVertexes and LayoutEdges corresponding to the given Nodes and Links. - * @param {Iterable} parts A collection of Nodes or Links. - * @param {boolean=} toplevelonly whether to skip Parts in the given collection that are contained by Groups. + * @param {Iterable} parts A collection of Nodes or Links. + * @param {boolean=} toplevelonly whether to skip Parts in the given collection that are contained by Groups; default is false. + * @param {function(Part):boolean|null=} pred optional predicate to apply to each Part -- + * if it returns false do not include Vertex or Edge in the network for that Part; + * default ignores link label nodes or links connecting with them */ - addParts(parts: Iterable, toplevelonly?: boolean); + addParts(parts: Iterable, toplevelonly?: boolean, pred?: (part: Part) => boolean): void; /** * Adds a LayoutVertex to the network. * @param {LayoutVertex} vertex */ - addVertex(vertex: LayoutVertex); + addVertex(vertex: LayoutVertex): void; /** * Allocate a new instance of LayoutEdge. @@ -5772,41 +6416,41 @@ declare module go { /** * Deletes all vertexes and edges that have no Part associated with them. */ - deleteArtificialVertexes(); + deleteArtificialVertexes(): void; /** * Removes a LayoutEdge from the network. * @param {LayoutEdge} edge */ - deleteEdge(edge: LayoutEdge); + deleteEdge(edge: LayoutEdge): void; /** * This convenience method deletes from this network any LayoutEdge corresponding to a Link. * @param {Link} link */ - deleteLink(link: Link); + deleteLink(link: Link): void; /** * This convenience method deletes any LayoutVertex corresponding to a Node. * @param {Node} node */ - deleteNode(node: Node); + deleteNode(node: Node): void; /** * Deletes all LayoutEdges whose "to vertex" and "from vertex" are the same vertex. */ - deleteSelfEdges(); + deleteSelfEdges(): void; /** * Removes a LayoutVertex from the network. * @param {LayoutVertex} vertex */ - deleteVertex(vertex: LayoutVertex); + deleteVertex(vertex: LayoutVertex): void; /** * Retrieve all of the Nodes and Links from the LayoutVertexes and LayoutEdges that are in this network. */ - findAllParts(): Set; + findAllParts(): Set; /** * Returns the LayoutEdge that was constructed for the Link. @@ -5832,12 +6476,12 @@ declare module go { * Reverses the direction of a LayoutEdge in the network. * @param {LayoutEdge} edge */ - reverseEdge(edge: LayoutEdge); + reverseEdge(edge: LayoutEdge): void; /** * Modify this network by splitting it up into separate subnetworks, each of which has all of its vertexes connected to each other, but not to any vertexes in any other subnetworks. */ - splitIntoSubNetworks(): List; + splitIntoSubNetworks(): List; } /** An edge represents a link in a LayoutNetwork. It holds layout-specific data for the link. */ @@ -5862,13 +6506,15 @@ declare module go { /** * Commits the route of this edge to the corresponding Link, if any. */ - commit(); + commit(): void; /** * Returns the edge's vertex at the other of this edge from the given vertex. * @param {LayoutVertex} v */ - getOtherVertex(v: LayoutVertex); + getOtherVertex(v: LayoutVertex): void; + + data: any; // undocumented } /** A vertex represents a node in a LayoutNetwork. It holds layout-specific data for the node. */ @@ -5888,18 +6534,18 @@ declare module go { centerY: number; /**Gets an iterator for all of the edges that go out of this vertex.*/ - destinationEdges: Iterator; + destinationEdges: Iterator; /**Gets an iterator for all of the vertexes that are connected with edges going out of this vertex.*/ - destinationVertexes: Iterator; + destinationVertexes: Iterator; /**Gets an iterator for all of the edges that are connected with this vertex in either direction.*/ - edges: Iterator; + edges: Iterator; - /**Gets the total number of edges that are connected with this vertex in either direction.*/ + /**This read-only property returns the total number of edges that are connected with this vertex in either direction.*/ edgesCount: number; - /**Gets or sets the offset of the #centerX and #centerY from the #bounds position.*/ + /**Gets or sets the offset of the .centerX and .centerY from the .bounds position.*/ focus: Point; /**Gets or sets the relative X position of the "center" point, the focus.*/ @@ -5918,13 +6564,13 @@ declare module go { node: Node; /**Gets an iterator for all of the edges that come into this vertex.*/ - sourceEdges: Iterator; + sourceEdges: Iterator; /**Gets an iterator for all of the vertexes that are connected with edges coming into this vertex.*/ - sourceVertexes: Iterator; + sourceVertexes: Iterator; /**Gets an iterator for all of the vertexes that are connected in either direction with this vertex.*/ - vertexes: Iterator; + vertexes: Iterator; /**Gets or sets the width of this vertex.*/ width: number; @@ -5939,44 +6585,46 @@ declare module go { * Adds a LayoutEdge to the list of successors (the edge will be going out from this vertex). * @param {LayoutEdge} edge */ - addDestinationEdge(edge: LayoutEdge); + addDestinationEdge(edge: LayoutEdge): void; /** * Adds a LayoutEdge to the list of predecessors (the edge will be coming into this vertex). * @param {LayoutEdge} edge */ - addSourceEdge(edge: LayoutEdge); + addSourceEdge(edge: LayoutEdge): void; /** - * Moves the Node corresponding to this vertex so that its position is at the current #bounds point. + * Moves the Node corresponding to this vertex so that its position is at the current .bounds point. */ - commit(); + commit(): void; /** * Deletes a LayoutEdge from the list of successors (the edge was going out from this vertex). * @param {LayoutEdge} edge */ - deleteDestinationEdge(edge: LayoutEdge); + deleteDestinationEdge(edge: LayoutEdge): void; /** * Deletes a LayoutEdge from the list of predecessors (the edge was coming into this vertex). * @param {LayoutEdge} edge */ - deleteSourceEdge(edge: LayoutEdge); + deleteSourceEdge(edge: LayoutEdge): void; /** - * This static method is used to compare the Part#text values of the #nodes of the argument LayoutVertexes. + * This static function is used to compare the Part.text values of the .nodes of the argument LayoutVertexes. * @param {LayoutVertex} m * @param {LayoutVertex} n */ static smartComparer(m: LayoutVertex, n: LayoutVertex): number; /** - * This static method is used to compare the Part#text values of the #nodes of the argument LayoutVertexes. + * This static function is used to compare the Part.text values of the .nodes of the argument LayoutVertexes. * @param {LayoutVertex} m * @param {LayoutVertex} n */ static standardComparer(m: LayoutVertex, n: LayoutVertex): number; + + data: any; // undocumented } /** @@ -5984,7 +6632,7 @@ declare module go { */ class TreeLayout extends Layout { /** - * Constructs a TreeLayout with no Layout#network and with no owning Layout#diagram. + * Constructs a TreeLayout with no Layout.network and with no owning Layout.diagram. */ constructor(); @@ -6000,7 +6648,7 @@ declare module go { /**Gets or sets a limit on how broad a tree should be.*/ alternateBreadthLimit: number; - /**Gets or sets the spot that children nodes' ports get as their ToSpot The default value is Spot#Default.*/ + /**Gets or sets the spot that children nodes' ports get as their ToSpot The default value is Spot.Default.*/ alternateChildPortSpot: Spot; /**Gets or sets the distance between a node and its comments.*/ @@ -6013,9 +6661,9 @@ declare module go { alternateCompaction: EnumValue; /**Gets or sets the default comparison function used for sorting.*/ - alternateComparer: (a:TreeVertex, b:TreeVertex) => number; + alternateComparer: (a: TreeVertex, b: TreeVertex) => number; - /**Gets or sets the object holding the default values for alternate layer TreeVertexes, used when the #treeStyle is #StyleAlternating or #StyleLastParents.*/ + /**Gets or sets the object holding the default values for alternate layer TreeVertexes, used when the .treeStyle is .StyleAlternating or .StyleLastParents.*/ alternateDefaults: TreeVertex; /**Gets or sets the distance between a parent node and its children.*/ @@ -6027,7 +6675,7 @@ declare module go { /**Gets or sets the default indentation of the first child.*/ alternateNodeIndent: number; - /**Gets or sets the fraction of this node's breadth is added to #nodeIndent to determine any spacing at the start of the children.*/ + /**Gets or sets the fraction of this node's breadth is added to .nodeIndent to determine any spacing at the start of the children.*/ alternateNodeIndentPastParent: number; /**Gets or sets the distance between child nodes.*/ @@ -6036,7 +6684,7 @@ declare module go { /**Gets or sets the spot that this node's port gets as its FromSpot.*/ alternatePortSpot: Spot; - /**Gets or sets the default indentation of the first child of each row, if the #alignment is not a "Center" alignment.*/ + /**Gets or sets the default indentation of the first child of each row, if the .alignment is not a "Center" alignment.*/ alternateRowIndent: number; /**Gets or sets the distance between rows of children.*/ @@ -6054,10 +6702,10 @@ declare module go { /**Gets or sets the default direction for tree growth.*/ angle: number; - /**Gets or sets how #arrangeTrees should lay out the separate trees.*/ + /**Gets or sets how .arrangeTrees should lay out the separate trees.*/ arrangement: EnumValue; - /**Gets or sets the space between which #arrangeTrees will position the trees.*/ + /**Gets or sets the space between which .arrangeTrees will position the trees.*/ arrangementSpacing: Size; /**Gets or sets a limit on how broad a tree should be.*/ @@ -6075,8 +6723,11 @@ declare module go { /**Gets or sets how closely to pack the child nodes of a subtree.*/ compaction: EnumValue; + /**Gets or sets whether to call .addComments.*/ + comments: boolean; + /**Gets or sets the default comparison function used for sorting.*/ - comparer: (a:TreeVertex, b:TreeVertex) => number; + comparer: (a: TreeVertex, b: TreeVertex) => number; /**Gets or sets the distance between a parent node and its children.*/ layerSpacing: number; @@ -6084,10 +6735,13 @@ declare module go { /**Gets or sets the fraction of the node's depth for which the children's layer starts overlapped with the parent's layer.*/ layerSpacingParentOverlap: number; + /**Gets or sets the manner in which the nodes are aligned in layers.*/ + layerStyle: EnumValue; + /**Gets or sets the default indentation of the first child.*/ nodeIndent: number; - /**Gets or sets the fraction of this node's breadth is added to #nodeIndent to determine any spacing at the start of the children.*/ + /**Gets or sets the fraction of this node's breadth is added to .nodeIndent to determine any spacing at the start of the children.*/ nodeIndentPastParent: number; /**Gets or sets the distance between child nodes.*/ @@ -6103,9 +6757,9 @@ declare module go { rootDefaults: TreeVertex; /**Gets or sets the collection of root vertexes.*/ - roots: Set; + roots: Set; - /**Gets or sets the default indentation of the first child of each row, if the #alignment is not a "Center" alignment.*/ + /**Gets or sets the default indentation of the first child of each row, if the .alignment is not a "Center" alignment.*/ rowIndent: number; /**Gets or sets the distance between rows of children.*/ @@ -6127,33 +6781,41 @@ declare module go { * Find associated objects to be positioned along with the TreeVertex. * @param {LayoutVertex} v */ - addComments(v: LayoutVertex); + addComments(v: LayoutVertex): void; /** * Position each separate tree. */ - arrangeTrees(); + arrangeTrees(): void; /** * Assign final property values for a TreeVertex. * @param {LayoutVertex} v */ - assignTreeVertexValues(v: LayoutVertex); + assignTreeVertexValues(v: LayoutVertex): void; + + /** + * This overridable method is called by commitLayout if layerStyle is LayerUniform + * to support custom arrangement of bands or labels across each layout layer. + * @param Array<*> layerRects an Array of Rects with the bounds of each of the "layers" + * @param {Point} offset the position of the top-left corner of the banded area relative to the coordinates given by the layerRects + */ + commitLayers(layerRects: Array, offset: Point): void; /** * Set the fromSpot and toSpot for each Vertex, position each Node according to the Vertex position, and then position the Links. */ - commitLayout(); + commitLayout(): void; /** * Commit the position and routing of all edge links. */ - commitLinks(); + commitLinks(): void; /** * Commit the position of all vertex nodes. */ - commitNodes(); + commitNodes(): void; /** * Create a new LayoutNetwork of TreeVertexes and TreeEdges. @@ -6162,94 +6824,101 @@ declare module go { /** * Assign the positions of the vertexes in the network. - * @param {Diagram|Group|Iterable} coll A Diagram or a Group or a collection of Parts. + * @param {(Diagram | Group | Iterable)} coll A Diagram or a Group or a collection of Parts. */ - doLayout(coll: Diagram); - doLayout(coll: Group); - doLayout(coll: Iterable); + doLayout(coll: (Diagram | Group | Iterable)): void; /** * Assign initial property values for a TreeVertex. * @param {LayoutVertex} v */ - initializeTreeVertexValues(v: LayoutVertex); + initializeTreeVertexValues(v: LayoutVertex): void; /** - * Position and TreeVertex#comments around the vertex. + * Position and TreeVertex.comments around the vertex. * @param {LayoutVertex} v */ - layoutComments(v: LayoutVertex); + layoutComments(v: LayoutVertex): void; - /**The children are positioned in a bus, only on the bottom or right side of the parent; This value is used for TreeLayout#alignment or TreeLayout#alternateAlignment.*/ + /**The children are positioned in a bus, only on the bottom or right side of the parent; This value is used for TreeLayout.alignment or TreeLayout.alternateAlignment.*/ static AlignmentBottomRightBus: EnumValue; /**The children are positioned in a bus on both sides of an "aisle" where the links to them go, with the last odd child (if any) placed at the end of the aisle in the middle.*/ static AlignmentBus: EnumValue; - /**Like TreeLayout#AlignmentBus with the children arranged on both sides of an "aisle" with any last odd child placed at the end of the aisle, but the children get an TreeVertex#angle that depends on which side of the aisle they were placed.*/ + /**Like TreeLayout.AlignmentBus with the children arranged on both sides of an "aisle" with any last odd child placed at the end of the aisle, but the children get an TreeVertex.angle that depends on which side of the aisle they were placed.*/ static AlignmentBusBranching: EnumValue; - /**The parent is centered at the middle of the range of its immediate child nodes; This value is used for TreeLayout#alignment or TreeLayout#alternateAlignment.*/ + /**The parent is centered at the middle of the range of its immediate child nodes; This value is used for TreeLayout.alignment or TreeLayout.alternateAlignment.*/ static AlignmentCenterChildren: EnumValue; - /**The parent is centered at the middle of the range of its child subtrees; This value is used for TreeLayout#alignment or TreeLayout#alternateAlignment.*/ + /**The parent is centered at the middle of the range of its child subtrees; This value is used for TreeLayout.alignment or TreeLayout.alternateAlignment.*/ static AlignmentCenterSubtrees: EnumValue; - /**The parent is positioned near the last of its children; This value is used for TreeLayout#alignment or TreeLayout#alternateAlignment.*/ + /**The parent is positioned near the last of its children; This value is used for TreeLayout.alignment or TreeLayout.alternateAlignment.*/ static AlignmentEnd: EnumValue; - /**The parent is positioned near the first of its children; This value is used for TreeLayout#alignment or TreeLayout#alternateAlignment.*/ + /**The parent is positioned near the first of its children; This value is used for TreeLayout.alignment or TreeLayout.alternateAlignment.*/ static AlignmentStart: EnumValue; - /**The children are positioned in a bus, only on the top or left side of the parent; This value is used for TreeLayout#alignment or TreeLayout#alternateAlignment.*/ + /**The children are positioned in a bus, only on the top or left side of the parent; This value is used for TreeLayout.alignment or TreeLayout.alternateAlignment.*/ static AlignmentTopLeftBus: EnumValue; - /**Do not move each root node, but position all of their descendants relative to their root; This value is used for TreeLayout#arrangement.*/ + /**Do not move each root node, but position all of their descendants relative to their root; This value is used for TreeLayout.arrangement.*/ static ArrangementFixedRoots: EnumValue; - /**Position each tree in a non-overlapping fashion by increasing X coordinates, starting at the Layout#arrangementOrigin; This value is used for TreeLayout#arrangement.*/ + /**Position each tree in a non-overlapping fashion by increasing X coordinates, starting at the Layout.arrangementOrigin; This value is used for TreeLayout.arrangement.*/ static ArrangementHorizontal: EnumValue; - /**Position each tree in a non-overlapping fashion by increasing Y coordinates, starting at the Layout#arrangementOrigin; This value is used for TreeLayout#arrangement.*/ + /**Position each tree in a non-overlapping fashion by increasing Y coordinates, starting at the Layout.arrangementOrigin; This value is used for TreeLayout.arrangement.*/ static ArrangementVertical: EnumValue; - /**A simple fitting of subtrees; This value is used for TreeLayout#compaction or TreeLayout#alternateCompaction.*/ + /**A simple fitting of subtrees; This value is used for TreeLayout.compaction or TreeLayout.alternateCompaction.*/ static CompactionBlock: EnumValue; - /**Only simple placement of children next to each other, as determined by their subtree breadth; This value is used for TreeLayout#compaction or TreeLayout#alternateCompaction.*/ + /**Only simple placement of children next to each other, as determined by their subtree breadth; This value is used for TreeLayout.compaction or TreeLayout.alternateCompaction.*/ static CompactionNone: EnumValue; - /**This value for TreeLayout#path causes the value of Diagram#isTreePathToChildren to effectively choose either TreeLayout#PathDestination (if true) or TreeLayout#PathSource (if false).*/ + /**This default value for TreeLayout.layerStyle causes each node takes up only the depth that it needs.*/ + static LayerIndividual: EnumValue; + + /**This value for TreeLayout.layerStyle causes all of the children of a parent node take up the same amount of depth -- this typically causes all cousins to be aligned.*/ + static LayerSiblings: EnumValue; + + /**This value for TreeLayout.layerStyle causes all nodes with the same TreeVertex.level throughout the tree take up the same amount of depth.*/ + static LayerUniform: EnumValue; + + /**This value for TreeLayout.path causes the value of Diagram.isTreePathToChildren to effectively choose either TreeLayout.PathDestination (if true) or TreeLayout.PathSource (if false).*/ static PathDefault: EnumValue; - /**The children of a TreeVertex are its LayoutVertex#destinationVertexes, the collection of connected LayoutEdge#toVertexes; This value is used for TreeLayout#path.*/ + /**The children of a TreeVertex are its LayoutVertex.destinationVertexes, the collection of connected LayoutEdge.toVertexes; This value is used for TreeLayout.path.*/ static PathDestination: EnumValue; - /**The children of a TreeVertex are its LayoutVertex#sourceVertexes, the collection of connected LayoutEdge#fromVertexes; This value is used for TreeLayout#path.*/ + /**The children of a TreeVertex are its LayoutVertex.sourceVertexes, the collection of connected LayoutEdge.fromVertexes; This value is used for TreeLayout.path.*/ static PathSource: EnumValue; - /**Lay out each child according to the sort order given by TreeVertex#comparer; This value is used for TreeLayout#sorting or TreeLayout#alternateSorting.*/ + /**Lay out each child according to the sort order given by TreeVertex.comparer; This value is used for TreeLayout.sorting or TreeLayout.alternateSorting.*/ static SortingAscending: EnumValue; - /**Lay out each child in reverse sort order given by TreeVertex#comparer; This value is used for TreeLayout#sorting or TreeLayout#alternateSorting.*/ + /**Lay out each child in reverse sort order given by TreeVertex.comparer; This value is used for TreeLayout.sorting or TreeLayout.alternateSorting.*/ static SortingDescending: EnumValue; - /**Lay out each child in the order in which they were found; This value is used for TreeLayout#sorting or TreeLayout#alternateSorting.*/ + /**Lay out each child in the order in which they were found; This value is used for TreeLayout.sorting or TreeLayout.alternateSorting.*/ static SortingForwards: EnumValue; - /**Lay out each child in reverse order from which they were found; This value is used for TreeLayout#sorting or TreeLayout#alternateSorting.*/ + /**Lay out each child in reverse order from which they were found; This value is used for TreeLayout.sorting or TreeLayout.alternateSorting.*/ static SortingReverse: EnumValue; - /**Alternate layers of the tree have different properties, typically including the angle; This value is used for TreeLayout#treeStyle.*/ + /**Alternate layers of the tree have different properties, typically including the angle; This value is used for TreeLayout.treeStyle.*/ static StyleAlternating: EnumValue; - /**Just like the standard layered tree style, except that the nodes with children but no grandchildren have alternate properties; This value is used for TreeLayout#treeStyle.*/ + /**Just like the standard layered tree style, except that the nodes with children but no grandchildren have alternate properties; This value is used for TreeLayout.treeStyle.*/ static StyleLastParents: EnumValue; - /**The normal tree style, where all of the children of each TreeVertex are lined up horizontally or vertically; This value is used for TreeLayout#treeStyle.*/ + /**The normal tree style, where all of the children of each TreeVertex are lined up horizontally or vertically; This value is used for TreeLayout.treeStyle.*/ static StyleLayered: EnumValue; - /**All of the nodes get the alternate properties, except the root node gets the default properties; This value is used for TreeLayout#treeStyle.*/ + /**All of the nodes get the alternate properties, except the root node gets the default properties; This value is used for TreeLayout.treeStyle.*/ static StyleRootOnly: EnumValue; } @@ -6263,7 +6932,7 @@ declare module go { /** * Commits the position of the Link and routes it. */ - commit(); + commit(): void; } /** This holds TreeLayout-specific information about Nodes.*/ @@ -6279,20 +6948,20 @@ declare module go { /**Gets or sets how broad a node and its descendants should be.*/ breadthLimit: number; - /**Gets or sets the spot that children nodes' ports get as their ToSpot, if #setsChildPortSpot is true and the node has only a single port.*/ + /**Gets or sets the spot that children nodes' ports get as their ToSpot, if .setsChildPortSpot is true and the node has only a single port.*/ childPortSpot: Spot; /**Gets or sets the logical children for this node.*/ - children: any[]; + children: Array; - /**Gets the number of immediate children this node has.*/ + /**This read-only property returns the number of immediate children this node has.*/ childrenCount: number; /**Gets or sets the space to leave between the node and the comments.*/ commentMargin: number; /**Gets or sets an array of Nodes that will be positioned near this node.*/ - comments: any[]; + comments: Array; /**Gets or sets the space to leave between consecutive comments.*/ commentSpacing: number; @@ -6306,7 +6975,7 @@ declare module go { /**Gets or sets the number of descendants this node has.*/ descendantCount: number; - /**Gets or sets whether this node has been initialized as part of TreeLayout#doLayout when building the tree structures.*/ + /**Gets or sets whether this node has been initialized as part of TreeLayout.doLayout when building the tree structures.*/ initialized: boolean; /**Gets or sets the distance between this node and its children.*/ @@ -6336,7 +7005,7 @@ declare module go { /**Gets or sets the logical parent for this node.*/ parent: TreeVertex; - /**Gets or sets the spot that this node's port gets as its FromSpot, if #setsPortSpot is true and the node has only a single port.*/ + /**Gets or sets the spot that this node's port gets as its FromSpot, if .setsPortSpot is true and the node has only a single port.*/ portSpot: Spot; /**Gets or sets the position of this node relative to its parent node.*/ @@ -6367,56 +7036,56 @@ declare module go { * Copy inherited properties from another TreeVertex to this one. * @param {TreeVertex} copy */ - copyInheritedPropertiesFrom(copy: TreeVertex); + copyInheritedPropertiesFrom(copy: TreeVertex): void; } /** * The ActionTool is responsible for handling and dispatching mouse events on GraphObjects - * that have GraphObject#isActionable set to true. + * that have GraphObject.isActionable set to true. * This is how one implements "controls", such as buttons or sliders or knobs, as GraphObjects * that can be inside Parts without interfering with the standard tool behaviors. */ class ActionTool extends Tool { /** - * You do not normally need to create an instance of this tool because one already exists as the ToolManager#actionTool. + * You do not normally need to create an instance of this tool because one already exists as the ToolManager.actionTool. */ constructor(); /** - * This tool can run when there is a mouse-down on an object with GraphObject#isActionable true or if the object is within a Panel that "isActionable". + * This tool can run when there is a mouse-down on an object with GraphObject.isActionable true or if the object is within a Panel that "isActionable". */ canStart(): boolean; /** - * Call the GraphObject#actionCancel event if defined on the current object. + * Call the GraphObject.actionCancel event if defined on the current object. */ - doCancel(); + doCancel(): void; /** - * If there is a GraphObject found with GraphObject#isActionable set to true, call that object's GraphObject#actionDown event, if it exists. + * If there is a GraphObject found with GraphObject.isActionable set to true, call that object's GraphObject.actionDown event, if it exists. */ - doMouseDown(); + doMouseDown(): void; /** - * If this tool is active call GraphObject#actionMove, if it exists, on the active object. + * If this tool is active call GraphObject.actionMove, if it exists, on the active object. */ - doMouseMove(); + doMouseMove(): void; /** - * Calls the GraphObject#actionUp event if defined, then effectively calls Tool#standardMouseClick to perform the normal click behaviors, and then stops this tool. + * Calls the GraphObject.actionUp event if defined, then effectively calls Tool.standardMouseClick to perform the normal click behaviors, and then stops this tool. */ - doMouseUp(); + doMouseUp(): void; } /** * The ClickCreatingTool lets the user create a node by clicking where they want the new node to be. * By default a double-click is required to start this tool; - * set #isDoubleClick to false if you want a single-click to create a node. + * set .isDoubleClick to false if you want a single-click to create a node. */ class ClickCreatingTool extends Tool { /** - * You do not normally need to create an instance of this tool because one already exists as the ToolManager#clickCreatingTool, which you can modify. + * You do not normally need to create an instance of this tool because one already exists as the ToolManager.clickCreatingTool, which you can modify. */ constructor(); @@ -6427,17 +7096,17 @@ declare module go { isDoubleClick: boolean; /** - * This tool can run when the diagram is not read-only and supports creating new nodes, and when there has been a click (or double-click if #isDoubleClick is true) in the background of the diagram (not on a Part), and #archetypeNodeData is an object that can be copied and added to the model. + * This tool can run when the diagram is not read-only and supports creating new nodes, and when there has been a click (or double-click if .isDoubleClick is true) in the background of the diagram (not on a Part), and .archetypeNodeData is an object that can be copied and added to the model. */ canStart(): boolean; /** - * Upon a click, call #insertPart and stop this tool. + * Upon a click, call .insertPart and stop this tool. */ - doMouseUp(); + doMouseUp(): void; /** - * Create a node by adding a copy of the #archetypeNodeData object to the diagram's model, assign its Part#location to be the given point, and select the new part. + * Create a node by adding a copy of the .archetypeNodeData object to the diagram's model, assign its Part.location to be the given point, and select the new part. * @param {Point} loc a Point in document coordinates. */ insertPart(loc: Point): Part; @@ -6445,13 +7114,13 @@ declare module go { /** * The ClickSelectingTool selects and deselects Parts when there is a click. - * It does this by calling Tool#standardMouseSelect. + * It does this by calling Tool.standardMouseSelect. * It is also responsible for handling and dispatching click events on GraphObjects - * by calling Tool#standardMouseClick. + * by calling Tool.standardMouseClick. */ class ClickSelectingTool extends Tool { /** - * You do not normally need to create an instance of this tool because one already exists as the ToolManager#clickSelectingTool. + * You do not normally need to create an instance of this tool because one already exists as the ToolManager.clickSelectingTool. */ constructor(); @@ -6461,9 +7130,9 @@ declare module go { canStart(): boolean; /** - * Upon a click, this calls Tool#standardMouseSelect to change the Diagram#selection collection, then calls Tool#standardMouseClick to perform the normal click behaviors, and then stops this tool. + * Upon a click, this calls Tool.standardMouseSelect to change the Diagram.selection collection, then calls Tool.standardMouseClick to perform the normal click behaviors, and then stops this tool. */ - doMouseUp(); + doMouseUp(): void; } /** @@ -6472,150 +7141,169 @@ declare module go { */ class ContextMenuTool extends Tool { /** - * You do not normally need to create an instance of this tool because one already exists as the ToolManager#contextMenuTool, which you can modify. + * You do not normally need to create an instance of this tool because one already exists as the ToolManager.contextMenuTool, which you can modify. */ constructor(); - /**Gets the currently showing context menu, or null if there is none.*/ + /**Gets or sets the currently showing context menu, or null if there is none.*/ currentContextMenu: Adornment; - /**Gets the original mouse-down point in document coordinates.*/ + /**Gets or sets the GraphObject found at the mouse point that has a context menu.*/ + currentObject: GraphObject; + + /**This read-only property returns the original mouse-down point in document coordinates.*/ mouseDownPoint: Point; /** - * Return true if it's a mouse right click that hasn't moved Tool#isBeyondDragSize and that is on a GraphObject with a GraphObject#contextMenu. + * Return true if it's a mouse right click that hasn't moved Tool.isBeyondDragSize and that is on a GraphObject with a GraphObject.contextMenu. */ canStart(): boolean; /** * Do nothing, activation is special and relies on doMouseUp */ - doActivate(); + doActivate(): void; /** * Handle mouse-enter, mouse-over, and mouse-leave events. */ - doMouseMove(); + doMouseMove(): void; /** - * If there is something found by #findObjectWithContextMenu, call #showContextMenu with that object's GraphObject#contextMenu or Diagram#contextMenu. + * If there is something found by .findObjectWithContextMenu, call .showContextMenu with that object's GraphObject.contextMenu or Diagram.contextMenu. */ - doMouseUp(); + doMouseUp(): void; /** - * Find a GraphObject at the current mouse point with a GraphObject#contextMenu, or return the Diagram if there is a Diagram#contextMenu. + * Find a GraphObject at the current mouse point with a GraphObject.contextMenu, or return the Diagram if there is a Diagram.contextMenu. */ - findObjectWithContextMenu(): any; + findObjectWithContextMenu(): GraphObject | Diagram; /** * Hide any context menu. */ - hideContextMenu(); + hideContextMenu(): void; /** * Hide the default context menu. */ - hideDefaultContextMenu(); + hideDefaultContextMenu(): void; /** - * This is called by #showContextMenu to position the context menu within the viewport. + * This is called by .showContextMenu to position the context menu within the viewport. * @param {Adornment} contextmenu * @param {GraphObject} obj */ - positionContextMenu(contextmenu: Adornment, obj: GraphObject); + positionContextMenu(contextmenu: Adornment, obj: GraphObject): void; /** * Show an Adornment as a context menu. * @param {Adornment} contextmenu * @param {GraphObject} obj */ - showContextMenu(contextmenu: Adornment, obj: GraphObject); + showContextMenu(contextmenu: Adornment, obj: GraphObject): void; /** * Show a series of HTML elements acting as a context menu. */ - showDefaultContextMenu(); + showDefaultContextMenu(): void; + } + + /** + * This helper structure for DraggingTool holds the original location Point. + */ + interface DraggingInfo { // undocumented + point: Point } /** * The DraggingTool is used to move or copy selected parts with the mouse. - * Dragging the selection moves parts for which Part#canMove is true. + * Dragging the selection moves parts for which Part.canMove is true. * If the user holds down the Control key, this tool will make a copy of the parts being dragged, - * for those parts for which Part#canCopy is true. + * for those parts for which Part.canCopy is true. */ class DraggingTool extends Tool { /** - * You do not normally need to create an instance of this tool because one already exists as the ToolManager#draggingTool, which you can modify. + * You do not normally need to create an instance of this tool because one already exists as the ToolManager.draggingTool, which you can modify. */ constructor(); - /**Gets the collection of Parts that this tool has copied.*/ - copiedParts: Map; + /**This read-only property returns the collection of Parts that this tool has copied.*/ + copiedParts: Map; /**Gets or sets whether for a copying operation the extended selection is copied or only the selected parts.*/ copiesEffectiveCollection: boolean; - /**Gets the Part found at the mouse point.*/ + /**This read-only property returns the Part found at the mouse point.*/ currentPart: Part; /**On touch gestures only, this property gets or sets the time in milliseconds for which the mouse must be stationary before this tool can be started.*/ delay: number; - /**Gets the collection of Parts being dragged.*/ - draggedParts: Map; + /**This read-only property returns the collection of Parts being dragged.*/ + draggedParts: Map; + + /**Gets or sets whether the user can drag a single Link, disconnecting it from its connected nodes and possibly connecting it to valid ports when the link is dropped.*/ + dragsLink: boolean; /**Gets or sets whether moving or copying a node also includes all of the node's tree children and their descendants, along with the links to those additional nodes.*/ dragsTree: boolean; - /**Gets or sets the size of the grid cell used when snapping during a drag if the value of #isGridSnapEnabled is true.*/ + /**Gets or sets the size of the grid cell used when snapping during a drag if the value of .isGridSnapEnabled is true.*/ gridSnapCellSize: Size; - /**Gets or sets the Spot that specifies what point in the grid cell dragged parts snap to, if the value of #isGridSnapEnabled is true.*/ + /**Gets or sets the Spot that specifies what point in the grid cell dragged parts snap to, if the value of .isGridSnapEnabled is true.*/ gridSnapCellSpot: Spot; - /**Gets or sets the snapping grid's origin point, in document coordinates, if the value of #isGridSnapEnabled is true.*/ + /**Gets or sets the snapping grid's origin point, in document coordinates, if the value of .isGridSnapEnabled is true.*/ gridSnapOrigin: Point; + /**Gets or sets whether for any internal copying operation is permitted by control-drag-and-drop.*/ + isCopyEnabled: boolean; + /**Gets or sets whether the DraggingTool snaps objects to grid points.*/ isGridSnapEnabled: boolean; /**Gets or sets whether the DraggingTool snaps objects to grid points during the drag.*/ isGridSnapRealtime: boolean; + /**Gets or sets the mouse point from which parts start to move.*/ + startPoint: Point; + /** - * This tool can run if the diagram allows selection and moves/copies/dragging-out, if the mouse has moved far enough away to be a drag and not a click, and if #findDraggablePart has found a selectable part at the mouse-down point. + * This tool can run if the diagram allows selection and moves/copies/dragging-out, if the mouse has moved far enough away to be a drag and not a click, and if .findDraggablePart has found a selectable part at the mouse-down point. */ canStart(): boolean; /** * Find the actual collection of nodes and links to be moved or copied, given an initial collection. - * @param {Iterable} parts A Set or List of Parts. + * @param {Iterable} parts A Set or List of Parts. */ - computeEffectiveCollection(parts: Iterable): Map; + computeEffectiveCollection(parts: Iterable): Map; /** - * This method computes the new location for a Node or simple Part, given a new desired location and an optional Map of dragged parts, taking any grid-snapping into consideration, any Part#dragComputation function, and any Part#minLocation and Part#maxLocation. + * This method computes the new location for a Node or simple Part, given a new desired location and an optional Map of dragged parts, taking any grid-snapping into consideration, any Part.dragComputation function, and any Part.minLocation and Part.maxLocation. * @param {Part} n * @param {Point} newloc * @param {Map=} draggedparts an optional Map mapping Parts to JavaScript Objects that have a "point" property remembering the original location of that Part. * @param {Point=} result an optional Point that is modified and returned */ - computeMove(n: Part, newloc: Point, draggedparts?: Map, result?: Point): Point; + computeMove(n: Part, newloc: Point, draggedparts?: Map, result?: Point): Point; /** * Start the dragging operation. */ - doActivate(); + doActivate(): void; /** * Abort any dragging operation. */ - doCancel(); + doCancel(): void; /** * Stop the dragging operation by stopping the transaction and cleaning up any temporary state. */ - doDeactivate(); + doDeactivate(): void; /** * Perform any additional side-effects during a drag, whether an internal move or copy or an external drag, that may affect the existing non-moved object(s). @@ -6623,10 +7311,10 @@ declare module go { * @param {GraphObject} obj the GraphObject at the point, * excluding what is being dragged or temporary objects; * the argument may be null if the drag is occurring in the background of the diagram. - * Use GraphObject#part to get the Node or Part at the root of + * Use GraphObject.part to get the Node or Part at the root of * the visual tree of the stationary object. */ - doDragOver(pt: Point, obj: GraphObject); + doDragOver(pt: Point, obj: GraphObject): void; /** * Perform any additional side-effects after a drop, whether an internal move or copy or an external drop, that may affect the existing non-moved object(s). @@ -6634,30 +7322,30 @@ declare module go { * @param {GraphObject} obj the GraphObject where the drop occurred, * excluding what was dropped or temporary objects; * the argument may be null if the drop occurred in the background of the diagram. - * Use GraphObject#part to get the Node or Part at the root of + * Use GraphObject.part to get the Node or Part at the root of * the visual tree of the stationary object. */ - doDropOnto(pt: Point, obj: GraphObject); + doDropOnto(pt: Point, obj: GraphObject): void; /** * Handle switching between copying and moving modes as the Control key is pressed or released. */ - doKeyDown(); + doKeyDown(): void; /** * Handle switching between copying and moving modes as the Control key is pressed or released. */ - doKeyUp(); + doKeyUp(): void; /** - * Move the #draggedParts (or if copying, the #copiedParts) to follow the current mouse point. + * Move the .draggedParts (or if copying, the .copiedParts) to follow the current mouse point. */ - doMouseMove(); + doMouseMove(): void; /** * On a mouse-up finish moving or copying the effective selection. */ - doMouseUp(); + doMouseUp(): void; /** * Return the selectable and movable/copyable Part at the mouse-down point. @@ -6678,41 +7366,41 @@ declare module go { Move a collection of Parts by a given offset. * @param {Map} parts a Map mapping Parts to JavaScript Objects that have a "point" property remembering the original location of that Part. * @param {Point} offset - * @param {boolean} check Whether to check Part#canMove on each part. + * @param {boolean} check Whether to check Part.canMove on each part. */ - moveParts(parts: Map, offset: Point, check: boolean); + moveParts(parts: Map, offset: Point, check: boolean): void; /** * This override prevents the Control modifier unselecting an already selected part. */ - standardMouseSelect(); + standardMouseSelect(): void; } /** * The DragSelectingTool lets the user select multiple parts with a rectangular area. - * There is a temporary part, the #box, + * There is a temporary part, the .box, * that shows the current area encompassed between the mouse-down * point and the current mouse point. - * The default drag selection box is a magenta rectangle. - * You can change the #box to customize its appearance -- see its documentation for an example. + * The default drag selection box is a blue rectangle. + * You can change the .box to customize its appearance -- see its documentation for an example. */ class DragSelectingTool extends Tool { /** - * You do not normally need to create an instance of this tool because one already exists as the ToolManager#dragSelectingTool, which you can modify. + * You do not normally need to create an instance of this tool because one already exists as the ToolManager.dragSelectingTool, which you can modify. */ constructor(); - /**Gets or sets the Part used as the "rubber-band selection box" that is stretched to follow the mouse, as feedback for what area will be passed to #selectInRect upon a mouse-up.*/ + /**Gets or sets the Part used as the "rubber-band selection box" that is stretched to follow the mouse, as feedback for what area will be passed to .selectInRect upon a mouse-up.*/ box: Part; /**Gets or sets the time in milliseconds for which the mouse must be stationary before this tool can be started.*/ delay: number; - /**Gets or sets whether a selectable Part may be only partly or must be completely enclosed by the rectangle given to #selectInRect.*/ + /**Gets or sets whether a selectable Part may be only partly or must be completely enclosed by the rectangle given to .selectInRect.*/ isPartialInclusion: boolean; /** - * This tool can run when the diagram allows selection, there has been delay of at least #delay milliseconds after the mouse-down before a mouse-move, there has been a mouse-drag far enough away not to be a click, and there is no selectable part at the mouse-down point. + * This tool can run when the diagram allows selection, there has been delay of at least .delay milliseconds after the mouse-down before a mouse-move, there has been a mouse-drag far enough away not to be a click, and there is no selectable part at the mouse-down point. */ canStart(): boolean; @@ -6722,30 +7410,30 @@ declare module go { computeBoxBounds(): Rect; /** - * Capture the mouse and show the #box. + * Capture the mouse and show the .box. */ - doActivate(); + doActivate(): void; /** - * Release the mouse and remove any #box. + * Release the mouse and remove any .box. */ - doDeactivate(); + doDeactivate(): void; /** - * Update the #box's position and size according to the value of #computeBoxBounds. + * Update the .box's position and size according to the value of .computeBoxBounds. */ - doMouseMove(); + doMouseMove(): void; /** - * Call #selectInRect with the value of a call to #computeBoxBounds. + * Call .selectInRect with the value of a call to .computeBoxBounds. */ - doMouseUp(); + doMouseUp(): void; /** * This method is called to select some parts within the area of a given rectangle. *@param {Rect} r */ - selectInRect(r: Rect); + selectInRect(r: Rect): void; } /** @@ -6760,22 +7448,25 @@ declare module go { /**Gets whether the linking operation is in the forwards direction, connecting from the "From" port to the "To" port.*/ isForwards: boolean; + /**Gets or sets whether it is valid to have partly or completely unconnected links.*/ + isUnconnectedLinkValid: boolean; + /**Gets or sets a predicate that determines whether or not a new link between two ports would be valid.*/ linkValidation: (fromNode: Node, fromPort: GraphObject, toNode: Node, toPort: GraphObject, link: Link) => boolean; - /**Gets or sets the original Node from which the new link is being drawn or from which the #originalLink was connected when being relinked.*/ + /**Gets or sets the original Node from which the new link is being drawn or from which the .originalLink was connected when being relinked.*/ originalFromNode: Node; - /**Gets or sets the GraphObject that is the port in the #originalFromNode.*/ + /**Gets or sets the GraphObject that is the port in the .originalFromNode.*/ originalFromPort: GraphObject; /**Gets or sets the original Link being reconnected by the RelinkingTool.*/ originalLink: Link; - /**Gets or sets the original Node to which the new link is being drawn or to which the #originalLink was connected when being relinked.*/ + /**Gets or sets the original Node to which the new link is being drawn or to which the .originalLink was connected when being relinked.*/ originalToNode: Node; - /**Gets or sets the GraphObject that is the port in the #originalToNode.*/ + /**Gets or sets the GraphObject that is the port in the .originalToNode.*/ originalToPort: GraphObject; /**Gets or sets the distance at which link snapping occurs.*/ @@ -6787,19 +7478,19 @@ declare module go { /**Gets or sets a proposed GraphObject port for connecting a link.*/ targetPort: GraphObject; - /**Gets or sets the temporary Node at the "from" end of the #temporaryLink while the user is drawing or reconnecting a link.*/ + /**Gets or sets the temporary Node at the "from" end of the .temporaryLink while the user is drawing or reconnecting a link.*/ temporaryFromNode: Node; - /**Gets or sets the GraphObject that is the port at the "from" end of the #temporaryLink while the user is drawing or reconnecting a link.*/ + /**Gets or sets the GraphObject that is the port at the "from" end of the .temporaryLink while the user is drawing or reconnecting a link.*/ temporaryFromPort: GraphObject; /**Gets or sets the temporary Link that is shown while the user is drawing or reconnecting a link.*/ temporaryLink: Link; - /**Gets or sets the temporary Node at the "to" end of the #temporaryLink while the user is drawing or reconnecting a link.*/ + /**Gets or sets the temporary Node at the "to" end of the .temporaryLink while the user is drawing or reconnecting a link.*/ temporaryToNode: Node; - /**Gets or sets the GraphObject that is the port at the "to" end of the #temporaryLink while the user is drawing or reconnecting a link.*/ + /**Gets or sets the GraphObject that is the port at the "to" end of the .temporaryLink while the user is drawing or reconnecting a link.*/ temporaryToPort: GraphObject; /** @@ -6810,12 +7501,12 @@ declare module go { * @param {GraphObject} tempport * @param {boolean} toend */ - copyPortProperties(realnode: Node, realport: GraphObject, tempnode: Node, tempport: GraphObject, toend: boolean); + copyPortProperties(realnode: Node, realport: GraphObject, tempnode: Node, tempport: GraphObject, toend: boolean): void; /** * Mouse movement results in a temporary node moving to where a valid target port is located, or to where the mouse is if there is no valid target port nearby. */ - doMouseMove(); + doMouseMove(): void; /** * Find a port with which the user could complete a valid link. @@ -6837,13 +7528,24 @@ declare module go { */ isLinked(fromport: GraphObject, toport: GraphObject): boolean; + /** + * Checks whether a proposed link would be valid according to Diagram.validCycle. + * This does not distinguish between different ports on a node, so this method does not need to take port arguments. + * This is called by isValidLink. + * @param {Node} from + * @param {Node} to + * @param {Link} ignore may be null; this is useful during relinking to ignore the originalLink + * @return {boolean} + */ + isValidCycle(from: Node, to: Node, ignore: Link): boolean; + /** * This predicate is true if it is permissible to connect a link from a given node/port. * @param {Node} fromnode * @param {GraphObject} fromport - * False if the node is in a Layer that does not Layer#allowLink. - * False if the port's GraphObject#fromLinkable is either false or null. - * False if the number of links connected to the port would exceed the port's GraphObject#fromMaxLinks. + * False if the node is in a Layer that does not Layer.allowLink. + * False if the port's GraphObject.fromLinkable is either false or null. + * False if the number of links connected to the port would exceed the port's GraphObject.fromMaxLinks. * Otherwise true. */ isValidFrom(fromnode: Node, fromport: GraphObject): boolean; @@ -6854,14 +7556,14 @@ declare module go { * @param {GraphObject} fromport the "from" GraphObject port. * @param {Node} tonode the "to" Node. * @param {GraphObject} toport the "to" GraphObject port. - * False if #isValidFrom is false for the "from" node/port. - * False if #isValidTo is false for the "to" node/port. - * False if #isInSameNode is true unless GraphObject#fromLinkableSelfNode - * and GraphObject#toLinkableSelfNode are true for the two ports. - * False if #isLinked is true unless GraphObject#fromLinkableDuplicates - * and GraphObject#toLinkableDuplicates are true for the two ports. + * False if .isValidFrom is false for the "from" node/port. + * False if .isValidTo is false for the "to" node/port. + * False if .isInSameNode is true unless GraphObject.fromLinkableSelfNode + * and GraphObject.toLinkableSelfNode are true for the two ports. + * False if .isLinked is true unless GraphObject.fromLinkableDuplicates + * and GraphObject.toLinkableDuplicates are true for the two ports. * False if trying to link to the link's own label node(s). - * If #linkValidation is a predicate and if it returns false, this predicate returns false. + * If .linkValidation is a predicate and if it returns false, this predicate returns false. * Otherwise this predicate is true. */ isValidLink(fromnode: Node, fromport: GraphObject, tonode: Node, toport: GraphObject): boolean; @@ -6870,9 +7572,9 @@ declare module go { * This predicate is true if it is permissible to connect a link to a given node/port. * @param {Node} tonode * @param {GraphObject} toport - * False if the node is in a Layer that does not Layer#allowLink. - * False if the port's GraphObject#toLinkable is either false or null. - * False if the number of links connected from the port would exceed the port's GraphObject#toMaxLinks. + * False if the node is in a Layer that does not Layer.allowLink. + * False if the port's GraphObject.toLinkable is either false or null. + * False if the number of links connected from the port would exceed the port's GraphObject.toMaxLinks. * Otherwise true. */ isValidTo(tonode: Node, toport: GraphObject): boolean; @@ -6883,7 +7585,7 @@ declare module go { * @param {GraphObject} tempport * @param {boolean} toend */ - setNoTargetPortProperties(tempnode: Node, tempport: GraphObject, toend: boolean); + setNoTargetPortProperties(tempnode: Node, tempport: GraphObject, toend: boolean): void; } /** @@ -6894,41 +7596,41 @@ declare module go { */ class LinkingTool extends LinkingBaseTool { /** - * You do not normally need to create an instance of this tool because one already exists as the ToolManager#linkingTool, which you can modify. + * You do not normally need to create an instance of this tool because one already exists as the ToolManager.linkingTool, which you can modify. */ constructor(); - /**Gets or sets an optional node data object representing a link label, that is copied by #insertLink and added to the GraphLinksModel when creating a new Link.*/ + /**Gets or sets an optional node data object representing a link label, that is copied by .insertLink and added to the GraphLinksModel when creating a new Link.*/ archetypeLabelNodeData: Object; - /**Gets or sets a data object that is copied by #insertLink and added to the GraphLinksModel when creating a new Link.*/ + /**Gets or sets a data object that is copied by .insertLink and added to the GraphLinksModel when creating a new Link.*/ archetypeLinkData: Object; /**Gets or sets the direction in which new links may be drawn.*/ direction: EnumValue; - /**Gets or sets the GraphObject at which #findLinkablePort should start its search.*/ + /**Gets or sets the GraphObject at which .findLinkablePort should start its search.*/ startObject: GraphObject; /** - * This tool can run when the diagram allows linking, the model is modifiable, the left-button mouse drag has moved far enough away to not be a click, and when #findLinkablePort has returned a valid port. + * This tool can run when the diagram allows linking, the model is modifiable, the left-button mouse drag has moved far enough away to not be a click, and when .findLinkablePort has returned a valid port. */ canStart(): boolean; /** * Start the linking operation. */ - doActivate(); + doActivate(): void; /** * Finishing the linking operation stops the transaction, releases the mouse, and resets the cursor. */ - doDeactivate(); + doDeactivate(): void; /** - * A mouse-up ends the linking operation; if there is a valid #targetPort nearby, this adds a new Link by calling #insertLink. + * A mouse-up ends the linking operation; if there is a valid .targetPort nearby, this adds a new Link by calling .insertLink. */ - doMouseUp(); + doMouseUp(): void; /** * Return the GraphObject at the mouse-down point, if it is part of a node and if it is valid to link with it. @@ -6936,7 +7638,7 @@ declare module go { findLinkablePort(): GraphObject; /** - * Make a copy of the #archetypeLinkData, set its node and port properties, and add it to the model. + * Make a copy of the .archetypeLinkData, set its node and port properties, and add it to the model. * @param {Node} fromnode * @param {GraphObject} fromport * @param {Node} tonode @@ -6944,13 +7646,13 @@ declare module go { */ insertLink(fromnode: Node, fromport: GraphObject, tonode: Node, toport: GraphObject): Link; - /**This value for LinkingTool#direction indicates that users may draw new links backwards only.*/ + /**This value for LinkingTool.direction indicates that users may draw new links backwards only.*/ static BackwardsOnly: EnumValue; - /**This value for LinkingTool#direction indicates that users may draw new links in either direction.*/ + /**This value for LinkingTool.direction indicates that users may draw new links in either direction.*/ static Either: EnumValue; - /**This value for LinkingTool#direction indicates that users may draw new links forwards only.*/ + /**This value for LinkingTool.direction indicates that users may draw new links forwards only.*/ static ForwardsOnly: EnumValue; } @@ -6963,14 +7665,14 @@ declare module go { */ class LinkReshapingTool extends Tool { /** - * You do not normally need to create an instance of this tool because one already exists as the ToolManager#linkReshapingTool, which you can modify. + * You do not normally need to create an instance of this tool because one already exists as the ToolManager.linkReshapingTool, which you can modify. */ constructor(); - /**Gets the Link that is being routed manually.*/ + /**This read-only property returns the Link that is being routed manually.*/ adornedLink: Link; - /**Gets the GraphObject that is the tool handle being dragged by the user.*/ + /**This read-only property returns the GraphObject that is the tool handle being dragged by the user.*/ handle: GraphObject; /**Gets or sets a small GraphObject that is copied as a reshape handle at each movable point in the selected link's route.*/ @@ -6979,11 +7681,11 @@ declare module go { /**Gets or sets a small GraphObject that is copied as a resegment handle at each mid point in the selected Link's route.*/ midHandleArchetype: GraphObject; - /**Gets the Point that was the original location of the handle that is being dragged to reshape the Link.*/ + /**This read-only property returns the Point that was the original location of the handle that is being dragged to reshape the Link.*/ originalPoint: Point; - /**Gets the List of Points that was the original route of the Link that is being reshaped.*/ - originalPoints: List; + /**This read-only property returns the List of Points that was the original route of the Link that is being reshaped.*/ + originalPoints: List; /** * This tool may run when there is a mouse-down event on a reshape handle. @@ -6991,47 +7693,60 @@ declare module go { canStart(): boolean; /** - * This is called by #doMouseMove and #doMouseUp to limit the input point before calling #reshape. + * This is called by .doMouseMove and .doMouseUp to limit the input point before calling .reshape. * @param {Point} p */ computeReshape(p: Point): Point; /** - * Start reshaping, if #findToolHandleAt finds a reshape handle at the mouse down point. + * Start reshaping, if .findToolHandleAt finds a reshape handle at the mouse down point. */ - doActivate(); + doActivate(): void; /** * Restore the link route to be the original points and stop this tool. */ - doCancel(); + doCancel(): void; /** * This stops the current reshaping operation with the link route shaped the way it is. */ - doDeactivate(); + doDeactivate(): void; /** - * Call #reshape with a new point determined by the mouse to change the route of the #adornedLink. + * Call .reshape with a new point determined by the mouse to change the route of the .adornedLink. */ - doMouseMove(); + doMouseMove(): void; /** - * Reshape the route with a point based on the most recent mouse point by calling #reshape, and then raise a "LinkReshaped" DiagramEvent before stopping this tool. + * Reshape the route with a point based on the most recent mouse point by calling .reshape, and then raise a "LinkReshaped" DiagramEvent before stopping this tool. */ - doMouseUp(); + doMouseUp(): void; /** - * Change the route of the #adornedLink by moving the point corresponding to the current #handle to be at the given Point. + * Get the permitted reshaping behavior for a particular reshape handle. + * @param {GraphObject} obj a reshape handle in the "LinkReshaping" Adornment. + */ + getReshapingBehavior(obj: GraphObject): EnumValue; + + /** + * Set the permitted reshaping behavior for a particular reshape handle. + * @param {GraphObject} obj a reshape handle in the "LinkReshaping" Adornment. + * @param {EnumValue} behavior one of LinkReshapingTool.All, .Vertical, .Horizontal, or .None + */ + setReshapingBehavior(obj: GraphObject, behavior: EnumValue): void; + + /** + * Change the route of the .adornedLink by moving the point corresponding to the current .handle to be at the given Point. * @param {Point} newPoint */ - reshape(newPoint: Point); + reshape(newPoint: Point): void; /** - * Show an Adornment with reshape handles at each of the interesting points of the link's route, if the link is selected and visible and if Part#canReshape is true. + * Show an Adornment with reshape handles at each of the interesting points of the link's route, if the link is selected and visible and if Part.canReshape is true. * @param {Part} part */ - updateAdornments(part: Part); + updateAdornments(part: Part): void; /**Allow dragging in any direction.*/ static All: EnumValue; @@ -7048,18 +7763,18 @@ declare module go { /** * The PanningTool supports manual panning, where the user can shift the - * Diagram#position by dragging the mouse. + * Diagram.position by dragging the mouse. */ class PanningTool extends Tool { /** - * You do not normally need to create an instance of this tool because one already exists as the ToolManager#panningTool. + * You do not normally need to create an instance of this tool because one already exists as the ToolManager.panningTool. */ constructor(); /**Gets or sets whether panning actions will allow events to bubble instead of panning in the diagram.*/ bubbles: boolean; - /**Gets the Point that was the original value of Diagram#position when the panning operation started.*/ + /**This read-only property returns the Point that was the original value of Diagram.position when the panning operation started.*/ originalPosition: Point; /** @@ -7068,45 +7783,45 @@ declare module go { canStart(): boolean; /** - * Capture the mouse, change the diagram cursor, and remember the Diagram#position. + * Capture the mouse, change the diagram cursor, and remember the Diagram.position. */ - doActivate(); + doActivate(): void; /** - * Restore the Diagram#position to what it was when this tool activated. + * Restore the Diagram.position to what it was when this tool activated. */ - doCancel(); + doCancel(): void; /** * Release the mouse and restore the default diagram cursor. */ - doDeactivate(); + doDeactivate(): void; /** - * Modify the Diagram#position according to how much the mouse has moved. + * Modify the Diagram.position according to how much the mouse has moved. */ - doMouseMove(); + doMouseMove(): void; /** - * Modify the Diagram#position according to how much the mouse has moved. + * Modify the Diagram.position according to how much the mouse has moved. */ - doMouseUp(); + doMouseUp(): void; } /** * The RelinkingTool allows the user to reconnect an existing Link - * if the Link#relinkableTo and/or Link#relinkableFrom properties are true. + * if the Link.relinkableTo and/or Link.relinkableFrom properties are true. */ class RelinkingTool extends Tool { /** - * You do not normally need to create an instance of this tool because one already exists as the ToolManager#relinkingTool, which you can modify. + * You do not normally need to create an instance of this tool because one already exists as the ToolManager.relinkingTool, which you can modify. */ constructor(); /**Gets or sets a small GraphObject that is copied as a relinking handle for the selected link path at the "from" end of the link.*/ fromHandleArchetype: GraphObject; - /**Gets the GraphObject that is the tool handle being dragged by the user.*/ + /**This read-only property returns the GraphObject that is the tool handle being dragged by the user.*/ handle: GraphObject; /**Gets or sets a small GraphObject that is copied as a relinking handle for the selected link path at the "to" end of the link.*/ @@ -7117,20 +7832,27 @@ declare module go { */ canStart(): boolean; + /** + * Make a temporary link look and act like the real Link being relinked. + * @param {Link} reallink + * @param {Link} templink + */ + copyLinkProperties(reallink: Link, templink: Link): void; + /** * Start the relinking operation. */ - doActivate(); + doActivate(): void; /** * Finishing the linking operation stops the transaction, releases the mouse, and resets the cursor. */ - doDeactivate(); + doDeactivate(): void; /** - * A mouse-up ends the relinking operation; if there is a valid #targetPort nearby, this modifies the old link to connect with the target port. + * A mouse-up ends the relinking operation; if there is a valid .targetPort nearby, this modifies the old link to connect with the target port. */ - doMouseUp(); + doMouseUp(): void; /** * Modify an existing Link to connect to a new node and port. @@ -7145,7 +7867,7 @@ declare module go { * Show an Adornment for each end of the Link that the user may reconnect. * @param {Part} part */ - updateAdornments(part: Part); + updateAdornments(part: Part): void; } /** @@ -7155,17 +7877,17 @@ declare module go { */ class ResizingTool extends Tool { /** - * You do not normally need to create an instance of this tool because one already exists as the ToolManager#resizingTool, which you can modify. + * You do not normally need to create an instance of this tool because one already exists as the ToolManager.resizingTool, which you can modify. */ constructor(); - /**Gets the GraphObject that is being resized.*/ + /**This read-only property returns the GraphObject that is being resized.*/ adornedObject: GraphObject; /**Gets or sets the width and height multiples with which the user must resize.*/ cellSize: Size; - /**Gets the GraphObject that is the tool handle being dragged by the user.*/ + /**This read-only property returns the GraphObject that is the tool handle being dragged by the user.*/ handle: GraphObject; /**Gets or sets a small GraphObject that is copied as a resizing handle for the selected part.*/ @@ -7180,10 +7902,10 @@ declare module go { /**Gets or sets the minimum size to which the user can resize.*/ minSize: Size; - /**Gets the Size that was the original value of the GraphObject#desiredSize of the element that is being resized.*/ + /**This read-only property returns the Size that was the original value of the GraphObject.desiredSize of the element that is being resized.*/ originalDesiredSize: Size; - /**Gets the Point that was the original value of the Part#location of the Part that is being resized.*/ + /**This read-only property returns the Point that was the original value of the Part.location of the Part that is being resized.*/ originalLocation: Point; /** @@ -7197,12 +7919,12 @@ declare module go { computeCellSize(): Size; /** - * The effective maximum resizing size is the minimum of the #maxSize and the #adornedObject's GraphObject#maxSize. + * The effective maximum resizing size is the minimum of the .maxSize and the .adornedObject's GraphObject.maxSize. */ computeMaxSize(): Size; /** - * The effective minimum resizing size is the maximum of #minSize and the #adornedObject's GraphObject#minSize. + * The effective minimum resizing size is the maximum of .minSize and the .adornedObject's GraphObject.minSize. */ computeMinSize(): Size; @@ -7210,64 +7932,64 @@ declare module go { * Given a Spot in the original bounds of the object being resized and a new Point, compute the new Rect. * @param {Point} newPoint a Point in local coordinates. * @param {Spot} spot the alignment spot of the handle being dragged. - * @param {Size} min the result of the call to #computeMinSize. - * @param {Size} max the result of the call to #computeMaxSize. - * @param {Size} cell the result of the call to #computeCellSize. - * @param {boolean} reshape true if the new size may change the aspect ratio from that of the natural bounds of the #adornedObject. + * @param {Size} min the result of the call to .computeMinSize. + * @param {Size} max the result of the call to .computeMaxSize. + * @param {Size} cell the result of the call to .computeCellSize. + * @param {boolean} reshape true if the new size may change the aspect ratio from that of the natural bounds of the .adornedObject. */ computeResize(newPoint: Point, spot: Spot, min: Size, max: Size, cell: Size, reshape: boolean): Rect; /** * Capture the mouse, remember the object's original bounds, and start a transaction.\ */ - doActivate(); + doActivate(): void; /** * Restore the original GraphObject's size. */ - doCancel(); + doCancel(): void; /** * Stop the current transaction and release the mouse. */ - doDeactivate(); + doDeactivate(): void; /** - * Call #resize with a new size determined by the current mouse point. + * Call .resize with a new size determined by the current mouse point. */ - doMouseMove(); + doMouseMove(): void; /** - * Call #resize with the final bounds based on the most recent mouse point, commit the transaction, and raise the "PartResized" DiagramEvent. + * Call .resize with the final bounds based on the most recent mouse point, commit the transaction, and raise the "PartResized" DiagramEvent. */ - doMouseUp(); + doMouseUp(): void; /** - * Change the size of the selected part's Part#resizeObject to have the given bounds. + * Change the size of the selected part's Part.resizeObject to have the given bounds. * @param {Rect} newr */ - rezise(newr: Rect); + resize(newr: Rect): void; /** - * Show an Adornment with the resize handles at points along the edge of the bounds of the selected Part's Part#resizeObject. + * Show an Adornment with the resize handles at points along the edge of the bounds of the selected Part's Part.resizeObject. * @param {Part} part */ - updateAdornments(part: Part); + updateAdornments(part: Part): void; } /** - * The RotatingTool is used to interactively change the GraphObject#angle of a GraphObject. - * This tool allows the user to rotate the Part#rotateObject of the selected Part. + * The RotatingTool is used to interactively change the GraphObject.angle of a GraphObject. + * This tool allows the user to rotate the Part.rotateObject of the selected Part. * Normally this works with Parts or Nodes; it does not make sense for Links. - * The Part must be Part#rotatable, which is false by default. + * The Part must be Part.rotatable, which is false by default. */ class RotatingTool extends Tool { /** - * You do not normally need to create an instance of this tool because one already exists as the ToolManager#rotatingTool, which you can modify. + * You do not normally need to create an instance of this tool because one already exists as the ToolManager.rotatingTool, which you can modify. */ constructor(); - /**Gets the GraphObject that is being rotated.*/ + /**This read-only property returns the GraphObject that is being rotated.*/ adornedObject: GraphObject; /**Gets or sets a small GraphObject that is copied as a rotation handle for the selected part.*/ @@ -7276,7 +7998,7 @@ declare module go { /**Gets or sets a small GraphObject that is copied as a rotation handle for the selected part.*/ handleArchetype: GraphObject; - /**Gets the angle that was the original value of the GraphObject#angle of the GraphObject that is being rotated.*/ + /**This read-only property returns the angle that was the original value of the GraphObject.angle of the GraphObject that is being rotated.*/ originalAngle: number; /**Gets or sets the the closeness to a desired angle at which the angle is "snapped to".*/ @@ -7297,51 +8019,51 @@ declare module go { computeRotate(newPoint: Point): number; /** - * Capture the mouse, remember the original GraphObject#angle, and start a transaction. + * Capture the mouse, remember the original GraphObject.angle, and start a transaction. */ - doActivate(); + doActivate(): void; /** - * Restore the original GraphObject#angle of the adorned object. + * Restore the original GraphObject.angle of the adorned object. */ - doCancel(); + doCancel(): void; /** * Stop the current transaction and release the mouse. */ - doDeactivate(); + doDeactivate(): void; /** - * Call #rotate with a new angle determined by the current mouse point. + * Call .rotate with a new angle determined by the current mouse point. */ - doMouseMove(); + doMouseMove(): void; /** - * Call #rotate with an angle based on the most recent mouse point, commit the transaction, and raise the "PartRotated" DiagramEvent. + * Call .rotate with an angle based on the most recent mouse point, commit the transaction, and raise the "PartRotated" DiagramEvent. */ - doMouseUp(); + doMouseUp(): void; /** - * Change the angle of the selected part's Part#rotateObject. + * Change the angle of the selected part's Part.rotateObject. * @param {number} newangle */ - rotate(newangle: number); + rotate(newangle: number): void; /** - * Show an Adornment with a rotate handle at a point to the side of the adorned object if the part is selected and visible and if Part#canRotate() is true. + * Show an Adornment with a rotate handle at a point to the side of the adorned object if the part is selected and visible and if Part.canRotate() is true. * @param {Part} part */ - updateAdornments(part: Part); + updateAdornments(part: Part): void; } /** * The TextEditingTool is used to let the user interactively edit text in place. * You do not normally need to create an instance of this tool - * because one already exists as the ToolManager#clickSelectingTool. + * because one already exists as the ToolManager.clickSelectingTool. */ class TextEditingTool extends Tool { /** - * You do not normally need to create an instance of this tool because one already exists as the ToolManager#textEditingTool, which you can modify. + * You do not normally need to create an instance of this tool because one already exists as the ToolManager.textEditingTool, which you can modify. */ constructor(); @@ -7362,48 +8084,48 @@ declare module go { /** * Finish editing by trying to accept the new text. - * @param {EnumValue} reason The reason must be either TextEditingTool#LostFocus, - * TextEditingTool#MouseDown, TextEditingTool#Tab, or TextEditingTool#Enter. + * @param {EnumValue} reason The reason must be either TextEditingTool.LostFocus, + * TextEditingTool.MouseDown, TextEditingTool.Tab, or TextEditingTool.Enter. */ - acceptText(reason: EnumValue); + acceptText(reason: EnumValue): void; /** - * This may run when there is a mouse-click on a TextBlock for which the TextBlock#editable property is true in a Part that Part#isSelected. + * This may run when there is a mouse-click on a TextBlock for which the TextBlock.editable property is true in a Part that Part.isSelected. */ canStart(): boolean; /** * Start editing the text for a TextBlock. */ - doActivate(); + doActivate(): void; /** * Abort any text editing operation. */ - doCancel(); + doCancel(): void; /** * Release the mouse. */ - doDeactivate(); + doDeactivate(): void; /** - * A click (mouse up) calls TextEditingTool#doActivate if this tool is not already active and if TextEditingTool#canStart returns true. + * A click (mouse up) calls TextEditingTool.doActivate if this tool is not already active and if TextEditingTool.canStart returns true. */ - doMouseDown(); + doMouseDown(): void; /** - * A click (mouse up) calls TextEditingTool#doActivate if this tool is not already active and if TextEditingTool#canStart returns true. + * A click (mouse up) calls TextEditingTool.doActivate if this tool is not already active and if TextEditingTool.canStart returns true. */ - doMouseUp(); + doMouseUp(): void; /** - * This calls TextEditingTool#doActivate if there is a TextBlock supplied. + * This calls TextEditingTool.doActivate if there is a TextBlock supplied. */ - doStart(); + doStart(): void; /** - * This predicate checks any TextBlock#textValidation predicate and this tool's #textValidation predicate to make sure the TextBlock#text property may be set to the new string. + * This predicate checks any TextBlock.textValidation predicate and this tool's .textValidation predicate to make sure the TextBlock.text property may be set to the new string. * @param {TextBlock} textblock the TextBlock that is being edited. * @param {string} oldstr the previous string value. * @param {string} newstr the proposed new string value. @@ -7419,10 +8141,10 @@ declare module go { /**The user has clicked somewhere else in the diagram.*/ static MouseDown: EnumValue; - /**A single click on a TextBlock with TextBlock#editable property set to true will start in-place editing.*/ + /**A single click on a TextBlock with TextBlock.editable property set to true will start in-place editing.*/ static SingleClick: EnumValue; - /**A single click on a TextBlock with TextBlock#editable property set to true will start in-place editing, but only if the Part that the TextBlock is in is already selected.*/ + /**A single click on a TextBlock with TextBlock.editable property set to true will start in-place editing, but only if the Part that the TextBlock is in is already selected.*/ static SingleClickSelected: EnumValue; /**The user has typed TAB.*/ @@ -7431,7 +8153,7 @@ declare module go { /** * Tools handle mouse events and keyboard events. - * The currently running tool, Diagram#currentTool, receives all input events from the Diagram. + * The currently running tool, Diagram.currentTool, receives all input events from the Diagram. */ class Tool { /** @@ -7439,7 +8161,7 @@ declare module go { */ constructor(); - /**Gets the Diagram that owns this tool and for which this tool is handling input events.*/ + /**This read-only property returns the Diagram that owns this tool and for which this tool is handling input events.*/ diagram: Diagram; /**Gets or sets whether this tool is started and is actively doing something.*/ @@ -7451,13 +8173,13 @@ declare module go { /**Gets or sets the name of this tool.*/ name: string; - /**Gets or sets the name of the transaction to be committed by #stopTransaction; if null, the transaction will be rolled back.*/ + /**Gets or sets the name of the transaction to be committed by .stopTransaction; if null, the transaction will be rolled back.*/ transactionResult: string; /** * This is called to cancel any running "WaitAfter" timer. */ - cancelWaitAfter(); + cancelWaitAfter(): void; /** * This predicate is used by the ToolManager to decide if this tool can be started mode-lessly by mouse and touch events. @@ -7465,76 +8187,81 @@ declare module go { canStart(): boolean; /** - * This method is called by the diagram after setting Diagram#currentTool, to make the new tool active. + * This predicate determines whether or not to allow pinch zooming from a multi-touch event. */ - doActivate(); + canStartMultiTouch(): boolean; + + /** + * This method is called by the diagram after setting Diagram.currentTool, to make the new tool active. + */ + doActivate(): void; /** * The diagram will call this method when the user wishes to cancel the current tool's operation. */ - doCancel(); + doCancel(): void; /** - * This method is called by the diagram on the old tool when Diagram#currentTool is set to a new tool. + * This method is called by the diagram on the old tool when Diagram.currentTool is set to a new tool. */ - doDeactivate(); + doDeactivate(): void; /** * The diagram will call this method upon a key down event. */ - doKeyDown(); + doKeyDown(): void; /** * The diagram will call this method upon a key up event. */ - doKeyUp(); + doKeyUp(): void; /** * The diagram will call this method upon a mouse down event. */ - doMouseDown(); + doMouseDown(): void; /** * The diagram will call this method upon a mouse move event. */ - doMouseMove(); + doMouseMove(): void; /** * The diagram will call this method upon a mouse up event. */ - doMouseUp(); + doMouseUp(): void; /** * The diagram will call this method as the mouse wheel is rotated. */ - doMouseWheel(); + doMouseWheel(): void; /** * This method is called by the diagram when this tool becomes the current tool; you should not call this method. */ - doStart(); + doStart(): void; /** * This method is called by the diagram when this tool stops being the current tool; you should not call this method. */ - doStop(); + doStop(): void; /** - * This is called a certain delay after a call to #standardWaitAfter if there has not been any call to #cancelWaitAfter. + * This is called a certain delay after a call to .standardWaitAfter if there has not been any call to .cancelWaitAfter. */ - doWaitAfter(); + doWaitAfter(): void; /** * This convenience function finds the front-most GraphObject that is at a given point and that is part of an Adornment that is of a given category. * @param {Point} p a Point in document coordinates. - * @param {string} category the required Part#category of the Adornment. + * @param {string} category the required Part.category of the Adornment. */ findToolHandleAt(p: Point, category: string): GraphObject; /** * Return true when the last mouse point is far enough away from the first mouse down point to constitute a drag operation instead of just a potential click. - * @param {Point=} first Point in view coordinates, defaults to Diagram#firstInput's InputEvent#viewPoint. - * @param {Point=} last Point in view coordinates, defaults to Diagram#lastInput's InputEvent#viewPoint. + * @param {Point=} first Point in view coordinates, defaults to Diagram.firstInput's InputEvent.viewPoint. + * @param {Point=} last Point in view coordinates, defaults to Diagram.lastInput's InputEvent.viewPoint. */ isBeyondDragSize(first?: Point, last?: Point): boolean; @@ -7544,42 +8271,52 @@ declare module go { * function to find target objects. * @param {function(GraphObject):boolean | null=} pred An optional custom predicate */ - standardMouseClick(navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean); + standardMouseClick(navig?: (obj: GraphObject) => GraphObject, pred?: (obj: GraphObject) => boolean): void; /** * Implement the standard behavior for mouse enter, over, and leave events, where the mouse is moving but no button is pressed. */ - standardMouseOver(); + standardMouseOver(): void; /** * Implement the standard behavior for selecting parts with the mouse, depending on the control and shift modifier keys. */ - standardMouseSelect(); + standardMouseSelect(): void; /** * Implement the standard behavior for mouse wheel events. */ - standardMouseWheel(); + standardMouseWheel(): void; /** - * This is called to start a new timer to call #doWaitAfter after a given delay. + * Initiates pinch-zooming on multi-touch devices. + */ + standardPinchZoomStart(): void; + + /** + * Continues pinch-zooming (started by standardPinchZoomStart) on multi-touch devices. + */ + standardPinchZoomMove(): void; + + /** + * This is called to start a new timer to call .doWaitAfter after a given delay. * @param {number} delay in milliseconds */ - standardWaitAfter(delay: number); + standardWaitAfter(delay: number): void; /** - * Call Diagram#startTransaction with the given transaction name. + * Call Diagram.startTransaction with the given transaction name. * @param {string=} tname a description of the transaction */ startTransaction(tname?: string): boolean; /** - * If the Diagram#currentTool is this tool, stop this tool and start the Diagram#defaultTool by making it be the new current tool. + * If the Diagram.currentTool is this tool, stop this tool and start the Diagram.defaultTool by making it be the new current tool. */ - stopTool(); + stopTool(): void; /** - * If #transactionResult is null, call Diagram#rollbackTransaction, otherwise call Diagram#commitTransaction. + * If .transactionResult is null, call Diagram.rollbackTransaction, otherwise call Diagram.commitTransaction. */ stopTransaction(): boolean; @@ -7587,7 +8324,7 @@ declare module go { * The diagram asks each tool to update any adornments the tool might use for a given part. * @param {Part} part */ - updateAdornments(part: Part); + updateAdornments(part: Part): void; } /** @@ -7596,29 +8333,29 @@ declare module go { */ class ToolManager extends Tool { /** - * You do not normally need to create an instance of this tool because one already exists as the Diagram#toolManager, which you can modify. + * You do not normally need to create an instance of this tool because one already exists as the Diagram.toolManager, which you can modify. */ constructor(); - /**Gets or sets the mode-less ActionTool, normally one of the #mouseDownTools.*/ + /**Gets or sets the mode-less ActionTool, normally one of the .mouseDownTools.*/ actionTool: ActionTool; - /**Gets or sets the mode-less ClickCreatingTool, normally one of the #mouseUpTools.*/ + /**Gets or sets the mode-less ClickCreatingTool, normally one of the .mouseUpTools.*/ clickCreatingTool: ClickCreatingTool; - /**Gets or sets the mode-less ClickSelectingTool, normally one of the #mouseUpTools.*/ + /**Gets or sets the mode-less ClickSelectingTool, normally one of the .mouseUpTools.*/ clickSelectingTool: ClickSelectingTool; - /**Gets or sets the mode-less ContextMenuTool, normally one of the #mouseUpTools.*/ + /**Gets or sets the mode-less ContextMenuTool, normally one of the .mouseUpTools.*/ contextMenuTool: ContextMenuTool; - /**Gets the currently showing tooltip, or null if there is none.*/ + /**This read-only property returns the currently showing tooltip, or null if there is none.*/ currentToolTip: Adornment; - /**Gets or sets the mode-less DraggingTool, normally one of the #mouseMoveTools.*/ + /**Gets or sets the mode-less DraggingTool, normally one of the .mouseMoveTools.*/ draggingTool: DraggingTool; - /**Gets or sets the mode-less DragSelectingTool, normally one of the #mouseMoveTools.*/ + /**Gets or sets the mode-less DragSelectingTool, normally one of the .mouseMoveTools.*/ dragSelectingTool: DragSelectingTool; /**Gets or sets the distance in view coordinates within which a mouse down-and-up is considered a click and beyond which a mouse movement is considered a drag.*/ @@ -7630,83 +8367,83 @@ declare module go { /**Gets or sets the time between when the mouse stops moving and a hover event, in milliseconds.*/ hoverDelay: number; - /**Gets or sets the mode-less LinkingTool, normally one of the #mouseMoveTools.*/ + /**Gets or sets the mode-less LinkingTool, normally one of the .mouseMoveTools.*/ linkingTool: LinkingTool; - /**Gets or sets the mode-less LinkReshapingTool, normally one of the #mouseDownTools.*/ + /**Gets or sets the mode-less LinkReshapingTool, normally one of the .mouseDownTools.*/ linkReshapingTool: LinkReshapingTool; - /**Gets the list of Tools that might be started upon a mouse-down event.*/ - mouseDownTools: List; + /**This read-only property returns the list of Tools that might be started upon a mouse-down event.*/ + mouseDownTools: List; - /**Gets the list of Tools that might be started upon a mouse-move event.*/ - mouseMoveTools: List; + /**This read-only property returns the list of Tools that might be started upon a mouse-move event.*/ + mouseMoveTools: List; - /**Gets the list of Tools that might be started upon a mouse-up event.*/ - mouseUpTools: List; + /**This read-only property returns the list of Tools that might be started upon a mouse-up event.*/ + mouseUpTools: List; /**Gets or sets the ToolManager's mouse wheel behavior.*/ mouseWheelBehavior: EnumValue; - /**Gets or sets the mode-less PanningTool, normally one of the #mouseMoveTools.*/ + /**Gets or sets the mode-less PanningTool, normally one of the .mouseMoveTools.*/ panningTool: PanningTool; - /**Gets or sets the mode-less RelinkingTool, normally one of the #mouseDownTools.*/ + /**Gets or sets the mode-less RelinkingTool, normally one of the .mouseDownTools.*/ relinkingTool: RelinkingTool; - /**Gets or sets the mode-less ResizingTool, normally one of the #mouseDownTools.*/ + /**Gets or sets the mode-less ResizingTool, normally one of the .mouseDownTools.*/ resizingTool: ResizingTool; - /**Gets or sets the mode-less RotatingTool, normally one of the #mouseDownTools.*/ + /**Gets or sets the mode-less RotatingTool, normally one of the .mouseDownTools.*/ rotatingTool: RotatingTool; - /**Gets or sets the mode-less TextEditingTool, normally one of the #mouseUpTools.*/ + /**Gets or sets the mode-less TextEditingTool, normally one of the .mouseUpTools.*/ textEditingTool: TextEditingTool; /** - * This just calls CommandHandler#doKeyDown on the diagram's Diagram#commandHandler. + * This just calls CommandHandler.doKeyDown on the diagram's Diagram.commandHandler. */ - doKeyDown(); + doKeyDown(): void; /** - * This just calls CommandHandler#doKeyUp on the diagram's Diagram#commandHandler. + * This just calls CommandHandler.doKeyUp on the diagram's Diagram.commandHandler. */ - doKeyUp(); + doKeyUp(): void; /** - * Iterate over the #mouseDownTools list and start the first tool for which its Tool#canStart predicate returns true. + * Iterate over the .mouseDownTools list and start the first tool for which its Tool.canStart predicate returns true. */ - doMouseDown(); + doMouseDown(): void; /** - * Implement the standard behavior for mouse hover and mouse hold events, called by #doWaitAfter when the mouse has not moved for a period of time. + * Implement the standard behavior for mouse hover and mouse hold events, called by .doWaitAfter when the mouse has not moved for a period of time. */ - doMouseHover(); + doMouseHover(): void; /** - * Iterate over the #mouseMoveTools list and start the first tool for which its Tool#canStart predicate returns true. + * Iterate over the .mouseMoveTools list and start the first tool for which its Tool.canStart predicate returns true. */ - doMouseMove(); + doMouseMove(): void; /** - * Iterate over the #mouseUpTools list and start the first tool for which its Tool#canStart predicate returns true. + * Iterate over the .mouseUpTools list and start the first tool for which its Tool.canStart predicate returns true. */ - doMouseUp(); + doMouseUp(): void; /** * The diagram will call this method as the mouse wheel is rotated. */ - doMouseWheel(); + doMouseWheel(): void; /** - * Implement the standard behavior for tooltips, called by #doWaitAfter when the mouse has not moved for a period of time. + * Implement the standard behavior for tooltips, called by .doWaitAfter when the mouse has not moved for a period of time. */ - doToolTip(); + doToolTip(): void; /** * Implement the standard behavior for when the mouse has not moved for a period of time. */ - doWaitAfter(); + doWaitAfter(): void; /** * Find a mouse tool of a given name. @@ -7717,19 +8454,19 @@ declare module go { /** * Hide any tooltip. */ - hideToolTip(); + hideToolTip(): void; /** * Initialize the three mouse tool lists with instances of the standard tools. */ - initializeStandardTools(); + initializeStandardTools(): void; /** - * This is called by #showToolTip to position the part within the viewport. + * This is called by .showToolTip to position the part within the viewport. * @param {Adornment} tooltip * @param {GraphObject} obj The GraphObject getting the tooltip. */ - positionToolTip(tooltip: Adornment, obj: GraphObject); + positionToolTip(tooltip: Adornment, obj: GraphObject): void; /** * Replace a mouse tool of a given name with a new tool. @@ -7744,54 +8481,81 @@ declare module go { * @param {Adornment} tooltip * @param {GraphObject} obj The GraphObject getting the tooltip; this is null if the tooltip is being shown for the diagram background. */ - showToolTip(tooltip: Adornment, obj: GraphObject); + showToolTip(tooltip: Adornment, obj: GraphObject): void; - /**This value for #mouseWheelBehavior indicates that the mouse wheel events are ignored, although scrolling or zooming by other means may still be allowed.*/ + /**This value for gestureBehavior indicates that the pointer/touch pinch gestures on the canvas intend to have no effect on the Diagram, but also no effect on the page.*/ + static GestureCancel: EnumValue; + + /**This value for gestureBehavior indicates that the pointer/touch pinch gestures on the canvas intend to have no effect on the Diagram, but will not be prevented, and may bubble up the page to have other effects (such as zooming the page).*/ + static GestureNone: EnumValue; + + /**This value for gestureBehavior indicates that the pointer/touch pinch gestures on the canvas intend to zoom the Diagram.*/ + static GestureZoom: EnumValue; + + /**This value for .mouseWheelBehavior indicates that the mouse wheel events are ignored, although scrolling or zooming by other means may still be allowed.*/ static WheelNone: EnumValue; - /**This default value for #mouseWheelBehavior indicates that mouse wheel events scroll the diagram.*/ + /**This default value for .mouseWheelBehavior indicates that mouse wheel events scroll the diagram.*/ static WheelScroll: EnumValue; - /**This value for #mouseWheelBehavior indicates that the mouse wheel events change the scale of the diagram.*/ + /**This value for .mouseWheelBehavior indicates that the mouse wheel events change the scale of the diagram.*/ static WheelZoom: EnumValue; } /** * This interface is implemented by the List, Set, and Map - * classes; it provides the #iterator read-only property that returns an Iterator. + * classes; it provides the .iterator read-only property that returns an Iterator. */ - class Iterable { + class Iterable { /*This is an interface and thus does not have a constructor.*/ /**Gets an Iterator that can iterate over the items in the collection.*/ - iterator: Iterator; + iterator: Iterator; } /** * This interface defines properties and methods for iterating over a collection; - * it provides the #next predicate and the #value read-only property. + * it provides the .next predicate and the .value read-only property. * Some Iterators also provide key property values along with each value. */ - class Iterator extends Iterable { + class Iterator extends Iterable { /*This is an interface and thus does not have a constructor.*/ - /**Gets the total number of items in the iterated collection.*/ + /**This read-only property returns the total number of items in the iterated collection.*/ count: number; /**Returns itself, which is convenient for code that expects an Iterable instead of an Iterator.*/ - iterator: Iterator; + iterator: Iterator; - /**Gets the current index to the item in the collection, assuming #next has just returned true.*/ + /**This read-only property returns the current index to the item in the collection, assuming .next has just returned true.*/ key; - /**Gets the current item in the collection, assuming #next has just returned true.*/ - value; + /**This read-only property returns the current item in the collection, assuming .next has just returned true.*/ + value: T; + + /** + * This is true if all invocations of the given predicate on items in the collection are true. + * @param {(x: T) => boolean} pred + */ + all(pred: (x: T) => boolean): boolean; + + /** + * This is true if any invocation of the given predicate on items in the collection is true. + * @param {(x: T) => boolean} pred + */ + any(pred: (x: T) => boolean): boolean; + + /** + * Call the given function on each item in the collection. + * @param {(x: T) => void} func + */ + each(func: (x: T) => void ): void; /** * Return the first item in the collection, or null if there is none. */ - first(): any; + first(): T; /** * Call this method to advance the iterator to the next item in the collection. @@ -7801,135 +8565,204 @@ declare module go { /** * Start this iterator all over again. */ - reset(); + reset(): void; } /** * An ordered iterable collection. * It optionally enforces the type of elements that may be added to the List. */ - class List { + class List { /** * This creates a List that checks the type of the values to be instances of a particular kind of Object. * @param {function(...)} type this must be a class function/constructor. */ - constructor(type: new(...args: any[]) => Object); + constructor(type: Constructor); /** * This creates a List that may check the types of the values. * @param {string=} type if supplied, this must be one of: 'number', 'string', 'boolean', or 'function' for the value type. */ constructor(type?: string); - /**Gets the length of the List.*/ + /**This read-only property returns the length of the List.*/ count: number; + /**This read-only property returns the length of the List. ES6-like synonym for count.*/ + size: number; + /**Gets an object that you can use for iterating over the List.*/ - iterator: Iterator; + iterator: Iterator; /**Gets an object that you can use for iterating over the List in backwards order.*/ - iteratorBackwards: Iterator; + iteratorBackwards: Iterator; - /**Gets the length of the List, a synonym for the #count property.*/ + /**This read-only property returns the length of the List, a synonym for the .count property.*/ length: number; /** * Adds a given value to the end of the List. - * @param {*} any + * @param {*} val */ - add(val: any); + add(val: T): void; /** * Adds all of the values of a collection (either an Iterable or an Array) to the end of this List. - * @param {Iterable|Array} coll + * @param {Iterable|Array} coll */ - addAll(coll: any): List; + addAll(coll: Iterable | Array): List; + + /** + * This is true if all invocations of the given predicate on items in the collection are true. + * @param {(x: T) => boolean} pred + */ + all(pred: (x: T) => boolean): boolean; + + /** + * This is true if any invocation of the given predicate on items in the collection is true. + * @param {(x: T) => boolean} pred + */ + any(pred: (x: T) => boolean): boolean; /** * Clears the List. */ - clear(); + clear(): void; /** * Returns whether the given value is in this List. - * @param {*} any + * @param {*} val */ - contains(val: any): boolean; + contains(val: T): boolean; /** * Makes a shallow copy of this List. */ - copy(): List; + copy(): List; + + /** + * Removes a given value (if found) from the List. ES6-like synonym for remove. + * @param {*} val + */ + delete(val: T): boolean; + + /** + * Call the given function on each item in the collection. + * @param {(x: T) => void} func + */ + each(func: (x: T) => void ): void; /** * Returns the element at the given index. * @param {number} i */ - elt(i: number); + elt(i: number): T; /** - * Returns the first item in the collection, or null if there is none. + * Returns the first item in the list, or null if there is none. */ - first(); + first(): T; + + /** + * Returns the element at the given index. ES6-like synonym for elt. + * @param {number} i + */ + get(i: number): T; + + /** + * Returns whether the given value is in this List. ES6-like synonym for contains. + * @param {*} val + */ + has(val: T): boolean; /** * Returns the index of the given value if it is in this List. - * @param {*} any + * @param {*} val */ - indexOf(val: any): number; + indexOf(val: T): number; /** * Insert a value before the index i. * @param {number} i - * @param {*} any + * @param {*} val */ - insertAt(i: number, val: any); + insertAt(i: number, val: T): void; + + /** + * Returns the last item in the list, or null if there is none. + */ + last(): T; + + /** + * Returns the last item in the list and removes it from the list, or just return null if there is none. + */ + pop(): T; + + /** + * Add an item at the end of the list -- a synonym for add. + */ + push(val: T): void; /** * Removes a given value (if found) from the List. - * @param {*} any + * @param {*} val */ - remove(val: any): boolean; + remove(val: T): boolean; /** * Removes a value at a given index from the List. * @param {number} i */ - removeAt(i: number); + removeAt(i: number): void; /** * Removes a range of values from the List. * @param {number} to * @param {number} from */ - removeRange(to: number, from: number); + removeRange(to: number, from: number): void; /** * Reverse the order of items in this List. */ - reverse(): List; + reverse(): List; + + /** + * Set the element at the given index to a given value. ES6-like synonym for setElt. + * @param {number} i + * @param {*} val + */ + set(i: number, val: T): void; /** * Set the element at the given index to a given value. * @param {number} i * @param {*} val */ - setElt(i: number, val: any); + setElt(i: number, val: T): void; /** * Sort the List according to a comparison function. * @param {function(*,*):number} sortfunc the same kind of function as passed to Array.sort */ - sort(sortfunc: (a: any, b: any) => number): List; + sort(sortfunc: (a: T, b: T) => number): List; /** * Produces a JavaScript Array from the contents of this List. */ - toArray(): any[]; + toArray(): Array; /** * Converts the List to a Set. */ - toSet(): Set; + toSet(): Set; + } + + /** + * This is a structure used by Map to hold key-value pairs. + */ + interface KeyValuePair { // undocumented + key: K, + value: V } /** @@ -7937,25 +8770,25 @@ declare module go { * same key. * It optionally enforces the type of the key and the type of the associated value. */ - class Map { + class Map { /** * This creates a Map that may check the types of the keys and/or values. * @param {function(...)} keytype if supplied, this must be a class function/constructor. * @param {function(...)} valtype if supplied, this must be a class function/constructor. */ - constructor(keytype: new(...args: any[]) => Object, valtype: new(...args: any[]) => Object); + constructor(keytype: Constructor, valtype: Constructor); /** * This creates a Map that may check the types of the keys and/or values. * @param {string=} keytype if supplied, this must be one of: 'number' or 'string' for the key type. * @param {function(...)} valtype if supplied, this must be a class function/constructor. */ - constructor(keytype: string, valtype: new(...args: any[]) => Object); + constructor(keytype: string, valtype: Constructor); /** * This creates a Map that may check the types of the keys and/or values. * @param {function(...)} keytype if supplied, this must be a class function/constructor. * @param {string} valtype if supplied, this must be one of: 'number', 'string', 'boolean', or 'function' for the value type. */ - constructor(keytype: new(...args: any[]) => Object, valtype: string); + constructor(keytype: Constructor, valtype: string); /** * This creates a Map that may check the types of the keys and/or values. * @param {string=} keytype if supplied, this must be one of: 'number' or 'string' for the key type. @@ -7963,161 +8796,257 @@ declare module go { */ constructor(keytype?: string, valtype?: string); - /**Gets the number of associations in the Map.*/ + /**This read-only property returns the number of associations in the Map.*/ count: number; - /**Gets an object that you can use for iterating over the Map.*/ - iterator: Iterator; + /**Gets an object that you can use for iterating over the key-value pairs of the Map.*/ + iterator: Iterator>; + + /**Gets an object that you can use for iterating over the keys in the Map.*/ + iteratorKeys: Iterator; + + /**Gets an object that you can use for iterating over the values of the Map.*/ + iteratorValues: Iterator; + + /**This read-only property returns the number of associations in the Map. ES6-like synonym for count.*/ + size: number; /** * Adds a key-value association to the Map, or replaces the value associated with the key if the key was already present in the map. - * @param {*} any + * @param {*} key * @param {*} val */ - add(key: any, val: any): boolean; + add(key: K, val: V): boolean; /** * Adds all of the key-value pairs of another Map to this Map. - * @param {Map} map + * @param {Map|Array} map */ - addAll(map: Map): Map; + addAll(map: Map | Array>): Map; + + /** + * This is true if all invocations of the given predicate on key-value pairs in the collection are true. + * @param {(x: Object) => boolean} pred + */ + all(pred: (x: Object) => boolean): boolean; + + /** + * This is true if any invocation of the given predicate on key-value pairs in the collection is true. + * @param {(x: Object) => boolean} pred + */ + any(pred: (x: Object) => boolean): boolean; /** * Clears the Map, removing all key-value associations. */ - clear(); + clear(): void; /** * Returns whether the given key is in this Map. - * @param {*} any + * @param {*} key */ - contains(key: any): boolean; + contains(key: K): boolean; /** * Makes a shallow copy of this Map. */ - copy(): Map; + copy(): Map; + + /** + * Removes a key (if found) from the Map. ES6-like synonym for remove. + * @param {*} key + */ + delete(key: K): boolean; + + /** + * Call the given function on each key-value pair in the collection. + * @param {(x: Object) => void} func + */ + each(func: (x: KeyValuePair) => void ): void; + + /** + * Returns the first key-value pair in the collection, or null if there is none. + */ + first(): KeyValuePair; + + /** + * Returns the value associated with a key. ES6-like synonym for getValue. + * @param {*} key + */ + get(key: K): V; /** * Returns the value associated with a key. - * @param {*} any + * @param {*} key */ - getValue(key: any); + getValue(key: K): V; + + /** + * Returns whether the given key is in this Map. ES6-like synonym for contains. + * @param {*} key + */ + has(key: K): boolean; /** * Removes a key (if found) from the Map. - * @param {*} any + * @param {*} key */ - remove(key: any): boolean; + remove(key: K): boolean; + + /** + * Adds a key-value association to the Map, or replaces the value associated with the key if the key was already present in the map. ES6-like synonym for add. + * @param {*} key + * @param {*} val + */ + set(key: K, val: V): boolean; /** * Produces a JavaScript Array of key/value pair objects from the contents of this Map. */ - toArray(): any[]; + toArray(): Array>; /** * Produces a Set that provides a read-only view onto the keys of this Map. */ - toKeySet(): Set; + toKeySet(): Set; } /** * An unordered iterable collection that cannot contain two instances of the same kind of value. * It optionally enforces the type of elements that may be added to the Set. */ - class Set { + class Set { /** * This creates a Set that checks the type of the values. * @param {function(...)} type this must be a class function/constructor. */ - constructor(type: new(...args: any[]) => Object); + constructor(type: Constructor); /** * This creates a Set that may check the types of the values. * @param {string=} type if supplied, this must be one of: 'number' or 'string' for the key type. */ constructor(type?: string); - /**Gets the number of elements in the Set.*/ + /**This read-only property returns the number of elements in the Set.*/ count: number; /**Gets an object that you can use for iterating over the Set.*/ - iterator: Iterator; + iterator: Iterator; + + /**This read-only property returns the number of elements in the Set. ES6-like synonym for count.*/ + size: number; /** * Adds a given value to the Set, if not already present. - * @param {*} any + * @param {*} val */ - add(val: any): boolean; + add(val: T): boolean; /** * Adds all of the values of a collection (either an Iterable or an Array) to this Set. - * @param {Iterable|Array} coll + * @param {Iterable|Array} coll */ - addAll(coll: any): Set; + addAll(coll: Iterable | Array): Set; + + /** + * This is true if all invocations of the given predicate on items in the collection are true. + * @param {(x: T) => boolean} pred + */ + all(pred: (x: T) => boolean): boolean; + + /** + * This is true if any invocation of the given predicate on items in the collection is true. + * @param {(x: T) => boolean} pred + */ + any(pred: (x: T) => boolean): boolean; /** * Clears the Set. */ - clear(); + clear(): void; /** * Returns whether the given value is in this Set. - * @param {*} any + * @param {*} val */ - contains(val: any): boolean; + contains(val: T): boolean; /** * Returns true if all of the values of a given collection are in this Set. - * @param {Iterable} coll + * @param {Iterable} coll */ - containsAll(coll: Iterable): boolean; + containsAll(coll: Iterable): boolean; /** * Returns true if any of the values of a given collection are in this Set. - * @param {Iterable} coll + * @param {Iterable} coll */ - containsAny(coll: Iterable): boolean; + containsAny(coll: Iterable): boolean; /** * Makes a shallow copy of this Set. */ - copy(): Set; + copy(): Set; + + /** + * Removes a value (if found) from the Set. ES6-like synonym for remove. + * @param {*} val + */ + delete(val: T): boolean; + + /** + * Call the given function on each item in the collection. + * @param {(x: T) => void} func + */ + each(func: (x: T) => void): void; /** * Returns the first item in the collection, or null if there is none. */ - first(); + first(): T; + + /** + * Returns whether the given value is in this Set. ES6-like synonym for contains. + * @param {*} val + */ + has(val: T): boolean; /** * Removes a value (if found) from the Set. - * @param {*} any + * @param {*} val */ - remove(val: any): boolean; + remove(val: T): boolean; /** * Removes all of the values of a collection from this Set. - * @param {Iterable} coll + * @param {Iterable} coll */ - removeAll(coll: Iterable): Set; + removeAll(coll: Iterable): Set; + + /** + * Removes all of the values of a collection from this Set. + * @param {Array} coll + */ + removeAll(coll: Array): Set; /** * Removes from this Set all items that are not in the given collection. - * @param {Iterable} coll + * @param {Iterable} coll */ - retainAll(coll: Iterable): Set; + retainAll(coll: Iterable): Set; /** * Produces a JavaScript Array from the contents of this Set. */ - toArray(): any[]; + toArray(): Array; /** * Converts the Set to a List. */ - toList(): List; + toList(): List; } - class EnumValue { + class EnumValue { // undocumented //Rawr! } } //END go From c8eb58771aa63a42ff404b060ec56e911d7e637e Mon Sep 17 00:00:00 2001 From: Simon Sarris Date: Wed, 8 Jul 2015 16:37:45 -0400 Subject: [PATCH 079/144] title capitalizations --- goJS/{goJS.d.ts => gojs.d.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename goJS/{goJS.d.ts => gojs.d.ts} (100%) diff --git a/goJS/goJS.d.ts b/goJS/gojs.d.ts similarity index 100% rename from goJS/goJS.d.ts rename to goJS/gojs.d.ts From d461a36b78fa5a7abf1a000f3a269b6d32b08625 Mon Sep 17 00:00:00 2001 From: Simon Sarris Date: Wed, 8 Jul 2015 16:43:19 -0400 Subject: [PATCH 080/144] fix typescript error --- goJS/{gojs.d.ts => goJS.d.ts} | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) rename goJS/{gojs.d.ts => goJS.d.ts} (99%) diff --git a/goJS/gojs.d.ts b/goJS/goJS.d.ts similarity index 99% rename from goJS/gojs.d.ts rename to goJS/goJS.d.ts index 063a1b3a86..8a67bbf465 100644 --- a/goJS/gojs.d.ts +++ b/goJS/goJS.d.ts @@ -8761,8 +8761,8 @@ declare module go { * This is a structure used by Map to hold key-value pairs. */ interface KeyValuePair { // undocumented - key: K, - value: V + key: K; + value: V; } /** From 0d0c92b5c09468c7c7b7ef0d50dec6c001e3a0c5 Mon Sep 17 00:00:00 2001 From: Simon Sarris Date: Wed, 8 Jul 2015 16:45:23 -0400 Subject: [PATCH 081/144] it really is case sensitive --- goJS/goJS-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/goJS/goJS-tests.ts b/goJS/goJS-tests.ts index bfde3b87f8..dd6266dc7e 100644 --- a/goJS/goJS-tests.ts +++ b/goJS/goJS-tests.ts @@ -3,7 +3,7 @@ /* Copyright (C) 1998-2015 by Northwoods Software Corporation. */ -/// +/// function init() { var $ = go.GraphObject.make; // for conciseness in defining templates From 9af5c7c23eaebf3bfcefb937e34c06dd2cfde5ca Mon Sep 17 00:00:00 2001 From: Simon Sarris Date: Wed, 8 Jul 2015 16:57:04 -0400 Subject: [PATCH 082/144] semicolons in typescript --- goJS/goJS.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/goJS/goJS.d.ts b/goJS/goJS.d.ts index 8a67bbf465..e773dcc2b9 100644 --- a/goJS/goJS.d.ts +++ b/goJS/goJS.d.ts @@ -7213,7 +7213,7 @@ declare module go { * This helper structure for DraggingTool holds the original location Point. */ interface DraggingInfo { // undocumented - point: Point + point: Point; } /** @@ -8529,7 +8529,7 @@ declare module go { iterator: Iterator; /**This read-only property returns the current index to the item in the collection, assuming .next has just returned true.*/ - key; + key: any; /**This read-only property returns the current item in the collection, assuming .next has just returned true.*/ value: T; @@ -8761,8 +8761,8 @@ declare module go { * This is a structure used by Map to hold key-value pairs. */ interface KeyValuePair { // undocumented - key: K; - value: V; + key: K; + value: V; } /** From e29cf4cafbd804cae59dfc4cc8007560310f4520 Mon Sep 17 00:00:00 2001 From: Jeff Cross Date: Wed, 8 Jul 2015 09:46:50 -0700 Subject: [PATCH 083/144] update angular2 typings to 2.0.0-alpha.30 --- angular2/angular2-2.0.0-alpha.30.d.ts | 6875 +++++++++++++++++++++ angular2/angular2-tests.ts | 1 + angular2/angular2.d.ts | 8003 ++++++++++++++----------- angular2/router-2.0.0-alpha.30.d.ts | 352 ++ angular2/router.d.ts | 352 ++ 5 files changed, 11938 insertions(+), 3645 deletions(-) create mode 100644 angular2/angular2-2.0.0-alpha.30.d.ts create mode 100644 angular2/router-2.0.0-alpha.30.d.ts create mode 100644 angular2/router.d.ts diff --git a/angular2/angular2-2.0.0-alpha.30.d.ts b/angular2/angular2-2.0.0-alpha.30.d.ts new file mode 100644 index 0000000000..ecbcae245c --- /dev/null +++ b/angular2/angular2-2.0.0-alpha.30.d.ts @@ -0,0 +1,6875 @@ +// Type definitions for Angular v2.0.0-alpha.30 +// Project: http://angular.io/ +// Definitions by: angular team +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// *********************************************************** +// This file is generated by the Angular build process. +// Please do not create manual edits or send pull requests +// modifying this file. +// *********************************************************** + +// Angular depends transitively on these libraries. +// If you don't have them installed you can run +// $ tsd query es6-promise rx rx-lite --action install --save +/// +/// + +interface List extends Array {} +interface Map {} +interface StringMap extends Map {} + +declare module ng { + type SetterFn = typeof Function; + type int = number; + interface Type extends Function { + // new (...args); + } + + // See https://github.com/Microsoft/TypeScript/issues/1168 + class BaseException /* extends Error */ { + message: string; + stack: string; + toString(): string; + } +} + + + +declare module ng { + + /** + * `DependencyAnnotation` is used by the framework to extend DI. + * + * Only annotations implementing `DependencyAnnotation` are added to the list of dependency + * properties. + * + * For example: + * + * ``` + * class Parent extends DependencyAnnotation {} + * class NotDependencyProperty {} + * + * class AComponent { + * constructor(@Parent @NotDependencyProperty aService:AService) {} + * } + * ``` + * + * will create the following dependency: + * + * ``` + * new Dependency(Key.get(AService), [new Parent()]) + * ``` + * + * The framework can use `new Parent()` to handle the `aService` dependency + * in a specific way. + * + * @exportedAs angular2/di_annotations + */ + class DependencyAnnotation { + + token: void; + } + + + /** + * Lifecycle events are guaranteed to be called in the following order: + * - `onChange` (optional if any bindings have changed), + * - `onInit` (optional after the first check only), + * - `onCheck`, + * - `onAllChangesDone` + */ + class LifecycleEvent { + + name: string; + } + + + /** + * An interface that NgFormModel and NgForm implement. + * + * Only used by the forms module. + */ + interface Form { + + addControl(dir: NgControl): void; + + removeControl(dir: NgControl): void; + + getControl(dir: NgControl): Control; + + addControlGroup(dir: NgControlGroup): void; + + removeControlGroup(dir: NgControlGroup): void; + + updateModel(dir: NgControl, value: any): void; + } + + + /** + * An interface implemented by all Angular type decorators, which allows them to be used as ES7 + * decorators as well as + * Angular DSL syntax. + * + * DSL syntax: + * + * ``` + * var MyClass = ng + * .Component({...}) + * .View({...}) + * .Class({...}); + * ``` + * + * ES7 syntax: + * + * ``` + * @ng.Component({...}) + * @ng.View({...}) + * class MyClass {...} + * ``` + */ + interface TypeDecorator { + + + /** + * Invoke as ES7 decorator. + */ + (type: T): T; + + + + /** + * Storage for the accumulated annotations so far used by the DSL syntax. + * + * Used by Class to annotate the generated class. + */ + annotations: Array; + + + /** + * Generate a class from the definition and annotate it with TypeDecorator. + */ + Class(obj: ClassDefinition): Type; + } + + + /** + * Declares the interface to be used with Class. + */ + interface ClassDefinition { + + + /** + * Optional argument for specifying the superclass. + */ + extends?: Type; + + + /** + * Required constructor function for a class. + * + * The function may be optionall wrapped in an `Array`, in which case additional parameter + * annotations may be + * specified. The number of arguments and the number of paramater annotations must match. + * + * See Class for example of usage. + */ + constructor: (Function | Array); + } + + + /** + * Specifies that a QueryList should be injected. + * + * See QueryList for usage and example. + * + * @exportedAs angular2/annotations + */ + class Query extends DependencyAnnotation { + + descendants: boolean; + + selector: void; + + isVarBindingQuery: boolean; + + varBindings: List; + + toString(): string; + } + + + /** + * A directive that contains a group of [NgControl]. + * + * Only used by the forms module. + */ + class ControlContainer { + + name: string; + + formDirective: Form; + + path: List; + } + + + /** + * A marker annotation that marks a class as available to `Injector` for creation. Used by tooling + * for generating constructor stubs. + * + * ``` + * class NeedsService { + * constructor(svc:UsefulService) {} + * } + * + * @Injectable + * class UsefulService {} + * ``` + * @exportedAs angular2/di_annotations + */ + class Injectable { + + visibility: Visibility; + } + + + /** + * Specifies how injector should resolve a dependency. + * + * See Self, Parent, Ancestor, Unbounded. + * + * @exportedAs angular2/di_annotations + */ + class Visibility { + + depth: number; + + crossBoundaries: boolean; + + includeSelf: boolean; + + toString(): string; + } + + + /** + * Injectable Objects that contains a live list of child directives in the light Dom of a directive. + * The directives are kept in depth-first pre-order traversal of the DOM. + * + * In the future this class will implement an Observable interface. + * For now it uses a plain list of observable callbacks. + * + * @exportedAs angular2/view + */ + class BaseQueryList { + + reset(newList: any): void; + + add(obj: any): void; + + fireCallbacks(): void; + + onChange(callback: any): void; + + removeCallback(callback: any): void; + + length: void; + + first: void; + + last: void; + } + + class AppProtoView { + + elementBinders: List; + + protoLocals: Map; + + render: RenderProtoViewRef; + + protoChangeDetector: ProtoChangeDetector; + + variableBindings: Map; + + variableLocations: Map; + + bindElement(parent: ElementBinder, distanceToParent: int, protoElementInjector: ProtoElementInjector, componentDirective?: DirectiveBinding): ElementBinder; + + + /** + * Adds an event binding for the last created ElementBinder via bindElement. + * + * If the directive index is a positive integer, the event is evaluated in the context of + * the given directive. + * + * If the directive index is -1, the event is evaluated in the context of the enclosing view. + * + * @param {string} eventName + * @param {AST} expression + * @param {int} directiveIndex The directive index in the binder or -1 when the event is not bound + * to a directive + */ + bindEvent(eventBindings: List, boundElementIndex: number, directiveIndex?: int): void; + } + + + /** + * Cost of making objects: http://jsperf.com/instantiate-size-of-object + */ + class AppView implements ChangeDispatcher, EventDispatcher { + + render: RenderViewRef; + + rootElementInjectors: List; + + elementInjectors: List; + + changeDetector: ChangeDetector; + + componentChildViews: List; + + viewContainers: List; + + preBuiltObjects: List; + + elementRefs: List; + + ref: ViewRef; + + + /** + * The context against which data-binding expressions in this view are evaluated against. + * This is always a component instance. + */ + context: any; + + + /** + * Variables, local to this view, that can be used in binding expressions (in addition to the + * context). This is used for thing like `